diff --git a/src/OpenSHC/Map/Units/Tribe.hpp b/src/OpenSHC/Map/Units/Tribe.hpp index 6499c24a56..4f4da3fad8 100644 --- a/src/OpenSHC/Map/Units/Tribe.hpp +++ b/src/OpenSHC/Map/Units/Tribe.hpp @@ -90,7 +90,7 @@ namespace Map { short field_0x288; // 0x00000288 length: 2 short unknownBool02; // 0x0000028A length: 2 short unknownBool01; // 0x0000028C length: 2 - ushort countdown; // 0x0000028E length: 2 + short countdown; // 0x0000028E length: 2 short someUnitArrayIndex; // 0x00000290 length: 2 short someIndex; // 0x00000292 length: 2 short attackWave; // 0x00000294 length: 2 diff --git a/src/OpenSHC/Map/Units/TribesState/addUnitToTribe.cpp b/src/OpenSHC/Map/Units/TribesState/addUnitToTribe.cpp new file mode 100644 index 0000000000..b5a1a61132 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/addUnitToTribe.cpp @@ -0,0 +1,30 @@ +#include "../TribesState.func.hpp" + +#include "OpenSHC/Globals/DAT_UnitSelectionDefinedData.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + // FUNCTION: STRONGHOLDCRUSADER 0x00522590 + void TribesState::addUnitToTribe(uint unitID, int tribeID) + { + this->tribes[tribeID].size = this->tribes[tribeID].size + 1; + int const bitFlagsIndex = (int)unitID / 16; + int const bitMaskIndex = (int)unitID % 16; + this->tribes[tribeID].unitSelectionBitMasked[bitFlagsIndex] + |= DAT_UnitSelectionDefinedData::instance.BitMaskHelper[bitMaskIndex]; + if (this->tribes[tribeID].selectionTargetUnitID == 0) { + this->tribes[tribeID].selectionTargetUnitID = unitID; + } + DAT_UnitsState::instance.units[unitID].selectionTargetUnitID = this->tribes[tribeID].selectionTargetUnitID; + DAT_UnitsState::instance.units[unitID].tribeID = tribeID; + DAT_UnitsState::instance.units[unitID].tribeUID = this->tribes[tribeID].uid; + DAT_UnitsState::instance.units[unitID].idInTribe = this->tribes[tribeID].size; + MACRO_CALL_MEMBER(TribesState_Func::setWhetherTribeContainsAnyUnits, this)(tribeID); + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/applyUnitTopSpeedDelayBasedOnTribeSize.cpp b/src/OpenSHC/Map/Units/TribesState/applyUnitTopSpeedDelayBasedOnTribeSize.cpp new file mode 100644 index 0000000000..63d6a540d0 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/applyUnitTopSpeedDelayBasedOnTribeSize.cpp @@ -0,0 +1,71 @@ +#include "../TribesState.func.hpp" + +#include "OpenSHC/IO/LowLevelMemory.func.hpp" +#include "OpenSHC/Map/Units/UnitLogicState.hpp" + +#include "OpenSHC/Globals/DAT_LowLevelMemory.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + // The pair slot advances for every member while the count only grows for living ones (0x524FCA), so + // dead members leave zero holes and trailing living members are not re-indexed. The swap test is + // signed (jge at 0x525009) and skipped entirely when skipDistanceSort is set. + // FUNCTION: STRONGHOLDCRUSADER 0x00524EF0 + void TribesState::applyUnitTopSpeedDelayBasedOnTribeSize(int tribeID, BOOLEnum skipDistanceSort) + { + short* const tribeSize = &this->tribes[tribeID].size; + int i; + int j; + int swapped; + if (*tribeSize >= 40) { + for (i = 0; i < *tribeSize; ++i) { + int const unitID = MACRO_CALL_MEMBER( + OpenSHC::Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)(tribeID, i); + DAT_UnitsState::instance.units[unitID].topSpeedDelayIndex = (short)(i < 199 ? i : 199); + } + return; + } + this->someUnitIDArrayCount = 0; + MACRO_CALL_MEMBER(OpenSHC::IO::LowLevelMemory_Func::fillMemory_ByteValue, DAT_LowLevelMemory::ptr)( + sizeof(this->someUnitIDMovementDistancePair), 0, this->someUnitIDMovementDistancePair); + for (i = 0; i < *tribeSize; ++i) { + int const unitID = MACRO_CALL_MEMBER( + OpenSHC::Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)(tribeID, i); + if (DAT_UnitsState::instance.units[unitID].logicalState == ULS_NORMAL + && DAT_UnitsState::instance.units[unitID].dying == 0) { + ++this->someUnitIDArrayCount; + this->someUnitIDMovementDistancePair[i].unitID = (short)unitID; + if (skipDistanceSort == FALSE) { + this->someUnitIDMovementDistancePair[i].movementDistance + = DAT_UnitsState::instance.units[unitID].movementDistance; + } + } + } + do { + swapped = 0; + for (j = 0; j < this->someUnitIDArrayCount - 1; ++j) { + int const unitID = this->someUnitIDMovementDistancePair[j].unitID; + int const nextUnitID = this->someUnitIDMovementDistancePair[j + 1].unitID; + int const distance = this->someUnitIDMovementDistancePair[j].movementDistance; + int const nextDistance = this->someUnitIDMovementDistancePair[j + 1].movementDistance; + if (skipDistanceSort == FALSE && nextDistance < distance) { + swapped = 1; + this->someUnitIDMovementDistancePair[j].unitID = (short)nextUnitID; + this->someUnitIDMovementDistancePair[j + 1].unitID = (short)unitID; + this->someUnitIDMovementDistancePair[j].movementDistance = (short)nextDistance; + this->someUnitIDMovementDistancePair[j + 1].movementDistance = (short)distance; + } + } + } while (swapped != 0); + for (i = 0; i < this->someUnitIDArrayCount; ++i) { + DAT_UnitsState::instance.units[this->someUnitIDMovementDistancePair[i].unitID].topSpeedDelayIndex + = (short)i; + } + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/assignAttackTargetsForTribe.cpp b/src/OpenSHC/Map/Units/TribesState/assignAttackTargetsForTribe.cpp new file mode 100644 index 0000000000..2729690e1c --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/assignAttackTargetsForTribe.cpp @@ -0,0 +1,235 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/Units/TroopValueState.func.hpp" +#include "OpenSHC/Map/Units/UnitsState.func.hpp" +#include "OpenSHC/Map/Units/SomeTribeBehaviorType.hpp" +#include "OpenSHC/Map/Units/States/UnitState.hpp" +#include "OpenSHC/Map/Units/UnitInstructionType.hpp" +#include "OpenSHC/Map/Units/UnitLogicState.hpp" +#include "OpenSHC/Map/Units/UnitType.hpp" +#include "OpenSHC/WindowsHelper/Enums/BOOLEnum.hpp" + +#include "OpenSHC/Globals/DAT_GameSynchronyState.hpp" +#include "OpenSHC/Globals/DAT_PathFindingState.hpp" +#include "OpenSHC/Globals/DAT_TroopValueState.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" +#include "OpenSHC/Globals/DAT_ViewportRenderState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Map::Units::SomeTribeBehaviorType; + using Map::Units::UnitInstructionType; + using Map::Units::UnitLogicState; + using Map::Units::UnitType; + using Map::Units::States::UnitState; + using WindowsHelper::Enums::BOOLEnum; + + /* + Every target arm loads tile, y and x itself. The compiler merges the identical + arm tails into one copy, which is the shape the original shows. The repeated + loads are what give x, y and tile their registers (ebx, ebp, esi) ahead of + unitID, which the original keeps on the stack. With one shared `found` flag + and the loads written once, unitID took ebx and the function measured 44.6%. + Two differences remain. The merged copy lands after the last arm (0x3f7), + where the original keeps the one after the 0x3f2 call. x and y have + swapped registers. No declaration order of x, y and tile changes that. + Loading tile, x, y instead fixes the swap (71.3%) but costs normalized + match (66.2% -> 63.9%), so the order stays. Putting the shared code + inside the 0x3f2 arm, with the other arms jumping to it, still leaves + the last copy. + */ + // FUNCTION: STRONGHOLDCRUSADER 0x005244D0 + BOOLEnum TribesState::assignAttackTargetsForTribe(int tribeID, SomeTribeBehaviorType targetType) + { + int index = 0; + BOOLEnum const allAssassins + = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::isTribeAllAssassins, this)(tribeID); + if (DAT_GameSynchronyState::instance.currentPlayerFullIDArray[this->tribes[tribeID].owner] != -1) { + return FALSE; + } + if (this->tribes[tribeID].size <= 0) { + return TRUE; + } + do { + uint x; + uint y; + uint tile; + int const unitID + = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)(tribeID, index); + index = index + 1; + if (DAT_UnitsState::instance.units[unitID].logicalState != Map::Units::ULS_NORMAL + || DAT_UnitsState::instance.units[unitID].dying != 0 + || DAT_UnitsState::instance.units[unitID].usingTeleport != 0 + || DAT_UnitsState::instance.units[unitID].field_0x413 != 0 + || DAT_UnitsState::instance.units[unitID].moveableUnk == 0) { + continue; + } + if (targetType != Map::Units::STBT_0x3fd) { + UnitStateShort const state = DAT_UnitsState::instance.units[unitID].state.generic; + if (state == Map::Units::States::US_MELEE_ATTACK_WALL + || state == Map::Units::States::US_MOVE_TO_DESTINATION || state == (UnitState)0x67) { + continue; + } + UnitTypeShort const unitType = DAT_UnitsState::instance.units[unitID].unitType; + if (unitType == Map::Units::UT_E_SPEAR) { + if (state == Map::Units::States::US_AIM_WEAPONUnk) { + continue; + } + } else if (unitType == Map::Units::UT_E_ENGINEER) { + if (state == Map::Units::States::US_RELOAD_WEAPONUnk) { + continue; + } + } else if (unitType == Map::Units::UT_E_LADDER) { + if (state == (UnitState)3) { + continue; + } + } else if (unitType == Map::Units::UT_TUNNELER) { + if (state == (UnitState)2 || state == (UnitState)3 + || state == Map::Units::States::US_RELOAD_WEAPONUnk + || state == Map::Units::States::US_STAND_UPUnk + || state == (Map::Units::States::US_STAND_UPUnk | Map::Units::States::US_IDLEUnk)) { + continue; + } + } + } + if (targetType == Map::Units::STBT_0x3f2) { + if (!MACRO_CALL_MEMBER(Map::Units::TroopValueState_Func::findEnemyWalls, DAT_TroopValueState::ptr)( + unitID)) { + continue; + } + tile = DAT_TroopValueState::instance.tile; + y = DAT_TroopValueState::instance.y; + x = DAT_TroopValueState::instance.x; + } else if (targetType == Map::Units::STBT_0x3f4) { + if (!MACRO_CALL_MEMBER(Map::Units::TroopValueState_Func::findNearestAvailableScalePoint, + DAT_TroopValueState::ptr)(unitID)) { + continue; + } + x = DAT_TroopValueState::instance.x; + y = DAT_TroopValueState::instance.y; + tile = DAT_TroopValueState::instance.tile; + DAT_UnitsState::instance.units[unitID].state.generic = (UnitState)0x67; + } else if (targetType == Map::Units::STBT_0x3f3) { + if (!MACRO_CALL_MEMBER(Map::Units::TroopValueState_Func::findNearestAvailableScalePoint, + DAT_TroopValueState::ptr)(unitID)) { + continue; + } + tile = DAT_TroopValueState::instance.tile; + y = DAT_TroopValueState::instance.y; + x = DAT_TroopValueState::instance.x; + } else if (targetType == Map::Units::STBT_0x3f5) { + if (!MACRO_CALL_MEMBER(Map::Units::TroopValueState_Func::findEnemyBuildingsClosestToUnit, + DAT_TroopValueState::ptr)(unitID)) { + continue; + } + tile = DAT_TroopValueState::instance.tile; + y = DAT_TroopValueState::instance.y; + x = DAT_TroopValueState::instance.x; + } else if (targetType == Map::Units::STBT_0x3fb) { + if (!MACRO_CALL_MEMBER(Map::Units::TroopValueState_Func::calculateTile2PeoplValueClosestToUnit, + DAT_TroopValueState::ptr)(unitID)) { + continue; + } + tile = DAT_TroopValueState::instance.tile; + y = DAT_TroopValueState::instance.y; + x = DAT_TroopValueState::instance.x; + } else if (targetType == Map::Units::STBT_0x3fd) { + if (!MACRO_CALL_MEMBER(Map::Units::TroopValueState_Func::findEnemyLord, DAT_TroopValueState::ptr)( + unitID)) { + continue; + } + tile = DAT_TroopValueState::instance.tile; + y = DAT_TroopValueState::instance.y; + x = DAT_TroopValueState::instance.x; + } else if (targetType == Map::Units::STBT_0x3f6) { + if (!MACRO_CALL_MEMBER(Map::Units::TroopValueState_Func::findEnemyTowersOrGates, + DAT_TroopValueState::ptr)(unitID)) { + continue; + } + tile = DAT_TroopValueState::instance.tile; + y = DAT_TroopValueState::instance.y; + x = DAT_TroopValueState::instance.x; + } else if (targetType == Map::Units::STBT_0x413) { + if (!MACRO_CALL_MEMBER(Map::Units::TroopValueState_Func::getClosestWideValueBasedOnPlayer, + DAT_TroopValueState::ptr)(unitID)) { + continue; + } + tile = DAT_TroopValueState::instance.tile; + y = DAT_TroopValueState::instance.y; + x = DAT_TroopValueState::instance.x; + } else if (targetType == Map::Units::STBT_0x414) { + if (!MACRO_CALL_MEMBER(Map::Units::TroopValueState_Func::getClosestWideValueBasedOnPlayer, + DAT_TroopValueState::ptr)(unitID)) { + continue; + } + tile = DAT_TroopValueState::instance.tile; + y = DAT_TroopValueState::instance.y; + x = DAT_TroopValueState::instance.x; + } else if (targetType == Map::Units::STBT_0x3f7) { + if (!MACRO_CALL_MEMBER(Map::Units::TroopValueState_Func::calculateTile2MoatValueClosestToUnit, + DAT_TroopValueState::ptr)(unitID)) { + continue; + } + tile = DAT_TroopValueState::instance.tile; + y = DAT_TroopValueState::instance.y; + x = DAT_TroopValueState::instance.x; + } else { + continue; + } + if (targetType != Map::Units::STBT_0x3f4) { + DAT_UnitsState::instance.units[unitID].state.generic = Map::Units::States::US_MOVE_TO_DESTINATION; + if (targetType == Map::Units::STBT_0x414) { + uint const freeTile = MACRO_CALL_MEMBER( + Map::Units::UnitsState_Func::findFreeTileNearby, DAT_UnitsState::ptr)(unitID, tile); + if (freeTile == 0) { + continue; + } + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::setDestinationForUnit, DAT_UnitsState::ptr)( + unitID, + freeTile + - DAT_ViewportRenderState::instance + .translationMatrix[DAT_ViewportRenderState::instance + .tileTranslationMatrix_YComponent[freeTile]] + .addXgetTile, + DAT_ViewportRenderState::instance.tileTranslationMatrix_YComponent[freeTile], 0); + short const tileY = DAT_ViewportRenderState::instance.tileTranslationMatrix_YComponent[tile]; + DAT_UnitsState::instance.units[unitID].attackAtTileY = tileY; + DAT_UnitsState::instance.units[unitID].targetID_OR_targetBuildingID = (short)tile; + DAT_UnitsState::instance.units[unitID].targetingType = Map::Units::UIT_ATTACK_WALL; + DAT_UnitsState::instance.units[unitID].state.generic + = Map::Units::States::US_MOVE_TO_DESTINATION; + DAT_UnitsState::instance.units[unitID].attackAtTileX = (short)tile + - (short)DAT_ViewportRenderState::instance.translationMatrix[tileY].addXgetTile; + continue; + } + } + short const tileY = DAT_ViewportRenderState::instance.tileTranslationMatrix_YComponent[tile]; + DAT_UnitsState::instance.units[unitID].attackAtTileY = tileY; + DAT_UnitsState::instance.units[unitID].targetedBuildingTile = tile; + DAT_UnitsState::instance.units[unitID].attackAtTileX + = (short)tile - (short)DAT_ViewportRenderState::instance.translationMatrix[tileY].addXgetTile; + DAT_UnitsState::instance.units[unitID].unknownDigMoatOrWallAttackFlag1015 = (undefined2)targetType; + if (!MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::stopUnitIfNextToTarget, DAT_UnitsState::ptr)( + unitID)) { + if (allAssassins != FALSE) { + DAT_PathFindingState::instance.allAssassinsUnk = 1; + } + if (!MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::setDestinationForUnit, DAT_UnitsState::ptr)( + unitID, x, y, 0)) { + DAT_UnitsState::instance.units[unitID].logicalState = Map::Units::ULS_REMOVE; + } + } + if (DAT_UnitsState::instance.units[unitID].selectionTargetUnitID == unitID) { + this->tribes[tribeID].targetX = (short)x; + this->tribes[tribeID].targetY = (short)y; + } + } while (index < this->tribes[tribeID].size); + return TRUE; + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/commandUnitsToLocation.cpp b/src/OpenSHC/Map/Units/TribesState/commandUnitsToLocation.cpp new file mode 100644 index 0000000000..eaf7758fbe --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/commandUnitsToLocation.cpp @@ -0,0 +1,119 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Map/Navigation/DirectionAlgorithmState.func.hpp" +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/Units/Instructions/UnitMatchSpeedEnum.hpp" +#include "OpenSHC/Map/Units/States/UnitState.hpp" +#include "OpenSHC/Map/Units/UnitLogicState.hpp" +#include "OpenSHC/Map/Units/UnitType.hpp" +#include "OpenSHC/WindowsHelper/Enums/BOOLEnum.hpp" + +#include "OpenSHC/Globals/DAT_CurrentTribeID.hpp" +#include "OpenSHC/Globals/DAT_DirectionAlgorithmState.hpp" +#include "OpenSHC/Globals/DAT_TribesState.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Map::Units::UnitLogicState; + using Map::Units::UnitType; + using Map::Units::Instructions::UnitMatchSpeedEnum; + using Map::Units::States::UnitState; + using WindowsHelper::Enums::BOOLEnum; + + // FUNCTION: STRONGHOLDCRUSADER 0x00526F00 + BOOLEnum TribesState::commandUnitsToLocation( + int tribeID, uint destinationX, uint destinationY, undefined4 matchUnitSpeeds) + { + int index = 0; + /* + noneCommanded is set after the size test, and the empty tribe jumps to the + shared `return FALSE`. The original keeps 1 in ebx (the flag, the index + step, the rally flag and the return value all use it) and spills the tribe + offset. With the flag set to TRUE in its declaration, the offset took ebx + and every 1 was an immediate (80.2% in quick_diff, 90.2% now). One + difference is left: `this` and index swap edi and ebp. reg_scores gives + both the same score (-61), so the symbol-id tiebreak decides. + */ + BOOLEnum noneCommanded; + if (this->tribes[tribeID].size <= 0) { + goto noneCommandedExit; + } + noneCommanded = TRUE; + do { + int const unitID + = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)(tribeID, index); + index = index + 1; + if (DAT_UnitsState::instance.units[unitID].logicalState != Map::Units::ULS_NORMAL + || DAT_UnitsState::instance.units[unitID].dying != 0) { + continue; + } + short const goToRallyPoint = DAT_UnitsState::instance.units[unitID].goToRallyPoint; + DAT_UnitsState::instance.units[unitID].rallyRelatedFlag = 0; + if (goToRallyPoint != 0 || DAT_UnitsState::instance.units[unitID].isSelectable_OR_matchTime == 0) { + DAT_UnitsState::instance.units[unitID].rallyRelatedFlag = 1; + continue; + } + MACRO_CALL_MEMBER(Map::Navigation::DirectionAlgorithmState_Func::setAxisBasedDistanceResult, + DAT_DirectionAlgorithmState::ptr)(destinationX, destinationY, + DAT_UnitsState::instance.units[unitID].x, DAT_UnitsState::instance.units[unitID].y); + if (DAT_DirectionAlgorithmState::instance.distanceHigh <= 4) { + DAT_UnitsState::instance.units[unitID].rallyRelatedFlag = 1; + continue; + } + if (DAT_UnitsState::instance.units[unitID].movementType_OR_targetUnitID != 0 + && DAT_UnitsState::instance + .units[DAT_UnitsState::instance.units[unitID] + .targetedUnitID__OR__engineerMannedSiegeEngineRef] + .logicalState + == Map::Units::ULS_NORMAL) { + DAT_UnitsState::instance.units[unitID].rallyRelatedFlag = 1; + continue; + } + short const shootTarget = DAT_UnitsState::instance.units[unitID].shootTargetedUnit; + if (shootTarget != 0 && this->tribes[DAT_CurrentTribeID::instance].countdown2 > 0 + && DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_A_HARCHER + && DAT_UnitsState::instance.units[unitID].targetUID + == DAT_UnitsState::instance.units[shootTarget].uid) { + DAT_UnitsState::instance.units[unitID].rallyRelatedFlag = 1; + continue; + } + if (DAT_UnitsState::instance.units[unitID].state.generic == Map::Units::States::US_MELEE_ATTACK) { + DAT_UnitsState::instance.units[unitID].rallyRelatedFlag = 1; + continue; + } + if ((char)matchUnitSpeeds == '\0') { + UnitTypeShort const unitType = DAT_UnitsState::instance.units[unitID].unitType; + if (unitType == Map::Units::UT_S_FBALLISTA || unitType == Map::Units::UT_S_CATAPULT + || unitType == Map::Units::UT_S_SHIELD || unitType == Map::Units::UT_S_TOWER + || unitType == Map::Units::UT_S_BATTERINGRAM) { + DAT_UnitsState::instance.units[unitID].rallyRelatedFlag = 1; + continue; + } + } + if (DAT_UnitsState::instance.units[unitID].engineerRelatedUnk != 0 + && (DAT_UnitsState::instance.units[unitID].resourceToDeposit == 0 + || DAT_UnitsState::instance.units[unitID].field_0x3c4 != 0)) { + DAT_UnitsState::instance.units[unitID].rallyRelatedFlag = 1; + continue; + } + DAT_UnitsState::instance.units[unitID].rallyRelatedFlag = 0; + noneCommanded = FALSE; + } while (index < this->tribes[tribeID].size); + if (noneCommanded != FALSE) { + noneCommandedExit: + return FALSE; + } + if ((char)matchUnitSpeeds != '\0') { + DAT_TribesState::instance.tribes[tribeID].freeUnitSpeeds = 0; + } + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::giveTribeMoveInstruction, this)( + tribeID, destinationX, destinationY, 0, 0, Map::Units::Instructions::UMSE_0); + return TRUE; + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/computeTribePercentages.cpp b/src/OpenSHC/Map/Units/TribesState/computeTribePercentages.cpp new file mode 100644 index 0000000000..167a124c3b --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/computeTribePercentages.cpp @@ -0,0 +1,100 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/Units/UnitsState.func.hpp" +#include "OpenSHC/Map/Units/States/UnitState.hpp" +#include "OpenSHC/Map/Units/UnitLogicState.hpp" +#include "OpenSHC/Map/Units/UnitType.hpp" +#include "OpenSHC/WindowsHelper/Enums/BOOLEnum.hpp" + +#include "OpenSHC/Globals/DAT_UnitsState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Map::Units::UnitLogicState; + using Map::Units::UnitType; + using Map::Units::States::UnitState; + using WindowsHelper::Enums::BOOLEnum; + + /* + What is left is register allocation: the original keeps the loop index in ebp + and spills `this`, where ours keeps `this` in ebp and spills the index. + */ + // FUNCTION: STRONGHOLDCRUSADER 0x005270F0 + void TribesState::computeTribePercentages(int tribeID) + { + int const targetUnitID = this->tribes[tribeID].selectionTargetUnitID; + this->tribes[tribeID].percentageDyingUnk = 0; + this->tribes[tribeID].percentageMovingUnk = 0; + this->tribes[tribeID].percentageAttackingUnk = 0; + this->tribes[tribeID].field_0x29c = 0; + this->tribes[tribeID].percentageShootingUnk = 0; + this->tribes[tribeID].field_0x2a0 = 0; + this->tribes[tribeID].percentageSomething = 0; + this->tribes[tribeID].movementSpeed = DAT_UnitsState::instance.units[targetUnitID].movementSpeed; + int countState7c = 0; + int countShooting = 0; + int countAttacking = 0; + int countMoving = 0; + int countDying = 0; + this->tribes[tribeID].unitType = DAT_UnitsState::instance.units[targetUnitID].unitType; + for (int i = 0; i < this->tribes[tribeID].size;) { + int const unitID + = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getSpecificUnitFromTribe, this)(tribeID, i); + ++i; + if (DAT_UnitsState::instance.units[unitID].logicalState != Map::Units::ULS_NORMAL) { + continue; + } + if (MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::isComputerManagedNonPeasant, DAT_UnitsState::ptr)( + unitID) + != FALSE) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::removeUnitFromTribe, this)(unitID, tribeID); + continue; + } + if (DAT_UnitsState::instance.units[unitID].dying != 0) { + countDying = countDying + 1; + continue; + } + if (DAT_UnitsState::instance.units[unitID].movementRelated != 8) { + countMoving = countMoving + 1; + } + if (DAT_UnitsState::instance.units[unitID].state.generic == Map::Units::States::US_MELEE_ATTACK) { + countAttacking = countAttacking + 1; + } + if (DAT_UnitsState::instance.units[unitID].state.generic == Map::Units::States::US_MELEE_ATTACK_WALL) { + countAttacking = countAttacking + 1; + } + if (DAT_UnitsState::instance.units[unitID].state.generic + == (Map::Units::States::US_DEATH_02 | Map::Units::States::US_STAND_UPUnk + | Map::Units::States::US_RELOAD_WEAPONUnk)) { + countState7c = countState7c + 1; + } + if (DAT_UnitsState::instance.units[unitID].field_0x430 != 0 + && (DAT_UnitsState::instance.units[unitID].state.generic == Map::Units::States::US_RELOAD_WEAPONUnk + || DAT_UnitsState::instance.units[unitID].state.generic == Map::Units::States::US_AIM_WEAPONUnk + || DAT_UnitsState::instance.units[unitID].state.generic + == Map::Units::States::US_FIRE_WEAPONUnk)) { + countShooting = countShooting + 1; + } + UnitTypeShort const unitType = this->tribes[tribeID].unitType; + if (unitType != (UnitType)0 && DAT_UnitsState::instance.units[unitID].unitType != unitType) { + this->tribes[tribeID].unitType = (UnitType)0; + } + short const movementSpeed = DAT_UnitsState::instance.units[unitID].movementSpeed; + if (movementSpeed > this->tribes[tribeID].movementSpeed) { + this->tribes[tribeID].movementSpeed = movementSpeed; + } + } + int const size = this->tribes[tribeID].size; + this->tribes[tribeID].percentageDyingUnk = (short)(size == 0 ? 100 : countDying * 100 / size); + this->tribes[tribeID].percentageMovingUnk = (short)(size == 0 ? 100 : countMoving * 100 / size); + this->tribes[tribeID].percentageAttackingUnk = (short)(size == 0 ? 100 : countAttacking * 100 / size); + this->tribes[tribeID].percentageShootingUnk = (short)(size == 0 ? 100 : countShooting * 100 / size); + this->tribes[tribeID].percentageSomething = (short)(size == 0 ? 100 : countState7c * 100 / size); + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/createAnimal.cpp b/src/OpenSHC/Map/Units/TribesState/createAnimal.cpp new file mode 100644 index 0000000000..563e14deff --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/createAnimal.cpp @@ -0,0 +1,152 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Map/Entities/EntityState.func.hpp" +#include "OpenSHC/Map/LandscapeState.func.hpp" +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/Units/UnitsState.func.hpp" +#include "OpenSHC/AI/Tribes/AITribeType.hpp" +#include "OpenSHC/Commands/MappersEnum.hpp" +#include "OpenSHC/Map/Units/UnitType.hpp" + +#include "OpenSHC/Globals/DAT_EntityState.hpp" +#include "OpenSHC/Globals/DAT_LandscapeState.hpp" +#include "OpenSHC/Globals/DAT_TileMapState.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" +#include "OpenSHC/Globals/DAT_ViewportRenderState.hpp" +#include "OpenSHC/Globals/SEC_RNG.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using AI::Tribes::AITribeType; + using Commands::MappersEnum; + using Map::Units::UnitType; + + /* + The `short` tribe-size local stays narrow: widening it costs 0.4 points. + + The herd tail returns tribeID once, at the end. With a `return tribeID` in + each arm, tribeID took ebx and the spawn counter was kept on the stack + (quick_diff 0.57). The original keeps the counter in ebx and reloads + tribeID from its slot for each return (quick_diff 0.93). + */ + // FUNCTION: STRONGHOLDCRUSADER 0x00525BA0 + dword TribesState::createAnimal(MappersEnum animalType, uint x, uint y, int tile) + { + uint unitID; + UnitType unitType = ((UnitType)0); + int _rng2 = 0; + dword tribeID = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::createTribe, this)(0, 0); + if ((int)tribeID <= 0) { + return (dword)(0); + } + /* + Three separate guards: the original gives each of them its own forward jump + rather than folding them into one chain. + */ + if (399 < x) { + return (dword)(0); + } + if (399 < y) { + return (dword)(0); + } + if (DAT_ViewportRenderState::instance.DAT_BinaryTileMap400x400[y * 400 + x] == 0) { + return (dword)(0); + } + int _tile = DAT_ViewportRenderState::instance.translationMatrix[y].addXgetTile + x; + if (animalType == Commands::M_MAPPER_DEER) { + if ((DAT_TileMapState::instance.LogicLayer[_tile] & 0x4a5014b1U)) { + return (dword)(0); + } + this->tribes[tribeID].tribeType = AI::Tribes::AITT_SWORDSMEN | AI::Tribes::AITT_SPEARMEN; + unitType = Map::Units::UT_ANTELOPESHDEER; + _rng2 = ((byte)SEC_RNG::instance.currentNumber2 & 3) + 9; + } else if (animalType == Commands::M_MAPPER_LION) { + if ((DAT_TileMapState::instance.LogicLayer[_tile] & 0x4a5014b1U)) { + return (dword)(0); + } + this->tribes[tribeID].tribeType = AI::Tribes::AITT_SWORDSMEN | AI::Tribes::AITT_PIKEMEN; + unitType = Map::Units::UT_LIONSHWOLF; + _rng2 = ((byte)SEC_RNG::instance.currentNumber2 & 1) + 3; + } else if (animalType == Commands::M_MAPPER_RABBIT) { + if ((DAT_TileMapState::instance.LogicLayer[_tile] & 0x4a5014b1U)) { + return (dword)(0); + } + this->tribes[tribeID].tribeType = AI::Tribes::AITT_SWORDSMEN | AI::Tribes::AITT_CROSSBOWMEN; + unitType = Map::Units::UT_RABBIT; + _rng2 = ((byte)SEC_RNG::instance.currentNumber2 & 7) + 0xe; + } else if (animalType == Commands::M_MAPPER_CAMEL) { + if ((DAT_TileMapState::instance.LogicLayer[_tile] & 0x4a5014b1U)) { + return (dword)(0); + } + this->tribes[tribeID].tribeType = ((AITribeType)0x10); + unitType = Map::Units::UT_CAMELSHBEAR; + _rng2 = ((byte)SEC_RNG::instance.currentNumber2 & 3) + 2; + } else { + if (animalType == Commands::M_MAPPER_CROW_SEAGULL) { + MACRO_CALL_MEMBER(Map::LandscapeState_Func::markNearbyTreesAsCrowTargets, DAT_LandscapeState::ptr)( + x, (int)(y)); + return (dword)(0); + } + if (animalType == Commands::M_MAPPER_SEAGULL) { + if (!(DAT_TileMapState::instance.LogicLayer[_tile] & 1)) { + return (dword)(0); + } + MACRO_CALL_MEMBER(Map::Entities::EntityState_Func::createSeagull, DAT_EntityState::ptr)( + x * 8, (int)(y * 8)); + return (dword)(0); + } + } + int iVar3 = 0; + if (0 < _rng2) { + do { + unitID = MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::spawnUnit, DAT_UnitsState::ptr)( + 0, 0, (int)(x * 8), (int)(y * 8), tile, unitType); + if (unitID) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::addUnitToTribe, this)(unitID, (int)(tribeID)); + DAT_UnitsState::instance.units[unitID].substate + = (short)(DAT_UnitsState::instance.units[unitID].fixedRng & 3); + if (unitType == Map::Units::UT_ANTELOPESHDEER) { + byte bVar2 = (byte)DAT_UnitsState::instance.units[unitID].fixedRng & 7; + DAT_UnitsState::instance.units[unitID].antelopeBasedRngValue = bVar2; + if (bVar2 == 3) { + DAT_UnitsState::instance.units[unitID].antelopeBasedRngValue = 1; + } else if (bVar2 == 4) { + DAT_UnitsState::instance.units[unitID].antelopeBasedRngValue = 1; + } else if (bVar2 == 5) { + DAT_UnitsState::instance.units[unitID].antelopeBasedRngValue = 1; + } else if ((bVar2 == 6) || (bVar2 == 7)) { + DAT_UnitsState::instance.units[unitID].antelopeBasedRngValue = 2; + } + if (!iVar3) { + DAT_UnitsState::instance.units[unitID].antelopeBasedRngValue = 0; + } else if ((iVar3 == 1) || (iVar3 == 2)) { + DAT_UnitsState::instance.units[unitID].antelopeBasedRngValue = 1; + } + } + DAT_UnitsState::instance.units[unitID].disappearFadeAlphaCountdown = 0x20; + } + iVar3 = iVar3 + 1; + } while (iVar3 < _rng2); + } + short sVar1 = this->tribes[tribeID].size; + this->tribes[tribeID].herdMinSize = sVar1 / 2; + if (animalType == Commands::M_MAPPER_LION) { + this->tribes[tribeID].herdMaxSize = sVar1; + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::storeLionXAndYInMapInfo, this)(x, y); + } else { + this->tribes[tribeID].herdMaxSize = sVar1 * 2; + if (animalType == Commands::M_MAPPER_DEER) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::storeDeerXAndYinMapInfo, this)(x, y); + } else if (animalType == Commands::M_MAPPER_RABBIT) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::setRabbitSpawnXY, this)(x, y); + } else if (animalType == Commands::M_MAPPER_CAMEL) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::setCamelSpawnXY, this)(x, y); + } + } + return (dword)(tribeID); + } + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/createTribe.cpp b/src/OpenSHC/Map/Units/TribesState/createTribe.cpp new file mode 100644 index 0000000000..e944d4bec4 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/createTribe.cpp @@ -0,0 +1,60 @@ +#include "../../../Map.func.hpp" +#include "../TribesState.func.hpp" + +#include "OpenSHC/IO/LowLevelMemory.func.hpp" +#include "OpenSHC/AI/Tribes/AITribeType.hpp" +#include "OpenSHC/Map/Units/SomeTribeBehaviorType.hpp" + +#include "OpenSHC/Globals/DAT_CurrentTribeID.hpp" +#include "OpenSHC/Globals/DAT_GameCore.hpp" +#include "OpenSHC/Globals/DAT_GameSynchronyState.hpp" +#include "OpenSHC/Globals/DAT_LowLevelMemory.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using AI::Tribes::AITribeType; + using Map::Units::SomeTribeBehaviorType; + + /* + The same shape as createTribeForPlayer: the search loop (over the global + DAT_CurrentTribeID) clears the free slot itself and breaks out, and the claim is + guarded by a second `tribeID <= 0` test that the original keeps after the clear. + */ + // FUNCTION: STRONGHOLDCRUSADER 0x00522890 + int TribesState::createTribe(int playerID, int setAsCurrentTribeID) + { + int tribeID = 0; + for (DAT_CurrentTribeID::instance = 1; (int)DAT_CurrentTribeID::instance < 1250; + DAT_CurrentTribeID::instance = DAT_CurrentTribeID::instance + 1) { + if (this->tribes[DAT_CurrentTribeID::instance].tribeState == 0) { + tribeID = DAT_CurrentTribeID::instance; + MACRO_CALL_MEMBER(IO::LowLevelMemory_Func::fillMemory_ByteValue, DAT_LowLevelMemory::ptr)( + sizeof(Tribe), '\0', &this->tribes[tribeID]); + break; + } + } + if (tribeID <= 0) { + return 0; + } + if (playerID == DAT_GameSynchronyState::instance.currentPlayerSlotID && setAsCurrentTribeID) { + this->DAT_CurrentTribeID = tribeID; + } + this->tribes[tribeID].owner = playerID; + this->tribes[tribeID].tribeState = 2; + this->tribes[tribeID].uid = DAT_GameCore::instance.uniqueGameObjectTracker; + DAT_GameCore::instance.uniqueGameObjectTracker = DAT_GameCore::instance.uniqueGameObjectTracker + 1; + this->tribes[tribeID].tribeType = ((AITribeType)0); + this->tribes[tribeID].field_0x1c = 0; + this->tribes[tribeID].field_0x1e = 0; + this->tribes[tribeID].tribeBehaviorType = ((SomeTribeBehaviorType)0); + this->tribes[tribeID].field_0x30 = 0; + this->tribes[tribeID].selectionTargetUnitID = 0; + this->tribes[tribeID].size = 0; + return tribeID; + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/createTribeForPlayer.cpp b/src/OpenSHC/Map/Units/TribesState/createTribeForPlayer.cpp new file mode 100644 index 0000000000..70fa26d4ed --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/createTribeForPlayer.cpp @@ -0,0 +1,54 @@ +#include "../../../Map.func.hpp" +#include "../TribesState.func.hpp" + +#include "OpenSHC/IO/LowLevelMemory.func.hpp" +#include "OpenSHC/AI/Tribes/AITribeType.hpp" +#include "OpenSHC/Map/Units/SomeTribeBehaviorType.hpp" + +#include "OpenSHC/Globals/DAT_GameCore.hpp" +#include "OpenSHC/Globals/DAT_LowLevelMemory.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using AI::Tribes::AITribeType; + using Map::Units::SomeTribeBehaviorType; + + /* + The search loop does the clear itself and breaks out, and the claim is guarded by + a second `tribeID <= 0` test after it: the original jump-threads that test into + the loop's exhausted exit (its own `return 0`) and into the entry test, but keeps + it after the clear, where the loop variable has gone through the call. + */ + // FUNCTION: STRONGHOLDCRUSADER 0x005227E0 + int TribesState::createTribeForPlayer(int playerID) + { + int tribeID; + for (tribeID = 1250 - playerID; tribeID > 0; tribeID = tribeID - 8) { + if (this->tribes[tribeID].tribeState == 0) { + MACRO_CALL_MEMBER(IO::LowLevelMemory_Func::fillMemory_ByteValue, DAT_LowLevelMemory::ptr)( + sizeof(Tribe), '\0', &this->tribes[tribeID]); + break; + } + } + if (tribeID <= 0) { + return 0; + } + this->tribes[tribeID].owner = playerID; + this->tribes[tribeID].tribeState = 2; + this->tribes[tribeID].uid = DAT_GameCore::instance.uniqueGameObjectTracker; + DAT_GameCore::instance.uniqueGameObjectTracker = DAT_GameCore::instance.uniqueGameObjectTracker + 1; + this->tribes[tribeID].tribeType = ((AITribeType)0); + this->tribes[tribeID].field_0x1c = 0; + this->tribes[tribeID].field_0x1e = 0; + this->tribes[tribeID].tribeBehaviorType = ((SomeTribeBehaviorType)0); + this->tribes[tribeID].field_0x30 = 0; + this->tribes[tribeID].selectionTargetUnitID = 0; + this->tribes[tribeID].size = 0; + return tribeID; + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/drawFlagsAndUnitDestinations.cpp b/src/OpenSHC/Map/Units/TribesState/drawFlagsAndUnitDestinations.cpp new file mode 100644 index 0000000000..a83cb6a891 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/drawFlagsAndUnitDestinations.cpp @@ -0,0 +1,211 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Map/TileMapState.func.hpp" +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Rendering/ViewportRenderState.func.hpp" +#include "OpenSHC/IO/Graphics/GmID.hpp" +#include "OpenSHC/Map/Units/UnitInstructionType.hpp" +#include "OpenSHC/Map/Units/UnitLogicState.hpp" + +#include "OpenSHC/Globals/DAT_BuildingsState.hpp" +#include "OpenSHC/Globals/DAT_GameSynchronyState.hpp" +#include "OpenSHC/Globals/DAT_TileMapState.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" +#include "OpenSHC/Globals/DAT_ViewportRenderState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using IO::Graphics::GmID; + using Map::Units::UnitInstructionType; + using Map::Units::UnitLogicState; + + /* + The `short` local stays narrow: widening it costs 3.9 points + (41.8% -> 37.9%). Splitting it so that only the three target-ID uses get an `int` + - which is where our `movzx` plus `movsx` pairs are against the original's single + `movsx` - costs 1.3 points too (47.0% -> 45.7%). + */ + // FUNCTION: STRONGHOLDCRUSADER 0x00523A30 + void TribesState::drawFlagsAndUnitDestinations(int tribeID) + { + UnitInstructionTypeShort targetingType; + int unitID; + int cursorValue; + short (*rallyPoint)[2]; + int tile; + short isRallying; + isRallying = this->tribes[tribeID].isRallyingUnk; + /* + Three nested tests, not one chain: the original has three separate forward + jumps (0x523a53, 0x523a62, 0x523a7d). The player ID is loaded first and the + tribe's owner compared to it (`mov esi, [..]`, `cmp [ebp + 0x2c], esi`), and + the starting index is a branch rather than a `setl` + (`test ax, ax`, `jge`, `mov esi, 1`). + */ + if (isRallying && DAT_GameSynchronyState::instance.currentPlayerSlotID == this->tribes[tribeID].owner) { + int rallyIndex = 0; + if (isRallying < 0) { + rallyIndex = 1; + } + if (rallyIndex < this->tribes[tribeID].rallyPointCount) { + rallyPoint = this->tribes[tribeID].rallyPointArray + rallyIndex; + do { + int const y = (*rallyPoint)[1]; + int const x = (*rallyPoint)[0]; + // spawn the rally point flag + MACRO_CALL_MEMBER(Rendering::ViewportRenderState_Func::createFloatingLayerElement, + DAT_ViewportRenderState::ptr)(IO::Graphics::GID_FLOATS_NEW, + (x + (int)DAT_TileMapState::instance.flagAnimationFrame + rallyIndex + y) % 10 + 0x61, 0x12, + -1, DAT_ViewportRenderState::instance.translationMatrix[y].addXgetTile + x, 0xa0022); + rallyIndex++; + rallyPoint++; + } while (rallyIndex < this->tribes[tribeID].rallyPointCount); + } + } + int index = 0; + if (0 < this->tribes[tribeID].size) { + do { + unitID = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getSpecificUnitFromTribe, this)( + tribeID, index); + index++; + if (DAT_UnitsState::instance.units[unitID].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[unitID].dying == 0 + && DAT_UnitsState::instance.units[unitID].unknownTestAgainst0_2 == 0 + && DAT_UnitsState::instance.units[unitID].owner + == DAT_GameSynchronyState::instance.currentPlayerSlotID) { + short speedMatching = DAT_UnitsState::instance.units[unitID].unitSpeedMatchingRelatedUnk; + /* + The speed-matching arm is the fall-through. The original reads + the field and tests it sixteen bits wide, then jumps 0x91 forward + when it is zero (`test dx, dx; je 0x91`), so the arm that draws + the speed cursor follows the test and the planned-destination arm + goes in the far block. + */ + if (speedMatching) { + /* + The zero is the fall-through. The original has + `cmp dx, 8; jl 0x4` - jumping over `xor eax, eax` into the + scaling - so `cursorValue = 0` sits under the test and the + `(8 - speed) * 4` arm comes after it. Written `speedMatching < 8` + first they swap and the test inverts to `jge`. + */ + if (speedMatching >= 8) { + cursorValue = 0; + } else { + cursorValue = (8 - speedMatching) * 4; + } + tile = DAT_UnitsState::instance.units[unitID].plannedDestinationX + + DAT_ViewportRenderState::instance + .translationMatrix[DAT_UnitsState::instance.units[unitID].plannedDestinationY] + .addXgetTile; + MACRO_CALL_MEMBER(Rendering::ViewportRenderState_Func::createFloatingLayerElement, + DAT_ViewportRenderState::ptr)( + IO::Graphics::GID_CURSORS, 0x6a - speedMatching, 10, 6, tile, cursorValue << 0x10 | 2); + cursorValue = DAT_TileMapState::instance.cursorOverlayAnimationFrame + -1; + /* + Negated rather than written `7 < cursorValue`: the original has + `cmp eax, 8` with a `jl` jumping over the subtraction, and + MSVC emits the constant it is handed, so the greater-than + spelling gives `cmp eax, 7; jle` instead. Same test, and + writing it this way is worth 1.7% here (55.9 -> 57.6). + */ + if (!(cursorValue < 8)) { + cursorValue = 0xf - cursorValue; + } + MACRO_CALL_MEMBER(Rendering::ViewportRenderState_Func::createFloatingLayerElement, + DAT_ViewportRenderState::ptr)(IO::Graphics::GID_CURSORS, cursorValue + 0x52, 0xc, 6, + tile, DAT_UnitsState::instance.units[unitID].unitSpeedMatchingRelatedUnk << 0x11 | 2); + } else { + if (DAT_UnitsState::instance.units[unitID].currentIndexInPathPlan + < DAT_UnitsState::instance.units[unitID].totalSizeOfPathPlan + && (targetingType = DAT_UnitsState::instance.units[unitID].targetingType, + targetingType != Map::Units::UIT_UNIT_ATTACK_UNIT) + && targetingType != Map::Units::UIT_ATTACK_LAND + && targetingType != Map::Units::UIT_MAN_SIEGE_EQUIPMENT) { + tile = DAT_UnitsState::instance.units[unitID].plannedDestinationX + + DAT_ViewportRenderState::instance + .translationMatrix[DAT_UnitsState::instance.units[unitID].plannedDestinationY] + .addXgetTile; + cursorValue = DAT_TileMapState::instance.cursorOverlayAnimationFrame + -1; + if (!(cursorValue < 8)) { + cursorValue = 0xf - cursorValue; + } + MACRO_CALL_MEMBER(Rendering::ViewportRenderState_Func::createFloatingLayerElement, + DAT_ViewportRenderState::ptr)( + IO::Graphics::GID_CURSORS, cursorValue + 0x52, 0xc, 6, tile, 2); + } + } + targetingType = DAT_UnitsState::instance.units[unitID].targetingType; + if (targetingType == Map::Units::UIT_ATTACK_LAND + || targetingType == Map::Units::UIT_THROW_COW) { + MACRO_CALL_MEMBER(Map::TileMapState_Func::spawnFloatingNumberAroundTile, + DAT_TileMapState::ptr)(DAT_UnitsState::instance.units[unitID].attackAtTileX, + DAT_UnitsState::instance.units[unitID].attackAtTileY, + DAT_UnitsState::instance.units[unitID].unkAttackRelated); + } else if (targetingType == Map::Units::UIT_FILL_MOAT) { + MACRO_CALL_MEMBER(Rendering::ViewportRenderState_Func::createFloatingTextElement, + DAT_ViewportRenderState::ptr)(0x4e, 6, -0x20, + DAT_UnitsState::instance.units[unitID].targetX + + DAT_ViewportRenderState::instance + .translationMatrix[DAT_UnitsState::instance.units[unitID].targetY] + .addXgetTile, + 2); + } else if (targetingType == Map::Units::UIT_DIG_MOAT) { + MACRO_CALL_MEMBER(Rendering::ViewportRenderState_Func::createFloatingTextElement, + DAT_ViewportRenderState::ptr)(0x4e, 6, -0x20, + DAT_UnitsState::instance.units[unitID].targetX + + DAT_ViewportRenderState::instance + .translationMatrix[DAT_UnitsState::instance.units[unitID].targetY] + .addXgetTile, + 2); + } else if (targetingType == Map::Units::UIT_UNIT_ATTACK_UNIT) { + int const targetUnitID = DAT_UnitsState::instance.units[unitID] + .targetedUnitID__OR__engineerMannedSiegeEngineRef; + if ((DAT_UnitsState::instance.units[targetUnitID].uid + == DAT_UnitsState::instance.units[unitID] + .targetedUnitUIDUnk_OR_someAppearTileUnk_OR_buildingUID_OR_pitchDitchUID_OR_entityUID) + && (DAT_UnitsState::instance.units[targetUnitID].logicalState + == Map::Units::ULS_NORMAL)) { + DAT_UnitsState::instance.units[targetUnitID].field_0x6c = 1; + } + } else if (targetingType == Map::Units::UIT_ATTACK_BUILDING) { + short const buildingID + = DAT_UnitsState::instance.units[unitID].targetID_OR_targetBuildingID; + if ((buildingID) + && (DAT_BuildingsState::instance.buildings[buildingID].uid + == DAT_UnitsState::instance.units[unitID] + .targetedUnitUIDUnk_OR_someAppearTileUnk_OR_buildingUID_OR_pitchDitchUID_OR_entityUID)) { + DAT_BuildingsState::instance.buildings[buildingID].targetMarker = 1; + } + } else if (targetingType == Map::Units::UIT_LIGHT_PITCH) { + short const pitchDitchID + = DAT_UnitsState::instance.units[unitID].targetID_OR_targetBuildingID; + if ((pitchDitchID) + && (DAT_TileMapState::instance.pitchDitches[pitchDitchID].uid + == DAT_UnitsState::instance.units[unitID] + .targetedUnitUIDUnk_OR_someAppearTileUnk_OR_buildingUID_OR_pitchDitchUID_OR_entityUID)) { + DAT_TileMapState::instance + .MiscDisplayLayer[DAT_TileMapState::instance.pitchDitches[pitchDitchID].tile] + = DAT_TileMapState::instance + .MiscDisplayLayer[DAT_TileMapState::instance.pitchDitches[pitchDitchID].tile] + | 0x4000; + } + } else { + uint buildingTile = DAT_UnitsState::instance.units[unitID].targetedBuildingTile; + if ((buildingTile) && (DAT_TileMapState::instance.BuildingLayer[buildingTile] != 0)) { + DAT_BuildingsState::instance + .buildings[DAT_TileMapState::instance.BuildingLayer[buildingTile]] + .targetMarker = 1; + } + } + } + } while (index < this->tribes[tribeID].size); + } + return; + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/getAvailableTribeID.cpp b/src/OpenSHC/Map/Units/TribesState/getAvailableTribeID.cpp new file mode 100644 index 0000000000..186050ab4f --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/getAvailableTribeID.cpp @@ -0,0 +1,64 @@ +#include "../../../Map.func.hpp" +#include "../TribesState.func.hpp" + +#include "OpenSHC/Game/GameMode.hpp" + +#include "OpenSHC/Globals/DAT_CurrentTribeID.hpp" +#include "OpenSHC/Globals/DAT_GameCore.hpp" +#include "OpenSHC/Globals/DAT_GameSynchronyState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Game::GameMode; + + /* + Both searches break out of their loop and test the slot ID again afterwards; the + original jump-threads that test into each loop's exhausted exit but keeps it on + the found path. The solitary search runs on DAT_CurrentTribeID itself and takes + the ID only when it finds a slot, as createTribe does; counting a local down + beside the global stores the global from a copy of the register. + */ + // FUNCTION: STRONGHOLDCRUSADER 0x00522720 + int TribesState::getAvailableTribeID(int playerID) + { + int tribeID; + if (DAT_GameSynchronyState::instance.currentGameMode == Game::GM_SOLITARY) { + tribeID = 0; + for (DAT_CurrentTribeID::instance = 1249; (int)DAT_CurrentTribeID::instance > 0; + DAT_CurrentTribeID::instance = DAT_CurrentTribeID::instance - 1) { + if (this->tribes[DAT_CurrentTribeID::instance].tribeState == 0 + && this->tribes[DAT_CurrentTribeID::instance].time == 0) { + tribeID = DAT_CurrentTribeID::instance; + break; + } + } + if (tribeID <= 0) { + return 0; + } + this->tribes[tribeID].time = 1; + return tribeID; + } + for (tribeID = 1250 - playerID, DAT_CurrentTribeID::instance = tribeID; tribeID > 0; + tribeID = tribeID - 8, DAT_CurrentTribeID::instance = tribeID) { + if (this->tribes[DAT_CurrentTribeID::instance].tribeState == 0 + && this->tribes[DAT_CurrentTribeID::instance].time == 0) { + break; + } + } + if (tribeID <= 0) { + return 0; + } + /* + The 400 is added to the full tick count and only then truncated + (`mov edx, [..]`, `add edx, 0x190`, `mov word ptr [..], dx`), not to a value + already cut down to a short. + */ + this->tribes[tribeID].time = (short)(DAT_GameCore::instance.mapTimeInTicks + 400); + return tribeID; + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/getSpecificUnitFromTribe.cpp b/src/OpenSHC/Map/Units/TribesState/getSpecificUnitFromTribe.cpp new file mode 100644 index 0000000000..4304fa21da --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/getSpecificUnitFromTribe.cpp @@ -0,0 +1,56 @@ +#include "../../../Map.func.hpp" +#include "../TribesState.func.hpp" + +#include "OpenSHC/Globals/DAT_00ee0fb4.hpp" +#include "OpenSHC/Globals/DAT_Tribe_HighestID.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + /* + An iterator over the tribe's members kept in two globals: the word index in + DAT_Tribe_HighestID and the bit index in DAT_00ee0fb4. param_2 == 0 restarts it. + The globals are written from the locals, which is why the restart and the + per-word reset store a register (`xor ecx, ecx` then `mov [..], ecx`) while the + wrap after the last bit stores an immediate. + */ + // FUNCTION: STRONGHOLDCRUSADER 0x00522410 + int TribesState::getSpecificUnitFromTribe(int tribeID, int param_2) + { + int wordIndex; + int bitIndex; + if (param_2 == 0) { + wordIndex = this->tribes[tribeID].highestID; + bitIndex = 0; + DAT_Tribe_HighestID::instance = wordIndex; + DAT_00ee0fb4::instance = bitIndex; + } else { + wordIndex = DAT_Tribe_HighestID::instance; + bitIndex = DAT_00ee0fb4::instance; + } + for (; wordIndex < 200; wordIndex++) { + short const bits = this->tribes[tribeID].unitSelectionBitMasked[wordIndex]; + if (bits != 0) { + for (; bitIndex < 16; bitIndex++) { + if ((1 << bitIndex) & (int)bits) { + DAT_00ee0fb4::instance = bitIndex + 1; + if (bitIndex + 1 == 16) { + DAT_Tribe_HighestID::instance = wordIndex + 1; + DAT_00ee0fb4::instance = 0; + return wordIndex * 16 + bitIndex; + } + DAT_Tribe_HighestID::instance = wordIndex; + return wordIndex * 16 + bitIndex; + } + } + } + bitIndex = 0; + DAT_00ee0fb4::instance = bitIndex; + } + return 0; + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/getUnitIDForIndexInTribe.cpp b/src/OpenSHC/Map/Units/TribesState/getUnitIDForIndexInTribe.cpp new file mode 100644 index 0000000000..cb900a3c71 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/getUnitIDForIndexInTribe.cpp @@ -0,0 +1,41 @@ +#include "../../../Map.func.hpp" +#include "../TribesState.func.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + /* + Two separate early returns: the original pushes ebx/esi/ebp only after the + tribe-state test (one `pop edi; ret` for that exit), which a combined + `state == 2 && index < size` guard does not give. + */ + // FUNCTION: STRONGHOLDCRUSADER 0x00522390 + int TribesState::getUnitIDForIndexInTribe(int tribeID, int unitSelectionIndex) + { + int count = 0; + if (this->tribes[tribeID].tribeState != 2) { + return 0; + } + if (unitSelectionIndex >= this->tribes[tribeID].size) { + return 0; + } + for (int wordIndex = 0; wordIndex < 200; wordIndex++) { + short const bits = this->tribes[tribeID].unitSelectionBitMasked[wordIndex]; + if (bits != 0) { + for (int bitIndex = 0; bitIndex < 16; bitIndex++) { + if ((1 << bitIndex) & (int)bits) { + if (count == unitSelectionIndex) { + return wordIndex * 16 + bitIndex; + } + count++; + } + } + } + } + return 0; + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/giveTribeAnInstruction.cpp b/src/OpenSHC/Map/Units/TribesState/giveTribeAnInstruction.cpp new file mode 100644 index 0000000000..fb47db9e1e --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/giveTribeAnInstruction.cpp @@ -0,0 +1,2227 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Map/Buildings/BuildingsState.func.hpp" +#include "OpenSHC/Map/Navigation/PathFindingState.func.hpp" +#include "OpenSHC/Map/TileMapState.func.hpp" +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/Units/UnitsState.func.hpp" +#include "OpenSHC/Random/RNG.func.hpp" +#include "OpenSHC/Rendering/ViewportRenderState.func.hpp" +#include "OpenSHC/Game/GameMode.hpp" +#include "OpenSHC/Game/GameMode2.hpp" +#include "OpenSHC/Map/Buildings/BuildingType.hpp" +#include "OpenSHC/Map/Navigation/PathHelper12.hpp" +#include "OpenSHC/Map/Units/States/UnitState.hpp" +#include "OpenSHC/Map/Units/UnitInstructionType.hpp" +#include "OpenSHC/Map/Units/UnitLogicState.hpp" +#include "OpenSHC/Map/Units/UnitType.hpp" +#include "OpenSHC/WindowsHelper/Enums/BOOLEnum.hpp" + +#include "OpenSHC/Globals/DAT_AttackInfoDefinedData.hpp" +#include "OpenSHC/Globals/DAT_BuildingsState.hpp" +#include "OpenSHC/Globals/DAT_GameCore.hpp" +#include "OpenSHC/Globals/DAT_GameState.hpp" +#include "OpenSHC/Globals/DAT_GameSynchronyState.hpp" +#include "OpenSHC/Globals/DAT_PathFindingState.hpp" +#include "OpenSHC/Globals/DAT_TileMapState.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" +#include "OpenSHC/Globals/DAT_ViewportRenderState.hpp" +#include "OpenSHC/Globals/SEC_RNG.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Game::GameMode; + using Game::GameMode2; + using Map::Buildings::BuildingType; + using Map::Navigation::PathHelper12; + using Map::Units::UnitInstructionType; + using Map::Units::UnitLogicState; + using Map::Units::UnitType; + using Map::Units::States::UnitState; + using WindowsHelper::Enums::BOOLEnum; + + /* + gynt: unitID and x and y and id are the target of the instruction decompilerscript: committed: 2025-01-30 + 21:57:43.216000 + */ + /* + The subscript stays, and this is the measurement that says why nothing else here + is worth trying from the instruction counts. + + The original has exactly one `imul .., 0x334` in the whole function; we have 63, + because every `this->tribes[tribeID].` recomputes the stride. Caching the base as + a shifted `TribesState*` - which keeps the field displacements identical to the + subscript's, unlike a `Tribe&` - fixes that completely and brings three separate + measures of closeness almost exactly into line: + + imul 0x334 63 -> 1 (original: 1) + instructions 2628 -> 2514 (original: 2501) + quick_diff 0.4296 -> 0.4622 + + reccmp scores it 60.4% -> 55.6%. And it is not register naming: the + register-blind ratio diff_regalloc.py computes goes 66.6% -> 66.4%, flat. So the + instruction sequence is no closer at all, even with the counts and the mnemonic + histogram matching. Three independent "looks closer" signals can all improve + while the actual alignment does not; only reccmp decides, and the 21-site pointer + hoist on _unitID_0x04 that was tried alongside this did not even change the imul + count - MSVC was already common-subexpressioning those. + + All thirteen switch dispatches in this function have been checked against their + tables, so this does not need redoing. They are at 0x52a1e8, 0x52a258, 0x52a2b8, + 0x52a308, 0x52a368, 0x52a3b8, 0x52a3fc, 0x52a464, 0x52a490, 0x52a4e4, 0x52a550, + 0x52a5a8 and 0x52a5e4 - found by searching the function for the indirect + `jmp dword ptr [reg*4 + disp]` rather than hunting them one at a time. + + Corrected: the outer switch's arm order (worth 23.9 earlier), then the second, + fourth, seventh, ninth and tenth, and one wrong label on the eleventh + (UT_TUNNELER, a behaviour bug). Already correct and left alone: the third, + fifth, eighth and twelfth have a single real arm each; the sixth and thirteenth + match in both order and labels. + + Every label set matched the import except the eleventh's, so the + catapult-for-mangonel class of mistake found in playUnitSelectionSound is not + widespread here. + + What is left in this function is cold-block placement and register allocation - + UIT_MAN_SIEGE_EQUIPMENT is emitted after our epilogue where the original has it + inline at 0x529a8b - which no arrangement of the source reaches. + */ + /* + The arms were not out-of-line helpers, and this is settled rather than assumed. + Ghidra has no unnamed function anywhere in 0x521180 - 0x52b860: every address in + that span is a named TribesState method and the gap between consecutive ones is + the preceding method's own length, so the original translation unit emitted no + static function of its own. Whatever helpers the 2002 source had, the compiler + inlined all of them. + + Inlining them back does not change the code either. The ladder arm - eighty-five + lines, nine locals of its own, one call site - was extracted into + + static BOOLEnum setLaddersAgainstWallTile( + TribesState* self, int tribeID, int _tribeSize, int _wallTile) + + with the arm reduced to `if (setLaddersAgainstWallTile(...)) return 1;`. MSVC + inlined it - no call appears in the diff and the function keeps its length - and + the score moved 60.6% -> 60.5%. An inlined static body therefore gets the same + slots and the same registers as the same statements written inline, which is also + why splitting the decompiler's folded scratch into a local per arm is exactly + neutral. Writing the arms as helpers is a readability choice with a small price, + not a way into the register allocation. + */ + // FUNCTION: STRONGHOLDCRUSADER 0x00527C80 + BOOLEnum TribesState::giveTribeAnInstruction( + int tribeID, UnitInstructionType unitInstructionType, int id, int unitUID, int param_5) + { + short* psVar1; + byte bVar2; + UnitStateShort UVar3; + /* + Both of this function's wide scratch locals stay as they are, and the two + measurements together say when widening pays and when it does not. + + `sVar9` is a `short` used 82 times, and the diff shows 33 register-to- + register re-extensions against the original's 10 - `movsx ecx, cx` each time + it is used as an index again. Widening it to `int` to extend once measures + 59.0% -> 58.3%. + + The same change was worth +17.4 on getMajoritySelectedUnitType. The + difference is that there the local had one purpose - the unit type, used for + a bound test and then as an array index - where `sVar9` here is the + decompiler's general short scratch, holding a tribe size in one arm and a + unit id in the next. Widening a single-purpose local that is tested and then + indexed with pays; widening a shared scratch does not. + + UVar4 stays 16 bits wide. The original compares it 32-bit in places - `cmp + ecx, 0x16` and `cmp ecx, 0x46` at the pitch-ditch arm against our + `cmp cx, ..` - and the switch dispatches on it 32-bit too, so UnitTypeInt + looks right. It measures 59.0% -> 57.6% across the sixteen uses. Reverted. + */ + UnitTypeShort UVar4; + /* + Dword flags, not `bool`s: diff_slots.py shows byte-aligned stack slots at + 0x13 and 0x1b on our side and none on the original's. + */ + BOOLEnum bVar5; + Unit* pUVar6; + char cVar7; + short sVar8; + int _unitID_0x03; + int _unitID_0x04; + int _targetUnitID; + uint _x_528565; + UnitInstructionType UVar10; + int iVar11; + int _unitID_0x05_0x16; + int iVar12; + int _unitID; + /* + This one stays `short`, although nine of our `movzx` plus `movsx` pairs are + its `tileTranslationMatrix_YComponent` reads indexing `translationMatrix` - + the same shape that took scatterTribeUnitsRandomly to 100% and gained the two + movement-speed functions about ten points each. Widening it costs 0.8 points + (27.9% -> 27.1%): the decompiler folded several of the original's variables + into this one, so the change lands on all of them at once and the losses eat + the gains. + */ + short sVar9; + uint uVar13; + int iVar15; + int _laddermanID; + undefined3 extraout_var; + int _unitID_0x1e; + BOOLEnum BVar16; + uint _freeTileX; + uint uVar17; + uint x; + int _unitID_0x11; + short _param_3_id_x_tile_buildingID_copy; + int _unitSelectionIndex; + int* piVar18; + uint y; + uint uVar19; + BOOLEnum _gamemodeSiegeThat; + int _unitTribeIndex; + int _ramOrHorse; + uint local_8; + dword _param_4_unitUID_Y_copy; + int _tile1_528565; + short _y_528565; + /* + An `int`: the original reads the size with `movsx esi, word ptr [ebp + 0x5c]` + at 0x527c99 and compares it 32 bits wide (`cmp esi, edx`), where a `short` + gives `movzx`. It is only ever used in `0 < _tribeSize` guards, so nothing is + truncated differently. + */ + int _tribeSize; + int _freeTile; + uint _defensiveTile1; + short _freeTileY; + short _y; + short _x; + ushort _targetArea; + iVar11 = id; + /* + Two things here make our frame exactly the original's 0x1c, down from 0x28, + and diff_slots.py reports the same sixteen slots on both sides with nothing + left over: the tribeID copy is gone, the subscripts having been its only real + users, and the two unitUID copies are one, because `_param_4_unitUID_Y` was + read only in the ATTACK_LAND arm and `_param_4_unitUID_Y_copy` only in the + siege arms, so their live ranges never overlap. + + What must NOT be done is bind the subscripts to a `Tribe&`. The original does + take the tribe's address once (`lea ebp, [eax + ecx]` at 0x527c93, spilled to + [esp + 0x18]), which makes a reference look right, and it is not needed for + the frame anyway - these two changes get there on their own. But its base is + `this + tribeID * 0x334` with the 0x28 `tribes` offset folded into every + displacement, so the size is `[ebp + 0x5c]`. A reference rebases onto + `&tribes[tribeID]` and the same field becomes `[eax + 0x34]` - the same + address, a different encoding, on all 74 tribe field accesses. That is worth + 4.8 points (56.8% against 52.0%), and it is what the plain subscript emits. + + This also explains two earlier measurements that had been put down to the + frame: the reference costing 2.8 points on its own, and the frame fix netting + only 0.1 when it was bundled with the reference - it got the frame exactly + right and broke every displacement at the same time, so the two cancelled. + + Caching the base while keeping the displacement does not work either, though + the slot census makes it look inviting: the original touches its tribeID + argument 36 times where the plain subscript touches it 90, because it holds + `this + tribeID * 0x334` in EBP. Shifting a TribesState pointer by whole Tribe + strides and subscripting at zero gives the right address with the right + encoding and one base to cache - and it loses. Measured twice, because the + first run was on the build where _tribeSize had lost its initialisation: on + corrected code it is 52.0% against the subscript's 56.8%, which is also what + the `Tribe&` scored. Caching the base costs 4.8 points whichever way the + displacement is written. + + The instructive part is that every cheap signal said the opposite. Caching + takes the function from 2312 instructions to 2187 against the original's 2157, + and lifts quick_diff from 0.4296 to 0.4622 - fewer instructions, closer + length, better ratio, worse score. The plain subscript re-derives + `tribeID * 0x334` at all 74 accesses and is still the better match, so do not + trust instruction count or quick_diff here without confirming on reccmp. + + The paradox resolves into register selection, which no source form reaches. + The UNIT_ATTACK_UNIT arm shows the original reading the size as + `movsx eax, word ptr [ebp + 0x5c]` - base cached in EBP, no imul - so it + really does cache. It also materialises zero in EAX (`xor eax, eax`) where we + use EDI and EDX. Asking for a cached base gets us one, but MSVC puts it in a + register of its own choosing and that cascades through everything else; the + re-derived form happens to leave the other registers where the original has + them. That is the whole of the remaining gap in this arm, together with cold + blocks: MAN_SIEGE_EQUIPMENT is emitted after the epilogue here and inline at + 0x529a8b in the original, with the arm order already matching the table. + */ + /* + Declaration order is a dead end here, and this can be shown rather than + measured, so do not run perm_decls.py over this run. The frame matches, so + diff_slots.py reports the same seven local slots on both sides - but the + access counts per slot are + + original 6, 9, 10, 14, 24, 25, 53 (total 141) + ours 6, 14, 19, 21, 25, 29, 32 (total 146) + + and reordering declarations only permutes which slot carries which count. The + two multisets are not equal, so no order can make them agree. What differs is + the distribution: the original's hottest local takes 53 accesses - from the + prologue that slot is its `id` copy, `mov edi, [esp + 0x38]` at 0x527ca6 then + `mov [esp + 0x10], edi` at 0x527cb0 - where ours tops out at 32, and its three + zeroed counters take 9, 10 and 14 against our 19, 21 and 29. The original + holds those values in registers across stretches where we spill them, which is + register allocation and not something declaration order reaches. + + The obvious-looking repair does not exist either: our `iVar11` and `uVar13` are + not further copies of `id` that could be merged into one hot local, they are + the decompiler's general scratch, reassigned at fifteen and twelve sites. + */ + _tribeSize = this->tribes[tribeID].size; + _param_4_unitUID_Y_copy = unitUID; + _ramOrHorse = 0; + local_8 = 0; + bVar5 = FALSE; + this->tribes[tribeID].someUnitID = 0; + this->tribes[tribeID].containsRabbit = 0; + _param_3_id_x_tile_buildingID_copy = (short)id; + uVar13 = id; + /* + The arm order here is the original's block order and is worth 23.9 points. The + nested switches' arm order is not worth anything, and that has now been tested + three times, each against the switch's own jump table: + + - 0x528e3a: putting the archer arm first so it falls through into the block + below, which is exactly what 0x528e41 does, costs 0.9 points; + - 0x5290c7: reordering its eight arms into table order adds 0.1 back; + - 0x52a308: moving the big arm to third, where 0x52838a puts it, costs 0.3. + + So the rule is about scope, not about ordering as such. The outer switch fixes + where each hundred-instruction arm begins, and getting that wrong misaligns + everything downstream - which is why it was worth 23.9. Inside an arm the + blocks are small and MSVC lays them out to its own branch heuristics, so + forcing source order on them just fights the compiler. Do not re-run these. + */ + switch (unitInstructionType) { + case Map::Units::UIT_NO_INSTRUCTION_OR_MOVEUnk: + _unitSelectionIndex = 0; + if (0 < _tribeSize) { + do { + _unitID_0x03 = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)( + tribeID, _unitSelectionIndex); + _unitSelectionIndex = _unitSelectionIndex + 1; + if ((DAT_UnitsState::instance.units[_unitID_0x03].logicalState == Map::Units::ULS_NORMAL) + && (DAT_UnitsState::instance.units[_unitID_0x03].dying == 0)) { + DAT_UnitsState::instance.units[_unitID_0x03].field_0x3c5 = 3; + DAT_UnitsState::instance.units[_unitID_0x03].targetingType + = Map::Units::UIT_NO_INSTRUCTION_OR_MOVEUnk; + DAT_UnitsState::instance.units[_unitID_0x03].field_0x3b0 = 0; + } + } while (_unitSelectionIndex < this->tribes[tribeID].size); + return TRUE; + } + break; + case Map::Units::UIT_STOP: + iVar11 = 0; + this->tribes[tribeID].isRallyingUnk = 0; + this->tribes[tribeID].someUnitID = 0; + if (0 < _tribeSize) { + do { + iVar12 = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)( + tribeID, iVar11); + iVar11 = iVar11 + 1; + if (DAT_UnitsState::instance.units[iVar12].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[iVar12].dying == 0 + && DAT_UnitsState::instance.units[iVar12].field_0x413 == 0) { + DAT_UnitsState::instance.units[iVar12].field_0x3c5 = 3; + DAT_UnitsState::instance.units[iVar12].targetingType + = Map::Units::UIT_NO_INSTRUCTION_OR_MOVEUnk; + DAT_UnitsState::instance.units[iVar12].field_0x3b0 = 0; + MACRO_CALL_MEMBER( + Map::Units::UnitsState_Func::makeUnitStopWalkingByClearingPathProgressState, + DAT_UnitsState::ptr)(iVar12); + DAT_UnitsState::instance.units[iVar12].targetedBuildingTile = 0; + DAT_UnitsState::instance.units[iVar12].movementType_OR_targetUnitID = 0; + } + } while (iVar11 < this->tribes[tribeID].size); + return TRUE; + } + break; + case Map::Units::UIT_UNIT_ATTACK_UNIT: + int _pathTile; + /* + unit attack target + */ + this->tribes[tribeID].isRallyingUnk = 0; + pUVar6 = DAT_UnitsState::instance.units + id; + _unitTribeIndex = 0; + /* + repurposed parameter: counts amount of melee units + */ + id = 0; + if (pUVar6->uid != unitUID) { + return FALSE; + } + if (0 < _tribeSize) { + do { + _unitID_0x04 = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)( + tribeID, _unitTribeIndex); + _unitTribeIndex = _unitTribeIndex + 1; + if (DAT_UnitsState::instance.units[_unitID_0x04].logicalState != Map::Units::ULS_NORMAL + || DAT_UnitsState::instance.units[_unitID_0x04].dying != 0 + || DAT_UnitsState::instance.units[_unitID_0x04].field_0x413 != 0) + continue; + DAT_UnitsState::instance.units[_unitID_0x04]._someX_2 = 0; + DAT_UnitsState::instance.units[_unitID_0x04]._someY_2 = 0; + /* + Arm order from the dispatch at 0x52a258: five dword entries and a + 0x49-entry byte index table at 0x52a26c, indexed by `unitType - + 5`. By address the arms run 0x527eac (mangonel, ballista, + fire ballista), 0x527efd (the six ranged types), 0x527f4b (the + eleven melee types) and 0x527f6d (catapult, trebuchet), so the + siege pair the import had third is really last and the mangonel + group it had last is first. + + LAB_00527ee1 sits inside the mangonel arm's tail, which is why + the ranged arm's `goto` is a backward jump in the original + (0x527efd to 0x527ee1). With that arm moved to the front the + label block needs an explicit `break` - the original ends it with + `jmp 0x527fab`, the switch's exit - or the melee labels below + would be fallen into. + */ + switch (DAT_UnitsState::instance.units[_unitID_0x04].unitType) { + case Map::Units::UT_S_MANGONEL: + case Map::Units::UT_S_BALLISTA: + case Map::Units::UT_S_FBALLISTA: + DAT_UnitsState::instance.units[_unitID_0x04].targetingType + = Map::Units::UIT_UNIT_ATTACK_UNIT; + DAT_UnitsState::instance.units[_unitID_0x04] + .targetedUnitID__OR__engineerMannedSiegeEngineRef = _param_3_id_x_tile_buildingID_copy; + DAT_UnitsState::instance.units[_unitID_0x04] + .targetedUnitUIDUnk_OR_someAppearTileUnk_OR_buildingUID_OR_pitchDitchUID_OR_entityUID + = unitUID; + DAT_UnitsState::instance.units[_unitID_0x04].field_0x3f8 = 0; + MACRO_CALL_MEMBER( + Map::Units::UnitsState_Func::makeUnitStopWalkingByClearingPathProgressState, + DAT_UnitsState::ptr)(_unitID_0x04); + DAT_UnitsState::instance.units[_unitID_0x04].shootBeforeStop = 10; + LAB_00527ee1: + if (DAT_UnitsState::instance.units[iVar11].unitType == Map::Units::UT_RABBIT) { + this->tribes[tribeID].containsRabbit = 1; + } + break; + case Map::Units::UT_E_ARCHER: + case Map::Units::UT_E_XBOW: + case Map::Units::UT_A_ARCHER: + case Map::Units::UT_A_SLINGER: + case Map::Units::UT_A_HARCHER: + case Map::Units::UT_A_FIRETHROWER: + /* + ranged units + */ + if (DAT_UnitsState::instance.units[_unitID_0x04].state.generic == (UnitState)0x69) { + DAT_UnitsState::instance.units[_unitID_0x04].state.generic + = Map::Units::States::US_MOVE_TO_DESTINATION; + } + DAT_UnitsState::instance.units[_unitID_0x04] + .targetedUnitUIDUnk_OR_someAppearTileUnk_OR_buildingUID_OR_pitchDitchUID_OR_entityUID + = unitUID; + DAT_UnitsState::instance.units[_unitID_0x04].targetUID = unitUID; + DAT_UnitsState::instance.units[_unitID_0x04].targetingType + = Map::Units::UIT_UNIT_ATTACK_UNIT; + DAT_UnitsState::instance.units[_unitID_0x04] + .targetedUnitID__OR__engineerMannedSiegeEngineRef = _param_3_id_x_tile_buildingID_copy; + DAT_UnitsState::instance.units[_unitID_0x04].shootTargetedUnit + = _param_3_id_x_tile_buildingID_copy; + DAT_UnitsState::instance.units[_unitID_0x04].field_0x3f8 = 0; + MACRO_CALL_MEMBER( + Map::Units::UnitsState_Func::makeUnitStopWalkingByClearingPathProgressState, + DAT_UnitsState::ptr)(_unitID_0x04); + goto LAB_00527ee1; + case Map::Units::UT_TUNNELER: + case Map::Units::UT_E_SPEAR: + case Map::Units::UT_E_PIKE: + case Map::Units::UT_E_MACE: + case Map::Units::UT_E_SWORD: + case Map::Units::UT_E_KNIGHT: + case Map::Units::UT_E_MONK: + case Map::Units::UT_LORD: + case Map::Units::UT_A_SLAVE: + case Map::Units::UT_A_ASSASSIN: + case Map::Units::UT_A_SWORDSMAN: + /* + melee units + */ + if (DAT_UnitsState::instance.units[iVar11].unitType != Map::Units::UT_ANTELOPESHDEER + && (param_5 != 1 + || (DAT_UnitsState::instance.units[iVar11].state.generic + != Map::Units::States::US_MELEE_ATTACK))) { + id = id + 1; + } + break; + case Map::Units::UT_S_CATAPULT: + case Map::Units::UT_S_TREBUCHET: + DAT_UnitsState::instance.units[_unitID_0x04].field_0x3c5 = 5; + DAT_UnitsState::instance.units[_unitID_0x04].targetingType = Map::Units::UIT_ATTACK_LAND; + DAT_UnitsState::instance.units[_unitID_0x04].attackAtTileX + = DAT_UnitsState::instance.units[iVar11].x; + DAT_UnitsState::instance.units[_unitID_0x04].attackAtTileY + = DAT_UnitsState::instance.units[iVar11].y; + DAT_UnitsState::instance.units[_unitID_0x04].unkAttackRelated = 0xb; + DAT_UnitsState::instance.units[_unitID_0x04].shootBeforeStop = 10; + break; + } + } while (_unitTribeIndex < this->tribes[tribeID].size); + /* + `id` is zeroed before the loop and counted up in the melee arm, so + this asks whether the selection held any melee units. The original is + one `cmp dword ptr [esp + 0x38], 0` against that counter's slot; the + decompiler rendered it as `id | x | id != 0`, which read an + uninitialised local and raised C4700. + */ + if (id != 0) { + /* + if there are melee units in the selection + */ + _targetUnitID = (int)this->tribes[tribeID].selectionTargetUnitID; + local_8 = (uint)DAT_UnitsState::instance.units[_targetUnitID].x; + unitInstructionType = (UnitInstructionType)DAT_UnitsState::instance.units[_targetUnitID].y; + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::predictUnitInterceptPosition, this)( + _targetUnitID, iVar11, (int*)&local_8, (int*)&unitInstructionType); + MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func::pathPlanningForTribe, + DAT_PathFindingState::ptr)(tribeID, (undefined4)((int)(iVar11)), local_8, + (uint)(unitInstructionType), id, + (dword)((int)((short)DAT_TileMapState::instance + .PathConnectionLayer[DAT_UnitsState::instance.units[_targetUnitID].tile])), + (int)(DAT_UnitsState::instance.units[_targetUnitID].owner)); + this->tribes[tribeID].someUnitID = _param_3_id_x_tile_buildingID_copy; + this->tribes[tribeID].someUnitUID = unitUID; + this->tribes[tribeID].someTile = DAT_UnitsState::instance.units[iVar11].tile; + iVar12 = 0; + sVar9 = this->tribes[tribeID].size; + this->tribes[tribeID].someTile2 = (int)DAT_UnitsState::instance.units[iVar11].destinationX_2Unk + + DAT_ViewportRenderState::instance + .translationMatrix[DAT_UnitsState::instance.units[iVar11].destinationY_2Unk] + .addXgetTile; + unitInstructionType = ((UnitInstructionType)0); + if (0 < sVar9) { + id = 0x12d5c6c; + do { + iVar11 = MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)(tribeID, iVar12); + iVar12 = iVar12 + 1; + if (DAT_UnitsState::instance.units[iVar11].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[iVar11].dying == 0 + && DAT_UnitsState::instance.units[iVar11].field_0x413 == 0) { + UVar4 = DAT_UnitsState::instance.units[iVar11].unitType; + switch (UVar4) { + case Map::Units::UT_TUNNELER: + case Map::Units::UT_E_SPEAR: + case Map::Units::UT_E_PIKE: + case Map::Units::UT_E_MACE: + case Map::Units::UT_E_SWORD: + case Map::Units::UT_E_KNIGHT: + case Map::Units::UT_E_MONK: + case Map::Units::UT_LORD: + case Map::Units::UT_A_SLAVE: + case Map::Units::UT_A_ASSASSIN: + case Map::Units::UT_A_SWORDSMAN: + if (((param_5 != 1) + || (DAT_UnitsState::instance.units[iVar11].state.generic + != Map::Units::States::US_MELEE_ATTACK)) + && (_pathTile = *(int*)id, _pathTile != 0)) { + sVar9 = DAT_ViewportRenderState::instance + .tileTranslationMatrix_YComponent[_pathTile]; + uVar13 = _pathTile + - DAT_ViewportRenderState::instance.translationMatrix[sVar9] + .addXgetTile; + if (*(int*)(id + 4) == 0) { + DAT_UnitsState::instance.units[iVar11].targetingType + = ((UnitInstructionType)0); + if (UVar4 == Map::Units::UT_LORD) + break; + } else { + DAT_UnitsState::instance.units[iVar11].targetingType + = Map::Units::UIT_UNIT_ATTACK_UNIT; + DAT_UnitsState::instance.units[iVar11] + .targetedUnitID__OR__engineerMannedSiegeEngineRef + = _param_3_id_x_tile_buildingID_copy; + DAT_UnitsState::instance.units[iVar11] + .targetedUnitUIDUnk_OR_someAppearTileUnk_OR_buildingUID_OR_pitchDitchUID_OR_entityUID + = unitUID; + } + UVar3 = DAT_UnitsState::instance.units[iVar11].state.generic; + DAT_UnitsState::instance.units[iVar11].plannedDestinationX = (short)uVar13; + DAT_UnitsState::instance.units[iVar11].plannedDestinationY = sVar9; + DAT_UnitsState::instance.units[iVar11].targetedBuildingTile = 0; + DAT_UnitsState::instance.units[iVar11].movementType_OR_targetUnitID = 0; + if (UVar3 == Map::Units::States::US_MELEE_ATTACK) { + DAT_UnitsState::instance.units[iVar11].movementCooldown + = DAT_UnitsState::instance.units[iVar11].movementSpeed * -4; + } + DAT_UnitsState::instance.units[iVar11].state.generic + = Map::Units::States::US_MOVE_TO_DESTINATION; + BVar16 = MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::isTribeAllAssassins, this)(tribeID); + /* + The all-assassins store is the fall-through. + The original jumps 0xc forward when the + result is zero (`test eax, eax; je 0xc`), so + the +136 store follows the test and the +128 + store goes in the far block - the same + displacement either way, just the two arms + the other way round. + */ + if (BVar16) { + DAT_PathFindingState::instance.allAssassinsUnk = 1; + } else { + DAT_PathFindingState::instance.notAllAssassinsUnk = 1; + } + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::setDestinationForUnit, + DAT_UnitsState::ptr)(iVar11, uVar13, (uint)(sVar9), 0); + UVar10 = (UnitInstructionType)((int)DAT_UnitsState::instance.units[iVar11] + .totalSizeOfPathPlan + / 2); + DAT_UnitsState::instance.units[iVar11].lookForEnemy = -0x32; + if ((int)UVar10 > (int)unitInstructionType) { + unitInstructionType = UVar10; + } + id = id + 0xc; + DAT_PathFindingState::instance.notAllAssassinsUnk = 0; + } + } + } + } while (iVar12 < this->tribes[tribeID].size); + } + iVar11 = unitInstructionType * 8; + /* + `< 9` stays, against the asm. The original has `cmp eax, 8` with + a `jg` at 0x52822b, where this gives `cmp 9` and a `jge`, and the + same at the other copy of this block. The height test further + down is the same story: 0x529bdb is `cmp eax, 0x10; jg` where + `< 0x11` gives `cmp 0x11; jge`, and 0x529bd6 is `cdq; xor eax, + edx; sub eax, edx` - a plain `x < 0 ? -x : x` - where the + decompiler's shift-and-xor gives the `sar` it was read back from. + + All four instructions are wrong in our output and correcting them + costs the same 0.9 points whichever subset is applied: the + constants alone, the absolute value alone, and all of them + together each measure 60.6% -> 59.7%. They sit in the same two + blocks, and the jump lengths those blocks are reached by are + worth more than the instructions themselves. + */ + if (iVar11 < 9) { + iVar11 = 8; + } + this->tribes[tribeID].field_0x2be = (short)iVar11; + return TRUE; + } + } + break; + case ((UnitInstructionType)0x20): + case Map::Units::UIT_SHOOT_TARGETUnk: + int _unitID_0x20; + local_8 = id * 0x490; + pUVar6 = DAT_UnitsState::instance.units + id; + _unitTribeIndex = 0; + id = 0; + if (pUVar6->uid != unitUID) { + return FALSE; + } + if (0 < _tribeSize) { + do { + iVar12 = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)( + tribeID, _unitTribeIndex); + _unitTribeIndex = _unitTribeIndex + 1; + if (DAT_UnitsState::instance.units[iVar12].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[iVar12].dying == 0 + && DAT_UnitsState::instance.units[iVar12].field_0x413 == 0 + && (UVar3 = DAT_UnitsState::instance.units[iVar12].state.generic, + UVar3 != Map::Units::States::US_MELEE_ATTACK)) { + /* + Arm order from 0x52a308: five dwords, 0x49-entry byte table + at 0x52a31c, base 5. By address 0x5282fd (mangonel group), + 0x528311 (ranged), 0x52838a (melee), 0x528398 (catapult + pair) - so the melee arm the import had first belongs third. + The mangonel arm falls through into the ranged arm, so that + pair has to stay adjacent and in that order, which it + already was. + */ + switch (DAT_UnitsState::instance.units[iVar12].unitType) { + case Map::Units::UT_S_MANGONEL: + case Map::Units::UT_S_BALLISTA: + case Map::Units::UT_S_FBALLISTA: + if (unitInstructionType == Map::Units::UIT_SHOOT_TARGETUnk) { + break; + } + DAT_UnitsState::instance.units[iVar12].shootBeforeStop = 10; + /* + and on into the ranged arm, which is what the + decompiler's goto back into it said + */ + case Map::Units::UT_E_ARCHER: + case Map::Units::UT_E_XBOW: + case Map::Units::UT_E_ARCHER_DEBUG: + case Map::Units::UT_A_ARCHER: + case Map::Units::UT_A_SLINGER: + case Map::Units::UT_A_HARCHER: + case Map::Units::UT_A_FIRETHROWER: + if (UVar3 == (UnitState)0x69) { + DAT_UnitsState::instance.units[iVar12].state.generic + = Map::Units::States::US_MOVE_TO_DESTINATION; + } + DAT_UnitsState::instance.units[iVar12].targetingType = Map::Units::UIT_UNIT_ATTACK_UNIT; + DAT_UnitsState::instance.units[iVar12].targetedUnitID__OR__engineerMannedSiegeEngineRef + = _param_3_id_x_tile_buildingID_copy; + DAT_UnitsState::instance.units[iVar12] + .targetedUnitUIDUnk_OR_someAppearTileUnk_OR_buildingUID_OR_pitchDitchUID_OR_entityUID + = unitUID; + DAT_UnitsState::instance.units[iVar12].field_0x3f8 = 0; + if (DAT_UnitsState::instance.units[iVar11].unitType == Map::Units::UT_RABBIT) { + this->tribes[tribeID].containsRabbit = 1; + } + if (DAT_UnitsState::instance.units[iVar12]._someX_2 == 0) { + sVar9 = DAT_UnitsState::instance.units[iVar12].destinationY_2Unk; + DAT_UnitsState::instance.units[iVar12]._someX_2 + = DAT_UnitsState::instance.units[iVar12].destinationX_2Unk; + DAT_UnitsState::instance.units[iVar12]._someY_2 = sVar9; + } + MACRO_CALL_MEMBER( + Map::Units::UnitsState_Func::makeUnitStopWalkingByClearingPathProgressState, + DAT_UnitsState::ptr)(iVar12); + break; + case Map::Units::UT_TUNNELER: + case Map::Units::UT_E_SPEAR: + case Map::Units::UT_E_PIKE: + case Map::Units::UT_E_MACE: + case Map::Units::UT_E_SWORD: + case Map::Units::UT_E_KNIGHT: + case Map::Units::UT_E_MONK: + case Map::Units::UT_LORD: + case Map::Units::UT_A_SLAVE: + case Map::Units::UT_A_ASSASSIN: + case Map::Units::UT_A_SWORDSMAN: + if (unitInstructionType != Map::Units::UIT_SHOOT_TARGETUnk) { + id = id + 1; + } + break; + case Map::Units::UT_S_CATAPULT: + case Map::Units::UT_S_TREBUCHET: + if (unitInstructionType != Map::Units::UIT_SHOOT_TARGETUnk) { + sVar9 = DAT_UnitsState::instance.units[iVar12]._someX_2; + DAT_UnitsState::instance.units[iVar12].field_0x3c5 = 5; + DAT_UnitsState::instance.units[iVar12].targetingType = Map::Units::UIT_ATTACK_LAND; + DAT_UnitsState::instance.units[iVar12].attackAtTileX + = DAT_UnitsState::instance.units[iVar11].x; + DAT_UnitsState::instance.units[iVar12].attackAtTileY + = DAT_UnitsState::instance.units[iVar11].y; + DAT_UnitsState::instance.units[iVar12].unkAttackRelated = 0xb; + if (sVar9 == 0) { + sVar9 = DAT_UnitsState::instance.units[iVar12].destinationY_2Unk; + DAT_UnitsState::instance.units[iVar12]._someX_2 + = DAT_UnitsState::instance.units[iVar12].destinationX_2Unk; + DAT_UnitsState::instance.units[iVar12]._someY_2 = sVar9; + } + MACRO_CALL_MEMBER( + Map::Units::UnitsState_Func::makeUnitStopWalkingByClearingPathProgressState, + DAT_UnitsState::ptr)(iVar12); + DAT_UnitsState::instance.units[iVar12].shootBeforeStop = 10; + } + break; + } + } + } while (_unitTribeIndex < this->tribes[tribeID].size); + /* + The melee counter against zero, as at the first site. + */ + if (id != 0) { + iVar12 = (int)this->tribes[tribeID].selectionTargetUnitID; + param_5 = (int)DAT_UnitsState::instance.units[iVar12].x; + unitInstructionType = (UnitInstructionType)DAT_UnitsState::instance.units[iVar12].y; + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::predictUnitInterceptPosition, this)( + iVar12, iVar11, ¶m_5, (int*)&unitInstructionType); + MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func::pathPlanningForTribe, + DAT_PathFindingState::ptr)(tribeID, (undefined4)((int)(iVar11)), (uint)(param_5), + (uint)(unitInstructionType), id, + (dword)((int)((short)DAT_TileMapState::instance + .PathConnectionLayer[DAT_UnitsState::instance.units[iVar12].tile])), + (int)(DAT_UnitsState::instance.units[iVar12].owner)); + this->tribes[tribeID].someUnitID = _param_3_id_x_tile_buildingID_copy; + this->tribes[tribeID].someUnitUID = unitUID; + this->tribes[tribeID].someTile = DAT_UnitsState::instance.units[iVar11].tile; + iVar12 = 0; + sVar9 = this->tribes[tribeID].size; + this->tribes[tribeID].someTile2 = (int)DAT_UnitsState::instance.units[iVar11].destinationX_2Unk + + DAT_ViewportRenderState::instance + .translationMatrix[DAT_UnitsState::instance.units[iVar11].destinationY_2Unk] + .addXgetTile; + unitInstructionType = ((UnitInstructionType)0); + if (0 < sVar9) { + id = 0x12d5c6c; + do { + _unitID_0x20 = MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)(tribeID, iVar12); + iVar12 = iVar12 + 1; + if (DAT_UnitsState::instance.units[_unitID_0x20].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[_unitID_0x20].dying == 0 + && DAT_UnitsState::instance.units[_unitID_0x20].field_0x413 == 0 + && DAT_UnitsState::instance.units[_unitID_0x20].state.generic + != Map::Units::States::US_MELEE_ATTACK) { + switch (DAT_UnitsState::instance.units[_unitID_0x20].unitType) { + case Map::Units::UT_TUNNELER: + case Map::Units::UT_E_SPEAR: + case Map::Units::UT_E_PIKE: + case Map::Units::UT_E_MACE: + case Map::Units::UT_E_SWORD: + case Map::Units::UT_E_KNIGHT: + case Map::Units::UT_E_MONK: + case Map::Units::UT_LORD: + case Map::Units::UT_A_SLAVE: + case Map::Units::UT_A_ASSASSIN: + case Map::Units::UT_A_SWORDSMAN: + _tile1_528565 = *(int*)id; + if (_tile1_528565 != 0) { + _y_528565 = DAT_ViewportRenderState::instance + .tileTranslationMatrix_YComponent[_tile1_528565]; + _x_528565 = _tile1_528565 + - DAT_ViewportRenderState::instance.translationMatrix[_y_528565] + .addXgetTile; + if (*(int*)(id + 4) == 0) { + DAT_UnitsState::instance.units[_unitID_0x20].targetingType + = ((UnitInstructionType)0); + if (DAT_UnitsState::instance.units[_unitID_0x20].unitType + == Map::Units::UT_LORD) + break; + } else { + DAT_UnitsState::instance.units[_unitID_0x20].targetingType + = Map::Units::UIT_UNIT_ATTACK_UNIT; + DAT_UnitsState::instance.units[_unitID_0x20] + .targetedUnitID__OR__engineerMannedSiegeEngineRef + = _param_3_id_x_tile_buildingID_copy; + DAT_UnitsState::instance.units[_unitID_0x20] + .targetedUnitUIDUnk_OR_someAppearTileUnk_OR_buildingUID_OR_pitchDitchUID_OR_entityUID + = unitUID; + } + DAT_UnitsState::instance.units[_unitID_0x20].plannedDestinationX + = (short)_x_528565; + DAT_UnitsState::instance.units[_unitID_0x20].plannedDestinationY + = _y_528565; + DAT_UnitsState::instance.units[_unitID_0x20].targetedBuildingTile = 0; + if (DAT_UnitsState::instance.units[_unitID_0x20].state.generic + == Map::Units::States::US_MELEE_ATTACK) { + DAT_UnitsState::instance.units[_unitID_0x20].movementCooldown + = DAT_UnitsState::instance.units[_unitID_0x20].movementSpeed * -4; + } + if (DAT_UnitsState::instance.units[_unitID_0x20]._someX_2 == 0) { + DAT_UnitsState::instance.units[_unitID_0x20]._someX_2 + = DAT_UnitsState::instance.units[_unitID_0x20].destinationX_2Unk; + DAT_UnitsState::instance.units[_unitID_0x20]._someY_2 + = DAT_UnitsState::instance.units[_unitID_0x20].destinationY_2Unk; + } + DAT_UnitsState::instance.units[_unitID_0x20].state.generic + = Map::Units::States::US_MOVE_TO_DESTINATION; + if (MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::isTribeAllAssassins, this)(tribeID) + == 0) { + DAT_PathFindingState::instance.notAllAssassinsUnk = 1; + } else { + DAT_PathFindingState::instance.allAssassinsUnk = 1; + } + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::setDestinationForUnit, + DAT_UnitsState::ptr)(_unitID_0x20, _x_528565, (uint)(_y_528565), 0); + DAT_UnitsState::instance.units[_unitID_0x20].moveDelay = 0; + DAT_UnitsState::instance.units[_unitID_0x20].lookForEnemy = -0x32; + if (DAT_UnitsState::instance.units[_unitID_0x20] + .movementType_OR_targetUnitID + != iVar11) { + DAT_UnitsState::instance.units[_unitID_0x20] + .movementType_OR_targetUnitID = _param_3_id_x_tile_buildingID_copy; + psVar1 = (short*)((int)&DAT_UnitsState::instance.units[0].huntedBy + + local_8); + *psVar1 = *psVar1 + 1; + } + UVar10 = (UnitInstructionType)((int)DAT_UnitsState::instance + .units[_unitID_0x20] + .totalSizeOfPathPlan + / 2); + if ((int)UVar10 > (int)unitInstructionType) { + unitInstructionType = UVar10; + } + id = id + 0xc; + DAT_PathFindingState::instance.notAllAssassinsUnk = 0; + } + } + } + } while (iVar12 < this->tribes[tribeID].size); + } + iVar11 = unitInstructionType * 8; + if (iVar11 < 9) { + iVar11 = 8; + } + this->tribes[tribeID].field_0x2be = (short)iVar11; + return TRUE; + } + } + break; + case Map::Units::UT_E_MACE: + iVar11 = 0; + if (0 < _tribeSize) { + do { + iVar12 = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)( + tribeID, iVar11); + iVar11 = iVar11 + 1; + if (DAT_UnitsState::instance.units[iVar12].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[iVar12].dying == 0 + && (int)(short)DAT_UnitsState::instance.units[iVar12].unitType - 0x27U < 2) { + DAT_UnitsState::instance.units[iVar12].field_0x3b0 = 1; + } + } while (iVar11 < this->tribes[tribeID].size); + return TRUE; + } + break; + case Map::Units::UIT_ATTACK_LAND: + case Map::Units::UIT_THROW_COW: + unitUID = this->tribes[tribeID].owner; + this->tribes[tribeID].isRallyingUnk = 0; + _unitTribeIndex = 0; + if (0 < _tribeSize) { + do { + _unitID_0x05_0x16 = MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)(tribeID, _unitTribeIndex); + _unitTribeIndex = _unitTribeIndex + 1; + if ((DAT_UnitsState::instance.units[_unitID_0x05_0x16].logicalState == Map::Units::ULS_NORMAL) + && (DAT_UnitsState::instance.units[_unitID_0x05_0x16].dying == 0)) { + switch (DAT_UnitsState::instance.units[_unitID_0x05_0x16].unitType) { + case Map::Units::UT_E_ARCHER: + case Map::Units::UT_E_XBOW: + case Map::Units::UT_E_ARCHER_DEBUG: + case Map::Units::UT_S_MANGONEL: + case Map::Units::UT_S_BALLISTA: + case Map::Units::UT_A_ARCHER: + case Map::Units::UT_A_SLINGER: + case Map::Units::UT_A_HARCHER: + case Map::Units::UT_A_FIRETHROWER: + case Map::Units::UT_S_FBALLISTA: + if (DAT_UnitsState::instance.units[_unitID_0x05_0x16].state.generic + == (UnitState)0x69) { + DAT_UnitsState::instance.units[_unitID_0x05_0x16].state.generic + = Map::Units::States::US_MOVE_TO_DESTINATION; + } + DAT_UnitsState::instance.units[_unitID_0x05_0x16].field_0x3f8 = 0; + DAT_UnitsState::instance.units[_unitID_0x05_0x16].targetingType + = (UnitInstructionTypeShort)unitInstructionType; + LAB_00528808: + DAT_UnitsState::instance.units[_unitID_0x05_0x16].field_0x3c5 + = (byte)unitInstructionType; + sVar9 = (short)_param_4_unitUID_Y_copy; + if (unitInstructionType == Map::Units::UIT_THROW_COW + && (UVar4 = DAT_UnitsState::instance.units[_unitID_0x05_0x16].unitType, + UVar4 == Map::Units::UT_S_CATAPULT || (UVar4 == Map::Units::UT_S_TREBUCHET))) { + if (DAT_GameState::instance.playerDataArray[unitUID].availableCows <= 0) { + DAT_UnitsState::instance.units[_unitID_0x05_0x16].field_0x3c5 = 5; + } else { + DAT_UnitsState::instance.units[_unitID_0x05_0x16].targetingType + = Map::Units::UIT_THROW_COW; + DAT_UnitsState::instance.units[_unitID_0x05_0x16].shootTargetMicroX + = _param_3_id_x_tile_buildingID_copy * 8; + DAT_UnitsState::instance.units[_unitID_0x05_0x16].shootTargetMicroY = sVar9 * 8; + DAT_UnitsState::instance.units[_unitID_0x05_0x16].shootTargetZ = (ushort) + * (byte*)(DAT_ViewportRenderState::instance + .translationMatrix[_param_4_unitUID_Y_copy] + .addXgetTile + + 0x1d32c38 + iVar11); + } + } + DAT_UnitsState::instance.units[_unitID_0x05_0x16].attackAtTileX + = _param_3_id_x_tile_buildingID_copy; + DAT_UnitsState::instance.units[_unitID_0x05_0x16].attackAtTileY = sVar9; + DAT_UnitsState::instance.units[_unitID_0x05_0x16].unkAttackRelated = (short)param_5; + DAT_UnitsState::instance.units[_unitID_0x05_0x16]._someX_2 = 0; + DAT_UnitsState::instance.units[_unitID_0x05_0x16]._someY_2 = 0; + MACRO_CALL_MEMBER( + Map::Units::UnitsState_Func::makeUnitStopWalkingByClearingPathProgressState, + DAT_UnitsState::ptr)(_unitID_0x05_0x16); + DAT_UnitsState::instance.units[_unitID_0x05_0x16].shootBeforeStop = 10; + break; + case Map::Units::UT_S_CATAPULT: + case Map::Units::UT_S_TREBUCHET: + if (DAT_UnitsState::instance.units[_unitID_0x05_0x16] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + != 0) + goto LAB_00528808; + } + } + if (this->tribes[tribeID].size <= _unitTribeIndex) { + return TRUE; + } + } while (true); + } + break; + case Map::Units::UIT_THROW_OIL: + iVar11 = 0; + this->tribes[tribeID].isRallyingUnk = 0; + if (0 < _tribeSize) { + do { + uVar13 = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)( + tribeID, iVar11); + iVar11 = iVar11 + 1; + if (DAT_UnitsState::instance.units[uVar13].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[uVar13].dying == 0 + && DAT_UnitsState::instance.units[uVar13].unitType == Map::Units::UT_E_ENGINEER) { + DAT_UnitsState::instance.units[uVar13].targetingType = Map::Units::UIT_THROW_OIL; + DAT_UnitsState::instance.units[uVar13].attackAtTileX = _param_3_id_x_tile_buildingID_copy; + DAT_UnitsState::instance.units[uVar13].attackAtTileY = (short)unitUID; + DAT_UnitsState::instance.units[uVar13].plannedDestinationX + = _param_3_id_x_tile_buildingID_copy; + DAT_UnitsState::instance.units[uVar13].plannedDestinationY = (short)unitUID; + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::deselectUnit, DAT_UnitsState::ptr)(uVar13); + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::clearOrDeselectUnitFromSelection, + DAT_UnitsState::ptr)(this->tribes[tribeID].owner, uVar13, 0); + DAT_UnitsState::instance.units[uVar13]._someX_2 = 0; + DAT_UnitsState::instance.units[uVar13]._someY_2 = 0; + } + } while (iVar11 < this->tribes[tribeID].size); + return TRUE; + } + break; + case Map::Units::UIT_LIGHT_PITCH: + int _ditchTile; + this->tribes[tribeID].isRallyingUnk = 0; + _unitTribeIndex = 0; + if ((DAT_TileMapState::instance.pitchDitches[id].uid == unitUID) && (0 < _tribeSize)) { + do { + iVar12 = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)( + tribeID, _unitTribeIndex); + _unitTribeIndex = _unitTribeIndex + 1; + if ((DAT_UnitsState::instance.units[iVar12].logicalState == Map::Units::ULS_NORMAL) + && (DAT_UnitsState::instance.units[iVar12].dying == 0)) { + DAT_UnitsState::instance.units[iVar12]._someX_2 = 0; + DAT_UnitsState::instance.units[iVar12]._someY_2 = 0; + UVar4 = DAT_UnitsState::instance.units[iVar12].unitType; + if ((UVar4 == Map::Units::UT_E_ARCHER) || (UVar4 == Map::Units::UT_A_ARCHER)) { + sVar9 = DAT_TileMapState::instance.pitchDitches[iVar11].y; + DAT_UnitsState::instance.units[iVar12].shootTargetMicroX + = DAT_TileMapState::instance.pitchDitches[iVar11].x * 8 + 4; + _ditchTile = DAT_TileMapState::instance.pitchDitches[iVar11].tile; + DAT_UnitsState::instance.units[iVar12].shootTargetMicroY = sVar9 * 8 + 4; + DAT_UnitsState::instance.units[iVar12].shootTargetZ + = (ushort)DAT_TileMapState::instance.HeightLayer[_ditchTile]; + DAT_UnitsState::instance.units[iVar12].shootTargetedUnit = -1; + DAT_UnitsState::instance.units[iVar12].targetID_OR_targetBuildingID + = _param_3_id_x_tile_buildingID_copy; + DAT_UnitsState::instance.units[iVar12] + .targetedUnitUIDUnk_OR_someAppearTileUnk_OR_buildingUID_OR_pitchDitchUID_OR_entityUID + = unitUID; + DAT_UnitsState::instance.units[iVar12].field_0x3c5 = 0x22; + DAT_UnitsState::instance.units[iVar12].targetingType = Map::Units::UIT_LIGHT_PITCH; + DAT_UnitsState::instance.units[iVar12].field_0x3f8 = 0; + MACRO_CALL_MEMBER( + Map::Units::UnitsState_Func::makeUnitStopWalkingByClearingPathProgressState, + DAT_UnitsState::ptr)(iVar12); + DAT_UnitsState::instance.units[iVar12].shootBeforeStop = 10; + } + } + } while (_unitTribeIndex < this->tribes[tribeID].size); + return TRUE; + } + /* + An explicit break: this arm sat last and fell out of the switch to the + shared `return 1`, which is where the original's 0x5289a3 block jumps + (0x52a156). It is no longer last. + */ + break; + case Map::Units::UIT_ATTACK_BUILDING: + case ((UnitInstructionType)0x24): + case ((UnitInstructionType)0x26): + _unitTribeIndex = 0; + id = 0; + this->tribes[tribeID].targetBuildingID = _param_3_id_x_tile_buildingID_copy; + this->tribes[tribeID].targetBuildingUID = unitUID; + this->tribes[tribeID].isRallyingUnk = 0; + if (0 < _tribeSize) { + do { + iVar12 = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)( + tribeID, _unitTribeIndex); + _unitTribeIndex = _unitTribeIndex + 1; + if (DAT_UnitsState::instance.units[iVar12].logicalState != Map::Units::ULS_NORMAL + || DAT_UnitsState::instance.units[iVar12].dying != 0 + || DAT_UnitsState::instance.units[iVar12].field_0x413 != 0) + continue; + DAT_UnitsState::instance.units[iVar12]._someX_2 = 0; + DAT_UnitsState::instance.units[iVar12]._someY_2 = 0; + /* + Arm order from 0x52a3fc: seven dwords, 0x49-entry byte table at + 0x52a418, base 5. By address the arms are 0x528b7e (horse + archer), 0x528b83 (the other five ranged types), 0x528c76 + (the five siege types), 0x528ca2 (battering ram), 0x528ccd + (knight) and 0x528ce4 (the ten melee types). The import had the + two fall-through pairs the wrong way round: knight-into-melee + first and horse-archer-into-ranged last. + + LAB_00528c46 is inside the horse archer arm's tail, which is why + the siege arm's `goto` is backward in the original (0x528c76 to + 0x528c46). With that arm moved to the front it needs an explicit + `break` - the original ends it `jmp 0x528cfb`, the switch's exit. + */ + switch (DAT_UnitsState::instance.units[iVar12].unitType) { + case Map::Units::UT_A_HARCHER: + _ramOrHorse = _ramOrHorse + 1; + /* + The ranged types share this arm; only the horse archer counts + towards _ramOrHorse, which is why the decompiler had them + jumping in from their own label. + */ + case Map::Units::UT_E_ARCHER: + case Map::Units::UT_E_XBOW: + case Map::Units::UT_A_ARCHER: + case Map::Units::UT_A_SLINGER: + case Map::Units::UT_A_FIRETHROWER: + if (unitInstructionType == (UnitInstructionType)0x24) { + switch (DAT_BuildingsState::instance.buildings[iVar11].buildingType) { + case Map::Buildings::BT_GATEHOUSELARGE: + case Map::Buildings::BT_GATEHOUSESMALL: + case Map::Buildings::BT_WOODGATE1: + case Map::Buildings::BT_WOODGATE2: + case Map::Buildings::BT_TOWER1: + case Map::Buildings::BT_TOWER2: + case Map::Buildings::BT_TOWER3: + case Map::Buildings::BT_TOWER4: + case Map::Buildings::BT_TOWER5: + goto switchD_00528bae_caseD_2d; + } + goto switchD_00528b77_caseD_5; + } + if (unitInstructionType != (UnitInstructionType)0x26) { + switchD_00528bae_caseD_2d: + /* + attack buildings + */ + if (DAT_UnitsState::instance.units[iVar12].state.generic == (UnitState)0x69) { + DAT_UnitsState::instance.units[iVar12].state.generic + = Map::Units::States::US_MOVE_TO_DESTINATION; + } + sVar8 = (short)((int)(DAT_BuildingsState::instance.buildings[iVar11].widthOrHeight * 8) + / 2); + DAT_UnitsState::instance.units[iVar12].shootTargetMicroX + = DAT_BuildingsState::instance.buildings[iVar11].x * 8 + sVar8; + sVar9 = DAT_BuildingsState::instance.buildings[iVar11].terrainHeightUnk; + DAT_UnitsState::instance.units[iVar12].shootTargetMicroY + = DAT_BuildingsState::instance.buildings[iVar11].y * 8 + sVar8; + DAT_UnitsState::instance.units[iVar12].shootTargetZ = sVar9; + DAT_UnitsState::instance.units[iVar12].shootTargetedUnit = -1; + DAT_UnitsState::instance.units[iVar12].targetID_OR_targetBuildingID + = _param_3_id_x_tile_buildingID_copy; + DAT_UnitsState::instance.units[iVar12] + .targetedUnitUIDUnk_OR_someAppearTileUnk_OR_buildingUID_OR_pitchDitchUID_OR_entityUID + = unitUID; + LAB_00528c46: + DAT_UnitsState::instance.units[iVar12].field_0x3c5 = 9; + DAT_UnitsState::instance.units[iVar12].targetingType = Map::Units::UIT_ATTACK_BUILDING; + DAT_UnitsState::instance.units[iVar12].field_0x3f8 = 0; + MACRO_CALL_MEMBER( + Map::Units::UnitsState_Func::makeUnitStopWalkingByClearingPathProgressState, + DAT_UnitsState::ptr)(iVar12); + DAT_UnitsState::instance.units[iVar12].shootBeforeStop = 10; + } + break; + case Map::Units::UT_S_CATAPULT: + case Map::Units::UT_S_TREBUCHET: + case Map::Units::UT_S_MANGONEL: + case Map::Units::UT_S_BALLISTA: + case Map::Units::UT_S_FBALLISTA: + if (unitInstructionType == (UnitInstructionType)0x26 + || DAT_BuildingsState::instance.buildings[iVar11].buildingType + == Map::Buildings::BT_PITCHDITCH) + break; + DAT_UnitsState::instance.units[iVar12].targetID_OR_targetBuildingID + = _param_3_id_x_tile_buildingID_copy; + DAT_UnitsState::instance.units[iVar12] + .targetedUnitUIDUnk_OR_someAppearTileUnk_OR_buildingUID_OR_pitchDitchUID_OR_entityUID + = unitUID; + goto LAB_00528c46; + case Map::Units::UT_S_BATTERINGRAM: + if ((DAT_BuildingsState::instance.buildings[iVar11].buildingType + != Map::Buildings::BT_PITCHDITCH) + && (DAT_UnitsState::instance.units[iVar12] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + == 4)) { + id = id + 1; + _ramOrHorse = _ramOrHorse + 1; + } + break; + case Map::Units::UT_E_KNIGHT: + if (DAT_BuildingsState::instance.buildings[iVar11].buildingType + != Map::Buildings::BT_PITCHDITCH) { + _ramOrHorse = _ramOrHorse + 1; + } + case Map::Units::UT_TUNNELER: + case Map::Units::UT_E_SPEAR: + case Map::Units::UT_E_PIKE: + case Map::Units::UT_E_MACE: + case Map::Units::UT_E_SWORD: + case Map::Units::UT_E_MONK: + case Map::Units::UT_LORD: + case Map::Units::UT_A_SLAVE: + case Map::Units::UT_A_ASSASSIN: + case Map::Units::UT_A_SWORDSMAN: + switchD_00528b77_caseD_5: + if (DAT_BuildingsState::instance.buildings[iVar11].buildingType + != Map::Buildings::BT_PITCHDITCH) { + id = id + 1; + } + break; + } + } while (_unitTribeIndex < this->tribes[tribeID].size); + } + if ((((DAT_GameSynchronyState::instance.currentGameMode == Game::GM_SOLITARY) + || (DAT_GameState::instance.mapAndTime.skirmishStrongWalls == 0)) + || (4 < (int)(short)DAT_BuildingsState::instance.buildings[iVar11].buildingType - 0x4aU)) + /* + Again the melee counter against zero, which the decompiler rendered + as `id | x | id != 0`. + */ + && (id != 0)) { + sVar9 = this->tribes[tribeID].selectionTargetUnitID; + if (unitInstructionType == Map::Units::UIT_ATTACK_BUILDING + || unitInstructionType == (UnitInstructionType)0x26) { + iVar12 = (int)DAT_UnitsState::instance.units[sVar9].owner; + } else { + iVar12 = 0; + } + MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func::pathfindingForAttacksUnk, + DAT_PathFindingState::ptr)(tribeID, iVar11, id, + (dword)((int)((short)DAT_TileMapState::instance + .PathConnectionLayer[DAT_UnitsState::instance.units[sVar9].tile])), + iVar12); + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::sortTribePathDestinationsByCost, this)( + tribeID, _ramOrHorse); + if ((DAT_PathFindingState::instance.searchQueue.destinationsArray[0].tile2OrAHelper != 0) + && (_unitTribeIndex = 0, 0 < this->tribes[tribeID].size)) { + id = 0x12d5c70; + do { + _unitID = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)( + tribeID, _unitTribeIndex); + _unitTribeIndex = _unitTribeIndex + 1; + if (DAT_UnitsState::instance.units[_unitID].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[_unitID].dying == 0 + && DAT_UnitsState::instance.units[_unitID].field_0x413 == 0) { + UVar4 = DAT_UnitsState::instance.units[_unitID].unitType; + /* + Arm order from 0x52a490: three dwords, 0x48-entry byte + table at 0x52a49c, base 5. The ranged arm is first, at + 0x528e41, and the melee arm second at 0x528e4c - eleven + bytes later, which is the whole of the ranged arm: it is + just the 0x24 test and a jump into the melee body. With + the import's order that `goto` was a backward jump and + the ranged arm sat past ninety lines of melee handling. + */ + switch (UVar4) { + case Map::Units::UT_E_ARCHER: + case Map::Units::UT_E_XBOW: + case Map::Units::UT_A_ARCHER: + case Map::Units::UT_A_SLINGER: + case Map::Units::UT_A_HARCHER: + case Map::Units::UT_A_FIRETHROWER: + if (unitInstructionType == (UnitInstructionType)0x24) + goto switchD_00528e3a_caseD_5; + break; + case Map::Units::UT_TUNNELER: + case Map::Units::UT_E_SPEAR: + case Map::Units::UT_E_PIKE: + case Map::Units::UT_E_MACE: + case Map::Units::UT_E_SWORD: + case Map::Units::UT_E_KNIGHT: + case Map::Units::UT_E_MONK: + case Map::Units::UT_LORD: + case Map::Units::UT_S_BATTERINGRAM: + case Map::Units::UT_A_SLAVE: + case Map::Units::UT_A_ASSASSIN: + case Map::Units::UT_A_SWORDSMAN: + switchD_00528e3a_caseD_5: + if (UVar4 != Map::Units::UT_S_BATTERINGRAM) + goto LAB_00528f32; + if (DAT_UnitsState::instance.units[_unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + != 4) + break; + if (bVar5) { + LAB_00528f32: + iVar12 = *(int*)(id + -4); + if (iVar12 == 0) + break; + sVar9 = DAT_ViewportRenderState::instance + .tileTranslationMatrix_YComponent[iVar12]; + unitUID = iVar12 + - DAT_ViewportRenderState::instance.translationMatrix[sVar9].addXgetTile; + DAT_UnitsState::instance.units[_unitID].targetingType + = ((UnitInstructionType)0); + DAT_UnitsState::instance.units[_unitID].plannedDestinationX = (short)unitUID; + DAT_UnitsState::instance.units[_unitID].plannedDestinationY = sVar9; + if (DAT_UnitsState::instance.units[_unitID].state.generic + == Map::Units::States::US_MELEE_ATTACK) { + DAT_UnitsState::instance.units[_unitID].movementCooldown + = DAT_UnitsState::instance.units[_unitID].movementSpeed * -4; + } + DAT_UnitsState::instance.units[_unitID].state.generic + = Map::Units::States::US_MOVE_TO_DESTINATION; + BVar16 = MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::isTribeAllAssassins, this)(tribeID); + if (!BVar16) { + DAT_PathFindingState::instance.notAllAssassinsUnk = 1; + } else { + DAT_PathFindingState::instance.allAssassinsUnk = 1; + } + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::setDestinationForUnit, + DAT_UnitsState::ptr)(_unitID, (uint)(unitUID), (uint)(sVar9), 0); + DAT_UnitsState::instance.units[_unitID].movementType_OR_targetUnitID = 0; + DAT_PathFindingState::instance.notAllAssassinsUnk = 0; + uVar13 = *(uint*)id; + DAT_UnitsState::instance.units[_unitID].targetedBuildingTile = uVar13; + sVar9 = DAT_ViewportRenderState::instance + .tileTranslationMatrix_YComponent[uVar13]; + DAT_UnitsState::instance.units[_unitID].attackAtTileY = sVar9; + sVar9 = *(short*)id + - (short)DAT_ViewportRenderState::instance.translationMatrix[sVar9] + .addXgetTile; + id = id + 0xc; + } else { + iVar12 = MACRO_CALL_MEMBER( + Map::Navigation::PathFindingState_Func::findBuildingAccessPoint, + DAT_PathFindingState::ptr)(_unitID, iVar11, ¶m_5); + bVar5 = TRUE; + if (iVar12 == 0) + goto LAB_00528f32; + sVar9 = DAT_ViewportRenderState::instance + .tileTranslationMatrix_YComponent[iVar12]; + unitUID = iVar12 + - DAT_ViewportRenderState::instance.translationMatrix[sVar9].addXgetTile; + BVar16 = MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::setDestinationForUnit, + DAT_UnitsState::ptr)(_unitID, (uint)(unitUID), (uint)(sVar9), 0); + if (!BVar16) + goto LAB_00528f32; + DAT_UnitsState::instance.units[_unitID].targetingType + = ((UnitInstructionType)0); + DAT_UnitsState::instance.units[_unitID].plannedDestinationX = (short)unitUID; + DAT_UnitsState::instance.units[_unitID].plannedDestinationY = sVar9; + if (DAT_UnitsState::instance.units[_unitID].state.generic + == Map::Units::States::US_MELEE_ATTACK) { + DAT_UnitsState::instance.units[_unitID].movementCooldown + = DAT_UnitsState::instance.units[_unitID].movementSpeed * -4; + } + DAT_UnitsState::instance.units[_unitID].state.generic + = Map::Units::States::US_MOVE_TO_DESTINATION; + DAT_UnitsState::instance.units[_unitID].movementType_OR_targetUnitID = 0; + DAT_PathFindingState::instance.notAllAssassinsUnk = 0; + sVar9 = DAT_ViewportRenderState::instance + .tileTranslationMatrix_YComponent[param_5]; + DAT_UnitsState::instance.units[_unitID].targetedBuildingTile = param_5; + DAT_UnitsState::instance.units[_unitID].attackAtTileY = sVar9; + sVar9 = (short)param_5 + - (short)DAT_ViewportRenderState::instance.translationMatrix[sVar9] + .addXgetTile; + } + DAT_UnitsState::instance.units[_unitID].attackAtTileX = sVar9; + break; + } + } + if (this->tribes[tribeID].size <= _unitTribeIndex) { + return TRUE; + } + } while (true); + } + } + break; + case Map::Units::UIT_ATTACK_WALL: + case ((UnitInstructionType)0x23): + case ((UnitInstructionType)0x25): + int _unitID_attackWall; + _unitTribeIndex = 0; + id = 0; + this->tribes[tribeID].isRallyingUnk = 0; + if (0 < _tribeSize) { + do { + uVar13 = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)( + tribeID, _unitTribeIndex); + _unitTribeIndex = _unitTribeIndex + 1; + if (DAT_UnitsState::instance.units[uVar13].logicalState != Map::Units::ULS_NORMAL + || DAT_UnitsState::instance.units[uVar13].dying != 0 + || DAT_UnitsState::instance.units[uVar13].field_0x413 != 0) + continue; + DAT_UnitsState::instance.units[uVar13]._someX_2 = 0; + DAT_UnitsState::instance.units[uVar13]._someY_2 = 0; + /* + Arm order from 0x52a4e4: eight dwords, 0x49-entry byte table at + 0x52a504, base 5. By address: 0x5290ce (horse archer), 0x5290d3 + (the other six ranged types), 0x5290e3 (the five siege types), + 0x52914f (tower), 0x5291d6 (battering ram), 0x5291e5 (knight), + 0x5291ea (the nine melee types). + + Ram, knight and melee are a three-way fall-through - the comment + below says so - and the original's spacing confirms it: 0x5291d6 + to 0x5291e5 is the ram body, 0x5291e5 to 0x5291ea is the knight's + single increment. Horse archer falls into ranged the same way. So + the only thing wrong was which end those two chains sat at: the + import had ram-knight-melee first and horse-archer-ranged last. + */ + switch (DAT_UnitsState::instance.units[uVar13].unitType) { + case Map::Units::UT_A_HARCHER: + _ramOrHorse = _ramOrHorse + 1; + /* + The ranged types share this arm; only the horse archer counts + towards _ramOrHorse. + */ + case Map::Units::UT_E_ARCHER: + case Map::Units::UT_E_XBOW: + case Map::Units::UT_A_ARCHER: + case Map::Units::UT_A_SLINGER: + case Map::Units::UT_A_ASSASSIN: + case Map::Units::UT_A_FIRETHROWER: + if (unitInstructionType == (UnitInstructionType)0x23) { + id = id + 1; + } + break; + case Map::Units::UT_S_CATAPULT: + case Map::Units::UT_S_TREBUCHET: + case Map::Units::UT_S_MANGONEL: + case Map::Units::UT_S_BALLISTA: + case Map::Units::UT_S_FBALLISTA: + if (unitInstructionType != (UnitInstructionType)0x25) { + sVar9 = DAT_ViewportRenderState::instance.tileTranslationMatrix_YComponent[iVar11]; + DAT_UnitsState::instance.units[uVar13].targetID_OR_targetBuildingID + = _param_3_id_x_tile_buildingID_copy; + DAT_UnitsState::instance.units[uVar13] + .targetedUnitUIDUnk_OR_someAppearTileUnk_OR_buildingUID_OR_pitchDitchUID_OR_entityUID + = unitUID; + DAT_UnitsState::instance.units[uVar13].attackAtTileY = sVar9; + DAT_UnitsState::instance.units[uVar13].attackAtTileX + = _param_3_id_x_tile_buildingID_copy + - (short)DAT_ViewportRenderState::instance.translationMatrix[sVar9].addXgetTile; + DAT_UnitsState::instance.units[uVar13].field_0x3c5 = 0x17; + DAT_UnitsState::instance.units[uVar13].targetingType = Map::Units::UIT_ATTACK_WALL; + MACRO_CALL_MEMBER( + Map::Units::UnitsState_Func::makeUnitStopWalkingByClearingPathProgressState, + DAT_UnitsState::ptr)(uVar13); + DAT_UnitsState::instance.units[uVar13].shootBeforeStop = 10; + } + break; + case Map::Units::UT_S_TOWER: + uVar19 = MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::findFreeTileNearby, + DAT_UnitsState::ptr)(uVar13, (uint)(iVar11)); + if (uVar19 != 0) { + MACRO_CALL_MEMBER( + Map::Units::UnitsState_Func::setDestinationForUnit, DAT_UnitsState::ptr)(uVar13, + (uint)(uVar19 + - DAT_ViewportRenderState::instance + .translationMatrix[DAT_ViewportRenderState::instance + .tileTranslationMatrix_YComponent[uVar19]] + .addXgetTile), + (uint)(DAT_ViewportRenderState::instance.tileTranslationMatrix_YComponent[uVar19]), + 0); + sVar9 = DAT_ViewportRenderState::instance.tileTranslationMatrix_YComponent[iVar11]; + DAT_UnitsState::instance.units[uVar13].targetingType = Map::Units::UIT_ATTACK_WALL; + DAT_UnitsState::instance.units[uVar13].state.generic + = Map::Units::States::US_MOVE_TO_DESTINATION; + DAT_UnitsState::instance.units[uVar13].targetID_OR_targetBuildingID + = _param_3_id_x_tile_buildingID_copy; + DAT_UnitsState::instance.units[uVar13].targetedBuildingTile = iVar11; + DAT_UnitsState::instance.units[uVar13].digTileTarget = uVar19; + DAT_UnitsState::instance.units[uVar13].attackAtTileY = sVar9; + DAT_UnitsState::instance.units[uVar13].attackAtTileX + = _param_3_id_x_tile_buildingID_copy + - (short)DAT_ViewportRenderState::instance.translationMatrix[sVar9].addXgetTile; + } + break; + case Map::Units::UT_S_BATTERINGRAM: + if (DAT_UnitsState::instance.units[uVar13] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + != 4) { + break; + } + local_8 = local_8 + 1; + /* + a crewed ram counts as a horseman too, which is the goto the + decompiler printed back into this arm + */ + case Map::Units::UT_E_KNIGHT: + _ramOrHorse = _ramOrHorse + 1; + case Map::Units::UT_TUNNELER: + case Map::Units::UT_E_SPEAR: + case Map::Units::UT_E_PIKE: + case Map::Units::UT_E_MACE: + case Map::Units::UT_E_SWORD: + case Map::Units::UT_E_MONK: + case Map::Units::UT_LORD: + case Map::Units::UT_A_SLAVE: + case Map::Units::UT_A_SWORDSMAN: + id = id + 1; + break; + } + } while (_unitTribeIndex < this->tribes[tribeID].size); + } + if ((DAT_GameSynchronyState::instance.currentGameMode != Game::GM_SOLITARY) + && (DAT_GameState::instance.mapAndTime.skirmishStrongWalls != 0)) { + id = local_8; + } + /* + The melee counter against zero again, as at the two sites above. + */ + if (id != 0) { + sVar9 = this->tribes[tribeID].selectionTargetUnitID; + if (unitInstructionType == Map::Units::UIT_ATTACK_WALL + || unitInstructionType == (UnitInstructionType)0x25) { + sVar8 = DAT_UnitsState::instance.units[sVar9].facingDirection; + iVar12 = (int)DAT_UnitsState::instance.units[sVar9].owner; + } else { + sVar8 = DAT_UnitsState::instance.units[sVar9].facingDirection; + iVar12 = 0; + } + MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func:: + findFreeSpaceNextToEnemyDefensiveStructureInSameAreaWithinDistance, + DAT_PathFindingState::ptr)(iVar11, id, + (int)((short)DAT_TileMapState::instance + .PathConnectionLayer[DAT_UnitsState::instance.units[sVar9].tile]), + iVar12, 0, (int)(sVar8)); + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::sortTribePathDestinationsByCost, this)( + tribeID, _ramOrHorse); + if ((DAT_PathFindingState::instance.searchQueue.destinationsArray[0].tile2OrAHelper != 0) + && (iVar12 = 0, 0 < this->tribes[tribeID].size)) { + id = 0x12d5c70; + do { + _unitID_attackWall = MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)(tribeID, iVar12); + iVar12 = iVar12 + 1; + if (DAT_UnitsState::instance.units[_unitID_attackWall].logicalState + == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[_unitID_attackWall].dying == 0 + && DAT_UnitsState::instance.units[_unitID_attackWall].field_0x413 == 0) { + UVar4 = DAT_UnitsState::instance.units[_unitID_attackWall].unitType; + switch (UVar4) { + case Map::Units::UT_E_ARCHER: + case Map::Units::UT_E_XBOW: + case Map::Units::UT_A_ARCHER: + case Map::Units::UT_A_SLINGER: + case Map::Units::UT_A_ASSASSIN: + case Map::Units::UT_A_HARCHER: + case Map::Units::UT_A_FIRETHROWER: + if (unitInstructionType != (UnitInstructionType)0x23) { + break; + } + /* + UT_TUNNELER belongs to this arm, not the ranged one + above. The byte table at 0x52a560 maps index 0 - unit + type 5 - to arm 0x52933c, the melee arm, while the + ranged types 0x16, 0x17, 0x46, 0x48, 0x49, 0x4a and 0x4c + map to 0x529331. With the label on the ranged arm a + tunneler met the `!= 0x23` test and broke out instead of + running this body. + + The two arms are adjacent and fall through in the + original as well - 0x529331 to 0x52933c is eleven bytes, + the `cmp` and the `jnz` - so only the label moved. + */ + case Map::Units::UT_TUNNELER: + case Map::Units::UT_E_SPEAR: + case Map::Units::UT_E_PIKE: + case Map::Units::UT_E_MACE: + case Map::Units::UT_E_SWORD: + case Map::Units::UT_E_KNIGHT: + case Map::Units::UT_E_MONK: + case Map::Units::UT_LORD: + case Map::Units::UT_A_SLAVE: + case Map::Units::UT_A_SWORDSMAN: + if (DAT_GameSynchronyState::instance.currentGameMode != Game::GM_SOLITARY + && DAT_GameState::instance.mapAndTime.skirmishStrongWalls != 0) { + break; + } + /* + The three groups chain: a ranged unit under + instruction 0x23 falls into the melee test, and a + melee unit that passes it falls into the ram arm. + That is the web of gotos the decompiler printed. + */ + case Map::Units::UT_S_BATTERINGRAM: + if (UVar4 == Map::Units::UT_S_BATTERINGRAM) { + if (DAT_UnitsState::instance.units[_unitID_attackWall] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + != 4) + break; + if (!bVar5) { + bVar5 = TRUE; + iVar15 + = MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func:: + findUnitPreferredOrientationBasedConnectedTile, + DAT_PathFindingState::ptr)(_unitID_attackWall, iVar11); + if (iVar15 != 0) { + sVar9 = DAT_ViewportRenderState::instance + .tileTranslationMatrix_YComponent[iVar15]; + unitUID = iVar15 + - DAT_ViewportRenderState::instance.translationMatrix[sVar9] + .addXgetTile; + BVar16 = MACRO_CALL_MEMBER( + Map::Units::UnitsState_Func::setDestinationForUnit, + DAT_UnitsState::ptr)( + _unitID_attackWall, (uint)(unitUID), (uint)(sVar9), 0); + if (BVar16) { + DAT_UnitsState::instance.units[_unitID_attackWall].targetingType + = ((UnitInstructionType)0); + DAT_UnitsState::instance.units[_unitID_attackWall] + .plannedDestinationX = (short)unitUID; + DAT_UnitsState::instance.units[_unitID_attackWall] + .plannedDestinationY = sVar9; + if (DAT_UnitsState::instance.units[_unitID_attackWall].state.generic + == Map::Units::States::US_MELEE_ATTACK) { + DAT_UnitsState::instance.units[_unitID_attackWall] + .movementCooldown + = DAT_UnitsState::instance.units[_unitID_attackWall] + .movementSpeed + * -4; + } + DAT_UnitsState::instance.units[_unitID_attackWall].state.generic + = Map::Units::States::US_MOVE_TO_DESTINATION; + DAT_UnitsState::instance.units[_unitID_attackWall] + .movementType_OR_targetUnitID = 0; + DAT_PathFindingState::instance.notAllAssassinsUnk = 0; + sVar9 = DAT_ViewportRenderState::instance + .tileTranslationMatrix_YComponent[iVar11]; + DAT_UnitsState::instance.units[_unitID_attackWall] + .targetedBuildingTile = iVar11; + DAT_UnitsState::instance.units[_unitID_attackWall].attackAtTileY + = sVar9; + DAT_UnitsState::instance.units[_unitID_attackWall].attackAtTileX + = _param_3_id_x_tile_buildingID_copy + - (short)DAT_ViewportRenderState::instance + .translationMatrix[sVar9] + .addXgetTile; + break; + } + } + } + } + iVar15 = *(int*)(id + -4); + if (iVar15 != 0) { + sVar9 = DAT_ViewportRenderState::instance + .tileTranslationMatrix_YComponent[iVar15]; + uVar13 = iVar15 + - DAT_ViewportRenderState::instance.translationMatrix[sVar9].addXgetTile; + DAT_UnitsState::instance.units[_unitID_attackWall].targetingType + = ((UnitInstructionType)0); + DAT_UnitsState::instance.units[_unitID_attackWall].plannedDestinationX + = (short)uVar13; + DAT_UnitsState::instance.units[_unitID_attackWall].plannedDestinationY = sVar9; + DAT_PathFindingState::instance.notAllAssassinsUnk = 1; + if (DAT_UnitsState::instance.units[_unitID_attackWall].state.generic + == Map::Units::States::US_MELEE_ATTACK) { + DAT_UnitsState::instance.units[_unitID_attackWall].movementCooldown + = DAT_UnitsState::instance.units[_unitID_attackWall].movementSpeed * -4; + } + DAT_UnitsState::instance.units[_unitID_attackWall].state.generic + = Map::Units::States::US_MOVE_TO_DESTINATION; + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::setDestinationForUnit, + DAT_UnitsState::ptr)(_unitID_attackWall, uVar13, (uint)(sVar9), 0); + DAT_PathFindingState::instance.notAllAssassinsUnk = 0; + uVar13 = *(uint*)id; + sVar9 = *(short*)id; + DAT_UnitsState::instance.units[_unitID_attackWall].movementType_OR_targetUnitID + = 0; + DAT_UnitsState::instance.units[_unitID_attackWall].targetedBuildingTile + = uVar13; + sVar8 = DAT_ViewportRenderState::instance + .tileTranslationMatrix_YComponent[uVar13]; + DAT_UnitsState::instance.units[_unitID_attackWall].attackAtTileY = sVar8; + id = id + 0xc; + DAT_UnitsState::instance.units[_unitID_attackWall].attackAtTileX = sVar9 + - (short)DAT_ViewportRenderState::instance.translationMatrix[sVar8] + .addXgetTile; + } + } + } + if (this->tribes[tribeID].size <= iVar12) { + return TRUE; + } + } while (true); + } + } + break; + case Map::Units::UIT_SET_LADDER: + int _unitID_setLadder; + iVar12 = 0; + id = 0; + this->tribes[tribeID].isRallyingUnk = 0; + if (0 < _tribeSize) { + do { + _unitID_setLadder = MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)(tribeID, iVar12); + iVar12 = iVar12 + 1; + if (DAT_UnitsState::instance.units[_unitID_setLadder].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[_unitID_setLadder].dying == 0 + && DAT_UnitsState::instance.units[_unitID_setLadder].unitType == Map::Units::UT_E_LADDER) { + id = id + 1; + DAT_UnitsState::instance.units[_unitID_setLadder]._someX_2 = 0; + DAT_UnitsState::instance.units[_unitID_setLadder]._someY_2 = 0; + } + } while (iVar12 < this->tribes[tribeID].size); + /* + The melee counter against zero, as at the first site. + */ + if (id != 0) { + sVar9 = this->tribes[tribeID].selectionTargetUnitID; + MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func:: + populateDestinationsArrayWithWallTileAndFreeTilePairInSameArea, + DAT_PathFindingState::ptr)(iVar11, id, + (dword)((int)((short)DAT_TileMapState::instance + .PathConnectionLayer[DAT_UnitsState::instance.units[sVar9].tile])), + (int)(DAT_UnitsState::instance.units[sVar9].owner)); + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::sortTribePathDestinationsByCost, this)( + tribeID, 0); + if ((DAT_PathFindingState::instance.searchQueue.destinationsArray[0].tile2OrAHelper != 0) + && (iVar11 = 0, 0 < this->tribes[tribeID].size)) { + piVar18 = &DAT_PathFindingState::instance.searchQueue.destinationsArray[0].tile2OrAHelper; + do { + _laddermanID = MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)(tribeID, iVar11); + iVar11 = iVar11 + 1; + if (DAT_UnitsState::instance.units[_laddermanID].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[_laddermanID].dying == 0 + && DAT_UnitsState::instance.units[_laddermanID].unitType == Map::Units::UT_E_LADDER + && (_freeTile = ((PathHelper12*)(piVar18 + -1))->tile1, _freeTile != 0)) { + /* + set ladder men destination to free id next to defensive structure + */ + _freeTileY + = DAT_ViewportRenderState::instance.tileTranslationMatrix_YComponent[_freeTile]; + _freeTileX = _freeTile + - DAT_ViewportRenderState::instance.translationMatrix[_freeTileY].addXgetTile; + DAT_UnitsState::instance.units[_laddermanID].targetingType + = ((UnitInstructionType)0); + DAT_UnitsState::instance.units[_laddermanID].plannedDestinationX + = (short)_freeTileX; + DAT_UnitsState::instance.units[_laddermanID].plannedDestinationY = _freeTileY; + DAT_PathFindingState::instance.notAllAssassinsUnk = 1; + if (DAT_UnitsState::instance.units[_laddermanID].state.generic + == Map::Units::States::US_MELEE_ATTACK) { + DAT_UnitsState::instance.units[_laddermanID].movementCooldown + = DAT_UnitsState::instance.units[_laddermanID].movementSpeed * -4; + } + DAT_UnitsState::instance.units[_laddermanID].state.generic + = (ushort)(*piVar18 != 0) * 2 + Map::Units::States::US_MOVE_TO_DESTINATION; + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::setDestinationForUnit, + DAT_UnitsState::ptr)(_laddermanID, _freeTileX, (uint)(_freeTileY), 0); + DAT_PathFindingState::instance.notAllAssassinsUnk = 0; + /* + One local: the decompiler read the same `*piVar18` + into two. + */ + _defensiveTile1 = *piVar18; + /* + set ladder man ladder target id + */ + DAT_UnitsState::instance.units[_laddermanID].targetedBuildingTile = _defensiveTile1; + sVar9 = DAT_ViewportRenderState::instance + .tileTranslationMatrix_YComponent[_defensiveTile1]; + DAT_UnitsState::instance.units[_laddermanID].attackAtTileY = sVar9; + piVar18 = piVar18 + 3; + DAT_UnitsState::instance.units[_laddermanID].attackAtTileX = (short)_defensiveTile1 + - (short)DAT_ViewportRenderState::instance.translationMatrix[sVar9].addXgetTile; + } + } while (iVar11 < this->tribes[tribeID].size); + return TRUE; + } + } + } + break; + case Map::Units::UIT_FILL_MOAT: + _targetArea = DAT_TileMapState::instance.PathConnectionLayer + [DAT_UnitsState::instance.units[this->tribes[tribeID].selectionTargetUnitID].tile]; + this->tribes[tribeID].isRallyingUnk = 0; + if ((int)(short)_targetArea != 0) { + iVar11 = MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func::canNavigateFunctionReturnsArea, + DAT_PathFindingState::ptr)( + this->tribes[tribeID].owner, (dword)((int)((short)_targetArea)), (uint)(id), (uint)(unitUID)); + if (iVar11 == 0) { + return TRUE; + } + unitUID = DAT_PathFindingState::instance.climbY; + uVar13 = DAT_PathFindingState::instance.climbX; + } + case Map::Units::UIT_DIG_MOAT: + int _unitID_digMoat; + iVar11 = unitUID; + iVar12 = 0; + this->tribes[tribeID].isRallyingUnk = 0; + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::giveUnitSelectionMoveInstructionNoMatchedSpeed, this)( + tribeID, uVar13, (uint)(unitUID), 0, 1); + if (0 < this->tribes[tribeID].size) { + do { + _unitID_digMoat = MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)(tribeID, iVar12); + iVar12 = iVar12 + 1; + if ((DAT_UnitsState::instance.units[_unitID_digMoat].logicalState == Map::Units::ULS_NORMAL) + && (DAT_UnitsState::instance.units[_unitID_digMoat].dying == 0)) { + switch (DAT_UnitsState::instance.units[_unitID_digMoat].unitType) { + case Map::Units::UT_E_ARCHER: + case Map::Units::UT_E_SPEAR: + case Map::Units::UT_E_PIKE: + case Map::Units::UT_E_MACE: + case Map::Units::UT_E_ENGINEER: + case Map::Units::UT_A_SLAVE: + if (DAT_UnitsState::instance.units[_unitID_digMoat].state.generic == (UnitState)0x69) { + DAT_UnitsState::instance.units[_unitID_digMoat].state.generic + = Map::Units::States::US_MOVE_TO_DESTINATION; + } + DAT_UnitsState::instance.units[_unitID_digMoat].targetingType + = (undefined2)unitInstructionType; + DAT_UnitsState::instance.units[_unitID_digMoat].attackAtTileX = (short)uVar13; + DAT_UnitsState::instance.units[_unitID_digMoat].attackAtTileY = (short)iVar11; + DAT_UnitsState::instance.units[_unitID_digMoat].targetX + = _param_3_id_x_tile_buildingID_copy; + DAT_UnitsState::instance.units[_unitID_digMoat].targetY + = (UnitStateShort)_param_4_unitUID_Y_copy; + DAT_UnitsState::instance.units[_unitID_digMoat].targetedBuildingTile = 0; + DAT_UnitsState::instance.units[_unitID_digMoat].movementType_OR_targetUnitID = 0; + DAT_UnitsState::instance.units[_unitID_digMoat]._someX_2 = 0; + DAT_UnitsState::instance.units[_unitID_digMoat]._someY_2 = 0; + } + } + } while (iVar12 < this->tribes[tribeID].size); + return TRUE; + } + break; + case Map::Units::UIT_CONSTRUCT_SIEGE_EQUIPMENTOIL_DUTYENGINEERRELATED: + int _buildingUID; + this->tribes[tribeID].isRallyingUnk = 0; + _y = DAT_BuildingsState::instance.buildings[id].buildingEntryY; + _x = DAT_BuildingsState::instance.buildings[id].buildingEntryX; + _unitTribeIndex = 0; + BVar16 = MACRO_CALL_MEMBER( + Rendering::ViewportRenderState_Func::xyAreValid, DAT_ViewportRenderState::ptr)((int)_x, (uint)(_y)); + if (!BVar16) { + return FALSE; + } + param_5 = (int)(short)DAT_TileMapState::instance + .PathConnectionLayer[DAT_ViewportRenderState::instance.translationMatrix[_y].addXgetTile + + (int)_x]; + unitUID = MACRO_CALL_MEMBER( + Map::Buildings::BuildingsState_Func::getRequiredEngineersCount, DAT_BuildingsState::ptr)(iVar11); + /* + `unitUID | unitUID != 0` is only ever truthy when unitUID is non-zero, + so this is that test written three ways at once - the same decompiler + artifact as the counter below, but harmless here. + */ + if ((unitUID != 0 + || (DAT_BuildingsState::instance.buildings[iVar11].buildingType + == Map::Buildings::BT_OILSMELTER)) + && 0 < this->tribes[tribeID].size) { + do { + uVar13 = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)( + tribeID, _unitTribeIndex); + iVar12 = _unitTribeIndex + 1; + if (DAT_UnitsState::instance.units[uVar13].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[uVar13].dying == 0 + && DAT_UnitsState::instance.units[uVar13].unitType == Map::Units::UT_E_ENGINEER + && (UVar3 = DAT_UnitsState::instance.units[uVar13].state.generic, + UVar3 != (Map::Units::States::US_STAND_UPUnk | Map::Units::States::US_IDLEUnk) + && (UVar3 != ((UnitState)10))) + && UVar3 != Map::Units::States::US_SIT_DOWNUnk + && UVar3 != (Map::Units::States::US_STAND_UPUnk | Map::Units::States::US_RELOAD_WEAPONUnk) + && UVar3 != (Map::Units::States::US_STAND_UPUnk | Map::Units::States::US_AIM_WEAPONUnk) + && UVar3 != (Map::Units::States::US_STAND_UPUnk | Map::Units::States::US_FIRE_WEAPONUnk) + && UVar3 != (Map::Units::States::US_STAND_UPUnk | Map::Units::States::US_LOOK_AROUNDUnk)) { + DAT_UnitsState::instance.units[uVar13]._someX_2 = 0; + DAT_UnitsState::instance.units[uVar13]._someY_2 = 0; + cVar7 = MACRO_CALL_MEMBER( + Map::Buildings::BuildingsState_Func::resolveBuildingEntryAccessibility, + DAT_BuildingsState::ptr)(iVar11, 1, (int)(DAT_UnitsState::instance.units[uVar13].x), + (int)(DAT_UnitsState::instance.units[uVar13].y)); + /* + The `extraout_var` reassembly of the upper three bytes stays, + although it is a decompiler artifact: 0x421be0 really returns + 0, 1 or 2 in the whole of EAX (0x421d4f sets ECX to 1 or 2), + and the original's test is `test eax, eax`. Our header + declares the callee `char`, so a plain `cVar7 != 0` tests only + AL and costs 1.7 points (27.9% -> 26.2%). Fixing it properly + means giving BuildingsState::resolveBuildingEntryAccessibility + an `int` return, which is outside this namespace. + */ + if (((((uint)(extraout_var) & 0xffffff) << 8) | (uint)(byte)(cVar7)) != 0 + && (_buildingUID = MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func:: + calculateCanPlayerUnitsNavigateToAreaFromArea, + DAT_PathFindingState::ptr)((int)DAT_UnitsState::instance.units[uVar13].owner, + (dword)((int)(param_5)), + (dword)((int)((short)DAT_TileMapState::instance + .PathConnectionLayer[DAT_UnitsState::instance.units[uVar13].tile])), + 0), + _buildingUID != 0)) { + sVar9 = DAT_BuildingsState::instance.buildings[iVar11].buildingEntryY; + sVar8 = DAT_BuildingsState::instance.buildings[iVar11].buildingEntryX; + _buildingUID = DAT_BuildingsState::instance.buildings[iVar11].uid; + DAT_UnitsState::instance.units[uVar13].targetID_OR_targetBuildingID + = _param_3_id_x_tile_buildingID_copy; + DAT_UnitsState::instance.units[uVar13].targetUID = _buildingUID; + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::setDestinationForUnit, + DAT_UnitsState::ptr)(uVar13, (uint)(sVar8), (uint)(sVar9), 0); + if (DAT_BuildingsState::instance.buildings[iVar11].buildingType + == Map::Buildings::BT_OILSMELTER) { + DAT_UnitsState::instance.units[uVar13].state.generic + = Map::Units::States::US_STAND_UPUnk | Map::Units::States::US_IDLEUnk; + DAT_UnitsState::instance.units[uVar13].workplaceBuildingID_1 + = _param_3_id_x_tile_buildingID_copy; + } else { + DAT_UnitsState::instance.units[uVar13].state.generic + = Map::Units::States::US_STAND_UPUnk; + DAT_UnitsState::instance.units[uVar13].resourceToDeposit = 0; + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::deselectUnit, DAT_UnitsState::ptr)( + uVar13); + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::clearOrDeselectUnitFromSelection, + DAT_UnitsState::ptr)(this->tribes[tribeID].owner, uVar13, 0); + unitUID = unitUID + -1; + iVar12 = _unitTribeIndex; + if (unitUID == 0) { + return TRUE; + } + } + } + } + _unitTribeIndex = iVar12; + } while (_unitTribeIndex < this->tribes[tribeID].size); + return TRUE; + } + break; + case Map::Units::UIT_MAN_SIEGE_EQUIPMENT: + int _siegeCrewIndex; + /* + manning siege equipment? + */ + this->tribes[tribeID].isRallyingUnk = 0; + if (DAT_UnitsState::instance.units[id].uid == unitUID + && (unitUID = MACRO_CALL_MEMBER( + Map::Units::UnitsState_Func::getRemainingRequiredEngineers, DAT_UnitsState::ptr)(id), + unitUID != 0) + && (iVar12 = 0, 0 < this->tribes[tribeID].size)) { + do { + uVar13 = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)( + tribeID, iVar12); + _siegeCrewIndex = iVar12 + 1; + if (DAT_UnitsState::instance.units[uVar13].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[uVar13].dying == 0 + && DAT_UnitsState::instance.units[uVar13].unitType == Map::Units::UT_E_ENGINEER) { + DAT_UnitsState::instance.units[iVar11]._someX_2 = 0; + DAT_UnitsState::instance.units[iVar11]._someY_2 = 0; + param_5 = (int)(short)DAT_TileMapState::instance + .PathConnectionLayer[DAT_UnitsState::instance.units[uVar13].tile]; + unitInstructionType = ((UnitInstructionType)0); + do { + _siegeCrewIndex = (int)DAT_UnitsState::instance.units[iVar11] + .digTileY__OR__countLifeCycleEngineersSentToManSiegeEngine; + x = (int) + DAT_AttackInfoDefinedData::instance.SiegeCrewPositionOffsets[_siegeCrewIndex][0] + + (int)DAT_UnitsState::instance.units[iVar11].x; + y = (int) + DAT_AttackInfoDefinedData::instance.SiegeCrewPositionOffsets[_siegeCrewIndex][1] + + (int)DAT_UnitsState::instance.units[iVar11].y; + uVar19 = (_siegeCrewIndex + 1) % 16; + DAT_UnitsState::instance.units[iVar11] + .digTileY__OR__countLifeCycleEngineersSentToManSiegeEngine = (short)uVar19; + BVar16 = MACRO_CALL_MEMBER(Rendering::ViewportRenderState_Func::xyAreValid, + DAT_ViewportRenderState::ptr)(x, y); + if (BVar16) { + _siegeCrewIndex + = DAT_ViewportRenderState::instance.translationMatrix[y].addXgetTile + x; + _param_4_unitUID_Y_copy + = (dword)(short)DAT_TileMapState::instance.PathConnectionLayer[_siegeCrewIndex]; + uVar19 = MACRO_CALL_MEMBER(Map::TileMapState_Func::getTotalHeightAtTile, + DAT_TileMapState::ptr)(_siegeCrewIndex); + uVar19 = ((int)DAT_UnitsState::instance.units[iVar11].buildingHeight + + (int)DAT_UnitsState::instance.units[iVar11].terrainOrClimbHeight) + - uVar19; + uVar17 = (int)uVar19 >> 0x1f; + if ((int)((uVar19 ^ uVar17) - uVar17) < 0x11 + && (_siegeCrewIndex + = MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func:: + calculateCanPlayerUnitsNavigateToAreaFromArea, + DAT_PathFindingState::ptr)( + (int)DAT_UnitsState::instance.units[iVar11].owner, + (dword)((int)(param_5)), (dword)((int)(_param_4_unitUID_Y_copy)), 0), + _siegeCrewIndex != 0)) + break; + } + unitInstructionType = (UnitInstructionType)(unitInstructionType + 1); + } while ((int)unitInstructionType < 0x10); + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::setDestinationForUnit, DAT_UnitsState::ptr)( + uVar13, x, y, 0); + DAT_UnitsState::instance.units[uVar13].state.generic + = Map::Units::States::US_MOVE_TO_DESTINATION; + DAT_UnitsState::instance.units[uVar13].targetingType = Map::Units::UIT_MAN_SIEGE_EQUIPMENT; + DAT_UnitsState::instance.units[uVar13].targetedUnitID__OR__engineerMannedSiegeEngineRef + = (short)id; + DAT_UnitsState::instance.units[uVar13].resourceToDeposit = 0; + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::deselectUnit, DAT_UnitsState::ptr)(uVar13); + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::clearOrDeselectUnitFromSelection, + DAT_UnitsState::ptr)(this->tribes[tribeID].owner, uVar13, 0); + unitUID = unitUID + -1; + _siegeCrewIndex = iVar12; + if (unitUID == 0) { + return TRUE; + } + } + iVar12 = _siegeCrewIndex; + if (this->tribes[tribeID].size <= _siegeCrewIndex) { + return TRUE; + } + } while (true); + } + break; + case Map::Units::UIT_EXIT_SIEGE_EQUIPMENT: + /* + The spawn position is a pair of `int`s rather than the decompiler's + shared `short`s. 0x529e0e reads the two path-finding results as dwords + (`mov ecx, dword ptr [0x12bb90c]`, `mov edx, dword ptr [0x12bb910]`) and + 0x529e36 reads the fallback coordinates with `movsx` into full registers, + storing a word only at the end - so the `(short)` belongs on the stores, + not on the reads, where it cost a truncation and a re-extension at each + of the three places the retry loop sets them. + */ + int _spawnX; + int _spawnY; + /* + disband siege engines? + */ + _param_4_unitUID_Y_copy = param_5 != 0 ? 0x10 : 0; + param_5 = (int)SEC_RNG::instance.currentNumber2 & 0x8000000f; + if (param_5 < 0) { + param_5 = (param_5 - 1U | 0xfffffff0) + 1; + } + MACRO_CALL_MEMBER(Random::RNG_Func::nextRandomNumber2, SEC_RNG::ptr)(); + if (DAT_UnitsState::instance.units[iVar11].uid == unitUID) { + DAT_UnitsState::instance.units[iVar11].state.generic = Map::Units::States::US_FIRE_WEAPONUnk; + unitInstructionType = ((UnitInstructionType)0); + if (0 < DAT_UnitsState::instance.units[iVar11] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300) { + tribeID = iVar11 * 0x490 + 0x1388860; + do { + _unitID_0x11 = (int)*(short*)tribeID; + *(undefined2*)tribeID = 0; + DAT_UnitsState::instance.units[_unitID_0x11].field_0x3c0 = 0; + DAT_UnitsState::instance.units[_unitID_0x11].field_0x3bc = 0; + DAT_UnitsState::instance.units[_unitID_0x11].animationCycleNumber = 0; + DAT_UnitsState::instance.units[_unitID_0x11].state.generic + = Map::Units::States::US_JESTER_ROAM_TO; + DAT_UnitsState::instance.units[_unitID_0x11].disappearFadeAlphaCountdown = 0x20; + DAT_UnitsState::instance.units[_unitID_0x11].engineerManningSiegeStateRef_checkType = 0xfe; + DAT_UnitsState::instance.units[_unitID_0x11].cachedState + = (UnitStateShort)_param_4_unitUID_Y_copy; + UVar4 = DAT_UnitsState::instance.units[iVar11].unitType; + if ((UVar4 == Map::Units::UT_S_MANGONEL) || (UVar4 == Map::Units::UT_S_BALLISTA)) { + DAT_UnitsState::instance.units[_unitID_0x11].goToRallyPoint = 1; + } + DAT_UnitsState::instance.units[_unitID_0x11].updateTickTracker = 0; + DAT_UnitsState::instance.units[_unitID_0x11].field_0x58 = 1; + unitUID = 0; + LAB_00529da0: + do { + uVar19 = (int)DAT_AttackInfoDefinedData::instance.SiegeCrewPositionOffsets[param_5][0] + + (int)DAT_UnitsState::instance.units[iVar11].x; + uVar13 = (int)DAT_AttackInfoDefinedData::instance.SiegeCrewPositionOffsets[param_5][1] + + (int)DAT_UnitsState::instance.units[iVar11].y; + param_5 = param_5 + 1U & 0x8000000f; + if (param_5 < 0) { + param_5 = (param_5 - 1U | 0xfffffff0) + 1; + } + MACRO_CALL_MEMBER( + Map::Navigation::PathFindingState_Func::findWalkableTileThatDoesNotContainUnit, + DAT_PathFindingState::ptr)(id, uVar19, uVar13, 1); + if (DAT_PathFindingState::instance.ALG_ResultTile == 0) { + MACRO_CALL_MEMBER( + Map::Navigation::PathFindingState_Func::findWalkableTileThatDoesNotContainUnit, + DAT_PathFindingState::ptr)(id, uVar19, uVar13, 0); + _spawnX = DAT_PathFindingState::instance.ALG_ResultX; + _spawnY = DAT_PathFindingState::instance.ALG_ResultY; + iVar12 = DAT_PathFindingState::instance.ALG_ResultTile; + if (DAT_PathFindingState::instance.ALG_ResultTile != 0) + break; + unitUID = unitUID + 1; + /* + `unitUID | unitUID != 0x10` is always true - it + parses as `unitUID | (unitUID != 0x10)`, which is + 0x10 when the counter reaches 16 and 1 when it is 0. + So the goto was unconditional and the three lines + below it were dead, leaving this retry loop to walk + off the end of the 16-entry table at 0xb4c7f0 that + LAB_00529da0 indexes with it (`movsx edi, word ptr + [eax*4 + 0xb4c7f0]`) until the path search happened + to succeed. The counter test is what was meant. + */ + if (unitUID != 0x10) + goto LAB_00529da0; + _spawnX = DAT_UnitsState::instance.units[iVar11].x; + _spawnY = DAT_UnitsState::instance.units[iVar11].y; + iVar12 = DAT_UnitsState::instance.units[iVar11].tile; + } else { + _spawnX = DAT_PathFindingState::instance.ALG_ResultX; + _spawnY = DAT_PathFindingState::instance.ALG_ResultY; + iVar12 = DAT_PathFindingState::instance.ALG_ResultTile; + } + } while (iVar12 == 0); + bVar2 = DAT_TileMapState::instance.HeightLayer[iVar12]; + DAT_UnitsState::instance.units[_unitID_0x11].totalSizeOfPathPlan = 0; + DAT_UnitsState::instance.units[_unitID_0x11].x = (short)_spawnX; + DAT_UnitsState::instance.units[_unitID_0x11].mimicCurrentXPosition = (short)_spawnX; + DAT_UnitsState::instance.units[_unitID_0x11].y = (short)_spawnY; + DAT_UnitsState::instance.units[_unitID_0x11].mimicCurrentYPosition = (short)_spawnY; + DAT_UnitsState::instance.units[_unitID_0x11].terrainOrClimbHeight = (ushort)bVar2; + DAT_UnitsState::instance.units[_unitID_0x11].tile = iVar12; + DAT_UnitsState::instance.units[_unitID_0x11].nextTileUnk = iVar12; + DAT_UnitsState::instance.units[_unitID_0x11].microXPosition = (short)(_spawnX * 8 + 4); + DAT_UnitsState::instance.units[_unitID_0x11].microYPosition = (short)(_spawnY * 8 + 4); + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::updateMicroPosition, DAT_UnitsState::ptr)( + _unitID_0x11); + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::resetUnitMovementState, DAT_UnitsState::ptr)( + _unitID_0x11); + tribeID = tribeID + 2; + DAT_UnitsState::instance.units[_unitID_0x11].animationSheetFrameOffset = 1; + DAT_UnitsState::instance.units[_unitID_0x11].field_0x30_animRelated = 0x10; + unitInstructionType = (UnitInstructionType)(unitInstructionType + 1); + } while ((int)unitInstructionType < (int)DAT_UnitsState::instance.units[iVar11] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300); + } + DAT_UnitsState::instance.units[iVar11] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 = 0; + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::makeUnitStopWalkingByClearingPathProgressState, + DAT_UnitsState::ptr)(id); + return TRUE; + } + break; + case Map::Units::UIT_DISBAND: + /* + disband? + */ + this->tribes[tribeID].isRallyingUnk = 0; + _unitTribeIndex = 0; + if (0 < _tribeSize) { + do { + _unitID_0x1e = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)( + tribeID, _unitTribeIndex); + _unitTribeIndex = _unitTribeIndex + 1; + if ((DAT_UnitsState::instance.units[_unitID_0x1e].logicalState == Map::Units::ULS_NORMAL) + && (DAT_UnitsState::instance.units[_unitID_0x1e].dying == 0)) { + switch (DAT_UnitsState::instance.units[_unitID_0x1e].unitType) { + case Map::Units::UT_TUNNELER: + case Map::Units::UT_E_ARCHER: + case Map::Units::UT_E_XBOW: + case Map::Units::UT_E_SPEAR: + case Map::Units::UT_E_PIKE: + case Map::Units::UT_E_MACE: + case Map::Units::UT_E_SWORD: + case Map::Units::UT_E_KNIGHT: + case Map::Units::UT_E_LADDER: + case Map::Units::UT_E_ENGINEER: + case Map::Units::UT_E_MONK: + case Map::Units::UT_A_ARCHER: + case Map::Units::UT_A_SLAVE: + case Map::Units::UT_A_SLINGER: + case Map::Units::UT_A_ASSASSIN: + case Map::Units::UT_A_HARCHER: + case Map::Units::UT_A_SWORDSMAN: + case Map::Units::UT_A_FIRETHROWER: + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::disbandUnit, DAT_UnitsState::ptr)( + _unitID_0x1e); + break; + case Map::Units::UT_S_CATAPULT: + case Map::Units::UT_S_TREBUCHET: + case Map::Units::UT_S_MANGONEL: + case Map::Units::UT_S_TOWER: + case Map::Units::UT_S_BATTERINGRAM: + case Map::Units::UT_S_SHIELD: + case Map::Units::UT_S_BALLISTA: + case Map::Units::UT_S_FBALLISTA: + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::giveTribeAnInstruction, this)(tribeID, + Map::Units::UIT_EXIT_SIEGE_EQUIPMENT, _unitID_0x1e, + DAT_UnitsState::instance.units[_unitID_0x1e].uid, 1); + _gamemodeSiegeThat = DAT_GameCore::instance.gameMode_2 == Game::GM_SIEGE_THAT; + DAT_UnitsState::instance.units[_unitID_0x1e].state.generic + = Map::Units::States::US_DISAPPEAR; + if (_gamemodeSiegeThat) { + MACRO_CALL_MEMBER(Map::Buildings::BuildingsState_Func::getPriceForDisbandedUnitType, + DAT_BuildingsState::ptr)( + (Map::Units::UnitType)(DAT_UnitsState::instance.units[_unitID_0x1e].unitType), + &tribeID); + piVar18 = DAT_GameState::instance + .playerDataArray[DAT_GameSynchronyState::instance.currentPlayerSlotID] + .startResources + + 0xf; + *piVar18 = *piVar18 + tribeID; + } + } + } + } while (_unitTribeIndex < this->tribes[tribeID].size); + } + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::deselectAllUnitsOneByOne, DAT_UnitsState::ptr)(); + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::clearOrDeselectUnitFromSelection, DAT_UnitsState::ptr)( + this->tribes[tribeID].owner, 0, 0); + return TRUE; + case ((UnitInstructionType)0x15): + this->tribes[tribeID].isRallyingUnk = 0; + uVar13 = (uint)DAT_BuildingsState::instance.buildings[id].buildingEntryY; + _unitTribeIndex = 0; + BVar16 + = MACRO_CALL_MEMBER(Rendering::ViewportRenderState_Func::xyAreValid, DAT_ViewportRenderState::ptr)( + (int)DAT_BuildingsState::instance.buildings[id].buildingEntryX, uVar13); + if (!BVar16) { + return FALSE; + } + param_5 + = (int)(short)DAT_TileMapState::instance + .PathConnectionLayer[DAT_ViewportRenderState::instance.translationMatrix[uVar13].addXgetTile + + (int)DAT_BuildingsState::instance.buildings[iVar11].buildingEntryX]; + if (0 < _tribeSize) { + do { + uVar13 = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)( + tribeID, _unitTribeIndex); + _unitTribeIndex = _unitTribeIndex + 1; + if (DAT_UnitsState::instance.units[uVar13].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[uVar13].dying == 0 + && DAT_UnitsState::instance.units[uVar13].unitType == Map::Units::UT_TUNNELER) { + DAT_UnitsState::instance.units[uVar13]._someX_2 = 0; + DAT_UnitsState::instance.units[uVar13]._someY_2 = 0; + iVar12 = MACRO_CALL_MEMBER(Map::Buildings::BuildingsState_Func::buildingIsAccessible, + DAT_BuildingsState::ptr)(iVar11, 1); + if (iVar12 != 0 + && (iVar12 = MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func:: + calculateCanPlayerUnitsNavigateToAreaFromArea, + DAT_PathFindingState::ptr)((int)DAT_UnitsState::instance.units[uVar13].owner, + (dword)((int)(param_5)), + (dword)((int)((short)DAT_TileMapState::instance + .PathConnectionLayer[DAT_UnitsState::instance.units[uVar13].tile])), + 0), + iVar12 != 0)) { + sVar9 = DAT_BuildingsState::instance.buildings[iVar11].buildingEntryY; + sVar8 = DAT_BuildingsState::instance.buildings[iVar11].buildingEntryX; + iVar11 = DAT_BuildingsState::instance.buildings[iVar11].uid; + DAT_UnitsState::instance.units[uVar13].workplaceBuildingID_1 + = _param_3_id_x_tile_buildingID_copy; + DAT_UnitsState::instance.units[uVar13].targetID_OR_targetBuildingID + = _param_3_id_x_tile_buildingID_copy; + DAT_UnitsState::instance.units[uVar13].targetUID = iVar11; + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::setDestinationForUnit, + DAT_UnitsState::ptr)(uVar13, (uint)(sVar8), (uint)(sVar9), 0); + DAT_UnitsState::instance.units[uVar13].state.generic + = Map::Units::States::US_LOOK_AROUNDUnk; + DAT_UnitsState::instance.units[uVar13].targetingType = ((UnitInstructionType)0x15); + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::deselectUnit, DAT_UnitsState::ptr)( + uVar13); + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::clearOrDeselectUnitFromSelection, + DAT_UnitsState::ptr)(this->tribes[tribeID].owner, uVar13, 0); + return TRUE; + } + } + } while (_unitTribeIndex < this->tribes[tribeID].size); + } + DAT_TileMapState::instance.showNoRubbleWhenDestroyingBuilding = 1; + MACRO_CALL_MEMBER(Map::Buildings::BuildingsState_Func::destroyBuilding, DAT_BuildingsState::ptr)( + iVar11); + break; + } + return TRUE; + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/giveTribeMoveInstruction.cpp b/src/OpenSHC/Map/Units/TribesState/giveTribeMoveInstruction.cpp new file mode 100644 index 0000000000..fdab39bc54 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/giveTribeMoveInstruction.cpp @@ -0,0 +1,512 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Map/Navigation/PathFindingState.func.hpp" +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/Units/UnitsState.func.hpp" +#include "OpenSHC/Synchrony/GameSynchronyState.func.hpp" +#include "OpenSHC/Map/Units/Instructions/UnitMatchSpeedEnum.hpp" +#include "OpenSHC/Map/Units/States/UnitState.hpp" +#include "OpenSHC/Map/Units/UnitInstructionType.hpp" +#include "OpenSHC/Map/Units/UnitLogicState.hpp" +#include "OpenSHC/Map/Units/UnitType.hpp" +#include "OpenSHC/WindowsHelper/Enums/BOOLEnum.hpp" + +#include "OpenSHC/Globals/DAT_EntityState.hpp" +#include "OpenSHC/Globals/DAT_GameSynchronyState.hpp" +#include "OpenSHC/Globals/DAT_PathFindingState.hpp" +#include "OpenSHC/Globals/DAT_TileMapState.hpp" +#include "OpenSHC/Globals/DAT_UnitSelectionDefinedData.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" +#include "OpenSHC/Globals/DAT_ViewportRenderState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Map::Units::UnitInstructionType; + using Map::Units::UnitLogicState; + using Map::Units::UnitType; + using Map::Units::Instructions::UnitMatchSpeedEnum; + using Map::Units::States::UnitState; + using WindowsHelper::Enums::BOOLEnum; + + /* + Written section by section against the original rather than the decompiler's + output. What each part of the shape is for: + - The tribe is always subscripted, never bound to a pointer: MSVC then keeps + `this + tribeID * 0x334` and reads the fields at +0x5a, +0x5c, ... as the + original does. A `Tribe*` makes it fold the 0x28 into the base instead. + - One `targetArea` holds the target unit's area and then the result of + canNavigateFunctionReturnsArea; one `defensive` flag is set by two separate + tests of the logic word (0x526676 stores the same 1 into one slot twice). + - `storeAsRallyPoint` is dead after the rally point is stored, and the original + keeps the "fallback search started" state in its slot, so it is reused for that. + - The filter reads `unitType` from the unit every time. Through a local, MSVC + knows the type after each passing digTile test and threads the jump past the + remaining type tests; the original tests them all in line. + - One `index` serves all three loops. + - The move delay is stored from each arm so the multiply is done in 16 bits + (`imul dx, dx, 3` / `add dx, dx`), as the original does. + */ + // FUNCTION: STRONGHOLDCRUSADER 0x005263A0 + undefined4 TribesState::giveTribeMoveInstruction( + int tribeID, uint x1, uint y1, int rallyBool, int storeAsRallyPoint, UnitMatchSpeedEnum speedMatching) + { + int allAssassins = 0; + int climbing = 0; + int index = 0; + int defensive = 0; + int crossArea = 0; + int crossAreaTargetTile = 0; + int crossAreaResultTile = 0; + int searchBudget = 500; + int unitID; + UnitStateShort unitState; + int delayIndex; + if (x1 == 0) { + if (y1 == 0) { + return 0; + } + } else { + if ((int)x1 < 0) { + return 0; + } + if ((int)x1 >= 400) { + return 0; + } + } + if (y1 > 399) { + return 0; + } + if (DAT_ViewportRenderState::instance.DAT_BinaryTileMap400x400[y1 * 400 + x1] == 0) { + return 0; + } + Tribe& tribe = this->tribes[tribeID]; + int targetUnitID = tribe.selectionTargetUnitID; + int const targetUnitX = DAT_UnitsState::instance.units[targetUnitID].x; + int const targetUnitY = DAT_UnitsState::instance.units[targetUnitID].y; + int targetArea + = (short)DAT_TileMapState::instance + .PathConnectionLayer[DAT_ViewportRenderState::instance.translationMatrix[targetUnitY].addXgetTile + + targetUnitX]; + int const tile = DAT_ViewportRenderState::instance.translationMatrix[y1].addXgetTile + x1; + int const area = (short)DAT_TileMapState::instance.PathConnectionLayer[tile]; + if (DAT_TileMapState::instance.LogicLayer[tile] & 0x30) { + return 0; + } + DAT_PathFindingState::instance.field_0x98 = 0; + ++this->fcn_mtribe; + if (targetUnitID + == MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getFirstUnitInTribeThatIsOnXTerrain, this)( + tribeID)) { + targetArea = MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func::canNavigateFunctionReturnsArea, + DAT_PathFindingState::ptr)(tribe.owner, area, DAT_UnitsState::instance.units[targetUnitID].x, + DAT_UnitsState::instance.units[targetUnitID].y); + if (targetArea == 0) { + return MACRO_CALL_MEMBER(Map::Units::TribesState_Func::applyMoveCommandOrRallyCommandToTribe, this)( + tribeID, x1, y1, rallyBool, storeAsRallyPoint); + } + targetUnitID = tribe.selectionTargetUnitID; + climbing = 1; + } else if (targetArea == 0) { + return MACRO_CALL_MEMBER(Map::Units::TribesState_Func::applyMoveCommandOrRallyCommandToTribe, this)( + tribeID, x1, y1, rallyBool, storeAsRallyPoint); + } + if (area <= 0) { + return 0; + } + if (MACRO_CALL_MEMBER(Map::Units::TribesState_Func::isTribeAllAssassins, this)(tribeID)) { + allAssassins = 1; + } else if (targetArea != area) { + int const canClimb + = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::tribeContainsUnitThatCanClimb, this)(tribeID); + int const climbArea = MACRO_CALL_MEMBER( + Map::Navigation::PathFindingState_Func::calculateCanPlayerUnitsNavigateToAreaFromArea, + DAT_PathFindingState::ptr)(tribe.owner, targetArea, area, canClimb); + if (climbArea == 0) { + if (!MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func::someBinaryAlgFunctionPathFinding, + DAT_PathFindingState::ptr)(targetUnitID)) { + return 0; + } + if (!MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func::findCrossAreaBridgeTileToTarget, + DAT_PathFindingState::ptr)(targetUnitID, x1, y1)) { + return 0; + } + crossArea = 1; + crossAreaTargetTile = DAT_PathFindingState::instance.ALG_TargetTile; + crossAreaResultTile = DAT_PathFindingState::instance.ALG_ResultTile; + } else if (!MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func::setClimbBasedOnClosestClimbData, + DAT_PathFindingState::ptr)(targetUnitID, targetArea, climbArea)) { + return 0; + } + } + if (storeAsRallyPoint) { + tribe.isRallyingUnk = (short)rallyBool; + tribe.rallyPointArray[0][0] = DAT_UnitsState::instance.units[targetUnitID].x; + tribe.rallyPointArray[0][1] = DAT_UnitsState::instance.units[targetUnitID].y; + tribe.rallyPointArray[1][0] = (short)x1; + tribe.rallyPointArray[1][1] = (short)y1; + tribe.currentRallyPointIndex = 1; + tribe.rallyPointCount = 2; + tribe.containsRabbit = 0; + } + this->ALG_ResultTileIndex = 0; + this->field_0x18 = 0; + if (DAT_TileMapState::instance.LogicLayer[tile] & 0x100) { + defensive = 1; + } + storeAsRallyPoint = 0; + if (DAT_TileMapState::instance.LogicLayer[tile] & 0x10000000) { + defensive = 1; + } + rallyBool = 1; + if (allAssassins) { + MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func::pathFindingWithBuildingsIncluded, + DAT_PathFindingState::ptr)(x1, y1, 0xffffffff, 0xffffffff, 500, 0); + } else if (climbing) { + MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func::findPathUsingClimbingWithHeightMargin16, + DAT_PathFindingState::ptr)(x1, y1, 0xffffffff, 0xffffffff, 500, FALSE); + } else { + MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func::findLinkageBasedPathOrWalkRadius, + DAT_PathFindingState::ptr)(x1, y1, -1, -1, 500, FALSE); + } + if (!MACRO_CALL_MEMBER(Map::Units::TribesState_Func::anyUnitsOfTribeAreOutsideCoverageOfPathFindingAlg, + this)(tribeID, DAT_PathFindingState::instance.searchGeneration)) { + do { + searchBudget += 500; + if (searchBudget >= 0x13a10 || ((climbing || defensive) && searchBudget >= 8000)) { + if (!DAT_PathFindingState::instance.field_0x98) { + if (allAssassins) { + if (!MACRO_CALL_MEMBER( + Map::Navigation::PathFindingState_Func::pathFindingWithBuildingsIncluded, + DAT_PathFindingState::ptr)(x1, y1, targetUnitX, targetUnitY, 100000, 0)) { + return 0; + } + } else if (climbing) { + if (!MACRO_CALL_MEMBER( + Map::Navigation::PathFindingState_Func::findPathUsingClimbingWithHeightMargin16, + DAT_PathFindingState::ptr)(x1, y1, targetUnitX, targetUnitY, 100000, FALSE)) { + return 0; + } + } else if (!MACRO_CALL_MEMBER( + Map::Navigation::PathFindingState_Func::findLinkageBasedPathOrWalkRadius, + DAT_PathFindingState::ptr)( + x1, y1, targetUnitX, targetUnitY, 100000, FALSE)) { + return 0; + } + } + MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::applyMovementDistanceToUnitsInTribeBasedOnUnitNumberInTribe, + this)(tribeID); + goto planDestinations; + } + rallyBool = DAT_PathFindingState::instance.searchQueue.currentDistance; + if (allAssassins) { + MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func::pathFindingWithBuildingsIncluded, + DAT_PathFindingState::ptr)(x1, y1, 0xffffffff, 0xffffffff, searchBudget, 1); + } else if (climbing) { + MACRO_CALL_MEMBER( + Map::Navigation::PathFindingState_Func::findPathUsingClimbingWithHeightMargin16, + DAT_PathFindingState::ptr)(x1, y1, 200, 0, searchBudget, TRUE); + } else { + MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func::findLinkageBasedPathOrWalkRadius, + DAT_PathFindingState::ptr)(x1, y1, -1, -1, searchBudget, TRUE); + } + } while ( + !MACRO_CALL_MEMBER(Map::Units::TribesState_Func::anyUnitsOfTribeAreOutsideCoverageOfPathFindingAlg, + this)(tribeID, DAT_PathFindingState::instance.searchGeneration)); + } + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::applyMovementDistanceToUnitsInTribe, this)(tribeID); + planDestinations: + if (0 < tribe.size) { + do { + unitID = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)( + tribeID, index); + ++index; + if (DAT_UnitsState::instance.units[unitID].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[unitID].dying == 0 + && DAT_UnitsState::instance.units[unitID].usingTeleport == 0 + && DAT_UnitsState::instance.units[unitID].field_0x413 == 0 + && DAT_UnitsState::instance.units[unitID].state.generic != (UnitStateShort)0xcf + && DAT_UnitsState::instance.units[unitID].rallyRelatedFlag == 0 + && DAT_UnitsState::instance.units[unitID].moveRelatedFlag != 1 + && DAT_UnitsState::instance.units[unitID].moveableUnk != 0 + && DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_TREBUCHET + && DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_MANGONEL + && DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_BALLISTA + && (DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_CATAPULT + || DAT_UnitsState::instance.units[unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + == 2) + && (DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_FBALLISTA + || DAT_UnitsState::instance.units[unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + == 2) + && (DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_TOWER + || DAT_UnitsState::instance.units[unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + == 4) + && (DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_BATTERINGRAM + || DAT_UnitsState::instance.units[unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + == 4) + && (DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_SHIELD + || DAT_UnitsState::instance.units[unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + == 1)) { + if (DAT_UnitsState::instance.units[unitID].unitType == Map::Units::UT_E_ENGINEER) { + DAT_UnitsState::instance.units[unitID].field_0x3c4 = 0; + } + if (allAssassins) { + if (defensive) { + if (storeAsRallyPoint == 0) { + int const found = MACRO_CALL_MEMBER( + Map::Navigation::PathFindingState_Func::pathFindingResultBased, + DAT_PathFindingState::ptr)(1, x1, y1, rallyBool); + ++this->ALG_ResultTileIndex; + if (!found) { + storeAsRallyPoint = 1; + this->ALG_ResultTileIndex = 0; + MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func:: + findNextTileInExistingSearchThatIsModuloDistanceAway, + DAT_PathFindingState::ptr)(1, x1, y1); + ++this->ALG_ResultTileIndex; + } + } else if (storeAsRallyPoint == 1) { + MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func:: + findNextTileInExistingSearchThatIsModuloDistanceAway, + DAT_PathFindingState::ptr)(1, x1, y1); + ++this->ALG_ResultTileIndex; + } + } else if (storeAsRallyPoint == 0) { + int const found = MACRO_CALL_MEMBER( + Map::Navigation::PathFindingState_Func:: + findNextTileByModuloAmongPreviousSearchNotOnDefensiveStructure, + DAT_PathFindingState::ptr)(3, x1, y1); + ++this->ALG_ResultTileIndex; + if (!found) { + storeAsRallyPoint = 1; + this->ALG_ResultTileIndex = 0; + MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func:: + findNextTileInExistingSearchThatIsModuloDistanceAway, + DAT_PathFindingState::ptr)(3, x1, y1); + ++this->ALG_ResultTileIndex; + } + } else if (storeAsRallyPoint == 1) { + MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func:: + findNextTileInExistingSearchThatIsModuloDistanceAway, + DAT_PathFindingState::ptr)(3, x1, y1); + ++this->ALG_ResultTileIndex; + } + } else if (tribe.unkIsAnimalTribe) { + MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func:: + findNextTileInExistingSearchThatIsModuloDistanceAway, + DAT_PathFindingState::ptr)(3, x1, y1); + ++this->ALG_ResultTileIndex; + } else if (defensive || climbing) { + MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func:: + findNextTileInExistingSearchThatIsModuloDistanceAway, + DAT_PathFindingState::ptr)(1, x1, y1); + ++this->ALG_ResultTileIndex; + } else if (DAT_UnitsState::instance.units[unitID].unitType == Map::Units::UT_S_CATAPULT + || DAT_UnitsState::instance.units[unitID].unitType == Map::Units::UT_S_FBALLISTA + || DAT_UnitsState::instance.units[unitID].unitType == Map::Units::UT_S_TOWER + || DAT_UnitsState::instance.units[unitID].unitType == Map::Units::UT_S_BATTERINGRAM + || DAT_UnitsState::instance.units[unitID].unitType == Map::Units::UT_S_SHIELD) { + MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func:: + findNextTileInExistingSearchThatIsModuloDistanceAway, + DAT_PathFindingState::ptr)(4, x1, y1); + ++this->ALG_ResultTileIndex; + } else { + MACRO_CALL_MEMBER(Map::Navigation::PathFindingState_Func:: + findNextTileInExistingSearchThatIsModuloDistanceAway, + DAT_PathFindingState::ptr)(2, x1, y1); + ++this->ALG_ResultTileIndex; + } + if ((int)this->ALG_ResultTileIndex >= 4000) { + break; + } + DAT_UnitsState::instance.units[unitID].plannedDestinationX = (short)this->ALG_ResultX; + DAT_UnitsState::instance.units[unitID].plannedDestinationY = (short)this->ALG_ResultY; + } + } while (index < tribe.size); + } + index = 0; + if (0 < tribe.size) { + do { + unitID = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)( + tribeID, index); + ++index; + if (DAT_UnitsState::instance.units[unitID].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[unitID].dying == 0 + && DAT_UnitsState::instance.units[unitID].usingTeleport == 0 + && DAT_UnitsState::instance.units[unitID].field_0x413 == 0 + && (unitState = DAT_UnitsState::instance.units[unitID].state.generic, + unitState != (UnitStateShort)0xcf) + && DAT_UnitsState::instance.units[unitID].rallyRelatedFlag == 0 + && DAT_UnitsState::instance.units[unitID].moveRelatedFlag != 1 + && DAT_UnitsState::instance.units[unitID].moveableUnk != 0 + && DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_TREBUCHET + && DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_MANGONEL + && DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_BALLISTA + && (DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_CATAPULT + || DAT_UnitsState::instance.units[unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + == 2) + && (DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_FBALLISTA + || DAT_UnitsState::instance.units[unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + == 2) + && (DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_TOWER + || DAT_UnitsState::instance.units[unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + == 4) + && (DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_BATTERINGRAM + || DAT_UnitsState::instance.units[unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + == 4) + && (DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_SHIELD + || DAT_UnitsState::instance.units[unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + == 1)) { + if (unitState == Map::Units::States::US_MELEE_ATTACK) { + DAT_UnitsState::instance.units[unitID].movementCooldown + = DAT_UnitsState::instance.units[unitID].movementSpeed * -4; + } + DAT_UnitsState::instance.units[unitID].state.generic + = Map::Units::States::US_MOVE_TO_DESTINATION; + DAT_UnitsState::instance.units[unitID].movementType_OR_targetUnitID = 0; + DAT_UnitsState::instance.units[unitID].targetedBuildingTile = 0; + if (allAssassins) { + DAT_PathFindingState::instance.allAssassinsUnk = 1; + } else if (climbing) { + DAT_PathFindingState::instance.notAllAssassinsUnk = 0; + } else { + DAT_PathFindingState::instance.notAllAssassinsUnk = !DAT_EntityState::instance.fireCount; + } + DAT_UnitsState::instance.units[unitID]._someX_2 = 0; + DAT_UnitsState::instance.units[unitID]._someY_2 = 0; + MACRO_CALL_MEMBER(Synchrony::GameSynchronyState_Func::throttledMultiplayerSyncUpdate, + DAT_GameSynchronyState::ptr)(); + if (unitState != Map::Units::States::US_MELEE_ATTACK + && DAT_UnitsState::instance.units[unitID].plannedDestinationX + == DAT_UnitsState::instance.units[unitID].destinationXPosition + && DAT_UnitsState::instance.units[unitID].plannedDestinationY + == DAT_UnitsState::instance.units[unitID].destinationYPosition + && DAT_UnitsState::instance.units[unitID].tunnelerFinishedDigging == 2) { + DAT_UnitsState::instance.units[unitID].unitSpeedMatchingRelatedUnk = 0x10; + } else { + if (!MACRO_CALL_MEMBER( + Map::Units::UnitsState_Func::setDestinationForUnit, DAT_UnitsState::ptr)(unitID, + DAT_UnitsState::instance.units[unitID].plannedDestinationX, + DAT_UnitsState::instance.units[unitID].plannedDestinationY, 0)) { + if (!crossArea + || !(DAT_TileMapState::instance + .LogicLayer[DAT_UnitsState::instance.units[unitID].tile] + & 0x10000100)) { + goto unitMoved; + } + MACRO_CALL_MEMBER( + Map::Units::UnitsState_Func::setDestinationForUnit, DAT_UnitsState::ptr)(unitID, + crossAreaTargetTile + - DAT_ViewportRenderState::instance + .translationMatrix[DAT_ViewportRenderState::instance + .tileTranslationMatrix_YComponent[crossAreaTargetTile]] + .addXgetTile, + DAT_ViewportRenderState::instance + .tileTranslationMatrix_YComponent[crossAreaTargetTile], + 0); + DAT_UnitsState::instance.units[unitID].state.generic = Map::Units::States::US_APPEAR; + DAT_UnitsState::instance.units[unitID] + .targetedUnitUIDUnk_OR_someAppearTileUnk_OR_buildingUID_OR_pitchDitchUID_OR_entityUID + = crossAreaResultTile; + } + if (speedMatching != Map::Units::Instructions::UMSE_0) { + DAT_UnitsState::instance.units[unitID].unitSpeedMatchingRelatedUnk = 0x10; + } + } + unitMoved: + DAT_PathFindingState::instance.notAllAssassinsUnk = 0; + if (!DAT_PathFindingState::instance.field_0x7c) { + ++this->field_0x18; + } else { + --this->field_0x18; + } + } + } while (index < tribe.size); + } + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::applyUnitTopSpeedDelayBasedOnTribeSize, this)( + tribeID, FALSE); + index = 0; + tribe.someUnitID = 0; + if (0 < tribe.size) { + do { + unitID = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)( + tribeID, index); + ++index; + if (DAT_UnitsState::instance.units[unitID].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[unitID].dying == 0 + && DAT_UnitsState::instance.units[unitID].usingTeleport == 0 + && DAT_UnitsState::instance.units[unitID].field_0x413 == 0 + && DAT_UnitsState::instance.units[unitID].state.generic != (UnitStateShort)0xcf + && DAT_UnitsState::instance.units[unitID].rallyRelatedFlag == 0 + && DAT_UnitsState::instance.units[unitID].moveRelatedFlag != 1 + && DAT_UnitsState::instance.units[unitID].moveableUnk != 0 + && DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_TREBUCHET + && DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_MANGONEL + && DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_BALLISTA + && (DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_CATAPULT + || DAT_UnitsState::instance.units[unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + == 2) + && (DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_FBALLISTA + || DAT_UnitsState::instance.units[unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + == 2) + && (DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_TOWER + || DAT_UnitsState::instance.units[unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + == 4) + && (DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_BATTERINGRAM + || DAT_UnitsState::instance.units[unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + == 4) + && (DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_S_SHIELD + || DAT_UnitsState::instance.units[unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + == 1)) { + delayIndex = DAT_UnitsState::instance.units[unitID].topSpeedDelayIndex; + if (tribe.unkIsAnimalTribe) { + DAT_UnitsState::instance.units[unitID].moveInstructionSpeedDelayTracker + = (short)DAT_UnitSelectionDefinedData::instance.UnitInstructionMoveDelay[delayIndex] + * 3; + } else if ((int)this->field_0x18 >= 0) { + DAT_UnitsState::instance.units[unitID].moveInstructionSpeedDelayTracker + = (short)DAT_UnitSelectionDefinedData::instance.UnitInstructionMoveDelay[delayIndex] + * 2; + } else { + DAT_UnitsState::instance.units[unitID].moveInstructionSpeedDelayTracker + = (short)DAT_UnitSelectionDefinedData::instance.UnitInstructionMoveDelay[delayIndex]; + } + if ((int)this->field_0x18 >= 0) { + DAT_UnitsState::instance.units[unitID].moveDelay + = (short)(DAT_UnitSelectionDefinedData::instance.UnitMoveDelay[delayIndex] / 2); + } else { + DAT_UnitsState::instance.units[unitID].moveDelay = 0; + } + if (DAT_UnitsState::instance.units[unitID].movementCooldown != 0) { + DAT_UnitsState::instance.units[unitID].moveDelay = 0; + } + DAT_UnitsState::instance.units[unitID].moveInstructionSpeedDelayTracker = 0; + DAT_UnitsState::instance.units[unitID].moveDelay = 0; + DAT_UnitsState::instance.units[unitID].horseArcherShootingVariation = 0; + DAT_UnitsState::instance.units[unitID].targetingType + = Map::Units::UIT_NO_INSTRUCTION_OR_MOVEUnk; + } + } while (index < tribe.size); + } + return 1; + } + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/isTribePathToDestinationClear.cpp b/src/OpenSHC/Map/Units/TribesState/isTribePathToDestinationClear.cpp new file mode 100644 index 0000000000..111af323a3 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/isTribePathToDestinationClear.cpp @@ -0,0 +1,68 @@ +#include "../TribesState.func.hpp" + +#include "OpenSHC/Map/Navigation/PathFindingState.func.hpp" +#include "OpenSHC/Map/Units/UnitLogicState.hpp" + +#include "OpenSHC/Globals/DAT_PathFindingState.hpp" +#include "OpenSHC/Globals/DAT_TileMapState.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" +#include "OpenSHC/Globals/DAT_ViewportRenderState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + // The coordinates are tested unsigned (ja 0x18F); ALG_ResultTileIndex counts the tiles taken and is + // compared signed (jge 0x1F4 at 0x524DCF); UnitLayer is read signed (movsx, 0x524DD5). The tribe size is + // re-read every iteration (0x524D80). All failure exits share the return block at 0x524CD7 except the + // occupied-tileUnk exit (0x524E00). + // FUNCTION: STRONGHOLDCRUSADER 0x00524CA0 + BOOLEnum TribesState::isTribePathToDestinationClear(int tribeID, uint fromX, uint fromY, uint destX, uint destY) + { + int unitSelectionIndex = 0; + if (fromX > 399 || fromY > 399 + || DAT_ViewportRenderState::instance.DAT_BinaryTileMap400x400[fromY * 400 + fromX] == 0) { + return 0; + } + if (destX > 399 || destY > 399 + || DAT_ViewportRenderState::instance.DAT_BinaryTileMap400x400[destY * 400 + destX] == 0) { + return 0; + } + int const destTile = DAT_ViewportRenderState::instance.translationMatrix[destY].addXgetTile + destX; + if (DAT_TileMapState::instance + .PathConnectionLayer[DAT_ViewportRenderState::instance.translationMatrix[fromY].addXgetTile + fromX] + != DAT_TileMapState::instance.PathConnectionLayer[destTile]) { + return 0; + } + this->ALG_ResultTileIndex = 0; + int const closestTileMode = (DAT_TileMapState::instance.LogicLayer[destTile] & 0x100) != 0 ? 1 : 2; + MACRO_CALL_MEMBER(Navigation::PathFindingState_Func::findLinkageBasedPathOrWalkRadius, + DAT_PathFindingState::ptr)(destX, destY, -1, -1, 500, FALSE); + for (;;) { + if (unitSelectionIndex >= this->tribes[tribeID].size) { + return 1; + } + int const unitID = MACRO_CALL_MEMBER( + OpenSHC::Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)(tribeID, unitSelectionIndex); + ++unitSelectionIndex; + if (DAT_UnitsState::instance.units[unitID].logicalState != ULS_NORMAL + || DAT_UnitsState::instance.units[unitID].dying != 0) { + continue; + } + int const tileUnk = MACRO_CALL_MEMBER(Navigation::PathFindingState_Func::findClosestTileToStartingTile, + DAT_PathFindingState::ptr)(closestTileMode); + ++this->ALG_ResultTileIndex; + if ((int)this->ALG_ResultTileIndex >= 500) { + return 0; + } + int const occupantUnitID = (short)DAT_TileMapState::instance.UnitLayer[tileUnk]; + if (occupantUnitID != 0 && unitID != occupantUnitID + && DAT_UnitsState::instance.units[occupantUnitID].tribeID != tribeID + && DAT_UnitsState::instance.units[occupantUnitID].tunnelerFinishedDigging != 2) { + return 0; + } + } + } + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/isTribeUnitBlockedByOtherUnit.cpp b/src/OpenSHC/Map/Units/TribesState/isTribeUnitBlockedByOtherUnit.cpp new file mode 100644 index 0000000000..3d9b2fd5d1 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/isTribeUnitBlockedByOtherUnit.cpp @@ -0,0 +1,56 @@ +#include "../TribesState.func.hpp" + +#include "OpenSHC/Map/Units/States/UnitState.hpp" +#include "OpenSHC/Map/Units/UnitLogicState.hpp" + +#include "OpenSHC/Globals/DAT_TileMapState.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + // FUNCTION: STRONGHOLDCRUSADER 0x00524B30 + BOOLEnum TribesState::isTribeUnitBlockedByOtherUnit(int tribeID) + { + int index = 0; + int const size = this->tribes[tribeID].size; + // a `continue` lets MSVC rotate the loop and copy the size test; the label before the loop keeps one test + nextUnit: + for (;;) { + if (index >= size) { + return FALSE; + } + int const unitID = MACRO_CALL_MEMBER(TribesState_Func::getUnitIDForIndexInTribe, this)(tribeID, index); + index++; + if (DAT_UnitsState::instance.units[unitID].logicalState != ULS_NORMAL + || DAT_UnitsState::instance.units[unitID].dying) { + goto nextUnit; + } + if (DAT_UnitsState::instance.units[unitID].usingTeleport) { + return FALSE; + } + if (DAT_UnitsState::instance.units[unitID].field_0x413) { + return FALSE; + } + if (DAT_UnitsState::instance.units[unitID].tunnelerFinishedDigging == 2) { + return FALSE; + } + if (DAT_UnitsState::instance.units[unitID].state.generic == States::US_MELEE_ATTACK) { + return FALSE; + } + if (DAT_UnitsState::instance.units[unitID].laddermanIsInPosition) { + return FALSE; + } + int const otherUnitID + = DAT_TileMapState::instance.UnitLayer[DAT_UnitsState::instance.units[unitID].tile]; + if (otherUnitID != 0 && unitID != otherUnitID + && DAT_UnitsState::instance.units[otherUnitID].tunnelerFinishedDigging != 2) { + return TRUE; + } + } + } + + } // namespace Units +} // namespace Map +} // namespace OpenSHC diff --git a/src/OpenSHC/Map/Units/TribesState/moveTribeToIndexedNearbyTile.cpp b/src/OpenSHC/Map/Units/TribesState/moveTribeToIndexedNearbyTile.cpp new file mode 100644 index 0000000000..f084e11e78 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/moveTribeToIndexedNearbyTile.cpp @@ -0,0 +1,61 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/Units/Instructions/UnitMatchSpeedEnum.hpp" + +#include "OpenSHC/Globals/DAT_UnitSelectionDefinedData.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" +#include "OpenSHC/Globals/DAT_ViewportRenderState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Map::Units::Instructions::UnitMatchSpeedEnum; + + /* + Returns nothing: the value left in EAX is the quotient of the idiv on the early + exit, the y coordinate or the path test's 0 at the end of the search, and the + only caller (updateTribeCombatStanceBehavior, 0x52AC9A) ignores it. + + The candidate count is a variable, not a literal: with `% 40` MSVC emits a + reciprocal multiply, while the original divides with `mov ecx, 0x28; idiv ecx`. + + Remaining gap (98.6%): MSVC turns the index into a pointer and ends the loop at + `&field_0xcc4[40].y`, a relocation against our data, where the original has the + plain address 0xb4df44. Writing that address as a literal matches, but it is + only right while the data stays at the original address, so the index stays. + */ + // FUNCTION: STRONGHOLDCRUSADER 0x0052A700 + void TribesState::moveTribeToIndexedNearbyTile(int tribeID) + { + int const targetUnitID = this->tribes[tribeID].selectionTargetUnitID; + int const x = DAT_UnitsState::instance.units[targetUnitID].x; + int const y = DAT_UnitsState::instance.units[targetUnitID].y; + int const someIndex = this->tribes[tribeID].someIndex; + int count = 40; + int index = someIndex % count; + if (index <= 0) { + index = 0; + } else if (index >= count) { + return; + } + do { + uint const x1 = DAT_UnitSelectionDefinedData::instance.field_0xcc4[index].x + x; + uint const y1 = DAT_UnitSelectionDefinedData::instance.field_0xcc4[index].y + y; + if (x1 <= 399 && y1 <= 399 + && DAT_ViewportRenderState::instance.DAT_BinaryTileMap400x400[y1 * 400 + x1] != 0) { + if (MACRO_CALL_MEMBER(Map::Units::TribesState_Func::isTribePathToDestinationClear, this)( + tribeID, x, y, x1, y1)) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::giveTribeMoveInstruction, this)( + tribeID, x1, y1, 0, 0, Map::Units::Instructions::UMSE_0); + return; + } + } + ++index; + } while (index < count); + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/moveUnitToBehaviorTarget.cpp b/src/OpenSHC/Map/Units/TribesState/moveUnitToBehaviorTarget.cpp new file mode 100644 index 0000000000..fc2f366a67 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/moveUnitToBehaviorTarget.cpp @@ -0,0 +1,147 @@ +#include "../../../Map.func.hpp" +#include "../TribesState.func.hpp" + +#include "OpenSHC/Map/Units/TroopValueState.func.hpp" +#include "OpenSHC/Map/Units/UnitsState.func.hpp" +#include "OpenSHC/Map/Units/SomeTribeBehaviorType.hpp" +#include "OpenSHC/Map/Units/States/UnitState.hpp" +#include "OpenSHC/Map/Units/UnitLogicState.hpp" + +#include "OpenSHC/Globals/DAT_GameSynchronyState.hpp" +#include "OpenSHC/Globals/DAT_TribesState.hpp" +#include "OpenSHC/Globals/DAT_TroopValueState.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" +#include "OpenSHC/Globals/DAT_ViewportRenderState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Map::Units::SomeTribeBehaviorType; + using Map::Units::UnitLogicState; + using Map::Units::States::UnitState; + + /* + Each arm stores y, x, tile and the found flag itself. The compiler merges the + x, tile and found stores into one shared tail, which is what the original + shows. Those four stores per arm are also what puts x, tile and found in + registers ahead of unitID. When the arms jumped to one shared assignment + instead, unitID took ebx and the function measured 37.1%. tribeID is read after + the four locals are declared so that its stack store follows y's. + */ + // FUNCTION: STRONGHOLDCRUSADER 0x00521280 + BOOLEnum TribesState::moveUnitToBehaviorTarget(int unitID, int param_2) + { + uint y = 0; + uint x = 0; + uint tile = 0; + BOOL found = FALSE; + int const tribeID = DAT_UnitsState::instance.units[unitID].tribeID; + if (DAT_UnitsState::instance.units[unitID].logicalState != Map::Units::ULS_NORMAL + || DAT_UnitsState::instance.units[unitID].dying != 0 + || DAT_UnitsState::instance.units[unitID].usingTeleport != 0 + || DAT_UnitsState::instance.units[unitID].field_0x413 != 0 + || DAT_GameSynchronyState::instance + .currentPlayerFullIDArray[DAT_UnitsState::instance.units[unitID].owner] + != -1) { + return FALSE; + } + if (param_2 == 0x3f2) { + if (MACRO_CALL_MEMBER(Map::Units::TroopValueState_Func::findEnemyWalls, DAT_TroopValueState::ptr)( + unitID)) { + x = DAT_TroopValueState::instance.x; + y = DAT_TroopValueState::instance.y; + tile = DAT_TroopValueState::instance.tile; + found = TRUE; + } + } else if (param_2 == 0x3f5) { + if (MACRO_CALL_MEMBER(Map::Units::TroopValueState_Func::findEnemyBuildingsClosestToUnit, + DAT_TroopValueState::ptr)(unitID)) { + x = DAT_TroopValueState::instance.x; + y = DAT_TroopValueState::instance.y; + tile = DAT_TroopValueState::instance.tile; + found = TRUE; + } + } else if (param_2 == 0x3fb) { + if (MACRO_CALL_MEMBER(Map::Units::TroopValueState_Func::calculateTile2PeoplValueClosestToUnit, + DAT_TroopValueState::ptr)(unitID)) { + x = DAT_TroopValueState::instance.x; + y = DAT_TroopValueState::instance.y; + tile = DAT_TroopValueState::instance.tile; + found = TRUE; + } else if (MACRO_CALL_MEMBER( + Map::Units::TroopValueState_Func::findEnemyWalls, DAT_TroopValueState::ptr)(unitID)) { + if (this->tribes[tribeID].selectionTargetUnitID == unitID) { + DAT_TribesState::instance.tribes[tribeID].tribeBehaviorType = Map::Units::STBT_0x3f2; + } + DAT_UnitsState::instance.units[unitID].unknownDigMoatOrWallAttackFlag1015 = 0x3f2; + x = DAT_TroopValueState::instance.x; + y = DAT_TroopValueState::instance.y; + tile = DAT_TroopValueState::instance.tile; + found = TRUE; + } + } else if (param_2 == 0x3fd) { + if (MACRO_CALL_MEMBER(Map::Units::TroopValueState_Func::findEnemyLord, DAT_TroopValueState::ptr)( + unitID)) { + x = DAT_TroopValueState::instance.x; + y = DAT_TroopValueState::instance.y; + tile = DAT_TroopValueState::instance.tile; + found = TRUE; + } + } else if (param_2 == 0x3f6) { + if (MACRO_CALL_MEMBER( + Map::Units::TroopValueState_Func::findEnemyTowersOrGates, DAT_TroopValueState::ptr)(unitID)) { + x = DAT_TroopValueState::instance.x; + y = DAT_TroopValueState::instance.y; + tile = DAT_TroopValueState::instance.tile; + found = TRUE; + } + } else if (param_2 == 0x413) { + if (MACRO_CALL_MEMBER(Map::Units::TroopValueState_Func::getClosestWideValueBasedOnPlayer, + DAT_TroopValueState::ptr)(unitID)) { + x = DAT_TroopValueState::instance.x; + y = DAT_TroopValueState::instance.y; + tile = DAT_TroopValueState::instance.tile; + found = TRUE; + } + } else if (param_2 == 0x414) { + if (MACRO_CALL_MEMBER(Map::Units::TroopValueState_Func::getClosestWideValueBasedOnPlayer, + DAT_TroopValueState::ptr)(unitID)) { + x = DAT_TroopValueState::instance.x; + y = DAT_TroopValueState::instance.y; + tile = DAT_TroopValueState::instance.tile; + found = TRUE; + } + } else if (param_2 == 0x3f7) { + if (MACRO_CALL_MEMBER(Map::Units::TroopValueState_Func::findNearestDiggableMoatPoint, + DAT_TroopValueState::ptr)(unitID)) { + x = DAT_TroopValueState::instance.x; + y = DAT_TroopValueState::instance.y; + tile = DAT_TroopValueState::instance.tile; + found = TRUE; + } + } + DAT_UnitsState::instance.units[unitID].targetedBuildingTile = 0; + if (!found) { + return FALSE; + } + short const tileY = DAT_ViewportRenderState::instance.tileTranslationMatrix_YComponent[tile]; + DAT_UnitsState::instance.units[unitID].attackAtTileY = tileY; + DAT_UnitsState::instance.units[unitID].targetedBuildingTile = tile; + DAT_UnitsState::instance.units[unitID].state.generic = Map::Units::States::US_MOVE_TO_DESTINATION; + DAT_UnitsState::instance.units[unitID].attackAtTileX + = (short)tile - (short)DAT_ViewportRenderState::instance.translationMatrix[tileY].addXgetTile; + if (DAT_UnitsState::instance.units[unitID].selectionTargetUnitID == unitID) { + this->tribes[tribeID].targetX = DAT_UnitsState::instance.units[unitID].attackAtTileX; + this->tribes[tribeID].targetY = DAT_UnitsState::instance.units[unitID].attackAtTileY; + } + if (!MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::stopUnitIfNextToTarget, DAT_UnitsState::ptr)(unitID)) { + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::setDestinationForUnit, DAT_UnitsState::ptr)( + unitID, x, y, 0); + } + return TRUE; + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/playAttackCommandFeedback.cpp b/src/OpenSHC/Map/Units/TribesState/playAttackCommandFeedback.cpp new file mode 100644 index 0000000000..80d4fa03f9 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/playAttackCommandFeedback.cpp @@ -0,0 +1,41 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Audio/SFX/SFXState.func.hpp" +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/Units/UnitsState.func.hpp" +#include "OpenSHC/Map/Units/UnitType.hpp" + +#include "OpenSHC/Globals/DAT_SFXState.hpp" +#include "OpenSHC/Globals/DAT_TribesState.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Map::Units::UnitType; + + // FUNCTION: STRONGHOLDCRUSADER 0x00522090 + void TribesState::playAttackCommandFeedback(int param_1) + { + int iVar1 = param_1; + MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::selectionContainsCombatUnit, DAT_UnitsState::ptr)(1); + UnitType unitType + = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getMajoritySelectedUnitType, this)(iVar1, ¶m_1); + if (unitType == Map::Units::UT_S_BATTERINGRAM || unitType == Map::Units::UT_S_CATAPULT + || unitType == Map::Units::UT_S_TREBUCHET || unitType == Map::Units::UT_S_MANGONEL + || unitType == Map::Units::UT_S_BALLISTA || unitType == Map::Units::UT_S_FBALLISTA) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::playUnitMoveSpeech, this)( + DAT_TribesState::instance.DAT_CurrentTribeID); + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::playUnitSelectionSound, this)(iVar1); + } else { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeech, DAT_SFXState::ptr)(unitType, 0x15); + if (unitType != Map::Units::UT_E_ENGINEER) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::playUnitSelectionSound, this)(iVar1); + } + } + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/playUnitCombatSpeechForTarget.cpp b/src/OpenSHC/Map/Units/TribesState/playUnitCombatSpeechForTarget.cpp new file mode 100644 index 0000000000..c44cf924da --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/playUnitCombatSpeechForTarget.cpp @@ -0,0 +1,196 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Audio/SFX/SFXState.func.hpp" +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/Units/UnitsState.func.hpp" +#include "OpenSHC/Map/Units/UnitType.hpp" +#include "OpenSHC/Map/Units/UnitTypeInt.hpp" + +#include "OpenSHC/Globals/DAT_EntityDefinedData.hpp" +#include "OpenSHC/Globals/DAT_SFXState.hpp" +#include "OpenSHC/Globals/DAT_TribesState.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Map::Units::UnitType; + using Map::Units::UnitTypeInt; + + // FUNCTION: STRONGHOLDCRUSADER 0x00521A90 + void TribesState::playUnitCombatSpeechForTarget(int selectionID, int unitID) + { + int selectedCount; + int const otherUnitID + = MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::selectionContainsCombatUnit, DAT_UnitsState::ptr)(1); + UnitTypeInt const unitType = MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::getMajoritySelectedUnitType, this)(selectionID, &selectedCount); + int const tribeSize = DAT_TribesState::instance.tribes[selectionID].size; + switch (unitType) { + case Map::Units::UT_E_ARCHER: + case Map::Units::UT_E_XBOW: + case Map::Units::UT_A_ARCHER: + case Map::Units::UT_A_SLINGER: + case Map::Units::UT_A_HARCHER: + case Map::Units::UT_A_FIRETHROWER: { + int range; + if (unitType == Map::Units::UT_E_ARCHER) { + range = DAT_EntityDefinedData::instance.EntityTypeArrayForProjectileRange[1] + * DAT_EntityDefinedData::instance.EntityTypeArrayForProjectileRange[1]; + } else if (unitType == Map::Units::UT_E_XBOW) { + range = DAT_EntityDefinedData::instance.EntityTypeArrayForProjectileRange[7] + * DAT_EntityDefinedData::instance.EntityTypeArrayForProjectileRange[7]; + } else if (unitType == Map::Units::UT_A_ARCHER) { + range = DAT_EntityDefinedData::instance.EntityTypeArrayForProjectileRange[1] + * DAT_EntityDefinedData::instance.EntityTypeArrayForProjectileRange[1]; + } else if (unitType == Map::Units::UT_A_SLINGER) { + range = DAT_EntityDefinedData::instance.EntityTypeArrayForProjectileRange[0x21] + * DAT_EntityDefinedData::instance.EntityTypeArrayForProjectileRange[0x21]; + } else if (unitType == Map::Units::UT_A_HARCHER) { + range = DAT_EntityDefinedData::instance.EntityTypeArrayForProjectileRange[1] + * DAT_EntityDefinedData::instance.EntityTypeArrayForProjectileRange[1]; + } else if (unitType == Map::Units::UT_A_FIRETHROWER) { + range = DAT_EntityDefinedData::instance.EntityTypeArrayForProjectileRange[0x22] + * DAT_EntityDefinedData::instance.EntityTypeArrayForProjectileRange[0x22]; + } else { + range = unitID; + } + int const otherX = DAT_UnitsState::instance.units[otherUnitID].x; + int const otherY = DAT_UnitsState::instance.units[otherUnitID].y; + int const unitX = DAT_UnitsState::instance.units[unitID].x; + int const unitY = DAT_UnitsState::instance.units[unitID].y; + if ((otherX - unitX) * (otherX - unitX) + (otherY - unitY) * (otherY - unitY) > range) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeech, DAT_SFXState::ptr)( + (UnitType)unitType, 0x1e); + } else { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeech, DAT_SFXState::ptr)( + (UnitType)unitType, 0x19); + } + if (unitType != Map::Units::UT_A_HARCHER) { + return; + } + if (selectedCount == 1) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[otherUnitID].x, DAT_UnitsState::instance.units[otherUnitID].y, + 0xea); + } else if (selectedCount <= 4) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[otherUnitID].x, DAT_UnitsState::instance.units[otherUnitID].y, + 0xeb); + } else { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[otherUnitID].x, DAT_UnitsState::instance.units[otherUnitID].y, + 0xec); + } + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[otherUnitID].x, DAT_UnitsState::instance.units[otherUnitID].y, 0x59); + return; + } + case Map::Units::UT_E_KNIGHT: { + int const count = selectedCount; + if (count == 1) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[otherUnitID].x, DAT_UnitsState::instance.units[otherUnitID].y, + 0x56); + } else { + if (count == 2 || count == 3) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[otherUnitID].x, + DAT_UnitsState::instance.units[otherUnitID].y, 0x57); + } + if (count >= 4) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[otherUnitID].x, + DAT_UnitsState::instance.units[otherUnitID].y, 0x58); + } + } + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[otherUnitID].x, DAT_UnitsState::instance.units[otherUnitID].y, 0x59); + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeech, DAT_SFXState::ptr)( + (UnitType)unitType, 0x15); + if (tribeSize >= 0xf) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[otherUnitID].x, DAT_UnitsState::instance.units[otherUnitID].y, + 0xfa); + } + return; + } + case Map::Units::UT_E_SWORD: + if (selectedCount == 1) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[otherUnitID].x, DAT_UnitsState::instance.units[otherUnitID].y, + 0xad); + } else if (selectedCount == 2) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[otherUnitID].x, DAT_UnitsState::instance.units[otherUnitID].y, + 0xae); + } else if (selectedCount >= 3) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[otherUnitID].x, DAT_UnitsState::instance.units[otherUnitID].y, + 0xaf); + } + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeech, DAT_SFXState::ptr)( + (UnitType)unitType, 0x15); + if (tribeSize >= 0xf) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[otherUnitID].x, DAT_UnitsState::instance.units[otherUnitID].y, + 0x14); + } + return; + case Map::Units::UT_E_SPEAR: + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeech, DAT_SFXState::ptr)( + (UnitType)unitType, 0x15); + if (tribeSize >= 0xf) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[otherUnitID].x, DAT_UnitsState::instance.units[otherUnitID].y, + 0x14); + } + return; + case Map::Units::UT_E_PIKE: + case Map::Units::UT_E_MACE: + case Map::Units::UT_E_MONK: { + UnitTypeShort const targetType = DAT_UnitsState::instance.units[unitID].unitType; + if (targetType == Map::Units::UT_E_KNIGHT || targetType == Map::Units::UT_E_SWORD + || targetType == Map::Units::UT_LORD) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeech, DAT_SFXState::ptr)( + (UnitType)unitType, 0x11); + } else { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeech, DAT_SFXState::ptr)( + (UnitType)unitType, 0x15); + } + if (tribeSize >= 0xf) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[otherUnitID].x, DAT_UnitsState::instance.units[otherUnitID].y, + 0x14); + } + return; + } + case Map::Units::UT_A_SWORDSMAN: + if (tribeSize >= 0xf) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[otherUnitID].x, DAT_UnitsState::instance.units[otherUnitID].y, + 0x14); + } + return; + default: { + UnitTypeShort const targetType = DAT_UnitsState::instance.units[unitID].unitType; + if (targetType != Map::Units::UT_E_KNIGHT && targetType != Map::Units::UT_E_SWORD + && targetType != Map::Units::UT_E_MACE && targetType != Map::Units::UT_E_PIKE + && targetType != Map::Units::UT_LORD) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeech, DAT_SFXState::ptr)( + (UnitType)unitType, 0x15); + return; + } + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeech, DAT_SFXState::ptr)( + (UnitType)unitType, 0x11); + return; + } + case Map::Units::UT_E_ENGINEER: + return; + } + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/playUnitMoveSpeech.cpp b/src/OpenSHC/Map/Units/TribesState/playUnitMoveSpeech.cpp new file mode 100644 index 0000000000..3b36132aaf --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/playUnitMoveSpeech.cpp @@ -0,0 +1,118 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Audio/SFX/SFXState.func.hpp" +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/Units/UnitsState.func.hpp" +#include "OpenSHC/Audio/SFX/SpeechEffectID.hpp" + +#include "OpenSHC/Globals/DAT_SFXState.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Audio::SFX::SpeechEffectID; + + /* + When a catapult or trebuchet has no stone, the original plays only the + out-of-ammunition speech and returns: it tail-calls playSpeechSFX and never + reaches the unit speech. The import played both. + */ + // FUNCTION: STRONGHOLDCRUSADER 0x00521EF0 + void TribesState::playUnitMoveSpeech(undefined4 param_1) + { + int _unitID; + UnitType _unitTypeID; + _unitID + = MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::selectionContainsCombatUnit, DAT_UnitsState::ptr)(1); + /* + The selected count is written into a block-scoped local that nothing reads + afterwards. MSVC packs it into the parameter's home, and because its scope has + ended, the two out-of-ammunition plays can be tail calls (`mov [esp + 4], 0x2e; + jmp playSpeechSFX`). Passing `¶m_1` keeps an address-taken variable alive + and blocks the tail call. + */ + { + int selectedCount; + _unitTypeID = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getMajoritySelectedUnitType, this)( + param_1, &selectedCount); + } + switch (_unitTypeID) { + case Map::Units::UT_E_ARCHER: + case Map::Units::UT_E_XBOW: + case Map::Units::UT_A_ARCHER: + case Map::Units::UT_A_SLINGER: + case Map::Units::UT_A_HARCHER: + case Map::Units::UT_A_FIRETHROWER: + /* + Any other ranged unit + */ + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeech, DAT_SFXState::ptr)(_unitTypeID, 0x1d); + return; + case Map::Units::UT_S_CATAPULT: + /* + Catapult + */ + if (DAT_UnitsState::instance.units[_unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + != 0) { + if (DAT_UnitsState::instance.units[_unitID].stoneAmmunition < 1) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSpeechSFX, DAT_SFXState::ptr)( + Audio::SFX::SEID_RESOURCE_NEED25); + return; + } + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeech, DAT_SFXState::ptr)(_unitTypeID, 0x10); + } + break; + case Map::Units::UT_S_TREBUCHET: + /* + Trebuchet + */ + if (DAT_UnitsState::instance.units[_unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + != 0) { + if (DAT_UnitsState::instance.units[_unitID].stoneAmmunition < 1) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSpeechSFX, DAT_SFXState::ptr)( + Audio::SFX::SEID_RESOURCE_NEED25); + return; + } + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeech, DAT_SFXState::ptr)(_unitTypeID, 0x11); + } + break; + case Map::Units::UT_S_MANGONEL: + /* + Mangonel + */ + if (DAT_UnitsState::instance.units[_unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + != 0) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeech, DAT_SFXState::ptr)(_unitTypeID, 0xf); + } + break; + case Map::Units::UT_S_BALLISTA: + case Map::Units::UT_S_FBALLISTA: + /* + Ballista and fire ballista + */ + if (DAT_UnitsState::instance.units[_unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + != 0) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeech, DAT_SFXState::ptr)(_unitTypeID, 0x12); + } + break; + case Map::Units::UT_S_BATTERINGRAM: + /* + Battering ram + */ + if (DAT_UnitsState::instance.units[_unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + != 0) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeech, DAT_SFXState::ptr)(_unitTypeID, 0x13); + } + } + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/playUnitSelectionSound.cpp b/src/OpenSHC/Map/Units/TribesState/playUnitSelectionSound.cpp new file mode 100644 index 0000000000..094290195f --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/playUnitSelectionSound.cpp @@ -0,0 +1,137 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Audio/SFX/SFXState.func.hpp" +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/Units/UnitsState.func.hpp" +#include "OpenSHC/Map/Units/UnitType.hpp" + +#include "OpenSHC/Globals/DAT_SFXState.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Map::Units::UnitType; + + /* + Arms from the byte table at 0x521a60 (indexed by unitType - 0x1b) and the jump + table at 0x521a48: swordsman 0x521819, knight 0x5218aa, engineer 0x521a11, + catapult / tower / battering ram 0x521983, horse archer 0x521915, and every other + type the bare return at 0x521876. The import had the knight's arm on the ladderman, + the knight sharing the swordsman's arm, the miner on the engineer's arm and the + mangonel in place of the catapult. + */ + // FUNCTION: STRONGHOLDCRUSADER 0x005217E0 + void TribesState::playUnitSelectionSound(int param_1) + { + int const unitID + = MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::selectionContainsCombatUnit, DAT_UnitsState::ptr)(1); + { + /* + The selected count is address-taken, and MSVC does not tail-call while an + address-taken local is in scope. The siege and engineer arms end in tail + calls in the original, so they sit past the end of this block and the + switch reaches them through a goto. + */ + int selectedCount; + switch (MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getMajoritySelectedUnitType, this)( + param_1, &selectedCount)) { + case Map::Units::UT_E_SWORD: + if (selectedCount == 1) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[unitID].x, DAT_UnitsState::instance.units[unitID].y, 0xad); + } else if (selectedCount == 2) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[unitID].x, DAT_UnitsState::instance.units[unitID].y, 0xae); + } else if (selectedCount >= 3) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[unitID].x, DAT_UnitsState::instance.units[unitID].y, 0xaf); + } + return; + case Map::Units::UT_E_KNIGHT: { + int const count = selectedCount; + if (count == 1) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[unitID].x, DAT_UnitsState::instance.units[unitID].y, 0x56); + } else { + if (count == 2 || count == 3) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, + DAT_SFXState::ptr)(DAT_UnitsState::instance.units[unitID].x, + DAT_UnitsState::instance.units[unitID].y, 0x57); + } + if (count >= 4) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, + DAT_SFXState::ptr)(DAT_UnitsState::instance.units[unitID].x, + DAT_UnitsState::instance.units[unitID].y, 0x58); + } + } + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[unitID].x, DAT_UnitsState::instance.units[unitID].y, 0x59); + return; + } + case Map::Units::UT_A_HARCHER: { + if (selectedCount == 1) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[unitID].x, DAT_UnitsState::instance.units[unitID].y, 0xea); + } else if (selectedCount <= 4) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[unitID].x, DAT_UnitsState::instance.units[unitID].y, 0xeb); + } else { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[unitID].x, DAT_UnitsState::instance.units[unitID].y, 0xec); + } + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[unitID].x, DAT_UnitsState::instance.units[unitID].y, 0x59); + return; + } + case Map::Units::UT_S_CATAPULT: + case Map::Units::UT_S_TOWER: + case Map::Units::UT_S_BATTERINGRAM: + goto siegeEngine; + case Map::Units::UT_E_ENGINEER: + goto engineer; + default: + return; + } + } + siegeEngine: { + int const requiredEngineers = MACRO_CALL_MEMBER( + Map::Units::UnitsState_Func::getRemainingRequiredEngineers, DAT_UnitsState::ptr)(unitID); + if (requiredEngineers > 0) { + if (DAT_UnitsState::instance.units[unitID] + .digTileX__OR__countCurrentlyManningEnginers__OR__forCowsRandomBelow300 + == 0 + || requiredEngineers > 3) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeechEffect, DAT_SFXState::ptr)(0xe); + return; + } + if (requiredEngineers == 1) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeechEffect, DAT_SFXState::ptr)(0xb); + return; + } + if (requiredEngineers == 2) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeechEffect, DAT_SFXState::ptr)(0xc); + return; + } + if (requiredEngineers == 3) { + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeechEffect, DAT_SFXState::ptr)(0xd); + } + return; + } + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocationFullVolume, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[unitID].x, DAT_UnitsState::instance.units[unitID].y, 0x68); + return; + } + engineer: + if (DAT_UnitsState::instance.units[unitID].unitType != Map::Units::UT_E_ENGINEER) { + return; + } + if (DAT_UnitsState::instance.units[unitID].resourceToDeposit == 0) { + return; + } + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playUnitSpeechEffect, DAT_SFXState::ptr)(0x24); + } + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/predictUnitInterceptPosition.cpp b/src/OpenSHC/Map/Units/TribesState/predictUnitInterceptPosition.cpp new file mode 100644 index 0000000000..9045f69e59 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/predictUnitInterceptPosition.cpp @@ -0,0 +1,97 @@ +#include "../TribesState.func.hpp" + +#include "OpenSHC/Map/Units/UnitType.hpp" + +#include "OpenSHC/Globals/DAT_TerrainDefinedData.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" + +#include + +namespace OpenSHC { +namespace Map { + namespace Units { + + using OpenSHC::Map::Units::UnitType; + + // The path plan byte is read signed (movsx at 0x52169E) although pathPlanStart is declared byte. + // FUNCTION: STRONGHOLDCRUSADER 0x00521500 + void TribesState::predictUnitInterceptPosition( + int targetUnitID, int unitID, int* unitCurrentX, int* unitCurrentY) + { + *unitCurrentX = DAT_UnitsState::instance.units[unitID].x; + *unitCurrentY = DAT_UnitsState::instance.units[unitID].y; + if (DAT_UnitsState::instance.units[unitID].tunnelerFinishedDigging != 2) { + return; + } + short const targetSpeed + = this->tribes[DAT_UnitsState::instance.units[targetUnitID].tribeID].minimumMovementSpeed; + short const unitSpeed = this->tribes[DAT_UnitsState::instance.units[unitID].tribeID].minimumMovementSpeed; + int targetFactor = targetSpeed; + if (targetSpeed <= 1) { + targetFactor = 1; + } + targetFactor *= 4; + int unitStep = unitSpeed; + if (unitSpeed <= 1) { + unitStep = 1; + } + unitStep *= 4; + int const targetX = DAT_UnitsState::instance.units[targetUnitID].x; + int const targetY = DAT_UnitsState::instance.units[targetUnitID].y; + if (DAT_UnitsState::instance.units[targetUnitID].stateBasedSpeed > 0) { + targetFactor /= 2; + } else if (DAT_UnitsState::instance.units[targetUnitID].unitType == UT_E_KNIGHT + && !DAT_UnitsState::instance.units[targetUnitID].isMatchingSpeed) { + targetFactor /= 3; + } else if (DAT_UnitsState::instance.units[targetUnitID].unitType == UT_E_SWORD) { + targetFactor /= 2; + } + if (DAT_UnitsState::instance.units[unitID].stateBasedSpeed > 0) { + targetFactor /= 2; + } else if (DAT_UnitsState::instance.units[unitID].unitType == UT_E_KNIGHT + && !DAT_UnitsState::instance.units[unitID].isMatchingSpeed) { + targetFactor /= 3; + } else if (DAT_UnitsState::instance.units[unitID].unitType == UT_E_SWORD) { + targetFactor /= 2; + } + int distanceX = abs(*unitCurrentX - targetX); + int distance = abs(*unitCurrentY - targetY); + if (distanceX > distance) { + distance = distanceX; + } + if ((distance - 2) * targetFactor < 0) { + return; + } + int pathIndex = DAT_UnitsState::instance.units[unitID].currentIndexInPathPlan; + if (pathIndex >= DAT_UnitsState::instance.units[unitID].totalSizeOfPathPlan) { + return; + } + int cost = unitStep; + do { + int direction = (char)DAT_UnitsState::instance.units[unitID].pathPlanStart[pathIndex / 2]; + if (pathIndex & 1) { + direction >>= 4; + } else { + direction &= 0xf; + } + *unitCurrentX + = DAT_TerrainDefinedData::instance.clockwiseCardinalTranslationMatrix[direction].int_.xOffset + + *unitCurrentX; + *unitCurrentY + += DAT_TerrainDefinedData::instance.clockwiseCardinalTranslationMatrix[direction].int_.yOffset; + distanceX = abs(*unitCurrentX - targetX); + distance = abs(*unitCurrentY - targetY); + if (distanceX > distance) { + distance = distanceX; + } + if ((distance - 2) * targetFactor < cost) { + return; + } + cost += unitStep; + ++pathIndex; + } while (pathIndex < DAT_UnitsState::instance.units[unitID].totalSizeOfPathPlan); + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/processDeerMoving.cpp b/src/OpenSHC/Map/Units/TribesState/processDeerMoving.cpp new file mode 100644 index 0000000000..89875cb9a1 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/processDeerMoving.cpp @@ -0,0 +1,169 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Audio/SFX/SFXState.func.hpp" +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/WildlifeState.func.hpp" +#include "OpenSHC/DE/SHCDE/eSFX.hpp" +#include "OpenSHC/Map/Units/Instructions/UnitMatchSpeedEnum.hpp" +#include "OpenSHC/Map/Units/SomeTribeBehaviorType.hpp" +#include "OpenSHC/Map/Units/UnitType.hpp" +#include "OpenSHC/UI/Enums/MenuViewType.hpp" +#include "OpenSHC/WindowsHelper/Enums/BOOLEnum.hpp" + +#include "OpenSHC/Globals/DAT_GameCore.hpp" +#include "OpenSHC/Globals/DAT_SFXState.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" +#include "OpenSHC/Globals/DAT_WildlifeState.hpp" +#include "OpenSHC/Globals/SEC_RNG.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using DE::SHCDE::eSFX; + using Map::Units::SomeTribeBehaviorType; + using Map::Units::UnitType; + using Map::Units::Instructions::UnitMatchSpeedEnum; + using UI::Enums::MenuViewType; + using WindowsHelper::Enums::BOOLEnum; + + /* + The same family as updateCamelTribeBehavior and updateRabbitTribeBehavior: the + grid cell indexed in full at each read, each branch above the dispatch returning + on its own, and the rally-point reads indexed inline rather than through a local. + The three grid reads are in the order that gives the original's load order and + registers (rocky tiles, lion count, marsh tiles, then the add). + */ + // FUNCTION: STRONGHOLDCRUSADER 0x0052AD50 + void TribesState::processDeerMoving(int tribeID) + { + int const targetUnitID = this->tribes[tribeID].selectionTargetUnitID; + int const marshTiles = DAT_WildlifeState::instance + .grid[DAT_UnitsState::instance.units[targetUnitID].x / 10] + [DAT_UnitsState::instance.units[targetUnitID].y / 10] + .marshTiles; + int const rockyTiles = DAT_WildlifeState::instance + .grid[DAT_UnitsState::instance.units[targetUnitID].x / 10] + [DAT_UnitsState::instance.units[targetUnitID].y / 10] + .rockyTiles; + int const predatorCount = DAT_WildlifeState::instance + .grid[DAT_UnitsState::instance.units[targetUnitID].x / 10] + [DAT_UnitsState::instance.units[targetUnitID].y / 10] + .field_0x48 + + DAT_WildlifeState::instance + .grid[DAT_UnitsState::instance.units[targetUnitID].x / 10] + [DAT_UnitsState::instance.units[targetUnitID].y / 10] + .lionCount; + short const size = this->tribes[tribeID].size; + this->tribes[tribeID].unkIsAnimalTribe = 1; + if (size > 30) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::trimTribeToSize, this)(tribeID, 30); + this->tribes[tribeID].herdMinSize = 15; + this->tribes[tribeID].herdMaxSize = 60; + } else { + this->tribes[tribeID].herdMinSize = size / 2; + this->tribes[tribeID].herdMaxSize = size * 2; + } + if (predatorCount != 0 && this->tribes[tribeID].predatorNearby == 0) { + this->tribes[tribeID].predatorNearby = 1; + } + if (MACRO_CALL_MEMBER(Map::Units::TribesState_Func::spawnDeerLionOrRabbit, this)( + tribeID, 100, Map::Units::UT_ANTELOPESHDEER) + != FALSE) { + MACRO_CALL_MEMBER(Map::WildlifeState_Func::findAndSetNewRallyPointForDeerAndLions, + DAT_WildlifeState::ptr)(tribeID, 2, 0); + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::standUpAllTribeUnits, this)(tribeID); + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::giveTribeMoveInstruction, this)(tribeID, + this->tribes[tribeID].rallyPointArray[this->tribes[tribeID].currentRallyPointIndex][0], + this->tribes[tribeID].rallyPointArray[this->tribes[tribeID].currentRallyPointIndex][1], 0, 0, + Map::Units::Instructions::UMSE_0); + this->tribes[tribeID].currentRallyPointIndex = this->tribes[tribeID].currentRallyPointIndex + 1; + if (this->tribes[tribeID].currentRallyPointIndex >= this->tribes[tribeID].rallyPointCount) { + this->tribes[tribeID].rallyPointCount = 0; + this->tribes[tribeID].tribeBehaviorType = Map::Units::STBT_1; + } + return; + } + if (this->tribes[tribeID].initialMoveOrderGiven == 0) { + int const unitID = this->tribes[tribeID].selectionTargetUnitID; + this->tribes[tribeID].initialMoveOrderGiven = 1; + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::giveTribeMoveInstruction, this)(tribeID, + DAT_UnitsState::instance.units[unitID].x, DAT_UnitsState::instance.units[unitID].y, 0, 0, + Map::Units::Instructions::UMSE_0); + this->tribes[tribeID].tribeBehaviorType = Map::Units::STBT_1; + return; + } + if (DAT_GameCore::instance.currentMenuViewType == UI::Enums::MVT_MAP_EDITOR_LANDSCAPING) { + this->tribes[tribeID].unknownCounter01 = 0; + return; + } + ushort const predatorNearby = this->tribes[tribeID].predatorNearby; + if (predatorNearby != 0) { + if (predatorNearby == 1) { + MACRO_CALL_MEMBER(Map::WildlifeState_Func::findAndSetNewRallyPointForDeerAndLions, + DAT_WildlifeState::ptr)(tribeID, 5, 0); + if (this->tribes[tribeID].rallyPointCount <= 0) { + MACRO_CALL_MEMBER(Map::WildlifeState_Func::findAndSetNewRallyPointForDeerAndLions, + DAT_WildlifeState::ptr)(tribeID, 5, 1); + } + if (this->tribes[tribeID].rallyPointCount > 0) { + int const unitID = this->tribes[tribeID].selectionTargetUnitID; + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSFXAtLocation, DAT_SFXState::ptr)( + DAT_UnitsState::instance.units[unitID].x, DAT_UnitsState::instance.units[unitID].y, + DE::SHCDE::FX_DEER_RUN); + MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::giveUnitSelectionMoveInstructionNoMatchedSpeed, this)(tribeID, + this->tribes[tribeID].rallyPointArray[this->tribes[tribeID].rallyPointCount - 1][0], + this->tribes[tribeID].rallyPointArray[this->tribes[tribeID].rallyPointCount - 1][1], 0, 0); + } else { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::scatterTribeUnitsRandomly, this)(tribeID); + } + } + this->tribes[tribeID].predatorNearby = this->tribes[tribeID].predatorNearby + 1; + if ((short)this->tribes[tribeID].predatorNearby >= 800) { + this->tribes[tribeID].predatorNearby = 0; + } + return; + } + if (this->tribes[tribeID].tribeBehaviorType == (SomeTribeBehaviorType)0) { + if (marshTiles != 0) { + this->tribes[tribeID].wanderIntervalTicks = 200; + } + if (rockyTiles > 20) { + this->tribes[tribeID].wanderIntervalTicks = 200; + } + this->tribes[tribeID].unknownAttackRelatedUpdateCounter + = this->tribes[tribeID].unknownAttackRelatedUpdateCounter + 1; + if ((short)this->tribes[tribeID].unknownAttackRelatedUpdateCounter + >= this->tribes[tribeID].wanderIntervalTicks) { + this->tribes[tribeID].unknownAttackRelatedUpdateCounter = 0; + this->tribes[tribeID].wanderIntervalTicks = (4 - (SEC_RNG::instance.currentNumber2 & 3)) * 200; + if (this->tribes[tribeID].rallyPointCount <= 0) { + MACRO_CALL_MEMBER(Map::WildlifeState_Func::findAndSetNewRallyPointForDeerAndLions, + DAT_WildlifeState::ptr)(tribeID, 5, 0); + return; + } + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::standUpAllTribeUnits, this)(tribeID); + MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::giveUnitSelectionMoveInstructionNoMatchedSpeed, this)(tribeID, + this->tribes[tribeID].rallyPointArray[this->tribes[tribeID].currentRallyPointIndex][0], + this->tribes[tribeID].rallyPointArray[this->tribes[tribeID].currentRallyPointIndex][1], 0, 0); + this->tribes[tribeID].currentRallyPointIndex = this->tribes[tribeID].currentRallyPointIndex + 1; + if (this->tribes[tribeID].currentRallyPointIndex >= this->tribes[tribeID].rallyPointCount) { + this->tribes[tribeID].tribeBehaviorType = Map::Units::STBT_1; + this->tribes[tribeID].rallyPointCount = 0; + } + } + } else if (this->tribes[tribeID].tribeBehaviorType == Map::Units::STBT_1) { + this->tribes[tribeID].unknownAttackRelatedUpdateCounter + = this->tribes[tribeID].unknownAttackRelatedUpdateCounter + 1; + if (this->tribes[tribeID].unknownAttackRelatedUpdateCounter == 800) { + this->tribes[tribeID].unknownAttackRelatedUpdateCounter = 0; + this->tribes[tribeID].tribeBehaviorType = (SomeTribeBehaviorType)0; + } + } + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/removeUnitFromThisTribeIfInTribe.cpp b/src/OpenSHC/Map/Units/TribesState/removeUnitFromThisTribeIfInTribe.cpp new file mode 100644 index 0000000000..07100c0ee7 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/removeUnitFromThisTribeIfInTribe.cpp @@ -0,0 +1,54 @@ +#include "../../../Map.func.hpp" +#include "../TribesState.func.hpp" + +#include "OpenSHC/Globals/DAT_UnitSelectionDefinedData.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + // FUNCTION: STRONGHOLDCRUSADER 0x00522630 + void TribesState::removeUnitFromThisTribeIfInTribe(uint unitID, int tribeID) + { + /* + The import had this guard with an empty body; the original returns. Like + removeUnitFromTribe, unitID is divided and taken modulo as a signed int, and + the selection-bit test is a 32-bit `test` of a movsx'd field against a + movzx'd mask. + */ + if (DAT_UnitsState::instance.units[unitID].tribeID == 0 + && ((int)this->tribes[tribeID].unitSelectionBitMasked[(int)unitID / 16] + & (int)DAT_UnitSelectionDefinedData::instance.BitMaskHelper[(int)unitID % 16]) + == 0) { + return; + } + short const _size = this->tribes[tribeID].size; + if (0 < _size) { + this->tribes[tribeID].size = _size - 1; + } + if (this->tribes[tribeID].size <= 0) { + this->tribes[tribeID].tribeState = 3; + } + /* + The word index and the bit index get a local each before the compound + assignment: the original divides before it multiplies the tribe ID, which + frees ebp to keep the tribe's base for the reads after it. + */ + int const wordIndex = (int)unitID / 16; + int const bitIndex = (int)unitID % 16; + this->tribes[tribeID].unitSelectionBitMasked[wordIndex] + &= DAT_UnitSelectionDefinedData::instance.BitMaskHelper2[bitIndex]; + if (DAT_UnitsState::instance.units[unitID].tribeID == tribeID) { + DAT_UnitsState::instance.units[unitID].selectionTargetUnitID = 0; + DAT_UnitsState::instance.units[unitID].tribeID = 0; + DAT_UnitsState::instance.units[unitID].idInTribe = 0; + } + if ((int)this->tribes[tribeID].selectionTargetUnitID == unitID) { + this->tribes[tribeID].selectionTargetUnitID = -1; + } + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/removeUnitFromTribe.cpp b/src/OpenSHC/Map/Units/TribesState/removeUnitFromTribe.cpp new file mode 100644 index 0000000000..130d335eaf --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/removeUnitFromTribe.cpp @@ -0,0 +1,55 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Map/Units/TribesState.func.hpp" + +#include "OpenSHC/Globals/DAT_UnitSelectionDefinedData.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + // FUNCTION: STRONGHOLDCRUSADER 0x00525A70 + void TribesState::removeUnitFromTribe(uint unitID, int tribeID) + { + /* + unitID is divided and taken modulo as a signed int: the original biases the + dividend (`cdq; and edx, 0xf; add; sar 4`) and repairs the negative remainder + (`and -0x7ffffff1; jns; dec; or -0x10; inc`), neither of which an unsigned + operand needs. + */ + if (DAT_UnitsState::instance.units[unitID].tribeID != 0 + || ((int)this->tribes[tribeID].unitSelectionBitMasked[(int)unitID / 16] + & (int)DAT_UnitSelectionDefinedData::instance.BitMaskHelper[(int)unitID % 16]) + != 0) { + short const _size = this->tribes[tribeID].size; + if (0 < _size) { + this->tribes[tribeID].size = _size - 1; + } + if (this->tribes[tribeID].size <= 0) { + this->tribes[tribeID].tribeState = 3; + } + /* + The word index and the bit index get a local each before the compound + assignment: the original divides before it multiplies the tribe ID, + which frees ebp to keep the tribe's base for the reads after it. + */ + int const wordIndex = (int)unitID / 16; + int const bitIndex = (int)unitID % 16; + this->tribes[tribeID].unitSelectionBitMasked[wordIndex] + &= DAT_UnitSelectionDefinedData::instance.BitMaskHelper2[bitIndex]; + if (DAT_UnitsState::instance.units[unitID].tribeID == tribeID) { + DAT_UnitsState::instance.units[unitID].selectionTargetUnitID = 0; + DAT_UnitsState::instance.units[unitID].tribeID = 0; + DAT_UnitsState::instance.units[unitID].idInTribe = 0; + } + if ((int)this->tribes[tribeID].selectionTargetUnitID == unitID) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::setTargetUnitForTribe, this)(tribeID); + } + } + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::setWhetherTribeContainsAnyUnits, this)(tribeID); + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/snapshotSelectionTribeAndComputeStance.cpp b/src/OpenSHC/Map/Units/TribesState/snapshotSelectionTribeAndComputeStance.cpp new file mode 100644 index 0000000000..0494e3727c --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/snapshotSelectionTribeAndComputeStance.cpp @@ -0,0 +1,59 @@ +#include "../TribesState.func.hpp" + +#include "OpenSHC/Map/Units/Behavior/UnitStanceEnum.hpp" +#include "OpenSHC/Map/Units/UnitLogicState.hpp" + +#include "OpenSHC/Globals/DAT_UnitsState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using OpenSHC::Map::Units::Behavior::USE_AGGRESSIVE; + using OpenSHC::Map::Units::Behavior::USE_STAND_GROUND; + + // maxUnitCount (uint) is compared signed (jle at 0x522CCF). The stance counter array is indexed with the + // tribe's unitStance without a range check (0x522D15). + // FUNCTION: STRONGHOLDCRUSADER 0x00522CA0 + void TribesState::snapshotSelectionTribeAndComputeStance(int playerID) + { + this->tribeCopiedToSlot0 = 0; + int stanceCount[3]; + stanceCount[0] = 0; + stanceCount[1] = 0; + stanceCount[2] = 0; + BOOL multipleTribes = FALSE; + int lastTribeID = -1; + for (int unitID = 1; unitID < (int)DAT_UnitsState::instance.maxUnitCount; ++unitID) { + if (DAT_UnitsState::instance.units[unitID].logicalState == ULS_NORMAL + && DAT_UnitsState::instance.units[unitID].dying == 0 + && DAT_UnitsState::instance.units[unitID].ifSelectedThenPlayerID == playerID) { + int const tribeID = DAT_UnitsState::instance.units[unitID].tribeID; + if (tribeID > 0) { + ++stanceCount[this->tribes[tribeID].unitStance]; + if (lastTribeID != -1 && tribeID != lastTribeID) { + multipleTribes = TRUE; + } + lastTribeID = tribeID; + } + } + } + if (lastTribeID != -1 && !multipleTribes) { + this->tribes[0] = this->tribes[lastTribeID]; + this->tribeCopiedToSlot0 = 1; + return; + } + if (stanceCount[2] + stanceCount[1] + stanceCount[0] != 0) { + if (stanceCount[2] >= stanceCount[1] && stanceCount[2] >= stanceCount[0]) { + this->tribes[0].unitStance = USE_AGGRESSIVE; + } else { + this->tribes[0].unitStance = stanceCount[1] >= stanceCount[0]; + } + } else { + this->tribes[0].unitStance = USE_STAND_GROUND; + } + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/sortTribePathDestinationsByCost.cpp b/src/OpenSHC/Map/Units/TribesState/sortTribePathDestinationsByCost.cpp new file mode 100644 index 0000000000..82e52a587c --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/sortTribePathDestinationsByCost.cpp @@ -0,0 +1,110 @@ +#include "../TribesState.func.hpp" + +#include "OpenSHC/Map/Navigation/PathFindingState.func.hpp" + +#include "OpenSHC/Globals/DAT_PathFindingState.hpp" +#include "OpenSHC/Globals/DAT_TileMapState.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + // A bubble-sort pass ends at the first entry whose tile2 is 0 or whose successor has tile1 or tile2 0 + // (0x524A30..0x524A4C); unreached entries (cost 10000000) are compacted out afterwards. + // FUNCTION: STRONGHOLDCRUSADER 0x00524930 + void TribesState::sortTribePathDestinationsByCost(int tribeIDThenSortIdx, int horseAndRamCount) + { + BOOLEnum const allAssassins = MACRO_CALL_MEMBER( + OpenSHC::Map::Units::TribesState_Func::isTribeAllAssassins, this)(tribeIDThenSortIdx); + int const selectionTargetUnitID = this->tribes[tribeIDThenSortIdx].selectionTargetUnitID; + int const x = DAT_UnitsState::instance.units[selectionTargetUnitID].x; + if (horseAndRamCount != 0) { + MACRO_CALL_MEMBER(Navigation::PathFindingState_Func::calculatePathKeepAndWallsGatesNotAllowed, + DAT_PathFindingState::ptr)( + x, DAT_UnitsState::instance.units[selectionTargetUnitID].y, -1, -1, 100000); + } else { + int const y = DAT_UnitsState::instance.units[selectionTargetUnitID].y; + if (allAssassins != FALSE) { + MACRO_CALL_MEMBER(Navigation::PathFindingState_Func::pathFindingWithBuildingsIncluded, + DAT_PathFindingState::ptr)(x, y, 0xffffffff, 0xffffffff, 100000, 0); + } else { + MACRO_CALL_MEMBER(Navigation::PathFindingState_Func::findLinkageBasedPathOrWalkRadius, + DAT_PathFindingState::ptr)(x, y, -1, -1, 100000, FALSE); + } + } + for (int i = 0; DAT_PathFindingState::instance.searchQueue.destinationsArray[i].tile1 != 0; ++i) { + int const tileUnk = DAT_PathFindingState::instance.searchQueue.destinationsArray[i].tile1; + if (DAT_TileMapState::instance.WalkLayer[tileUnk] == DAT_PathFindingState::instance.searchGeneration) { + DAT_PathFindingState::instance.searchQueue.destinationsArray[i].tile3OrAnotherHelper + = DAT_TileMapState::instance.CertainPathLayer[tileUnk]; + } else { + DAT_PathFindingState::instance.searchQueue.destinationsArray[i].tile3OrAnotherHelper = 10000000; + } + } + int swapped; + do { + tribeIDThenSortIdx = 0; + swapped = 0; + if (DAT_PathFindingState::instance.searchQueue.destinationsArray[0].tile1 == 0) { + break; + } + do { + int const tile2 = DAT_PathFindingState::instance.searchQueue.destinationsArray[tribeIDThenSortIdx] + .tile2OrAHelper; + if (tile2 == 0) { + break; + } + int const nextTile1 + = DAT_PathFindingState::instance.searchQueue.destinationsArray[tribeIDThenSortIdx + 1].tile1; + if (nextTile1 == 0) { + break; + } + int const nextTile2 + = DAT_PathFindingState::instance.searchQueue.destinationsArray[tribeIDThenSortIdx + 1] + .tile2OrAHelper; + if (nextTile2 == 0) { + break; + } + int const cost = DAT_PathFindingState::instance.searchQueue.destinationsArray[tribeIDThenSortIdx] + .tile3OrAnotherHelper; + int const nextCost + = DAT_PathFindingState::instance.searchQueue.destinationsArray[tribeIDThenSortIdx + 1] + .tile3OrAnotherHelper; + if (cost > nextCost) { + DAT_PathFindingState::instance.searchQueue.destinationsArray[tribeIDThenSortIdx + 1].tile1 + = DAT_PathFindingState::instance.searchQueue.destinationsArray[tribeIDThenSortIdx].tile1; + swapped = 1; + DAT_PathFindingState::instance.searchQueue.destinationsArray[tribeIDThenSortIdx].tile1 + = nextTile1; + DAT_PathFindingState::instance.searchQueue.destinationsArray[tribeIDThenSortIdx].tile2OrAHelper + = nextTile2; + DAT_PathFindingState::instance.searchQueue.destinationsArray[tribeIDThenSortIdx + 1] + .tile2OrAHelper = tile2; + DAT_PathFindingState::instance.searchQueue.destinationsArray[tribeIDThenSortIdx] + .tile3OrAnotherHelper = nextCost; + DAT_PathFindingState::instance.searchQueue.destinationsArray[tribeIDThenSortIdx + 1] + .tile3OrAnotherHelper = cost; + } + ++tribeIDThenSortIdx; + } while (DAT_PathFindingState::instance.searchQueue.destinationsArray[tribeIDThenSortIdx].tile1 != 0); + } while (swapped != 0); + int outCount = 0; + for (int i = 0; DAT_PathFindingState::instance.searchQueue.destinationsArray[i].tile1 != 0; ++i) { + if (DAT_PathFindingState::instance.searchQueue.destinationsArray[i].tile3OrAnotherHelper != 10000000) { + if (i != outCount) { + DAT_PathFindingState::instance.searchQueue.destinationsArray[outCount].tile1 + = DAT_PathFindingState::instance.searchQueue.destinationsArray[i].tile1; + DAT_PathFindingState::instance.searchQueue.destinationsArray[outCount].tile2OrAHelper + = DAT_PathFindingState::instance.searchQueue.destinationsArray[i].tile2OrAHelper; + DAT_PathFindingState::instance.searchQueue.destinationsArray[outCount].tile3OrAnotherHelper + = DAT_PathFindingState::instance.searchQueue.destinationsArray[i].tile3OrAnotherHelper; + } + ++outCount; + } + } + DAT_PathFindingState::instance.searchQueue.destinationsArray[outCount].tile1 = 0; + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/spawnDeerLionOrRabbit.cpp b/src/OpenSHC/Map/Units/TribesState/spawnDeerLionOrRabbit.cpp new file mode 100644 index 0000000000..272072713c --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/spawnDeerLionOrRabbit.cpp @@ -0,0 +1,97 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/Units/UnitsState.func.hpp" +#include "OpenSHC/Map/Units/UnitType.hpp" +#include "OpenSHC/UI/Enums/MenuViewType.hpp" +#include "OpenSHC/WindowsHelper/Enums/BOOLEnum.hpp" + +#include "OpenSHC/Globals/DAT_GameCore.hpp" +#include "OpenSHC/Globals/DAT_GameState.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" +#include "OpenSHC/Globals/SEC_RNG.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Map::Units::UnitType; + using UI::Enums::MenuViewType; + using WindowsHelper::Enums::BOOLEnum; + + /* + The tribe is reached through a TribesState pointer shifted by the tribe, as in + trimTribeToSize: the original keeps `lea esi, [eax + ecx]` and reads every field + at its offset in TribesState. The sizes are compared sixteen bits wide + (`cmp cx, di`), so they are shorts. The reads of the spawn position, terrain + height, herd sizes and RNG byte are in the order that puts x and y in ebx and ebp. + */ + // FUNCTION: STRONGHOLDCRUSADER 0x00525F20 + BOOLEnum TribesState::spawnDeerLionOrRabbit(int tribeID, int spawnInterval, UnitType unitType) + { + if (DAT_GameCore::instance.currentMenuViewType == UI::Enums::MVT_MAP_EDITOR_LANDSCAPING) { + return FALSE; + } + if (tribeID <= 0) { + return FALSE; + } + if (this->tribes[tribeID].predatorNearby != 0) { + return FALSE; + } + TribesState* const _tb = (TribesState*)((char*)this + tribeID * sizeof(Tribe)); + int const targetUnitID = _tb->tribes[0].selectionTargetUnitID; + int unitID = targetUnitID; + if (unitType == Map::Units::UT_ANTELOPESHDEER) { + unitID = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getNonDyingUnit, this)(tribeID); + if (unitID == 0) { + unitID = targetUnitID; + } + } + int const x = DAT_UnitsState::instance.units[unitID].x; + int const y = DAT_UnitsState::instance.units[unitID].y; + int const terrainHeight = DAT_UnitsState::instance.units[unitID].terrainOrClimbHeight; + short const herdMinSize = _tb->tribes[0].herdMinSize; + short const size = _tb->tribes[0].size; + int const rng = (byte)SEC_RNG::instance.currentNumber2 & 0x7f; + if (size <= herdMinSize) { + spawnInterval = spawnInterval / 4; + } + _tb->tribes[0].field_0x284 = _tb->tribes[0].field_0x284 + 1; + if ((short)_tb->tribes[0].field_0x284 < spawnInterval) { + return FALSE; + } + _tb->tribes[0].field_0x284 = 0; + if (size >= _tb->tribes[0].herdMaxSize) { + return FALSE; + } + int chance; + if (unitType == Map::Units::UT_RABBIT + && DAT_GameState::instance.mapAndTime.eventCountdownRabbitInfestation) { + chance = 110; + } else { + chance = size < herdMinSize ? 25 : 100; + } + if (chance > rng) { + return FALSE; + } + int const spawnedUnitID = MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::spawnUnit, DAT_UnitsState::ptr)( + 0, 0, x * 8, y * 8, terrainHeight, unitType); + if (spawnedUnitID == 0) { + return FALSE; + } + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::addUnitToTribe, this)(spawnedUnitID, tribeID); + DAT_UnitsState::instance.units[spawnedUnitID].substate + = (short)(DAT_UnitsState::instance.units[spawnedUnitID].fixedRng & 3); + if (unitType == Map::Units::UT_ANTELOPESHDEER) { + DAT_UnitsState::instance.units[spawnedUnitID].antelopeBasedRngValue = 2; + } + DAT_UnitsState::instance.units[spawnedUnitID].disappearFadeAlphaCountdown = 0x20; + if (unitType == Map::Units::UT_ANTELOPESHDEER) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::updateAnimalHerdBehaviorState, this)(tribeID); + } + return TRUE; + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/spawnQueuedReinforcementWaves.cpp b/src/OpenSHC/Map/Units/TribesState/spawnQueuedReinforcementWaves.cpp new file mode 100644 index 0000000000..0217e94fc9 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/spawnQueuedReinforcementWaves.cpp @@ -0,0 +1,579 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/AI/Siege/SiegeUnitCounts.hpp" +#include "OpenSHC/AI/Tribes/AITribeType.hpp" +#include "OpenSHC/Game/GameMode.hpp" +#include "OpenSHC/Game/GameMode2.hpp" +#include "OpenSHC/Game/Player/Enums/BuildingEntryInfoEnum.hpp" +#include "OpenSHC/Game/TrailType.hpp" +#include "OpenSHC/Map/Units/UnitType.hpp" +#include "OpenSHC/Map/Units/UnitTypeInt.hpp" +#include "OpenSHC/WindowsHelper/Enums/BOOLEnum.hpp" + +#include "OpenSHC/Globals/DAT_GameCore.hpp" +#include "OpenSHC/Globals/DAT_GameState.hpp" +#include "OpenSHC/Globals/DAT_GameSynchronyState.hpp" +#include "OpenSHC/Globals/DAT_MapPropertiesState.hpp" +#include "OpenSHC/Globals/DAT_SH1_SiegeAdvancedMode.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using AI::Siege::SiegeUnitCounts; + using AI::Tribes::AITribeType; + using Game::GameMode; + using Game::GameMode2; + using Game::TrailType; + using Map::Units::UnitType; + using Map::Units::UnitTypeInt; + using WindowsHelper::Enums::BOOLEnum; + + /* + The two flags measure in opposite directions, so only one of them is widened. + Both together cost 6.4 points (58.5% -> 52.1%); `bVar2` alone gains 1.1 + (58.5% -> 59.6%), so `bVar1` stays `bool` despite the original's `xor ebx, ebx` + and the byte-sized slot diff_slots.py reports for it at 0x13. + */ + // FUNCTION: STRONGHOLDCRUSADER 0x00527440 + void TribesState::spawnQueuedReinforcementWaves() + { + int iVar3; + dword dVar4; + dword _tribeID1; + int iVar5; + int iVar6; + int* piVar7; + SiegeUnitCounts* pSVar8; + int _siegeInfoSubIndex; + int _playerID; + AITribeType _tribeType; + UnitTypeInt _unitType; + int _destinationIndexTracker; + int _unitType1Count; + int local_4; + int _playerID_2; + int _count; + int _destinationIndex; + int _newCount; + _tribeType = (AITribeType)0; + bool bVar1 = false; + + _unitType = ((UnitType)0); + _destinationIndexTracker = 0; + BOOLEnum bVar2 = FALSE; + if (DAT_GameCore::instance.gameMode_2 != Game::GM_EDITOR + && DAT_GameCore::instance.gameMode_2 != Game::GM_SIEGE_THAT + && (DAT_GameSynchronyState::instance.currentGameMode != Game::GM_SOLITARY + || (((DAT_GameCore::instance.gameMode_2 == Game::GM_BUILDERUnk + || (DAT_GameCore::instance.gameMode_2 == Game::GM_CRUSADER_TUTORIAL)) + || (0 < DAT_GameState::instance + .playerDataArray[DAT_GameSynchronyState::instance.currentPlayerSlotID] + .buildingEntryInfos[Game::Player::Enums::BEIE_KEEP] + .id)))) + && 0 <= DAT_GameState::instance.mapAndTime.countUpTo201) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::updateTribeUnitAssignments, this)(); + _playerID_2 = DAT_GameSynchronyState::instance.currentPlayerSlotID; + if ((DAT_GameCore::instance.gameMode_2 == Game::GM_BUILDERUnk) + || (DAT_GameCore::instance.gameMode_2 == Game::GM_CRUSADER_TUTORIAL)) { + pSVar8 = &DAT_GameState::instance.mapAndTime.siegeInformation; + do { + iVar3 = 100; + /* + The difficulty chain stays an if/else-if, against the asm. The + original dispatches it by subtracting through the values - + `test ecx, ecx; je`, `sub ecx, 2; je`, `sub ecx, 1; jne` - which + is MSVC's shape for a switch over a few close-together cases, + where an equality chain gives a `cmp` per arm. Rewriting these + three arms as `switch (difficulty)` measures 59.6% -> 55.9%, so + whatever the sub-chain buys is less than the arm placement it + changes. Reverted. + */ + if (!DAT_GameState::instance.mapAndTime.difficulty) { + if (_playerID_2 == 1) { + iVar3 = 0x43; + } else if (!DAT_SH1_SiegeAdvancedMode::instance) { + LAB_005279a0: + iVar3 = 167; + } + } else if (DAT_GameState::instance.mapAndTime.difficulty == 2) { + if (_playerID_2 == 1) { + iVar3 = 133; + } else if (!DAT_SH1_SiegeAdvancedMode::instance) { + iVar3 = 75; + } + } else if (DAT_GameState::instance.mapAndTime.difficulty == 3) { + if (_playerID_2 == 1) + goto LAB_005279a0; + if (!DAT_SH1_SiegeAdvancedMode::instance) { + iVar3 = 50; + } + } + pSVar8->archers = (pSVar8->archers * iVar3) / 100; + pSVar8 = (SiegeUnitCounts*)&pSVar8->crossbowmen; + } while ((int)pSVar8 < 0x117cea0); + _siegeInfoSubIndex = 0; + do { + if (DAT_GameState::instance.mapAndTime.startGoods[_siegeInfoSubIndex + 0x19] != 0) { + switch (_siegeInfoSubIndex) { + case 0: + _tribeType = AI::Tribes::AITT_ARCHERS; + _unitType = Map::Units::UT_E_ARCHER; + break; + case 1: + _tribeType = AI::Tribes::AITT_CROSSBOWMEN; + _unitType = Map::Units::UT_E_XBOW; + break; + case 2: + _tribeType = AI::Tribes::AITT_SPEARMEN; + _unitType = Map::Units::UT_E_SPEAR; + break; + case 3: + _tribeType = AI::Tribes::AITT_PIKEMEN; + _unitType = Map::Units::UT_E_PIKE; + break; + case 4: + _tribeType = AI::Tribes::AITT_MACEMEN; + _unitType = Map::Units::UT_E_MACE; + break; + case 5: + _tribeType = AI::Tribes::AITT_SWORDSMEN; + _unitType = Map::Units::UT_E_SWORD; + break; + case 6: + _tribeType = AI::Tribes::AITT_KNIGHTS; + _unitType = Map::Units::UT_E_KNIGHT; + break; + /* + This switch is the one whose table is 0x527c34, where entry 7 + is the laddermen arm at 0x527a43 - the arm that sets 4 and + 0x1d. The other 18-entry table, 0x527bec, sends entry 7 + straight to the merge point, which is why the fourth switch + below has no case 7. Which switch is which is settled by the + call each one feeds: 0x527c34's reaches + createTribeWithSpawnedUnit (0x523190) and 0x527bec's reaches + spawnUnitsIntoNewTribe (0x523030). Moving the arm the other + way costs 17.1 points (59.6% -> 42.5%). + */ + case 7: + _tribeType = AI::Tribes::AITT_LADDERMEN; + _unitType = Map::Units::UT_E_LADDER; + break; + case 8: + _tribeType = AI::Tribes::AITT_ENGINEERS; + _unitType = Map::Units::UT_E_ENGINEER; + break; + case 9: + _tribeType = AI::Tribes::AITT_HOPS_FARMER_UNK; + _unitType = Map::Units::UT_E_MONK; + break; + case 10: + _tribeType = AI::Tribes::AITT_ARAB_ARCHER; + _unitType = Map::Units::UT_A_ARCHER; + break; + case 0xb: + _tribeType = AI::Tribes::AITT_ARAB_SLAVE; + _unitType = Map::Units::UT_A_SLAVE; + break; + case 0xc: + _tribeType = AI::Tribes::AITT_ARAB_SLINGER; + _unitType = Map::Units::UT_A_SLINGER; + break; + case 0xd: + _tribeType = AI::Tribes::AITT_ARAB_ASSASSIN; + _unitType = Map::Units::UT_A_ASSASSIN; + break; + case 0xe: + _tribeType = AI::Tribes::AITT_ARAB_HORSE_ARCHER; + _unitType = Map::Units::UT_A_HARCHER; + break; + case 0xf: + _tribeType = AI::Tribes::AITT_ARAB_SWORDSMAN; + _unitType = Map::Units::UT_A_SWORDSMAN; + break; + case 0x10: + _tribeType = AI::Tribes::AITT_ARAB_FIRETHROWER; + _unitType = Map::Units::UT_A_FIRETHROWER; + break; + case 0x11: + _tribeType = AI::Tribes::AITT_FIRE_BALLISTA; + _unitType = Map::Units::UT_S_FBALLISTA; + } + do { + _count = DAT_GameState::instance.mapAndTime.startGoods[_siegeInfoSubIndex + 0x19]; + int _nUnits = _count; + if (9 < _count) { + _nUnits = 9; + } + DAT_GameState::instance.mapAndTime.startGoods[_siegeInfoSubIndex + 0x19] + = _count - _nUnits; + _destinationIndex = _destinationIndexTracker; + if (39 < _destinationIndexTracker) { + _destinationIndex = 0; + } + _tribeID1 = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::createTribeWithSpawnedUnit, + this)((short)_destinationIndexTracker, _tribeType, + DAT_GameState::instance.mapAndTime.unitMoveDestinationXYPairs[0][_destinationIndex] + .x, + DAT_GameState::instance.mapAndTime.unitMoveDestinationXYPairs[0][_destinationIndex] + .y, + 2, (UnitType)((int)(_unitType)), _nUnits); + _newCount = DAT_GameState::instance.mapAndTime.startGoods[_siegeInfoSubIndex + 0x19]; + /* + The original reaches this field through the global, not + `this`. All five of these 0x32 stores are + `mov word ptr [eax + I::instance+86]` in the + binary - 0x527696, 0x5277a6, 0x5278ff, 0x527b0b and + 0x527b86 - addressing the instance absolutely with the + tribe index in eax, where `this->tribes[..]` gives the + two-register `[eax + + 0x56]`. So the original + source almost certainly wrote the global here. + + Changing all five to DAT_TribesState::instance measures + 59.6% -> 57.2%, even though it is demonstrably right: + afterwards four of the five match instruction for + instruction and the `+ 0x56` form is gone from the diff + entirely. Materialising the global costs more in + register pressure elsewhere than the five stores gain. + Left as `this->` for the score, with the finding recorded + - if this function's allocation is ever brought into line + the global is the form to go back to. + */ + this->tribes[_tribeID1].unknownAttackRelatedUpdateCounter = 0x32; + _destinationIndexTracker = _destinationIndexTracker + 1; + } while (_newCount); + } + _siegeInfoSubIndex = _siegeInfoSubIndex + 1; + /* + The tunneler count stays inside the loop body, where the + decompiler put it. The original reads it after the back-edge - + `jl` closing the do-while, then `mov esi, [MapPropertiesState + + 340]; test esi, esi; je` - and moving it there is the same value, + since it is assigned in the loop and read nowhere until the + while below. It measures 60.4% -> 54.8%, so the read being + loop-carried is worth more here than its position. + */ + iVar3 = DAT_MapPropertiesState::instance.SEC_Section1067.tunnelersCount; + } while (_siegeInfoSubIndex < 20); + while (iVar3) { + iVar6 = iVar3; + if (9 < iVar3) { + iVar6 = 9; + } + iVar5 = _destinationIndexTracker; + if (0x27 < _destinationIndexTracker) { + iVar5 = 0; + } + dVar4 = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::createTribeWithSpawnedUnit, this)( + (short)_destinationIndexTracker, AI::Tribes::AITT_TUNNELERS, + DAT_GameState::instance.mapAndTime.unitMoveDestinationXYPairs[0][iVar5].x, + DAT_GameState::instance.mapAndTime.unitMoveDestinationXYPairs[0][iVar5].y, 2, + Map::Units::UT_TUNNELER, iVar6); + this->tribes[dVar4].unknownAttackRelatedUpdateCounter = 0x32; + iVar3 = iVar3 - iVar6; + _destinationIndexTracker = _destinationIndexTracker + 1; + } + DAT_GameState::instance.mapAndTime.countUpTo201 = -1; + } else if (DAT_GameSynchronyState::instance.currentGameMode == Game::GM_SOLITARY) { + DAT_GameState::instance.mapAndTime.countUpTo201 + = DAT_GameState::instance.mapAndTime.countUpTo201 + 1; + if (200 < DAT_GameState::instance.mapAndTime.countUpTo201) { + DAT_GameState::instance.mapAndTime.countUpTo201 = 0; + iVar3 = 0; + while (true) { + if (iVar3 == 7) { + iVar3 = 8; + } + if (DAT_GameState::instance.mapAndTime.startGoods[iVar3 + 0x19] != 0) + break; + iVar3 = iVar3 + 1; + if (9 < iVar3) + goto LAB_005276b5; + } + switch (iVar3) { + case 0: + _tribeType = AI::Tribes::AITT_ARCHERS; + _unitType = Map::Units::UT_E_ARCHER; + break; + case 1: + _tribeType = AI::Tribes::AITT_CROSSBOWMEN; + _unitType = Map::Units::UT_E_XBOW; + break; + case 2: + _tribeType = AI::Tribes::AITT_SPEARMEN; + _unitType = Map::Units::UT_E_SPEAR; + break; + case 3: + _tribeType = AI::Tribes::AITT_PIKEMEN; + _unitType = Map::Units::UT_E_PIKE; + break; + case 4: + _tribeType = AI::Tribes::AITT_MACEMEN; + _unitType = Map::Units::UT_E_MACE; + break; + case 5: + _tribeType = AI::Tribes::AITT_SWORDSMEN; + _unitType = Map::Units::UT_E_SWORD; + break; + case 6: + _tribeType = AI::Tribes::AITT_KNIGHTS; + _unitType = Map::Units::UT_E_KNIGHT; + break; + case 8: + _tribeType = AI::Tribes::AITT_ENGINEERS; + _unitType = Map::Units::UT_E_ENGINEER; + break; + case 9: + _tribeType = AI::Tribes::AITT_HOPS_FARMER_UNK; + _unitType = Map::Units::UT_E_MONK; + } + iVar6 = DAT_GameState::instance.mapAndTime.startGoods[iVar3 + 0x19]; + _unitType1Count = iVar6; + if (9 < iVar6) { + _unitType1Count = 9; + } + _playerID = 1; + DAT_GameState::instance.mapAndTime.startGoods[iVar3 + 0x19] = iVar6 - _unitType1Count; + piVar7 = &DAT_GameState::instance.playerDataArray[1] + .buildingEntryInfos[Game::Player::Enums::BEIE_CAMPGROUND] + .xEntry; + do { + if ((DAT_GameSynchronyState::instance.currentPlayerFullIDArray[_playerID] != -1) + || (DAT_GameSynchronyState::instance.currentAIArray[_playerID] != 0)) { + dVar4 = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::spawnUnitsIntoNewTribe, this)( + _destinationIndexTracker, _tribeType, (int)(*piVar7), (int)(piVar7[1]), _playerID, + (UnitType)((int)(_unitType)), ((UnitType)0), _unitType1Count, 0); + this->tribes[dVar4].unknownAttackRelatedUpdateCounter = 0x32; + bVar2 = TRUE; + _destinationIndexTracker = _destinationIndexTracker + 1; + } + _playerID = _playerID + 1; + piVar7 = piVar7 + 0xe7d; + } while (_playerID < 9); + LAB_005276b5: + iVar3 = 10; + /* + Top-tested, with the back-edge returning to the test, and the + bound written as `< 0x14` because that is the constant the + original compares against. Its loop at 0x005276c0 is + + L:cmp dword ptr [ecx*4 + 0x117ce50], 0 + jnz + add ecx, 1 + cmp ecx, 0x14 + jl L + jmp + + so the index stays scaled into the addressing rather than being + walked as a pointer, and the test is at the top. A `while` gets + rotated: MSVC peels the first test and bottom-tests the rest. + Same change as createTribeForPlayer, worth +11.0 there. + */ + LAB_005276c0: + if (DAT_GameState::instance.mapAndTime.startGoods[iVar3 + 0x19] == 0) { + iVar3 = iVar3 + 1; + if (iVar3 < 0x14) { + goto LAB_005276c0; + } + goto LAB_005277c5; + } + switch (iVar3) { + case 10: + _tribeType = AI::Tribes::AITT_ARAB_ARCHER; + _unitType = Map::Units::UT_A_ARCHER; + break; + case 0xb: + _tribeType = AI::Tribes::AITT_ARAB_SLAVE; + _unitType = Map::Units::UT_A_SLAVE; + break; + case 0xc: + _tribeType = AI::Tribes::AITT_ARAB_SLINGER; + _unitType = Map::Units::UT_A_SLINGER; + break; + case 0xd: + _tribeType = AI::Tribes::AITT_ARAB_ASSASSIN; + _unitType = Map::Units::UT_A_ASSASSIN; + break; + case 0xe: + _tribeType = AI::Tribes::AITT_ARAB_HORSE_ARCHER; + _unitType = Map::Units::UT_A_HARCHER; + break; + case 0xf: + _tribeType = AI::Tribes::AITT_ARAB_SWORDSMAN; + _unitType = Map::Units::UT_A_SWORDSMAN; + break; + case 0x10: + _tribeType = AI::Tribes::AITT_ARAB_FIRETHROWER; + _unitType = Map::Units::UT_A_FIRETHROWER; + break; + case 0x11: + _tribeType = AI::Tribes::AITT_FIRE_BALLISTA; + _unitType = Map::Units::UT_S_FBALLISTA; + } + iVar6 = DAT_GameState::instance.mapAndTime.startGoods[iVar3 + 0x19]; + _unitType1Count = iVar6; + if (9 < iVar6) { + _unitType1Count = 9; + } + iVar5 = 1; + DAT_GameState::instance.mapAndTime.startGoods[iVar3 + 0x19] = iVar6 - _unitType1Count; + piVar7 = &DAT_GameState::instance.playerDataArray[1] + .buildingEntryInfos[Game::Player::Enums::BEIE_CAMPGROUND] + .xEntry; + do { + if ((DAT_GameSynchronyState::instance.currentPlayerFullIDArray[iVar5] != -1) + || (DAT_GameSynchronyState::instance.currentAIArray[iVar5] != 0)) { + dVar4 = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::spawnUnitsIntoNewTribe, this)( + _destinationIndexTracker, _tribeType, (int)(*piVar7), (int)(piVar7[1]), iVar5, + (UnitType)((int)(_unitType)), ((UnitType)0), _unitType1Count, 0); + this->tribes[dVar4].unknownAttackRelatedUpdateCounter = 0x32; + bVar2 = TRUE; + _destinationIndexTracker = _destinationIndexTracker + 1; + } + iVar5 = iVar5 + 1; + piVar7 = piVar7 + 0xe7d; + } while (iVar5 < 9); + LAB_005277c5: + if (!bVar2) { + DAT_GameState::instance.mapAndTime.countUpTo201 = -1; + } + } + } else if ((DAT_GameSynchronyState::instance.currentGameMode == Game::GM_SKIRMISH_SINGLE_PLAYER) + || (!DAT_GameState::instance.mapAndTime.skirmishNoRushTicks)) { + DAT_GameState::instance.mapAndTime.countUpTo201 + = DAT_GameState::instance.mapAndTime.countUpTo201 + 1; + iVar3 = 200; + if (DAT_GameCore::instance.gameMode_2 == Game::GM_SKIRMISH_AND_MULTIPLAYER + && DAT_GameCore::instance.isSkirmishTrail == TRUE + && DAT_GameCore::instance.currentTrailType == Game::TT_EXTREME) { + iVar3 = 0x32; + } + if (iVar3 < DAT_GameState::instance.mapAndTime.countUpTo201) { + DAT_GameState::instance.mapAndTime.countUpTo201 = 0; + local_4 = 1; + _unitType1Count = 0x14; + piVar7 = &DAT_GameState::instance.playerDataArray[1] + .buildingEntryInfos[Game::Player::Enums::BEIE_CAMPGROUND] + .xEntry; + do { + if ((DAT_GameSynchronyState::instance.currentPlayerFullIDArray[local_4] != -1) + || (DAT_GameSynchronyState::instance.currentAIArray[local_4] != 0)) { + iVar3 = 0; + do { + if (iVar3 == 7) { + iVar3 = 8; + } + if (*(int*)(DAT_GameState::instance.mapAndTime.unused_0x3ff00 + + (_unitType1Count + iVar3) * 4) + != 0) { + switch (iVar3) { + case 0: + _tribeType = AI::Tribes::AITT_ARCHERS; + _unitType = Map::Units::UT_E_ARCHER; + break; + case 1: + _tribeType = AI::Tribes::AITT_CROSSBOWMEN; + _unitType = Map::Units::UT_E_XBOW; + break; + case 2: + _tribeType = AI::Tribes::AITT_SPEARMEN; + _unitType = Map::Units::UT_E_SPEAR; + break; + case 3: + _tribeType = AI::Tribes::AITT_PIKEMEN; + _unitType = Map::Units::UT_E_PIKE; + break; + case 4: + _tribeType = AI::Tribes::AITT_MACEMEN; + _unitType = Map::Units::UT_E_MACE; + break; + case 5: + _tribeType = AI::Tribes::AITT_SWORDSMEN; + _unitType = Map::Units::UT_E_SWORD; + break; + case 6: + _tribeType = AI::Tribes::AITT_KNIGHTS; + _unitType = Map::Units::UT_E_KNIGHT; + break; + /* + No case 7: entry 7 of this switch's table, + 0x527bec, is the merge point 0x5278a6, so a + laddermen wave here reuses whatever the previous + iteration left in the two variables. + */ + case 8: + _tribeType = AI::Tribes::AITT_ENGINEERS; + _unitType = Map::Units::UT_E_ENGINEER; + break; + case 9: + _tribeType = AI::Tribes::AITT_HOPS_FARMER_UNK; + _unitType = Map::Units::UT_E_MONK; + break; + case 10: + _tribeType = AI::Tribes::AITT_ARAB_ARCHER; + _unitType = Map::Units::UT_A_ARCHER; + break; + case 0xb: + _tribeType = AI::Tribes::AITT_ARAB_SLAVE; + _unitType = Map::Units::UT_A_SLAVE; + break; + case 0xc: + _tribeType = AI::Tribes::AITT_ARAB_SLINGER; + _unitType = Map::Units::UT_A_SLINGER; + break; + case 0xd: + _tribeType = AI::Tribes::AITT_ARAB_ASSASSIN; + _unitType = Map::Units::UT_A_ASSASSIN; + break; + case 0xe: + _tribeType = AI::Tribes::AITT_ARAB_HORSE_ARCHER; + _unitType = Map::Units::UT_A_HARCHER; + break; + case 0xf: + _tribeType = AI::Tribes::AITT_ARAB_SWORDSMAN; + _unitType = Map::Units::UT_A_SWORDSMAN; + break; + case 0x10: + _tribeType = AI::Tribes::AITT_ARAB_FIRETHROWER; + _unitType = Map::Units::UT_A_FIRETHROWER; + break; + case 0x11: + _tribeType = AI::Tribes::AITT_FIRE_BALLISTA; + _unitType = Map::Units::UT_S_FBALLISTA; + } + iVar6 = *(int*)(DAT_GameState::instance.mapAndTime.unused_0x3ff00 + + (_unitType1Count + iVar3) * 4); + iVar5 = iVar6; + if (9 < iVar6) { + iVar5 = 9; + } + *(int*)(DAT_GameState::instance.mapAndTime.unused_0x3ff00 + + (_unitType1Count + iVar3) * 4) = iVar6 - iVar5; + dVar4 = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::spawnUnitsIntoNewTribe, + this)(_destinationIndexTracker, _tribeType, (int)(*piVar7), + (int)(piVar7[1]), local_4, (UnitType)((int)(_unitType)), ((UnitType)0), + iVar5, 0); + this->tribes[dVar4].unknownAttackRelatedUpdateCounter = 0x32; + bVar1 = true; + _destinationIndexTracker = _destinationIndexTracker + 1; + break; + } + iVar3 = iVar3 + 1; + } while (iVar3 < 0x14); + } + _unitType1Count = _unitType1Count + 0x14; + local_4 = local_4 + 1; + piVar7 = piVar7 + 0xe7d; + } while (local_4 < 9); + if (!bVar1) { + DAT_GameState::instance.mapAndTime.countUpTo201 = -1; + } + } + } + } + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/trimTribeToSize.cpp b/src/OpenSHC/Map/Units/TribesState/trimTribeToSize.cpp new file mode 100644 index 0000000000..015e24469b --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/trimTribeToSize.cpp @@ -0,0 +1,50 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/Units/UnitLogicState.hpp" + +#include "OpenSHC/Globals/DAT_CurrentTribeID.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Map::Units::UnitLogicState; + + // FUNCTION: STRONGHOLDCRUSADER 0x00522EF0 + void TribesState::trimTribeToSize(undefined4 tribeID, int smallerSize) + { + int const currentTribeID = DAT_CurrentTribeID::instance; + int unitSelectionIndex = 0; + /* + The tribe is reached through a TribesState pointer shifted by the tribe, not a + `Tribe&`: the original takes `lea ebp, [eax + edi]` and reads the size as + `[ebp + 0x5c]`, where a reference folds the `tribes` offset into the base + (0.93 against 1.0 in quick_diff). The tribe is DAT_CurrentTribeID, read once; + the tribeID parameter is unused, as in the original. + */ + TribesState* const _tb = (TribesState*)((char*)this + currentTribeID * sizeof(Tribe)); + if (this->tribes[currentTribeID].tribeState == 0) { + return; + } + int const size = _tb->tribes[0].size; + if (size < smallerSize || size <= 0) { + return; + } + do { + int const unitID = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)( + currentTribeID, unitSelectionIndex); + UnitLogicStateShort const value = DAT_UnitsState::instance.units[unitID].logicalState; + unitSelectionIndex = unitSelectionIndex + 1; + if ((value == (UnitLogicState)1 || value == Map::Units::ULS_NORMAL + || value == Map::Units::ULS_TRANSITIONING) + && unitSelectionIndex >= smallerSize) { + DAT_UnitsState::instance.units[unitID].logicalState = Map::Units::ULS_REMOVE; + } + } while (unitSelectionIndex < _tb->tribes[0].size); + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/updateCamelTribeBehavior.cpp b/src/OpenSHC/Map/Units/TribesState/updateCamelTribeBehavior.cpp new file mode 100644 index 0000000000..9a7d79e7f5 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/updateCamelTribeBehavior.cpp @@ -0,0 +1,111 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/WildlifeState.func.hpp" +#include "OpenSHC/Map/Units/Instructions/UnitMatchSpeedEnum.hpp" +#include "OpenSHC/Map/Units/SomeTribeBehaviorType.hpp" +#include "OpenSHC/UI/Enums/MenuViewType.hpp" +#include "OpenSHC/WindowsHelper/Enums/BOOLEnum.hpp" + +#include "OpenSHC/Globals/DAT_GameCore.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" +#include "OpenSHC/Globals/DAT_WildlifeState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Map::Units::SomeTribeBehaviorType; + using Map::Units::Instructions::UnitMatchSpeedEnum; + using UI::Enums::MenuViewType; + using WindowsHelper::Enums::BOOLEnum; + + /* + Every branch above the behaviour dispatch ends in its own `ret 4` in the + original, so each returns here. The move order and the update counter are + ushorts compared sixteen bits wide (`cmp ax, dx`); the timeout is an int compared + against the counter read as a short (`movsx eax, ax; cmp eax, ecx`). + */ + // FUNCTION: STRONGHOLDCRUSADER 0x0052B630 + void TribesState::updateCamelTribeBehavior(int tribeID) + { + BOOLEnum const noTunnelers = MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::isTribeFreeOfTunnelingUnits, this)(tribeID, this->tribes[tribeID].uid); + this->tribes[tribeID].unknownCounter01 = this->tribes[tribeID].unknownCounter01 + 1; + this->tribes[tribeID].unkIsAnimalTribe = 1; + if (this->tribes[tribeID].unknownCounter01 >= 8000) { + this->tribes[tribeID].unknownCounter01 = 4000; + } + if (noTunnelers != FALSE + && MACRO_CALL_MEMBER(Map::Units::TribesState_Func::trySpawnAdditionalWildlifeForTribe, this)( + tribeID, 1000, 10, 0x2f) + != 0) { + this->tribes[tribeID].initialMoveOrderGiven = 1; + this->tribes[tribeID].unknownAttackRelatedUpdateCounter = 0; + return; + } + ushort const moveOrder = this->tribes[tribeID].initialMoveOrderGiven; + if (moveOrder == 0) { + int const targetUnitID = this->tribes[tribeID].selectionTargetUnitID; + this->tribes[tribeID].unknownAttackRelatedUpdateCounter = 0; + this->tribes[tribeID].initialMoveOrderGiven = 2; + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::giveTribeMoveInstruction, this)(tribeID, + DAT_UnitsState::instance.units[targetUnitID].x, DAT_UnitsState::instance.units[targetUnitID].y, 0, + 0, Map::Units::Instructions::UMSE_0); + this->tribes[tribeID].tribeBehaviorType = Map::Units::STBT_1; + return; + } + if (DAT_GameCore::instance.currentMenuViewType == UI::Enums::MVT_MAP_EDITOR_LANDSCAPING) { + this->tribes[tribeID].unknownCounter01 = 0; + return; + } + if (moveOrder == 1) { + this->tribes[tribeID].unknownAttackRelatedUpdateCounter = 0; + this->tribes[tribeID].initialMoveOrderGiven = 2; + MACRO_CALL_MEMBER(Map::WildlifeState_Func::findAndSetNewRallyPointForDeerAndLions, + DAT_WildlifeState::ptr)(tribeID, 2, 0); + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::standUpAllTribeUnits, this)(tribeID); + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::giveTribeMoveInstruction, this)(tribeID, + this->tribes[tribeID].rallyPointArray[this->tribes[tribeID].currentRallyPointIndex][0], + this->tribes[tribeID].rallyPointArray[this->tribes[tribeID].currentRallyPointIndex][1], 0, 0, + Map::Units::Instructions::UMSE_0); + this->tribes[tribeID].currentRallyPointIndex = this->tribes[tribeID].currentRallyPointIndex + 1; + if (this->tribes[tribeID].currentRallyPointIndex >= this->tribes[tribeID].rallyPointCount) { + this->tribes[tribeID].rallyPointCount = 0; + this->tribes[tribeID].tribeBehaviorType = Map::Units::STBT_1; + } + this->tribes[tribeID].tribeBehaviorType = Map::Units::STBT_1; + return; + } + if (this->tribes[tribeID].tribeBehaviorType == (SomeTribeBehaviorType)0) { + if (this->tribes[tribeID].unknownAttackRelatedUpdateCounter++ == 0) { + MACRO_CALL_MEMBER(Map::WildlifeState_Func::findAndSetNewRallyPointForDeerAndLions, + DAT_WildlifeState::ptr)(tribeID, 2, 1); + if (this->tribes[tribeID].rallyPointCount > 0) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::standUpAllTribeUnits, this)(tribeID); + int const lastRallyPoint = this->tribes[tribeID].rallyPointCount; + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::giveUnitSelectionMoveInstructionNoMatchedSpeed, + this)(tribeID, this->tribes[tribeID].rallyPointArray[lastRallyPoint - 1][0], + this->tribes[tribeID].rallyPointArray[lastRallyPoint - 1][1], 0, 0); + } + } else if (noTunnelers != FALSE) { + this->tribes[tribeID].tribeBehaviorType = Map::Units::STBT_1; + this->tribes[tribeID].unknownAttackRelatedUpdateCounter = 0; + } + } else if (this->tribes[tribeID].tribeBehaviorType == Map::Units::STBT_1) { + int timeout = 800; + if (this->tribes[tribeID].unknownCounter01 <= 100) { + timeout = 10; + } + this->tribes[tribeID].unknownAttackRelatedUpdateCounter + = this->tribes[tribeID].unknownAttackRelatedUpdateCounter + 1; + if ((short)this->tribes[tribeID].unknownAttackRelatedUpdateCounter >= timeout) { + this->tribes[tribeID].tribeBehaviorType = (SomeTribeBehaviorType)0; + this->tribes[tribeID].unknownAttackRelatedUpdateCounter = 0; + } + } + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/updateLionWolfTribeBehavior.cpp b/src/OpenSHC/Map/Units/TribesState/updateLionWolfTribeBehavior.cpp new file mode 100644 index 0000000000..2dcecdc5ec --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/updateLionWolfTribeBehavior.cpp @@ -0,0 +1,124 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/WildlifeState.func.hpp" +#include "OpenSHC/Map/Units/Instructions/UnitMatchSpeedEnum.hpp" +#include "OpenSHC/Map/Units/SomeTribeBehaviorType.hpp" +#include "OpenSHC/Map/Units/UnitType.hpp" +#include "OpenSHC/UI/Enums/MenuViewType.hpp" +#include "OpenSHC/WindowsHelper/Enums/BOOLEnum.hpp" + +#include "OpenSHC/Globals/DAT_GameCore.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" +#include "OpenSHC/Globals/DAT_WildlifeState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Map::Units::SomeTribeBehaviorType; + using Map::Units::UnitType; + using Map::Units::Instructions::UnitMatchSpeedEnum; + using UI::Enums::MenuViewType; + using WindowsHelper::Enums::BOOLEnum; + + /* + The same shape as updateCamelTribeBehavior: every branch above the behaviour + dispatch ends in its own `ret 4` in the original, and the countdown, move order + and update counter are ushorts compared sixteen bits wide. + */ + // FUNCTION: STRONGHOLDCRUSADER 0x0052B110 + void TribesState::updateLionWolfTribeBehavior(int tribeID) + { + BOOLEnum const noTunnelers = MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::isTribeFreeOfTunnelingUnits, this)(tribeID, this->tribes[tribeID].uid); + this->tribes[tribeID].unknownCounter01 = this->tribes[tribeID].unknownCounter01 + 1; + this->tribes[tribeID].unkIsAnimalTribe = 1; + if (this->tribes[tribeID].unknownCounter01 >= 8000) { + this->tribes[tribeID].unknownCounter01 = 4000; + } + ushort const countdown = this->tribes[tribeID].countdown; + if (countdown != 0) { + if (countdown == 100) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::setStateForAllTribeUnits, this)(tribeID, 0xd0); + this->tribes[tribeID].unknownBool01 = 1; + } + return; + } + if (noTunnelers != FALSE + && MACRO_CALL_MEMBER(Map::Units::TribesState_Func::spawnDeerLionOrRabbit, this)( + tribeID, 500, Map::Units::UT_LIONSHWOLF) + != FALSE) { + this->tribes[tribeID].initialMoveOrderGiven = 1; + this->tribes[tribeID].unknownAttackRelatedUpdateCounter = 0; + return; + } + ushort const moveOrder = this->tribes[tribeID].initialMoveOrderGiven; + if (moveOrder == 0) { + int const targetUnitID = this->tribes[tribeID].selectionTargetUnitID; + this->tribes[tribeID].unknownAttackRelatedUpdateCounter = 0; + this->tribes[tribeID].initialMoveOrderGiven = 2; + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::giveTribeMoveInstruction, this)(tribeID, + DAT_UnitsState::instance.units[targetUnitID].x, DAT_UnitsState::instance.units[targetUnitID].y, 0, + 0, Map::Units::Instructions::UMSE_0); + this->tribes[tribeID].tribeBehaviorType = Map::Units::STBT_1; + return; + } + if (moveOrder == 1) { + this->tribes[tribeID].unknownAttackRelatedUpdateCounter = 0; + this->tribes[tribeID].initialMoveOrderGiven = 2; + MACRO_CALL_MEMBER(Map::WildlifeState_Func::findAndSetNewRallyPointForDeerAndLions, + DAT_WildlifeState::ptr)(tribeID, 2, 0); + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::standUpAllTribeUnits, this)(tribeID); + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::giveTribeMoveInstruction, this)(tribeID, + this->tribes[tribeID].rallyPointArray[this->tribes[tribeID].currentRallyPointIndex][0], + this->tribes[tribeID].rallyPointArray[this->tribes[tribeID].currentRallyPointIndex][1], 0, 0, + Map::Units::Instructions::UMSE_0); + this->tribes[tribeID].currentRallyPointIndex = this->tribes[tribeID].currentRallyPointIndex + 1; + if (this->tribes[tribeID].currentRallyPointIndex >= this->tribes[tribeID].rallyPointCount) { + this->tribes[tribeID].rallyPointCount = 0; + this->tribes[tribeID].tribeBehaviorType = Map::Units::STBT_1; + } + this->tribes[tribeID].tribeBehaviorType = Map::Units::STBT_1; + return; + } + if (DAT_GameCore::instance.currentMenuViewType == UI::Enums::MVT_MAP_EDITOR_LANDSCAPING) { + this->tribes[tribeID].unknownCounter01 = 0; + return; + } + if (this->tribes[tribeID].tribeBehaviorType == (SomeTribeBehaviorType)0) { + if (this->tribes[tribeID].unknownAttackRelatedUpdateCounter++ == 0) { + MACRO_CALL_MEMBER(Map::WildlifeState_Func::findAndSetNewRallyPointForDeerAndLions, + DAT_WildlifeState::ptr)(tribeID, 2, 0); + if (this->tribes[tribeID].rallyPointCount > 0) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::standUpAllTribeUnits, this)(tribeID); + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::applyLadderDestructionToTribeUnits, this)( + tribeID); + } + } else if (this->tribes[tribeID].unknownAttackRelatedUpdateCounter == 150) { + if (this->tribes[tribeID].unknownBool02 == 0) { + short const lastRallyPoint = this->tribes[tribeID].rallyPointCount; + if (lastRallyPoint > 0) { + MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::giveUnitSelectionMoveInstructionNoMatchedSpeed, this)( + tribeID, this->tribes[tribeID].rallyPointArray[lastRallyPoint - 1][0], + this->tribes[tribeID].rallyPointArray[lastRallyPoint - 1][1], 0, 0); + } + } + } else if (noTunnelers != FALSE) { + this->tribes[tribeID].tribeBehaviorType = Map::Units::STBT_1; + this->tribes[tribeID].unknownAttackRelatedUpdateCounter = 0; + } + } else if (this->tribes[tribeID].tribeBehaviorType == Map::Units::STBT_1) { + this->tribes[tribeID].unknownAttackRelatedUpdateCounter + = this->tribes[tribeID].unknownAttackRelatedUpdateCounter + 1; + if (this->tribes[tribeID].unknownAttackRelatedUpdateCounter == 300) { + this->tribes[tribeID].tribeBehaviorType = (SomeTribeBehaviorType)0; + this->tribes[tribeID].unknownAttackRelatedUpdateCounter = 0; + } + } + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/updateRabbitTribeBehavior.cpp b/src/OpenSHC/Map/Units/TribesState/updateRabbitTribeBehavior.cpp new file mode 100644 index 0000000000..effbb94ba3 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/updateRabbitTribeBehavior.cpp @@ -0,0 +1,128 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/WildlifeState.func.hpp" +#include "OpenSHC/Map/Units/Instructions/UnitMatchSpeedEnum.hpp" +#include "OpenSHC/Map/Units/SomeTribeBehaviorType.hpp" +#include "OpenSHC/Map/Units/UnitType.hpp" +#include "OpenSHC/UI/Enums/MenuViewType.hpp" +#include "OpenSHC/WindowsHelper/Enums/BOOLEnum.hpp" + +#include "OpenSHC/Globals/DAT_GameCore.hpp" +#include "OpenSHC/Globals/DAT_GameState.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" +#include "OpenSHC/Globals/DAT_WildlifeState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Map::Units::SomeTribeBehaviorType; + using Map::Units::UnitType; + using Map::Units::Instructions::UnitMatchSpeedEnum; + using UI::Enums::MenuViewType; + using WindowsHelper::Enums::BOOLEnum; + + /* + The same shape as updateCamelTribeBehavior. The grid cell is indexed in full in + both reads rather than through named x / 10 and y / 10 locals, which put the + tribe ID and `this` in other registers. + */ + // FUNCTION: STRONGHOLDCRUSADER 0x0052B390 + void TribesState::updateRabbitTribeBehavior(int tribeID) + { + int const targetUnitID = this->tribes[tribeID].selectionTargetUnitID; + int const rockyTiles = DAT_WildlifeState::instance + .grid[DAT_UnitsState::instance.units[targetUnitID].x / 10] + [DAT_UnitsState::instance.units[targetUnitID].y / 10] + .rockyTiles; + int const marshTiles = DAT_WildlifeState::instance + .grid[DAT_UnitsState::instance.units[targetUnitID].x / 10] + [DAT_UnitsState::instance.units[targetUnitID].y / 10] + .marshTiles; + BOOLEnum const noTunnelers = MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::isTribeFreeOfTunnelingUnits, this)(tribeID, this->tribes[tribeID].uid); + this->tribes[tribeID].unkIsAnimalTribe = 1; + int spawnInterval = 80; + if (DAT_GameState::instance.mapAndTime.eventCountdownRabbitInfestation) { + spawnInterval = 3; + } + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::spawnDeerLionOrRabbit, this)( + tribeID, spawnInterval, Map::Units::UT_RABBIT); + if (this->tribes[tribeID].initialMoveOrderGiven == 0) { + int const unitID = this->tribes[tribeID].selectionTargetUnitID; + this->tribes[tribeID].initialMoveOrderGiven = 1; + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::standUpAllTribeUnits, this)(tribeID); + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::giveTribeMoveInstruction, this)(tribeID, + DAT_UnitsState::instance.units[unitID].x, DAT_UnitsState::instance.units[unitID].y, 0, 0, + Map::Units::Instructions::UMSE_0); + this->tribes[tribeID].tribeBehaviorType = Map::Units::STBT_1; + return; + } + if (DAT_GameCore::instance.currentMenuViewType == UI::Enums::MVT_MAP_EDITOR_LANDSCAPING) { + this->tribes[tribeID].unknownCounter01 = 0; + return; + } + ushort const predatorNearby = this->tribes[tribeID].predatorNearby; + if (predatorNearby != 0) { + if (predatorNearby == 1) { + MACRO_CALL_MEMBER(Map::WildlifeState_Func::findAndSetNewRallyPointForDeerAndLions, + DAT_WildlifeState::ptr)(tribeID, 3, 0); + if (this->tribes[tribeID].rallyPointCount <= 0) { + MACRO_CALL_MEMBER(Map::WildlifeState_Func::findAndSetNewRallyPointForDeerAndLions, + DAT_WildlifeState::ptr)(tribeID, 3, 1); + } + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::standUpAllTribeUnits, this)(tribeID); + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::scatterTribeUnitsRandomly, this)(tribeID); + } + this->tribes[tribeID].predatorNearby = this->tribes[tribeID].predatorNearby + 1; + if ((short)this->tribes[tribeID].predatorNearby >= 3000) { + this->tribes[tribeID].predatorNearby = 0; + } + return; + } + if (this->tribes[tribeID].tribeBehaviorType == (SomeTribeBehaviorType)0) { + if (this->tribes[tribeID].unknownAttackRelatedUpdateCounter++ == 0) { + if (MACRO_CALL_MEMBER(Map::WildlifeState_Func::buildRallyPointPathForTribe, DAT_WildlifeState::ptr)( + tribeID, 4) + == FALSE) { + MACRO_CALL_MEMBER(Map::WildlifeState_Func::findAndSetNewRallyPointForDeerAndLions, + DAT_WildlifeState::ptr)(tribeID, 2, 1); + } + if (this->tribes[tribeID].rallyPointCount > 0) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::standUpAllTribeUnits, this)(tribeID); + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::applyLadderDestructionToTribeUnits, this)( + tribeID); + } + } else if (this->tribes[tribeID].unknownAttackRelatedUpdateCounter == 150) { + short const lastRallyPoint = this->tribes[tribeID].rallyPointCount; + if (lastRallyPoint > 0) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::giveUnitSelectionMoveInstructionNoMatchedSpeed, + this)(tribeID, this->tribes[tribeID].rallyPointArray[lastRallyPoint - 1][0], + this->tribes[tribeID].rallyPointArray[lastRallyPoint - 1][1], 0, 0); + } + } else if (noTunnelers != FALSE) { + this->tribes[tribeID].tribeBehaviorType = Map::Units::STBT_1; + this->tribes[tribeID].unknownAttackRelatedUpdateCounter = 0; + } + } else if (this->tribes[tribeID].tribeBehaviorType == Map::Units::STBT_1) { + if (marshTiles != 0) { + this->tribes[tribeID].wanderIntervalTicks = 20; + } else if (rockyTiles > 20) { + this->tribes[tribeID].wanderIntervalTicks = 20; + } else { + this->tribes[tribeID].wanderIntervalTicks = 400; + } + this->tribes[tribeID].unknownAttackRelatedUpdateCounter + = this->tribes[tribeID].unknownAttackRelatedUpdateCounter + 1; + if ((short)this->tribes[tribeID].unknownAttackRelatedUpdateCounter + >= this->tribes[tribeID].wanderIntervalTicks) { + this->tribes[tribeID].tribeBehaviorType = (SomeTribeBehaviorType)0; + this->tribes[tribeID].unknownAttackRelatedUpdateCounter = 0; + } + } + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/updateTribeCombatStanceBehavior.cpp b/src/OpenSHC/Map/Units/TribesState/updateTribeCombatStanceBehavior.cpp new file mode 100644 index 0000000000..194d200e0e --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/updateTribeCombatStanceBehavior.cpp @@ -0,0 +1,272 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Map/Navigation/PathFindingState.func.hpp" +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/Units/Behavior/UnitStanceEnum.hpp" +#include "OpenSHC/Map/Units/Instructions/UnitMatchSpeedEnum.hpp" +#include "OpenSHC/Map/Units/States/UnitState.hpp" +#include "OpenSHC/Map/Units/UnitInstructionType.hpp" +#include "OpenSHC/Map/Units/UnitLogicState.hpp" +#include "OpenSHC/Map/Units/UnitType.hpp" +#include "OpenSHC/WindowsHelper/Enums/BOOLEnum.hpp" + +#include "OpenSHC/Globals/DAT_BuildingsState.hpp" +#include "OpenSHC/Globals/DAT_GameState.hpp" +#include "OpenSHC/Globals/DAT_PathFindingState.hpp" +#include "OpenSHC/Globals/DAT_TileMapState.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" +#include "OpenSHC/Globals/DAT_ViewportRenderState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Map::Units::UnitInstructionType; + using Map::Units::UnitLogicState; + using Map::Units::UnitType; + using Map::Units::Behavior::UnitStanceEnum; + using Map::Units::Instructions::UnitMatchSpeedEnum; + using Map::Units::States::UnitState; + using WindowsHelper::Enums::BOOLEnum; + + // FUNCTION: STRONGHOLDCRUSADER 0x0052A7D0 + void TribesState::updateTribeCombatStanceBehavior(int tribeID) + { + short* counter; + UnitTypeShort targetUnitType; + int enemyUnitID; + BOOLEnum arrived; + int unitID2; + int targetUnitID; + int index; + uint x1; + uint y1; + int i; + short shortValue; + targetUnitID = this->tribes[tribeID].selectionTargetUnitID; + shortValue = this->tribes[tribeID].someUnitID; + /* + The non-zero arm comes first. The original tests the id sixteen bits wide + and skips forward when it is zero - `test ax, ax; je 0x8d` - so the block + that runs when the tribe still has a target unit is the fall-through. Written + the other way round (`if (!id)`) that whole 25-instruction block, down to the + UIT_UNIT_ATTACK_UNIT call, is emitted past the stance loop and every branch + in it is displaced. + */ + if (shortValue) { + index = (int)shortValue; + if (DAT_UnitsState::instance.units[index].uid == this->tribes[tribeID].someUnitUID) { + if ((int)DAT_UnitsState::instance.units[index].destinationX_2Unk + + DAT_ViewportRenderState::instance + .translationMatrix[DAT_UnitsState::instance.units[index].destinationY_2Unk] + .addXgetTile + == this->tribes[tribeID].someTile2) { + shortValue = this->tribes[tribeID].field_0x2be; + if (shortValue) { + this->tribes[tribeID].field_0x2be = shortValue + -1; + goto updateCounters; + } + if (DAT_UnitsState::instance.units[index].tile == this->tribes[tribeID].someTile) + goto updateCounters; + } + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::giveTribeAnInstruction, this)( + tribeID, Map::Units::UIT_UNIT_ATTACK_UNIT, index, this->tribes[tribeID].someUnitUID, 1); + } else { + this->tribes[tribeID].someUnitID = 0; + } + } else { + if (this->tribes[tribeID].unitStance == Map::Units::Behavior::USE_AGGRESSIVE) { + i = 0; + do { + index = ((this->tribes[tribeID].someUnitArrayIndex - i) + 10) % 10; + enemyUnitID = (int)this->tribes[tribeID].someUnitArray[index]; + if (enemyUnitID) { + if (DAT_UnitsState::instance.units[enemyUnitID].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[enemyUnitID].dying == 0 + && DAT_UnitsState::instance.units[enemyUnitID].uid + == this->tribes[tribeID].someUnitUIDArray[index] + && DAT_GameState::instance.mapAndTime + .playerTeams[DAT_UnitsState::instance.units[targetUnitID].owner] + != DAT_GameState::instance.mapAndTime + .playerTeams[DAT_UnitsState::instance.units[enemyUnitID].owner] + && DAT_TileMapState::instance + .PathConnectionLayer[DAT_UnitsState::instance.units[targetUnitID].tile] + == DAT_TileMapState::instance + .PathConnectionLayer[DAT_UnitsState::instance.units[enemyUnitID].tile]) { + index = (int)DAT_UnitsState::instance.units[targetUnitID].microXPosition + - (int)DAT_UnitsState::instance.units[enemyUnitID].microXPosition; + unitID2 = (int)DAT_UnitsState::instance.units[targetUnitID].microYPosition + - (int)DAT_UnitsState::instance.units[enemyUnitID].microYPosition; + if (index * index + unitID2 * unitID2 < 250000) { + if ((this->tribes[tribeID].unknownAttackRelatedUpdateCounter == 0) + && (this->tribes[tribeID].aggressiveStanceCounter == 0x3b)) { + index = 0; + if (this->tribes[tribeID].size < 1) + goto attackEnemyUnit; + goto checkIdleMeleeUnits; + } + break; + } + } else { + this->tribes[tribeID].someUnitArray[index] = 0; + } + } + i = i + 1; + } while (i < 10); + } + } + goto updateCounters; + checkIdleMeleeUnits: + do { + unitID2 + = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)(tribeID, index); + index = index + 1; + if (DAT_UnitsState::instance.units[unitID2].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[unitID2].dying == 0 + && DAT_UnitsState::instance.units[unitID2].state.generic != Map::Units::States::US_MELEE_ATTACK) { + switch (DAT_UnitsState::instance.units[unitID2].unitType) { + case Map::Units::UT_TUNNELER: + case Map::Units::UT_E_SPEAR: + case Map::Units::UT_E_PIKE: + case Map::Units::UT_E_MACE: + case Map::Units::UT_E_SWORD: + case Map::Units::UT_E_KNIGHT: + case Map::Units::UT_E_MONK: + case Map::Units::UT_S_BATTERINGRAM: + if (DAT_UnitsState::instance.units[unitID2].SA == 0) + goto updateCounters; + } + } + } while (index < this->tribes[tribeID].size); + attackEnemyUnit: + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::giveTribeAnInstruction, this)( + tribeID, ((UnitInstructionType)0x20), enemyUnitID, DAT_UnitsState::instance.units[enemyUnitID].uid, 0); + updateCounters: + counter = (short*)&this->tribes[tribeID].unknownAttackRelatedUpdateCounter; + *counter = *counter + 1; + /* + Both counters are tested through the `short*` that incremented them. The + original re-reads each field after the add (`movzx eax, word ptr + [esi + 0x56]`, `cmp ax, 0x32`, signed `jle`). A fresh read of the ushort + field folds into `cmp word ptr [mem]` instead, and the test is unsigned. + */ + if (0x32 < *counter) { + /* + The rallying arm comes first: `xor ebx, ebx; cmp word ptr [esi + 0x22e], + bx; je 0x109` jumps away when the flag is clear, so the tribe-is-rallying + body is the fall-through and the aggressive-stance body goes in the far + block. + */ + if (this->tribes[tribeID].isRallyingUnk) { + arrived = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::allUnitsReachedTheirDestination, this)( + tribeID); + /* + The import had this guard with an empty body; nothing advances the + rally point until the tribe has arrived. + */ + if (arrived) { + shortValue = this->tribes[tribeID].rallyPointCount; + index = this->tribes[tribeID].currentRallyPointIndex + 1; + this->tribes[tribeID].unknownAttackRelatedUpdateCounter = 0; + if (index >= shortValue) { + if (this->tribes[tribeID].isRallyingUnk == -1) { + this->tribes[tribeID].currentRallyPointIndex = 0; + this->tribes[tribeID].isRallyingUnk = 0; + } + index = 0; + } + if (this->tribes[tribeID].isRallyingUnk != 0) { + x1 = (uint)this->tribes[tribeID].rallyPointArray[index][0]; + y1 = (uint)this->tribes[tribeID].rallyPointArray[index][1]; + this->tribes[tribeID].currentRallyPointIndex = (short)index; + targetUnitType = DAT_UnitsState::instance.units[targetUnitID].unitType; + if (targetUnitType == Map::Units::UT_E_ARCHER || targetUnitType == Map::Units::UT_E_XBOW + || targetUnitType == Map::Units::UT_A_ARCHER + || targetUnitType == Map::Units::UT_A_SLINGER + || targetUnitType == Map::Units::UT_A_FIRETHROWER) { + if (0x1b0 < DAT_UnitsState::instance.units[targetUnitID].closestEnemyMicroDistance) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::giveTribeMoveInstruction, this)( + tribeID, x1, y1, 0, 0, Map::Units::Instructions::UMSE_0); + } + } else if (targetUnitType == Map::Units::UT_A_HARCHER) { + MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::giveUnitSelectionMoveInstructionNoMatchedSpeed, this)( + tribeID, x1, y1, 0, 0); + } else if ((0x60 < DAT_UnitsState::instance.units[targetUnitID].closestEnemyMicroDistance) + || (this->tribes[tribeID].unitStance != Map::Units::Behavior::USE_AGGRESSIVE)) { + MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::giveUnitSelectionMoveInstructionNoMatchedSpeed, this)( + tribeID, x1, y1, 0, 0); + } + } + } + } else { + if (this->tribes[tribeID].unitStance == Map::Units::Behavior::USE_AGGRESSIVE) { + counter = &this->tribes[tribeID].aggressiveStanceCounter; + *counter = *counter + 1; + /* + The import had this guard with an empty body, so the counter was + reset and the arm entered on every tick. The original's + `cmp ax, 0x3c; jl` skips the whole arm. + */ + if (0x3c <= *counter) { + shortValue = this->tribes[tribeID].size; + this->tribes[tribeID].aggressiveStanceCounter = 0; + if (0 < shortValue) { + index = 0; + do { + unitID2 = MACRO_CALL_MEMBER( + Map::Units::TribesState_Func::getUnitIDForIndexInTribe, this)(tribeID, index); + index = index + 1; + if (DAT_UnitsState::instance.units[unitID2].logicalState == Map::Units::ULS_NORMAL + && DAT_UnitsState::instance.units[unitID2].dying == 0 + && DAT_UnitsState::instance.units[unitID2].state.generic + != Map::Units::States::US_MELEE_ATTACK) { + switch (DAT_UnitsState::instance.units[unitID2].unitType) { + case Map::Units::UT_TUNNELER: + case Map::Units::UT_E_SPEAR: + case Map::Units::UT_E_PIKE: + case Map::Units::UT_E_MACE: + case Map::Units::UT_E_SWORD: + case Map::Units::UT_E_KNIGHT: + case Map::Units::UT_E_MONK: + case Map::Units::UT_S_BATTERINGRAM: + case Map::Units::UT_A_SLAVE: + case Map::Units::UT_A_ASSASSIN: + case Map::Units::UT_A_SWORDSMAN: + if (DAT_UnitsState::instance.units[unitID2].SA == 0) + goto checkScatterMove; + } + } + } while (index < this->tribes[tribeID].size); + } + MACRO_CALL_MEMBER( + Map::Navigation::PathFindingState_Func::aggressiveStanceTargetBuildingAtRange, + DAT_PathFindingState::ptr)(targetUnitID, 15); + if (DAT_PathFindingState::instance.ALG_ResultTile) { + shortValue = DAT_TileMapState::instance + .BuildingLayer[DAT_PathFindingState::instance.ALG_ResultTile]; + if (shortValue) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::giveTribeAnInstruction, this)( + tribeID, (UnitInstructionType)0x26, (int)shortValue, + DAT_BuildingsState::instance.buildings[shortValue].uid, 0); + } else { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::giveTribeAnInstruction, this)( + tribeID, (UnitInstructionType)0x25, + DAT_PathFindingState::instance.ALG_ResultTile, 0, 0); + } + } + } + } + } + checkScatterMove: + if (this->tribes[tribeID].pendingScatterMove != 0) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::moveTribeToIndexedNearbyTile, this)(tribeID); + this->tribes[tribeID].pendingScatterMove = 0; + } + } + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/updateTribeUnitAssignments.cpp b/src/OpenSHC/Map/Units/TribesState/updateTribeUnitAssignments.cpp new file mode 100644 index 0000000000..37e1a608d6 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/updateTribeUnitAssignments.cpp @@ -0,0 +1,103 @@ +#include "../../../Map.func.hpp" + +#include "OpenSHC/Map/Units/TribesState.func.hpp" +#include "OpenSHC/Map/Units/UnitLogicState.hpp" + +#include "OpenSHC/Globals/DAT_CurrentTribeID.hpp" +#include "OpenSHC/Globals/DAT_GameCore.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + using Map::Units::UnitLogicState; + + // FUNCTION: STRONGHOLDCRUSADER 0x00527330 + void TribesState::updateTribeUnitAssignments() + { + uint _unitID; + this->clans = 0; + this->field_0x8 = 1; + /* + A `for`, not the original's do-while, because the two `continue`s have to run + the increment: the label they replace sat in front of it. The first test is + always true, so the two forms are equivalent. This costs 2.9 points + (60.0% -> 57.1%) for the entry test the do-while does not have; writing the + arms out with a `clearTribe` call in each instead measures worse still + (quick_diff 0.6076 against 0.6250), so the `for` stands. The import's + `if (0x4e1 < instance) {}` had an empty body, which made this loop run + forever. + */ + for (DAT_CurrentTribeID::instance = 1; (int)DAT_CurrentTribeID::instance < 1250; + DAT_CurrentTribeID::instance = DAT_CurrentTribeID::instance + 1) { + /* + The state, the size and the time are all compared as 16-bit values + (`movzx ecx, word ptr`, then `cmp cx, bx` / `cmp cx, 3` / `jle`), so they + stay `short` here; the earlier `(ushort)` casts turned the signed `jle` on + the size into a test only zero could pass. It costs 1.4 points + (58.4% -> 57.0%), which is the price of being right about negative sizes. + */ + short const _state = this->tribes[DAT_CurrentTribeID::instance].tribeState; + int _tribeUnitIndex = 0; + if (_state) { + int _tribeID = DAT_CurrentTribeID::instance; + if (_state != 3) { + short const _size = this->tribes[DAT_CurrentTribeID::instance].size; + /* + The unit sweep is the fall-through. The original compares the + size against the zero it is holding in bx and jumps 0x7d forward + when it is not positive (`cmp cx, bx; jle 0x7d`), so the sweep + follows the test and the four-line time check goes in the far + block. The `<= 0` sense itself is right and stays - see above. + */ + if (0 < _size) { + int const _tribeSize = (int)_size; + int local_4 = 0; + if (0 < _tribeSize) { + do { + _unitID = MACRO_CALL_MEMBER(Map::Units::TribesState_Func::getSpecificUnitFromTribe, + this)(_tribeID, _tribeUnitIndex); + int _unitLogicalState = DAT_UnitsState::instance.units[_unitID].logicalState; + _tribeUnitIndex = _tribeUnitIndex + 1; + /* + `< 1` stays although the original has + `test edx, edx; jle` where ours gives + `cmp edx, 1; jl`: written `<= 0` the whole chain + below it re-lays out and the function measures + 75.0% -> 55.3%. The instruction is one line; the + block order it costs is twenty. + */ + if (_unitLogicalState < 1 + || (2 < _unitLogicalState + && (_unitLogicalState != Map::Units::ULS_TRANSITIONING)) + || DAT_UnitsState::instance.units[_unitID].dying != 0 + || DAT_UnitsState::instance.units[_unitID].tribeID != _tribeID) { + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::removeUnitFromTribe, this)( + _unitID, _tribeID); + _tribeID = DAT_CurrentTribeID::instance; + } else { + local_4 = local_4 + 1; + } + } while (_tribeUnitIndex < _tribeSize); + if (local_4) { + this->clans = this->clans + 1; + this->field_0x8 = DAT_CurrentTribeID::instance; + continue; + } + } + } else { + short const _tribeTime = this->tribes[DAT_CurrentTribeID::instance].time; + if (_tribeTime && (int)DAT_GameCore::instance.mapTimeInTicks <= (int)_tribeTime + && _tribeTime) + continue; + } + } + MACRO_CALL_MEMBER(Map::Units::TribesState_Func::clearTribe, this)(_tribeID); + } + } + } + + } +} +} diff --git a/src/OpenSHC/Map/Units/TribesState/updateTribes.cpp b/src/OpenSHC/Map/Units/TribesState/updateTribes.cpp new file mode 100644 index 0000000000..8217bc7b59 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/updateTribes.cpp @@ -0,0 +1,123 @@ +#include "../TribesState.func.hpp" + +#include "OpenSHC/Map/Units/TroopValueState.func.hpp" +#include "OpenSHC/AI/Tribes/AITribeType.hpp" +#include "OpenSHC/Game/GameMode.hpp" + +#include "OpenSHC/Globals/DAT_CurrentTribeID.hpp" +#include "OpenSHC/Globals/DAT_GameCore.hpp" +#include "OpenSHC/Globals/DAT_GameState.hpp" +#include "OpenSHC/Globals/DAT_GameSynchronyState.hpp" +#include "OpenSHC/Globals/DAT_TroopValueState.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + // FUNCTION: STRONGHOLDCRUSADER 0x0052B860 + void TribesState::updateTribes() + { + uint const tickSlot = DAT_GameCore::instance.mapTimeInTicks & 0x1f; + DAT_GameState::instance.mapAndTime.eventCountdownRabbitInfestation--; + DAT_CurrentTribeID::instance = 1; + do { + if (this->tribes[DAT_CurrentTribeID::instance].tribeState == 2) { + if (this->tribes[DAT_CurrentTribeID::instance].countdown2 > 0) { + this->tribes[DAT_CurrentTribeID::instance].countdown2--; + } + if ((DAT_CurrentTribeID::instance & 0x1f) == tickSlot) { + MACRO_CALL_MEMBER(TribesState_Func::computeTribePercentages, this)( + DAT_CurrentTribeID::instance); + } + if (DAT_GameSynchronyState::instance + .currentPlayerFullIDArray[this->tribes[DAT_CurrentTribeID::instance].owner] + != -1 + || DAT_GameSynchronyState::instance.currentGameMode != Game::GM_SOLITARY) { + // human players: only the animal tribes keep their own behaviour + switch (this->tribes[DAT_CurrentTribeID::instance].tribeType) { + case 13: + MACRO_CALL_MEMBER(TribesState_Func::processDeerMoving, this)(DAT_CurrentTribeID::instance); + break; + case 14: + MACRO_CALL_MEMBER(TribesState_Func::updateLionWolfTribeBehavior, this)( + DAT_CurrentTribeID::instance); + break; + case 15: + MACRO_CALL_MEMBER(TribesState_Func::updateRabbitTribeBehavior, this)( + DAT_CurrentTribeID::instance); + break; + case 16: + MACRO_CALL_MEMBER(TribesState_Func::updateCamelTribeBehavior, this)( + DAT_CurrentTribeID::instance); + break; + default: + MACRO_CALL_MEMBER(TribesState_Func::updateTribeCombatStanceBehavior, this)( + DAT_CurrentTribeID::instance); + break; + } + } else { + switch (this->tribes[DAT_CurrentTribeID::instance].tribeType) { + case AI::Tribes::AITT_TUNNELERS: + case AI::Tribes::AITT_ARCHERS: + case AI::Tribes::AITT_LADDERMEN: + case AI::Tribes::AITT_SPEARMEN: + case AI::Tribes::AITT_PIKEMEN: + case AI::Tribes::AITT_CROSSBOWMEN: + case AI::Tribes::AITT_SWORDSMEN: + case AI::Tribes::AITT_MACEMEN: + case AI::Tribes::AITT_KNIGHTS: + case AI::Tribes::AITT_ENGINEERS: + case AI::Tribes::AITT_HOPS_FARMER_UNK: + case 19: + case 20: + case 21: + case AI::Tribes::AITT_CATAPULT: + case AI::Tribes::AITT_TREBUCHET: + case AI::Tribes::AITT_FIRE_BALLISTA: + case AI::Tribes::AITT_ARAB_ARCHER: + case AI::Tribes::AITT_ARAB_SLAVE: + case AI::Tribes::AITT_ARAB_SLINGER: + case AI::Tribes::AITT_ARAB_ASSASSIN: + case AI::Tribes::AITT_ARAB_HORSE_ARCHER: + case AI::Tribes::AITT_ARAB_SWORDSMAN: + case AI::Tribes::AITT_ARAB_FIRETHROWER: + MACRO_CALL_MEMBER(TroopValueState_Func::updateTribeBehaviorBasedOnBehaviorType, + DAT_TroopValueState::ptr)(DAT_CurrentTribeID::instance); + break; + case 13: + MACRO_CALL_MEMBER(TribesState_Func::processDeerMoving, this)(DAT_CurrentTribeID::instance); + break; + case 14: + MACRO_CALL_MEMBER(TribesState_Func::updateLionWolfTribeBehavior, this)( + DAT_CurrentTribeID::instance); + break; + case 15: + MACRO_CALL_MEMBER(TribesState_Func::updateRabbitTribeBehavior, this)( + DAT_CurrentTribeID::instance); + break; + case 16: + MACRO_CALL_MEMBER(TribesState_Func::updateCamelTribeBehavior, this)( + DAT_CurrentTribeID::instance); + break; + case 17: + case 18: + MACRO_CALL_MEMBER(TribesState_Func::markTribeAsAnimalTribe, this)( + DAT_CurrentTribeID::instance); + break; + default: + MACRO_CALL_MEMBER(TribesState_Func::updateTribeCombatStanceBehavior, this)( + DAT_CurrentTribeID::instance); + break; + } + } + if (this->tribes[DAT_CurrentTribeID::instance].countdown != 0) { + this->tribes[DAT_CurrentTribeID::instance].countdown--; + } + } + DAT_CurrentTribeID::instance++; + } while ((int)DAT_CurrentTribeID::instance < countof(this->tribes)); + } + + } // namespace Units +} // namespace Map +} // namespace OpenSHC diff --git a/src/OpenSHC/Map/Units/TribesState/upgradeTribeArrayLayoutForMapVersion.cpp b/src/OpenSHC/Map/Units/TribesState/upgradeTribeArrayLayoutForMapVersion.cpp new file mode 100644 index 0000000000..9fed500be6 --- /dev/null +++ b/src/OpenSHC/Map/Units/TribesState/upgradeTribeArrayLayoutForMapVersion.cpp @@ -0,0 +1,35 @@ +#include "../TribesState.func.hpp" + +#include "OpenSHC/OS.func.hpp" + +namespace OpenSHC { +namespace Map { + namespace Units { + + // Old record layout: 0x26C bytes per tribe (100-word member bitmask), tail of 0x16C bytes at old offset 0x100. + // The original calls the CRT memmove at 0x583760 twice (the first one guarded by dst != src, 0x523F16), + // through the OS_Func::_memmove resolver. The new second half of the + // bitmask is zeroed with rep stosd (0x32 dwords, 0x523F62): MSVC 2005 emits that for this loop but a call for + // memset(p, 0, 200) (tested). receivedMapVersion is compared signed (jge at 0x523EFF). Tribes 0x4E1 down to 0. + // FUNCTION: STRONGHOLDCRUSADER 0x00523EF0 + void TribesState::upgradeTribeArrayLayoutForMapVersion( + PackagedFileMagicNum receivedMapVersion, PackagedFileMagicNum packagerMapVersion) + { + if (receivedMapVersion != packagerMapVersion && (int)receivedMapVersion < 0xa9) { + for (int tribeIndex = 1249; tribeIndex >= 0; --tribeIndex) { + char* const oldRecord = (char*)this->tribes + tribeIndex * 0x26c; + Tribe* const tribe = &this->tribes[tribeIndex]; + if ((void*)tribe != (void*)oldRecord) { + MACRO_CALL(OpenSHC::OS_Func::_memmove)(tribe, oldRecord, 0x26c); + } + MACRO_CALL(OpenSHC::OS_Func::_memmove)(&tribe->field_0x1c8, oldRecord + 0x100, 0x16c); + for (int k = 100; k < 200; ++k) { + tribe->unitSelectionBitMasked[k] = 0; + } + } + } + } + + } +} +} diff --git a/src/OpenSHC/OS/OS.cpp b/src/OpenSHC/OS/OS.cpp index 0f85c5144a..19b7c36e38 100644 --- a/src/OpenSHC/OS/OS.cpp +++ b/src/OpenSHC/OS/OS.cpp @@ -143,6 +143,9 @@ namespace OS { return _strnicmp(_Str1, _Str2, _MaxCount); } + // STUB: STRONGHOLDCRUSADER 0x00583760 + void* _memmove(void* _Dst, void* _Src, size_t _Size) { return memmove(_Dst, _Src, _Size); } + // STUB: STRONGHOLDCRUSADER 0x00583D55 void _exit(int _Code) { exit(_Code); } diff --git a/status/addresses-SHC-3BB0A8C1.txt b/status/addresses-SHC-3BB0A8C1.txt index 47b2ecfdf6..0474ace7c2 100644 --- a/status/addresses-SHC-3BB0A8C1.txt +++ b/status/addresses-SHC-3BB0A8C1.txt @@ -46387,15 +46387,15 @@ SHC_3BB0A8C1_0x00521210 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00521240 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x00521280 | 0.0% | Pending +SHC_3BB0A8C1_0x00521280 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x00521500 | 0.0% | Pending +SHC_3BB0A8C1_0x00521500 | 91.4% | Reimplemented; the original loads the second tribe ID before the first speed clamp but the tribe field after it SHC_3BB0A8C1_0x00521690 | 0.0% | Pending SHC_3BB0A8C1_0x00521720 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x005217E0 | 0.0% | Pending +SHC_3BB0A8C1_0x005217E0 | 92.4% | Knight count is copied through eax; the original loads it straight into edi SHC_3BB0A8C1_0x00521A48 | 0.0% | Pending @@ -46505,7 +46505,7 @@ SHC_3BB0A8C1_0x00521A8E | 0.0% | Pending SHC_3BB0A8C1_0x00521A8F | 0.0% | Pending -SHC_3BB0A8C1_0x00521A90 | 0.0% | Pending +SHC_3BB0A8C1_0x00521A90 | 94.4% | unitID load hoisted above the range chain; knight count is copied through eax SHC_3BB0A8C1_0x00521E50 | 0.0% | Pending @@ -46633,9 +46633,9 @@ SHC_3BB0A8C1_0x00521EA5 | 0.0% | Pending SHC_3BB0A8C1_0x00521EA6 | 0.0% | Pending -SHC_3BB0A8C1_0x00521EB0 | 82.4% | pop esi scheduling +SHC_3BB0A8C1_0x00521EB0 | 94.1% | Reimplemented, asm differs -SHC_3BB0A8C1_0x00521EF0 | 0.0% | Pending +SHC_3BB0A8C1_0x00521EF0 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00522030 | 0.0% | Pending @@ -46763,7 +46763,7 @@ SHC_3BB0A8C1_0x00522082 | 0.0% | Pending SHC_3BB0A8C1_0x00522083 | 0.0% | Pending -SHC_3BB0A8C1_0x00522090 | 0.0% | Pending +SHC_3BB0A8C1_0x00522090 | 98.0% | param load hoisted, asm differs SHC_3BB0A8C1_0x00522110 | 100.0% | Reimplemented @@ -46781,9 +46781,9 @@ SHC_3BB0A8C1_0x005222B0 | 0.0% | Pending SHC_3BB0A8C1_0x00522360 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x00522390 | 0.0% | Pending +SHC_3BB0A8C1_0x00522390 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x00522410 | 0.0% | Pending +SHC_3BB0A8C1_0x00522410 | 64.1% | the original keeps zero in ecx and saves only esi/edi; ours keeps zero in edi and needs ebx SHC_3BB0A8C1_0x005224E0 | 100.0% | Reimplemented @@ -46791,15 +46791,15 @@ SHC_3BB0A8C1_0x00522520 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00522550 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x00522590 | 0.0% | Pending +SHC_3BB0A8C1_0x00522590 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x00522630 | 0.0% | Pending +SHC_3BB0A8C1_0x00522630 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x00522720 | 0.0% | Pending +SHC_3BB0A8C1_0x00522720 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x005227E0 | 0.0% | Pending +SHC_3BB0A8C1_0x005227E0 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x00522890 | 0.0% | Pending +SHC_3BB0A8C1_0x00522890 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00522950 | 100.0% | Reimplemented @@ -46815,11 +46815,11 @@ SHC_3BB0A8C1_0x00522C20 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00522C50 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x00522CA0 | 0.0% | Pending +SHC_3BB0A8C1_0x00522CA0 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00522DD0 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x00522EF0 | 0.0% | Pending +SHC_3BB0A8C1_0x00522EF0 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00522F70 | 100.0% | Reimplemented @@ -46861,7 +46861,7 @@ SHC_3BB0A8C1_0x005237F0 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00523920 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x00523A30 | 0.0% | Pending +SHC_3BB0A8C1_0x00523A30 | 82.5% | Constant 1 in edi with the unit index on the stack SHC_3BB0A8C1_0x00523B00 | 0.0% | Pending @@ -46871,7 +46871,7 @@ SHC_3BB0A8C1_0x00523E30 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00523EB0 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x00523EF0 | 0.0% | Pending +SHC_3BB0A8C1_0x00523EF0 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00523F70 | 100.0% | Reimplemented @@ -46891,11 +46891,11 @@ SHC_3BB0A8C1_0x005242B0 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00524340 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x005244D0 | 0.0% | Pending +SHC_3BB0A8C1_0x005244D0 | 69.0% | Register allocation: x/y swapped; the merged arm tail lands after 0x3f7, not after 0x3f2 SHC_3BB0A8C1_0x00524890 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x00524930 | 0.0% | Pending +SHC_3BB0A8C1_0x00524930 | 58.7% | the original shares the argument pushes of the two non-horse path calls and keeps the sort index in ecx; ours pushes per call SHC_3BB0A8C1_0x005249C0 | 0.0% | Pending @@ -46903,17 +46903,17 @@ SHC_3BB0A8C1_0x00524A10 | 0.0% | Pending SHC_3BB0A8C1_0x00524A30 | 0.0% | Pending -SHC_3BB0A8C1_0x00524B30 | 0.0% | Pending +SHC_3BB0A8C1_0x00524B30 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00524BF0 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x00524CA0 | 0.0% | Pending +SHC_3BB0A8C1_0x00524CA0 | 66.1% | the original keeps the unit index in a stack slot and tribeID in ebp, and inlines the FALSE epilogue after the first guard SHC_3BB0A8C1_0x00524D80 | 0.0% | Pending SHC_3BB0A8C1_0x00524E20 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x00524EF0 | 0.0% | Pending +SHC_3BB0A8C1_0x00524EF0 | 72.6% | Register allocation: the bubble-sort counter takes ebx; the original keeps it in the tribeID parameter slot SHC_3BB0A8C1_0x00525060 | 0.0% | Pending @@ -46945,13 +46945,13 @@ SHC_3BB0A8C1_0x00525870 | 97.1% | Reimplemented, asm differs SHC_3BB0A8C1_0x00525970 | 97.1% | Reimplemented, asm differs -SHC_3BB0A8C1_0x00525A70 | 0.0% | Pending +SHC_3BB0A8C1_0x00525A70 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00525B70 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x00525BA0 | 0.0% | Pending +SHC_3BB0A8C1_0x00525BA0 | 96.1% | Scratch-register order in the spawn and herd-tail calls -SHC_3BB0A8C1_0x00525F20 | 0.0% | Pending +SHC_3BB0A8C1_0x00525F20 | 100.0% | Reimplemented SHC_3BB0A8C1_0x005260B0 | 100.0% | Reimplemented @@ -46961,19 +46961,19 @@ SHC_3BB0A8C1_0x005262A0 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00526370 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x005263A0 | 0.0% | Pending +SHC_3BB0A8C1_0x005263A0 | 52.6% | Stack slot and register assignment differ (this is kept in edi; the original spills it) SHC_3BB0A8C1_0x005266F0 | 0.0% | Pending SHC_3BB0A8C1_0x00526D50 | 0.0% | Pending -SHC_3BB0A8C1_0x00526F00 | 0.0% | Pending +SHC_3BB0A8C1_0x00526F00 | 90.3% | Register allocation: this and index swap edi/ebp (reg_scores tie) -SHC_3BB0A8C1_0x005270F0 | 0.0% | Pending +SHC_3BB0A8C1_0x005270F0 | 58.6% | this held in a register where the original spills it and keeps the loop index in ebp -SHC_3BB0A8C1_0x00527330 | 0.0% | Pending +SHC_3BB0A8C1_0x00527330 | 75.0% | the original compares the 16-bit fields against the zero held in bx and keeps the repeated time test unfolded -SHC_3BB0A8C1_0x00527440 | 0.0% | Pending +SHC_3BB0A8C1_0x00527440 | 60.5% | the original lays out the game-mode checks after the first call inline; ours moves them and loads the arguments in another order SHC_3BB0A8C1_0x005275A0 | 0.0% | Pending @@ -47085,7 +47085,7 @@ SHC_3BB0A8C1_0x00527C74 | 0.0% | Pending SHC_3BB0A8C1_0x00527C78 | 0.0% | Pending -SHC_3BB0A8C1_0x00527C80 | 0.0% | Pending +SHC_3BB0A8C1_0x00527C80 | 60.8% | register allocation; caching the tribe base (Tribe& or a shifted pointer) costs about 5 points, see the notes in the source SHC_3BB0A8C1_0x005292C0 | 0.0% | Pending @@ -48877,9 +48877,9 @@ SHC_3BB0A8C1_0x0052A638 | 0.0% | Pending SHC_3BB0A8C1_0x0052A640 | 98.4% | Reimplemented, one instruction off: MSVC anchors the strength-reduced loop pointer on XYPair::x where the original anchors on ::y, so the loop sentinel immediate differs -SHC_3BB0A8C1_0x0052A700 | 0.0% | Pending +SHC_3BB0A8C1_0x0052A700 | 98.6% | loop end is a relocation (&field_0xcc4[40].y) where the original has the absolute 0xb4df44 -SHC_3BB0A8C1_0x0052A7D0 | 0.0% | Pending +SHC_3BB0A8C1_0x0052A7D0 | 81.2% | Aggressive-stance scan: the slot address and the tribe offset are hoisted differently SHC_3BB0A8C1_0x0052ACB4 | 0.0% | Pending @@ -49141,15 +49141,15 @@ SHC_3BB0A8C1_0x0052AD41 | 0.0% | Pending SHC_3BB0A8C1_0x0052AD42 | 0.0% | Pending -SHC_3BB0A8C1_0x0052AD50 | 0.0% | Pending +SHC_3BB0A8C1_0x0052AD50 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x0052B110 | 0.0% | Pending +SHC_3BB0A8C1_0x0052B110 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x0052B390 | 0.0% | Pending +SHC_3BB0A8C1_0x0052B390 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x0052B630 | 0.0% | Pending +SHC_3BB0A8C1_0x0052B630 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x0052B860 | 0.0% | Pending +SHC_3BB0A8C1_0x0052B860 | 91.2% | Reimplemented; the original keeps two identical markTribeAsAnimalTribe arms (tribe types 17 and 18) that MSVC merges here, which shifts every branch by 10 bytes SHC_3BB0A8C1_0x0052B9A0 | 0.0% | Pending diff --git a/tools/reimplementation-helper/batch/declare_at_use.py b/tools/reimplementation-helper/batch/declare_at_use.py index e64f6c68f0..4205732eb9 100644 --- a/tools/reimplementation-helper/batch/declare_at_use.py +++ b/tools/reimplementation-helper/batch/declare_at_use.py @@ -9,8 +9,14 @@ tracking brace depth from that assignment to the last use. Anything it cannot prove is left alone and reported, so the output doubles as a list of what still needs a hand. -Declaration position does not change code generation, so this is a readability pass; run -it before measuring, not instead of. +Declaration position *does* change code generation, so measure after running this. MSVC +assigns stack slots in declaration order - see perm_decls.py - and moving a declaration +past another one moves both locals between slots, which usually moves them between +registers too. Three functions in Map/Units/TribesState turned on nothing else: +getMajorityArcherTypeEuropeanOrArabian 69.6% -> 88.2%, getTribeAliveStatus +68.6% -> 85.9% and updateTribeRallyFlags 74.7% -> 100%, all three just by declaring the +local that reads the tribe size after the zero-initialised counters instead of before +them. This docstring used to say the opposite; it was wrong. usage: declare_at_use.py [path-filter] diff --git a/tools/reimplementation-helper/batch/deparen.py b/tools/reimplementation-helper/batch/deparen.py index 305163585d..76e0b66fbc 100644 --- a/tools/reimplementation-helper/batch/deparen.py +++ b/tools/reimplementation-helper/batch/deparen.py @@ -65,6 +65,11 @@ def scan_top(s): continue if tok in ("<", ">") and s[i - 1:i + 1] == "->": continue + # a shift is not a comparison: splitting `1 << n` at the first `<` + # rejoins it as `1 < < n`, which still parses as far as the rewriter + # is concerned and then fails to compile. + if tok in ("<", ">") and tok in (s[i - 1:i], s[i + 1:i + 2]): + continue hit = tok break if hit: diff --git a/tools/reimplementation-helper/batch/diff_anchor.py b/tools/reimplementation-helper/batch/diff_anchor.py index 7ce6bcc8ea..df4029bfc7 100644 --- a/tools/reimplementation-helper/batch/diff_anchor.py +++ b/tools/reimplementation-helper/batch/diff_anchor.py @@ -42,10 +42,17 @@ import common -# `lea esi, [ecx + 0x367e4]`, `add esi, 0x367e4`, `lea ebx, [eax + ebp]` is not an anchor +# `lea esi, [ecx + 0x367e4]`, `add esi, 0x367e4`, `lea ebx, [eax + ebp]` is not an anchor. +# A cursor into a global array is set up with neither of those - it is +# `mov esi, StructResolver::Instance<..>::instance+3568 (OFFSET)` - so that form counts too, +# with the offset into the global as the constant. Missing it hid the 0xac anchor difference in +# addUnitsToTribeAndComputeMovementSpeed and addUnitToTribeAndUpdateTribeMovementSpeed, where the +# original anchors the unit cursor on `movementSpeed` and we anchor it on `dying`. ANCHOR_RE = re.compile(r"^(?:lea (e[a-z]{2}), \[(e[a-z]{2}) \+ (0x[0-9a-f]{4,}|\d{4,})\]" - r"|add (e[a-z]{2}), (0x[0-9a-f]{4,}|\d{4,}))$") + r"|add (e[a-z]{2}), (0x[0-9a-f]{4,}|\d{4,})" + r"|mov (e[a-z]{2}), \S*::instance\+(\d{4,})(?: \(OFFSET\))?)$") MIN_ANCHOR = 0x1000 +MIN_FIELD_ANCHOR = 0x40 def op(line): @@ -59,9 +66,12 @@ def anchors(lines): m = ANCHOR_RE.match(line) if not m: continue - reg = m.group(1) or m.group(4) - value = int(m.group(3) or m.group(5), 0) - if value >= MIN_ANCHOR: + reg = m.group(1) or m.group(4) or m.group(6) + value = int(m.group(3) or m.group(5) or m.group(7), 0) + # MIN_ANCHOR exists to keep small `add reg, N` strides out of the way. It does not + # apply to the mov-into-global form: there the constant is an offset inside the + # global, so a few thousand is an ordinary anchor - 3568 for the unit cursor. + if value >= (MIN_FIELD_ANCHOR if m.group(6) else MIN_ANCHOR): out.append((reg, value)) return out diff --git a/tools/reimplementation-helper/batch/diff_cmp_operands.py b/tools/reimplementation-helper/batch/diff_cmp_operands.py new file mode 100644 index 0000000000..b2cb37d0b8 --- /dev/null +++ b/tools/reimplementation-helper/batch/diff_cmp_operands.py @@ -0,0 +1,77 @@ +"""Comparisons written with their operands the wrong way round. + +`if (a < b)` and `if (b > a)` are the same test and MSVC emits a different `cmp` for +each: the left operand goes first. So a comparison written the other way round costs +the `cmp` and its `jcc` or `setcc`, and neither diff_jcc nor diff_inv_jcc reports it - +the branch sense is consistent with the operands, so nothing looks inverted. + +It found +10.1 on snapshotSelectionTribeAndComputeStance (`cmp ecx, esi; setge al` +against our `cmp esi, ecx; setle al`) and a two-instruction miss in +addUnitsToTribeAndComputeMovementSpeed. + +This looks for an orig `cmp A, B` facing an ours `cmp B, A` in the same diff block, +with the following jcc or setcc mirrored to match - which is what makes it a swap +rather than an unrelated pair. + +usage: diff_cmp_operands.py +""" + +import re +import sys + +import common + +MIRROR = {"jl": "jg", "jg": "jl", "jle": "jge", "jge": "jle", + "jb": "ja", "ja": "jb", "jbe": "jae", "jae": "jbe", + "setl": "setg", "setg": "setl", "setle": "setge", "setge": "setle", + "setb": "seta", "seta": "setb", "setbe": "setae", "setae": "setbe"} + +CMP = re.compile(r"^cmp\s+([^,]+),\s*(.+)$") + + +def operands(line): + m = CMP.match(common._normalize(line).strip()) + return (m.group(1).strip(), m.group(2).strip()) if m else None + + +def follower(rows, i): + for r in rows[i + 1:i + 3]: + w = r.strip().split() + if w and w[0] in MIRROR: + return w[0] + return None + + +def main(): + hits = 0 + for f, e, a in common.entries(common.load_diff()): + if not e or float(e["matching"]) >= 1.0: + continue + found = [] + for hunk in e.get("diff") or []: + for block in hunk[1]: + o = [r[1] for r in block.get("orig", [])] + r_ = [r[1] for r in block.get("recomp", [])] + for i, ol in enumerate(o): + oo = operands(ol) + if not oo: + continue + for j, rl in enumerate(r_): + ro = operands(rl) + if not ro or ro != (oo[1], oo[0]): + continue + of, rf = follower(o, i), follower(r_, j) + if of and rf and MIRROR.get(of) == rf: + found.append((ol.strip(), of, rl.strip(), rf)) + break + if found: + hits += 1 + print("### %s %.1f%%" % (e["name"].split("::")[-1], + float(e["matching"]) * 100)) + for ol, of, rl, rf in found[:4]: + print(" orig %-46s %s" % (ol[:46], of)) + print(" ours %-46s %s" % (rl[:46], rf)) + print("\n%d function(s) with a swapped comparison" % hits) + + +main() diff --git a/tools/reimplementation-helper/batch/diff_inv_jcc.py b/tools/reimplementation-helper/batch/diff_inv_jcc.py new file mode 100644 index 0000000000..be11cddab4 --- /dev/null +++ b/tools/reimplementation-helper/batch/diff_inv_jcc.py @@ -0,0 +1,60 @@ +"""Inverted conditional jumps, including where the diff has slipped out of alignment. + +An `if`/`else` whose arms are the wrong way round costs far more than the one branch +it flips: the arm the original falls through into gets emitted in the far block +instead, and every branch past it shifts. Two of these were worth +7.7 +(updateTribeCombatStanceBehavior) and +0.7 (sortTribePathDestinationsByCost, which +had two in its first ten lines). + +diff_jcc.py only compares jcc pairs the differ managed to line up, and an inversion +tends to misalign the very block it sits in - so neither of those showed up there. +This walks each diff block and reports an orig-only jcc facing a recomp-only jcc of +the opposite sense. + +Not every hit is real: any orig jcc in a block is paired against any opposite recomp +jcc in the same block, so expect false positives in blocks holding several branches. +Read the diff around each hit before changing anything. A good sign is the original +jumping a short distance where ours jumps a long one, or vice versa. + +usage: diff_inv_jcc.py (reads the last reccmp run; re-run reccmp first) +""" +import sys, os, re +sys.path.insert(0, os.path.join("tools", "reimplementation-helper", "batch")) +import common + +INV = {} +for a, b in [("je","jne"),("jz","jnz"),("jl","jge"),("jle","jg"),("jb","jae"), + ("jbe","ja"),("js","jns"),("jo","jno"),("jp","jnp")]: + INV[a] = b; INV[b] = a + +def mnem(row): + return row.split()[0].lower() if row.strip() else "" + +hits = 0 +for f, e, addr in common.entries(common.load_diff()): + if not e or float(e["matching"]) >= 1.0: + continue + found = [] + for hunk in e.get("diff") or []: + for block in hunk[1]: + o = [r[1] for r in block.get("orig", [])] + r_ = [r[1] for r in block.get("recomp", [])] + if not o or not r_: + continue + oj = [x for x in o if mnem(x) in INV] + rj = [x for x in r_ if mnem(x) in INV] + for x in oj: + for y in rj: + if INV[mnem(x)] == mnem(y): + found.append((mnem(x), mnem(y), o[0][:58], r_[0][:58])) + break + else: + continue + break + if found: + hits += 1 + print("### %s %.1f%% (%d)" % (e["name"].split("::")[-1], float(e["matching"])*100, len(found))) + for om, rm, oc, rc in found[:3]: + print(" orig %-4s / ours %-4s orig-block: %s" % (om, rm, oc)) + print(" %34s ours-block: %s" % ("", rc)) +print("\n%d function(s) with an inverted branch" % hits) diff --git a/tools/reimplementation-helper/batch/diff_regalloc.py b/tools/reimplementation-helper/batch/diff_regalloc.py new file mode 100644 index 0000000000..35afedd663 --- /dev/null +++ b/tools/reimplementation-helper/batch/diff_regalloc.py @@ -0,0 +1,61 @@ +"""Split each function's remaining gap into register naming and real structure. + +reccmp compares instruction text, so which register MSVC picked for `this` cascades +into every instruction that touches it. playUnitCombatSpeechForTarget is the clear +case: its prologue differs only in `mov ebx, ecx` against our `mov edi, ecx`, and +from there almost nothing lines up - 31.0% raw against 65.5% once the register names +are taken out. + +This re-scores every function with the general-purpose register names replaced by one +token, leaving esp alone because stack references are meaningful. + + blind >> raw the mismatch is mostly which register holds what. Not reachable from + the source; isTribePathToDestinationClear (18.8 -> 68.5) and + createAnimal (46.8 -> 82.0) are both in this group, which is why + every structural change tried on them measured flat or worse. + blind ~= raw the instructions really differ. Worth reading the diff. + +"reach" is the instruction count that differs even register-blind, so it ranks what +is actually worth attacking - unlike rank_functions.py, which ranks by total loss and +sends you at the register-bound ones first. + +usage: diff_regalloc.py [--by-name] +""" + +import difflib +import re +import sys + +import common + +REG = re.compile(r"\b(?:e?(?:ax|bx|cx|dx|si|di|bp)|[abcd][lh]|sil|dil|bpl)\b") + + +def blind(line): + return REG.sub("R", common._normalize(line)) + + +def main(): + by_name = "--by-name" in sys.argv[1:] + rows = [] + for f, e, a in common.entries(common.load_diff()): + if not e or float(e["matching"]) >= 1.0: + continue + orig, recomp = common._asm_lines(e) + if not orig: + continue + b = difflib.SequenceMatcher( + None, [blind(x) for x in orig], [blind(x) for x in recomp], + autojunk=False).ratio() + raw = float(e["matching"]) + rows.append((len(orig) * (1 - b), len(orig) * (1 - raw), raw * 100, + b * 100, e["name"].split("::")[-1])) + rows.sort(key=(lambda r: r[4]) if by_name else (lambda r: -r[0])) + print("%7s %7s %6s %6s %s" % ("reach", "lost", "raw", "blind", "function")) + for reach, lost, raw, b, name in rows: + print("%7.0f %7.0f %6.1f %6.1f %s" % (reach, lost, raw, b, name)) + print("\n%d function(s). reach = instructions that differ even register-blind." + % len(rows)) + + +main() diff --git a/tools/reimplementation-helper/batch/test_deparen.py b/tools/reimplementation-helper/batch/test_deparen.py index 9a62a38451..54def94862 100644 --- a/tools/reimplementation-helper/batch/test_deparen.py +++ b/tools/reimplementation-helper/batch/test_deparen.py @@ -29,6 +29,10 @@ ("(a == 1)", "a == 1"), # nested || of the same operator flattens ("((a == 1 || (b == 2)) || c == 3)", "a == 1 || b == 2 || c == 3"), + # a shift is not a comparison: an earlier version split `1 << n` at the first `<` + # and rejoined it as `1 < < n`, which does not compile + ("((int)*p & 1 << ((byte)i & 0x1f))", "(int)*p & 1 << ((byte)i & 0x1f)"), + ("(x >> 2 == 0)", "x >> 2 == 0"), ] if __name__ == "__main__":