From 909a69a07dc19bec30bbe5729f566aee2a34fe3f Mon Sep 17 00:00:00 2001 From: Karrz1 <127596890+Karrz1@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:48:24 +0000 Subject: [PATCH] 0.1.40: bots since 0.1.39.1 (Kel'Thuzad fight work, dungeon routes for the Shaper's Terrace, Blackmaw Hold, Alcaz Prison and Wailing Caverns, bots open keyed doors, gather tools, bot names, bug fixes) --- .../0060_companion_owner_orders.sql | 16 + .../0061_drowned_city_marrow_crumb.sql | 13 + .../0062_blackmaw_hold_route_varrox_room.sql | 39 + ...ailing_caverns_route_to_the_cliff_link.sql | 23 + ...066_alcaz_prison_route_west_wing_first.sql | 50 + sql/playerbot_v2/0067_bot_text_pools.sql | 315 +++ ...rs_terrace_route_from_the_live_landing.sql | 62 + ...ckmaw_hold_route_from_the_live_landing.sql | 63 + ...ace_route_not_through_the_titanic_door.sql | 52 + ...1_alcaz_prison_route_as_live_clears_it.sql | 64 + sql/playerbot_v2/README.md | 1 + .../Addon/ForeverBots/Bindings.xml | 2 + .../Addon/ForeverBots/ForeverBots.lua | 49 +- .../Addon/ForeverBots/ForeverBots_Spec.lua | 36 +- .../Addon/ForeverBots/Locale_ruRU.lua | 7 +- .../PlayerbotV2/Addon/ForeverBots/README.md | 2 + src/modules/PlayerbotV2/Api/BotSwim.h | 45 + src/modules/PlayerbotV2/Api/PlayerbotAPI.cpp | 220 +- src/modules/PlayerbotV2/Api/PlayerbotAPI.h | 16 +- .../PlayerbotV2/Api/PlayerbotMovement.cpp | 244 +- .../PlayerbotV2/Api/PlayerbotMovement.h | 10 + src/modules/PlayerbotV2/BOT_COMMANDS.md | 7 + src/modules/PlayerbotV2/Bot/BotAI.h | 105 +- src/modules/PlayerbotV2/Bot/BotBridge.cpp | 15 +- .../PlayerbotV2/Bot/BotBridgeFormat.cpp | 60 + src/modules/PlayerbotV2/Bot/BotBridgeFormat.h | 9 + src/modules/PlayerbotV2/Bot/BotChatModel.cpp | 8 +- .../PlayerbotV2/Bot/BotChatModelClient.cpp | 17 +- .../PlayerbotV2/Bot/BotChatModelClient.h | 4 +- .../PlayerbotV2/Bot/BotChatReactor.cpp | 25 +- .../PlayerbotV2/Bot/BotCommandParser.cpp | 25 +- src/modules/PlayerbotV2/Bot/BotIntent.h | 16 +- .../PlayerbotV2/Bot/BotIntentEmitter.cpp | 18 + .../PlayerbotV2/Bot/BotIntentEmitter.h | 5 + .../PlayerbotV2/Bot/BotIntentExecutor.cpp | 4 + src/modules/PlayerbotV2/Bot/BotSnapshot.h | 58 + .../PlayerbotV2/Bot/BotSnapshotBuilder.cpp | 2092 ++++++++++------- .../PlayerbotV2/Bot/BotSnapshotView.cpp | 6 + src/modules/PlayerbotV2/Bot/BotSnapshotView.h | 4 + src/modules/PlayerbotV2/Bot/BotTextMgr.cpp | 92 +- src/modules/PlayerbotV2/Bot/BotTextMgr.h | 9 + src/modules/PlayerbotV2/Bot/CcPick.h | 7 +- .../PlayerbotV2/Bot/ClassicHealCover.h | 4 + .../PlayerbotV2/Bot/Dungeon/DungeonScript.cpp | 4 + .../PlayerbotV2/Bot/Dungeon/DungeonScript.h | 15 + .../PlayerbotV2/Bot/Dungeon/PrePullCc.h | 10 +- .../Bot/Dungeon/PveGroupCoordinator.cpp | 85 +- .../Bot/Dungeon/PveGroupCoordinator.h | 7 + .../Bot/Dungeon/Scripts/AlcazPrisonScript.cpp | 35 +- .../Dungeon/Scripts/BlackmawHoldScript.cpp | 28 +- .../Dungeon/Scripts/BlackwingLairScript.cpp | 7 + .../Bot/Dungeon/Scripts/DeadminesScript.cpp | 2 +- .../Bot/Dungeon/Scripts/DireMaulScript.cpp | 2 +- .../Dungeon/Scripts/ExcavationSiteScript.cpp | 9 +- .../Scripts/LowerBlackrockSpireScript.cpp | 7 + .../Bot/Dungeon/Scripts/MoltenCoreScript.cpp | 8 + .../Bot/Dungeon/Scripts/NaxxramasScript.cpp | 13 +- .../Dungeon/Scripts/RazorfenDownsScript.cpp | 2 +- .../Scripts/RuinsOfLordaeronScript.cpp | 7 + .../Dungeon/Scripts/ShadowfangKeepScript.cpp | 9 + .../Dungeon/Scripts/ShapersTerraceScript.cpp | 54 +- .../Bot/Dungeon/Scripts/StratholmeScript.cpp | 7 + .../Scripts/TempleOfAhnQirajScript.cpp | 2 +- src/modules/PlayerbotV2/Bot/Formation.cpp | 9 +- src/modules/PlayerbotV2/Bot/PackPullGate.h | 6 +- src/modules/PlayerbotV2/Bot/PullDelay.h | 83 + .../PlayerbotV2/Bot/Quest/CompanionQuest.cpp | 129 +- .../PlayerbotV2/Bot/Quest/CompanionQuest.h | 5 + .../PlayerbotV2/Bot/Quest/QuestOrders.cpp | 10 +- src/modules/PlayerbotV2/Bot/QuestLoot.h | 41 +- .../PlayerbotV2/Bot/Raid/RaidAdvice.cpp | 2 + .../PlayerbotV2/Bot/Raid/RaidBrain.cpp | 534 ++++- .../Bot/Raid/RaidEncounterData_NAXX.cpp | 103 +- .../PlayerbotV2/Bot/Raid/RaidEncounters.cpp | 6 + .../PlayerbotV2/Bot/Raid/RaidEncounters.h | 48 +- .../PlayerbotV2/Bot/Raid/RaidFightScript.cpp | 111 +- .../PlayerbotV2/Bot/Raid/RaidFightScript.h | 50 + .../Bot/Raid/RaidMechanics_Naxx.cpp | 53 +- src/modules/PlayerbotV2/Bot/Raid/RaidOrder.h | 3 + src/modules/PlayerbotV2/Bot/SpellFamily.h | 30 + .../PlayerbotV2/Bot/States/MaintainHelpers.h | 6 + .../Bot/States/Rules/AmbientRules.cpp | 510 +++- .../Bot/States/Rules/CompanionQuestRules.cpp | 8 + .../Bot/States/Rules/CoreFlowRules.cpp | 9 +- .../Bot/States/Rules/GuildRules.cpp | 159 +- .../Bot/States/Rules/LootDrainRules.cpp | 11 +- .../Bot/States/Rules/OocConsumableRules.cpp | 10 +- .../Bot/States/Rules/PrologueRules.cpp | 40 +- .../Bot/States/Rules/SurvivalRules.cpp | 67 +- .../PlayerbotV2/Bot/States/State_Dead.cpp | 14 +- .../PlayerbotV2/Bot/States/State_Idle.cpp | 1232 +++++++--- .../PlayerbotV2/Bot/States/State_InCombat.cpp | 147 +- .../PlayerbotV2/Bot/States/State_InGroup.cpp | 4 +- src/modules/PlayerbotV2/Bot/TownErrand.h | 86 +- .../PlayerbotV2/Bot/TownErrandConfig.h | 79 + .../PlayerbotV2/Bot/World/HunterPetsByRace.h | 4 +- .../PlayerbotV2/Bot/World/ZonePicker.cpp | 25 +- .../PlayerbotV2/Combat/Apl/ApClassicHeal.h | 15 +- .../Combat/Apl/Apl_Classic_Paladin.cpp | 19 + .../Combat/Apl/Apl_Classic_Warrior.cpp | 42 + src/modules/PlayerbotV2/Combat/LazyKey.h | 635 +++++ .../PlayerbotV2/Commands/cs_playerbot_v2.cpp | 95 +- .../PlayerbotV2/Diagnostics/ScenarioDefs.h | 136 +- .../PlayerbotV2/Diagnostics/ScenarioMonitor.h | 20 +- .../Diagnostics/ScenarioRunner.cpp | 167 +- .../PlayerbotV2/Fleet/BotComposition.cpp | 16 +- .../PlayerbotV2/Fleet/BotGuildNamePool.cpp | 21 +- .../Fleet/BotPopulationManager.cpp | 84 +- .../PlayerbotV2/Fleet/BotPopulationManager.h | 11 +- .../PlayerbotV2/Fleet/BotSetupPipeline.cpp | 64 +- .../PlayerbotV2/Fleet/OwnerRegistry.cpp | 23 +- src/modules/PlayerbotV2/Fleet/OwnerRegistry.h | 14 +- src/modules/PlayerbotV2/Group/GroupSnapshot.h | 5 + .../Group/GroupSnapshotBuilder.cpp | 67 + src/modules/PlayerbotV2/PlayerbotV2.cpp | 53 +- src/modules/PlayerbotV2/PlayerbotV2.h | 5 +- .../PlayerbotV2/Session/BotSession.cpp | 50 + src/modules/PlayerbotV2/Session/LazyKey.cpp | 304 +++ src/modules/PlayerbotV2/Session/LazyKey.h | 16 + .../PlayerbotV2/Travel/TownNpcIndex.cpp | 70 +- src/modules/PlayerbotV2/Travel/TownNpcIndex.h | 17 + src/modules/PlayerbotV2/Util/BotLocaleRu.cpp | 9 +- src/modules/PlayerbotV2/Util/ConfigReader.cpp | 2 + src/modules/PlayerbotV2/Util/ConfigReader.h | 3 + .../PlayerbotV2/conf/playerbot.conf.dist | 41 +- tests/game/ClassicBotBridge.cpp | 15 + tests/game/ClassicBotLocale.cpp | 16 +- tests/game/ClassicBotSwim.cpp | 59 + tests/game/ClassicCcPick.cpp | 8 + tests/game/ClassicFormation.cpp | 75 + tests/game/ClassicLazyKey.cpp | 246 ++ tests/game/ClassicScenarioMonitor.cpp | 76 + tests/game/ClassicTownErrand.cpp | 106 + 133 files changed, 8672 insertions(+), 1799 deletions(-) create mode 100644 sql/playerbot_v2/0060_companion_owner_orders.sql create mode 100644 sql/playerbot_v2/0061_drowned_city_marrow_crumb.sql create mode 100644 sql/playerbot_v2/0062_blackmaw_hold_route_varrox_room.sql create mode 100644 sql/playerbot_v2/0065_wailing_caverns_route_to_the_cliff_link.sql create mode 100644 sql/playerbot_v2/0066_alcaz_prison_route_west_wing_first.sql create mode 100644 sql/playerbot_v2/0067_bot_text_pools.sql create mode 100644 sql/playerbot_v2/0068_shapers_terrace_route_from_the_live_landing.sql create mode 100644 sql/playerbot_v2/0069_blackmaw_hold_route_from_the_live_landing.sql create mode 100644 sql/playerbot_v2/0070_shapers_terrace_route_not_through_the_titanic_door.sql create mode 100644 sql/playerbot_v2/0071_alcaz_prison_route_as_live_clears_it.sql create mode 100644 src/modules/PlayerbotV2/Bot/PullDelay.h create mode 100644 src/modules/PlayerbotV2/Combat/LazyKey.h create mode 100644 src/modules/PlayerbotV2/Session/LazyKey.cpp create mode 100644 src/modules/PlayerbotV2/Session/LazyKey.h create mode 100644 tests/game/ClassicFormation.cpp create mode 100644 tests/game/ClassicLazyKey.cpp diff --git a/sql/playerbot_v2/0060_companion_owner_orders.sql b/sql/playerbot_v2/0060_companion_owner_orders.sql new file mode 100644 index 0000000000..606e7f06d5 --- /dev/null +++ b/sql/playerbot_v2/0060_companion_owner_orders.sql @@ -0,0 +1,16 @@ +-- Migration: 0060_companion_owner_orders +-- Date: 2026-11-21 +-- Purpose: The owner's standing orders on a companion, "loot all" and "gather on", were kept in the bot logic only and were gone after +-- every relog, `.bot call` and restart (Alex Black Cat, RU general 11-21: an alt's gather and loot all reset on each relog). +-- They are stored with the companion and given back at its login. +-- +-- Columns: +-- owner_orders bits: 0x01 loot all (rolls on everything, greys included), 0x02 gather on (herbs, ore, skins). 0 = neither. +-- Reverts: yes (DROP COLUMN owner_orders). + +ALTER TABLE playerbot_v2_character + ADD COLUMN owner_orders TINYINT UNSIGNED NOT NULL DEFAULT 0; + +INSERT INTO playerbot_v2_schema_version (version, sha256) VALUES + (60, REPEAT('0', 64)) +ON DUPLICATE KEY UPDATE applied_at = CURRENT_TIMESTAMP; diff --git a/sql/playerbot_v2/0061_drowned_city_marrow_crumb.sql b/sql/playerbot_v2/0061_drowned_city_marrow_crumb.sql new file mode 100644 index 0000000000..35eccc48b3 --- /dev/null +++ b/sql/playerbot_v2/0061_drowned_city_marrow_crumb.sql @@ -0,0 +1,13 @@ +-- Migration: 0061_drowned_city_marrow_crumb +-- Date: 2026-11-23 +-- Purpose: The Drowned City (map 2970) route crumb 107 stood on Deathless Marrow's dais (-13322.97,3073.15,-6.07), a bump of +-- navmesh 3 y high and 3 y wide. drowned_full af63: after Marrow every route step that landed on the dais sent the tank +-- back south; it paced y 3040-3060 for 2100 s and never came nearer the crumb than 13 y. The crumb moves to the floor +-- east of the dais, 8.8 y from Marrow's spot (still the crumb nearest her, where the walk to the next boss starts); +-- the walks 106 -> 107 -> 108 stay on the flat floor (navmesh polygons 5973, 5978, 5980, 5979, z -7.8 to -7.2). +-- Reverts: UPDATE ... SET position_x = -13322.97, position_y = 3073.15, position_z = -6.07 for the same row. + +-- @target: shared + +UPDATE {SHARED}.playerbot_dungeon_routes SET position_x = -13316.50, position_y = 3079.00, position_z = -7.80 + WHERE map_id = 2970 AND difficulty = 0 AND seq = 107; diff --git a/sql/playerbot_v2/0062_blackmaw_hold_route_varrox_room.sql b/sql/playerbot_v2/0062_blackmaw_hold_route_varrox_room.sql new file mode 100644 index 0000000000..4967a30544 --- /dev/null +++ b/sql/playerbot_v2/0062_blackmaw_hold_route_varrox_room.sql @@ -0,0 +1,39 @@ +-- Migration: 0062_blackmaw_hold_route_varrox_room +-- Date: 2026-11-23 +-- Purpose: Blackmaw Hold (map 2974): the route's last leg, from Elder Shaman Bloodmane to Varrox Bleakhoof's new spot in the high north +-- room of the east cave (world SQL 2026_11_23_24_world_forever_blackmaw_varrox_room). Varrox stood on the only short way from +-- the Unbound Spirit to the Behemoth: the old crumbs 131-132 passed 10 y from him, and the tank pulled him fifth, before the +-- Behemoth and Bloodmane (blackmaw_full chain69b, 23 Nov: both left standing when the goal fell). Crumbs 0-155 stay; 156-178 +-- replace the old 156-167. Built on the 2974 navmesh: the shortest path from crumb 155 (by Bloodmane) to the new spot, a crumb +-- about every 15-30 y, each leg a straight line on the walkable mesh (checked every yard), each crumb at least 4.8 y from a +-- wall. The way passes route pack 44 and two Blackmaw Shaman / Grizzly packs north of the shrine. +-- Reverts: no (0044 has the old tail). + +-- @target: shared + +DELETE FROM {SHARED}.playerbot_dungeon_routes WHERE map_id = 2974 AND difficulty = 0 AND seq >= 156; + +INSERT INTO {SHARED}.playerbot_dungeon_routes (map_id, difficulty, seq, position_x, position_y, position_z) VALUES + (2974,0,156,3506.58,2995.78,145.90), + (2974,0,157,3501.31,3010.93,145.41), + (2974,0,158,3482.27,3031.40,149.97), + (2974,0,159,3471.87,3037.51,156.28), + (2974,0,160,3467.73,3051.82,162.82), + (2974,0,161,3472.87,3064.80,165.70), + (2974,0,162,3498.04,3076.02,166.11), + (2974,0,163,3506.67,3081.33,167.07), + (2974,0,164,3507.80,3090.80,166.41), + (2974,0,165,3518.87,3093.80,166.00), + (2974,0,166,3536.93,3099.67,167.68), + (2974,0,167,3544.48,3102.24,169.02), + (2974,0,168,3559.13,3113.60,171.36), + (2974,0,169,3568.71,3125.91,172.30), + (2974,0,170,3582.62,3131.09,174.86), + (2974,0,171,3599.78,3126.31,176.19), + (2974,0,172,3629.80,3120.53,178.47), + (2974,0,173,3643.11,3124.53,179.49), + (2974,0,174,3660.91,3122.35,180.66), + (2974,0,175,3671.80,3115.87,182.09), + (2974,0,176,3673.33,3088.67,189.49), + (2974,0,177,3668.78,3074.49,189.22), + (2974,0,178,3660.47,3060.67,189.15); diff --git a/sql/playerbot_v2/0065_wailing_caverns_route_to_the_cliff_link.sql b/sql/playerbot_v2/0065_wailing_caverns_route_to_the_cliff_link.sql new file mode 100644 index 0000000000..1046344381 --- /dev/null +++ b/sql/playerbot_v2/0065_wailing_caverns_route_to_the_cliff_link.sql @@ -0,0 +1,23 @@ +-- Migration: 0065_wailing_caverns_route_to_the_cliff_link +-- Date: 2026-11-24 +-- Purpose: Wailing Caverns (map 43): the route from Lord Serpentis' cliff link no longer goes into the pocket under his ledge. +-- 0036 ran Skum (crumb 167), then crumbs 168-191 back north-east to the floor under the ledge (-61.6,-15.5), a dead end, +-- and only then the link's lower end (crumb 192). wc_full af69i: the squad walked that pocket in and out, about 540 y in +-- and 800 y back round by the south to the link, and crossed at 3317 s of a 3600 s run. The new crumbs 168-183 go straight +-- from Skum up the west passage to the link's upper end B (-288.23,-6.15,-58.98), about 350 y, the way the tank walked +-- to it in that run. 184 on is 0036's 192-208 (link end A, then the ledge to Serpentis and Verdan) renumbered. +-- Built from the map 43 navmesh: a crumb every 18-32 y, every crumb-to-crumb leg a clean path of at most 7 polygons +-- and at most 1.45x its straight line. +-- Reverts: yes (crumbs 168-208 of map 43 as 0036 has them). + +-- @target: shared + +DELETE FROM {SHARED}.playerbot_dungeon_routes WHERE map_id = 43 AND difficulty = 0 AND seq >= 168; + +INSERT INTO {SHARED}.playerbot_dungeon_routes (map_id, difficulty, seq, position_x, position_y, position_z) VALUES + (43,0,168,-270.76,-302.58,-68.23),(43,0,169,-263.13,-290.53,-66.93),(43,0,170,-263.73,-269.38,-64.94),(43,0,171,-272.16,-252.00,-62.35),(43,0,172,-274.49,-232.18,-62.23),(43,0,173,-267.57,-204.43,-62.79), + (43,0,174,-283.13,-193.87,-60.90),(43,0,175,-298.13,-179.91,-61.98),(43,0,176,-306.73,-158.60,-59.46),(43,0,177,-313.01,-136.37,-61.64),(43,0,178,-308.80,-119.91,-61.92),(43,0,179,-307.73,-94.51,-64.11), + (43,0,180,-315.04,-73.07,-64.08),(43,0,181,-313.67,-51.73,-63.05),(43,0,182,-307.20,-31.69,-61.15),(43,0,183,-288.23,-6.15,-58.98),(43,0,184,-289.07,3.2,-63.96),(43,0,185,-277.57,19.56,-60.51), + (43,0,186,-266.07,35.93,-55.63),(43,0,187,-253.17,51.14,-52.57),(43,0,188,-233.62,55.38,-48.85),(43,0,189,-213.74,57.04,-49.05),(43,0,190,-193.9,55.52,-47.16),(43,0,191,-174.16,52.3,-41.38), + (43,0,192,-159.28,40.37,-34.94),(43,0,193,-149.28,23.05,-28.41),(43,0,194,-139.28,5.73,-27.52),(43,0,195,-129.28,-11.59,-27.49),(43,0,196,-120.16,-24.62,-28.58),(43,0,197,-108.08,-8.68,-27.89), + (43,0,198,-96,7.26,-29.89),(43,0,199,-83.92,23.2,-30.37),(43,0,200,-81.86,32.26,-30.99); diff --git a/sql/playerbot_v2/0066_alcaz_prison_route_west_wing_first.sql b/sql/playerbot_v2/0066_alcaz_prison_route_west_wing_first.sql new file mode 100644 index 0000000000..758bbf711d --- /dev/null +++ b/sql/playerbot_v2/0066_alcaz_prison_route_west_wing_first.sql @@ -0,0 +1,50 @@ +-- Migration: 0066_alcaz_prison_route_west_wing_first +-- Date: 2026-11-24 +-- Purpose: Alcaz Prison (map 2994): the route takes the west wing first. The old order (Overseer Wrex, Katerina the Cleaner, The +-- Questioner, Tidemistress Ca'zass, Blazeroar) walked from the entrance into Wrex's east cell block, back across the hall +-- into the west wing, and back across the hall again from The Questioner to the stair down to Ca'zass. The new order is +-- Katerina the Cleaner, The Questioner, Overseer Wrex, Tidemistress Ca'zass, Blazeroar: west wing, back through the hall +-- once to Wrex beside the stair, then down. 720 y of walk on the 2994 navmesh instead of 789, and the hall is crossed +-- once instead of twice. The crumbs are the 0043 crumbs in the new order (3 and 9, the hall crumbs of the old double +-- crossing, are left out). Every leg is a clean navmesh path of at most 30 y. AlcazPrisonScript.cpp has the same order. +-- Reverts: run 0043 again. + +-- @target: shared + +DELETE FROM {SHARED}.playerbot_dungeon_routes WHERE map_id = 2994; + +INSERT INTO {SHARED}.playerbot_dungeon_routes (map_id, difficulty, seq, position_x, position_y, position_z) VALUES + (2994,0,0,-8796.80,2838.10,29.90), + (2994,0,1,-8796.73,2858.93,21.55), + (2994,0,2,-8796.80,2881.27,19.09), + (2994,0,3,-8802.58,2886.67,19.49), + (2994,0,4,-8823.64,2889.60,15.58), + (2994,0,5,-8845.78,2889.60,15.13), + (2994,0,6,-8852.40,2889.38,14.02), + (2994,0,7,-8871.63,2889.60,14.42), + (2994,0,8,-8886.00,2893.69,14.42), + (2994,0,9,-8867.38,2889.60,14.95), + (2994,0,10,-8849.29,2889.60,15.22), + (2994,0,11,-8830.13,2888.75,14.10), + (2994,0,12,-8812.11,2887.04,17.51), + (2994,0,13,-8792.07,2887.60,19.35), + (2994,0,14,-8769.96,2886.40,15.13), + (2994,0,15,-8762.13,2882.13,15.31), + (2994,0,16,-8758.44,2864.22,14.15), + (2994,0,17,-8758.67,2847.51,14.02), + (2994,0,18,-8763.13,2869.33,14.35), + (2994,0,19,-8764.98,2887.64,15.13), + (2994,0,20,-8764.98,2906.27,12.15), + (2994,0,21,-8763.29,2924.71,6.69), + (2994,0,22,-8745.87,2932.40,6.15), + (2994,0,23,-8727.60,2932.40,6.15), + (2994,0,24,-8745.87,2932.40,6.15), + (2994,0,25,-8764.98,2932.00,6.73), + (2994,0,26,-8783.91,2932.31,6.46), + (2994,0,27,-8802.40,2932.40,6.42), + (2994,0,28,-8806.93,2950.76,7.13), + (2994,0,29,-8818.89,2970.40,6.55), + (2994,0,30,-8837.60,2968.53,7.04), + (2994,0,31,-8858.47,2966.20,7.22), + (2994,0,32,-8875.82,2975.38,6.15), + (2994,0,33,-8886.83,2974.72,5.89); diff --git a/sql/playerbot_v2/0067_bot_text_pools.sql b/sql/playerbot_v2/0067_bot_text_pools.sql new file mode 100644 index 0000000000..37fb653a1d --- /dev/null +++ b/sql/playerbot_v2/0067_bot_text_pools.sql @@ -0,0 +1,315 @@ +-- Migration: 0067_bot_text_pools +-- Date: 2026-11-25 +-- Purpose: Move the chat lines that were hard-coded in the source into the shared text table, +-- so a realm can rewrite bot speech without rebuilding. Every line below is the text the +-- code already said, verbatim ({} fmt args became %placeholders), the code keeps its +-- builtin pool as fallback for a server whose shared table has no rows for a key. +-- +-- New keys (playerbot_v2_bot_text.name): +-- guild_ding a bot levels up, %my_level is the new level +-- guild_login_greet greet the guild at login +-- guild_smalltalk idle guild smalltalk (only with a human guildmate online) +-- guild_tavern_hangout tavern-night pitch, %venue is the faction tavern name +-- guild_rival a rival guild's members are near +-- guild_quest_brag a quest was turned in +-- guild_lfm long LFG queue pulse +-- guild_event_announce officer callout before a guild event, %event_label, %mins_until +-- guild_tavern_chat chatter during the tavern party +-- guild_staging_* chatter during a raid / dungeon / bg night staging (generic = fallback) +-- guild_babble the slow ambient babble (30 min per bot) +-- guild_join_welcome a real player joined the guild, %s is the joiner's first name +-- banter_ a companion's party-chat banter (ready / wipe / thanks / ouch / +-- bosskill), banter__ are +-- the per-role / per-personality extras, merged in with the base key +-- banter_raid_wipe one corpse in a wiped raid says so in raid chat +-- say_kindness_heal a free bot healed a passing player: the /say with it +-- say_kindness_rez a free bot resurrects a passing player: the /say with it +-- +-- INSERT IGNORE against the (name, reply_type, text(200)) unique key: re-running is a no-op. +-- No text contains a ',' (the migration runner splits statements on it). +-- Reverts: yes (DELETE the rows of the keys above). +-- +-- @target: shared + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('guild_ding', 'Ding %my_level!', 0, 0), + ('guild_ding', '%my_level achieved', 0, 0), + ('guild_ding', 'hit %my_level :)', 0, 0), + ('guild_ding', 'Level %my_level!', 0, 0), + ('guild_ding', 'ding %my_level', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('guild_login_greet', 'hi all', 0, 0), + ('guild_login_greet', 'hey :)', 0, 0), + ('guild_login_greet', 'o/', 0, 0), + ('guild_login_greet', 'hello!', 0, 0), + ('guild_login_greet', 'evening', 0, 0), + ('guild_login_greet', 'yo', 0, 0), + ('guild_login_greet', 'hi guild', 0, 0), + ('guild_login_greet', 'hey hey', 0, 0), + ('guild_login_greet', 'o/ everyone', 0, 0), + ('guild_login_greet', 'back online', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('guild_smalltalk', 'anyone need help with anything?', 0, 0), + ('guild_smalltalk', 'what''s good tonight folks', 0, 0), + ('guild_smalltalk', 'soloing this is rough', 0, 0), + ('guild_smalltalk', 'anyone running dungeons?', 0, 0), + ('guild_smalltalk', 'pulled too much again, classic', 0, 0), + ('guild_smalltalk', 'where is everyone leveling?', 0, 0), + ('guild_smalltalk', 'the new patch feels good', 0, 0), + ('guild_smalltalk', 'anyone got mats to spare?', 0, 0), + ('guild_smalltalk', 'drinking tea, brb', 0, 0), + ('guild_smalltalk', 'good run earlier, ty', 0, 0), + ('guild_smalltalk', 'checking AH brb', 0, 0), + ('guild_smalltalk', 'this zone is gorgeous', 0, 0), + ('guild_smalltalk', 'lf groupmates for tonight', 0, 0), + ('guild_smalltalk', 'back from a break, hi all', 0, 0), + ('guild_smalltalk', 'rolling around questing', 0, 0), + ('guild_smalltalk', 'anyone seen [redacted-name] online?', 0, 0), + ('guild_smalltalk', 'love this server', 0, 0), + ('guild_smalltalk', 'phase is acting weird, anyone else?', 0, 0), + ('guild_smalltalk', 'great patch notes today', 0, 0), + ('guild_smalltalk', 'stretch break', 0, 0), + ('guild_smalltalk', 'tea then back to grinding', 0, 0), + ('guild_smalltalk', 'anyone need a port?', 0, 0), + ('guild_smalltalk', 'this mount drop is brutal', 0, 0), + ('guild_smalltalk', 'looking for a leveling buddy', 0, 0), + ('guild_smalltalk', 'kicking back, easy night', 0, 0), + ('guild_smalltalk', 'anyone want to chain quests?', 0, 0), + ('guild_smalltalk', 'this rep grind...', 0, 0), + ('guild_smalltalk', 'soloing dungeons for chests', 0, 0), + ('guild_smalltalk', 'wow my repair bill', 0, 0), + ('guild_smalltalk', 'good music tonight, share recs', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('guild_tavern_hangout', 'anyone want to hit the tavern? %venue', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('guild_rival', 'rival guild spotted', 0, 0), + ('guild_rival', 'show them how it''s done', 0, 0), + ('guild_rival', 'they think they''re tough', 0, 0), + ('guild_rival', 'second place again', 0, 0), + ('guild_rival', 'watch the rivals here', 0, 0), + ('guild_rival', 'let''s outperform them', 0, 0), + ('guild_rival', 'rival in sight, on guard', 0, 0), + ('guild_rival', 'amateurs', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('guild_quest_brag', 'another one down', 0, 0), + ('guild_quest_brag', 'just finished a quest', 0, 0), + ('guild_quest_brag', 'feeling productive tonight', 0, 0), + ('guild_quest_brag', 'quest log getting lighter', 0, 0), + ('guild_quest_brag', 'another tick on the list', 0, 0), + ('guild_quest_brag', 'ding XP', 0, 0), + ('guild_quest_brag', 'easy gold', 0, 0), + ('guild_quest_brag', 'quest hub clear', 0, 0), + ('guild_quest_brag', 'love a good quest chain', 0, 0), + ('guild_quest_brag', 'rolling through quests', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('guild_lfm', 'LFM for a dungeon, anyone?', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('guild_event_announce', '%event_label starts in %mins_until min!', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('guild_tavern_chat', 'this is fun', 0, 0), + ('guild_tavern_chat', 'cheers everyone', 0, 0), + ('guild_tavern_chat', '/dance', 0, 0), + ('guild_tavern_chat', 'best night of the week', 0, 0), + ('guild_tavern_chat', 'love these party nights', 0, 0), + ('guild_tavern_chat', 'more people should hit the tavern', 0, 0), + ('guild_tavern_chat', 'great turnout', 0, 0), + ('guild_tavern_chat', 'tavern night incoming', 0, 0), + ('guild_tavern_chat', 'rolling tipsy', 0, 0), + ('guild_tavern_chat', '/toast', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('guild_staging_generic', 'anyone joining?', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('guild_staging_raid', 'raid night, who''s in?', 0, 0), + ('guild_staging_raid', 'rolling for raid spots', 0, 0), + ('guild_staging_raid', '/g raid in 10', 0, 0), + ('guild_staging_raid', 'looking for one more dps', 0, 0), + ('guild_staging_raid', 'loot reservations open', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('guild_staging_dungeon', 'dungeon night, who''s down?', 0, 0), + ('guild_staging_dungeon', 'lf2m for keys', 0, 0), + ('guild_staging_dungeon', 'let''s chain some 5-mans', 0, 0), + ('guild_staging_dungeon', 'got a healer?', 0, 0), + ('guild_staging_dungeon', 'rolling tank dual spec', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('guild_staging_bg', 'BG night! /join wsg', 0, 0), + ('guild_staging_bg', 'premade rolling', 0, 0), + ('guild_staging_bg', 'honor cap incoming', 0, 0), + ('guild_staging_bg', 'anyone seen the queue times?', 0, 0), + ('guild_staging_bg', 'rated arena later maybe', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('guild_babble', 'Hey everyone!', 0, 0), + ('guild_babble', 'anyone need a hand with anything?', 0, 0), + ('guild_babble', 'Got some good loot today.', 0, 0), + ('guild_babble', 'Anyone running dungeons later?', 0, 0), + ('guild_babble', 'Crafting reagents up in the bank if anyone needs them.', 0, 0), + ('guild_babble', 'Who''s online tonight?', 0, 0), + ('guild_babble', 'lfg if anyone wants to group', 0, 0), + ('guild_babble', 'How''s everyone doing?', 0, 0), + ('guild_babble', 'Just dinged again — slow grind.', 0, 0), + ('guild_babble', 'Hope to see folks at the next raid night.', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('guild_join_welcome', 'welcome %s!', 0, 0), + ('guild_join_welcome', 'welcome to the guild %s :)', 0, 0), + ('guild_join_welcome', 'hey %s, welcome!', 0, 0), + ('guild_join_welcome', 'welcome aboard %s!', 0, 0), + ('guild_join_welcome', '%s welcome! :)', 0, 0), + ('guild_join_welcome', 'glad to have you %s!', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('say_kindness_heal', 'there you go', 0, 0), + ('say_kindness_heal', 'patched you up', 0, 0), + ('say_kindness_heal', 'heal inc', 0, 0), + ('say_kindness_heal', 'careful out there', 0, 0), + ('say_kindness_heal', 'you looked like you needed that', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('say_kindness_rez', 'rez inc', 0, 0), + ('say_kindness_rez', 'hold on, rezzing you', 0, 0), + ('say_kindness_rez', 'got you', 0, 0), + ('say_kindness_rez', 'rez coming', 0, 0), + ('say_kindness_rez', 'don''t release, rezzing', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_raid_wipe', 'well, that went badly', 0, 0), + ('banter_raid_wipe', 'wipe :(', 0, 0), + ('banter_raid_wipe', 'ouch', 0, 0), + ('banter_raid_wipe', 'ok that one is on me', 0, 0), + ('banter_raid_wipe', 'and we''re all dead', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_ready', 'ready', 0, 0), + ('banter_ready', 'rdy', 0, 0), + ('banter_ready', 'yep ready', 0, 0), + ('banter_ready', 'good to go', 0, 0), + ('banter_ready', 'all set', 0, 0), + ('banter_ready', 'ready :)', 0, 0), + ('banter_ready', 'yup', 0, 0), + ('banter_ready', 'ready when you are', 0, 0); + +-- 'ready' was listed twice in the builtin pool (twice as likely), the unique key keeps one row, +-- so the repeat becomes weight 2 (the same trick migration 0022 used for the ike3 repeats). +UPDATE {SHARED}.playerbot_v2_bot_text SET weight = 2 + WHERE name = 'banter_ready' AND reply_type = 0 AND text = 'ready'; + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_ready_tank', 'ready to tank', 0, 0), + ('banter_ready_tank', 'tank ready', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_ready_healer', 'healer ready', 0, 0), + ('banter_ready_healer', 'heals ready', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_ready_caster', 'ready, mana is good', 0, 0), + ('banter_ready_caster', 'mana is good', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_ready_rp', 'aye, ready', 0, 0), + ('banter_ready_rp', 'ready, lead on', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_wipe', 'my bad', 0, 0), + ('banter_wipe', 'wp', 0, 0), + ('banter_wipe', 'wp wp', 0, 0), + ('banter_wipe', 'ouch', 0, 0), + ('banter_wipe', 'rip', 0, 0), + ('banter_wipe', 'well that went well', 0, 0), + ('banter_wipe', 'oof', 0, 0), + ('banter_wipe', 'that was rough', 0, 0), + ('banter_wipe', 'rip us', 0, 0), + ('banter_wipe', 'wow ok', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_wipe_tank', 'my bad, bad pull', 0, 0), + ('banter_wipe_tank', 'sorry, lost them', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_wipe_healer', 'sorry, too slow with the heals', 0, 0), + ('banter_wipe_healer', 'my bad, couldn''t keep up', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_wipe_polite', 'sorry everyone', 0, 0), + ('banter_wipe_polite', 'sorry guys, my fault', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_wipe_rude', 'great job everyone', 0, 0), + ('banter_wipe_rude', 'wow', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_thanks', 'ty', 0, 0), + ('banter_thanks', 'thanks', 0, 0), + ('banter_thanks', 'thx', 0, 0), + ('banter_thanks', 'ty!', 0, 0), + ('banter_thanks', 'tyvm', 0, 0), + ('banter_thanks', 'ty rez', 0, 0), + ('banter_thanks', 'thx rez', 0, 0), + ('banter_thanks', 'ty :)', 0, 0), + ('banter_thanks', 'thanks for the rez', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_thanks_polite', 'thank you!', 0, 0), + ('banter_thanks_polite', 'much appreciated', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_thanks_rude', 'finally', 0, 0), + ('banter_thanks_rude', 'about time', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_ouch', 'ouch', 0, 0), + ('banter_ouch', 'ow', 0, 0), + ('banter_ouch', 'oof', 0, 0), + ('banter_ouch', 'that hurt', 0, 0), + ('banter_ouch', 'ugh', 0, 0), + ('banter_ouch', 'argh', 0, 0), + ('banter_ouch', 'rip', 0, 0), + ('banter_ouch', 'owie', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_ouch_tank', 'that stings', 0, 0), + ('banter_ouch_tank', 'ow, my armor', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_ouch_caster', 'squishy, i know', 0, 0), + ('banter_ouch_caster', 'paper armor strikes again', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_bosskill', 'gg', 0, 0), + ('banter_bosskill', 'gg!', 0, 0), + ('banter_bosskill', 'gg wp', 0, 0), + ('banter_bosskill', 'nice', 0, 0), + ('banter_bosskill', 'well done', 0, 0), + ('banter_bosskill', 'nice one', 0, 0), + ('banter_bosskill', 'woo', 0, 0), + ('banter_bosskill', 'finally', 0, 0), + ('banter_bosskill', 'good one', 0, 0), + ('banter_bosskill', 'that went well', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_bosskill_polite', 'gg everyone', 0, 0), + ('banter_bosskill_polite', 'well played all', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_bosskill_tank', 'easy', 0, 0), + ('banter_bosskill_tank', 'gg, nice heals', 0, 0); + +INSERT IGNORE INTO {SHARED}.playerbot_v2_bot_text (name, text, say_type, reply_type) VALUES + ('banter_bosskill_rp', 'victory!', 0, 0), + ('banter_bosskill_rp', 'for glory, gg', 0, 0); + +INSERT INTO {SHARED}.playerbot_v2_schema_version (version, sha256) VALUES + (67, REPEAT('0', 64)) +ON DUPLICATE KEY UPDATE applied_at = CURRENT_TIMESTAMP; diff --git a/sql/playerbot_v2/0068_shapers_terrace_route_from_the_live_landing.sql b/sql/playerbot_v2/0068_shapers_terrace_route_from_the_live_landing.sql new file mode 100644 index 0000000000..f7e438c0c2 --- /dev/null +++ b/sql/playerbot_v2/0068_shapers_terrace_route_from_the_live_landing.sql @@ -0,0 +1,62 @@ +-- Migration: 0068_shapers_terrace_route_from_the_live_landing +-- Date: 2026-11-25 +-- Purpose: The Shaper's Terrace (map 3001) as live has it (world 2026_11_25_80..84, from Karrz's capture of 25 Nov 2026): live lands a +-- player on a ledge 54 y over a pool (-5921.34,-975.49,63.26), not by the exit trigger down by the tar as 0045 had it, and the +-- standing bosses are at live's spots. The ledge is not joined to the rest of the navmesh: Karrz walked 7 y to its south-east +-- edge and jumped into the pool (START_SWIM at -5894.65,-1006.33,9.58, no fall damage). So: +-- * a one-way nav link from that edge to that splash (bots fall it as a jump, PlayerbotAPI move_to drop), +-- * a new route: crumb 0 the landing, 1 the link's mouth, 2 the splash, then one wing at a time: the north (Cinder on his +-- hill, Titanosaur by the Titanic Door, Snowtalon at the ice panel, Vitrix), the middle (Tor'Rel and Izha'Rel, Venomridge +-- and Bolt), the south (Thunderhoof, King Op, the Direhorn Matriarch) and Nanaya on the Pillar of Assimilation last +-- (about 4140 y, the shortest walk that ends at Nanaya, ShapersTerraceScript.cpp has the same order). +-- Built from the map 3001 navmesh: a crumb every 20 y of walked path or so (215 crumbs, gaps up to 33 y), every crumb-to-crumb +-- leg after the splash is a path on the navmesh of at most 8 polygons (centroid path, two legs on slopes walk 2.4x their straight line). +-- Reverts: yes (0045's route of map 3001, delete the link). + +-- @target: shared + +DELETE FROM {SHARED}.playerbot_dungeon_routes WHERE map_id = 3001; + +INSERT INTO {SHARED}.playerbot_dungeon_routes (map_id, difficulty, seq, position_x, position_y, position_z) VALUES + (3001,0,0,-5921.34,-975.49,63.26),(3001,0,1,-5914.01,-977.20,63.38),(3001,0,2,-5894.65,-1006.33,9.60),(3001,0,3,-5877.33,-1013.33,12.26),(3001,0,4,-5875.68,-992.16,12.26),(3001,0,5,-5860.84,-977.38,12.26), + (3001,0,6,-5836.27,-969.07,13.33),(3001,0,7,-5821.00,-951.00,19.60),(3001,0,8,-5814.40,-930.80,23.80),(3001,0,9,-5804.44,-915.38,24.97),(3001,0,10,-5793.60,-900.00,23.82),(3001,0,11,-5793.87,-875.02,25.60), + (3001,0,12,-5772.69,-863.25,26.56),(3001,0,13,-5783.02,-852.09,28.62),(3001,0,14,-5785.07,-844.00,29.86),(3001,0,15,-5804.73,-835.13,34.93),(3001,0,16,-5814.13,-822.13,41.17),(3001,0,17,-5835.33,-812.47,51.86), + (3001,0,18,-5842.27,-793.67,58.80),(3001,0,19,-5864.60,-798.20,70.46),(3001,0,20,-5889.07,-800.18,79.82),(3001,0,21,-5905.73,-802.58,87.28),(3001,0,22,-5908.80,-813.24,92.00),(3001,0,23,-5909.07,-821.07,98.06), + (3001,0,24,-5907.38,-828.89,104.17),(3001,0,25,-5897.51,-842.93,110.13),(3001,0,26,-5904.20,-862.50,113.10),(3001,0,27,-5894.45,-847.20,111.57),(3001,0,28,-5901.47,-830.80,107.40),(3001,0,29,-5907.38,-828.89,104.17), + (3001,0,30,-5909.07,-821.07,98.06),(3001,0,31,-5908.80,-813.24,92.00),(3001,0,32,-5905.73,-802.58,87.28),(3001,0,33,-5889.07,-800.18,79.82),(3001,0,34,-5868.27,-800.60,73.33),(3001,0,35,-5856.20,-794.47,65.66), + (3001,0,36,-5836.76,-803.64,54.44),(3001,0,37,-5821.87,-803.47,46.22),(3001,0,38,-5806.93,-788.71,42.13),(3001,0,39,-5800.53,-770.76,43.20),(3001,0,40,-5792.00,-757.33,40.86),(3001,0,41,-5770.67,-757.33,37.53), + (3001,0,42,-5770.67,-737.47,38.00),(3001,0,43,-5749.33,-736.00,34.93),(3001,0,44,-5728.00,-736.00,31.33),(3001,0,45,-5706.67,-736.00,28.60),(3001,0,46,-5696.60,-723.80,30.86),(3001,0,47,-5695.04,-723.79,30.88), + (3001,0,48,-5688.09,-725.07,28.80),(3001,0,49,-5689.47,-706.13,26.33),(3001,0,50,-5685.33,-693.33,24.73),(3001,0,51,-5685.33,-672.00,21.93),(3001,0,52,-5681.71,-647.82,19.68),(3001,0,53,-5685.33,-672.00,21.93), + (3001,0,54,-5685.33,-693.33,24.73),(3001,0,55,-5682.93,-715.20,26.53),(3001,0,56,-5670.73,-723.93,28.06),(3001,0,57,-5664.00,-736.00,27.53),(3001,0,58,-5642.67,-736.00,29.93),(3001,0,59,-5621.33,-736.00,31.33), + (3001,0,60,-5600.00,-736.00,31.73),(3001,0,61,-5578.67,-736.00,31.06),(3001,0,62,-5557.73,-737.20,27.20),(3001,0,63,-5537.81,-735.79,24.32),(3001,0,64,-5521.78,-746.13,19.91),(3001,0,65,-5514.89,-761.33,18.66), + (3001,0,66,-5501.65,-776.21,19.46),(3001,0,67,-5496.32,-801.65,18.82),(3001,0,68,-5493.16,-810.40,18.66),(3001,0,69,-5483.11,-809.87,20.62),(3001,0,70,-5469.92,-808.59,23.20),(3001,0,71,-5454.13,-797.92,21.97), + (3001,0,72,-5443.10,-792.40,21.74),(3001,0,73,-5458.04,-799.73,21.42),(3001,0,74,-5473.00,-806.20,22.86),(3001,0,75,-5484.20,-813.07,19.00),(3001,0,76,-5505.47,-817.87,18.66),(3001,0,77,-5514.24,-825.65,19.14), + (3001,0,78,-5520.80,-845.80,22.62),(3001,0,79,-5547.33,-849.40,18.66),(3001,0,80,-5555.47,-862.77,18.66),(3001,0,81,-5575.80,-872.13,18.66),(3001,0,82,-5578.67,-884.62,19.24),(3001,0,83,-5578.67,-906.67,20.53), + (3001,0,84,-5578.67,-928.00,21.93),(3001,0,85,-5578.67,-949.33,21.26),(3001,0,86,-5578.67,-970.67,19.53),(3001,0,87,-5578.67,-992.00,17.93),(3001,0,88,-5578.67,-1013.33,13.73),(3001,0,89,-5578.67,-1034.67,10.13), + (3001,0,90,-5591.38,-1044.80,9.33),(3001,0,91,-5599.64,-1057.73,9.33),(3001,0,92,-5611.47,-1070.22,9.26),(3001,0,93,-5622.22,-1089.16,10.42),(3001,0,94,-5628.44,-1091.11,9.98),(3001,0,95,-5637.53,-1102.87,12.40), + (3001,0,96,-5642.67,-1120.00,17.80),(3001,0,97,-5642.03,-1141.65,25.80),(3001,0,98,-5642.35,-1165.28,29.80),(3001,0,99,-5644.75,-1186.03,33.37),(3001,0,100,-5644.64,-1205.60,34.60),(3001,0,101,-5624.27,-1205.67,35.33), + (3001,0,102,-5628.32,-1223.80,34.17),(3001,0,103,-5624.27,-1205.67,35.33),(3001,0,104,-5644.64,-1205.60,34.60),(3001,0,105,-5644.75,-1186.03,33.37),(3001,0,106,-5642.35,-1165.28,29.80),(3001,0,107,-5659.73,-1151.20,25.71), + (3001,0,108,-5656.36,-1131.64,22.60),(3001,0,109,-5660.09,-1123.91,17.71),(3001,0,110,-5668.80,-1131.47,11.49),(3001,0,111,-5685.33,-1141.33,9.60),(3001,0,112,-5697.27,-1159.20,8.26),(3001,0,113,-5720.53,-1171.82,8.82), + (3001,0,114,-5736.36,-1188.89,2.51),(3001,0,115,-5760.98,-1189.16,-4.16),(3001,0,116,-5778.13,-1180.93,-2.94),(3001,0,117,-5792.00,-1184.00,-3.54),(3001,0,118,-5813.33,-1184.00,-2.94),(3001,0,119,-5834.13,-1184.00,-1.54), + (3001,0,120,-5854.45,-1186.03,-0.71),(3001,0,121,-5877.33,-1184.00,1.37),(3001,0,122,-5908.77,-1192.19,6.76),(3001,0,123,-5933.00,-1183.30,9.07),(3001,0,124,-5933.00,-1204.20,8.84),(3001,0,125,-5933.60,-1225.42,9.53), + (3001,0,126,-5933.53,-1249.60,9.44),(3001,0,127,-5921.28,-1269.87,10.35),(3001,0,128,-5918.29,-1290.61,9.71),(3001,0,129,-5918.73,-1312.00,8.84),(3001,0,130,-5920.00,-1333.33,6.84),(3001,0,131,-5932.80,-1343.29,7.22), + (3001,0,132,-5934.08,-1351.47,8.43),(3001,0,133,-5942.67,-1373.78,11.66),(3001,0,134,-5960.40,-1382.53,11.51),(3001,0,135,-5964.27,-1395.68,10.77),(3001,0,136,-5962.67,-1418.67,10.77),(3001,0,137,-5962.67,-1440.00,9.71), + (3001,0,138,-5952.41,-1463.46,8.84),(3001,0,139,-5962.56,-1482.24,9.12),(3001,0,140,-5958.84,-1500.18,7.66),(3001,0,141,-5962.67,-1525.33,7.57),(3001,0,142,-5961.60,-1546.29,7.57),(3001,0,143,-5956.27,-1565.73,7.71), + (3001,0,144,-5951.15,-1585.97,7.57),(3001,0,145,-5955.02,-1609.60,7.82),(3001,0,146,-5957.78,-1630.13,7.82),(3001,0,147,-5966.44,-1651.47,8.97),(3001,0,148,-5964.64,-1672.37,8.24),(3001,0,149,-5971.15,-1691.25,8.72), + (3001,0,150,-5964.40,-1716.09,10.88),(3001,0,151,-5962.61,-1735.31,18.59),(3001,0,152,-5956.40,-1750.00,25.75),(3001,0,153,-5960.00,-1769.42,26.57),(3001,0,154,-5972.44,-1780.98,32.44),(3001,0,155,-5985.07,-1800.27,41.42), + (3001,0,156,-5998.40,-1817.40,47.82),(3001,0,157,-6016.18,-1820.71,54.84),(3001,0,158,-6025.60,-1833.67,59.42),(3001,0,159,-6037.87,-1841.00,60.75),(3001,0,160,-6042.60,-1859.27,58.35),(3001,0,161,-6061.28,-1865.33,60.40), + (3001,0,162,-6078.40,-1864.67,59.55),(3001,0,163,-6093.33,-1878.33,59.68),(3001,0,164,-6082.87,-1886.07,60.68),(3001,0,165,-6077.60,-1902.61,59.02),(3001,0,166,-6060.00,-1910.88,54.96),(3001,0,167,-6053.11,-1925.20,54.31), + (3001,0,168,-6061.24,-1946.13,48.80),(3001,0,169,-6082.83,-1957.07,46.06),(3001,0,170,-6097.40,-1971.80,42.95),(3001,0,171,-6107.08,-1971.40,43.91),(3001,0,172,-6090.40,-1961.53,43.82),(3001,0,173,-6066.80,-1952.36,46.88), + (3001,0,174,-6054.31,-1932.80,52.44),(3001,0,175,-6056.47,-1914.40,54.88),(3001,0,176,-6071.42,-1907.24,57.64),(3001,0,177,-6084.96,-1893.71,60.35),(3001,0,178,-6084.27,-1880.76,60.08),(3001,0,179,-6084.05,-1871.52,59.76), + (3001,0,180,-6066.49,-1859.91,59.73),(3001,0,181,-6050.84,-1865.96,58.97),(3001,0,182,-6040.98,-1847.73,58.93),(3001,0,183,-6029.28,-1837.87,59.92),(3001,0,184,-6016.18,-1820.71,54.84),(3001,0,185,-5998.40,-1817.40,47.82), + (3001,0,186,-5985.07,-1800.27,41.42),(3001,0,187,-5972.44,-1780.98,32.44),(3001,0,188,-5960.00,-1769.42,26.57),(3001,0,189,-5941.33,-1760.00,21.42),(3001,0,190,-5918.99,-1758.83,16.46),(3001,0,191,-5900.84,-1738.36,14.04), + (3001,0,192,-5891.73,-1742.00,14.48),(3001,0,193,-5877.73,-1740.18,14.17),(3001,0,194,-5862.11,-1739.59,13.57),(3001,0,195,-5834.67,-1738.67,14.17),(3001,0,196,-5813.33,-1738.67,14.64),(3001,0,197,-5792.00,-1738.67,15.64), + (3001,0,198,-5767.11,-1737.20,22.35),(3001,0,199,-5760.27,-1727.56,27.37),(3001,0,200,-5754.27,-1726.60,31.04),(3001,0,201,-5751.15,-1717.81,34.31),(3001,0,202,-5749.33,-1696.00,35.97),(3001,0,203,-5750.24,-1674.13,34.04), + (3001,0,204,-5739.07,-1653.93,33.04),(3001,0,205,-5724.00,-1641.20,37.77),(3001,0,206,-5733.00,-1620.80,38.17),(3001,0,207,-5740.60,-1610.80,37.91),(3001,0,208,-5750.24,-1608.16,39.11),(3001,0,209,-5770.67,-1606.73,39.97), + (3001,0,210,-5770.67,-1594.40,39.93),(3001,0,211,-5798.00,-1591.20,37.93),(3001,0,212,-5813.33,-1589.33,37.33),(3001,0,213,-5836.44,-1590.31,37.71),(3001,0,214,-5854.20,-1587.50,37.26); + +-- The landing ledge's south-east edge, where Karrz stood before he jumped, to where he hit the water. One way, radius 8 takes in +-- the whole landing spot (7.5 y from the mouth). +DELETE FROM {SHARED}.playerbot_nav_links WHERE map_id = 3001 AND kind = 'drop' AND comment LIKE 'Shaper''s Terrace landing ledge%'; +INSERT INTO {SHARED}.playerbot_nav_links (map_id, from_x, from_y, from_z, to_x, to_y, to_z, radius, bidirectional, kind, comment, verified, created_by) VALUES + (3001,-5914.01,-977.20,63.38,-5894.65,-1006.33,9.60,8,0,'drop','Shaper''s Terrace landing ledge into the pool: live capture 25 Nov 2026 (Karrz jumped here, no fall damage)',1,'karrz'); diff --git a/sql/playerbot_v2/0069_blackmaw_hold_route_from_the_live_landing.sql b/sql/playerbot_v2/0069_blackmaw_hold_route_from_the_live_landing.sql new file mode 100644 index 0000000000..e659118f77 --- /dev/null +++ b/sql/playerbot_v2/0069_blackmaw_hold_route_from_the_live_landing.sql @@ -0,0 +1,63 @@ +-- Migration: 0069_blackmaw_hold_route_from_the_live_landing +-- Date: 2026-11-26 +-- Purpose: Blackmaw Hold (map 2974) as live has it (world 2026_11_26_40..42, from Karrz's capture of 25-26 Nov 2026). Live lands a +-- player at the tunnel's north end (3375.09,3822.24,306.98), not at (3470,3690) as 0044 had it, the Blackmaw Behemoth and +-- Clawbert stand low in the west hall (136 y) where Elder Shaman Bloodmane stood, Bloodmane in the east cave where they stood, +-- and Varrox Bleakhoof waits in a deep chamber about 200 y below the Behemoth's hall (z -62), not in the high north room +-- 0062 walked to. That chamber is not joined to the rest of the navmesh: after the Behemoth Karrz walked west to the hall's +-- edge and fell (from (3423.8,2936.9,133.4), 4.5 s), into a pool (START_SWIM at 3396.2,2921.1,-65.5, no fall damage), swam +-- north-east to the shore and walked to Varrox. There is no way back up. So: +-- * a one-way nav link from that edge to that splash (bots fall it as a jump, PlayerbotAPI move_to drop), +-- * a new route: the landing, then Withermaw, Bonesnout the Unbroken, Impaan the Imprisoner, the Unbound Spirit, Elder +-- Shaman Bloodmane and the Blackmaw Behemoth, the link's mouth, the splash, and Varrox last (about 4150 y, the shortest +-- walk from the landing that ends with the Behemoth before the fall, BlackmawHoldScript.cpp has the same order). +-- Built from the map 2974 navmesh: a crumb every 20 y of walked path or so (209 crumbs, gaps up to 30 y), every crumb-to-crumb +-- leg but the fall is a path on the navmesh of at most 9 polygons. The pool is in the chamber's navmesh (its water +-- polygons), so the swim to the shore needs no second link. +-- Reverts: yes (0044 and 0062's route of map 2974, delete the link). + +-- @target: shared + +DELETE FROM {SHARED}.playerbot_dungeon_routes WHERE map_id = 2974; + +INSERT INTO {SHARED}.playerbot_dungeon_routes (map_id, difficulty, seq, position_x, position_y, position_z) VALUES + (2974,0,0,3375.09,3822.24,306.98),(2974,0,1,3370.84,3803.91,308.00),(2974,0,2,3371.79,3791.15,306.77),(2974,0,3,3383.93,3774.80,308.67),(2974,0,4,3392.44,3763.20,306.58),(2974,0,5,3407.73,3752.13,306.20), + (2974,0,6,3425.69,3748.36,309.07),(2974,0,7,3432.43,3738.72,306.83),(2974,0,8,3445.33,3722.67,304.47),(2974,0,9,3446.93,3702.20,302.41),(2974,0,10,3460.53,3693.56,301.50),(2974,0,11,3461.96,3691.56,302.12), + (2974,0,12,3477.16,3684.62,300.78),(2974,0,13,3489.87,3680.16,296.93),(2974,0,14,3497.51,3659.73,295.54),(2974,0,15,3500.67,3633.93,294.94),(2974,0,16,3512.53,3616.27,294.83),(2974,0,17,3520.80,3606.73,295.34), + (2974,0,18,3533.60,3595.69,295.14),(2974,0,19,3545.16,3578.76,294.83),(2974,0,20,3546.80,3558.33,296.07),(2974,0,21,3551.31,3530.77,293.19),(2974,0,22,3549.80,3508.07,291.94),(2974,0,23,3558.13,3486.29,295.22), + (2974,0,24,3566.71,3469.73,297.32),(2974,0,25,3574.40,3452.00,296.83),(2974,0,26,3570.47,3433.13,296.61),(2974,0,27,3584.09,3416.98,296.07),(2974,0,28,3596.00,3398.22,293.10),(2974,0,29,3622.22,3400.44,290.12), + (2974,0,30,3636.27,3408.27,289.47),(2974,0,31,3647.47,3429.07,291.87),(2974,0,32,3659.47,3422.08,291.97),(2974,0,33,3665.33,3400.22,291.45),(2974,0,34,3673.07,3383.73,290.12),(2974,0,35,3679.20,3368.80,289.32), + (2974,0,36,3697.27,3359.00,287.47),(2974,0,37,3712.09,3359.29,284.52),(2974,0,38,3734.30,3369.20,284.11),(2974,0,39,3714.31,3362.40,284.52),(2974,0,40,3697.27,3359.00,287.47),(2974,0,41,3679.20,3368.80,289.32), + (2974,0,42,3667.36,3368.69,290.85),(2974,0,43,3648.98,3359.20,288.43),(2974,0,44,3625.33,3351.02,278.38),(2974,0,45,3612.40,3336.53,272.87),(2974,0,46,3593.80,3331.60,272.67),(2974,0,47,3577.65,3333.33,273.09), + (2974,0,48,3572.31,3355.29,268.30),(2974,0,49,3550.93,3361.56,261.18),(2974,0,50,3536.87,3379.20,257.47),(2974,0,51,3510.24,3382.45,254.85),(2974,0,52,3489.44,3380.32,254.42),(2974,0,53,3466.22,3380.31,253.98), + (2974,0,54,3443.20,3378.71,253.72),(2974,0,55,3424.16,3379.36,254.10),(2974,0,56,3402.27,3378.13,252.61),(2974,0,57,3381.87,3380.00,251.98),(2974,0,58,3359.79,3382.88,250.74),(2974,0,59,3339.07,3383.40,250.67), + (2974,0,60,3338.67,3402.67,251.34),(2974,0,61,3317.33,3402.67,251.21),(2974,0,62,3297.80,3409.80,250.45),(2974,0,63,3317.33,3402.67,251.21),(2974,0,64,3338.67,3402.67,251.34),(2974,0,65,3357.42,3413.69,256.61), + (2974,0,66,3360.89,3433.96,263.98),(2974,0,67,3381.27,3438.00,274.07),(2974,0,68,3402.51,3442.40,285.57),(2974,0,69,3423.82,3446.58,293.67),(2974,0,70,3423.31,3465.55,298.58),(2974,0,71,3419.47,3470.67,301.47), + (2974,0,72,3403.73,3482.83,305.03),(2974,0,73,3380.22,3480.93,314.12),(2974,0,74,3362.99,3481.71,321.99),(2974,0,75,3346.33,3491.00,333.14),(2974,0,76,3331.13,3492.53,336.74),(2974,0,77,3313.07,3502.31,339.10), + (2974,0,78,3309.40,3511.00,341.07),(2974,0,79,3317.33,3529.87,347.07),(2974,0,80,3310.58,3544.27,344.34),(2974,0,81,3310.31,3559.91,344.34),(2974,0,82,3314.99,3573.33,343.22),(2974,0,83,3316.32,3596.64,342.31), + (2974,0,84,3318.31,3616.27,343.98),(2974,0,85,3323.20,3628.53,345.50),(2974,0,86,3323.20,3634.47,347.07),(2974,0,87,3348.10,3641.90,343.24),(2974,0,88,3323.20,3634.47,347.07),(2974,0,89,3324.09,3627.11,344.78), + (2974,0,90,3318.31,3616.27,343.98),(2974,0,91,3316.32,3596.64,342.31),(2974,0,92,3314.99,3573.33,343.22),(2974,0,93,3309.33,3552.07,344.61),(2974,0,94,3310.58,3544.27,344.34),(2974,0,95,3317.33,3529.87,347.07), + (2974,0,96,3309.40,3511.00,341.07),(2974,0,97,3318.40,3499.02,338.65),(2974,0,98,3331.13,3492.53,336.74),(2974,0,99,3349.87,3491.13,332.47),(2974,0,100,3370.04,3480.80,318.92),(2974,0,101,3396.47,3482.73,307.41), + (2974,0,102,3410.45,3475.04,304.13),(2974,0,103,3429.67,3470.47,298.47),(2974,0,104,3444.21,3464.43,296.18),(2974,0,105,3455.07,3442.47,297.81),(2974,0,106,3464.62,3430.00,298.12),(2974,0,107,3462.08,3411.09,293.46), + (2974,0,108,3461.67,3383.60,292.67),(2974,0,109,3462.40,3356.75,300.55),(2974,0,110,3466.44,3336.13,309.32),(2974,0,111,3465.07,3315.87,318.14),(2974,0,112,3461.44,3293.65,325.51),(2974,0,113,3460.22,3272.80,329.18), + (2974,0,114,3464.53,3246.27,325.07),(2974,0,115,3465.96,3225.60,323.36),(2974,0,116,3478.22,3222.76,323.10),(2974,0,117,3499.57,3212.27,321.73),(2974,0,118,3522.00,3214.80,320.47),(2974,0,119,3543.84,3216.80,319.33), + (2974,0,120,3556.37,3208.69,317.19),(2974,0,121,3563.40,3194.80,315.36),(2974,0,122,3575.42,3192.49,314.02),(2974,0,123,3581.27,3171.60,312.16),(2974,0,124,3587.07,3156.40,311.22),(2974,0,125,3597.49,3139.79,310.45), + (2974,0,126,3597.67,3117.60,309.22),(2974,0,127,3615.82,3104.40,304.69),(2974,0,128,3620.32,3082.35,301.12),(2974,0,129,3616.71,3061.82,297.54),(2974,0,130,3592.76,3060.31,294.82),(2974,0,131,3572.89,3070.04,291.71), + (2974,0,132,3555.29,3078.49,287.54),(2974,0,133,3543.56,3093.07,282.91),(2974,0,134,3520.62,3105.51,276.42),(2974,0,135,3502.56,3111.25,273.54),(2974,0,136,3482.40,3111.67,262.56),(2974,0,137,3459.56,3109.69,257.49), + (2974,0,138,3443.80,3102.67,254.36),(2974,0,139,3434.40,3089.78,249.40),(2974,0,140,3419.80,3075.40,244.29),(2974,0,141,3419.68,3056.59,241.38),(2974,0,142,3421.69,3042.31,240.51),(2974,0,143,3412.40,3034.47,238.89), + (2974,0,144,3406.31,3019.20,232.69),(2974,0,145,3394.19,3014.40,227.62),(2974,0,146,3375.07,3011.13,223.89),(2974,0,147,3364.00,2998.49,219.85),(2974,0,148,3351.87,2986.00,218.02),(2974,0,149,3334.93,2977.47,217.02), + (2974,0,150,3324.33,2971.00,219.56),(2974,0,151,3305.78,2965.60,216.25),(2974,0,152,3293.40,2942.53,210.16),(2974,0,153,3276.00,2933.81,207.41),(2974,0,154,3274.67,2912.00,205.49),(2974,0,155,3249.10,2911.50,203.89), + (2974,0,156,3274.67,2912.00,205.49),(2974,0,157,3303.47,2912.11,205.22),(2974,0,158,3318.71,2897.87,205.22),(2974,0,159,3338.56,2888.69,207.36),(2974,0,160,3354.04,2883.20,205.67),(2974,0,161,3378.98,2886.00,201.58), + (2974,0,162,3395.80,2879.07,200.29),(2974,0,163,3406.40,2860.59,199.20),(2974,0,164,3408.31,2843.16,196.29),(2974,0,165,3423.20,2839.13,195.82),(2974,0,166,3449.07,2849.24,193.58),(2974,0,167,3467.47,2855.60,192.96), + (2974,0,168,3489.65,2849.17,193.28),(2974,0,169,3492.80,2824.58,193.54),(2974,0,170,3509.69,2805.20,192.47),(2974,0,171,3529.00,2799.00,189.89),(2974,0,172,3545.97,2801.23,185.06),(2974,0,173,3556.27,2819.47,175.96), + (2974,0,174,3554.19,2839.15,169.38),(2974,0,175,3567.38,2857.07,169.05),(2974,0,176,3580.53,2870.19,169.44),(2974,0,177,3603.56,2868.27,173.05),(2974,0,178,3626.49,2868.44,173.40),(2974,0,179,3637.33,2868.27,172.74), + (2974,0,180,3658.80,2867.02,172.16),(2974,0,181,3681.30,2868.80,172.20),(2974,0,182,3658.80,2867.02,172.16),(2974,0,183,3637.33,2868.27,172.74),(2974,0,184,3617.40,2870.53,174.22),(2974,0,185,3593.78,2867.33,170.91), + (2974,0,186,3571.87,2869.20,169.49),(2974,0,187,3576.93,2889.29,171.14),(2974,0,188,3587.73,2903.91,164.96),(2974,0,189,3594.73,2922.20,159.89),(2974,0,190,3591.60,2941.78,156.82),(2974,0,191,3586.40,2964.71,149.85), + (2974,0,192,3568.27,2977.33,146.60),(2974,0,193,3552.13,2981.47,145.22),(2974,0,194,3531.56,2974.93,146.87),(2974,0,195,3510.08,2977.12,145.17),(2974,0,196,3500.44,2961.51,139.54),(2974,0,197,3479.60,2962.00,136.80), + (2974,0,198,3453.33,2957.33,135.89),(2974,0,199,3451.91,2944.98,135.89),(2974,0,200,3436.49,2935.24,136.47),(2974,0,201,3426.60,2938.20,134.43),(2974,0,202,3396.20,2921.10,-65.50),(2974,0,203,3424.00,2912.00,-63.84), + (2974,0,204,3445.96,2920.09,-63.84),(2974,0,205,3458.20,2937.07,-63.84),(2974,0,206,3463.84,2962.83,-63.10),(2974,0,207,3480.00,2976.07,-62.11),(2974,0,208,3482.40,3001.00,-62.45); + +-- The west edge of the Behemoth's hall, on the navmesh 3 y short of where Karrz left it, to where he hit the water. One way. +DELETE FROM {SHARED}.playerbot_nav_links WHERE map_id = 2974 AND kind = 'drop' AND comment LIKE 'Blackmaw Hold Behemoth hall%'; +INSERT INTO {SHARED}.playerbot_nav_links (map_id, from_x, from_y, from_z, to_x, to_y, to_z, radius, bidirectional, kind, comment, verified, created_by) VALUES + (2974,3426.60,2938.20,134.43,3396.20,2921.10,-65.50,8,0,'drop','Blackmaw Hold Behemoth hall edge into the pool by Varrox: live capture 26 Nov 2026 (Karrz fell here, no fall damage)',1,'karrz'); diff --git a/sql/playerbot_v2/0070_shapers_terrace_route_not_through_the_titanic_door.sql b/sql/playerbot_v2/0070_shapers_terrace_route_not_through_the_titanic_door.sql new file mode 100644 index 0000000000..9780644ec1 --- /dev/null +++ b/sql/playerbot_v2/0070_shapers_terrace_route_not_through_the_titanic_door.sql @@ -0,0 +1,52 @@ +-- Migration: 0070_shapers_terrace_route_not_through_the_titanic_door +-- Date: 2026-11-26 +-- Purpose: The Shaper's Terrace (map 3001): 0068's route went from the Titanic Door's front (crumb 48) through the door to the +-- Titanosaur (crumbs 49-55) and back. The door is live's locked raid gate (world 2026_11_25_82, state closed, Karrz used it 12 +-- times on 25 Nov 2026 and it never opened), and the Titanosaur stands behind it: with the door closed the navmesh has no other +-- way to him. A closed door is not walked through (PathGenerator's closed-door check), so the tank stood at the door's front for +-- good (shapers_full af84 26 Nov 2026: group_stalled at 565 s, reach_reject PATHFIND_INCOMPLETE from crumb 47 toward 49). +-- This is 0068's route without crumbs 49-55: from the door's front straight on to the east (crumb 48 to 0068's 56, 17 y along +-- the door's face, 8 y clear of it), renumbered, 208 crumbs. ShapersTerraceScript and shapers_full drop the Titanosaur. The +-- landing link of 0068 stays. +-- Reverts: yes (0068's route). + +-- @target: shared + +DELETE FROM {SHARED}.playerbot_dungeon_routes WHERE map_id = 3001; + +INSERT INTO {SHARED}.playerbot_dungeon_routes (map_id, difficulty, seq, position_x, position_y, position_z) VALUES + (3001,0,0,-5921.34,-975.49,63.26),(3001,0,1,-5914.01,-977.20,63.38),(3001,0,2,-5894.65,-1006.33,9.60),(3001,0,3,-5877.33,-1013.33,12.26),(3001,0,4,-5875.68,-992.16,12.26),(3001,0,5,-5860.84,-977.38,12.26), + (3001,0,6,-5836.27,-969.07,13.33),(3001,0,7,-5821.00,-951.00,19.60),(3001,0,8,-5814.40,-930.80,23.80),(3001,0,9,-5804.44,-915.38,24.97),(3001,0,10,-5793.60,-900.00,23.82),(3001,0,11,-5793.87,-875.02,25.60), + (3001,0,12,-5772.69,-863.25,26.56),(3001,0,13,-5783.02,-852.09,28.62),(3001,0,14,-5785.07,-844.00,29.86),(3001,0,15,-5804.73,-835.13,34.93),(3001,0,16,-5814.13,-822.13,41.17),(3001,0,17,-5835.33,-812.47,51.86), + (3001,0,18,-5842.27,-793.67,58.80),(3001,0,19,-5864.60,-798.20,70.46),(3001,0,20,-5889.07,-800.18,79.82),(3001,0,21,-5905.73,-802.58,87.28),(3001,0,22,-5908.80,-813.24,92.00),(3001,0,23,-5909.07,-821.07,98.06), + (3001,0,24,-5907.38,-828.89,104.17),(3001,0,25,-5897.51,-842.93,110.13),(3001,0,26,-5904.20,-862.50,113.10),(3001,0,27,-5894.45,-847.20,111.57),(3001,0,28,-5901.47,-830.80,107.40),(3001,0,29,-5907.38,-828.89,104.17), + (3001,0,30,-5909.07,-821.07,98.06),(3001,0,31,-5908.80,-813.24,92.00),(3001,0,32,-5905.73,-802.58,87.28),(3001,0,33,-5889.07,-800.18,79.82),(3001,0,34,-5868.27,-800.60,73.33),(3001,0,35,-5856.20,-794.47,65.66), + (3001,0,36,-5836.76,-803.64,54.44),(3001,0,37,-5821.87,-803.47,46.22),(3001,0,38,-5806.93,-788.71,42.13),(3001,0,39,-5800.53,-770.76,43.20),(3001,0,40,-5792.00,-757.33,40.86),(3001,0,41,-5770.67,-757.33,37.53), + (3001,0,42,-5770.67,-737.47,38.00),(3001,0,43,-5749.33,-736.00,34.93),(3001,0,44,-5728.00,-736.00,31.33),(3001,0,45,-5706.67,-736.00,28.60),(3001,0,46,-5696.60,-723.80,30.86),(3001,0,47,-5695.04,-723.79,30.88), + (3001,0,48,-5688.09,-725.07,28.80),(3001,0,49,-5670.73,-723.93,28.06),(3001,0,50,-5664.00,-736.00,27.53),(3001,0,51,-5642.67,-736.00,29.93),(3001,0,52,-5621.33,-736.00,31.33),(3001,0,53,-5600.00,-736.00,31.73), + (3001,0,54,-5578.67,-736.00,31.06),(3001,0,55,-5557.73,-737.20,27.20),(3001,0,56,-5537.81,-735.79,24.32),(3001,0,57,-5521.78,-746.13,19.91),(3001,0,58,-5514.89,-761.33,18.66),(3001,0,59,-5501.65,-776.21,19.46), + (3001,0,60,-5496.32,-801.65,18.82),(3001,0,61,-5493.16,-810.40,18.66),(3001,0,62,-5483.11,-809.87,20.62),(3001,0,63,-5469.92,-808.59,23.20),(3001,0,64,-5454.13,-797.92,21.97),(3001,0,65,-5443.10,-792.40,21.74), + (3001,0,66,-5458.04,-799.73,21.42),(3001,0,67,-5473.00,-806.20,22.86),(3001,0,68,-5484.20,-813.07,19.00),(3001,0,69,-5505.47,-817.87,18.66),(3001,0,70,-5514.24,-825.65,19.14),(3001,0,71,-5520.80,-845.80,22.62), + (3001,0,72,-5547.33,-849.40,18.66),(3001,0,73,-5555.47,-862.77,18.66),(3001,0,74,-5575.80,-872.13,18.66),(3001,0,75,-5578.67,-884.62,19.24),(3001,0,76,-5578.67,-906.67,20.53),(3001,0,77,-5578.67,-928.00,21.93), + (3001,0,78,-5578.67,-949.33,21.26),(3001,0,79,-5578.67,-970.67,19.53),(3001,0,80,-5578.67,-992.00,17.93),(3001,0,81,-5578.67,-1013.33,13.73),(3001,0,82,-5578.67,-1034.67,10.13),(3001,0,83,-5591.38,-1044.80,9.33), + (3001,0,84,-5599.64,-1057.73,9.33),(3001,0,85,-5611.47,-1070.22,9.26),(3001,0,86,-5622.22,-1089.16,10.42),(3001,0,87,-5628.44,-1091.11,9.98),(3001,0,88,-5637.53,-1102.87,12.40),(3001,0,89,-5642.67,-1120.00,17.80), + (3001,0,90,-5642.03,-1141.65,25.80),(3001,0,91,-5642.35,-1165.28,29.80),(3001,0,92,-5644.75,-1186.03,33.37),(3001,0,93,-5644.64,-1205.60,34.60),(3001,0,94,-5624.27,-1205.67,35.33),(3001,0,95,-5628.32,-1223.80,34.17), + (3001,0,96,-5624.27,-1205.67,35.33),(3001,0,97,-5644.64,-1205.60,34.60),(3001,0,98,-5644.75,-1186.03,33.37),(3001,0,99,-5642.35,-1165.28,29.80),(3001,0,100,-5659.73,-1151.20,25.71),(3001,0,101,-5656.36,-1131.64,22.60), + (3001,0,102,-5660.09,-1123.91,17.71),(3001,0,103,-5668.80,-1131.47,11.49),(3001,0,104,-5685.33,-1141.33,9.60),(3001,0,105,-5697.27,-1159.20,8.26),(3001,0,106,-5720.53,-1171.82,8.82),(3001,0,107,-5736.36,-1188.89,2.51), + (3001,0,108,-5760.98,-1189.16,-4.16),(3001,0,109,-5778.13,-1180.93,-2.94),(3001,0,110,-5792.00,-1184.00,-3.54),(3001,0,111,-5813.33,-1184.00,-2.94),(3001,0,112,-5834.13,-1184.00,-1.54),(3001,0,113,-5854.45,-1186.03,-0.71), + (3001,0,114,-5877.33,-1184.00,1.37),(3001,0,115,-5908.77,-1192.19,6.76),(3001,0,116,-5933.00,-1183.30,9.07),(3001,0,117,-5933.00,-1204.20,8.84),(3001,0,118,-5933.60,-1225.42,9.53),(3001,0,119,-5933.53,-1249.60,9.44), + (3001,0,120,-5921.28,-1269.87,10.35),(3001,0,121,-5918.29,-1290.61,9.71),(3001,0,122,-5918.73,-1312.00,8.84),(3001,0,123,-5920.00,-1333.33,6.84),(3001,0,124,-5932.80,-1343.29,7.22),(3001,0,125,-5934.08,-1351.47,8.43), + (3001,0,126,-5942.67,-1373.78,11.66),(3001,0,127,-5960.40,-1382.53,11.51),(3001,0,128,-5964.27,-1395.68,10.77),(3001,0,129,-5962.67,-1418.67,10.77),(3001,0,130,-5962.67,-1440.00,9.71),(3001,0,131,-5952.41,-1463.46,8.84), + (3001,0,132,-5962.56,-1482.24,9.12),(3001,0,133,-5958.84,-1500.18,7.66),(3001,0,134,-5962.67,-1525.33,7.57),(3001,0,135,-5961.60,-1546.29,7.57),(3001,0,136,-5956.27,-1565.73,7.71),(3001,0,137,-5951.15,-1585.97,7.57), + (3001,0,138,-5955.02,-1609.60,7.82),(3001,0,139,-5957.78,-1630.13,7.82),(3001,0,140,-5966.44,-1651.47,8.97),(3001,0,141,-5964.64,-1672.37,8.24),(3001,0,142,-5971.15,-1691.25,8.72),(3001,0,143,-5964.40,-1716.09,10.88), + (3001,0,144,-5962.61,-1735.31,18.59),(3001,0,145,-5956.40,-1750.00,25.75),(3001,0,146,-5960.00,-1769.42,26.57),(3001,0,147,-5972.44,-1780.98,32.44),(3001,0,148,-5985.07,-1800.27,41.42),(3001,0,149,-5998.40,-1817.40,47.82), + (3001,0,150,-6016.18,-1820.71,54.84),(3001,0,151,-6025.60,-1833.67,59.42),(3001,0,152,-6037.87,-1841.00,60.75),(3001,0,153,-6042.60,-1859.27,58.35),(3001,0,154,-6061.28,-1865.33,60.40),(3001,0,155,-6078.40,-1864.67,59.55), + (3001,0,156,-6093.33,-1878.33,59.68),(3001,0,157,-6082.87,-1886.07,60.68),(3001,0,158,-6077.60,-1902.61,59.02),(3001,0,159,-6060.00,-1910.88,54.96),(3001,0,160,-6053.11,-1925.20,54.31),(3001,0,161,-6061.24,-1946.13,48.80), + (3001,0,162,-6082.83,-1957.07,46.06),(3001,0,163,-6097.40,-1971.80,42.95),(3001,0,164,-6107.08,-1971.40,43.91),(3001,0,165,-6090.40,-1961.53,43.82),(3001,0,166,-6066.80,-1952.36,46.88),(3001,0,167,-6054.31,-1932.80,52.44), + (3001,0,168,-6056.47,-1914.40,54.88),(3001,0,169,-6071.42,-1907.24,57.64),(3001,0,170,-6084.96,-1893.71,60.35),(3001,0,171,-6084.27,-1880.76,60.08),(3001,0,172,-6084.05,-1871.52,59.76),(3001,0,173,-6066.49,-1859.91,59.73), + (3001,0,174,-6050.84,-1865.96,58.97),(3001,0,175,-6040.98,-1847.73,58.93),(3001,0,176,-6029.28,-1837.87,59.92),(3001,0,177,-6016.18,-1820.71,54.84),(3001,0,178,-5998.40,-1817.40,47.82),(3001,0,179,-5985.07,-1800.27,41.42), + (3001,0,180,-5972.44,-1780.98,32.44),(3001,0,181,-5960.00,-1769.42,26.57),(3001,0,182,-5941.33,-1760.00,21.42),(3001,0,183,-5918.99,-1758.83,16.46),(3001,0,184,-5900.84,-1738.36,14.04),(3001,0,185,-5891.73,-1742.00,14.48), + (3001,0,186,-5877.73,-1740.18,14.17),(3001,0,187,-5862.11,-1739.59,13.57),(3001,0,188,-5834.67,-1738.67,14.17),(3001,0,189,-5813.33,-1738.67,14.64),(3001,0,190,-5792.00,-1738.67,15.64),(3001,0,191,-5767.11,-1737.20,22.35), + (3001,0,192,-5760.27,-1727.56,27.37),(3001,0,193,-5754.27,-1726.60,31.04),(3001,0,194,-5751.15,-1717.81,34.31),(3001,0,195,-5749.33,-1696.00,35.97),(3001,0,196,-5750.24,-1674.13,34.04),(3001,0,197,-5739.07,-1653.93,33.04), + (3001,0,198,-5724.00,-1641.20,37.77),(3001,0,199,-5733.00,-1620.80,38.17),(3001,0,200,-5740.60,-1610.80,37.91),(3001,0,201,-5750.24,-1608.16,39.11),(3001,0,202,-5770.67,-1606.73,39.97),(3001,0,203,-5770.67,-1594.40,39.93), + (3001,0,204,-5798.00,-1591.20,37.93),(3001,0,205,-5813.33,-1589.33,37.33),(3001,0,206,-5836.44,-1590.31,37.71),(3001,0,207,-5854.20,-1587.50,37.26); diff --git a/sql/playerbot_v2/0071_alcaz_prison_route_as_live_clears_it.sql b/sql/playerbot_v2/0071_alcaz_prison_route_as_live_clears_it.sql new file mode 100644 index 0000000000..00f679c801 --- /dev/null +++ b/sql/playerbot_v2/0071_alcaz_prison_route_as_live_clears_it.sql @@ -0,0 +1,64 @@ +-- Migration: 0071_alcaz_prison_route_as_live_clears_it +-- Date: 2026-11-27 +-- Purpose: Alcaz Prison (map 2994): the route for live's layout (world 2026_11_27_40..43, from Karrz's capture of a full clear on +-- 26 Nov) in live's kill order: Overseer Wrex, Katerina the Cleaner, Blazeroar, The Questioner. From live's landing +-- (-8796.59, 2838.67, 28.77) only Wrex's wing is open: with live's doors shut, the 2994 navmesh joins the landing to Wrex +-- and to the Maximum Security Door 649547 (-8791.3, 2932.4), and nothing else. Legs 21-22 go through that door (the rogue +-- picks its lock, as on live) to Katerina and Blazeroar, legs 39-40 come back out through it, legs 43-44 go through the +-- Prison Gate 649552 (-8763.4, 2871.3), which shuts 3 s after each use, to The Questioner. No other leg crosses a door. +-- Crumbs 10, 26, 31 and 46 are the bosses' spots. 47 crumbs, 789 y, every leg is a navmesh path of at most 26 y. +-- Tidemistress Ca'zass is not spawned (live has her nowhere), so the route does not go down to her old room. +-- Reverts: run 0066 again. + +-- @target: shared + +DELETE FROM {SHARED}.playerbot_dungeon_routes WHERE map_id = 2994; + +INSERT INTO {SHARED}.playerbot_dungeon_routes (map_id, difficulty, seq, position_x, position_y, position_z) VALUES + (2994,0,0,-8796.59,2838.67,28.77), + (2994,0,1,-8796.73,2858.93,21.55), + (2994,0,2,-8797.60,2876.21,19.33), + (2994,0,3,-8801.53,2887.93,19.35), + (2994,0,4,-8823.64,2889.60,15.58), + (2994,0,5,-8836.62,2886.40,15.13), + (2994,0,6,-8852.40,2889.38,14.02), + (2994,0,7,-8873.15,2887.47,14.20), + (2994,0,8,-8889.24,2901.42,15.04), + (2994,0,9,-8886.00,2904.93,14.69), + (2994,0,10,-8885.80,2921.30,14.91), + (2994,0,11,-8885.97,2902.29,14.85), + (2994,0,12,-8873.15,2887.47,14.20), + (2994,0,13,-8853.60,2886.67,14.33), + (2994,0,14,-8836.62,2886.40,15.13), + (2994,0,15,-8823.64,2889.60,15.58), + (2994,0,16,-8802.58,2886.67,19.49), + (2994,0,17,-8780.13,2888.00,17.29), + (2994,0,18,-8762.13,2893.16,14.86), + (2994,0,19,-8761.78,2910.89,10.64), + (2994,0,20,-8764.98,2932.00,6.73), + (2994,0,21,-8783.91,2932.31,6.46), + (2994,0,22,-8802.40,2932.40,6.42), + (2994,0,23,-8807.47,2933.53,7.09), + (2994,0,24,-8807.93,2949.00,7.22), + (2994,0,25,-8797.13,2966.40,6.89), + (2994,0,26,-8808.50,2971.10,6.01), + (2994,0,27,-8825.07,2966.27,7.22), + (2994,0,28,-8847.73,2968.53,7.40), + (2994,0,29,-8858.47,2966.20,7.22), + (2994,0,30,-8875.82,2975.38,6.15), + (2994,0,31,-8901.20,2971.50,5.89), + (2994,0,32,-8875.82,2975.38,6.15), + (2994,0,33,-8858.47,2966.20,7.22), + (2994,0,34,-8837.60,2968.53,7.04), + (2994,0,35,-8825.07,2966.27,7.22), + (2994,0,36,-8811.67,2955.53,6.55), + (2994,0,37,-8807.93,2949.00,7.22), + (2994,0,38,-8806.40,2929.16,6.86), + (2994,0,39,-8802.40,2932.40,6.42), + (2994,0,40,-8780.13,2932.13,6.82), + (2994,0,41,-8762.13,2926.49,6.78), + (2994,0,42,-8764.98,2906.27,12.15), + (2994,0,43,-8764.98,2887.64,15.13), + (2994,0,44,-8763.13,2869.33,14.35), + (2994,0,45,-8771.84,2863.52,13.57), + (2994,0,46,-8773.00,2854.20,13.86); diff --git a/sql/playerbot_v2/README.md b/sql/playerbot_v2/README.md index 7f7c56eb1b..f4ed085c60 100644 --- a/sql/playerbot_v2/README.md +++ b/sql/playerbot_v2/README.md @@ -24,6 +24,7 @@ Applied in ascending numeric order; each file records itself in - `0040_companion_talent_code.sql` — `playerbot_v2_character.companion_talents`: a companion's own talent build, given as a Wowhead Forever talent calculator code (`change talents `), kept across relog and restart - `0041_bot_text_fixes.sql` — (shared DB) removes stock lines that read as nonsense or as a bot: the `suggest_something` line that was only `%zone_name`, and "dont ask me %s, im just a bot" - `0042_bot_text_meta_lines.sql` — (shared DB) removes four "not understood" replies that talk about the chat like a program ("getting confused from chat again", "i will attempt to understand that comment", ...) +- `0060_companion_owner_orders.sql` — `playerbot_v2_character.owner_orders`: a companion's standing "loot all" and "gather on" orders, kept across relog, `.bot call` and restart ## Discipline - Never edit a numbered migration after it ships. Add a new one to amend. diff --git a/src/modules/PlayerbotV2/Addon/ForeverBots/Bindings.xml b/src/modules/PlayerbotV2/Addon/ForeverBots/Bindings.xml index e110529d63..1d036ab806 100644 --- a/src/modules/PlayerbotV2/Addon/ForeverBots/Bindings.xml +++ b/src/modules/PlayerbotV2/Addon/ForeverBots/Bindings.xml @@ -23,4 +23,6 @@ + + diff --git a/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots.lua b/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots.lua index 3961274d6d..181ca7134a 100644 --- a/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots.lua +++ b/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots.lua @@ -212,6 +212,18 @@ for _, c in ipairs(CLASSES) do end local ROLE_LABEL = { tank = L["Tank"], healer = L["Heal"], dps = L["DPS"] } +-- The specs of each class for the bot menu's Spec list: { spec id the bot's setspec takes, name }. +local MENU_SPECS = { + WARRIOR = { { 71, "Arms" }, { 72, "Fury" }, { 73, "Protection" } }, + PALADIN = { { 65, "Holy" }, { 66, "Protection" }, { 70, "Retribution" } }, + HUNTER = { { 253, "Beast Mastery" }, { 254, "Marksmanship" }, { 255, "Survival" } }, + ROGUE = { { 259, "Assassination" }, { 260, "Combat" }, { 261, "Subtlety" } }, + PRIEST = { { 256, "Discipline" }, { 257, "Holy" }, { 258, "Shadow" } }, + SHAMAN = { { 262, "Elemental" }, { 263, "Enhancement" }, { 264, "Restoration" } }, + MAGE = { { 62, "Arcane" }, { 63, "Fire" }, { 64, "Frost" } }, + WARLOCK = { { 265, "Affliction" }, { 266, "Demonology" }, { 267, "Destruction" } }, + DRUID = { { 102, "Balance" }, { 103, "Feral" }, { 104, "Feral (bear)" }, { 105, "Restoration" } }, +} -- What the add-on was doing when the client blocked a call: set before the steps that touch the client's own frames. local currentStep = "" @@ -938,15 +950,22 @@ do end end --- Lazy lock (warlock): one key, the server picks the next spell (dots, curse, Shadow Bolt, cooldowns) and casts it on your target. +-- Lazy key (every class): one key, the server picks the next spell of your class and role (the warlock's dots and Shadow Bolt, a +-- warrior's Revenge and Sunder in Defensive Stance, a priest's heal on the most hurt group member...) and casts it. -- The client will not let an add-on choose spells in a fight, so the key clicks a secure button that runs the server command --- ".playerbot lazy" as the player's own line, in combat too. Press it again for every cast. +-- ".playerbot lazy" as the player's own line, in combat too. Press it again for every cast. The heal and tank keys play that role +-- whatever your spec is (a feral druid tanking, a shadow priest healing a pull). do - local b = CreateFrame("Button", "ForeverBotsKeyLazy", UIParent, "SecureActionButtonTemplate") - b:RegisterForClicks("AnyUp", "AnyDown") - b:SetAttribute("type", "macro") - b:SetAttribute("macrotext", ".playerbot lazy") - _G["BINDING_NAME_CLICK ForeverBotsKeyLazy:LeftButton"] = L["Lazy lock (warlock: next spell on your target)"] + local function LazyKey(name, macrotext, label) + local b = CreateFrame("Button", name, UIParent, "SecureActionButtonTemplate") + b:RegisterForClicks("AnyUp", "AnyDown") + b:SetAttribute("type", "macro") + b:SetAttribute("macrotext", macrotext) + _G["BINDING_NAME_CLICK " .. name .. ":LeftButton"] = label + end + LazyKey("ForeverBotsKeyLazy", ".playerbot lazy", L["Lazy key (any class: next spell of your spec)"]) + LazyKey("ForeverBotsKeyLazyHeal", ".playerbot lazy heal", L["Lazy key: heal (most hurt group member)"]) + LazyKey("ForeverBotsKeyLazyTank", ".playerbot lazy tank", L["Lazy key: tank (threat on your target)"]) end -- Duplicate macros: a key bound to a macro ("bind ALT-E MACRO Corruption" in bindings-cache.wtf) runs the first macro of that @@ -1699,6 +1718,7 @@ function UI.BuildBots() GameTooltip:SetOwner(self, "ANCHOR_RIGHT") GameTooltip:SetText(L["Gear: %s"]:format(GEAR_NAME[ForeverBotsDB.gear or "match"] or "?")) GameTooltip:AddLine(L["The gear the next bots wear. Click to go to the next choice: Match, Best, BiS, T1, T2, T3."], 1, 1, 1, true) + GameTooltip:AddLine(L["BiS and T1 to T3 start at level 60. Below that the bots wear gear for their level, as with Match."], 1, 0.82, 0, true) GameTooltip:Show() end) gearBtn:SetScript("OnLeave", function() GameTooltip:Hide() end) @@ -1946,7 +1966,10 @@ local function BuildFrame() frame:SetSize(LAYOUT.W, LAYOUT.TOP + LAYOUT.PANE_H + LAYOUT.FOOTER) frame:SetScale(WindowScale()) frame:SetPoint("CENTER") - frame:SetFrameStrata("DIALOG") + -- the same layer as the bags and the game's own windows, and raised on a click: an opened bag can sit over it (row 352, the + -- DIALOG layer kept it on top of every bag) + frame:SetFrameStrata("MEDIUM") + frame:SetToplevel(true) frame:SetMovable(true) frame:SetClampedToScreen(true) frame:EnableMouse(true) @@ -2755,6 +2778,16 @@ local function AddBotMenu(root, unit, who) end end + -- Spec: every spec of the class ("setspec ": the spec, its role and its talents). Role "Damage" keeps the damage spec + -- the bot plays, so a shaman stayed Enhancement with no menu way to Elemental (row 286). + local specs = MENU_SPECS[token] + if specs then + local specMenu = menu:CreateButton(L["Spec"]) + for _, s in ipairs(specs) do + specMenu:CreateButton(L[s[2]], function() Send("setspec " .. s[1]) end) + end + end + -- Raid icons: the bot follows the icon you put on a mob (the server's "assign [kill|cc|tank]"). -- One list, a title per job: a submenu per job made this menu four levels deep, and where the screen has no room on the -- right the client opens each level on the other side, so the fourth level lay over the bot menu and the third over the diff --git a/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots_Spec.lua b/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots_Spec.lua index ddaec834fd..dae73bfe2b 100644 --- a/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots_Spec.lua +++ b/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots_Spec.lua @@ -1,7 +1,8 @@ --[[ ForeverBots_Spec: the Spec page of the bot manager. The picked bot's spec and role, buttons to give it another role (its -talents follow the role) or to hand the role back to its talents, and Re-pick talents (the starter build of its spec). -The bot's own orders setrole and talents apply, sent hidden. +talents follow the role) or to hand the role back to its talents, a button per spec of its class (Elemental or Enhancement +for a damage shaman, Fire or Frost for a mage), and Re-pick talents (the starter build of its spec). +The bot's own orders setrole, setspec and talents apply, sent hidden. ]] local ADDON, ns = ... @@ -25,6 +26,13 @@ local CLASS_ROLES = { WARRIOR = { "tank", "dps" }, PALADIN = { "tank", "healer", "dps" }, SHAMAN = { "healer", "dps" }, HUNTER = { "dps" }, ROGUE = { "dps" }, PRIEST = { "healer", "dps" }, MAGE = { "dps" }, WARLOCK = { "dps" }, DRUID = { "tank", "healer", "dps" }, } +-- The specs of each class, in talent tab order: "setspec " plays that spec and re-learns its talents. "Damage" alone keeps +-- the damage spec the bot plays, Enhancement for a new shaman; Elemental was only a whisper away (row 286). +local CLASS_SPECS = { + WARRIOR = { 71, 72, 73 }, PALADIN = { 65, 66, 70 }, HUNTER = { 253, 254, 255 }, ROGUE = { 259, 260, 261 }, + PRIEST = { 256, 257, 258 }, SHAMAN = { 262, 263, 264 }, MAGE = { 62, 63, 64 }, WARLOCK = { 265, 266, 267 }, + DRUID = { 102, 103, 104, 105 }, +} local ROLE_LABEL = { tank = L["Tank"], healer = L["Healer"], dps = L["Damage"] } local ROLE_TOKEN = { TANK = "tank", HEALER = "healer", DPS = "dps" } @@ -66,6 +74,19 @@ local function Refresh(bot) b:Hide() end end + local specs = bot and CLASS_SPECS[bot.class] or {} + for i, b in ipairs(pane.specButtons) do + local s = specs[i] + b.spec = s + if s then + b:SetText(SPEC_NAME[s] or tostring(s)) + b:SetEnabled(bot.online and true or false) + if bot.specId == s then b:LockHighlight() else b:UnlockHighlight() end + b:Show() + else + b:Hide() + end + end local online = bot and bot.online or false pane.auto:SetEnabled(online) pane.talents:SetEnabled(online) @@ -97,6 +118,17 @@ local function Build(p) p.talents:SetPoint("TOPLEFT", p, "TOPLEFT", 118, -134) p.talents:SetScript("OnClick", function() Order("talents", "apply") end) W.Tip(p.talents, L["Re-pick talents"], L["The bot takes the starter talent build of its spec again (not in combat)."]) + local shead = p:CreateFontString(nil, "OVERLAY", "GameFontNormal") + shead:SetPoint("TOPLEFT", 0, -170) + shead:SetText(L["Pick a spec"]) + p.specButtons = {} + for i = 1, 4 do + local b = W.MakeButton(p, "", 68) + b:SetPoint("TOPLEFT", p, "TOPLEFT", (i - 1) * 72, -188) + b:SetScript("OnClick", function(self) if self.spec then Order("setspec", self.spec) end end) + W.Tip(b, L["Pick a spec"], L["The bot plays this spec from now on (its role follows) and re-learns its talents for it. Kept across relog and Call."]) + p.specButtons[i] = b + end end W.AddTab({ diff --git a/src/modules/PlayerbotV2/Addon/ForeverBots/Locale_ruRU.lua b/src/modules/PlayerbotV2/Addon/ForeverBots/Locale_ruRU.lua index 215e4abdad..6d35d7282b 100644 --- a/src/modules/PlayerbotV2/Addon/ForeverBots/Locale_ruRU.lua +++ b/src/modules/PlayerbotV2/Addon/ForeverBots/Locale_ruRU.lua @@ -109,6 +109,7 @@ ForeverBotsLocale = { ["Match"] = "Как у меня", ["Best"] = "Лучшее", ["The gear the next bots wear. Click to go to the next choice: Match, Best, BiS, T1, T2, T3."] = "Экипировка следующих ботов. Щелкните для следующего варианта: Как у меня, Лучшее, BiS, T1, T2, T3.", + ["BiS and T1 to T3 start at level 60. Below that the bots wear gear for their level, as with Match."] = "BiS и T1-T3 действуют с 60-го уровня. До него боты носят экипировку по своему уровню, как при «Как у меня».", ["Your saved bots"] = "Сохраненные боты", ["Save group"] = "Сохранить группу", ["Puts every bot with you on your saved list."] = "Добавляет всех ваших текущих ботов в список сохраненных.", @@ -199,7 +200,9 @@ ForeverBotsLocale = { ["raid ready: calling your saved bots..."] = "проверка готовности: призыв сохраненных ботов...", ["Show / hide the bot window"] = "Показать / скрыть окно ботов", ["Show / hide the bot window (works in combat)"] = "Показать / скрыть окно ботов (работает в бою)", - ["Lazy lock (warlock: next spell on your target)"] = "Автокаст чернокнижника (следующее заклинание по вашей цели)", + ["Lazy key (any class: next spell of your spec)"] = "Автокаст (любой класс: следующее заклинание вашей специализации)", + ["Lazy key: heal (most hurt group member)"] = "Автокаст: лечение (самый раненый член группы)", + ["Lazy key: tank (threat on your target)"] = "Автокаст: танк (угроза на вашей цели)", ["removed %d duplicate macro(s) (same name and text as another), so macro keys stay on the same macro."] = "удалено повторяющихся макросов: %d (то же имя и текст, что у другого), чтобы клавиши макросов не сбивались.", ["two macros are named %s but differ; a key bound to that name uses the first. Rename or delete one in /macro."] = "два макроса называются %s, но различаются; клавиша с этим именем запускает первый. Переименуйте или удалите один в /macro.", ["Call saved bots"] = "Призвать сохраненных", @@ -596,4 +599,6 @@ ForeverBotsLocale = { ["Tank leads"] = "Танк ведет группу", -- check ["In a dungeon or a raid your tank bot leads: it walks on, pulls pack by pack, waits for mana and for you, and goes boss to boss. You follow. In a raid it stops before each boss: pull it yourself, or say go.\nClick: on or off. Right-click: pause (it holds where it stands) or go on.\nGreen: on. Blue: paused. It ends when you leave the dungeon or raid. Follow, Stay and Come pause it: say go (or right-click) and it leads on."] = "В подземелье или рейде группу ведет ваш бот-танк: идет вперед, пулит по одной группе мобов, ждет ману и вас и идет от босса к боссу. Вы следуете за ним. В рейде он останавливается перед каждым боссом: пульте его сами или скажите go.\nЩелчок: вкл. или выкл. Правый щелчок: пауза (стоит на месте) или дальше.\nЗеленый: вкл. Синий: пауза. Заканчивается, когда вы выходите из подземелья или рейда. «За мной», «Стоять» и «Ко мне» ставят ведение на паузу: скажите go (или правый щелчок), и танк ведет дальше.", -- check ["the tank does not lead now: click the button first."] = "танк сейчас не ведет: сначала нажмите кнопку.", + ["Pick a spec"] = "Выбрать специализацию", -- check + ["The bot plays this spec from now on (its role follows) and re-learns its talents for it. Kept across relog and Call."] = "Бот играет в этой специализации (роль меняется вместе с ней) и заново учит таланты для нее. Сохраняется после перезахода и вызова.", -- check } diff --git a/src/modules/PlayerbotV2/Addon/ForeverBots/README.md b/src/modules/PlayerbotV2/Addon/ForeverBots/README.md index 72c12d262e..2927478e6b 100644 --- a/src/modules/PlayerbotV2/Addon/ForeverBots/README.md +++ b/src/modules/PlayerbotV2/Addon/ForeverBots/README.md @@ -149,6 +149,8 @@ Timings (0.5.18): every handler the add-on gives the client is timed. A call ove Key bindings (0.2.2): Esc > Options > Key Bindings > AddOns > "WoW Forever Bots". Unbound by default; one entry each for Attack, Pull, Pull back, Follow, Stay, Resume, Stop attacking, Flee, Come, Fall back, Toggle stance (Next stance since the stance button got three steps), Show / hide the bot window, and one key each for the stances Passive, Defensive and Aggressive and for Ignore my target and Clear ignored mobs. The order keys send the same line as the window buttons and work in combat. Lazy lock key (0.2.4, warlocks): one key that does the right next thing on your target. Each press casts one spell at an enemy, never a pet summon: the curse (Curse of Tongues on mana users, Curse of Agony on the rest), Corruption, Immolate and Siphon Life kept up, Conflagrate, Shadow Bolt as the filler (the free instant bolt on a Shadow Trance proc), Life Tap when mana runs low, Death Coil / Drain Life when your health is low. An enemy hitting you in melee gets Death Coil, then Howl of Terror when two or more are on you, then Fear (not on bosses, and not on mobs in dungeons and raids). Both on-use trinkets and your racial go whenever ready on a long fight, in the same press as the next spell. The wand takes over when mana is dry. Press it with no enemy selected to put Demon Armor up and summon your pet. It also sends your pet at the target. Bind it under "Lazy lock" and tap or mash it; it runs the server command `.playerbot lazy`, which you can also type. + +Lazy key for every class: the same key now plays every class, on the role of your spec. Damage: procs and executes first (Overpower, Execute, Hammer of Wrath, Riposte, Mongoose Bite), cooldowns on bosses and players (Arcane Power, Combustion, Rapid Fire, Adrenaline Rush, Elemental Mastery), dots kept up (Rend, Serpent Sting, Shadow Word: Pain, Flame Shock, Moonfire, Rake, Rip), combo points spent at five (Slice and Dice, Eviscerate, Ferocious Bite), then the filler (Sinister Strike, Frostbolt, Lightning Bolt, Wrath, Smite, Mind Flay; Heroic Strike / Maul with rage to spare), the wand when the mana is gone. Tank: Defensive Stance or Bear Form first, Taunt / Growl when your target hits someone else, then Shield Block, Revenge, Shield Slam, Thunder Clap on two or more, Demoralizing Shout / Roar and Sunder Armor / Maul; a paladin keeps Righteous Fury, Holy Shield and Consecration up. Heal: the most hurt group member in 40 yards (you included) gets the heal that fits: a shield, Holy Shock, Swiftmend or Nature's Swiftness when it is close to death, Prayer of Healing / Chain Heal when three are hurt, the HoT (Renew, Rejuvenation), then the main heal; a druid leaves its form to heal. With nobody hurt the key fights. Interrupts (Pummel / Shield Bash, Kick, Counterspell, Earth Shock, Silence, Bash) go on any cast. Out of combat with nothing selected it keeps your buffs up (Battle Shout, blessing and aura, aspect, Fortitude and Inner Fire, Lightning Shield and the weapon imbue, Arcane Intellect and armor, Mark of the Wild and Thorns). Melee classes start their swing and the pet joins the fight. Two more keys play a role whatever your spec: "Lazy key: heal" (`.playerbot lazy heal`) and "Lazy key: tank" (`.playerbot lazy tank`); `.playerbot lazy dps` is the damage rotation. The warlock keeps its own rotation above. Attack (mouseover) key: hover a mob and press it; the mob becomes your target and the bots attack it. Group pings (the ping wheel, if your client has one): an Attack ping on an enemy sends the bots in, an On my way ping on the ground sends them there. Needs a server with the ping hooks. ## 0.5.1 window diff --git a/src/modules/PlayerbotV2/Api/BotSwim.h b/src/modules/PlayerbotV2/Api/BotSwim.h index 123a51e491..d2bc23af9d 100644 --- a/src/modules/PlayerbotV2/Api/BotSwim.h +++ b/src/modules/PlayerbotV2/Api/BotSwim.h @@ -89,4 +89,49 @@ inline bool SettleKeepsFollowRange(float dx, float dy, float dz, float follow_ra return limit > 0.0f && dx * dx + dy * dy + dz * dz < limit * limit; } +// A goal under the water: well under the swim z. The navmesh holds deep water as polygons on its surface only, so the polygon nearest +// such a goal is the surface right over it, not ground a stride off. The far-end snap put a rogue's melee spot by a murloc on the +// Vile Reef floor 57 y up on the surface (vile_reef_fight af60), and the rogue swam up and down at the surface for the whole fight. +inline bool IsUnderwaterGoal(float goal_z, float swim_z) +{ + return goal_z < swim_z - kDiveMargin; +} + +// One straight swim (no route through the water): across no more than a pool or a flooded hall, longer trips are the router's; down +// or up as deep as the water goes there. The 40 y cap on the whole leg kept a bot on the surface 57 y over the fight it was ordered to. +constexpr float kMaxSwimLegAcross = 40.0f; +constexpr float kMaxSwimLegLength = 90.0f; +inline bool SwimLegFits(float dxy, float len) +{ + return len >= 1.0f && dxy <= kMaxSwimLegAcross && len <= kMaxSwimLegLength; +} + +// A bot under the water by what it is down there for (its fight, or the player who leads its group, himself under the water) stays at +// that depth: the settle lifted a rogue that catch-up had set beside his leader on the reef floor straight back to the surface, 59 y +// up (vile_reef_fight af60). Its breath is BreathGoesUp's. +constexpr float kHoldDepthYards = 12.0f; +inline bool HoldsDepth(float bot_z, float swim_z, float anchor_dist, float anchor_z) +{ + return bot_z < swim_z && anchor_dist <= kHoldDepthYards && IsUnderwaterGoal(anchor_z, swim_z); +} + +// Breath, from the server's own timer (Player::HandleDrowning: it runs down while the head is under water, comes back ten times as fast +// above it, and stops, -1, once full or for a bot that cannot drown: water breathing, undead's longer breath counted in). A player under +// water keeps fighting or swimming and goes up when the bar runs short, then stays up until it is full before he dives again. The bot's +// own 35 s clock counted only the time out of combat: a mage fought on the Vile Reef, sat down to eat at 25 y deep once the fight ended, +// and drowned before the clock got to 35 s (vile_reef_fight af64). Up with 25 s left: from the reef 60 y down that is 13 s of swimming. +// `refilling` is the bot's latch across ticks: true from the moment it goes up until the timer stops. +constexpr int BreathUpAtLeftMs = 25000; +inline bool BreathGoesUp(int breath_left_ms, bool& refilling) +{ + if (breath_left_ms < 0) + { + refilling = false; + return false; + } + if (breath_left_ms <= BreathUpAtLeftMs) + refilling = true; + return refilling; +} + } // namespace Playerbot::BotMovement::Swim diff --git a/src/modules/PlayerbotV2/Api/PlayerbotAPI.cpp b/src/modules/PlayerbotV2/Api/PlayerbotAPI.cpp index 441b62faa6..98600772b9 100644 --- a/src/modules/PlayerbotV2/Api/PlayerbotAPI.cpp +++ b/src/modules/PlayerbotV2/Api/PlayerbotAPI.cpp @@ -13,6 +13,7 @@ #include "PlayerbotAPI.h" #include "BotLanguage.h" #include "Bot/QuestLoot.h" +#include "Bot/Quest/CompanionQuest.h" #include "Bot/BotBridge.h" #include "ClassicBotSkills.h" #include "Travel/ReachMemory.h" @@ -1836,7 +1837,11 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, float const sx = p_->GetPositionX(), sy = p_->GetPositionY(), sz = p_->GetPositionZ(); float const dxy = std::sqrt((x - sx) * (x - sx) + (y - sy) * (y - sy)); float const fall = sz - z; - if (dxy > 40.0f || fall < 4.0f || fall > 40.0f || p_->IsFlying() || p_->IsInFlight() || p_->GetVehicle() || p_->IsInWater()) + // 220 y down, 45 y out: The Shaper's Terrace's landing ledge stands 54 y over the pool players jump into, 35-41 y out from + // where a bot on the ledge leaves it (live capture 25 Nov 2026); in Blackmaw Hold the way to Varrox is a 200 y fall from the + // Behemoth's hall into a pool, 35 y out (live capture 26 Nov 2026). At these sizes the jump below stays under MoveJump's + // 50 y/s, so it lands when flight_ms says. + if (dxy > 45.0f || fall < 4.0f || fall > 220.0f || p_->IsFlying() || p_->IsInFlight() || p_->GetVehicle() || p_->IsInWater()) return Result::Locked; // A free fall: the jump spline's parabola (height = g*T^2/8, MotionMaster::MoveJump) is exactly gravity over the drop // when T = sqrt(2*fall/g), so the leap takes that long. A fixed 8 y/s along the whole path took 3 s for a 15 y drop and @@ -1858,6 +1863,10 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, { if (!dp->IsInWorld() || !dp->IsAlive()) return; + // A fall into water does no harm: the client ends it swimming and sends no fall landing (live, The Shaper's Terrace + // 25 Nov 2026: a 54 y jump into the pool, START_SWIM, no environmental damage). + if (dp->GetMap() && dp->GetMap()->IsInWater(dp->GetPhaseShift(), dx, dy, dz)) + return; dp->m_movementInfo.pos.Relocate(dx, dy, dz); dp->HandleFall(); }, Milliseconds(flight_ms)); @@ -2645,7 +2654,11 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // one, so the goal was picked again and again (Burning Steppes, Simer: 53 path_fail Magma for one quest goal in 3 minutes). // Left unsnapped, the goal ends as FarFromPolyEnd, which suppresses it for long and lets goal selection move on. bool const end_in_hazard = BotMovement::ClassifyDestinationLiquid(p_, ae.x, ae.y, ae.z) == BotMovement::LiquidVerdict::Hazard; - if (off_end <= 12.0f && std::fabs(dz_end) < max_dz && !snaps_under && !end_in_hazard && !::Playerbot::V2::Fleet::PathHasCliff(path.GetPath()) + // Nor is the water's surface over a goal under the water (BotMovement::Swim::IsUnderwaterGoal): it is swum to (TrySwimLeg below). + float goal_swim_z = 0.f; + bool const underwater_goal = BotMovement::SwimLevel(p_, x, y, z, goal_swim_z) && BotMovement::Swim::IsUnderwaterGoal(z, goal_swim_z); + if (off_end <= 12.0f && std::fabs(dz_end) < max_dz && !snaps_under && !end_in_hazard && !underwater_goal && + !::Playerbot::V2::Fleet::PathHasCliff(path.GetPath()) && !rise_onto_model(ae.x, ae.y, ae.z)) { if (SehSafeCalculatePath(path, ae.x, ae.y, ae.z) && !(path.GetPathType() & (PATHFIND_NOPATH | PATHFIND_FARFROMPOLY_END))) @@ -3636,13 +3649,13 @@ bool API::TrySwimLeg(float x, float y, float z, bool run) if (BotMovement::g_LiquidPathPolicy && BotMovement::g_LiquidPathPolicy(p_) != BotMovement::LiquidPolicy::None) return false; - // Longer than a pool or a flooded hall: that is a trip for the router, not one straight swim. - constexpr float kMaxLeg = 40.0f; + // Across more than a pool or a flooded hall: that is a trip for the router, not one straight swim. A dive goes as deep as the water + // (BotMovement::Swim::SwimLegFits). constexpr float kSampleStep = 2.0f; float const sx = p_->GetPositionX(), sy = p_->GetPositionY(), sz = p_->GetPositionZ(); float const dx = x - sx, dy = y - sy, dz = z - sz; float const len = std::sqrt(dx * dx + dy * dy + dz * dz); - if (len < 1.0f || len > kMaxLeg) + if (!BotMovement::Swim::SwimLegFits(std::sqrt(dx * dx + dy * dy), len)) return false; // In water at a point: water or ocean only (magma and slime are never swum), below the surface or on it. A bot that crossed the @@ -4094,7 +4107,13 @@ Result API::start_attack(ObjectGuid target, uint8 avoid_school_mask) // A hunter engaged from range stands at its shooting spot (chase to 28 y). When the mob then comes inside Auto Shot's dead zone the // fight turns to melee, but this path never chased again: the hunter stood a few yards off, unable to shoot or swing (Isane, 2026-10-20). // Close in once it stands still; a hunter already walking keeps its chase. - if (p_->GetClass() == CLASS_HUNTER && hunter_dead_zone && melee_swing && p_->movespline->Finalized() && !p_->IsWithinMeleeRange(tu)) + // Not for a grouped hunter with shots whose mob someone else holds: that hunter steps back out of the dead zone (the classic hunter + // rotation's dead-zone step), and closing in here walked it back in front of the mob each time (alcaz_full af70c: Blazeroar's Flame + // Breath). A hunter with nothing to shoot still closes in. + bool const held_by_other = p_->GetGroup() && tu->GetVictim() && tu->GetVictim() != p_ && + p_->GetWeaponForAttack(RANGED_ATTACK, true) != nullptr && (!p_->NeedsAmmo() || (p_->GetAmmoId() != 0 && p_->HasItemCount(p_->GetAmmoId()))); + if (p_->GetClass() == CLASS_HUNTER && hunter_dead_zone && melee_swing && !held_by_other && p_->movespline->Finalized() && + !p_->IsWithinMeleeRange(tu)) { p_->GetMotionMaster()->MoveChase(tu); logHunterChase("dead_zone_close_in"); } // The opening engage chases once; another layer's move (formation slot, follow) replaces that chase and this path never issued it // again, so a hunter ordered at a mob beyond its shooting range stood in the aim pose for good (PC 20 Oct, whelp ~30+ y away). @@ -4266,7 +4285,9 @@ Result API::stop_attack(bool clear_ghost_combat) // Attack off ends Auto Shot as well (a player's attack toggle does); left running it keeps the hunter in the aim pose with no target. if (p_->GetClass() == CLASS_HUNTER) p_->InterruptSpell(CURRENT_AUTOREPEAT_SPELL, false); - if (!p_->IsInCombat()) + // A station show's sheath hold keeps the tool out — an OOC stop_attack is no + // reason to stow it mid-visit (the hold itself drops the moment combat starts). + if (!p_->IsInCombat() && !p_->BotSheathHold()) p_->SetSheath(SHEATH_STATE_UNARMED); // Mirror a real client deselecting on disengage — keeps the published // UNIT_FIELD_TARGET truthful for other players' target-of-target frames. @@ -4976,7 +4997,22 @@ Result API::face_target(ObjectGuid target, bool combat) if (!p_) return Result::Other; if (target.IsEmpty()) return Result::InvalidTarget; Unit* u = ObjectAccessor::GetUnit(*p_, target); - if (!u) return Result::InvalidTarget; + if (!u) + { + // A station (anvil, cooking fire, loom): the bot at work faces the gameobject. SetFacingToObject + // takes any WorldObject; the same already-facing guard as the unit path skips a no-op turn. + if (combat) return Result::InvalidTarget; + GameObject* go = p_->GetMap() ? p_->GetMap()->GetGameObject(target) : nullptr; + if (!go) return Result::InvalidTarget; + if (!p_->isMoving()) + { + ClearStaleMoveFlags(p_); + float const off = Position::NormalizeOrientation(p_->GetOrientation() - p_->GetAbsoluteAngle(go)); + if (off > 0.1f && off < 2.0f * float(M_PI) - 0.1f) + p_->SetFacingToObject(go, /*force*/ true); + } + return Result::Ok; + } if (combat) { // Combat re-face. The melee swing needs the victim within +-60 degrees @@ -6077,6 +6113,27 @@ Result API::set_stand_state(uint8 state) return Result::Ok; } +Result API::set_sheath(uint8 sheath, int8_t hold) +{ + if (!p_) return Result::Other; + SheathState const state = sheath > SHEATH_STATE_RANGED ? SHEATH_STATE_UNARMED : static_cast(sheath); + p_->SetSheath(state); + // Drawn bots get auto-resheathed after 3 idle seconds (Player::Update) — a show + // drawing weapons on purpose holds that off until it's resheathed or fights. + // hold < 0 keeps that default; a passing call (skill-up cast) draws without it + // so the resheath timer cleans the pose up itself when the casts stop. + p_->SetBotSheathHold(hold < 0 ? state != SHEATH_STATE_UNARMED : hold != 0); + TC_LOG_INFO("playerbot.v2", "[sheath] {} -> state={} now={}", p_->GetName(), uint32(sheath), uint32(p_->GetSheath())); + return Result::Ok; +} + +Result API::play_sound(uint32 sound_kit) +{ + if (!p_ || !sound_kit) return Result::Other; + p_->PlayDistanceSound(sound_kit); + return Result::Ok; +} + Result API::dismiss_pet() { if (!p_) return Result::Other; @@ -6779,11 +6836,40 @@ Result API::sell_trash(ObjectGuid npc) constexpr uint32 kTightBagThreshold = 3; bool const bags_tight = CountFreeBagSlots(p_) <= kTightBagThreshold; + // Craft surplus: products of recipes the bot knows that aren't also an + // input to a known recipe — the smith hawks his sharpening stones, the + // cook her baked eggs. Bars / bolts / powders that feed a known recipe + // stay as working stock. Conjured outputs (healthstones, mage water) + // vendor for nothing — skip them; gear stays under IsBagRot's rules, and + // uncommon-or-better products are worth more than the vendor pays. + std::unordered_set craft_in; + std::unordered_set craft_out; + for (auto const& [sid, ps] : p_->GetSpellMap()) + { + if (ps.state == PLAYERSPELL_REMOVED || !ps.active || ps.disabled) continue; + SpellInfo const* si = sSpellMgr->GetSpellInfo(sid, DIFFICULTY_NONE); + if (!si) continue; + for (SpellEffectInfo const& eff : si->GetEffects()) + if (eff.Effect == SPELL_EFFECT_CREATE_ITEM && eff.ItemType) + craft_out.insert(uint32(eff.ItemType)); + for (size_t r = 0; r < si->Reagent.size(); ++r) + if (si->Reagent[r] > 0) + craft_in.insert(uint32(si->Reagent[r])); + } + for (uint32 const e : craft_in) craft_out.erase(e); + std::vector to_sell; - p_->ForEachItem(ItemSearchLocation::Inventory, [this, &to_sell, bags_tight](Item* it) + p_->ForEachItem(ItemSearchLocation::Inventory, [this, &to_sell, bags_tight, &craft_out](Item* it) { ItemTemplate const* tmpl = it ? it->GetTemplate() : nullptr; - if (IsBagRot(p_, it, tmpl, bags_tight)) to_sell.push_back(it); + uint32 const cls = tmpl ? tmpl->GetClass() : 0; + if (tmpl && !it->IsNotEmptyBag() && !tmpl->HasFlag(ITEM_FLAG_CONJURED) + && tmpl->GetQuality() < ITEM_QUALITY_UNCOMMON + && cls != ITEM_CLASS_WEAPON && cls != ITEM_CLASS_ARMOR + && craft_out.count(it->GetEntry())) + to_sell.push_back(it); + else if (IsBagRot(p_, it, tmpl, bags_tight)) + to_sell.push_back(it); return ItemSearchCallbackResult::Continue; }); @@ -7114,17 +7200,29 @@ Result API::loot_corpse(ObjectGuid corpse, bool quest_items_only) if (quest_items_only) { ObjectGuid const owner = loot->GetOwnerGUID(); - uint32 taken = 0; + uint32 taken = 0, left = 0; for (uint8 slot = 0; slot < loot->items.size(); ++slot) { - if (!IsPendingQuestLoot(p_, loot, slot)) continue; + if (!IsPendingQuestLoot(p_, loot, slot)) + { + // One for the whole group that a player of the group still needs: left for him (QuestLootIsAPlayers). + LootItem const& li = loot->items[slot]; + if (li.needs_quest && !li.is_looted && li.HasAllowedLooter(p_->GetGUID()) && QuestLootIsAPlayers(p_, loot, li)) + { + ++left; + TC_LOG_INFO("playerbot.v2", "[loot_quest] {} corpse={} leaves item {} for the player (one for the group, he needs it)", + p_->GetName(), corpse.GetCounter(), li.itemid); + } + continue; + } LootItem const& qi = loot->items[slot]; ItemPosCountVec dest; if (p_->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, qi.itemid, qi.count) != EQUIP_ERR_OK) continue; p_->StoreLootItem(owner, slot, loot); ++taken; } - TC_LOG_INFO("playerbot.v2", "[loot_quest] {} corpse={} took {} quest item(s)", p_->GetName(), corpse.GetCounter(), taken); + TC_LOG_INFO("playerbot.v2", "[loot_quest] {} corpse={} took {} quest item(s), left {} for the player", p_->GetName(), corpse.GetCounter(), + taken, left); if (WorldSession* sess = p_->GetSession()) sess->DoLootRelease(loot); return Result::Ok; @@ -7390,6 +7488,26 @@ void TakeGameObjectLoot(Player* p, GameObject* obj, ObjectGuid go_guid) p->SendLootRelease(go_guid); } +// A door whose lock has a Lockpicking case (Pick Lock opens it) and no case a plain click opens. +bool DoorTakesLockpicking(GameObjectTemplate const* info) +{ + LockEntry const* lock = info ? sLockStore.LookupEntry(info->GetLockId()) : nullptr; + if (!lock) + return false; + bool pick = false; + for (uint8 i = 0; i < MAX_LOCK_CASE; ++i) + { + if (lock->Type[i] != LOCK_KEY_SKILL) + continue; + SkillType const skill = SkillByLockType(LockType(lock->Index[i])); + if (skill == SKILL_LOCKPICKING) + pick = true; + else if (skill == SKILL_NONE) + return false; // a hand door (Open, Quick Open): clicked, not picked + } + return pick; +} + // The bot's spell that opens a lock of this kind (Herbalism 2366 for LOCKTYPE_HERBALISM, Mining 2575 for LOCKTYPE_MINING): the // spell a player's right-click on an herb or vein casts. Of several ranks the one with the largest bonus to the lock skill // (Spell::CanOpenLock adds the effect's value to the skill), 0 when the bot knows none. @@ -7687,6 +7805,10 @@ Result API::use_game_object(ObjectGuid go_guid) // found none (Discord 2026-11-09). A bot never opens one of these by a plain click. if (obj->GetGoType() == GAMEOBJECT_TYPE_CHEST && Playerbot::ChestNeedsSkill(obj->GetGOInfo())) return gather_node(obj); + // A shut door whose lock takes Lockpicking (Alcaz Prison's Maximum Security Door 649547): a rogue casts Pick Lock on it, as on a + // locked box. A plain click on such a door does nothing for a player (the client asks for the key). + if (obj->GetGoType() == GAMEOBJECT_TYPE_DOOR && obj->GetGoState() == GO_STATE_READY && DoorTakesLockpicking(obj->GetGOInfo())) + return gather_node(obj); // Mounted-restriction check from HandleGameObjectUseOpcode: most GOs // refuse interaction while mounted unless flagged UsableMounted. if (p_->IsMounted() && !obj->GetGOInfo()->IsUsableMounted()) @@ -7841,7 +7963,9 @@ Result API::gather_node(GameObject* obj) if (lock->Type[i] != LOCK_KEY_SKILL) continue; SkillType const skill = SkillByLockType(LockType(lock->Index[i])); - if (skill != SKILL_HERBALISM && skill != SKILL_MINING) + // A door takes only Pick Lock (use_game_object sends no other door here); a chest, Herb Gathering or Mining. + bool const door = obj->GetGoType() == GAMEOBJECT_TYPE_DOOR; + if (door ? skill != SKILL_LOCKPICKING : (skill != SKILL_HERBALISM && skill != SKILL_MINING)) continue; if (p_->GetSkillValue(skill) == 0 || p_->GetSkillValue(skill) < lock->Skill[i]) continue; @@ -7859,6 +7983,25 @@ Result API::gather_node(GameObject* obj) ClearStaleMoveFlags(p_); if (!p_->HasInArc(static_cast(M_PI), obj)) p_->SetFacingToObject(obj, true); + // The tool the spell asks for in the bags (SpellInfo Totem): Pick Lock (1804) wants Thieves' Tools (5060), which a rogue buys + // from a trade vendor for 15 silver. A bot does not shop. Without it every cast fails SPELL_FAILED_TOTEMS (153): alcaz_full in the + // alcaz-1127-r3 run (27 Nov) cast Pick Lock on the Maximum Security Door all run long, 153 each time, and the grant at levelling + // (BotSetupPipeline LearnLevelKit) never showed on the scenario rogue. So the bot takes it here, where the spell is cast. + if (SpellInfo const* info = sSpellMgr->GetSpellInfo(spell, DIFFICULTY_NONE)) + { + for (int32 const tool : info->Totem) + { + if (tool <= 0 || p_->HasItemCount(uint32(tool), 1, true)) + continue; + ItemPosCountVec dest; + InventoryResult const ir = p_->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, uint32(tool), 1); + if (ir == EQUIP_ERR_OK && p_->StoreNewItem(dest, uint32(tool), true)) + TC_LOG_INFO("playerbot.v2", "[gather] {} takes tool item {} for spell {}", p_->GetName(), tool, spell); + else + TC_LOG_INFO("playerbot.v2", "[gather] {} cannot take tool item {} for spell {}: bag result {}", p_->GetName(), tool, + spell, uint32(ir)); + } + } SpellCastResult const r = p_->CastSpell(obj, spell, false); TC_LOG_INFO("playerbot.v2", "[gather] {} cast {} on entry={} skill {} {}/{} result={}", p_->GetName(), spell, obj->GetEntry(), uint32(skill), uint32(p_->GetSkillValue(skill)), uint32(lock->Skill[i]), uint32(r)); @@ -7932,9 +8075,28 @@ Result API::accept_quest(ObjectGuid quest_giver, uint32 quest_id) TYPEMASK_UNIT | TYPEMASK_GAMEOBJECT | TYPEMASK_ITEM); } if (!object) { log_reject("giver_not_found", QuestRefusal::NoGiver); return Result::InvalidTarget; } - if (quest_giver.IsPlayer()) { log_reject("player_giver_unsupp", QuestRefusal::Other); return Result::Other; } - if (!object->hasQuest(quest_id)) { log_reject("giver_lost_relation", QuestRefusal::NoGiver); return Result::InvalidTarget; } - if (!p_->CanInteractWithQuestGiver(object)) { log_reject("out_of_range", QuestRefusal::OutOfRange); return Result::OutOfRange; } + if (quest_giver.IsPlayer()) + { + // A group mate passes on a quest that an item started (a dropped crest, a note): no creature or object hands it out and the + // one item went to him, so the bot takes it from him like a shared quest (the owner's "accept", row 240). Nothing else + // comes from a player here. + Player* mate = object->ToPlayer(); + if (!mate || mate == p_ || !p_->IsInSameGroupWith(mate)) + { log_reject("player_giver_not_group", QuestRefusal::NoGiver); return Result::InvalidTarget; } + QuestStatus const ms = mate->GetQuestStatus(quest_id); + if ((ms != QUEST_STATUS_INCOMPLETE && ms != QUEST_STATUS_COMPLETE) || !CompanionQuest::QuestStartedByItemOnly(quest_id)) + { log_reject("player_giver_unsupp", QuestRefusal::Other); return Result::Other; } + if (!p_->IsWithinDistInMap(mate, INTERACTION_DISTANCE)) + { log_reject("out_of_range", QuestRefusal::OutOfRange); return Result::OutOfRange; } + // The mate stays the giver, as for a quest he shares (WorldSession::HandleQuestgiverAcceptQuestOpcode passes the sharer): + // AddQuest reads a timed quest's time left from him, and AddQuestAndCheckCompletion runs no giver script for a player. + // Every later use of `object` is null-safe as well; it is never an item here, so no quest item is taken from anyone. + } + else + { + if (!object->hasQuest(quest_id)) { log_reject("giver_lost_relation", QuestRefusal::NoGiver); return Result::InvalidTarget; } + if (!p_->CanInteractWithQuestGiver(object)) { log_reject("out_of_range", QuestRefusal::OutOfRange); return Result::OutOfRange; } + } // Junk-quest accept-gate (R2, defense-in-depth). A quest with ZERO // objectives AND no creature/GO turn-in NPC is structurally unfinishable // and unturnable — accepting it parks the bot forever (current_quest_id=0 @@ -8525,6 +8687,26 @@ Result API::equip_item(uint8 from_bag, uint8 from_slot, uint8 to_slot) return Result::Ok; } +Result API::give_item(uint32 entry, uint16 count) +{ + if (!p_) return Result::Other; + if (!entry || !count) return Result::InvalidTarget; + if (!sObjectMgr->GetItemTemplate(entry)) return Result::InvalidTarget; + ItemPosCountVec dest; + if (p_->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, entry, count) != EQUIP_ERR_OK) + return Result::ServerRefused; + return p_->StoreNewItem(dest, entry, true) ? Result::Ok : Result::ServerRefused; +} + +Result API::learn_spell(uint32 spell_id) +{ + if (!p_) return Result::Other; + if (!spell_id || !sSpellMgr->GetSpellInfo(spell_id, DIFFICULTY_NONE)) return Result::InvalidTarget; + if (p_->HasSpell(spell_id)) return Result::Ok; + p_->LearnSpell(spell_id, /*dependent=*/false); + return p_->HasSpell(spell_id) ? Result::Ok : Result::ServerRefused; +} + Result API::accept_shared_quest() { last_quest_refusal_ = QuestRefusal::None; @@ -11434,6 +11616,10 @@ static uint32 LearnHigherRanksOfKnownSpells(Player* p) { if (!entry || entry->Spell >= 100000 || !seen.insert(entry->Spell).second || p->HasSpell(entry->Spell)) continue; + // A spell no player can learn (all its skill line abilities NeverLearned, e.g. the 1-point Holy Light copy 19981) is no rank + // to teach a bot + if (SpellFamily::IsNeverLearned(entry->Spell)) + continue; SpellInfo const* si = sSpellMgr->GetSpellInfo(entry->Spell, DIFFICULTY_NONE); if (!si || si->IsPassive() || si->SpellLevel == 0 || si->SpellLevel > p->GetLevel() || si->SpellFamilyName != classEntry->SpellClassSet) continue; diff --git a/src/modules/PlayerbotV2/Api/PlayerbotAPI.h b/src/modules/PlayerbotV2/Api/PlayerbotAPI.h index 74eb74d8c6..ba665fc765 100644 --- a/src/modules/PlayerbotV2/Api/PlayerbotAPI.h +++ b/src/modules/PlayerbotV2/Api/PlayerbotAPI.h @@ -558,7 +558,8 @@ public: // SMSG_EMOTE packet visible to nearby players. `target` is optional and // changes the emote's directional cue (wave at someone, etc.). Result perform_emote(uint32 emote_id, ObjectGuid target = ObjectGuid::Empty); - // Face the bot toward `target` (Unit::SetFacingToObject). Used for RP / + // Face the bot toward `target` (Unit::SetFacingToObject; also resolves a gameobject — a bot at a + // craft station faces the anvil). Used for RP / // screenshots / pet-pose alignment. Returns InvalidTarget when the named // object isn't visible from the bot's map. // combat = true: re-face a fight victim (see PlayerbotAPI.cpp): turns only a standing, @@ -689,6 +690,10 @@ public: // raw byte mirrors UnitStandStateType. ServerRefused mid-cast since // sitting cancels the cast; otherwise idempotent. Result set_stand_state(uint8 state); + // Draw or stow the visible weapons (SheathState: 0=UNARMED, 1=MELEE, + // 2=RANGED). The station show draws the tool; combat paths manage it themselves. + Result set_sheath(uint8 sheath, int8_t hold = -1); + Result play_sound(uint32 sound_kit); // Inventory // `target` may be a unit or one of the bot's own items (a poison or @@ -741,6 +746,15 @@ public: // destination can't be unequipped (cursed gear / quest item). Result equip_item(uint8 from_bag, uint8 from_slot, uint8 to_slot); + // Put `count` of an item entry into the bot's bags (the same CanStoreNewItem + + // StoreNewItem the setup pipeline uses — a profession tool granted at its + // station). InvalidTarget = unknown entry; ServerRefused = bags full. + Result give_item(uint32 entry, uint16 count); + + // Teach the bot a spell it doesn't yet know — the starter recipe a craft- + // station visit grants, backfilling bots set up before DoLearnProfessions. + Result learn_spell(uint32 spell_id); + // ---- Group loot -------------------------------------------------- // Cast the bot's vote on a master/group loot roll. `loot_object` is // the loot source guid (creature corpse / GO chest), `loot_list_id` diff --git a/src/modules/PlayerbotV2/Api/PlayerbotMovement.cpp b/src/modules/PlayerbotV2/Api/PlayerbotMovement.cpp index 258d735e30..4a5bc8ed7d 100644 --- a/src/modules/PlayerbotV2/Api/PlayerbotMovement.cpp +++ b/src/modules/PlayerbotV2/Api/PlayerbotMovement.cpp @@ -10,6 +10,7 @@ #include "MMapManager.h" #include "MMapDefines.h" #include "FollowMovementGenerator.h" +#include "Group.h" #include "MotionMaster.h" #include "MoveSplineInit.h" #include "Object.h" @@ -176,6 +177,223 @@ int SehSafeNearestPolyProbe(void const* query, float const* detourPt, return NearestPolyProbeGuarded(query, detourPt, extents, filter, nearestOut); } +// ---- MeshIslandExit ---------------------------------------------------------- + +namespace { +bool RefIn(dtPolyRef const* refs, int n, dtPolyRef r) noexcept +{ + for (int i = 0; i < n; ++i) + if (refs[i] == r) + return true; + return false; +} + +// The polygons linked to `start` (links of any kind, off-mesh connections too), breadth first, at most `cap` of them in `seen`. +// A region that reaches `cap` is no scrap; the search stops there. Plain data only: it runs inside the SEH frame of +// IslandExitGuarded. +int FloodRegion(dtNavMesh const* nav, dtQueryFilter const* filter, dtPolyRef start, dtPolyRef* seen, int cap) noexcept +{ + int n = 0, head = 0; + seen[n++] = start; + while (head < n) + { + dtPolyRef const ref = seen[head++]; + dtMeshTile const* tile = nullptr; + dtPoly const* poly = nullptr; + if (dtStatusFailed(nav->getTileAndPolyByRef(ref, &tile, &poly))) + continue; + for (unsigned int i = poly->firstLink; i != DT_NULL_LINK; i = tile->links[i].next) + { + dtPolyRef const nref = tile->links[i].ref; + if (!nref || RefIn(seen, n, nref)) + continue; + dtMeshTile const* ntile = nullptr; + dtPoly const* npoly = nullptr; + if (dtStatusFailed(nav->getTileAndPolyByRef(nref, &ntile, &npoly)) || !filter->passFilter(nref, ntile, npoly)) + continue; + if (n >= cap) + return n; + seen[n++] = nref; + } + } + return n; +} + +// 1: the bot at `pos` (Detour order) stands on a scrap of mesh, and `exitOut` holds a point 1 y inside the nearest polygon of a +// region of at least kMeshIslandPolys polygons (at most maxYd away on the level, 6 y up or down). 2: on a scrap, no such region +// in reach. 0: not on a scrap. +int IslandExitSearch(void const* queryV, void const* floodV, void const* standV, float const* pos, float maxYd, float* exitOut, + int* islandPolys) noexcept +{ + auto const* q = static_cast(queryV); + auto const* flood = static_cast(floodV); + auto const* stand = static_cast(standV); + dtNavMesh const* nav = q->getAttachedNavMesh(); + if (!nav) + return 0; + float const ext[3] = { 1.5f, 3.0f, 1.5f }; + float snapped[3]; + dtPolyRef start = 0; + if (dtStatusFailed(q->findNearestPoly(pos, ext, flood, &start, snapped)) || !start) + return 0; + dtPolyRef island[kMeshIslandPolys]; + int const n = FloodRegion(nav, flood, start, island, kMeshIslandPolys); + if (n >= kMeshIslandPolys) + return 0; + *islandPolys = n; + constexpr float kClimbYd = 6.0f; + constexpr int kNear = 128; + float const box[3] = { maxYd, kClimbYd, maxYd }; + dtPolyRef nearRefs[kNear]; + int nc = 0; + if (dtStatusFailed(q->queryPolygons(pos, box, stand, nearRefs, &nc, kNear))) + return 2; + constexpr int kRejectCap = kMeshIslandPolys * 4; + dtPolyRef rejected[kRejectCap]; // other scraps met on the way + int nr = 0; + for (int tries = 0; tries < 8; ++tries) // a slope can hold several scraps between him and the floor + { + int best = -1; + float bestD2 = maxYd * maxYd; + float bp[3] = { 0.f, 0.f, 0.f }; + for (int i = 0; i < nc; ++i) + { + if (RefIn(island, n, nearRefs[i]) || RefIn(rejected, nr, nearRefs[i])) + continue; + float cp[3]; + if (dtStatusFailed(q->closestPointOnPoly(nearRefs[i], pos, cp, nullptr))) + continue; + if (std::fabs(cp[1] - pos[1]) > kClimbYd) + continue; + float const d2 = (cp[0] - pos[0]) * (cp[0] - pos[0]) + (cp[2] - pos[2]) * (cp[2] - pos[2]); + if (d2 < bestD2) + { + bestD2 = d2; + best = i; + dtVcopy(bp, cp); + } + } + if (best < 0) + return 2; + dtPolyRef region[kMeshIslandPolys]; + int const rn = FloodRegion(nav, flood, nearRefs[best], region, kMeshIslandPolys); + if (rn >= kMeshIslandPolys) + { + // That region's polygon is under his feet as well (two layers of mesh within a yard): he stands on the floor, and the + // scrap is only the polygon Detour picked first. rol_full af63 (23 Nov): "walks 0.0 y off it" at (1525.9,167.3,64.2). + if (bestD2 < 0.5f * 0.5f && std::fabs(bp[1] - pos[1]) < 1.5f) + return 0; + // 1 y past the edge into that polygon, so the bot ends standing on it and not on the seam it shares with the scrap. + float const d = std::sqrt(bestD2); + float in[3] = { bp[0], bp[1], bp[2] }; + if (d > 0.01f) + { + in[0] += (bp[0] - pos[0]) / d; + in[2] += (bp[2] - pos[2]) / d; + } + if (dtStatusFailed(q->closestPointOnPoly(nearRefs[best], in, exitOut, nullptr))) + dtVcopy(exitOut, bp); + return 1; + } + for (int j = 0; j < rn && nr < kRejectCap; ++j) + rejected[nr++] = region[j]; + } + return 2; +} + +#ifdef _MSC_VER +int IslandExitGuarded(void const* query, void const* flood, void const* stand, float const* pos, float maxYd, float* exitOut, + int* islandPolys) noexcept +{ + __try + { + return IslandExitSearch(query, flood, stand, pos, maxYd, exitOut, islandPolys); + } + __except (GetExceptionCode() == EXCEPTION_ASSERTION_FAILURE + ? EXCEPTION_CONTINUE_SEARCH : EXCEPTION_EXECUTE_HANDLER) + { + return -1; + } +} +#else +int IslandExitGuarded(void const* query, void const* flood, void const* stand, float const* pos, float maxYd, float* exitOut, + int* islandPolys) noexcept +{ + return IslandExitSearch(query, flood, stand, pos, maxYd, exitOut, islandPolys); +} +#endif +} // namespace + +bool MeshIslandExit(Player* p, float maxYd, Position& out, int* islandPolys) +{ + if (!p || !p->IsInWorld() || !p->IsAlive() || p->GetTransport() || p->GetVehicle() || p->IsFlying() || p->IsInWater()) + return false; + Map* m = p->GetMap(); + if (!m) + return false; + float const x = p->GetPositionX(), y = p->GetPositionY(), z = p->GetPositionZ(); + if (!EnsureGridForQuery(m, x, y)) + return false; + uint32 const terrainMapId = PhasingHandler::GetTerrainMapId(p->GetPhaseShift(), p->GetMapId(), m->GetTerrain(), x, y); + dtNavMeshQuery const* query = MMAP::MMapManager::instance()->GetNavMeshQuery(terrainMapId, p->GetMapId(), p->GetInstanceId()); + if (!query) + return false; + // Linked is linked, whatever the ground: a patch of floor beside a pool is no scrap. The step itself ends on dry footing. + dtQueryFilter flood; + flood.setIncludeFlags(0xFFFF); + flood.setExcludeFlags(0); + dtQueryFilter stand; + stand.setIncludeFlags(NAV_GROUND | NAV_GROUND_STEEP | NAV_ROAD); + stand.setExcludeFlags(0); + float const pos[3] = { y, z, x }; + float exitPt[3] = { 0.f, 0.f, 0.f }; + int polys = 0; + int found = 0; + { + ReadLockIfOwnQueries const lock; + found = IslandExitGuarded(query, &flood, &stand, pos, maxYd, exitPt, &polys); + } + if (found <= 0) + return false; + float const ex = found == 1 ? exitPt[2] : x, ey = found == 1 ? exitPt[0] : y, ez = found == 1 ? exitPt[1] : z; + // Why a scrap was found and no step taken, once per bot per 10 s: the step is the data to look at. + auto refused = [&](char const* why) + { + static std::mutex s_mu; + static std::unordered_map s_at; + uint32 const now = GameTime::GetGameTimeMS(); + std::lock_guard lk(s_mu); + uint32& at = s_at[p->GetGUID().GetCounter()]; + if (at != 0 && now - at < 10000u) + return false; + at = now ? now : 1u; + TC_LOG_INFO("playerbot.v2", "[mesh_scrap] {} on a scrap of navmesh ({} polygons) at ({:.1f},{:.1f},{:.1f}) map {}: no step to ({:.1f},{:.1f},{:.1f}): {}", + p->GetName(), polys, x, y, z, p->GetMapId(), ex, ey, ez, why); + return false; + }; + if (found != 1) + return refused("no larger region within reach"); + // He walks it: nothing in the way, and ground under every yard of it with no step over 2.5 y (no ledge, no hole). + if (!LineIsClear(p, x, y, z + 1.5f, ex, ey, ez + 1.5f)) + return refused("the line is blocked"); + int const steps = std::max(1, int(std::ceil(std::hypot(ex - x, ey - y)))); + float prev = z; + for (int i = 1; i <= steps; ++i) + { + float const t = float(i) / float(steps); + float g = 0.f; + if (!ProbeGround(p, x + (ex - x) * t, y + (ey - y) * t, z + (ez - z) * t, g)) + return refused("no ground under the step"); + if (std::fabs(g - prev) > 2.5f) + return refused("a ledge in the step"); + prev = g; + } + out.Relocate(ex, ey, ez); + if (islandPolys) + *islandPolys = polys; + return true; +} + // ---- SnapToGround ----------------------------------------------------------- bool SnapToGround(Player* p, float x, float y, float& z) @@ -190,8 +408,10 @@ bool SnapToGround(Player* p, float x, float y, float& z) // Pre-load the destination grid. UpdateAllowedPositionZ samples vmap // through the local grid; if the grid hasn't streamed in yet the // sampler returns INVALID_HEIGHT and we'd silently keep the bad Z. - // LoadGrid is a no-op when the grid is already resident. - m->LoadGrid(x, y); + // LoadGrid is a no-op when the grid is already resident. From a bot logic thread or a same-map split build the load goes to + // the world thread (EnsureGridForQuery): loading a grid there adds creatures and tiles while the map threads read them. + if (!EnsureGridForQuery(m, x, y)) + return false; float const original = z; @@ -319,7 +539,8 @@ float GroundZ(Player* p, float x, float y, float zHint, char const* where, bool* constexpr float kGroundProbeUp = 3.0f; constexpr float kGroundProbeDown = 40.0f; - m->LoadGrid(x, y); + if (!EnsureGridForQuery(m, x, y)) // the world thread loads it (see SnapToGround) + return zHint; float g = INVALID_HEIGHT; try { @@ -362,7 +583,8 @@ bool ProbeGround(Player* p, float x, float y, float zHint, float& out) return false; constexpr float kProbeUp = 3.0f; constexpr float kProbeDown = 40.0f; - m->LoadGrid(x, y); + if (!EnsureGridForQuery(m, x, y)) // the world thread loads it (see SnapToGround) + return false; float g = INVALID_HEIGHT; try { @@ -906,6 +1128,20 @@ void UpdateSwimState(Player* p) // is out of it, paths again to a navmesh point by the leader, which in water is the surface: a settle that took the follower out // of range was undone at the leader's next step and the two took turns (lake_swim 2026-11-09: a follower 2 y behind a leader on // the surface, settled down and lifted back up 14 times in 25 s). Left where it is, it still swims (the flag above). + // Under the swim z by its fight or by its group's leader, both down there too: it stays down (Swim::HoldsDepth). + if (z < swimZ) + { + auto holds = [&](Unit const* anchor) + { + return anchor && anchor->IsInMap(p) && anchor->IsAlive() && + Swim::HoldsDepth(z, swimZ, p->GetExactDist(anchor), anchor->GetPositionZ()); + }; + Player const* leader = nullptr; + if (Group const* grp = p->GetGroup(); grp && grp->GetLeaderGUID() != p->GetGUID()) + leader = ObjectAccessor::GetPlayer(*p, grp->GetLeaderGUID()); + if (holds(p->GetVictim()) || holds(leader)) + return; + } if (gen == FOLLOW_MOTION_TYPE) { auto const* follow = static_cast(p->GetMotionMaster()->GetCurrentMovementGenerator()); diff --git a/src/modules/PlayerbotV2/Api/PlayerbotMovement.h b/src/modules/PlayerbotV2/Api/PlayerbotMovement.h index 25a7f56941..a0aeda741c 100644 --- a/src/modules/PlayerbotV2/Api/PlayerbotMovement.h +++ b/src/modules/PlayerbotV2/Api/PlayerbotMovement.h @@ -109,6 +109,16 @@ bool ProbeGround(Player* p, float x, float y, float zHint, float& out); bool NearestNavPoint(Player* p, float tx, float ty, float tz, float hxy, float hz, Position& out); +// A bot standing on a scrap of navmesh that no path leaves: a few polygons of a rocky slope that Recast kept apart from the floor +// around them (fewer than kMeshIslandPolys polygons reached by links of any kind). A player walks on and off such a scrap, the +// bot got there on foot in a fight, but every path from it ends on its own edge. blackmaw_full af61 (22 Nov): the tank stood +// 120 s on 6 polygons of the slope at (3589.1,3348.0,274.2); the floor the group stood on was 5.9 y away and 4.5 y up, with four +// more scraps of 2 to 19 polygons in between. Finds the nearest point of a region of at least kMeshIslandPolys polygons, at most +// maxYd away on the level and 6 y up or down, with a clear line and ground under every yard of the step. Writes it to `out` and returns true; false when the bot is +// not on such a scrap or no walkable step off it exists. World thread (or a bot logic thread with its own navmesh queries). +constexpr int kMeshIslandPolys = 64; +bool MeshIslandExit(Player* p, float maxYd, Position& out, int* islandPolys = nullptr); + // Snapshot builds that run beside other builds of the SAME map must not load grids: a grid load adds creatures and navmesh // tiles while the other threads are reading them. While a ScopedDeferGridLoads is alive on a thread, EnsureGridForQuery // hands a grid that is not loaded yet to the world thread (LoadDeferredGrids, after the build barrier) and returns false, so diff --git a/src/modules/PlayerbotV2/BOT_COMMANDS.md b/src/modules/PlayerbotV2/BOT_COMMANDS.md index 5974e0856b..58d88aa9e0 100644 --- a/src/modules/PlayerbotV2/BOT_COMMANDS.md +++ b/src/modules/PlayerbotV2/BOT_COMMANDS.md @@ -105,6 +105,11 @@ out of date AddOns"). The addon only sends ordinary chat, so it needs nothing el circle|arrow|line|none`, `/fb spacing tight|close|spread`, `/fb distance <1-20>`, `/fb maintank [name]`, `/fb tank |clear`, `/fb assign [role]`, `/fb assign list`. - Confirmation whispers from bots are hidden from your chat frame by the addon (they feed the status line). +- **Lazy key** (Key Bindings > AddOns > "WoW Forever Bots"): one key that plays your own character, one spell per press, in + combat too: `.playerbot lazy` for every class on the role of your spec, "Lazy key: heal" (`.playerbot lazy heal`) and + "Lazy key: tank" (`.playerbot lazy tank`) for that role whatever the spec. The server picks the spell from what you know, what + is ready, your resources and what is on the target; heals go to the most hurt group member in 40 yards. The warlock keeps its + own rotation. The add-on's README lists what each role does. There is also an older `PlayerbotControl` addon (roster, stats, alts); this guide covers `ForeverBots`. @@ -162,6 +167,7 @@ from the bot. | `gear` / `inventory` | yes | yes | `Raveni: 15 pieces worn, avg item level 66, best: Ironfoe, ...; 14 free bag slots; 12g 40s 5c`. `inv` lists bag items; `equipped` lists each worn slot. | | `money`, `level`, `xp`, `dur`, `skills`, `recipes`, `rep`, `spec` | yes | no | One-line introspection verbs. | | `change talents ` (also `set talents`, `talents `) | yes | no | Learns your own build. Make it in the Wowhead Forever talent calculator (https://www.wowhead.com/forever/talent-calc), copy the page link (or just the code part, such as `--05003201`) and whisper it. The bot drops its talents, learns yours and plays the spec of ours closest to it (a deep Protection build tanks). Below 60 it fills the tree with most points first, row by row, and puts each new level's point down your build: `Talents: learning your build 0/31/20: 21 points now, the rest as I level.` A link for another class, a code from another calculator or a build the game would not allow is refused with the reason. Kept across relog for your companions. `talents link` answers with the bot's talents as a calculator link; `talents default` (or a `setspec`) gives it our builds back. | +| `setspec ` | yes | no | Plays that spec of its class from now on and re-learns its talents for it: `setspec elemental`, `setspec enh`, `setspec resto`, `setspec fire`, `setspec prot`, or `tank`, `heal`, `dps`. Its role follows the spec. Kept across relog for your companions. The ForeverBots add-on has the same as the Spec list in the bot's right-click menu and the spec buttons on the Spec page. | | `sell grey` / `sell junk` / `sell your junk` / `s *` | yes | yes | Sells everything a vendor visit sells (greys, trade goods for no profession of the bot's, gear it can't use, outgrown greens when the bags are tight) to the vendor you have selected, else the nearest friendly vendor within 200 yards. In reach: `Raveni: selling 7 thing(s) to Dolanaar Vendor`. Farther away it walks over and sells when it arrives (`at Dolanaar Vendor, selling 7 thing(s)`; after a minute without getting there it says so). Nothing to sell: `nothing to sell, my bags only hold things I keep (0 free slots)`. No vendor: `no vendor near here`. Plain `sell` (selected vendor) and `sell [n]` also exist. | | `repair` | yes | yes | Same pattern with a repair vendor: `Raveni: repairing at ...`. | | `loot` | yes | yes | Need before greed with the usual etiquette (human gets first claim). `Raveni: need before greed, the usual rules`. | @@ -438,6 +444,7 @@ The module logs nothing unless `Logger.playerbot.v2=3` is set. Grep the server l | `[quest]` | A quest order the parser handed to `QuestOrders` (`[owner_order] [quest] ...`). | | `[InstanceCap]` | Group larger than the map holds. | | `[say_reply]` | A world bot's answer to a player's /say. | +| `[lazykey]` | Every press of the lazy key (not the warlock's, that is `[lazy]`): the spell, the rule that chose it, the server's answer, role, tree and resources. | | `[world]` | Spawner status line every 60 s. | | `[death-recovery]`, `[raid_pull]`, `[raid_tank]`, `[solo_flee]`, `[bg_queue]`, `[cast_speed]`, `[GroupRelogin]` | Corpse runs, raid pulls and tanking, fleeing, battleground queues, cast pacing, bots re-joining after your login. | diff --git a/src/modules/PlayerbotV2/Bot/BotAI.h b/src/modules/PlayerbotV2/Bot/BotAI.h index da02827bae..98181cb3d0 100644 --- a/src/modules/PlayerbotV2/Bot/BotAI.h +++ b/src/modules/PlayerbotV2/Bot/BotAI.h @@ -24,6 +24,7 @@ #include "BotPersonality.h" #include "BotArchetype.h" #include "BotRng.h" +#include "Api/BotSwim.h" // Swim::BreathGoesUp (needs_air) #include "ObjectGuid.h" #include #include @@ -79,6 +80,12 @@ public: char const* last_rule_fired() const { return last_rule_fired_; } void set_last_rule_fired(char const* name); + // Skill-up station prop: a craft_skillup cast at a focus puts the trade tool in the hand and + // keeps the upgrade rule off the mainhand while the cast run is live. Timestamped — a run that + // just stops (moves off, quest, fight) expires on its own, no cleanup emit needed. + bool station_prop_out(uint32 now_ms) const { return int32(station_prop_until_ms_ - now_ms) > 0; } + void station_prop_extend(uint32 now_ms, uint32 span_ms = 12000) { station_prop_until_ms_ = now_ms + span_ms; } + // BG outcome dedup — the post-match leave rule fires multiple times // (bg_status=4 persists ~2min until TC kicks); we only want to record // the win/loss tally ONCE per match. Keyed by the snapshot published_at @@ -530,6 +537,12 @@ public: bool saw_special_phase() const { return saw_special_phase_; } void set_saw_special_phase(bool v) { saw_special_phase_ = v; } + // A finder run's goodbye (State_Idle, idle:finder_goodbye_*): once the dungeon is done with a player in the group, each bot + // in turn says goodbye, hearths and leaves the group. `map` and `instance` name the run it was planned for, `at_ms` when the + // next step is due, `stage` 0 = waiting its turn, 1 = said goodbye, 2 = gone. + struct FinderGoodbye { uint32 map = 0; uint32 instance = 0; uint32 at_ms = 0; uint8 stage = 0; }; + FinderGoodbye& finder_goodbye() { return finder_goodbye_; } + // Owner-set follow distance preference. The /follow whisper picks this // up so owners can customize how tightly the bot tails. 0.f means // "use default" (5yd). Owners with melee-heavy comp prefer 4-5yd, with @@ -1527,8 +1540,19 @@ public: // reset on clear_dungeon_cross (landing / relocate). bool dungeon_cross_direct() const { return dungeon_cross_direct_; } void set_dungeon_cross_direct(bool d) { dungeon_cross_direct_ = d; } + // A DIRECT crossing down a one-way link whose far end lies far below its mouth (a jump off a ledge into the pool below, as + // The Shaper's Terrace's landing): DungeonHonorCross drives it as a fall (API::move_to drop, a jump spline under gravity) + // instead of a straight walk through the air. Set ONLY by the nav-link hop; reset on clear_dungeon_cross. + bool dungeon_cross_drop() const { return dungeon_cross_drop_; } + void set_dungeon_cross_drop(bool d) { dungeon_cross_drop_ = d; } + // How long (3D, yards) the nav link the bot is crossing is, mouth to far end; 0 when the crossing is not a nav-link hop. Set ONLY + // by the nav-link hop; reset on clear_dungeon_cross. DungeonHonorCross gives up an exit further off than a hop is long, and a + // link can be longer than the usual give-up distance (The Shaper's Terrace's ledge: 66 y down to the pool). + float dungeon_cross_link_len() const { return dungeon_cross_link_len_; } + void set_dungeon_cross_link_len(float l) { dungeon_cross_link_len_ = l; } void clear_dungeon_cross() { dungeon_cross_until_ms_ = 0; cross_episode_since_ms_ = 0; - dungeon_cross_direct_ = false; cross_fight_yield_ = false; } + dungeon_cross_direct_ = false; dungeon_cross_drop_ = false; dungeon_cross_link_len_ = 0.f; + cross_fight_yield_ = false; } // A crossing that stalled while mobs hit the bot gives way to the fight until combat ends (DungeonHonorCross); the // commitment itself is kept, so the hop resumes (or its out-of-combat recovery fires) after the fight. bool cross_fight_yield() const { return cross_fight_yield_; } @@ -1733,7 +1757,12 @@ public: // into a pit at (-13610.7,2775.3,-37.0); the tank ran down and back up the slope beside it every 7 s for 29 minutes // (1,700 s, z -29 to -37) and the group stood idle below. This tracks the bot's best distance to the step it strides // at; no headway for kStrideStallMs means the step is a dead end. - static constexpr float kStrideSameStepY = 5.0f; // two steps this close are the same step (the start point moves) + // The step is measured against the first step of the watch (the anchor), not the last one: the dead end's step moves with the + // bot. scan66 drowned_full (af66): the stride toward Captain Dreadrise picked (-13607.6,2777.9), (-13604.6,2780.6) and + // (-13601.6,2783.2) by turns as the tank ran up and down the slope, the outer two 8 y apart, so each pick restarted the watch at + // 5 y; the tank ran that slope for 53 minutes and the run timed out. A step that really moves on (the bot gets somewhere) leaves + // this radius within a couple of seconds of walking and starts a fresh watch. + static constexpr float kStrideSameStepY = 12.0f; // a step this close to the anchor is the same step static constexpr float kStrideHeadwayY = 1.5f; // the best distance must shrink by this much to count static constexpr uint32 kStrideStallMs = 8000; static constexpr uint32 kStrideGapMs = 2000; // not striding for this long starts the watch afresh @@ -1741,7 +1770,6 @@ public: uint32 stride_note(uint32 map_id, float sx, float sy, float sz, float bx, float by, float bz, uint32 now_ms) { float const ddx = sx - stride_x_, ddy = sy - stride_y_, ddz = sz - stride_z_; - float const d = std::sqrt((bx - sx) * (bx - sx) + (by - sy) * (by - sy) + (bz - sz) * (bz - sz)); bool const same = stride_map_ == map_id && stride_seen_ms_ && now_ms - stride_seen_ms_ < kStrideGapMs && ddx * ddx + ddy * ddy + ddz * ddz <= kStrideSameStepY * kStrideSameStepY; stride_seen_ms_ = now_ms ? now_ms : 1u; @@ -1749,6 +1777,12 @@ public: { stride_map_ = map_id; stride_x_ = sx; stride_y_ = sy; stride_z_ = sz; + } + // Headway is toward the anchor. + float const d = std::sqrt((bx - stride_x_) * (bx - stride_x_) + (by - stride_y_) * (by - stride_y_) + + (bz - stride_z_) * (bz - stride_z_)); + if (!same) + { stride_best_ = d; stride_best_ms_ = stride_seen_ms_; return 0; @@ -1762,6 +1796,38 @@ public: } float stride_best() const { return stride_best_; } + // The same watch one level up: the bot's best distance to the BOSS over all its strides toward it. A dead end the bot runs into + // and back out of takes turns with a step out of it, and the two are far enough apart that each one restarts the step watch + // above, so it never trips. drowned_full af68 (24 Nov, with the 12 y anchor): the stride toward Captain Dreadrise picked + // (-13607.6,2777.9,-36.9) into the pit and the tank came back up to (-13588,2784,-27) between picks, 15 y apart, for 56 + // minutes; the run timed out at 2 of 6. A stride that gets nowhere near its boss for kStrideBossStallMs is a dead end too. + // Strides toward a boss through a winding cave that do get somewhere close the distance well inside that time; where they do + // not, the route the dungeon was given takes over, which is the authored way there anyway. + static constexpr float kStrideBossHeadwayY = 5.0f; // the best distance to the boss must shrink by this much to count + static constexpr uint32 kStrideBossStallMs = 60000; + static constexpr uint32 kStrideBossGapMs = 30000; // no stride toward this boss for this long starts the watch afresh + // Returns how long the bot has strode toward this boss without getting kStrideBossHeadwayY closer to it. Only time spent + // striding counts (ticks less than kStrideGapMs apart), so a tank held between strides (the group's mana, a pull) does not run + // the clock down. + uint32 stride_boss_note(uint32 map_id, uint32 boss_entry, float bx, float by, float bz, float tx, float ty, float tz, uint32 now_ms) + { + float const d = std::sqrt((tx - bx) * (tx - bx) + (ty - by) * (ty - by) + (tz - bz) * (tz - bz)); + bool const same = stride_boss_map_ == map_id && stride_boss_entry_ == boss_entry && stride_boss_seen_ms_ && + now_ms - stride_boss_seen_ms_ < kStrideBossGapMs; + if (same && now_ms - stride_boss_seen_ms_ < kStrideGapMs) + stride_boss_stall_ms_ += now_ms - stride_boss_seen_ms_; + stride_boss_seen_ms_ = now_ms ? now_ms : 1u; + if (!same || stride_boss_best_ - d > kStrideBossHeadwayY) + { + stride_boss_map_ = map_id; + stride_boss_entry_ = boss_entry; + stride_boss_best_ = d; + stride_boss_stall_ms_ = 0; + } + return stride_boss_stall_ms_; + } + float stride_boss_best() const { return stride_boss_best_; } + // ---- refused-destination memory (refusal-aware target selection, // 2026-07-20) ---- // BUG THIS FIXES: PlayerbotAPI::move_to keeps a PER-DESTINATION path-fail @@ -3467,6 +3533,7 @@ private: // Bumped by every set_last_rule_fired(): lets a tick tell "a rule fired // this tick" from a last_rule_fired_ left over from an earlier tick. uint32 rule_fire_seq_ = 0; + uint32 station_prop_until_ms_ = 0; public: uint32 rule_fire_seq() const { return rule_fire_seq_; } // [attack_rule]: the target of an [attack_start] line logged during this tick's dispatch, and the rule count then. The line names @@ -3608,8 +3675,7 @@ private: bool corpse_recovery_emitted_ = false; uint32 ghost_since_ms_ = 0; uint32 swimming_since_ms_ = 0; - uint32 underwater_since_ms_ = 0; - uint32 underwater_seen_ms_ = 0; + bool breath_refill_ = false; ObjectGuid stuck_chase_victim_; uint16 stuck_chase_ticks_ = 0; ObjectGuid last_taxi_discover_fm_; @@ -3725,6 +3791,7 @@ private: uint32 pending_mail_open_at_ms_ = 0; uint32 chat_pause_until_ms_ = 0; bool saw_special_phase_ = false; + FinderGoodbye finder_goodbye_{}; ObjectGuid last_seen_group_; bool group_greet_primed_ = false; float follow_distance_ = 0.f; @@ -4194,6 +4261,11 @@ private: float stride_best_ = 0.f; uint32 stride_best_ms_ = 0; uint32 stride_seen_ms_ = 0; + uint32 stride_boss_map_ = 0; // boss-stride headway toward the boss (stride_boss_note) + uint32 stride_boss_entry_ = 0; + float stride_boss_best_ = 0.f; + uint32 stride_boss_stall_ms_ = 0; // striding time since the best distance last improved + uint32 stride_boss_seen_ms_ = 0; uint32 move_commit_progress_ms_ = 0; // Refused-destination ring (see move_refused_recently() above). struct RefusedDst { float x = 0.f, y = 0.f, z = 0.f; uint32 ms = 0; }; @@ -4204,6 +4276,8 @@ private: float dungeon_cross_z_ = 0.f; uint32 dungeon_cross_until_ms_ = 0; bool dungeon_cross_direct_ = false; // DB nav-link crossing (see accessor) + bool dungeon_cross_drop_ = false; // ... down a one-way link with a long fall (see accessor) + float dungeon_cross_link_len_ = 0.f; // ... and how long that link is (see accessor) // Cross EPISODE wall-clock — survives set_dungeon_cross re-commits; reset only // when the crossing is genuinely cleared (landed / relocated). See cross_episode_ms. uint32 cross_episode_since_ms_ = 0; @@ -5373,20 +5447,10 @@ public: return swimming_since_ms_ != 0 && (now_ms - swimming_since_ms_) > kSwimStuckTimeoutMs; } - // How long the bot's head has been under water (idle:surface_to_breathe), on the snapshot clock (published_at_ms) as - // update_swim_state is. A sighting more than 5 s after the last one starts a new dive. Returns the time under so far, 0 when not. - uint32 note_underwater(bool under, uint32 now_ms) - { - if (!under) - { - underwater_since_ms_ = 0; - return 0; - } - if (underwater_since_ms_ == 0 || now_ms - underwater_seen_ms_ > 5000u) - underwater_since_ms_ = now_ms ? now_ms : 1u; - underwater_seen_ms_ = now_ms; - return now_ms - underwater_since_ms_; - } + // Up for air (Swim::BreathGoesUp, on the server's breath timer): true from the moment the breath runs short until it is full again. + // Every state asks it (idle:surface_to_breathe, the dungeon preempt, the fight), so time under water counts however it was spent. + bool breath_refilling() const { return breath_refill_; } + bool needs_air(int32 breath_left_ms) { return BotMovement::Swim::BreathGoesUp(breath_left_ms, breath_refill_); } // Per-target start_attack lockout. When idle:quest_batch:kill (or any // rule that emits StartAttackIntent) picks a target the server keeps @@ -5430,7 +5494,8 @@ public: } RaidSchoolState& raid_school() { return raid_school_; } RaidSchoolState const& raid_school() const { return raid_school_; } - // The dungeon pack stop's per-pack walk verdicts (PackPullGate.h). Bot worker only: the tank's own idle tick. + // The dungeon pack stop's per-pack walk verdicts (PackPullGate.h). Bot worker only: the tank's own idle tick, and a crowd-control + // caster's (idle:dungeon_auto_cc_script), which measures the tank's walk to an idle mob before it sheeps it. PackPullGate& pack_pull_gate() { return pack_pull_gate_; } PackPullGate const& pack_pull_gate() const { return pack_pull_gate_; } void prune_start_attack_cache(uint32 now_ms) diff --git a/src/modules/PlayerbotV2/Bot/BotBridge.cpp b/src/modules/PlayerbotV2/Bot/BotBridge.cpp index b1dc256666..89e8a53524 100644 --- a/src/modules/PlayerbotV2/Bot/BotBridge.cpp +++ b/src/modules/PlayerbotV2/Bot/BotBridge.cpp @@ -137,7 +137,8 @@ uint32 g_last_bad_warn_ms = 0; struct ChatAsk { BotId bot = 0; std::string sender; ObjectGuid sender_guid; bool sender_is_bot = false; std::string channel; uint32 asked_ms = 0; uint64 talk_key = 0; // a bot-to-bot talk line (AskTalk), kept for TakeTalk std::vector group; // a group order (AskGroupOrder): the other bots that take the answer's action too - uint32 deadline_ms = 0; }; // a raid line (AskRaidLine): an answer at or after this time is dropped (the fixed line was said) + uint32 deadline_ms = 0; // a raid line (AskRaidLine): an answer at or after this time is dropped (the fixed line was said) + std::vector speakers; }; // AskTalk: the speakers of the talk so far (StripSpeakerLabel) // Raid lines the program answered in time (AskRaidLine / RaidLineAnswered), by event id. std::unordered_set g_raid_answered; // The group's part of a group order: each other bot runs the answer's action a moment after the first (HandleGroupFollowups). @@ -1819,6 +1820,14 @@ void HandleReplies(ConfigReader::BridgeConfig const& cfg, uint32 now_ms) if (channel == "whisper" && to.empty()) to = ask.sender; g_chat.erase(it); + // The program labelled the line with a name, as the talk it was shown is written: the game names the speaker already. + if (!text.empty()) + { + std::vector names = ask.speakers; + names.push_back(bot_name); + names.push_back(ask.sender); + text = StripSpeakerLabel(text, names); + } if (auto pi = g_post_ask.find(r.reply_to); pi != g_post_ask.end()) { PostAsk const post = std::move(pi->second); @@ -2575,7 +2584,9 @@ bool BotBridge::AskTalk(Player* bot, std::string const& scene, std::string const Write(e); if (g_chat.size() > 2048) g_chat.clear(); - g_chat[e.id] = ChatAsk{ bot->GetGUID().GetCounter(), std::string(), ObjectGuid::Empty, false, "say", now_ms, key ? key : kNoTalkKey }; + ChatAsk ask{ bot->GetGUID().GetCounter(), std::string(), ObjectGuid::Empty, false, "say", now_ms, key ? key : kNoTalkKey }; + ask.speakers = TalkSpeakers(chat); + g_chat[e.id] = std::move(ask); g_talk_minute.push_back(now_ms); return true; } diff --git a/src/modules/PlayerbotV2/Bot/BotBridgeFormat.cpp b/src/modules/PlayerbotV2/Bot/BotBridgeFormat.cpp index 05ba9d706a..45986979c5 100644 --- a/src/modules/PlayerbotV2/Bot/BotBridgeFormat.cpp +++ b/src/modules/PlayerbotV2/Bot/BotBridgeFormat.cpp @@ -664,6 +664,66 @@ std::string CleanSayText(std::string const& raw, std::size_t max_bytes) namespace { +std::string TrimSpaces(std::string_view s) +{ + std::size_t b = 0, e = s.size(); + while (b < e && (s[b] == ' ' || s[b] == '\t')) ++b; + while (e > b && (s[e - 1] == ' ' || s[e - 1] == '\t')) --e; + return std::string(s.substr(b, e - b)); +} + +std::string LowerAscii(std::string s) +{ + for (char& c : s) + c = char(std::tolower(static_cast(c))); + return s; +} + +} // namespace + +std::string StripSpeakerLabel(std::string const& line, std::vector const& names) +{ + std::size_t const colon = line.find(':'); + if (colon == std::string::npos || colon > 26) + return line; + std::string head = TrimSpaces(std::string_view(line).substr(0, colon)); + if (head.size() >= 2 && ((head.front() == '<' && head.back() == '>') || (head.front() == '[' && head.back() == ']'))) + head = TrimSpaces(std::string_view(head).substr(1, head.size() - 2)); + if (head.empty()) + return line; + head = LowerAscii(std::move(head)); + for (std::string const& n : names) + if (!n.empty() && LowerAscii(n) == head) + { + std::string rest = TrimSpaces(std::string_view(line).substr(colon + 1)); + return rest.empty() ? line : rest; + } + return line; +} + +std::vector TalkSpeakers(std::string const& talk) +{ + std::vector out; + std::size_t start = 0; + while (start < talk.size()) + { + std::size_t const nl = talk.find('\n', start); + std::string_view const l = std::string_view(talk).substr(start, nl == std::string::npos ? std::string::npos : nl - start); + if (std::size_t const c = l.find(": "); c != std::string_view::npos && c > 0 && c <= 24) + { + std::string name(l.substr(0, c)); + if (std::find(out.begin(), out.end(), name) == out.end()) + out.push_back(std::move(name)); + } + if (nl == std::string::npos) + break; + start = nl + 1; + } + return out; +} + +namespace { + struct ActWord { Act act; char const* word; }; constexpr ActWord kActs[] = { { Act::Follow, "follow" }, { Act::Stay, "stay" }, { Act::Resume, "resume" }, { Act::Attack, "attack" }, diff --git a/src/modules/PlayerbotV2/Bot/BotBridgeFormat.h b/src/modules/PlayerbotV2/Bot/BotBridgeFormat.h index bb7f022daf..c662e92e69 100644 --- a/src/modules/PlayerbotV2/Bot/BotBridgeFormat.h +++ b/src/modules/PlayerbotV2/Bot/BotBridgeFormat.h @@ -187,6 +187,15 @@ private: // cut to `max_bytes` on a word boundary without splitting a UTF-8 character. Empty when nothing is left. std::string CleanSayText(std::string const& raw, std::size_t max_bytes); +// A chat line that opens with a speaker's name as a label ("Name: text", "Name : text", "[Name ]: text", ": text"), the way +// a model copies the talk it was shown: the label goes when the name is one of `names` (the bot, the one it answers, the others in +// its talk; any case). In game the line already carries the speaker's name, so the label read as a second, odd name ("[Botname ]:" +// in an English talk on a Russian realm, celguar 11-21). The line is returned unchanged when nothing would be left after it. +std::string StripSpeakerLabel(std::string const& line, std::vector const& names); + +// The names that open the lines of a talk written as "Name: text" lines (BotChatModel::AskSay / BotBridge::AskTalk's `chat`). +std::vector TalkSpeakers(std::string const& talk); + // ---- actions: the rules that need no game state ---- // What the game side found out about the bot and the one asking. Filled by BotBridge.cpp, read by CheckActionContext. diff --git a/src/modules/PlayerbotV2/Bot/BotChatModel.cpp b/src/modules/PlayerbotV2/Bot/BotChatModel.cpp index c1b3d50c53..af99020f7e 100644 --- a/src/modules/PlayerbotV2/Bot/BotChatModel.cpp +++ b/src/modules/PlayerbotV2/Bot/BotChatModel.cpp @@ -1,6 +1,7 @@ // BotChatModel - see header. #include "BotChatModel.h" +#include "Bot/BotBridgeFormat.h" #include "BotBridge.h" #include "BotChatModelClient.h" #include "BotConversation.h" @@ -38,6 +39,7 @@ struct Job BotId bot = 0; std::string bot_name; std::string sender_name; + std::vector talk_names; // AskSay: the speakers of the talk so far BotChatModel::Channel channel = BotChatModel::Channel::Whisper; uint64 history_key = 0; std::string question; @@ -169,7 +171,10 @@ void WorkerLoop() } if (job.bot == 0) continue; - std::string answer = ChatModel::CleanReply(raw, job.bot_name); + std::vector names = job.talk_names; + if (!job.sender_name.empty()) + names.push_back(job.sender_name); + std::string answer = ChatModel::CleanReply(raw, job.bot_name, 250, names); if (answer.empty()) { TC_LOG_INFO("playerbot.v2", "[conv] {} <- {}: chat model reply unusable: \"{}\"", job.bot_name, job.sender_name, raw); @@ -345,6 +350,7 @@ bool BotChatModel::AskSay(Player* bot, std::string const& system, std::string co job.bot = id; job.bot_name = bot->GetName(); job.channel = Channel::Say; + job.talk_names = Bridge::TalkSpeakers(chat); job.history_key = key; job.settings = SettingsFrom(cfg); job.asked = now; diff --git a/src/modules/PlayerbotV2/Bot/BotChatModelClient.cpp b/src/modules/PlayerbotV2/Bot/BotChatModelClient.cpp index ea303f937a..e67a5a89e6 100644 --- a/src/modules/PlayerbotV2/Bot/BotChatModelClient.cpp +++ b/src/modules/PlayerbotV2/Bot/BotChatModelClient.cpp @@ -1,6 +1,7 @@ // BotChatModelClient - see header. #include "BotChatModelClient.h" +#include "BotBridgeFormat.h" #include #include @@ -163,7 +164,7 @@ std::string FilterChars(std::string const& in) } // namespace -std::string CleanReply(std::string const& raw, std::string const& bot_name, std::size_t max_bytes) +std::string CleanReply(std::string const& raw, std::string const& bot_name, std::size_t max_bytes, std::vector const& other_names) { std::string s = raw; @@ -199,15 +200,13 @@ std::string CleanReply(std::string const& raw, std::string const& bot_name, std: } s = Trim(s); - // "Name: text", ": text", "[Name]: text" - the model speaking as the bot by name (the add-on also hides a whisper - // that starts ":" as an order confirmation). - if (std::size_t const colon = s.find(':'); colon != std::string::npos && colon <= 26) + // "Name: text", ": text", "[Name ]: text" - the model labelling the line with the bot's name, or with the name of the one + // it answers or of another bot in its talk, as the talk it was shown is written (the add-on also hides a whisper that starts + // ":" as an order confirmation). { - std::string head = Lower(Trim(s.substr(0, colon))); - if (head.size() >= 2 && ((head.front() == '<' && head.back() == '>') || (head.front() == '[' && head.back() == ']'))) - head = Trim(head.substr(1, head.size() - 2)); - if (!bot_name.empty() && head == Lower(bot_name)) - s = Trim(s.substr(colon + 1)); + std::vector names = other_names; + names.push_back(bot_name); + s = Bridge::StripSpeakerLabel(s, names); } // Wrapping quotes. diff --git a/src/modules/PlayerbotV2/Bot/BotChatModelClient.h b/src/modules/PlayerbotV2/Bot/BotChatModelClient.h index de315107a9..379cef07ad 100644 --- a/src/modules/PlayerbotV2/Bot/BotChatModelClient.h +++ b/src/modules/PlayerbotV2/Bot/BotChatModelClient.h @@ -44,7 +44,9 @@ bool ParseReply(std::string const& body, std::string& out, std::string& error); // Turns a raw model reply into one chat line a bot can say: drops a block, keeps the first non-empty line, strips a // leading "Name:" (also ":" / "[Name]:") and wrapping quotes or asterisks, removes '|' (the client's escape character) and characters the game // font has no glyph for (emoji), and cuts it to `max_bytes` on a word boundary. Empty when nothing usable is left. -std::string CleanReply(std::string const& raw, std::string const& bot_name, std::size_t max_bytes = 250); +// `other_names`: the one the bot answers and the others in its talk; a line labelled with one of their names loses the label too. +std::string CleanReply(std::string const& raw, std::string const& bot_name, std::size_t max_bytes = 250, + std::vector const& other_names = {}); class Client { diff --git a/src/modules/PlayerbotV2/Bot/BotChatReactor.cpp b/src/modules/PlayerbotV2/Bot/BotChatReactor.cpp index 314e2a4b51..c7961e839c 100644 --- a/src/modules/PlayerbotV2/Bot/BotChatReactor.cpp +++ b/src/modules/PlayerbotV2/Bot/BotChatReactor.cpp @@ -2052,16 +2052,23 @@ void BotChatReactor::ReactGuildJoin(uint64 guild_id, ObjectGuid joiner_guid, // Compose a welcome line. Address the joiner by first name where possible. std::string first = joiner_name; if (auto sp = first.find(' '); sp != std::string::npos) first.resize(sp); - static constexpr char const* kTemplates[] = { - "welcome {}!", "welcome to the guild {} :)", "hey {}, welcome!", - "welcome aboard {}!", "{} welcome! :)", "glad to have you {}!", - }; - constexpr size_t kN = sizeof(kTemplates) / sizeof(*kTemplates); - std::string line = kTemplates[seed % kN]; - if (auto pos = line.find("{}"); pos != std::string::npos) + // Migration 0067: the text table's guild_join_welcome key first (%s = the joiner); + // the builtin templates otherwise, picked by the same stable seed. + std::string line = BotTextMgr::instance().Get("guild_join_welcome", + { { "%s", first.empty() ? std::string("friend") : first } }); + if (line.empty()) { - if (!first.empty()) line.replace(pos, 2, first); - else line.replace(pos, 2, "friend"); + static constexpr char const* kTemplates[] = { + "welcome {}!", "welcome to the guild {} :)", "hey {}, welcome!", + "welcome aboard {}!", "{} welcome! :)", "glad to have you {}!", + }; + constexpr size_t kN = sizeof(kTemplates) / sizeof(*kTemplates); + line = kTemplates[seed % kN]; + if (auto pos = line.find("{}"); pos != std::string::npos) + { + if (!first.empty()) line.replace(pos, 2, first); + else line.replace(pos, 2, "friend"); + } } // Stamp throttle only now that we will emit. diff --git a/src/modules/PlayerbotV2/Bot/BotCommandParser.cpp b/src/modules/PlayerbotV2/Bot/BotCommandParser.cpp index 2c3e99df84..9e0e85c14d 100644 --- a/src/modules/PlayerbotV2/Bot/BotCommandParser.cpp +++ b/src/modules/PlayerbotV2/Bot/BotCommandParser.cpp @@ -123,6 +123,20 @@ void ApplyClassicRoleSpec(Player const* p, ::Playerbot::Role role) // An owner's `/setrole` on a companion is its declared role: stored with it (Role::Unknown clears) so a relog or // `.bot call` pins the same role again instead of re-inferring one from its talents. +// The owner's standing orders on a companion ("loot all", "gather on") are stored with it, so a relog, `.bot call` or restart keeps them +// (Alex Black Cat, RU general 11-21: an alt's gather and loot all were gone after every relog). Bots nobody owns are not written. +void PersistOwnerOrders(Player const* p, ::Playerbot::BotAI const* ai) +{ + if (!p || !ai) + return; + ::Playerbot::BotId const id = p->GetGUID().GetCounter(); + if (::Playerbot::Services::Owners().GetOwner(id).account_id == 0) + return; + using OR = ::Playerbot::OwnerRegistry; + uint8 const orders = (ai->loot_all() ? OR::kOwnerOrderLootAll : 0) | (ai->gather_ordered() ? OR::kOwnerOrderGather : 0); + ::Playerbot::Services::Owners().SaveOwnerOrders(id, orders); +} + void PersistDeclaredRole(Player const* p, ::Playerbot::Role role) { ::Playerbot::BotId const id = p->GetGUID().GetCounter(); @@ -1476,6 +1490,7 @@ bool OwnerWordOrder(Player* sender, Player* bot, std::string const& n) return true; bool const all = n != "loot"; ai->set_loot_all(all); + PersistOwnerOrders(bot, ai); TC_LOG_INFO("playerbot.v2", "[owner_order] {} <- {}: loot {}", me, sender->GetName(), all ? "all" : "need-greed"); if (MayAnswerGroupQuestion(bot)) say(all ? me + ": looting everything, greys included, and rolling for myself" @@ -2588,7 +2603,7 @@ bool BotCommandParser::ApplyLeadOrder(Player* sender, std::string const& line, c reply = fmt::format("{} leads the raid now: it pulls pack by pack, waits for mana and for you, and stops before each boss for you to pull " "(or say 'go'). Say 'lead pause' to hold, 'lead off' to lead yourself.", name); else if (in_dungeon) - reply = fmt::format("{} leads the dungeon now: it pulls pack by pack and waits for mana and for you. Say 'lead pause' to hold, 'lead off' to lead yourself.", name); + reply = fmt::format("{} leads the dungeon now: it pulls pack by pack and waits for you, and before a boss for a healer low on mana. Say 'lead pause' to hold, 'lead off' to lead yourself.", name); else reply = fmt::format("{} leads once you are inside a dungeon or a raid. Say 'lead off' to lead yourself.", name); break; @@ -6003,6 +6018,7 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri ai->set_aoe_preference(false); ai->set_aoe_denied(false); ai->set_gather_ordered(false); + PersistOwnerOrders(bot, ai); Push(bot, WhisperIntent{sender->GetName(), "Clearprefs: focus, role, follow_distance, verbose, aoe, gather reset."}); return true; @@ -6022,6 +6038,7 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri ai->set_aoe_preference(false); ai->set_aoe_denied(false); ai->set_gather_ordered(false); + PersistOwnerOrders(p, ai); }); Push(bot, WhisperIntent{sender->GetName(), fmt::format("Clearprefs_all: reset on {} bot(s).", changed)}); @@ -6118,7 +6135,7 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri // gather on — picks the herbs and ore veins near it as it follows you, with the gathering skills it has (GatheringRules.cpp), // and skins what the group kills once you have looted it (LootDrainRules.cpp) // gather off — leaves them alone again (the default) - // gather — toggle. gather_all sets every bot of the group. Memory only; clearprefs turns it off. + // gather — toggle. gather_all sets every bot of the group. Stored with a companion (PersistOwnerOrders); clearprefs turns it off. bool const all = cmd != "gather"; BotAI* self_ai = Services::Registry().ai(bot->GetGUID().GetCounter()); if (!self_ai) @@ -6135,13 +6152,17 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri const uint32 changed = ForEachGroupBot(bot, [&](Player const* p) { if (BotAI* ai = Services::Registry().ai(p->GetGUID().GetCounter())) + { ai->set_gather_ordered(desired); + PersistOwnerOrders(p, ai); + } }); Push(bot, WhisperIntent{sender->GetName(), desired ? fmt::format("Gather: ON for {} bot(s).", changed) : fmt::format("Gather: OFF for {} bot(s).", changed)}); return true; } self_ai->set_gather_ordered(desired); + PersistOwnerOrders(bot, self_ai); std::string what; for (auto const& [skill, word] : { std::pair{ SKILL_HERBALISM, "herbs" }, std::pair{ SKILL_MINING, "ore" }, std::pair{ SKILL_SKINNING, "skins" } }) if (bot->HasSkill(skill)) diff --git a/src/modules/PlayerbotV2/Bot/BotIntent.h b/src/modules/PlayerbotV2/Bot/BotIntent.h index dd6525623e..4c1338a48a 100644 --- a/src/modules/PlayerbotV2/Bot/BotIntent.h +++ b/src/modules/PlayerbotV2/Bot/BotIntent.h @@ -76,6 +76,10 @@ struct NearTeleportToIntent { float x, y, z, o; bool navmesh_point = false; }; // owner-useful ones via whisper (sit/stand) but the intent carries the raw // byte so future rules (auto-sit on inn furniture etc.) can use the rest. struct SetStandStateIntent { uint8 stand_state; }; +// CMSG_SET_SHEATHED mirror: sheath matches SheathState — 0=UNARMED (hands away), +// 1=MELEE, 2=RANGED. The station show draws the tool so the smith visibly holds it. +struct SetSheathIntent { uint8 sheath; int8_t hold = -1; }; +struct PlaySoundIntent { uint32 sound_kit; }; // distance sound to everyone in earshot (station-work audio) // ---- Movement ---- // direct=true executes a straight MovePoint spline WITHOUT pathfinding ("just @@ -112,6 +116,8 @@ struct FollowIntent { ObjectGuid leader; float distance; float angle_ra struct UseItemIntent { uint8 bag, slot; ObjectGuid target; }; struct UseItemByEntryIntent { uint32 item_entry; ObjectGuid target; }; struct EquipItemIntent { uint8 from_bag, from_slot; uint8 to_slot; }; +struct GiveItemIntent { uint32 item_entry; uint16 count; }; // conjure-to-bags (profession tool at its station) +struct LearnSpellIntent { uint32 spell_id; }; // teach a spell (starter recipe at a craft station) struct LootIntent { ObjectGuid corpse_or_object; bool quest_only = false; }; // quest_only: take only this bot's quest drops struct ReleaseCorpseIntent {}; struct ReviveAtCorpseIntent {}; @@ -648,10 +654,10 @@ struct HousingIntent using IntentBody = std::variant< CastSpellIntent, GroundTargetSpellIntent, CancelCastIntent, StartAttackIntent, StopAttackIntent, PetAttackIntent, PetCastSpellIntent, - DismissPetIntent, SetStandStateIntent, UnstuckIntent, CancelAuraIntent, + DismissPetIntent, SetStandStateIntent, SetSheathIntent, PlaySoundIntent, UnstuckIntent, CancelAuraIntent, MoveToIntent, TeleportToIntent, StopMovementIntent, JumpIntent, MountIntent, DismountIntent, HearthIntent, FollowIntent, - UseItemIntent, UseItemByEntryIntent, EquipItemIntent, LootIntent, + UseItemIntent, UseItemByEntryIntent, EquipItemIntent, GiveItemIntent, LearnSpellIntent, LootIntent, ReleaseCorpseIntent, ReviveAtCorpseIntent, ReclaimCorpseIntent, SpiritResurrectIntent, AcceptRezIntent, QuestAcceptIntent, QuestCompleteIntent, QuestAbandonIntent, @@ -720,17 +726,17 @@ inline size_t IntentKind(Intent const& i) { return i.body.index(); } // wedge read as "Dismount | ServerRefused" — diagnosed as the wrong bug on // 2026-06-10). The static_asserts force this list to be updated whenever an // alternative is added to / removed from IntentBody. -static_assert(std::variant_size_v == 101, +static_assert(std::variant_size_v == 105, "IntentBody changed — update IntentKindName() below to match."); inline char const* IntentKindName(size_t kind) { static constexpr char const* kNames[] = { "CastSpell", "GroundTargetSpell", "CancelCast", "StartAttack", "StopAttack", "PetAttack", "PetCastSpell", - "DismissPet", "SetStandState", "Unstuck", "CancelAura", + "DismissPet", "SetStandState", "SetSheath", "PlaySound", "Unstuck", "CancelAura", "MoveTo", "TeleportTo", "StopMovement", "Jump", "Mount", "Dismount", "Hearth", "Follow", - "UseItem", "UseItemByEntry", "EquipItem", "Loot", + "UseItem", "UseItemByEntry", "EquipItem", "GiveItem", "LearnSpell", "Loot", "ReleaseCorpse", "ReviveAtCorpse", "ReclaimCorpse", "SpiritResurrect", "AcceptRez", "QuestAccept", "QuestComplete", "QuestAbandon", diff --git a/src/modules/PlayerbotV2/Bot/BotIntentEmitter.cpp b/src/modules/PlayerbotV2/Bot/BotIntentEmitter.cpp index dcd9c9bc78..6434f5383e 100644 --- a/src/modules/PlayerbotV2/Bot/BotIntentEmitter.cpp +++ b/src/modules/PlayerbotV2/Bot/BotIntentEmitter.cpp @@ -6,6 +6,7 @@ #include "AoeDeny.h" #include "BotSnapshot.h" #include "BotSnapshotView.h" +#include "PullDelay.h" #include "Log.h" #include "SharedDefines.h" #include "SpellInfo.h" @@ -467,6 +468,10 @@ bool BotIntentEmitter::start_attack(ObjectGuid target) if (ai_->start_attack_recently_refused(target.GetCounter(), now_ms)) return false; } + // The damage dealers' wait after their tank's pull (Bot/PullDelay.h): every engage path starts its attack here, so the wait + // holds whichever rule picked the mob (af76 dev run: the rogue opened 0.1 s after the tank by a path that never asked the hold). + if (ai_ && school_snap_ && PartyPullDelayHolds(*ai_, BotSnapshotView{ *school_snap_ }, target)) + return false; // An enemy the raid brain forbids this bot is attacked by no rule: the raid layer's own steps honour the list, and so must the // rotations and the combat state's own target picks, or the bot swings at it between two raid passes and the next pass drops it // again. naxx_horsemen af43: resting spare tanks had Mograine forbidden and still opened on him ("attack_start ... last_rule @@ -574,6 +579,19 @@ bool BotIntentEmitter::move_already_emitted(float x, float y, float z) const bool BotIntentEmitter::move_to(float x, float y, float z, bool run, bool direct, bool drop, bool follow_drop) { + // A move to the far end of a committed nav-link crossing (DungeonNavLinkHop: a DB traversal link across a real navmesh split) + // IS that crossing, whichever rule emits it, so it goes as the straight no-pathfind spline. The hop hands its far end back to + // its caller as the next step, and the callers emit it as a plain move_to: State_InGroup's rejoin of the tank did, and the + // pathed move toward the far side of the split came back Incomplete 0.9 y on, the bot stopped, and DungeonHonorCross's direct + // re-assert of the same point 3 y away was then swallowed by the dedup below. WC wc_full af67 (24 Nov): the tank crossed + // Serpentis' cliff link 1, the four behind it hopped at (-292,-2,-57.7) and stood 8 y short of (-289.1,3.2,-64.0), walked + // back, the tank was relocated back to them and the group stalled under the ledge. + if (ai_ && !direct && !drop && ai_->dungeon_cross_direct() && ai_->dungeon_cross_active(GameTime::GetGameTimeMS())) + { + const float cdx = x - ai_->dungeon_cross_x(), cdy = y - ai_->dungeon_cross_y(), cdz = z - ai_->dungeon_cross_z(); + if (cdx * cdx + cdy * cdy + cdz * cdz <= 1.0f) + direct = true; + } // Per-bot dedup: skip if the previous move_to went to ~the same XYZ // within the lockout window. See BotAI::kMoveToEmitLockoutMs / the long // comment on note_move_to_emitted for the rationale (spline thrash, diff --git a/src/modules/PlayerbotV2/Bot/BotIntentEmitter.h b/src/modules/PlayerbotV2/Bot/BotIntentEmitter.h index 2cc1c27541..27d6b52279 100644 --- a/src/modules/PlayerbotV2/Bot/BotIntentEmitter.h +++ b/src/modules/PlayerbotV2/Bot/BotIntentEmitter.h @@ -158,6 +158,7 @@ public: bool dismiss_pet() { return emit(DismissPetIntent{}); } bool sit() { return emit(SetStandStateIntent{1}); } bool stand(){ return emit(SetStandStateIntent{0}); } + bool set_sheath(uint8 sheath, int8_t hold = -1) { return emit(SetSheathIntent{sheath, hold}); } // clear_generators=true tears down stale MotionMaster generators (not just // the active spline) — see StopMovementIntent. Use it when a movement // target may have outlived its validity (e.g. on a cross-map teleport). @@ -468,6 +469,10 @@ public: { return emit(VendorIntent{VendorBuyByCategoryIntent{vendor, item_class, item_subclass, total_count}}); } bool equip_item(uint8 from_bag, uint8 from_slot, uint8 to_slot) { return emit(EquipItemIntent{from_bag, from_slot, to_slot}); } + bool give_item(uint32 entry, uint16 count = 1) + { return emit(GiveItemIntent{entry, count}); } + bool learn_spell(uint32 spell_id) + { return emit(LearnSpellIntent{spell_id}); } // Mana break: a mana item is due but a cast is running. Until the item goes out (or 4 s pass) cast()/cast_rank() refuse any // spell with a cast time, so the running cast is the last one and the next tick can use the item. diff --git a/src/modules/PlayerbotV2/Bot/BotIntentExecutor.cpp b/src/modules/PlayerbotV2/Bot/BotIntentExecutor.cpp index 8d86fd9342..0aeb0ff2af 100644 --- a/src/modules/PlayerbotV2/Bot/BotIntentExecutor.cpp +++ b/src/modules/PlayerbotV2/Bot/BotIntentExecutor.cpp @@ -320,6 +320,8 @@ struct IntentVisitor Result operator()(PetCastSpellIntent const& i) { return api.pet_cast(i.spell_id, i.target); } Result operator()(DismissPetIntent const&) { return api.dismiss_pet(); } Result operator()(SetStandStateIntent const& i) { return api.set_stand_state(i.stand_state); } + Result operator()(SetSheathIntent const& i) { return api.set_sheath(i.sheath, i.hold); } + Result operator()(PlaySoundIntent const& i) { return api.play_sound(i.sound_kit); } // SayChat/YellChat/EmoteChat/GuildChat/RaidChat/OfficerChat/RaidWarning/ // Whisper/PartyChat are bundled into `ChatIntent`. See operator()(ChatIntent). Result operator()(UnstuckIntent const& i) { return api.unstuck(i.distance); } @@ -423,6 +425,8 @@ struct IntentVisitor Result operator()(LootRollIntent const& i) { return api.loot_roll(i.loot_object, i.loot_list_id, i.vote_type); } Result operator()(BindHomebindIntent const& i) { return api.bind_homebind(i.innkeeper); } Result operator()(EquipItemIntent const& i) { return api.equip_item(i.from_bag, i.from_slot, i.to_slot); } + Result operator()(GiveItemIntent const& i) { return api.give_item(i.item_entry, i.count); } + Result operator()(LearnSpellIntent const& i) { return api.learn_spell(i.spell_id); } // ---- Subsystem-wrapper handlers (variant-pressure relief) ---- // diff --git a/src/modules/PlayerbotV2/Bot/BotSnapshot.h b/src/modules/PlayerbotV2/Bot/BotSnapshot.h index 3efc413c09..7f021a8c11 100644 --- a/src/modules/PlayerbotV2/Bot/BotSnapshot.h +++ b/src/modules/PlayerbotV2/Bot/BotSnapshot.h @@ -371,6 +371,12 @@ struct NearbyUnit // action). It runs to the nearest friend within CreatureFamilyFleeAssistanceRadius and calls assistance there, which brings // that friend's pack (SM 2026-10-30: Scarlet mobs flee at 15 % and turned 2-3 mob pulls into 8). A feared mob is not one. bool seeks_help = false; + // creature_formations (FormationMgr): the spawn id of the formation's leader, 0 = in none; and whether this mob going into combat + // brings others of it (CreatureGroup::MemberEngagingTarget: the leader calls its members with FLAG_MEMBERS_ASSIST_LEADER, a member + // calls the leader with FLAG_LEADER_ASSISTS_MEMBER). Crowd control on such a mob is a pull of its formation (lbrs_full af59: the Polymorph on Scarshield + // Legionnaire 182 brought 181 and 179 onto the mage before the tank had pulled). + uint64 formation_leader = 0; + bool engage_calls_formation = false; // UNIT_FLAG_UNINTERACTIBLE (0x02000000, the old NOT_SELECTABLE): players // cannot select/target the unit, and Unit::IsValidAttackTarget rejects it — // so a bot can NEVER acquire it as a victim. Invisible "stalker" / trigger @@ -386,6 +392,10 @@ struct NearbyUnit // Set from BOTH the live unit flag and the creature_template flag (mirrors // is_pacified: a static template flag may not be applied to the live unit). bool untargetable = false; + // Attackers only (combat.attackers): Unit::IsValidAttackTarget from the bot, read by the builder while no map updates. False + // for an attacker the bot can see and reach but never damage (an IMMUNE_TO_PC event creature): the false-combat escape counts + // it as immune instead of looking the unit up from a bot worker (State_Idle). Other unit lists leave it true. + bool valid_attack_target = true; // Creature-only: Creature::CanNotReachTarget() — the mob's OWN // ChaseMovementGenerator reports it cannot path to its current target // (!isInAccessiblePlaceFor / PATHFIND_NOPATH, maintained per-tick by TC). @@ -1047,6 +1057,9 @@ struct LfgState bool in_dungeon = false; // True when an LFG vote-to-kick is active in the bot's group. bool vote_kick_active = false; + // True once LFGMgr has the run finished (LFG_STATE_FINISHED_DUNGEON: the final encounter of the matched dungeon is done). + // With in_dungeon it tells a finder group apart from a party made by hand. Set under the same gate as in_dungeon. + bool finished_dungeon = false; void reset() { *this = LfgState{}; } }; @@ -1416,6 +1429,10 @@ struct CombatTargetsState // The victim stands in a liquid that burns a player (tar, lava: BotMovement::LiquidHurts at its spot). A melee bot does not follow it // in (State_InCombat chase_blocked): shapers_full af51, the rogue chased an Ironhide Ravasaur into the Tar Pits and died there. bool victim_in_damaging_liquid = false; + // A dry spot inside the bot's melee reach of such a victim, reached by a dry path (BotSnapshotBuilder LiquidVictimBankSpot): the + // bank a melee bot walks to and swings from (Ragnaros, who never leaves his lava). Unset when the bot is in reach already or none. + bool victim_bank_known = false; + float victim_bank_x = 0.0f, victim_bank_y = 0.0f, victim_bank_z = 0.0f; ObjectGuid current_target; // True only when current_target resolves to a LIVE unit the bot could // legally attack (IsValidAttackTarget on the world thread). Autonomy @@ -1472,6 +1489,8 @@ struct CombatTargetsState victim_reach = 0.0f; victim_group_target = false; victim_in_damaging_liquid = false; + victim_bank_known = false; + victim_bank_x = victim_bank_y = victim_bank_z = 0.0f; current_target = ObjectGuid::Empty; current_target_hostile = false; attackers.clear(); @@ -1627,6 +1646,14 @@ struct NearbyObject // A shut door whose lock takes a key this bot carries (Lock.db2 LOCK_KEY_ITEM: the Gordok Courtyard and Inner Doors in Dire Maul): // the key's item entry, 0 for any other object. Such a door is in the list as a hand_door too, for this bot only. uint32 key_item = 0; + // A shut door whose lock this bot opens with a spell of its own: the lock has a skill case (Lockpicking for Pick Lock) and the bot's + // skill reaches it (Alcaz Prison's Maximum Security Door 649547, lock 4295: Lockpicking 250 or the Overseer's Keyring; on live a + // rogue picked it, 26 Nov). For this bot only, like key_item; such a door is in the list as a hand_door too. + bool pick_lock = false; + // DOOR only: its facing in radians (the way through the door runs along it, (cos o, sin o)) and whether it shuts by itself after + // a use (template autoClose: Alcaz Prison's Prison Gates, 3 s). Such a door each bot opens for itself (idle:dungeon_open_hand_door). + float o = 0.f; + bool auto_close = false; // CHEST (type 3) only: one the bot's dungeon lists as holding a door key (DungeonScript::key_chests), spawned and not yet opened. bool key_chest = false; // RITUAL (type 18) without an owner (the Altar of the Keepers / of Archaedas in Uldaman, the Blackrock Altar in UBRS): true when @@ -1701,6 +1728,9 @@ struct EnvironmentState bool transport_is_ship = false; bool is_underwater = false; float water_surface_z = 0.0f; + // The server's breath timer (Player::HandleDrowning): ms of breath left, counting down while the head is under water and back up + // ten times as fast above it; -1 when it is not running (full, water breathing, dead). + int32 breath_left_ms = -1; bool is_in_damaging_liquid = false; // Also set in a liquid that burns (tar, lava, is_in_damaging_liquid), wherever the bot is: idle:flee_damaging_liquid and the combat // step-out walk to it. A random 25 y heading from the middle of the Tar Pits ended in tar again and the move gate refused it (af51). @@ -1764,6 +1794,26 @@ struct DungeonExecState float inside_entrance_y = 0.f; float inside_entrance_z = 0.f; + // The creatures the dungeon rules look for, collected by the builder (BuildDungeonScan) while no map is updating. The rules run on + // the bot workers, and a grid walk there races the map thread that moves creatures between cells: the af65 worldserver crashed + // (23 Nov, drowned_full) inside the catch-up boss scan's Cell::VisitAllObjects. Positions are the build's. + struct ScanUnit + { + ObjectGuid guid; + uint32 entry = 0; + float x = 0.f, y = 0.f, z = 0.f; + bool fightable = false; // bosses: attackable now, or hostile and asleep until a player comes near + bool in_los = false; // bosses within kScanLosYd: in the bot's line of sight + bool in_combat = false; + }; + static constexpr float kScanBossYd = 500.0f; // the whole dungeon, as the boss scans always looked + static constexpr float kScanHostileYd = 150.0f; // the tank's next-pack scan + static constexpr float kScanLosYd = 40.0f; + // Alive creatures of the dungeon's boss list and of its portal hops (the boss beyond, the ones that open it) within kScanBossYd. + std::vector scan_bosses; + // Alive creatures within kScanHostileYd the bot may attack, not critters, totems or companion pets. + std::vector scan_hostiles; + void reset() { *this = DungeonExecState{}; } }; @@ -2806,9 +2856,16 @@ struct BotSnapshot // The owner is in the bot's group: the bot is a companion and does what its owner's party does, not world-bot // errands (questing, vendors, gathering, travel). See IdleRuleRegistry::tick. bool owner_in_group = false; + // The player who leads the bot (the owner in its group, else the player who commands it) is in the water, on the bot's map and + // within kLeaderWaterYd: the bot swims with him, as a party member does. The ways out of the water for a bot on its own + // (idle:water_escape, idle:swim_stuck) leave it be (Discord 2026-11-22, Egod: bots in the water stood and watched). + bool leader_in_water = false; // The character is a real player's own (not on a bot pool account): an alt summoned into the party (`.playerbot summon`, the // add-on). The free upkeep meant for the server's bots (the gold floor and the free repair, Bot/AlwaysBuffs.h) leaves it out. bool players_own_character = false; + // The character is played from a game client (a self bot, .playerbot self) or is a player-led scenario's stand-in + // (Scenario::PlaysAsHuman): the bot logic drives a person's character, so it never hands its group to "the human" in it. + bool plays_as_human = false; // The bot is in a group with a player who controls it although it has no owner in that group: a world bot the player invited // (or a companion whose owner is not in the group). Same duty as a companion: it does what the group does, no errands, and the // controller's orders reach it. controller_guid is that player (the group leader when human, else the first human member). @@ -3126,6 +3183,7 @@ struct BotSnapshot owner_guid = ObjectGuid::Empty; owner_in_group = false; players_own_character = false; + plays_as_human = false; led_by_player = false; controller_guid = ObjectGuid::Empty; no_tag_stance = false; diff --git a/src/modules/PlayerbotV2/Bot/BotSnapshotBuilder.cpp b/src/modules/PlayerbotV2/Bot/BotSnapshotBuilder.cpp index b4f9de6af0..75cc854abc 100644 --- a/src/modules/PlayerbotV2/Bot/BotSnapshotBuilder.cpp +++ b/src/modules/PlayerbotV2/Bot/BotSnapshotBuilder.cpp @@ -1,7 +1,10 @@ #include "BotSnapshotBuilder.h" #include "BotRegistry.h" +#include "CreatureGroups.h" // FormationMgr: a mob's formation and its assist flags #include "GroupControl.h" #include "Bot/SpellFamily.h" +#include "Bot/MeleeReach.h" // LiquidVictimBankSpot: the server's melee reach +#include "PathGenerator.h" // LiquidVictimBankSpot: a dry path to the bank #include "ClassicSpec.h" #include "BotAI.h" #include "BagSizeTable.h" @@ -26,6 +29,7 @@ #include "Dungeon/PveGroupCoordinator.h" #include "Raid/RaidBrain.h" #include "Dungeon/DungeonScript.h" // DungeonScriptMgr::GetScriptFor + event_summoned_bosses() +#include "BotSnapshotView.h" // BuildDungeonScan: the advice for the snapshot being built #include "Player.h" #include "TemporarySummon.h" #include "PlayerbotAPI.h" // IsItemRenderableInSlot (auto-equip candidate gate) @@ -101,6 +105,7 @@ #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include +#include #include #include #include @@ -1512,6 +1517,87 @@ uint8 DeepWaterBearings(Player const* p, Map* m, uint32 now_ms) return mask; } +// A dry spot inside the bot's melee reach of a victim standing in a liquid that burns a player (lava, tar): the bank a player swings from. +// A melee bot never walked in after such a victim, and it never walked to the bank either: it waited for the mob to come out. Ragnaros +// never comes out (he stands in the lava of his lair for the whole fight), so every rogue and warrior stood 37-40 y away for the whole +// fight and hit him 0 times (mc_ragnaros af53 1120, 1103 [liquid_hold] / combat:melee_hold_liquid lines; DoctorSun, BUGS-ALL 312). +// The spot is on a ring round the victim inside the server's melee reach (MeleeReach::Of, 3D centre distance), on ground that is not +// in the liquid, in sight of the victim, and reached by a path whose every 2 y is out of the burning liquid too (the player path filter +// takes magma polys). Bearings nearest the bot's own come first. Kept per bot until the victim has moved 2 y or 1.5 s have passed: +// up to 6 path probes per look. thread_local like the LoS memo: each map's bots build on one worker. +bool LiquidVictimBankSpot(Player* p, Map* m, ObjectGuid victim, float vx, float vy, float vz, float victim_reach, uint32 now_ms, + float& outX, float& outY, float& outZ) +{ + struct Entry { uint32 at_ms; ObjectGuid victim; float vx, vy; bool ok; float x, y, z; }; + thread_local std::unordered_map s_cache; + if (s_cache.size() > 16384) + s_cache.clear(); + uint64 const key = p->GetGUID().GetCounter(); + auto it = s_cache.find(key); + if (it != s_cache.end() && it->second.victim == victim && now_ms - it->second.at_ms < 1500u + && (it->second.vx - vx) * (it->second.vx - vx) + (it->second.vy - vy) * (it->second.vy - vy) < 2.0f * 2.0f) + { + outX = it->second.x; outY = it->second.y; outZ = it->second.z; + return it->second.ok; + } + Entry e{ now_ms, victim, vx, vy, false, 0.0f, 0.0f, 0.0f }; + auto hazard_at = [&](float x, float y, float z) + { + return BotMovement::ClassifyDestinationLiquid(p, x, y, z) == BotMovement::LiquidVerdict::Hazard; + }; + float const reach = MeleeReach::Of(victim_reach); + float const bx = p->GetPositionX(), by = p->GetPositionY(); + float const base = std::atan2(by - vy, bx - vx); + float const zTop = std::max(p->GetPositionZ(), vz) + 4.0f; + int probes = 0; + constexpr int kMaxPathProbes = 6; + constexpr int kBearings = 24; // 15 degrees apart + for (float ring = reach - 0.5f; ring >= 2.0f && !e.ok && probes < kMaxPathProbes; ring -= 1.5f) + for (int i = 0; i < kBearings && !e.ok && probes < kMaxPathProbes; ++i) + { + // 0, +15, -15, +30, -30 ... degrees from the bot's own bearing + int const step = (i + 1) / 2; + float const turn = float((i % 2) ? step : -step) * (2.0f * float(M_PI) / float(kBearings)); + float const x = vx + ring * std::cos(base + turn); + float const y = vy + ring * std::sin(base + turn); + float const z = m->GetHeight(p->GetPhaseShift(), x, y, zTop, true, 16.0f); + if (z <= INVALID_HEIGHT + 1.0f) + continue; + float const dz = z - vz; + if (ring * ring + dz * dz > reach * reach) + continue; + if (hazard_at(x, y, z)) + continue; + if (!m->isInLineOfSight(p->GetPhaseShift(), x, y, z + p->GetCollisionHeight(), vx, vy, vz + 2.0f, + LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::Nothing)) + continue; + ++probes; + PathGenerator path(p); + if (!BotMovement::SehSafeCalculatePath(path, x, y, z) || (path.GetPathType() & (PATHFIND_NOPATH | PATHFIND_INCOMPLETE))) + continue; + auto const& pts = path.GetPath(); + bool dry = true; + for (size_t k = 1; k < pts.size() && dry; ++k) + { + float const sx = pts[k - 1].x, sy = pts[k - 1].y, sz = pts[k - 1].z; + float const ex = pts[k].x, ey = pts[k].y, ez = pts[k].z; + float const len = std::sqrt((ex - sx) * (ex - sx) + (ey - sy) * (ey - sy)); + int const n = std::max(1, int(len / 2.0f)); + for (int s = 1; s <= n && dry; ++s) + { + float const f = float(s) / float(n); + dry = !hazard_at(sx + (ex - sx) * f, sy + (ey - sy) * f, sz + (ez - sz) * f); + } + } + if (!dry) + continue; + e.ok = true; e.x = x; e.y = y; e.z = z; + } + s_cache[key] = e; + outX = e.x; outY = e.y; outZ = e.z; + return e.ok; +} + // ---- Ground-hazard classifiers (raid / dungeon generic avoidance) ---- // A ground effect is worth leaving when the spell HURTS whoever stands in // it: a direct damage effect, an aura dealing periodic damage, or a periodic @@ -1772,6 +1858,41 @@ static uint32 KeyForShutDoor(Player const* p, GameObject const* go) return 0; } +// A shut door whose lock `p` opens with a skill it has: a lock case that asks for a skill (Lockpicking, opened by Pick Lock) at or below +// the bot's value. A player with the skill casts the spell on the door (API::use_game_object casts it for the bot). Alcaz Prison's +// Maximum Security Door 649547 (lock 4295: Lockpicking 250, or the Overseer's Keyring 263992) stands between Overseer Wrex and the rest +// of the prison; on live a rogue picked it (Karrz's capture, 26 Nov: Pick Lock 1804, 5 s, and it stayed open). Same state and flag +// tests as KeyForShutDoor: GO_FLAG_LOCKED is what such a door carries. +static bool PickLockForShutDoor(Player const* p, GameObject const* go) +{ + if (go->GetGoType() != GAMEOBJECT_TYPE_DOOR || !go->isSpawned() || go->GetGoState() != GO_STATE_READY) + return false; + if (go->HasFlag(GameObjectFlags(GO_FLAG_IN_USE | GO_FLAG_INTERACT_COND | GO_FLAG_NOT_SELECTABLE))) + return false; + LockEntry const* lock = sLockStore.LookupEntry(go->GetGOInfo()->GetLockId()); + if (!lock) + return false; + for (uint8 li = 0; li < MAX_LOCK_CASE; ++li) + { + if (lock->Type[li] != LOCK_KEY_SKILL) + continue; + SkillType const skill = SkillByLockType(LockType(lock->Index[li])); + if (skill != SKILL_LOCKPICKING) + continue; + uint16 const value = p->GetSkillValue(skill); + if (value != 0 && value >= lock->Skill[li]) + return true; + // A rogue short of the lock: said once a minute (the builder runs every tick), so a party held at such a door shows why. + static std::atomic s_shortAt{ 0 }; + uint32 const now = getMSTime(); + uint32 was = s_shortAt.load(std::memory_order_relaxed); + if (p->HasSpell(1804) && getMSTimeDiff(was, now) > 60000 && s_shortAt.compare_exchange_strong(was, now)) + TC_LOG_INFO("playerbot.v2", "[pick_lock] {} cannot pick entry={}: Lockpicking {} of {}", p->GetName(), go->GetEntry(), + uint32(value), uint32(lock->Skill[li])); + } + return false; +} + // A chest the bot's dungeon lists as holding a door key (DungeonScript::key_chests: Fengus's Chest in Dire Maul North), spawned and // not yet opened. static bool IsListedKeyChest(Player const* p, GameObject const* go) @@ -1899,6 +2020,119 @@ SnapRecyclePool& RecyclePool() } // anonymous +// A boss that stands immune to players until one comes near: its SmartAI script makes it attackable on an out-of-combat +// line-of-sight event (event 10, action 144 with 0). Ruins of Lordaeron's Rath'mael 250657 stands at his ritual like that and wakes +// at 20 y; rol_full af61 (22 Nov) walked past him to The Baron and Bjork (boss_skipped), because every boss scan took him for +// not fightable. Cached per entry: the scripts are load-time data. +static bool BossWakesOnApproach(Creature const* c) +{ + static std::mutex s_mutex; + static std::unordered_map s_cache; + uint32 const entry = c->GetEntry(); + { + std::lock_guard lock(s_mutex); + if (auto it = s_cache.find(entry); it != s_cache.end()) + return it->second; + } + bool wakes = false; + for (SmartScriptHolder const& h : sSmartScriptMgr->GetScript(int32(entry), SMART_SCRIPT_TYPE_CREATURE)) + if (h.event.type == SMART_EVENT_OOC_LOS && h.action.type == SMART_ACTION_SET_IMMUNE_PC && !h.action.setImmunePC.immunePC) + wakes = true; + std::lock_guard lock(s_mutex); + s_cache.emplace(entry, wakes); + return wakes; +} + +// A listed boss the bot can fight now: alive, and a valid attack target for it, or hostile and asleep until a player comes near +// (BossWakesOnApproach). A boss that stands immune or unselectable until an event the bots do not run is not the next pull: with +// it in the boss scans the tank walked up to it and "pulled" it every 30 s while the attack never took. eea74327b3 +// uldaman_revelosh: Baelog (6906, the Lost Dwarves) at 23 y in sight, 120 s group_stalled; b3ca0b4b67 st_mijan: Weaver (5720). +static bool BossFightable(Player const* origin, Creature const* c) +{ + if (!c || !c->IsAlive()) + return false; + if (origin->IsValidAttackTarget(c)) + return true; + return c->IsImmuneToPC() && c->IsHostileTo(origin) && !c->IsInCombat() && + !c->HasUnitFlag(UnitFlags(UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_UNINTERACTIBLE)) && BossWakesOnApproach(c); +} + +// DungeonExecState::scan_bosses / scan_hostiles: the creatures the dungeon rules used to find with grid walks of their own on the +// bot workers (the boss scans, the lever and portal checks, the tank's next-pack scan). Here, during the snapshot build, no map is +// updating. Instances only; the advice is the one the rules will read for this snapshot. +static void BuildDungeonScan(Player* p, BotAI* bot_ai, BotSnapshot& snap) +{ + using DE = DungeonExecState; + DE& de = snap.dungeon_exec; + de.scan_bosses.clear(); + de.scan_hostiles.clear(); + Map* map = p->GetMap(); + if (!map || !map->IsDungeon() || map->IsBattlegroundOrArena() || !p->IsAlive()) + return; + // The tank runs the boss and pack scans; every member uses the lever and portal checks. The others' builds skip the walks. + Role const role = (bot_ai && bot_ai->role_override() != Role::Unknown) ? bot_ai->role_override() : snap.group.my_role; + bool const tank = role == Role::Tank; + DungeonAdvice const advice = Services::Dungeons().GetAdvice(BotSnapshotView(snap)); + if (!tank && advice.use_go_entries.empty() && advice.portal_hops.empty()) + return; + std::vector entries = advice.bosses; + for (DungeonAdvice::PortalHop const& hop : advice.portal_hops) + { + entries.push_back(hop.boss_entry); + entries.insert(entries.end(), hop.opened_by.begin(), hop.opened_by.end()); + } + if (!entries.empty()) + { + struct ScanBossCheck + { + std::vector const& entries; + bool operator()(Creature* c) const + { + if (!c || !c->IsAlive()) return false; + return std::find(entries.begin(), entries.end(), c->GetEntry()) != entries.end(); + } + }; + std::list found; + ScanBossCheck chk{ entries }; + Trinity::CreatureListSearcher searcher(p, found, chk); + Cell::VisitAllObjects(p, searcher, DE::kScanBossYd); + uint32 const now = GameTime::GetGameTimeMS(); + for (Creature* c : found) + { + if (!p->IsWithinDistInMap(c, DE::kScanBossYd)) + continue; + DE::ScanUnit u; + u.guid = c->GetGUID(); + u.entry = c->GetEntry(); + u.x = c->GetPositionX(); u.y = c->GetPositionY(); u.z = c->GetPositionZ(); + u.fightable = BossFightable(p, c); + u.in_los = p->IsWithinDistInMap(c, DE::kScanLosYd) && CachedLosCheck(p, c, now); + u.in_combat = c->IsInCombat(); + de.scan_bosses.push_back(u); + } + } + if (!tank) + return; + std::list hostiles; + Trinity::AnyUnfriendlyUnitInObjectRangeCheck hchk(p, p, DE::kScanHostileYd); + Trinity::UnitListSearcher hsearch(p, hostiles, hchk); + Cell::VisitAllObjects(p, hsearch, DE::kScanHostileYd); + for (Unit* u : hostiles) + { + Creature const* c = u ? u->ToCreature() : nullptr; + if (!c || !c->IsAlive() || c->IsCritter() || c->IsTotem() || c->GetCreatureType() == CREATURE_TYPE_NON_COMBAT_PET) + continue; + if (!p->IsValidAttackTarget(c)) + continue; + DE::ScanUnit su; + su.guid = c->GetGUID(); + su.entry = c->GetEntry(); + su.x = c->GetPositionX(); su.y = c->GetPositionY(); su.z = c->GetPositionZ(); + su.fightable = true; + de.scan_hostiles.push_back(su); + } +} + std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* bot_ai, SnapshotVer next_version, TickId tick) { if (!p || !p->IsInWorld()) return {}; @@ -2145,6 +2379,8 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b p->GetPhaseShift(), p->GetPositionX(), p->GetPositionY()); else snap->environment.water_surface_z = 0.0f; + // The breath the server counts, whatever state the bot was in: a fight under water used it up as much as a swim does. + snap->environment.breath_left_ms = p->GetMirrorTimerLeft(BREATH_TIMER); // Open-world water-escape FOCUS target (FIX #12). When the bot is in real // swim-water (a liquid that does not hurt), resolve the nearest DRY navmesh footing @@ -2662,6 +2898,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b { if (WorldSession const* sess = p->GetSession()) snap->players_own_character = !Services::Accounts().is_pool_account(sess->GetAccountId()); + snap->plays_as_human = Scenario::PlaysAsHuman(p); if (uint64 const owner_low = Services::Owners().OwnerCharacter(snap->bot_id)) { ObjectGuid owner_guid = ObjectGuid::Create(owner_low); @@ -2779,7 +3016,11 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // solo fleet that motivated the isLFGGroup() gate above). GetState is a // read-only, non-mutating getter (LFGMgr operator[]-insert bug fixed). if (p->GetGroup() && snap->instance_ctx.is_in_dungeon) - snap->lfg.in_dungeon = (sLFGMgr->GetState(p->GetGUID()) == lfg::LFG_STATE_DUNGEON); + { + lfg::LfgState const lfg_state = sLFGMgr->GetState(p->GetGUID()); + snap->lfg.in_dungeon = (lfg_state == lfg::LFG_STATE_DUNGEON); + snap->lfg.finished_dungeon = (lfg_state == lfg::LFG_STATE_FINISHED_DUNGEON); + } // Owned auctions across all four houses (Neutral=1, Alliance=2, Horde=6, // Goblin=7). Bots typically only post in their faction's house but might @@ -3688,6 +3929,17 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b if (snap->owner_in_group) if (Player const* owner = ObjectAccessor::FindConnectedPlayer(snap->owner_guid); owner && owner->GetMapId() == p->GetMapId()) snap->owner_dist = p->GetExactDist2d(owner); + // The leading player in the water near the bot: it follows him there (vile_reef_fight af60: the party swam down with the rogue + // who led it, idle:water_escape took each bot back to the bank between fights, the follow took it down again, and three bots + // went under and back up six times in a minute while the hunter drowned on the way out). + { + constexpr float kLeaderWaterYd = 100.0f; + ObjectGuid const lead = snap->owner_in_group ? snap->owner_guid : snap->led_by_player ? snap->controller_guid : ObjectGuid::Empty; + if (!lead.IsEmpty() && lead != p->GetGUID()) + if (Player const* l = ObjectAccessor::FindConnectedPlayer(lead); + l && l->IsAlive() && l->GetMapId() == p->GetMapId() && l->IsInWater() && p->GetExactDist2d(l) <= kLeaderWaterYd) + snap->leader_in_water = true; + } if (bot_ai) { snap->holding_position = bot_ai->holding_position(snap->published_at_ms); @@ -4351,6 +4603,18 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b ZLiquidStatus const vst = vmap->GetLiquidStatus(p->GetPhaseShift(), snap->combat.victim_x, snap->combat.victim_y, snap->combat.victim_z, {}, &vld); snap->combat.victim_in_damaging_liquid = (vst & MAP_LIQUID_STATUS_IN_CONTACT) != 0 && BotMovement::LiquidHurts(vld, vst); + // The bank a melee bot swings from (LiquidVictimBankSpot): only for a class that can fight in melee, out of reach now. + uint8 const bank_cls = p->GetClass(); + if (snap->combat.victim_in_damaging_liquid && p->IsAlive() && !snap->combat.victim_group_target && + bank_cls != CLASS_MAGE && bank_cls != CLASS_PRIEST && bank_cls != CLASS_WARLOCK && bank_cls != CLASS_HUNTER) + { + float const bdx = snap->combat.victim_x - p->GetPositionX(), bdy = snap->combat.victim_y - p->GetPositionY(); + float const bdz = snap->combat.victim_z - p->GetPositionZ(); + if (!MeleeReach::InReach(bdx * bdx + bdy * bdy + bdz * bdz, snap->combat.victim_reach)) + snap->combat.victim_bank_known = LiquidVictimBankSpot(p, vmap, snap->combat.victim, snap->combat.victim_x, + snap->combat.victim_y, snap->combat.victim_z, snap->combat.victim_reach, snap->published_at_ms, + snap->combat.victim_bank_x, snap->combat.victim_bank_y, snap->combat.victim_bank_z); + } } Pet const* threat_pet = p->GetPet(); auto fill_threat = [&](NearbyUnit& u, Unit* t) @@ -4573,6 +4837,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b boss_pause = bc->IsDungeonBoss() || bc->isWorldBoss() || bc->GetCreatureClassification() == CreatureClassifications::Obsolete; if (!u.untargetable && (!u.is_pacified || boss_pause) && u.hp > 0) ++snap->combat.fightable_attackers; + u.valid_attack_target = p->IsValidAttackTarget(a); fill_threat(u, a); snap->combat.attackers.push_back(u); } @@ -4604,6 +4869,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b if (Unit const* v = a->GetVictim()) u.victim = v->GetGUID(); u.is_player = a->GetTypeId() == TYPEID_PLAYER; + u.valid_attack_target = p->IsValidAttackTarget(a); if (u.hp > 0) ++snap->combat.fightable_attackers; snap->combat.attackers.push_back(u); @@ -5156,6 +5422,15 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b u.is_fleeing = mt == FLEEING_MOTION_TYPE || mt == TIMED_FLEEING_MOTION_TYPE || mt == ASSISTANCE_MOTION_TYPE; u.seeks_help = mt == ASSISTANCE_MOTION_TYPE; } + // The formation from the static table, not the live CreatureGroup: the load-time data is read-only here. + if (c->GetSpawnId()) + if (FormationInfo const* fi = sFormationMgr->GetFormationInfo(c->GetSpawnId())) + { + u.formation_leader = fi->LeaderSpawnId; + u.engage_calls_formation = fi->LeaderSpawnId == c->GetSpawnId() + ? (fi->GroupAI & FLAG_MEMBERS_ASSIST_LEADER) != 0 + : (fi->GroupAI & FLAG_LEADER_ASSISTS_MEMBER) != 0; + } // Uninteractible (NOT_SELECTABLE): unkillable, unacquirable hazard // stalkers. Engage/pull rules skip these; the in-combat advance // walks the tank through them. See NearbyUnit + the harbor note. @@ -7439,6 +7714,919 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b } } + // ---- Nearby GameObjects (30yd, capped, filtered by useful types) ---- + // Before the quest sections below: the actionable index, quest tools, turn-ins, offers, world quests and the companion + // quest help all read nearby_objects. Built after them, a quest object, ender or giver was never in the snapshot they saw + // (a summoned alt never handed in at an object, never used one and never took a quest from one: rows 240 and 250). + { + constexpr float SCAN_RADIUS = 30.0f; + constexpr size_t MAX_OBJECTS = 16; + thread_local std::vector scratch_gos; + scratch_gos.clear(); + scratch_gos.reserve(64); + Trinity::AllGameObjectsWithEntryInRange go_check(p, /*entry*/ 0, SCAN_RADIUS); + Trinity::GameObjectListSearcher searcher(p, scratch_gos, go_check); + Cell::VisitGridObjects(p, searcher, SCAN_RADIUS); + + // thread_local scratch reused across builds — mirrors the + // enemy/friend by_dist pattern. clear()+reserve() retains capacity + // so the per-build heap alloc is paid once per worker thread. + thread_local std::vector> by_dist; + by_dist.clear(); + by_dist.reserve(scratch_gos.size()); + for (GameObject* go : scratch_gos) + { + if (!go) continue; + // Filter to types bot logic actually drives. Skip everything else to + // keep the vector bounded — chairs, transports, etc would + // dominate the cap in major cities. GATHERING_NODE (50) is the + // modern herbalism/mining node type — without it in the + // snapshot, the `idle:gather` rule's `obj.go_type != 50` + // continue-skip would never find a candidate and the rule + // would never fire. + const uint8 t = go->GetGoType(); + const bool useful = + t == GAMEOBJECT_TYPE_MAILBOX || + t == GAMEOBJECT_TYPE_CHEST || + t == GAMEOBJECT_TYPE_GATHERING_NODE || + t == GAMEOBJECT_TYPE_FISHINGHOLE || + t == GAMEOBJECT_TYPE_QUESTGIVER || + t == GAMEOBJECT_TYPE_BINDER || + t == GAMEOBJECT_TYPE_GOOBER || + t == GAMEOBJECT_TYPE_MEETINGSTONE || + t == GAMEOBJECT_TYPE_GUILD_BANK || + // Quest-interaction GO types — needed by idle:quest_use_go + // (B4) so QUEST_OBJECTIVE_GAMEOBJECT (type 2) targets are + // visible. GENERIC covers most static quest props (banners, + // crates, books). BUTTON covers levers / switches. SPELL_FOCUS + // covers altars / runes that gate quest casts. + t == GAMEOBJECT_TYPE_GENERIC || + t == GAMEOBJECT_TYPE_BUTTON || + t == GAMEOBJECT_TYPE_SPELL_FOCUS || + // Cross-continent travel (Phase C). SPELLCASTER (22) is + // the static portal GO; TRANSPORT (11) is mooring rooms / + // elevators / etc; MO_TRANSPORT (15) is the seafaring + // ships and zeppelins that move between continents. The + // builder pre-resolves their destinations so the bot logic can + // walk to them and use/board. + t == GAMEOBJECT_TYPE_SPELLCASTER || + t == GAMEOBJECT_TYPE_TRANSPORT || + t == GAMEOBJECT_TYPE_MAP_OBJ_TRANSPORT || + // Battleground objectives. FLAGSTAND (24) covers AB/EotS/ + // BfG capturable nodes + AV banners + WSG/TP/BfG flag + // pedestals + IoC/SoTA/SS objective markers. FLAGDROP (26) + // covers dropped CTF flags. CAPTURE_POINT (42) is the + // modern WG/AV-style capture object — auto_use_go_types + // doesn't read it directly but BG node-state population + // walks it from a separate path; including here lets + // future scripts opt in via auto_use_go_types. Without + // these, idle:bg_use_objective_go silently no-ops for + // every BG that opts in, making node captures impossible. + t == GAMEOBJECT_TYPE_FLAGSTAND || + t == GAMEOBJECT_TYPE_FLAGDROP || + t == GAMEOBJECT_TYPE_CAPTURE_POINT || + // Modern BG mechanic GOs (BG audit N12/N25/N32/N67): the + // Cata+ CTF flags are NEW_FLAG (36) on the pedestal and + // NEW_FLAG_DROP (37) on the ground; EotS towers and the + // Silvershard cart zones are CONTROL_ZONE (29). These were + // missing from this filter, so idle:bg_use_objective_go + // could never SEE the very GOs the WSG/TP/EotS/Kotmogu + // scripts opt into via auto_use_go_types — flag and orb + // pickup was structurally impossible fleet-wide. + t == GAMEOBJECT_TYPE_NEW_FLAG || + t == GAMEOBJECT_TYPE_NEW_FLAG_DROP || + t == GAMEOBJECT_TYPE_CONTROL_ZONE || + // DESTRUCTIBLE_BUILDING (33): IoC keep gates + SoTA defense- + // line gates. The BG siege-vehicle fire rule scans these and + // casts the vehicle's gate-damage spell at the standing ones + // (is_destroyed below); without them in the snapshot a siege + // engine could never break a gate and the General was never + // reached (BG audit IoC / SoTA siege blockers). + t == GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING || + // TRAP (6): includes environmental hazards like bonfires + // and pyres. Builder classifies as hazard below if the + // trap's spell is hostile, so idle:flee_hazard can step + // the bot out of damage range. We DO want non-hostile + // traps in nearby_objects too (some quest scripts trigger + // off them), so the type passes the filter unconditionally. + t == GAMEOBJECT_TYPE_TRAP || + // RITUAL (18): an altar that needs several users (Uldaman's two altars, the UBRS Blackrock Altar). The group's + // bots fill the places a person in the group leaves open (ritual_join below). + t == GAMEOBJECT_TYPE_RITUAL || + // DOOR (0): only a shut one a player opens by hand (IsShutHandDoor, or named by the dungeon: IsListedShutHandDoor), + // or one that opens to a key this bot carries (KeyForShutDoor) or to its Lockpicking (PickLockForShutDoor), for + // idle:dungeon_open_hand_door. + (t == GAMEOBJECT_TYPE_DOOR && (IsShutHandDoor(go) || IsListedShutHandDoor(go) || KeyForShutDoor(p, go) != 0 || + PickLockForShutDoor(p, go))); + if (!useful) continue; + const float dx = go->GetPositionX() - p->GetPositionX(); + const float dy = go->GetPositionY() - p->GetPositionY(); + const float dz = go->GetPositionZ() - p->GetPositionZ(); + by_dist.emplace_back(dx*dx + dy*dy + dz*dz, go); + } + std::sort(by_dist.begin(), by_dist.end(), + [](auto const& a, auto const& b) { return a.first < b.first; }); + if (by_dist.size() > MAX_OBJECTS) by_dist.resize(MAX_OBJECTS); + + // An object's loot the bot has open (an herb or vein its gathering spell opened): the gather rule takes it. + snap->world_objects.loot_open = p->GetLootGUID().IsGameObject() ? p->GetLootGUID() : ObjectGuid::Empty; + snap->world_objects.nearby_objects.reserve(by_dist.size()); + for (auto const& [_, go] : by_dist) + { + BotSnapshot::NearbyObject n{}; + n.guid = go->GetGUID(); + n.entry = go->GetEntry(); + n.go_type = go->GetGoType(); + // [bgflag_diag] TEMP — confirm CTF flag GO (type 36) is in-snapshot on + // EotS(566)/TP(726), and which bot sees it (incl. distance via pos). + if ((p->GetMapId() == 726 || p->GetMapId() == 566) && go->GetGoType() == 36) + { + static thread_local uint32 s_bfAt = 0; + uint32 const bfn = getMSTime(); + if (bfn - s_bfAt > 5000) + { + s_bfAt = bfn; + TC_LOG_INFO("playerbot.v2", + "[bgflag_diag] map={} flagGO entry={} at ({:.0f},{:.0f},{:.0f}) " + "seen_by={} bot_pos=({:.0f},{:.0f},{:.0f})", + p->GetMapId(), go->GetEntry(), go->GetPositionX(), + go->GetPositionY(), go->GetPositionZ(), p->GetName(), + p->GetPositionX(), p->GetPositionY(), p->GetPositionZ()); + } + } + n.x = go->GetPositionX(); + n.y = go->GetPositionY(); + n.z = go->GetPositionZ(); + if (n.go_type == GAMEOBJECT_TYPE_RITUAL) + n.ritual_join = RitualNeedsBot(p, go); + n.hand_door = n.go_type == GAMEOBJECT_TYPE_DOOR; // the filter above lets in only a shut hand door + if (n.hand_door && !IsShutHandDoor(go) && !IsListedShutHandDoor(go)) + { + n.key_item = KeyForShutDoor(p, go); // a door only a key opens: the bot uses its key on it + n.pick_lock = n.key_item == 0 && PickLockForShutDoor(p, go); // or its Pick Lock + } + if (n.hand_door) + { + n.o = go->GetOrientation(); + n.auto_close = go->GetGOInfo()->GetAutoCloseTime() != 0; + } + if (n.go_type == GAMEOBJECT_TYPE_CHEST) + n.key_chest = IsListedKeyChest(p, go); + // Destructible gate breach state (IoC / SoTA) so the siege-fire + // rule skips already-down gates and advances to the next line. + if (n.go_type == GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING) + n.is_destroyed = + go->GetDestructibleState() == GO_DESTRUCTIBLE_DESTROYED; + // Herb / ore vein: a chest whose lock asks for Herbalism or Mining (the gathering rules, GatheringRules.cpp). + if (n.go_type == GAMEOBJECT_TYPE_CHEST) + if (LockEntry const* lock = sLockStore.LookupEntry(go->GetGOInfo()->GetLockId())) + for (uint8 li = 0; li < MAX_LOCK_CASE; ++li) + { + if (lock->Type[li] != LOCK_KEY_SKILL) + continue; + SkillType const sk = SkillByLockType(LockType(lock->Index[li])); + if (sk != SKILL_HERBALISM && sk != SKILL_MINING) + continue; + n.gather_skill = uint16(sk); + n.gather_req = lock->Skill[li]; + n.gather_ready = go->isSpawned() && go->getLootState() == GO_READY; + break; + } + // Pre-resolve teleport destination for SPELLCASTER GOs. + // Type 22 stores its triggered spell in spellCaster.spell. + // The spell's destination is in the spell_target_position + // table (loaded once at server start, read-only thereafter + // — safe to query from this snapshot path). Most type-22 + // GOs are altars / event triggers without a teleport effect; + // for those, GetSpellTargetPosition returns null and the + // teleport_dest_* fields stay zero. + if (n.go_type == GAMEOBJECT_TYPE_SPELLCASTER) + { + if (GameObjectTemplate const* tmpl = go->GetGOInfo()) + { + const uint32 spell_id = tmpl->spellCaster.spell; + if (spell_id != 0) + { + // Resolve the teleport destination through the SHARED + // PortalIndex resolver, which scans all effect indices + // AND follows the FORCE_CAST/TRIGGER_SPELL indirection + // modern portals use. The GO's own spell often carries + // no spell_target_position: either the teleport sits on + // a non-zero effect index (~156 portals server-wide), or + // the spell merely FORCE_CASTs the real teleport (e.g. + // Org's Undercity portal 293684 -> 17611 -> 121862 -> + // map 0). Either way the old direct scan left + // teleport_dest_map=0, so the in-range use_portal gate + // (dest must match the goal map) skipped the portal and + // the bot walked to it but never used it. Using the same + // resolver as PortalIndex keeps the snapshot and the + // travel graph in lockstep. + uint32 dmap = 0; + float dtx = 0.f, dty = 0.f, dtz = 0.f; + if (Playerbot::V2::Travel::ResolvePortalSpellDest(spell_id, dmap, dtx, dty, dtz)) + { + n.teleport_dest_map = dmap; + n.teleport_dest_x = dtx; + n.teleport_dest_y = dty; + n.teleport_dest_z = dtz; + } + } + } + } + // Hazard classification for TRAP-type GOs (bonfires, pyres, + // lava grates). We mark a trap as a hazard when its trap + // spell is hostile (SpellInfo::IsPositive() == false). The + // hazard_radius is the radius the core fires the trap at (see + // below). idle:flee_hazard + // uses both fields to step the bot 5y past the radius so it + // stops standing inside a bonfire and dying. + else if (n.go_type == GAMEOBJECT_TYPE_TRAP) + { + if (GameObjectTemplate const* tmpl = go->GetGOInfo()) + { + const uint32 trap_spell = tmpl->trap.spell; + if (trap_spell != 0) + { + if (SpellInfo const* si = sSpellMgr->GetSpellInfo(trap_spell, DIFFICULTY_NONE)) + { + if (!si->IsPositive()) + { + // The core halves the radius only for an owned trap (GameObject::Update, since 2026-10-16); a + // world trap fires at the full radius. Halving every trap left bots 6-11 y from Majordomo's + // Intense Heat pit (20533, radius 10) thinking they stood clear: 17 of the 43 deaths in + // release-0130 mc_majordomo were that pit. + n.is_hazard = true; + n.hazard_radius = go->GetOwnerGUID().IsEmpty() ? float(tmpl->trap.radius) + : tmpl->trap.radius / 2.0f; + } + } + } + } + } + // Continental transport (ship / zeppelin). Same teleport_dest + // semantics: bot logic walks to the transport, server auto-attaches + // the bot as a passenger when the bounding box overlaps, the + // transport carries them across maps, and the bot's same-map + // rules pick up at the destination dock. We populate the + // FIRST destination map that isn't the bot's current map — + // most transports cycle between exactly two continents, so + // there's no ambiguity. (Multi-stop tours like the Pandaria + // cruise are rare and not worth special-casing.) + // ONLY type-15 MAP_OBJ_TRANSPORT (cross-map ships/zeppelins) get a + // cross-map destination. Type-11 GAMEOBJECT_TYPE_TRANSPORT here is a + // local animated LIFT (Orgrimmar zeppelin-tower elevators, city + // lifts) — same-map, no TransportTemplate. It is still pushed to + // nearby_objects (the elevator rules find it), but with NO + // teleport_dest_map (stays kInvalidMapId), so the cross-map board + // rule never targets it. Old code accepted type-11 too; an elevator + // with no template kept the default dest, and when that default was + // 0 (== Eastern Kingdoms, a real map) the bot boarded the lift as if + // it were the EK zeppelin and rode it up and down forever. + else if (n.go_type == GAMEOBJECT_TYPE_MAP_OBJ_TRANSPORT) + { + if (TransportTemplate const* tt = + sTransportMgr->GetTransportTemplate(go->GetEntry())) + { + for (uint32 map_id : tt->MapIds) + { + if (map_id != p->GetMapId()) + { + n.teleport_dest_map = map_id; + // No exact dest coords — the transport drops + // the passenger at its dock spawn, which the + // Bot logic doesn't strictly need to plan; we just + // need to know "this transport reaches the + // goal map". + break; + } + } + } + } + // Type-11 local lift (Orgrimmar zeppelin-tower elevators, city / + // raid lifts). We're on the WORLD THREAD here with the live navmesh + // and the bot is physically near this elevator (it's in range of the + // grid scan), so this is the right place to lazily derive the stop's + // walkable board/disembark LEDGES (nearest navmesh poly beside each + // platform-centre). Cheap after the first encounter — every stop's + // result is cached in ElevatorIndex. The elevator rules then read the + // ledge via ElevatorIndex::LedgeFor on the bot worker. + else if (n.go_type == GAMEOBJECT_TYPE_TRANSPORT) + { + // Derive ledges for the WHOLE nearby lift cluster (not just this + // GO), so the boardable-lift preference can compare sibling lifts + // immediately (e.g. the two Org zeppelin lifts ~150y apart — one + // boardable, one a pit). Cheap + cached after the first pass. + V2::Travel::ElevatorIndex::Instance().EnsureLedgesNear(p, /*range*/ 200.0f); + } + snap->world_objects.nearby_objects.push_back(n); + } + + // ---- MO-transport scan (ships / zeppelins) ---- + // Continental transports (GAMEOBJECT_TYPE_MAP_OBJ_TRANSPORT 15 = boats, + // and the cross-map TRANSPORT 11 = zeppelins) live in Map::_transports, + // NOT the grid, so the Cell::VisitGridObjects scan above NEVER returns + // them. That left every cross-map boarding rule blind: 0 bots boarded a + // ship fleet-wide despite 98K+ walk_to_known_dock fires — the dominant + // cause of the leveling stall (bots can't reach off-continent quests). + // Scan the map's transport set directly and add any nearby continental + // transport (one with a destination map != current) so a bot waiting at + // a dock can SEE its docked ship and board it. Generous radius — the bot + // waits on the pier, tens of yards from the ship's moving pivot. Few + // transports exist per map, so this is cheap; we bypass the 16-object + // cap above because transports are rare and always travel-relevant. + if (Map* tmap = p->GetMap()) + { + constexpr float kTransportScanSq = 200.0f * 200.0f; + for (Transport* tr : tmap->GetTransports()) + { + if (!tr) continue; + const uint8 tt = tr->GetGoType(); + if (tt != GAMEOBJECT_TYPE_TRANSPORT && + tt != GAMEOBJECT_TYPE_MAP_OBJ_TRANSPORT) continue; + const float tdx = tr->GetPositionX() - p->GetPositionX(); + const float tdy = tr->GetPositionY() - p->GetPositionY(); + const float tdz = tr->GetPositionZ() - p->GetPositionZ(); + if (tdx*tdx + tdy*tdy + tdz*tdz > kTransportScanSq) continue; + BotSnapshot::NearbyObject n{}; + n.guid = tr->GetGUID(); + n.entry = tr->GetEntry(); + n.go_type = tt; + n.x = tr->GetPositionX(); + n.y = tr->GetPositionY(); + n.z = tr->GetPositionZ(); + // Resolve the transport's destination continent (first MapId + // that isn't the bot's current map) — mirrors the grid-GO + // transport handling so the boarding rule's dest match works. + if (TransportTemplate const* ttpl = + sTransportMgr->GetTransportTemplate(tr->GetEntry())) + { + for (uint32 map_id : ttpl->MapIds) + { + if (map_id != p->GetMapId()) + { + n.teleport_dest_map = map_id; + break; + } + } + } + snap->world_objects.nearby_objects.push_back(n); + } + + // Tram cars (type-11 GOs that run between two stations on one map, the Deeprun Tram): they sit in the grid, so the + // MO-transport set above never holds them, and the 30 y object scan only sees one standing right beside the bot. A + // bot waiting on the platform for a ride looked at "transports in sight 0" for 300 s, then gave the route up. The + // cars are few and known (PortalIndex), so look them up by spawn id within the same 200 y. + if (Services::Initialized() && Services::Portals().IsInitialized()) + { + auto const& car_ids = Services::Portals().ShuttleSpawnIds(p->GetMapId()); + if (!car_ids.empty()) + { + static std::atomic s_carLogAt{0}; + uint32 const cnow = GameTime::GetGameTimeMS(); + uint32 last = s_carLogAt.load(std::memory_order_relaxed); + if (cnow - last >= 120000u && s_carLogAt.compare_exchange_strong(last, cnow ? cnow : 1u)) + { + size_t in_world = 0; + for (uint64 const id : car_ids) + if (GameObject* c = tmap->GetGameObjectBySpawnId(id); c && c->IsInWorld()) ++in_world; + TC_LOG_INFO("playerbot.v2", "[xport_cars] map {}: {} tram cars known, {} in the world; {} sees {:.0f},{:.0f},{:.0f}", + p->GetMapId(), car_ids.size(), in_world, p->GetName(), p->GetPositionX(), p->GetPositionY(), p->GetPositionZ()); + } + } + for (uint64 const spawn_id : car_ids) + { + GameObject* car = tmap->GetGameObjectBySpawnId(spawn_id); + if (!car || !car->IsInWorld()) continue; + const float cdx = car->GetPositionX() - p->GetPositionX(); + const float cdy = car->GetPositionY() - p->GetPositionY(); + const float cdz = car->GetPositionZ() - p->GetPositionZ(); + if (cdx*cdx + cdy*cdy + cdz*cdz > kTransportScanSq) continue; + bool const have = std::any_of(snap->world_objects.nearby_objects.begin(), snap->world_objects.nearby_objects.end(), + [&](BotSnapshot::NearbyObject const& o) { return o.guid == car->GetGUID(); }); + if (have) continue; + BotSnapshot::NearbyObject n{}; + n.guid = car->GetGUID(); + n.entry = car->GetEntry(); + n.go_type = car->GetGoType(); + n.x = car->GetPositionX(); + n.y = car->GetPositionY(); + n.z = car->GetPositionZ(); + snap->world_objects.nearby_objects.push_back(n); + } + } + } + + // ---- Extended gathering-node scan (200y) ---- + // The 30y nearby_objects scan above covers vendor / quest-giver + // / chest interactions where the bot is typically at the giver. + // For gathering nodes we want a much wider horizon so the bot can + // SEE a node from across a clearing and walk toward it. Per the + // user's design: 40y attract in Questing mode (opportunistic), + // 150-200y attract in Professioning mode (active seeking). + // Snapshot exposes nodes up to 200y; the rule picks attract radius + // based on the bot's activity_mode. + // + // Cost: O(creatures+GOs within 200y) extra cell visit, gated to + // bots that have at least one gathering skill — non-gatherers see + // no overhead. The append is filtered to GATHERING_NODE / FISHINGHOLE + // / CHEST(gather variant) so it doesn't pollute nearby_objects with + // unrelated GOs. + constexpr uint16 kHerbalismSk = 182; + constexpr uint16 kMiningSk = 186; + constexpr uint16 kSkinningSk = 393; + constexpr uint16 kFishingSk = 356; + const bool has_any_gather = + p->HasSkill(kHerbalismSk) || p->HasSkill(kMiningSk) || + p->HasSkill(kSkinningSk) || p->HasSkill(kFishingSk); + // Per-bot 1Hz throttle on the 200y gather-node Cell::VisitGridObjects. + // Same rationale as the hub scan above: nodes are static; the + // 30y nearby_objects scan still gives near-bot coverage every tick. + BotAI* gs_ai = bot_ai; + const uint32 gather_now_ms = GameTime::GetGameTimeMS(); + constexpr uint32 kGatherScanIntervalMs = 1000u; + const bool gather_throttled = gs_ai && + gs_ai->last_gather_scan_ms() != 0 && + (gather_now_ms - gs_ai->last_gather_scan_ms()) < kGatherScanIntervalMs; + if (has_any_gather && !gather_throttled) + { + if (gs_ai) gs_ai->set_last_gather_scan_ms(gather_now_ms); + constexpr float EXT_GATHER_RADIUS = 200.0f; + constexpr size_t EXT_GATHER_MAX = 32; + // Same thread_local + reserve(64) pattern as the 30y scan + // above. Distinct buffer (`ext_gos`) because both scans can + // appear in the same Build pass; reusing the same buffer + // would corrupt the 30y result. + thread_local std::vector scratch_ext_gos; + scratch_ext_gos.clear(); + scratch_ext_gos.reserve(128); + Trinity::AllGameObjectsWithEntryInRange ext_check(p, /*entry*/ 0, EXT_GATHER_RADIUS); + Trinity::GameObjectListSearcher ext_searcher(p, scratch_ext_gos, ext_check); + Cell::VisitGridObjects(p, ext_searcher, EXT_GATHER_RADIUS); + + std::unordered_set ext_seen; + ext_seen.reserve(snap->world_objects.nearby_objects.size() + 16); + for (auto const& nb : snap->world_objects.nearby_objects) + ext_seen.insert(nb.guid); + + std::vector> ext_by_dist; + ext_by_dist.reserve(scratch_ext_gos.size()); + for (GameObject* go : scratch_ext_gos) + { + if (!go) continue; + const uint8 t = uint8(go->GetGoType()); + if (t != GAMEOBJECT_TYPE_GATHERING_NODE && + t != GAMEOBJECT_TYPE_FISHINGHOLE) continue; + if (ext_seen.count(go->GetGUID())) continue; + const float dx = go->GetPositionX() - p->GetPositionX(); + const float dy = go->GetPositionY() - p->GetPositionY(); + const float dz = go->GetPositionZ() - p->GetPositionZ(); + ext_by_dist.emplace_back(dx*dx + dy*dy + dz*dz, go); + } + std::sort(ext_by_dist.begin(), ext_by_dist.end(), + [](auto const& a, auto const& b) { return a.first < b.first; }); + if (ext_by_dist.size() > EXT_GATHER_MAX) ext_by_dist.resize(EXT_GATHER_MAX); + for (auto const& [_, go] : ext_by_dist) + { + BotSnapshot::NearbyObject n{}; + n.guid = go->GetGUID(); + n.entry = go->GetEntry(); + n.go_type = go->GetGoType(); + n.x = go->GetPositionX(); + n.y = go->GetPositionY(); + n.z = go->GetPositionZ(); + snap->world_objects.nearby_objects.push_back(n); + } + } + + // ---- Spell-based ground-hazard scan (G-P1c) ---- + // Modern boss "stand in fire" mechanics are NOT GameObject traps + // (handled above). They are DynamicObject area-spell entities + // (classic voidzones / Consecration-like ground effects) and + // AreaTrigger entities (the modern shape-based ground effects used + // by virtually every retail boss). Neither is reachable through the + // GameObject scan, so without this pass the bot has no snapshot + // signal that it is standing in a damage patch — idle:flee_hazard + // and the in-combat dungeon-positioning path (G-P0a) both consume + // is_hazard / hazard_radius NearbyObject entries and step the bot + // out, so feeding these two entity classes into nearby_objects is + // all that is required to make bots dodge fire. + // + // PERF: this is the hottest path (200-2000 bots, ~20K Builds/s + // post-throttle). Hazards only matter while the bot is fighting, so + // the ENTIRE scan is gated behind p->IsInCombat() — the ~95% idle + // fleet pays nothing (not even the cell visit). When it does run we + // restrict the grid map-type mask to DYNAMICOBJECT | AREATRIGGER so + // VisitAllObjects skips creatures, players, and GameObjects + // entirely, and we cap the appended hazards to the closest few. + // Instance extension (raid / dungeon ground-hazard avoidance): inside a + // dungeon or raid map the scan also runs out of combat - a healer + // walking up to the fight, or a bot whose combat flag dropped between + // pulls, must still see the Rain of Fire it is standing in - and it + // additionally feeds snap->combat.ground_hazards (spell / caster / + // radius, damage-classified) for the [raid_hazard] step-out. The + // nearby_objects is_hazard feed below keeps its original in-combat + // gate. Battlegrounds stay excluded (instance maps, not dungeons). + Map const* haz_map = p->GetMap(); + const bool haz_instance = haz_map && haz_map->IsDungeon() && !haz_map->IsBattlegroundOrArena(); + const bool haz_combat = p->IsInCombat(); + if (haz_combat || haz_instance) + { + constexpr float HAZ_SCAN_RADIUS = 40.0f; + constexpr size_t HAZ_MAX = 12; + // Reuse the WorldObjectListSearcher + AllWorldObjectsInRange + // pattern (same as the TC core scripts), but constrain the + // visited grid containers to the two hazard-bearing types via + // the searcher's mapTypeMask so the visit never touches the + // (far larger) creature / player / GO maps. + thread_local std::vector scratch_haz; + scratch_haz.clear(); + scratch_haz.reserve(32); + Trinity::AllWorldObjectsInRange haz_check(p, HAZ_SCAN_RADIUS); + Trinity::WorldObjectListSearcher haz_searcher( + p, scratch_haz, haz_check, + GRID_MAP_TYPE_MASK_DYNAMICOBJECT | GRID_MAP_TYPE_MASK_AREATRIGGER); + Cell::VisitAllObjects(p, haz_searcher, HAZ_SCAN_RADIUS); + + // Each candidate carries (dist^2, position, radius). We resolve + // the spell + caster, apply the hostile-and-non-positive gate, + // then sort by distance and keep the closest HAZ_MAX so a + // densely-stacked AoE encounter can't blow past the cap. + struct HazCand + { + float d2; float x, y, z, radius; ObjectGuid guid; + uint32 spell; ObjectGuid caster; bool hurts; GroundHazardSource src; + }; + std::vector haz_by_dist; + haz_by_dist.reserve(scratch_haz.size()); + + // Shared classifier: a ground effect is a hazard when its + // creating spell is hostile (SpellInfo::IsPositive() == false) + // AND its caster is NOT friendly to the bot. A friendly + // Consecration / Healing Rain / Death and Decay cast by the bot + // or a party member must never be flagged. When the caster is + // absent (despawned / environmental), we treat a non-positive + // spell as an environmental hazard (e.g. lingering fire). When + // the spell is positive, we never flag — that is the safe + // default for indeterminate hostility. + auto isHostileGround = [&](SpellInfo const* si, Unit* caster) -> bool + { + if (!si || si->IsPositive()) + return false; // positive => never a hazard + if (!caster) + return true; // no caster => environmental hazard + return !caster->IsFriendlyTo(p); // hostile / neutral non-friendly only + }; + + for (WorldObject* wo : scratch_haz) + { + if (!wo) continue; + + if (DynamicObject const* dyn = wo->ToDynObject()) + { + SpellInfo const* si = dyn->GetSpellInfo(); + if (!isHostileGround(si, dyn->GetCaster())) + continue; + const float dx = dyn->GetPositionX() - p->GetPositionX(); + const float dy = dyn->GetPositionY() - p->GetPositionY(); + const float dz = dyn->GetPositionZ() - p->GetPositionZ(); + haz_by_dist.push_back({ dx*dx + dy*dy + dz*dz, + dyn->GetPositionX(), dyn->GetPositionY(), dyn->GetPositionZ(), + dyn->GetRadius(), dyn->GetGUID(), + dyn->GetSpellId(), dyn->GetCasterGUID(), SpellHurtsInArea(si), + GroundHazardSource::DynObject }); + } + else if (AreaTrigger const* at = wo->ToAreaTrigger()) + { + // AreaTrigger exposes only the spell id; resolve the + // SpellInfo through SpellMgr (DIFFICULTY_NONE matches the + // GO-trap classifier above). GetMaxSearchRadius() returns + // the largest extent of the trigger's current shape + // (sphere / box / polygon bounding radius incl. scale), + // which is the conservative radius we want the bot to + // clear. + SpellInfo const* si = sSpellMgr->GetSpellInfo(at->GetSpellId(), DIFFICULTY_NONE); + if (!isHostileGround(si, at->GetCaster())) + continue; + const float dx = at->GetPositionX() - p->GetPositionX(); + const float dy = at->GetPositionY() - p->GetPositionY(); + const float dz = at->GetPositionZ() - p->GetPositionZ(); + // Damage test: the creating spell itself, else the + // template's CAST / ADDAURA actions aimed at enemies + // (the data-driven AT shape). A scripted AT (no + // actions - AreaTriggerAI applies the effect) is taken + // on the hostile-non-positive verdict above. + bool at_hurts = SpellHurtsInArea(si); + if (!at_hurts) + { + AreaTriggerTemplate const* att = at->GetTemplate(); + if (!att || att->Actions.empty()) + at_hurts = true; + else + for (AreaTriggerAction const& act : att->Actions) + { + if (act.ActionType != AREATRIGGER_ACTION_CAST && + act.ActionType != AREATRIGGER_ACTION_ADDAURA) + continue; + if (act.TargetType != AREATRIGGER_ACTION_USER_ANY && + act.TargetType != AREATRIGGER_ACTION_USER_ENEMY) + continue; + if (SpellHurtsInArea(sSpellMgr->GetSpellInfo(act.Param, DIFFICULTY_NONE))) + { at_hurts = true; break; } + } + } + haz_by_dist.push_back({ dx*dx + dy*dy + dz*dz, + at->GetPositionX(), at->GetPositionY(), at->GetPositionZ(), + at->GetMaxSearchRadius(), at->GetGUID(), + at->GetSpellId(), at->GetCasterGuid(), at_hurts, + GroundHazardSource::AreaTrigger }); + } + } + + std::sort(haz_by_dist.begin(), haz_by_dist.end(), + [](HazCand const& a, HazCand const& b) { return a.d2 < b.d2; }); + + // ---- combat.ground_hazards (raid / dungeon step-out feed) ---- + // Instances only (the consumer is the dungeon / raid cascade). + // Three sources, merged closest-first and capped at + // kMaxGroundHazards: the damaging DynamicObject / AreaTrigger + // zones above (centre within 30y), trigger creatures pulsing a + // damage aura (void zone, poison cloud - from this Build's 40y + // unfriendly-unit scratch, filled by the merged enemy+friend + // scan), and hostile damaging trap GameObjects already in + // nearby_objects. + if (haz_instance) + { + constexpr float kGroundHazRange = 30.0f; + auto& gh = snap->combat.ground_hazards; + thread_local std::vector> gh_by_dist; + gh_by_dist.clear(); + for (HazCand const& h : haz_by_dist) + { + if (!h.hurts || h.radius <= 0.0f) continue; + if (h.d2 > kGroundHazRange * kGroundHazRange) continue; + gh_by_dist.push_back({ h.d2, GroundHazard{ h.x, h.y, h.z, h.radius, + h.spell, h.caster, h.src } }); + } + for (Unit* t : scratch_enemies_tl()) + { + Creature const* c = t ? t->ToCreature() : nullptr; + if (!c || !c->IsAlive() || c->IsFriendlyTo(p)) continue; + const float dx = c->GetPositionX() - p->GetPositionX(); + const float dy = c->GetPositionY() - p->GetPositionY(); + const float dz = c->GetPositionZ() - p->GetPositionZ(); + const float d2 = dx*dx + dy*dy + dz*dz; + if (d2 > kGroundHazRange * kGroundHazRange) continue; + uint32 zone_spell = 0; + const float r = TriggerCreatureZone(c, zone_spell); + if (r <= 0.0f) continue; + ObjectGuid const owner = !c->GetCreatorGUID().IsEmpty() ? c->GetCreatorGUID() + : c->GetGUID(); + gh_by_dist.push_back({ d2, GroundHazard{ c->GetPositionX(), c->GetPositionY(), + c->GetPositionZ(), r, zone_spell, owner, + GroundHazardSource::TriggerCreature } }); + } + for (auto const& o : snap->world_objects.nearby_objects) + { + if (!o.is_hazard || o.entry == 0 || o.hazard_radius <= 0.0f) continue; + GameObject const* go = ObjectAccessor::GetGameObject(*p, o.guid); + if (!go) continue; + GameObjectTemplate const* tmpl = go->GetGOInfo(); + if (!tmpl || tmpl->type != GAMEOBJECT_TYPE_TRAP) continue; + SpellInfo const* tsi = sSpellMgr->GetSpellInfo(tmpl->trap.spell, DIFFICULTY_NONE); + if (!SpellHurtsInArea(tsi)) continue; + if (Unit const* owner = go->GetOwner()) + if (owner->IsFriendlyTo(p)) continue; // a friendly hunter's trap + const float dx = o.x - p->GetPositionX(); + const float dy = o.y - p->GetPositionY(); + const float dz = o.z - p->GetPositionZ(); + const float d2 = dx*dx + dy*dy + dz*dz; + if (d2 > kGroundHazRange * kGroundHazRange) continue; + gh_by_dist.push_back({ d2, GroundHazard{ o.x, o.y, o.z, o.hazard_radius, + tmpl->trap.spell, go->GetOwnerGUID(), + GroundHazardSource::GoTrap } }); + } + std::sort(gh_by_dist.begin(), gh_by_dist.end(), + [](auto const& a, auto const& b) { return a.first < b.first; }); + if (gh_by_dist.size() > kMaxGroundHazards) gh_by_dist.resize(kMaxGroundHazards); + gh.reserve(gh_by_dist.size()); + for (auto const& [_, h] : gh_by_dist) + gh.push_back(h); + } + + if (haz_by_dist.size() > HAZ_MAX) haz_by_dist.resize(HAZ_MAX); + + for (auto const& h : haz_by_dist) + { + if (!haz_combat) break; // nearby_objects feed: original in-combat gate + BotSnapshot::NearbyObject n{}; + n.guid = h.guid; + // entry / go_type stay 0 — these are not GameObjects. The + // consumer keys off is_hazard / hazard_radius, not go_type. + n.x = h.x; + n.y = h.y; + n.z = h.z; + n.is_hazard = true; + n.hazard_radius = h.radius; + snap->world_objects.nearby_objects.push_back(n); + } + } + + // ---- combat.tank_los (raid / dungeon LoS step feed) ---- + // LoS from the bot to every live same-map group tank (threat_tanks, + // built with group_tank above), through the TTL-cached raycast the + // nearby scans use. In combat inside an instance only: the + // [raid_los] step (State_InCombat) is its sole consumer, and a raid + // has at most a handful of tanks. + if (haz_combat && haz_instance) + { + const uint32 los_now = GameTime::GetGameTimeMS(); + for (Unit const* tk : threat_tanks) + { + if (!tk || tk == p) continue; + if (snap->combat.tank_los.size() >= 8) break; + snap->combat.tank_los.push_back({ tk->GetGUID(), CachedLosCheck(p, tk, los_now) }); + } + } + + // ---- Quest-relevant GameObject expansion (POI-aware) ---- + // Mirrors the "quest-target neutral creature" expansion above: the + // baseline 30y nearby_objects scan misses GameObjects that are + // 50-150y from the bot. Many ITEM-objective quests source their + // item from a *lootable GO* (Quest 29401/29412 "Blown Away" loots + // item 71034 from balloons scattered around Razor Hill). The bot + // arrives at the POI center but the balloons cluster 100+ yards + // away across the POI polygon — outside 30y, so nearby_objects is + // empty and idle:quest_use_go silently no-ops. + // + // Strategy: build the set of (a) entries directly named by an + // active QUEST_OBJECTIVE_GAMEOBJECT, and (b) item-ids the active + // QUEST_OBJECTIVE_ITEM rows need; then do a wider scan and admit + // a GO if (a) matches its entry OR (b) intersects with its quest + // item drop list. Two-pass radii (80y around bot + 160y around + // POI when the bot is within 50y of POI) mirror the creature + // expansion above. + if (!snap->quest_log.quests.empty()) + { + std::unordered_set q_go_entries; + std::unordered_set q_item_ids; + q_go_entries.reserve(8); + q_item_ids.reserve(8); + for (auto const& q : snap->quest_log.quests) + { + if (q.state != 0) continue; // 0 = INCOMPLETE + for (auto const& oe : q.objectives) + { + if (oe.progress >= oe.amount) continue; + if (oe.type == QUEST_OBJECTIVE_GAMEOBJECT && oe.object_id > 0) + q_go_entries.insert(uint32(oe.object_id)); + else if (oe.type == QUEST_OBJECTIVE_ITEM && oe.object_id > 0) + q_item_ids.insert(uint32(oe.object_id)); + } + } + + if (!q_go_entries.empty() || !q_item_ids.empty()) + { + std::vector q_pool; + + // ---- Tier 1.3 (behavior-preserving): single-traversal reuse ---- + // The original ran TWO bot-centered VisitGridObjects passes: an + // 80y pass (always) and a 160y pass (when sitting on a POI), + // concatenating both into q_pool. The 160y pass re-walks every + // cell the 80y pass already walked (same center, GameObjects, + // AllGameObjectsWithEntryInRange uses IsWithinDist), so the + // 80y grid traversal is pure duplicate work whenever the wide + // pass fires. + // + // We reuse a SINGLE traversal: when the wide pass fires we walk + // 160y ONCE and reconstruct q_pool with the IDENTICAL multiset + // the two-pass code produced — every GO within 80y appears + // TWICE (once for the would-be 80y pass, once for the 160y + // pass) and every 80–160y GO appears once. Order within q_pool + // does NOT affect output here because q_by_dist below is SORTED + // by distance before the cap, so the membership after sort+cap + // depends only on the (distance,go) MULTISET — which is + // preserved exactly, including the duplicate-occupies-two-slots + // cap interaction of the original. When the wide pass does NOT + // fire we keep the plain single 80y traversal. + bool wide_fires = false; + { + auto const& poi = snap->quest_log.current_objective_poi; + if (poi.valid && poi.map_id == snap->position.map_id) + { + const float pdx = poi.x - p->GetPositionX(); + const float pdy = poi.y - p->GetPositionY(); + const float pdz = poi.z - p->GetPositionZ(); + const float poi_dist_sq = pdx*pdx + pdy*pdy + pdz*pdz; + wide_fires = (poi_dist_sq < (50.0f * 50.0f)); + } + } + + if (!wide_fires) + { + // Narrow-only: exactly the original 80y pass. + thread_local std::vector scratch_q_gos; + scratch_q_gos.clear(); + scratch_q_gos.reserve(128); + constexpr float kQGoRadiusBot = 80.0f; + Trinity::AllGameObjectsWithEntryInRange q_check(p, /*entry*/ 0, kQGoRadiusBot); + Trinity::GameObjectListSearcher q_searcher(p, scratch_q_gos, q_check); + Cell::VisitGridObjects(p, q_searcher, kQGoRadiusBot); + q_pool.insert(q_pool.end(), scratch_q_gos.begin(), scratch_q_gos.end()); + } + else + { + // Wide fires: single 160y traversal, then rebuild the exact + // [80y-subset] ++ [full-160y] multiset the two passes made. + thread_local std::vector scratch_q_gos_poi; + scratch_q_gos_poi.clear(); + scratch_q_gos_poi.reserve(256); + constexpr float kQGoRadiusPOI = 160.0f; + constexpr float kQGoRadiusBot = 80.0f; + Trinity::AllGameObjectsWithEntryInRange q_check_poi(p, /*entry*/ 0, kQGoRadiusPOI); + Trinity::GameObjectListSearcher q_searcher_poi(p, scratch_q_gos_poi, q_check_poi); + Cell::VisitGridObjects(p, q_searcher_poi, kQGoRadiusPOI); + + // Segment 1 — reproduces the would-be 80y pass: every GO + // the 160y result holds that is also within 80y. We re-use + // the EXACT predicate AllGameObjectsWithEntryInRange applied + // (IsWithinDist with is3D=false / 2D), so this membership is + // identical to the dropped 80y pass. + q_pool.reserve(scratch_q_gos_poi.size() * 2); + for (GameObject* go : scratch_q_gos_poi) + if (go && p->IsWithinDist(go, kQGoRadiusBot, /*is3D*/ false)) + q_pool.push_back(go); + // Segment 2 — the full 160y pass. + q_pool.insert(q_pool.end(), scratch_q_gos_poi.begin(), scratch_q_gos_poi.end()); + } + + std::unordered_set already_in; + already_in.reserve(snap->world_objects.nearby_objects.size() + 16); + for (auto const& nb : snap->world_objects.nearby_objects) + already_in.insert(nb.guid); + + // Sort candidates by distance so we keep the closest ones + // first under the per-bot append cap. + std::vector> q_by_dist; + q_by_dist.reserve(q_pool.size()); + for (GameObject* go : q_pool) + { + if (!go) continue; + if (already_in.count(go->GetGUID())) continue; + const uint32 entry = go->GetEntry(); + const bool entry_match = q_go_entries.count(entry) > 0; + bool item_match = false; + if (!entry_match && !q_item_ids.empty()) + { + if (std::vector const* drops = + sObjectMgr->GetGameObjectQuestItemList(entry)) + { + for (uint32 item_id : *drops) + { + if (q_item_ids.count(item_id)) + { + item_match = true; + break; + } + } + } + // Loot-template GO sources (vanilla: no questitem rows). + if (!item_match) + for (uint32 item_id : q_item_ids) + if (QuestItemDropsFromGameObject(item_id, entry)) + { + item_match = true; + break; + } + } + if (!entry_match && !item_match) continue; + const float dx = go->GetPositionX() - p->GetPositionX(); + const float dy = go->GetPositionY() - p->GetPositionY(); + const float dz = go->GetPositionZ() - p->GetPositionZ(); + q_by_dist.emplace_back(dx*dx + dy*dy + dz*dz, go); + } + std::sort(q_by_dist.begin(), q_by_dist.end(), + [](auto const& a, auto const& b) { return a.first < b.first; }); + + constexpr size_t kQAppendCap = 24; + if (q_by_dist.size() > kQAppendCap) q_by_dist.resize(kQAppendCap); + + for (auto const& [_, go] : q_by_dist) + { + if (already_in.count(go->GetGUID())) continue; + BotSnapshot::NearbyObject n{}; + n.guid = go->GetGUID(); + n.entry = go->GetEntry(); + n.go_type = go->GetGoType(); + n.x = go->GetPositionX(); + n.y = go->GetPositionY(); + n.z = go->GetPositionZ(); + snap->world_objects.nearby_objects.push_back(n); + already_in.insert(go->GetGUID()); + } + } + } + } + // ---- Cross-quest actionable index ---- // For every active (non-complete, non-optional, non-blacklisted) // objective in the bot's log, list the *currently visible* progression @@ -8453,906 +9641,6 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b } } - // ---- Nearby GameObjects (30yd, capped, filtered by useful types) ---- - { - constexpr float SCAN_RADIUS = 30.0f; - constexpr size_t MAX_OBJECTS = 16; - thread_local std::vector scratch_gos; - scratch_gos.clear(); - scratch_gos.reserve(64); - Trinity::AllGameObjectsWithEntryInRange go_check(p, /*entry*/ 0, SCAN_RADIUS); - Trinity::GameObjectListSearcher searcher(p, scratch_gos, go_check); - Cell::VisitGridObjects(p, searcher, SCAN_RADIUS); - - // thread_local scratch reused across builds — mirrors the - // enemy/friend by_dist pattern. clear()+reserve() retains capacity - // so the per-build heap alloc is paid once per worker thread. - thread_local std::vector> by_dist; - by_dist.clear(); - by_dist.reserve(scratch_gos.size()); - for (GameObject* go : scratch_gos) - { - if (!go) continue; - // Filter to types bot logic actually drives. Skip everything else to - // keep the vector bounded — chairs, transports, etc would - // dominate the cap in major cities. GATHERING_NODE (50) is the - // modern herbalism/mining node type — without it in the - // snapshot, the `idle:gather` rule's `obj.go_type != 50` - // continue-skip would never find a candidate and the rule - // would never fire. - const uint8 t = go->GetGoType(); - const bool useful = - t == GAMEOBJECT_TYPE_MAILBOX || - t == GAMEOBJECT_TYPE_CHEST || - t == GAMEOBJECT_TYPE_GATHERING_NODE || - t == GAMEOBJECT_TYPE_FISHINGHOLE || - t == GAMEOBJECT_TYPE_QUESTGIVER || - t == GAMEOBJECT_TYPE_BINDER || - t == GAMEOBJECT_TYPE_GOOBER || - t == GAMEOBJECT_TYPE_MEETINGSTONE || - t == GAMEOBJECT_TYPE_GUILD_BANK || - // Quest-interaction GO types — needed by idle:quest_use_go - // (B4) so QUEST_OBJECTIVE_GAMEOBJECT (type 2) targets are - // visible. GENERIC covers most static quest props (banners, - // crates, books). BUTTON covers levers / switches. SPELL_FOCUS - // covers altars / runes that gate quest casts. - t == GAMEOBJECT_TYPE_GENERIC || - t == GAMEOBJECT_TYPE_BUTTON || - t == GAMEOBJECT_TYPE_SPELL_FOCUS || - // Cross-continent travel (Phase C). SPELLCASTER (22) is - // the static portal GO; TRANSPORT (11) is mooring rooms / - // elevators / etc; MO_TRANSPORT (15) is the seafaring - // ships and zeppelins that move between continents. The - // builder pre-resolves their destinations so the bot logic can - // walk to them and use/board. - t == GAMEOBJECT_TYPE_SPELLCASTER || - t == GAMEOBJECT_TYPE_TRANSPORT || - t == GAMEOBJECT_TYPE_MAP_OBJ_TRANSPORT || - // Battleground objectives. FLAGSTAND (24) covers AB/EotS/ - // BfG capturable nodes + AV banners + WSG/TP/BfG flag - // pedestals + IoC/SoTA/SS objective markers. FLAGDROP (26) - // covers dropped CTF flags. CAPTURE_POINT (42) is the - // modern WG/AV-style capture object — auto_use_go_types - // doesn't read it directly but BG node-state population - // walks it from a separate path; including here lets - // future scripts opt in via auto_use_go_types. Without - // these, idle:bg_use_objective_go silently no-ops for - // every BG that opts in, making node captures impossible. - t == GAMEOBJECT_TYPE_FLAGSTAND || - t == GAMEOBJECT_TYPE_FLAGDROP || - t == GAMEOBJECT_TYPE_CAPTURE_POINT || - // Modern BG mechanic GOs (BG audit N12/N25/N32/N67): the - // Cata+ CTF flags are NEW_FLAG (36) on the pedestal and - // NEW_FLAG_DROP (37) on the ground; EotS towers and the - // Silvershard cart zones are CONTROL_ZONE (29). These were - // missing from this filter, so idle:bg_use_objective_go - // could never SEE the very GOs the WSG/TP/EotS/Kotmogu - // scripts opt into via auto_use_go_types — flag and orb - // pickup was structurally impossible fleet-wide. - t == GAMEOBJECT_TYPE_NEW_FLAG || - t == GAMEOBJECT_TYPE_NEW_FLAG_DROP || - t == GAMEOBJECT_TYPE_CONTROL_ZONE || - // DESTRUCTIBLE_BUILDING (33): IoC keep gates + SoTA defense- - // line gates. The BG siege-vehicle fire rule scans these and - // casts the vehicle's gate-damage spell at the standing ones - // (is_destroyed below); without them in the snapshot a siege - // engine could never break a gate and the General was never - // reached (BG audit IoC / SoTA siege blockers). - t == GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING || - // TRAP (6): includes environmental hazards like bonfires - // and pyres. Builder classifies as hazard below if the - // trap's spell is hostile, so idle:flee_hazard can step - // the bot out of damage range. We DO want non-hostile - // traps in nearby_objects too (some quest scripts trigger - // off them), so the type passes the filter unconditionally. - t == GAMEOBJECT_TYPE_TRAP || - // RITUAL (18): an altar that needs several users (Uldaman's two altars, the UBRS Blackrock Altar). The group's - // bots fill the places a person in the group leaves open (ritual_join below). - t == GAMEOBJECT_TYPE_RITUAL || - // DOOR (0): only a shut one a player opens by hand (IsShutHandDoor, or named by the dungeon: IsListedShutHandDoor), - // or one that opens to a key this bot carries (KeyForShutDoor), for idle:dungeon_open_hand_door. - (t == GAMEOBJECT_TYPE_DOOR && (IsShutHandDoor(go) || IsListedShutHandDoor(go) || KeyForShutDoor(p, go) != 0)); - if (!useful) continue; - const float dx = go->GetPositionX() - p->GetPositionX(); - const float dy = go->GetPositionY() - p->GetPositionY(); - const float dz = go->GetPositionZ() - p->GetPositionZ(); - by_dist.emplace_back(dx*dx + dy*dy + dz*dz, go); - } - std::sort(by_dist.begin(), by_dist.end(), - [](auto const& a, auto const& b) { return a.first < b.first; }); - if (by_dist.size() > MAX_OBJECTS) by_dist.resize(MAX_OBJECTS); - - // An object's loot the bot has open (an herb or vein its gathering spell opened): the gather rule takes it. - snap->world_objects.loot_open = p->GetLootGUID().IsGameObject() ? p->GetLootGUID() : ObjectGuid::Empty; - snap->world_objects.nearby_objects.reserve(by_dist.size()); - for (auto const& [_, go] : by_dist) - { - BotSnapshot::NearbyObject n{}; - n.guid = go->GetGUID(); - n.entry = go->GetEntry(); - n.go_type = go->GetGoType(); - // [bgflag_diag] TEMP — confirm CTF flag GO (type 36) is in-snapshot on - // EotS(566)/TP(726), and which bot sees it (incl. distance via pos). - if ((p->GetMapId() == 726 || p->GetMapId() == 566) && go->GetGoType() == 36) - { - static thread_local uint32 s_bfAt = 0; - uint32 const bfn = getMSTime(); - if (bfn - s_bfAt > 5000) - { - s_bfAt = bfn; - TC_LOG_INFO("playerbot.v2", - "[bgflag_diag] map={} flagGO entry={} at ({:.0f},{:.0f},{:.0f}) " - "seen_by={} bot_pos=({:.0f},{:.0f},{:.0f})", - p->GetMapId(), go->GetEntry(), go->GetPositionX(), - go->GetPositionY(), go->GetPositionZ(), p->GetName(), - p->GetPositionX(), p->GetPositionY(), p->GetPositionZ()); - } - } - n.x = go->GetPositionX(); - n.y = go->GetPositionY(); - n.z = go->GetPositionZ(); - if (n.go_type == GAMEOBJECT_TYPE_RITUAL) - n.ritual_join = RitualNeedsBot(p, go); - n.hand_door = n.go_type == GAMEOBJECT_TYPE_DOOR; // the filter above lets in only a shut hand door - if (n.hand_door && !IsShutHandDoor(go) && !IsListedShutHandDoor(go)) - n.key_item = KeyForShutDoor(p, go); // a door only a key opens: the bot uses its key on it - if (n.go_type == GAMEOBJECT_TYPE_CHEST) - n.key_chest = IsListedKeyChest(p, go); - // Destructible gate breach state (IoC / SoTA) so the siege-fire - // rule skips already-down gates and advances to the next line. - if (n.go_type == GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING) - n.is_destroyed = - go->GetDestructibleState() == GO_DESTRUCTIBLE_DESTROYED; - // Herb / ore vein: a chest whose lock asks for Herbalism or Mining (the gathering rules, GatheringRules.cpp). - if (n.go_type == GAMEOBJECT_TYPE_CHEST) - if (LockEntry const* lock = sLockStore.LookupEntry(go->GetGOInfo()->GetLockId())) - for (uint8 li = 0; li < MAX_LOCK_CASE; ++li) - { - if (lock->Type[li] != LOCK_KEY_SKILL) - continue; - SkillType const sk = SkillByLockType(LockType(lock->Index[li])); - if (sk != SKILL_HERBALISM && sk != SKILL_MINING) - continue; - n.gather_skill = uint16(sk); - n.gather_req = lock->Skill[li]; - n.gather_ready = go->isSpawned() && go->getLootState() == GO_READY; - break; - } - // Pre-resolve teleport destination for SPELLCASTER GOs. - // Type 22 stores its triggered spell in spellCaster.spell. - // The spell's destination is in the spell_target_position - // table (loaded once at server start, read-only thereafter - // — safe to query from this snapshot path). Most type-22 - // GOs are altars / event triggers without a teleport effect; - // for those, GetSpellTargetPosition returns null and the - // teleport_dest_* fields stay zero. - if (n.go_type == GAMEOBJECT_TYPE_SPELLCASTER) - { - if (GameObjectTemplate const* tmpl = go->GetGOInfo()) - { - const uint32 spell_id = tmpl->spellCaster.spell; - if (spell_id != 0) - { - // Resolve the teleport destination through the SHARED - // PortalIndex resolver, which scans all effect indices - // AND follows the FORCE_CAST/TRIGGER_SPELL indirection - // modern portals use. The GO's own spell often carries - // no spell_target_position: either the teleport sits on - // a non-zero effect index (~156 portals server-wide), or - // the spell merely FORCE_CASTs the real teleport (e.g. - // Org's Undercity portal 293684 -> 17611 -> 121862 -> - // map 0). Either way the old direct scan left - // teleport_dest_map=0, so the in-range use_portal gate - // (dest must match the goal map) skipped the portal and - // the bot walked to it but never used it. Using the same - // resolver as PortalIndex keeps the snapshot and the - // travel graph in lockstep. - uint32 dmap = 0; - float dtx = 0.f, dty = 0.f, dtz = 0.f; - if (Playerbot::V2::Travel::ResolvePortalSpellDest(spell_id, dmap, dtx, dty, dtz)) - { - n.teleport_dest_map = dmap; - n.teleport_dest_x = dtx; - n.teleport_dest_y = dty; - n.teleport_dest_z = dtz; - } - } - } - } - // Hazard classification for TRAP-type GOs (bonfires, pyres, - // lava grates). We mark a trap as a hazard when its trap - // spell is hostile (SpellInfo::IsPositive() == false). The - // hazard_radius is the radius the core fires the trap at (see - // below). idle:flee_hazard - // uses both fields to step the bot 5y past the radius so it - // stops standing inside a bonfire and dying. - else if (n.go_type == GAMEOBJECT_TYPE_TRAP) - { - if (GameObjectTemplate const* tmpl = go->GetGOInfo()) - { - const uint32 trap_spell = tmpl->trap.spell; - if (trap_spell != 0) - { - if (SpellInfo const* si = sSpellMgr->GetSpellInfo(trap_spell, DIFFICULTY_NONE)) - { - if (!si->IsPositive()) - { - // The core halves the radius only for an owned trap (GameObject::Update, since 2026-10-16); a - // world trap fires at the full radius. Halving every trap left bots 6-11 y from Majordomo's - // Intense Heat pit (20533, radius 10) thinking they stood clear: 17 of the 43 deaths in - // release-0130 mc_majordomo were that pit. - n.is_hazard = true; - n.hazard_radius = go->GetOwnerGUID().IsEmpty() ? float(tmpl->trap.radius) - : tmpl->trap.radius / 2.0f; - } - } - } - } - } - // Continental transport (ship / zeppelin). Same teleport_dest - // semantics: bot logic walks to the transport, server auto-attaches - // the bot as a passenger when the bounding box overlaps, the - // transport carries them across maps, and the bot's same-map - // rules pick up at the destination dock. We populate the - // FIRST destination map that isn't the bot's current map — - // most transports cycle between exactly two continents, so - // there's no ambiguity. (Multi-stop tours like the Pandaria - // cruise are rare and not worth special-casing.) - // ONLY type-15 MAP_OBJ_TRANSPORT (cross-map ships/zeppelins) get a - // cross-map destination. Type-11 GAMEOBJECT_TYPE_TRANSPORT here is a - // local animated LIFT (Orgrimmar zeppelin-tower elevators, city - // lifts) — same-map, no TransportTemplate. It is still pushed to - // nearby_objects (the elevator rules find it), but with NO - // teleport_dest_map (stays kInvalidMapId), so the cross-map board - // rule never targets it. Old code accepted type-11 too; an elevator - // with no template kept the default dest, and when that default was - // 0 (== Eastern Kingdoms, a real map) the bot boarded the lift as if - // it were the EK zeppelin and rode it up and down forever. - else if (n.go_type == GAMEOBJECT_TYPE_MAP_OBJ_TRANSPORT) - { - if (TransportTemplate const* tt = - sTransportMgr->GetTransportTemplate(go->GetEntry())) - { - for (uint32 map_id : tt->MapIds) - { - if (map_id != p->GetMapId()) - { - n.teleport_dest_map = map_id; - // No exact dest coords — the transport drops - // the passenger at its dock spawn, which the - // Bot logic doesn't strictly need to plan; we just - // need to know "this transport reaches the - // goal map". - break; - } - } - } - } - // Type-11 local lift (Orgrimmar zeppelin-tower elevators, city / - // raid lifts). We're on the WORLD THREAD here with the live navmesh - // and the bot is physically near this elevator (it's in range of the - // grid scan), so this is the right place to lazily derive the stop's - // walkable board/disembark LEDGES (nearest navmesh poly beside each - // platform-centre). Cheap after the first encounter — every stop's - // result is cached in ElevatorIndex. The elevator rules then read the - // ledge via ElevatorIndex::LedgeFor on the bot worker. - else if (n.go_type == GAMEOBJECT_TYPE_TRANSPORT) - { - // Derive ledges for the WHOLE nearby lift cluster (not just this - // GO), so the boardable-lift preference can compare sibling lifts - // immediately (e.g. the two Org zeppelin lifts ~150y apart — one - // boardable, one a pit). Cheap + cached after the first pass. - V2::Travel::ElevatorIndex::Instance().EnsureLedgesNear(p, /*range*/ 200.0f); - } - snap->world_objects.nearby_objects.push_back(n); - } - - // ---- MO-transport scan (ships / zeppelins) ---- - // Continental transports (GAMEOBJECT_TYPE_MAP_OBJ_TRANSPORT 15 = boats, - // and the cross-map TRANSPORT 11 = zeppelins) live in Map::_transports, - // NOT the grid, so the Cell::VisitGridObjects scan above NEVER returns - // them. That left every cross-map boarding rule blind: 0 bots boarded a - // ship fleet-wide despite 98K+ walk_to_known_dock fires — the dominant - // cause of the leveling stall (bots can't reach off-continent quests). - // Scan the map's transport set directly and add any nearby continental - // transport (one with a destination map != current) so a bot waiting at - // a dock can SEE its docked ship and board it. Generous radius — the bot - // waits on the pier, tens of yards from the ship's moving pivot. Few - // transports exist per map, so this is cheap; we bypass the 16-object - // cap above because transports are rare and always travel-relevant. - if (Map* tmap = p->GetMap()) - { - constexpr float kTransportScanSq = 200.0f * 200.0f; - for (Transport* tr : tmap->GetTransports()) - { - if (!tr) continue; - const uint8 tt = tr->GetGoType(); - if (tt != GAMEOBJECT_TYPE_TRANSPORT && - tt != GAMEOBJECT_TYPE_MAP_OBJ_TRANSPORT) continue; - const float tdx = tr->GetPositionX() - p->GetPositionX(); - const float tdy = tr->GetPositionY() - p->GetPositionY(); - const float tdz = tr->GetPositionZ() - p->GetPositionZ(); - if (tdx*tdx + tdy*tdy + tdz*tdz > kTransportScanSq) continue; - BotSnapshot::NearbyObject n{}; - n.guid = tr->GetGUID(); - n.entry = tr->GetEntry(); - n.go_type = tt; - n.x = tr->GetPositionX(); - n.y = tr->GetPositionY(); - n.z = tr->GetPositionZ(); - // Resolve the transport's destination continent (first MapId - // that isn't the bot's current map) — mirrors the grid-GO - // transport handling so the boarding rule's dest match works. - if (TransportTemplate const* ttpl = - sTransportMgr->GetTransportTemplate(tr->GetEntry())) - { - for (uint32 map_id : ttpl->MapIds) - { - if (map_id != p->GetMapId()) - { - n.teleport_dest_map = map_id; - break; - } - } - } - snap->world_objects.nearby_objects.push_back(n); - } - - // Tram cars (type-11 GOs that run between two stations on one map, the Deeprun Tram): they sit in the grid, so the - // MO-transport set above never holds them, and the 30 y object scan only sees one standing right beside the bot. A - // bot waiting on the platform for a ride looked at "transports in sight 0" for 300 s, then gave the route up. The - // cars are few and known (PortalIndex), so look them up by spawn id within the same 200 y. - if (Services::Initialized() && Services::Portals().IsInitialized()) - { - auto const& car_ids = Services::Portals().ShuttleSpawnIds(p->GetMapId()); - if (!car_ids.empty()) - { - static std::atomic s_carLogAt{0}; - uint32 const cnow = GameTime::GetGameTimeMS(); - uint32 last = s_carLogAt.load(std::memory_order_relaxed); - if (cnow - last >= 120000u && s_carLogAt.compare_exchange_strong(last, cnow ? cnow : 1u)) - { - size_t in_world = 0; - for (uint64 const id : car_ids) - if (GameObject* c = tmap->GetGameObjectBySpawnId(id); c && c->IsInWorld()) ++in_world; - TC_LOG_INFO("playerbot.v2", "[xport_cars] map {}: {} tram cars known, {} in the world; {} sees {:.0f},{:.0f},{:.0f}", - p->GetMapId(), car_ids.size(), in_world, p->GetName(), p->GetPositionX(), p->GetPositionY(), p->GetPositionZ()); - } - } - for (uint64 const spawn_id : car_ids) - { - GameObject* car = tmap->GetGameObjectBySpawnId(spawn_id); - if (!car || !car->IsInWorld()) continue; - const float cdx = car->GetPositionX() - p->GetPositionX(); - const float cdy = car->GetPositionY() - p->GetPositionY(); - const float cdz = car->GetPositionZ() - p->GetPositionZ(); - if (cdx*cdx + cdy*cdy + cdz*cdz > kTransportScanSq) continue; - bool const have = std::any_of(snap->world_objects.nearby_objects.begin(), snap->world_objects.nearby_objects.end(), - [&](BotSnapshot::NearbyObject const& o) { return o.guid == car->GetGUID(); }); - if (have) continue; - BotSnapshot::NearbyObject n{}; - n.guid = car->GetGUID(); - n.entry = car->GetEntry(); - n.go_type = car->GetGoType(); - n.x = car->GetPositionX(); - n.y = car->GetPositionY(); - n.z = car->GetPositionZ(); - snap->world_objects.nearby_objects.push_back(n); - } - } - } - - // ---- Extended gathering-node scan (200y) ---- - // The 30y nearby_objects scan above covers vendor / quest-giver - // / chest interactions where the bot is typically at the giver. - // For gathering nodes we want a much wider horizon so the bot can - // SEE a node from across a clearing and walk toward it. Per the - // user's design: 40y attract in Questing mode (opportunistic), - // 150-200y attract in Professioning mode (active seeking). - // Snapshot exposes nodes up to 200y; the rule picks attract radius - // based on the bot's activity_mode. - // - // Cost: O(creatures+GOs within 200y) extra cell visit, gated to - // bots that have at least one gathering skill — non-gatherers see - // no overhead. The append is filtered to GATHERING_NODE / FISHINGHOLE - // / CHEST(gather variant) so it doesn't pollute nearby_objects with - // unrelated GOs. - constexpr uint16 kHerbalismSk = 182; - constexpr uint16 kMiningSk = 186; - constexpr uint16 kSkinningSk = 393; - constexpr uint16 kFishingSk = 356; - const bool has_any_gather = - p->HasSkill(kHerbalismSk) || p->HasSkill(kMiningSk) || - p->HasSkill(kSkinningSk) || p->HasSkill(kFishingSk); - // Per-bot 1Hz throttle on the 200y gather-node Cell::VisitGridObjects. - // Same rationale as the hub scan above: nodes are static; the - // 30y nearby_objects scan still gives near-bot coverage every tick. - BotAI* gs_ai = bot_ai; - const uint32 gather_now_ms = GameTime::GetGameTimeMS(); - constexpr uint32 kGatherScanIntervalMs = 1000u; - const bool gather_throttled = gs_ai && - gs_ai->last_gather_scan_ms() != 0 && - (gather_now_ms - gs_ai->last_gather_scan_ms()) < kGatherScanIntervalMs; - if (has_any_gather && !gather_throttled) - { - if (gs_ai) gs_ai->set_last_gather_scan_ms(gather_now_ms); - constexpr float EXT_GATHER_RADIUS = 200.0f; - constexpr size_t EXT_GATHER_MAX = 32; - // Same thread_local + reserve(64) pattern as the 30y scan - // above. Distinct buffer (`ext_gos`) because both scans can - // appear in the same Build pass; reusing the same buffer - // would corrupt the 30y result. - thread_local std::vector scratch_ext_gos; - scratch_ext_gos.clear(); - scratch_ext_gos.reserve(128); - Trinity::AllGameObjectsWithEntryInRange ext_check(p, /*entry*/ 0, EXT_GATHER_RADIUS); - Trinity::GameObjectListSearcher ext_searcher(p, scratch_ext_gos, ext_check); - Cell::VisitGridObjects(p, ext_searcher, EXT_GATHER_RADIUS); - - std::unordered_set ext_seen; - ext_seen.reserve(snap->world_objects.nearby_objects.size() + 16); - for (auto const& nb : snap->world_objects.nearby_objects) - ext_seen.insert(nb.guid); - - std::vector> ext_by_dist; - ext_by_dist.reserve(scratch_ext_gos.size()); - for (GameObject* go : scratch_ext_gos) - { - if (!go) continue; - const uint8 t = uint8(go->GetGoType()); - if (t != GAMEOBJECT_TYPE_GATHERING_NODE && - t != GAMEOBJECT_TYPE_FISHINGHOLE) continue; - if (ext_seen.count(go->GetGUID())) continue; - const float dx = go->GetPositionX() - p->GetPositionX(); - const float dy = go->GetPositionY() - p->GetPositionY(); - const float dz = go->GetPositionZ() - p->GetPositionZ(); - ext_by_dist.emplace_back(dx*dx + dy*dy + dz*dz, go); - } - std::sort(ext_by_dist.begin(), ext_by_dist.end(), - [](auto const& a, auto const& b) { return a.first < b.first; }); - if (ext_by_dist.size() > EXT_GATHER_MAX) ext_by_dist.resize(EXT_GATHER_MAX); - for (auto const& [_, go] : ext_by_dist) - { - BotSnapshot::NearbyObject n{}; - n.guid = go->GetGUID(); - n.entry = go->GetEntry(); - n.go_type = go->GetGoType(); - n.x = go->GetPositionX(); - n.y = go->GetPositionY(); - n.z = go->GetPositionZ(); - snap->world_objects.nearby_objects.push_back(n); - } - } - - // ---- Spell-based ground-hazard scan (G-P1c) ---- - // Modern boss "stand in fire" mechanics are NOT GameObject traps - // (handled above). They are DynamicObject area-spell entities - // (classic voidzones / Consecration-like ground effects) and - // AreaTrigger entities (the modern shape-based ground effects used - // by virtually every retail boss). Neither is reachable through the - // GameObject scan, so without this pass the bot has no snapshot - // signal that it is standing in a damage patch — idle:flee_hazard - // and the in-combat dungeon-positioning path (G-P0a) both consume - // is_hazard / hazard_radius NearbyObject entries and step the bot - // out, so feeding these two entity classes into nearby_objects is - // all that is required to make bots dodge fire. - // - // PERF: this is the hottest path (200-2000 bots, ~20K Builds/s - // post-throttle). Hazards only matter while the bot is fighting, so - // the ENTIRE scan is gated behind p->IsInCombat() — the ~95% idle - // fleet pays nothing (not even the cell visit). When it does run we - // restrict the grid map-type mask to DYNAMICOBJECT | AREATRIGGER so - // VisitAllObjects skips creatures, players, and GameObjects - // entirely, and we cap the appended hazards to the closest few. - // Instance extension (raid / dungeon ground-hazard avoidance): inside a - // dungeon or raid map the scan also runs out of combat - a healer - // walking up to the fight, or a bot whose combat flag dropped between - // pulls, must still see the Rain of Fire it is standing in - and it - // additionally feeds snap->combat.ground_hazards (spell / caster / - // radius, damage-classified) for the [raid_hazard] step-out. The - // nearby_objects is_hazard feed below keeps its original in-combat - // gate. Battlegrounds stay excluded (instance maps, not dungeons). - Map const* haz_map = p->GetMap(); - const bool haz_instance = haz_map && haz_map->IsDungeon() && !haz_map->IsBattlegroundOrArena(); - const bool haz_combat = p->IsInCombat(); - if (haz_combat || haz_instance) - { - constexpr float HAZ_SCAN_RADIUS = 40.0f; - constexpr size_t HAZ_MAX = 12; - // Reuse the WorldObjectListSearcher + AllWorldObjectsInRange - // pattern (same as the TC core scripts), but constrain the - // visited grid containers to the two hazard-bearing types via - // the searcher's mapTypeMask so the visit never touches the - // (far larger) creature / player / GO maps. - thread_local std::vector scratch_haz; - scratch_haz.clear(); - scratch_haz.reserve(32); - Trinity::AllWorldObjectsInRange haz_check(p, HAZ_SCAN_RADIUS); - Trinity::WorldObjectListSearcher haz_searcher( - p, scratch_haz, haz_check, - GRID_MAP_TYPE_MASK_DYNAMICOBJECT | GRID_MAP_TYPE_MASK_AREATRIGGER); - Cell::VisitAllObjects(p, haz_searcher, HAZ_SCAN_RADIUS); - - // Each candidate carries (dist^2, position, radius). We resolve - // the spell + caster, apply the hostile-and-non-positive gate, - // then sort by distance and keep the closest HAZ_MAX so a - // densely-stacked AoE encounter can't blow past the cap. - struct HazCand - { - float d2; float x, y, z, radius; ObjectGuid guid; - uint32 spell; ObjectGuid caster; bool hurts; GroundHazardSource src; - }; - std::vector haz_by_dist; - haz_by_dist.reserve(scratch_haz.size()); - - // Shared classifier: a ground effect is a hazard when its - // creating spell is hostile (SpellInfo::IsPositive() == false) - // AND its caster is NOT friendly to the bot. A friendly - // Consecration / Healing Rain / Death and Decay cast by the bot - // or a party member must never be flagged. When the caster is - // absent (despawned / environmental), we treat a non-positive - // spell as an environmental hazard (e.g. lingering fire). When - // the spell is positive, we never flag — that is the safe - // default for indeterminate hostility. - auto isHostileGround = [&](SpellInfo const* si, Unit* caster) -> bool - { - if (!si || si->IsPositive()) - return false; // positive => never a hazard - if (!caster) - return true; // no caster => environmental hazard - return !caster->IsFriendlyTo(p); // hostile / neutral non-friendly only - }; - - for (WorldObject* wo : scratch_haz) - { - if (!wo) continue; - - if (DynamicObject const* dyn = wo->ToDynObject()) - { - SpellInfo const* si = dyn->GetSpellInfo(); - if (!isHostileGround(si, dyn->GetCaster())) - continue; - const float dx = dyn->GetPositionX() - p->GetPositionX(); - const float dy = dyn->GetPositionY() - p->GetPositionY(); - const float dz = dyn->GetPositionZ() - p->GetPositionZ(); - haz_by_dist.push_back({ dx*dx + dy*dy + dz*dz, - dyn->GetPositionX(), dyn->GetPositionY(), dyn->GetPositionZ(), - dyn->GetRadius(), dyn->GetGUID(), - dyn->GetSpellId(), dyn->GetCasterGUID(), SpellHurtsInArea(si), - GroundHazardSource::DynObject }); - } - else if (AreaTrigger const* at = wo->ToAreaTrigger()) - { - // AreaTrigger exposes only the spell id; resolve the - // SpellInfo through SpellMgr (DIFFICULTY_NONE matches the - // GO-trap classifier above). GetMaxSearchRadius() returns - // the largest extent of the trigger's current shape - // (sphere / box / polygon bounding radius incl. scale), - // which is the conservative radius we want the bot to - // clear. - SpellInfo const* si = sSpellMgr->GetSpellInfo(at->GetSpellId(), DIFFICULTY_NONE); - if (!isHostileGround(si, at->GetCaster())) - continue; - const float dx = at->GetPositionX() - p->GetPositionX(); - const float dy = at->GetPositionY() - p->GetPositionY(); - const float dz = at->GetPositionZ() - p->GetPositionZ(); - // Damage test: the creating spell itself, else the - // template's CAST / ADDAURA actions aimed at enemies - // (the data-driven AT shape). A scripted AT (no - // actions - AreaTriggerAI applies the effect) is taken - // on the hostile-non-positive verdict above. - bool at_hurts = SpellHurtsInArea(si); - if (!at_hurts) - { - AreaTriggerTemplate const* att = at->GetTemplate(); - if (!att || att->Actions.empty()) - at_hurts = true; - else - for (AreaTriggerAction const& act : att->Actions) - { - if (act.ActionType != AREATRIGGER_ACTION_CAST && - act.ActionType != AREATRIGGER_ACTION_ADDAURA) - continue; - if (act.TargetType != AREATRIGGER_ACTION_USER_ANY && - act.TargetType != AREATRIGGER_ACTION_USER_ENEMY) - continue; - if (SpellHurtsInArea(sSpellMgr->GetSpellInfo(act.Param, DIFFICULTY_NONE))) - { at_hurts = true; break; } - } - } - haz_by_dist.push_back({ dx*dx + dy*dy + dz*dz, - at->GetPositionX(), at->GetPositionY(), at->GetPositionZ(), - at->GetMaxSearchRadius(), at->GetGUID(), - at->GetSpellId(), at->GetCasterGuid(), at_hurts, - GroundHazardSource::AreaTrigger }); - } - } - - std::sort(haz_by_dist.begin(), haz_by_dist.end(), - [](HazCand const& a, HazCand const& b) { return a.d2 < b.d2; }); - - // ---- combat.ground_hazards (raid / dungeon step-out feed) ---- - // Instances only (the consumer is the dungeon / raid cascade). - // Three sources, merged closest-first and capped at - // kMaxGroundHazards: the damaging DynamicObject / AreaTrigger - // zones above (centre within 30y), trigger creatures pulsing a - // damage aura (void zone, poison cloud - from this Build's 40y - // unfriendly-unit scratch, filled by the merged enemy+friend - // scan), and hostile damaging trap GameObjects already in - // nearby_objects. - if (haz_instance) - { - constexpr float kGroundHazRange = 30.0f; - auto& gh = snap->combat.ground_hazards; - thread_local std::vector> gh_by_dist; - gh_by_dist.clear(); - for (HazCand const& h : haz_by_dist) - { - if (!h.hurts || h.radius <= 0.0f) continue; - if (h.d2 > kGroundHazRange * kGroundHazRange) continue; - gh_by_dist.push_back({ h.d2, GroundHazard{ h.x, h.y, h.z, h.radius, - h.spell, h.caster, h.src } }); - } - for (Unit* t : scratch_enemies_tl()) - { - Creature const* c = t ? t->ToCreature() : nullptr; - if (!c || !c->IsAlive() || c->IsFriendlyTo(p)) continue; - const float dx = c->GetPositionX() - p->GetPositionX(); - const float dy = c->GetPositionY() - p->GetPositionY(); - const float dz = c->GetPositionZ() - p->GetPositionZ(); - const float d2 = dx*dx + dy*dy + dz*dz; - if (d2 > kGroundHazRange * kGroundHazRange) continue; - uint32 zone_spell = 0; - const float r = TriggerCreatureZone(c, zone_spell); - if (r <= 0.0f) continue; - ObjectGuid const owner = !c->GetCreatorGUID().IsEmpty() ? c->GetCreatorGUID() - : c->GetGUID(); - gh_by_dist.push_back({ d2, GroundHazard{ c->GetPositionX(), c->GetPositionY(), - c->GetPositionZ(), r, zone_spell, owner, - GroundHazardSource::TriggerCreature } }); - } - for (auto const& o : snap->world_objects.nearby_objects) - { - if (!o.is_hazard || o.entry == 0 || o.hazard_radius <= 0.0f) continue; - GameObject const* go = ObjectAccessor::GetGameObject(*p, o.guid); - if (!go) continue; - GameObjectTemplate const* tmpl = go->GetGOInfo(); - if (!tmpl || tmpl->type != GAMEOBJECT_TYPE_TRAP) continue; - SpellInfo const* tsi = sSpellMgr->GetSpellInfo(tmpl->trap.spell, DIFFICULTY_NONE); - if (!SpellHurtsInArea(tsi)) continue; - if (Unit const* owner = go->GetOwner()) - if (owner->IsFriendlyTo(p)) continue; // a friendly hunter's trap - const float dx = o.x - p->GetPositionX(); - const float dy = o.y - p->GetPositionY(); - const float dz = o.z - p->GetPositionZ(); - const float d2 = dx*dx + dy*dy + dz*dz; - if (d2 > kGroundHazRange * kGroundHazRange) continue; - gh_by_dist.push_back({ d2, GroundHazard{ o.x, o.y, o.z, o.hazard_radius, - tmpl->trap.spell, go->GetOwnerGUID(), - GroundHazardSource::GoTrap } }); - } - std::sort(gh_by_dist.begin(), gh_by_dist.end(), - [](auto const& a, auto const& b) { return a.first < b.first; }); - if (gh_by_dist.size() > kMaxGroundHazards) gh_by_dist.resize(kMaxGroundHazards); - gh.reserve(gh_by_dist.size()); - for (auto const& [_, h] : gh_by_dist) - gh.push_back(h); - } - - if (haz_by_dist.size() > HAZ_MAX) haz_by_dist.resize(HAZ_MAX); - - for (auto const& h : haz_by_dist) - { - if (!haz_combat) break; // nearby_objects feed: original in-combat gate - BotSnapshot::NearbyObject n{}; - n.guid = h.guid; - // entry / go_type stay 0 — these are not GameObjects. The - // consumer keys off is_hazard / hazard_radius, not go_type. - n.x = h.x; - n.y = h.y; - n.z = h.z; - n.is_hazard = true; - n.hazard_radius = h.radius; - snap->world_objects.nearby_objects.push_back(n); - } - } - - // ---- combat.tank_los (raid / dungeon LoS step feed) ---- - // LoS from the bot to every live same-map group tank (threat_tanks, - // built with group_tank above), through the TTL-cached raycast the - // nearby scans use. In combat inside an instance only: the - // [raid_los] step (State_InCombat) is its sole consumer, and a raid - // has at most a handful of tanks. - if (haz_combat && haz_instance) - { - const uint32 los_now = GameTime::GetGameTimeMS(); - for (Unit const* tk : threat_tanks) - { - if (!tk || tk == p) continue; - if (snap->combat.tank_los.size() >= 8) break; - snap->combat.tank_los.push_back({ tk->GetGUID(), CachedLosCheck(p, tk, los_now) }); - } - } - - // ---- Quest-relevant GameObject expansion (POI-aware) ---- - // Mirrors the "quest-target neutral creature" expansion above: the - // baseline 30y nearby_objects scan misses GameObjects that are - // 50-150y from the bot. Many ITEM-objective quests source their - // item from a *lootable GO* (Quest 29401/29412 "Blown Away" loots - // item 71034 from balloons scattered around Razor Hill). The bot - // arrives at the POI center but the balloons cluster 100+ yards - // away across the POI polygon — outside 30y, so nearby_objects is - // empty and idle:quest_use_go silently no-ops. - // - // Strategy: build the set of (a) entries directly named by an - // active QUEST_OBJECTIVE_GAMEOBJECT, and (b) item-ids the active - // QUEST_OBJECTIVE_ITEM rows need; then do a wider scan and admit - // a GO if (a) matches its entry OR (b) intersects with its quest - // item drop list. Two-pass radii (80y around bot + 160y around - // POI when the bot is within 50y of POI) mirror the creature - // expansion above. - if (!snap->quest_log.quests.empty()) - { - std::unordered_set q_go_entries; - std::unordered_set q_item_ids; - q_go_entries.reserve(8); - q_item_ids.reserve(8); - for (auto const& q : snap->quest_log.quests) - { - if (q.state != 0) continue; // 0 = INCOMPLETE - for (auto const& oe : q.objectives) - { - if (oe.progress >= oe.amount) continue; - if (oe.type == QUEST_OBJECTIVE_GAMEOBJECT && oe.object_id > 0) - q_go_entries.insert(uint32(oe.object_id)); - else if (oe.type == QUEST_OBJECTIVE_ITEM && oe.object_id > 0) - q_item_ids.insert(uint32(oe.object_id)); - } - } - - if (!q_go_entries.empty() || !q_item_ids.empty()) - { - std::vector q_pool; - - // ---- Tier 1.3 (behavior-preserving): single-traversal reuse ---- - // The original ran TWO bot-centered VisitGridObjects passes: an - // 80y pass (always) and a 160y pass (when sitting on a POI), - // concatenating both into q_pool. The 160y pass re-walks every - // cell the 80y pass already walked (same center, GameObjects, - // AllGameObjectsWithEntryInRange uses IsWithinDist), so the - // 80y grid traversal is pure duplicate work whenever the wide - // pass fires. - // - // We reuse a SINGLE traversal: when the wide pass fires we walk - // 160y ONCE and reconstruct q_pool with the IDENTICAL multiset - // the two-pass code produced — every GO within 80y appears - // TWICE (once for the would-be 80y pass, once for the 160y - // pass) and every 80–160y GO appears once. Order within q_pool - // does NOT affect output here because q_by_dist below is SORTED - // by distance before the cap, so the membership after sort+cap - // depends only on the (distance,go) MULTISET — which is - // preserved exactly, including the duplicate-occupies-two-slots - // cap interaction of the original. When the wide pass does NOT - // fire we keep the plain single 80y traversal. - bool wide_fires = false; - { - auto const& poi = snap->quest_log.current_objective_poi; - if (poi.valid && poi.map_id == snap->position.map_id) - { - const float pdx = poi.x - p->GetPositionX(); - const float pdy = poi.y - p->GetPositionY(); - const float pdz = poi.z - p->GetPositionZ(); - const float poi_dist_sq = pdx*pdx + pdy*pdy + pdz*pdz; - wide_fires = (poi_dist_sq < (50.0f * 50.0f)); - } - } - - if (!wide_fires) - { - // Narrow-only: exactly the original 80y pass. - thread_local std::vector scratch_q_gos; - scratch_q_gos.clear(); - scratch_q_gos.reserve(128); - constexpr float kQGoRadiusBot = 80.0f; - Trinity::AllGameObjectsWithEntryInRange q_check(p, /*entry*/ 0, kQGoRadiusBot); - Trinity::GameObjectListSearcher q_searcher(p, scratch_q_gos, q_check); - Cell::VisitGridObjects(p, q_searcher, kQGoRadiusBot); - q_pool.insert(q_pool.end(), scratch_q_gos.begin(), scratch_q_gos.end()); - } - else - { - // Wide fires: single 160y traversal, then rebuild the exact - // [80y-subset] ++ [full-160y] multiset the two passes made. - thread_local std::vector scratch_q_gos_poi; - scratch_q_gos_poi.clear(); - scratch_q_gos_poi.reserve(256); - constexpr float kQGoRadiusPOI = 160.0f; - constexpr float kQGoRadiusBot = 80.0f; - Trinity::AllGameObjectsWithEntryInRange q_check_poi(p, /*entry*/ 0, kQGoRadiusPOI); - Trinity::GameObjectListSearcher q_searcher_poi(p, scratch_q_gos_poi, q_check_poi); - Cell::VisitGridObjects(p, q_searcher_poi, kQGoRadiusPOI); - - // Segment 1 — reproduces the would-be 80y pass: every GO - // the 160y result holds that is also within 80y. We re-use - // the EXACT predicate AllGameObjectsWithEntryInRange applied - // (IsWithinDist with is3D=false / 2D), so this membership is - // identical to the dropped 80y pass. - q_pool.reserve(scratch_q_gos_poi.size() * 2); - for (GameObject* go : scratch_q_gos_poi) - if (go && p->IsWithinDist(go, kQGoRadiusBot, /*is3D*/ false)) - q_pool.push_back(go); - // Segment 2 — the full 160y pass. - q_pool.insert(q_pool.end(), scratch_q_gos_poi.begin(), scratch_q_gos_poi.end()); - } - - std::unordered_set already_in; - already_in.reserve(snap->world_objects.nearby_objects.size() + 16); - for (auto const& nb : snap->world_objects.nearby_objects) - already_in.insert(nb.guid); - - // Sort candidates by distance so we keep the closest ones - // first under the per-bot append cap. - std::vector> q_by_dist; - q_by_dist.reserve(q_pool.size()); - for (GameObject* go : q_pool) - { - if (!go) continue; - if (already_in.count(go->GetGUID())) continue; - const uint32 entry = go->GetEntry(); - const bool entry_match = q_go_entries.count(entry) > 0; - bool item_match = false; - if (!entry_match && !q_item_ids.empty()) - { - if (std::vector const* drops = - sObjectMgr->GetGameObjectQuestItemList(entry)) - { - for (uint32 item_id : *drops) - { - if (q_item_ids.count(item_id)) - { - item_match = true; - break; - } - } - } - // Loot-template GO sources (vanilla: no questitem rows). - if (!item_match) - for (uint32 item_id : q_item_ids) - if (QuestItemDropsFromGameObject(item_id, entry)) - { - item_match = true; - break; - } - } - if (!entry_match && !item_match) continue; - const float dx = go->GetPositionX() - p->GetPositionX(); - const float dy = go->GetPositionY() - p->GetPositionY(); - const float dz = go->GetPositionZ() - p->GetPositionZ(); - q_by_dist.emplace_back(dx*dx + dy*dy + dz*dz, go); - } - std::sort(q_by_dist.begin(), q_by_dist.end(), - [](auto const& a, auto const& b) { return a.first < b.first; }); - - constexpr size_t kQAppendCap = 24; - if (q_by_dist.size() > kQAppendCap) q_by_dist.resize(kQAppendCap); - - for (auto const& [_, go] : q_by_dist) - { - if (already_in.count(go->GetGUID())) continue; - BotSnapshot::NearbyObject n{}; - n.guid = go->GetGUID(); - n.entry = go->GetEntry(); - n.go_type = go->GetGoType(); - n.x = go->GetPositionX(); - n.y = go->GetPositionY(); - n.z = go->GetPositionZ(); - snap->world_objects.nearby_objects.push_back(n); - already_in.insert(go->GetGUID()); - } - } - } - } - // ---- Battleground queue state ---- { // A bot standing on a battleground map is in a battleground even when its bg data is not set yet (the first ticks after the port, or @@ -11286,6 +11574,8 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b snap->quest_discovery.quest_turnins.clear(); } + BuildDungeonScan(p, bot_ai, *snap); + return snap; } diff --git a/src/modules/PlayerbotV2/Bot/BotSnapshotView.cpp b/src/modules/PlayerbotV2/Bot/BotSnapshotView.cpp index bef6f67682..dce890dbe0 100644 --- a/src/modules/PlayerbotV2/Bot/BotSnapshotView.cpp +++ b/src/modules/PlayerbotV2/Bot/BotSnapshotView.cpp @@ -453,6 +453,12 @@ float BotSnapshotView::spell_min_range(uint32 spell_id, NearbyUnit const& t) con float min = si->GetMinRange(false); if (si->RangeEntry->Flags & SPELL_RANGE_RANGED) min += std::max(1.5f + t.combat_reach + 4.0f / 3.0f, 5.0f); // DEFAULT_PLAYER_COMBAT_REACH + target reach + 4/3, at least NOMINAL_MELEE_RANGE + // Spell::CalcMinMaxRange's other branch: a range entry without the ranged flag that has a minimum gets both combat reaches added. + // This client's Hunter Range (114, Auto Shot and every shot) has no flags, so against Blazeroar the core's dead zone was 8 + 1.5 + his + // reach while this said 8: the hunter "stepped back" to 12 y, still inside, and the core sent it in to melee in front of him + // (alcaz_full af70c 2026-11-25, killed by Flame Breath). + else if (min > 0.0f) + min += 1.5f + t.combat_reach; // DEFAULT_PLAYER_COMBAT_REACH + target reach return min; } diff --git a/src/modules/PlayerbotV2/Bot/BotSnapshotView.h b/src/modules/PlayerbotV2/Bot/BotSnapshotView.h index deb6c62f84..ace9550d34 100644 --- a/src/modules/PlayerbotV2/Bot/BotSnapshotView.h +++ b/src/modules/PlayerbotV2/Bot/BotSnapshotView.h @@ -100,12 +100,15 @@ public: { return slot < s_->archetype.role_affinity.size() ? s_->archetype.role_affinity[slot] : 0.f; } bool lfg_in_queue() const { return s_->lfg.in_queue; } bool lfg_in_dungeon() const { return s_->lfg.in_dungeon; } + bool lfg_finished_dungeon() const { return s_->lfg.finished_dungeon; } uint16 completed_quest_count() const { return s_->quest_log.completed_quest_count; } std::string const& owner_name() const { return s_->owner_name; } bool has_owner_character() const { return !s_->owner_name.empty(); } bool is_companion_with_owner() const { return s_->owner_in_group; } // In a group with a player who commands it: a companion, or a world bot a player invited. Neither runs world errands. bool is_led_by_player() const { return s_->owner_in_group || s_->led_by_player; } + // The player who leads it is in the water near it (BotSnapshot::leader_in_water). + bool leader_in_water() const { return s_->leader_in_water; } // A bot of the world: no owner, not in any group, not led by a player. bool is_free_world_bot() const { return s_->owner_guid.IsEmpty() && s_->owner_name.empty() && s_->group.group_guid.IsEmpty() && !s_->led_by_player; } bool no_tag_stance() const { return s_->no_tag_stance; } @@ -197,6 +200,7 @@ public: bool transport_is_ship() const { return s_->environment.transport_is_ship; } bool is_underwater() const { return s_->environment.is_underwater; } float water_surface_z() const { return s_->environment.water_surface_z; } + int32 breath_left_ms() const { return s_->environment.breath_left_ms; } bool is_in_damaging_liquid() const { return s_->environment.is_in_damaging_liquid; } // Open-world water-escape focus (FIX #12): nearest DRY footing the builder // resolved while the bot is in swim-water; idle:water_escape drives to it. diff --git a/src/modules/PlayerbotV2/Bot/BotTextMgr.cpp b/src/modules/PlayerbotV2/Bot/BotTextMgr.cpp index 4d4ecd99aa..481c297c40 100644 --- a/src/modules/PlayerbotV2/Bot/BotTextMgr.cpp +++ b/src/modules/PlayerbotV2/Bot/BotTextMgr.cpp @@ -158,15 +158,9 @@ BotTextMgr::Row const* BotTextMgr::PickWeighted(std::vector const& rows, Ac return nullptr; } -BotTextMgr::Line BotTextMgr::Pick(std::string_view key, TextPlaceholders const& ph) const +BotTextMgr::Line BotTextMgr::FromRow(Row const* row, TextPlaceholders const& ph) { Line out; - auto it = texts_.find(std::string(key)); - if (it == texts_.end()) - return out; - Row const* row = PickWeighted(it->second, [](Row const&) { return true; }); - if (!row) - return out; out.text = row->text; out.yell = row->say_type == 1; Fill(out.text, ph); @@ -176,6 +170,44 @@ BotTextMgr::Line BotTextMgr::Pick(std::string_view key, TextPlaceholders const& return out; } +BotTextMgr::Line BotTextMgr::Pick(std::string_view key, TextPlaceholders const& ph) const +{ + auto it = texts_.find(std::string(key)); + if (it == texts_.end()) + return {}; + Row const* row = PickWeighted(it->second, [](Row const&) { return true; }); + return row ? FromRow(row, ph) : Line{}; +} + +BotTextMgr::Line BotTextMgr::PickKeys(std::vector const& keys, TextPlaceholders const& ph) const +{ + uint64 total = 0; + for (std::string_view key : keys) + { + auto it = texts_.find(std::string(key)); + if (it == texts_.end()) + continue; + for (Row const& r : it->second) + total += r.weight; + } + if (total == 0) + return {}; + uint64 roll = urand(0, uint32(std::min(total, 0xFFFFFFFFu) - 1)); + for (std::string_view key : keys) + { + auto it = texts_.find(std::string(key)); + if (it == texts_.end()) + continue; + for (Row const& r : it->second) + { + if (roll < r.weight) + return FromRow(&r, ph); + roll -= r.weight; + } + } + return {}; +} + std::string BotTextMgr::GetReply(ReplyType type, std::string const& other_name) const { auto it = texts_.find("reply"); @@ -1417,6 +1449,52 @@ std::string PickBanter(Banter kind, uint8 cls, Role role, BotPersonality const& bool const rude = pers.politeness == Politeness::Rude; bool const rp = pers.verbosity == Verbosity::Roleplay; + // The text table's banter_ key first (migration 0067), its role / class / personality + // variants merged in with the same conditionals as the builtin pools below; those pools stand + // for a server whose table has no banter rows. + char const* base = nullptr; + switch (kind) + { + case Banter::Ready: base = "banter_ready"; break; + case Banter::Wipe: base = "banter_wipe"; break; + case Banter::Thanks: base = "banter_thanks"; break; + case Banter::Ouch: base = "banter_ouch"; break; + case Banter::BossKill: base = "banter_bosskill"; break; + } + std::vector wanted = { base }; + auto add_key = [&](char const* suffix) { wanted.emplace_back(std::string(base) + suffix); }; + switch (kind) + { + case Banter::Ready: + if (tank) add_key("_tank"); + if (healer) add_key("_healer"); + else if (caster) add_key("_caster"); + if (rp) add_key("_rp"); + break; + case Banter::Wipe: + if (tank) add_key("_tank"); + if (healer) add_key("_healer"); + if (polite) add_key("_polite"); + if (rude) add_key("_rude"); + break; + case Banter::Thanks: + if (polite) add_key("_polite"); + if (rude) add_key("_rude"); + break; + case Banter::Ouch: + if (tank) add_key("_tank"); + if (caster) add_key("_caster"); + break; + case Banter::BossKill: + if (polite) add_key("_polite"); + if (tank) add_key("_tank"); + if (rp) add_key("_rp"); + break; + } + std::vector keys(wanted.begin(), wanted.end()); + if (std::string line = BotTextMgr::instance().GetKeys(keys); !line.empty()) + return line; + std::array pools{}; size_t n = 0; auto add = [&](LineSpan s) { pools[n++] = s; }; diff --git a/src/modules/PlayerbotV2/Bot/BotTextMgr.h b/src/modules/PlayerbotV2/Bot/BotTextMgr.h index 97ec0b3e19..79b25d3e7c 100644 --- a/src/modules/PlayerbotV2/Bot/BotTextMgr.h +++ b/src/modules/PlayerbotV2/Bot/BotTextMgr.h @@ -112,6 +112,12 @@ public: Line Pick(std::string_view key, TextPlaceholders const& ph = {}) const; std::string Get(std::string_view key, TextPlaceholders const& ph = {}) const { return Pick(key, ph).text; } + // One weighted random line among the merged rows of `keys` (a base key and its role / class / + // personality variants, e.g. 'banter_ready' + 'banter_ready_tank'). Keys without rows are skipped; + // empty when none of them has rows. + Line PickKeys(std::vector const& keys, TextPlaceholders const& ph = {}) const; + std::string GetKeys(std::vector const& keys, TextPlaceholders const& ph = {}) const { return PickKeys(keys, ph).text; } + // Random 'reply' row of the given type, %s filled with `other_name`. Empty when none. std::string GetReply(ReplyType type, std::string const& other_name) const; @@ -133,6 +139,9 @@ private: template static Row const* PickWeighted(std::vector const& rows, Accept&& accept); + // Row -> Line: text + say_type, placeholders filled; empty when an unfilled one remains. + static Line FromRow(Row const* row, TextPlaceholders const& ph); + std::unordered_map> texts_; std::unordered_map chance_; size_t count_ = 0; diff --git a/src/modules/PlayerbotV2/Bot/CcPick.h b/src/modules/PlayerbotV2/Bot/CcPick.h index afb60e039d..dad7e39346 100644 --- a/src/modules/PlayerbotV2/Bot/CcPick.h +++ b/src/modules/PlayerbotV2/Bot/CcPick.h @@ -2,7 +2,9 @@ // list: the pure choice behind State_Idle idle:dungeon_auto_cc_script. // // An eligible candidate is a live enemy of the script's priority list that no teammate has locked yet, that is not hitting the -// bot itself, is not the skull (the group's focus-kill mark) and whose creature type the CC spell accepts. Among them the +// bot itself, is not the skull (the group's focus-kill mark) and whose creature type the CC spell accepts. An idle mob also +// has to be one the tank can walk to: crowd control on an idle mob pulls its pack, and a pack the tank's pull passes by +// (another level, across a gap) comes to the group with nobody able to hold it. Among them the // group's kill focus (PveOrder::kill_focus, the first priority add of the script's list that is engaged) goes first: it is the // most dangerous caster, and once it is locked the coordinator moves the focus on to the next add (PveGroupCoordinator skips // adds a member has CC-locked), so the DPS burn a different one. Deadmines 2026-10-09: the Defias Evoker's Flamestrike (546 damage) @@ -24,6 +26,7 @@ struct CcCandidate bool is_skull = false; // the group's focus-kill mark bool wrong_type = false; // the CC spell cannot take its creature type (mechanical, ...) bool is_kill_focus = false; // the coordinator's current kill focus + bool tank_cannot_pull = false; // an idle mob the tank can only walk to the long way round, or not at all (PackPullGate.h) }; constexpr size_t kNoCcTarget = size_t(-1); @@ -34,7 +37,7 @@ inline size_t PickCcTarget(std::vector const& candidates) for (size_t i = 0; i < candidates.size(); ++i) { CcCandidate const& c = candidates[i]; - if (!c.in_priority_list || c.locked || c.hits_me || c.is_skull || c.wrong_type) + if (!c.in_priority_list || c.locked || c.hits_me || c.is_skull || c.wrong_type || c.tank_cannot_pull) continue; if (c.is_kill_focus) return i; diff --git a/src/modules/PlayerbotV2/Bot/ClassicHealCover.h b/src/modules/PlayerbotV2/Bot/ClassicHealCover.h index fbfe67454b..45cb51fd27 100644 --- a/src/modules/PlayerbotV2/Bot/ClassicHealCover.h +++ b/src/modules/PlayerbotV2/Bot/ClassicHealCover.h @@ -23,6 +23,10 @@ constexpr float kHealTankTroubleCover = 1.25f; // him to it, and he went on dropping while it cast. constexpr float kDamageRateTauMs = 3000.0f; +// How far ahead the damage of a member's own periodic auras is counted (GroupMemberSummary::aura_damage_due): one Greater Heal / Holy +// Light, the slowest heal that still has to land in time. +constexpr int32_t kAuraDueHorizonMs = 2500; + struct DamageRate { float per_s = 0.0f; // damage per second as of at_ms diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/DungeonScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/DungeonScript.cpp index e277e44344..793b8d39d0 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/DungeonScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/DungeonScript.cpp @@ -98,6 +98,10 @@ inline void MergeAdvice(DungeonAdvice& dst, DungeonAdvice const& src) cat(dst.tank_swap_on_spells, src.tank_swap_on_spells); cat(dst.soak_spells, src.soak_spells); cat(dst.bosses, src.bosses); + dst.keep_clear_of_carriers.insert(dst.keep_clear_of_carriers.end(), + src.keep_clear_of_carriers.begin(), src.keep_clear_of_carriers.end()); + dst.spread_from_bosses.insert(dst.spread_from_bosses.end(), + src.spread_from_bosses.begin(), src.spread_from_bosses.end()); dst.progression_waypoints.insert(dst.progression_waypoints.end(), src.progression_waypoints.begin(), src.progression_waypoints.end()); } diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/DungeonScript.h b/src/modules/PlayerbotV2/Bot/Dungeon/DungeonScript.h index ccfe6de6bf..79e9722c12 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/DungeonScript.h +++ b/src/modules/PlayerbotV2/Bot/Dungeon/DungeonScript.h @@ -64,6 +64,16 @@ struct DungeonAdvice // move ≥ N yards from allies (M+ Volcanic / Quaking aftershock, // raid debuffs that explode for AoE). std::vector spread_on_self_auras; + // A harmful aura on a player that hurts the players next to its carrier, and a carrier who cannot walk off (confused, stunned, + // rooted): every other member keeps `radius` yards from the carrier while it lasts. Shaper's Terrace Cinder's Conflagration + // 1310512 confuses its carrier for 4 s and every second burns every ally within 5 y of the carrier for 300 (16806). + struct CarrierClearance { uint32_t aura; float radius; }; + std::vector keep_clear_of_carriers; + // A boss whose spell lands on one player and hurts every ally within `radius` yards of that player: while the group fights + // it, the ranged members and the healer stand at least `radius` yards from every other member (the melee and the tank stay + // on the boss). Shaper's Terrace Vitrix's Poison Shock 1312870 hits its target and everyone within 10 y of it for 1270-1470. + struct BossSplashSpread { uint32_t boss; float radius; }; + std::vector spread_from_bosses; // Boss spell ids that, when seen mid-cast, require all bots to // stack on the boss / a designated target (raid stack-soaks). std::vector stack_on_cast_spells; @@ -306,6 +316,11 @@ public: // entry id) and must be fixed in bosses[], never masked here. virtual std::vector event_summoned_bosses() const { return {}; } + // Bosses of bosses[] that the instance script summons on the way (Majordomo after the eight runes, Ragnaros by Majordomo, + // Nefarian by Victor Nefarius): no creature row, still owed and killed for the clear. Only the smoketest's spawn check reads + // it (no_spawn is no data error for these). Unlike event_summoned_bosses() it does not loosen the dungeon's completion. + virtual std::vector scripted_spawn_bosses() const { return {}; } + // Doors (GO entries) of this dungeon that players open by hand although the door carries no lock that says so. A shut hand door // is normally known by its lock (BotSnapshotBuilder IsShutHandDoor: the Deadmines Heavy Doors' Quick Open). The Hall of Thanes' // Vault Door has no lock and no flag, the same data as the Iron Doors its switch and its bosses open, yet in the official sniff diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/PrePullCc.h b/src/modules/PlayerbotV2/Bot/Dungeon/PrePullCc.h index 2f3a8054f6..0e6b65e2b3 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/PrePullCc.h +++ b/src/modules/PlayerbotV2/Bot/Dungeon/PrePullCc.h @@ -5,6 +5,10 @@ // mark (MarksNeedOrder: crowd control on an idle mob is otherwise the owner's call, and a bot-led squad has no owner order). // The mage's autonomous marked CC (idle:dungeon_auto_cc_marked) does the Polymorph. The tank waits for the mob to read // is_cc_locked (or a refusal / the wait cap), then runs its pull back (BotAI::PullBackPlan). +// A mob whose formation comes with it (NearbyUnit::engage_calls_formation) is asked for "on the pull": the sheep on it would +// be the pull, with the tank not yet in it. The moon goes on the mob, the mage is not released for an idle mob, the tank +// pulls as soon as the moon is on, and the mage holds the mob once it is in the fight, as it runs in (the in-combat marked CC). +// The coordinator ends such a request when the mob reads held. #include "ObjectGuid.h" #include @@ -21,6 +25,7 @@ struct Request uint32 requested_ms = 0; uint32 done_ms = 0; // the tank stopped waiting (0 = still waiting) State state = State::Pending; + bool on_pull = false; // held once it is in the fight, never before the pull (its formation comes with it) }; inline constexpr uint32 kWaitCapMs = 8000; // the tank waits this long for the mob to be held ... @@ -28,6 +33,7 @@ inline constexpr uint32 kWaitHardCapMs = 20000; // ... and up to this long while inline constexpr float kSpellReachY = 30.0f; // Polymorph's range: a mage farther out is still walking in inline constexpr uint32 kLifeMs = 35000; // a request is dropped this long after it was opened (> hard cap + kAfterDoneMs) inline constexpr uint32 kAfterDoneMs = 12000; // the mark and the mage's release outlast the tank's wait by this +inline constexpr uint32 kMarkWaitMs = 2000; // an on-pull request: the tank waits this long at most for the moon to go on namespace detail { inline std::mutex& Mutex() { static std::mutex m; return m; } @@ -47,13 +53,13 @@ inline bool Get(uint64 group_low, uint32 now_ms, Request& out) } // Open a request unless the group has a live one. True when opened. -inline bool Open(uint64 group_low, ObjectGuid mob, uint64 caster_low, uint32 now_ms) +inline bool Open(uint64 group_low, ObjectGuid mob, uint64 caster_low, uint32 now_ms, bool on_pull = false) { Request cur; if (Get(group_low, now_ms, cur)) return false; std::lock_guard lk(detail::Mutex()); Request r; - r.mob = mob; r.caster_low = caster_low; r.requested_ms = now_ms ? now_ms : 1u; + r.mob = mob; r.caster_low = caster_low; r.requested_ms = now_ms ? now_ms : 1u; r.on_pull = on_pull; detail::Map()[group_low] = r; return true; } diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.cpp index 12cfaafc37..c8c1c4929e 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.cpp @@ -406,6 +406,21 @@ void PveGroupCoordinator::Update(uint32 now_ms) 100.0f * float(u.hp) / float(u.max_hp) <= rule.hpMax) want = std::max(want, mem.size()); } + // An encounter that sends tanked adds the whole fight (RaidRules::allTanks) has every live tank on the roster while it is on. + // naxx_kelthuzad kt62a (1123): the roster stayed at three (0-1 engaged Abominations at a time, the Soldiers and Weavers are no + // tank's) until 133 s; the bear Mctankda played DPS in Cat Form, an Abomination stood on it untanked, and the Abominations killed + // 15 of 43 with the three tanks on Mortal Wound swaps among themselves. + // The fight is the group's combat: a listed enemy alive near it is enough (kt66a/b: keyed on the enemy's own combat flag the + // roster went 4 -> 3 -> 4 three times in the first 70 s, between sent Soldiers). + if (Raid::RaidRules const* rules = Raid::RulesForMap(b.map_id); rules && !rules->allTanks.empty() && b.in_combat) + for (auto const& sn : snaps) + { + if (sn->position.map_id != b.map_id) continue; + for (auto const& u : sn->combat.nearby_enemies) + if (u.hp > 0 && + std::find(rules->allTanks.begin(), rules->allTanks.end(), u.entry) != rules->allTanks.end()) + want = std::max(want, mem.size()); + } // A melee-soak boss (RaidRules::meleeSoak, Patchwerk) needs the main tank and every soaker on the roster: with three, the // fourth tank played DPS, drank no Stoneshield and had no tank healer while the raid layer still sent it in as a soaker, and // the bear on the roster was not one of the raid layer's soakers (naxx_patchwerk 1115 night, [raid_soak]). @@ -1860,8 +1875,16 @@ void PveGroupCoordinator::PlanPrePullCc(uint64 bkey, uint64 group_low, uint32 ma group_low, map_id, cu->entry, pcc.mob.GetCounter(), caster->src->name); } } - // The mage may crowd-control the idle marked mob: the squad's tank asked for it (MarksNeedOrder). - if (pcc.state != PrePullCc::State::Refused) + // An on-pull request is done once the mob is held in the fight: the moon and the mage's assignment stay kAfterDoneMs more. + if (pcc.on_pull && !pcc.done_ms && cu->is_cc_locked) + { + PrePullCc::Done(group_low, now_ms); + TC_LOG_INFO("playerbot.v2", "[raid_pull] group={} map={} {} ({}) is held in the fight after {} ms", + group_low, map_id, cu->entry, pcc.mob.GetCounter(), uint32(now_ms - pcc.requested_ms)); + } + // The mage may crowd-control the idle marked mob: the squad's tank asked for it (MarksNeedOrder). Not on an on-pull + // request: the moon alone assigns the mob, and the hold waits for the mob to be in the fight (MarkGate::MayEngage). + if (pcc.state != PrePullCc::State::Refused && !pcc.on_pull) if (auto pit = plan.find(pcc.caster_low); pit != plan.end()) pit->second.marks_released = true; } @@ -1918,7 +1941,15 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma if (Raid::GetBrain().AllSchoolsAvoided(group_low, map_id, u.guid)) continue; if (find_mob(u.guid)) continue; Member const* v = member_of(u.victim); - mobs.push_back({ &u, v && !v->tank }); + // A mob on a tank whose raid order forbids it that mob is loose too: that tank does not hold it, so another tank has to take + // it. naxx_kelthuzad kt70f (1125): the first Abomination was sent at the bear, which takes none (TankSpot::skipClassMask); + // the bear dropped it ("the raid order forbids it") for 10 s while the three warriors stood at their slots with nothing, + // counting it held, until it turned on Mcmagee in the camp and killed it at 43 s. + bool forbiddenOnTank = false; + if (v && v->tank) + if (RaidOrder const* ro = Raid::GetBrain().OrderFor(v->guid_low); ro && ro->active) + forbiddenOnTank = std::find(ro->forbidden_targets.begin(), ro->forbidden_targets.end(), u.guid) != ro->forbidden_targets.end(); + mobs.push_back({ &u, v && (!v->tank || forbiddenOnTank) }); } } @@ -1959,6 +1990,8 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma auto raid_forbids = [&](uint64 tank_low, ObjectGuid mob) -> bool { RaidOrder const* ro = Raid::GetBrain().OrderFor(tank_low); + if (ro && ro->active && ro->no_tank_off && Raid::NoTank(map_id, mob.GetEntry())) + return true; return ro && ro->active && std::find(ro->forbidden_targets.begin(), ro->forbidden_targets.end(), mob) != ro->forbidden_targets.end(); }; for (auto it = sticky.begin(); it != sticky.end();) @@ -2255,8 +2288,10 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma if (!pick || is_taken(pick->u->guid)) { pick = nullptr; + // Not one the raid order forbids this tank: naxx_kelthuzad kt69i (1124), a Soldier of the Frozen Wastes sent at the main tank + // was handed to it 57 times from 50 y out ("takes Soldier ... on Mctankwa why=on_main_tank"), past the fixed row's forbid. for (auto const& m : mobs) - if (m.u->victim == t->src->guid && !is_taken(m.u->guid) && + if (m.u->victim == t->src->guid && !is_taken(m.u->guid) && !raid_forbids(t->guid_low, m.u->guid) && !(Raid::TankLast(map_id, m.u->entry) && other_free_mob(m.u->guid))) { pick = &m; why = "on_main_tank"; break; } } if (!pick) { pick = nearest_free(t); why = "nearest"; } @@ -2325,7 +2360,11 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma Mob const* held = find_mob(sit->second); if (!held || held->u->is_dungeon_boss || held->u->is_boss_rank || Raid::OffTankMob(map_id, held->u->entry)) continue; if (mk_grp && (sit->second == mk_grp->GetTargetIcon(7) || sit->second == mk_grp->GetTargetIcon(6))) continue; - int const have = prio_of(*held); + // A summoned add no tank is meant to hold (RaidRules::noTank) is held only while nothing else needs the tank: any loose + // mob it may tank outranks it. naxx_kelthuzad kt61b (1122): the free tanks took Soldiers of the Frozen Wastes 57 y off + // (why=loose_nearest) and Soul Weavers, both priority equal to or above the Abominations', and kept them while an + // Abomination stood on a mage 12 s; the Abominations killed 35 of 43. + int const have = Raid::NoTank(map_id, held->u->entry) ? 0 : prio_of(*held); if (have >= want) continue; const float dx = m.u->x - t->src->x, dy = m.u->y - t->src->y; const float d2 = dx * dx + dy * dy; @@ -2979,10 +3018,13 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma fl.dmg_total = 0; fl.dmg_last_ms = 0; fl.start_mana.clear(); + fl.dps_label.clear(); for (auto const& e : mem) { TakeDamageDone(e.guid_low, true); if (e.src && e.src->max_mana > 0) fl.start_mana[e.guid_low] = Pct(e.src->mana, e.src->max_mana); + if (e.src && e.is_bot && !e.tank && !e.healer) + fl.dps_label[e.guid_low] = std::string(e.src->name) + "(" + ShortClass(e.cls) + ")"; } uint32 alive = 0, tanks = 0, healers = 0; for (auto const& e : mem) @@ -3071,8 +3113,10 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma if (listed++ >= 8) continue; if (!mob_txt.empty()) mob_txt += ", "; Member const* v = member_of(m.u->victim); - mob_txt += MobName(m.u->entry) + " " + std::to_string(Pct(m.u->hp, m.u->max_hp)) + "%>" + - (v ? v->src->name : std::string("pet")) + (m.loose ? "!" : ""); + // The creature's guid counter (#n): one add's life can be followed from line to line (naxx_kelthuzad: how long each Soul + // Weaver lives, from its first line to its last). + mob_txt += MobName(m.u->entry) + " #" + std::to_string(m.u->guid.GetCounter()) + " " + std::to_string(Pct(m.u->hp, m.u->max_hp)) + + "%>" + (v ? v->src->name : std::string("pet")) + (m.loose ? "!" : ""); // Where a boss is: a boss dragged off his spot shows in the line (naxx_horsemen r23: Sir Zeliek's Holy Wrath killed raiders at // Mograine's corner and then at Korth'azz's, and the log could not say where Zeliek stood; Heigan pulled 40 y west, Feugen across). if (m.u->is_dungeon_boss || m.u->is_boss_rank) @@ -3172,6 +3216,14 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma rows.emplace_back(d, std::string(e.src->name) + "(" + ShortClass(e.cls) + ") " + std::to_string(d) + " (" + std::to_string(d / dur) + "/s" + mana + ")"); } + for (auto const& [low, label] : fl.dps_label) + { + if (std::any_of(mem.begin(), mem.end(), [&](auto const& e) { return e.guid_low == low; })) + continue; // listed above + if (uint64 const d = TakeDamageDone(low, true)) + rows.emplace_back(d, label + " " + std::to_string(d) + " (" + std::to_string(d / dur) + "/s, dead)"); + } + fl.dps_label.clear(); std::sort(rows.begin(), rows.end(), [](auto const& a, auto const& b) { return a.first > b.first; }); std::string txt; for (auto const& r : rows) { if (!txt.empty()) txt += ", "; txt += r.second; } @@ -3694,6 +3746,7 @@ void PveGroupCoordinator::PlanSightPull(uint64 bkey, uint64 group_low, uint32 ma constexpr float kArrivedYd = 10.0f; // a mob this close to the spot has come in // b3ca0b4b67 overnight: a spot the mobs did not come to held the group for 20 s; 12 s is a caster's walk round a corner and back. constexpr uint32 kSightPullCapMs = 12000; + constexpr uint32 kSightPullSpentMs = 120000; // a mob a plan ended on is left to the tank this long (SightPull::spent) constexpr float kSideYd = 2.0f; // the spot stays hidden this far to each side of it constexpr float kFloorDz = 4.0f; // the spot is on the return point's floor constexpr float kMaxPathYd = 35.0f; @@ -3882,15 +3935,27 @@ void PveGroupCoordinator::PlanSightPull(uint64 bkey, uint64 group_low, uint32 ma } if (left.empty()) return end("every mob that stood off has come in"); + auto spend = [&](std::vector const& mobs) + { + for (ObjectGuid const& g : mobs) + sp.spent[g.GetCounter()] = now_ms ? now_ms : 1u; + }; if (now_ms - sp.since_ms > kSightPullCapMs) - return end(fmt::format("{} s cap, {} still out", kSightPullCapMs / 1000u, left.size()).c_str()); + { + spend(left); + return end(fmt::format("{} s cap, {} still out, left to the tank for {} s", kSightPullCapMs / 1000u, left.size(), + kSightPullSpentMs / 1000u).c_str()); + } if (seen_again) { float x = 0.f, y = 0.f, z = 0.f; std::string why; if (sp.replans >= 1 || !search(stopped, sp.x, sp.y, sp.z, x, y, z, why)) + { + spend(left); return end(fmt::format("a mob stopped with the spot in its sight: {}{}", names(stopped), why.empty() ? std::string() : " (" + why + ")").c_str()); + } ++sp.replans; TC_LOG_INFO("playerbot.v2", "[sight_pull] group={} map={} {} stopped with the spot ({:.1f},{:.1f}) in sight: new spot ({:.1f},{:.1f},{:.1f})", group_low, map_id, names(stopped), sp.x, sp.y, x, y, z); @@ -3925,9 +3990,11 @@ void PveGroupCoordinator::PlanSightPull(uint64 bkey, uint64 group_low, uint32 ma float const ay = pulling_back ? pb.ry : tank->GetPositionY(); float const az = pulling_back ? pb.rz : tank->GetPositionZ(); char const* const from = pulling_back ? "the return point" : "the tank"; + for (auto it = sp.spent.begin(); it != sp.spent.end();) + it = now_ms - it->second >= kSightPullSpentMs ? sp.spent.erase(it) : std::next(it); std::vector mobs; for (Creature* c : standing) - if (dist2(c->GetPositionX(), c->GetPositionY(), ax, ay) <= kStandOffNearYd * kStandOffNearYd) + if (dist2(c->GetPositionX(), c->GetPositionY(), ax, ay) <= kStandOffNearYd * kStandOffNearYd && !sp.spent.count(c->GetGUID().GetCounter())) mobs.push_back(c); if (mobs.empty()) return; diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.h b/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.h index 873bb2282f..c193f9ff4b 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.h +++ b/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.h @@ -119,6 +119,9 @@ private: uint32 dmg_last_ms = 0; // Mana % of each member when the pull started, for the [raid_dps] line. std::unordered_map start_mana; + // The damage dealers at the pull's start ("Mcmagea(Mag)"), so [raid_dps] also lists the ones dead by its end: the members of the + // last plan are the living ones only (naxx_kelthuzad kt69j: 2 of 24 listed). + std::unordered_map dps_label; }; // Raid tank -> mob assignment for one (group, map) bucket, the generic @@ -277,6 +280,10 @@ private: uint8 replans = 0; // the spot was searched again (a mob saw it from where it stopped next) std::vector mobs; // the mobs still standing off uint32 no_spot_log_ms = 0; + // Mobs a plan ended on while they were still out there (the cap, or one that stopped with the spot in sight), and when: a plan + // does not start on them again for kSightPullSpentMs, so the tank's own rules go and fetch them (wc_full af69i: a Deviate + // Venomwing 50-60 y off held the group at the spot in 12 s plans, one after the other, for the last five minutes of the run). + std::unordered_map spent; }; std::unordered_map sight_pull_; uint32 last_plan_ms_ = 0; diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/AlcazPrisonScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/AlcazPrisonScript.cpp index dfa7a4d701..b2d53c5359 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/AlcazPrisonScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/AlcazPrisonScript.cpp @@ -1,8 +1,11 @@ // AlcazPrisonScript - per-dungeon advice for Alcaz Prison (map 2994, Classic 1.60 Forever, levels 50-55). -// The creatures and the boss fights are in classic_instance_alcaz_prison.cpp and 2026_11_14_41_world_forever_alcaz_prison.sql; -// the route (playerbot_dungeon_routes, 0043_alcaz_prison_route.sql) and this file follow the same boss order: -// Overseer Wrex, Katerina the Cleaner, The Questioner, Tidemistress Ca'zass, Blazeroar (the shortest walk through the -// prison that keeps Wrex first and Blazeroar last; every leg was path-checked on the 2994 navmesh). +// The creatures and the boss fights are in classic_instance_alcaz_prison.cpp and the world SQL (since 2026_11_27_40: live's layout, +// from Karrz's capture of a full clear on 26 Nov); the route (playerbot_dungeon_routes, 0071_alcaz_prison_route_as_live_clears_it.sql) +// and this file follow live's kill order: Overseer Wrex, Katerina the Cleaner, Blazeroar, The Questioner. The doors decide it. From the +// landing only Wrex's wing is open. The Maximum Security Door (649547) to Katerina and Blazeroar takes Wrex's Overseer's Keyring or +// Lockpicking 250: on live the group's rogue picked it, and the bots' rogue does the same (idle:dungeon_open_hand_door, pick_lock). +// The Prison Gate (649552) to The Questioner has no lock and shuts 3 s after each use; every bot opens it for itself (hand_doors). +// Tidemistress Ca'zass is not on live and not spawned. #include "../DungeonScript.h" @@ -21,7 +24,7 @@ public: DungeonAdvice a; // The casters of the packs: their bolts are the spike damage on the group. a.high_priority_kill_entries = { - 255373, // Strashaz Enchantress (Lightning Bolt, Frost Shock; two of them join Ca'zass) + 255373, // Strashaz Enchantress (Lightning Bolt, Frost Shock) 255364, // Renegade Conjurer (Frostbolt, Frost Nova) 255262, // Alcaz Chaplain (two of them join Katerina) }; @@ -38,23 +41,29 @@ public: 260386, // Commander Folkar 264770, // Mason Connery }; + // Live's order (capture 26 Nov, 21:59-22:13). a.bosses = { 255391, // Overseer Wrex 257016, // Katerina the Cleaner - 256236, // The Questioner - 255997, // Tidemistress Ca'zass 255702, // Blazeroar + 256236, // The Questioner }; - // 1:1 with `bosses`: their spawn spots (guids 48120006, 48120043, 48120052, 48120017, 48120077). + // 1:1 with `bosses`: live's spots (2026_11_27_40; the Questioner walks between this spot and (-8762.1, 2845.5)). a.progression_waypoints = { - { -8762.0f, 2852.0f, 14.0f }, // Overseer Wrex - { -8852.0f, 2888.0f, 14.02f }, // Katerina the Cleaner - { -8888.0f, 2888.0f, 14.42f }, // The Questioner - { -8728.0f, 2932.0f, 6.15f }, // Tidemistress Ca'zass - { -8890.0f, 2966.0f, 5.89f }, // Blazeroar + { -8885.8f, 2921.3f, 14.91f }, // Overseer Wrex + { -8808.5f, 2971.1f, 6.01f }, // Katerina the Cleaner + { -8901.2f, 2971.5f, 5.89f }, // Blazeroar + { -8773.0f, 2854.2f, 13.86f }, // The Questioner }; return a; } + + // The Prison Gate to The Questioner: no lock, a click opens it (and it shuts again 3 s later). + std::vector hand_doors() const override { return { 649552 }; } + + // Tidemistress Ca'zass keeps her boss slot (the client's DungeonEncounter 3410, as live) but live spawns her nowhere Karrz went, and + // neither do we (2026_11_27_40): her encounter stays NOT_STARTED, so the clear is complete without her. + std::vector event_summoned_bosses() const override { return { 255997 }; } }; } // anonymous diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/BlackmawHoldScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/BlackmawHoldScript.cpp index afe71c861c..3e68c94cf2 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/BlackmawHoldScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/BlackmawHoldScript.cpp @@ -1,8 +1,10 @@ // BlackmawHoldScript - per-dungeon advice for Blackmaw Hold (map 2974, Classic 1.60 Forever, levels 55-60). -// The creatures and the boss fights are in classic_instance_blackmaw_hold.cpp and 2026_11_19_70/71_world_forever_blackmaw_hold; -// the route (playerbot_dungeon_routes, 0044_blackmaw_hold_route.sql) and this file follow the same boss order: Withermaw, -// Bonesnout the Unbroken, Impaan the Imprisoner, the Unbound Spirit, the Blackmaw Behemoth, Elder Shaman Bloodmane, Varrox -// Bleakhoof (the shortest walk from the landing that ends at Varrox; every leg was path-checked on the 2974 navmesh). +// The boss fights are in classic_instance_blackmaw_hold.cpp, the creatures where live has them in 2026_11_26_41 (a live capture of +// 25-26 Nov 2026); the route (playerbot_dungeon_routes, 0069_blackmaw_hold_route_from_the_live_landing.sql) and this file follow +// the same boss order: Withermaw, Bonesnout the Unbroken, Impaan the Imprisoner, the Unbound Spirit, Elder Shaman Bloodmane, the +// Blackmaw Behemoth, Varrox Bleakhoof (the shortest walk from live's landing that ends with the Behemoth; every leg was path-checked +// on the 2974 navmesh). Varrox waits in a chamber 200 y below the Behemoth's hall: the way down is a one-way fall into a pool +// (0069's nav link) with no way back up, so he is last. // The Unbound Spirit cannot be hit until Elder Bramblesnap's ritual has run; it starts when the group comes near him, so // walking to the Spirit's spot is enough. @@ -48,19 +50,19 @@ public: 247198, // Bonesnout the Unbroken 247206, // Impaan the Imprisoner 247231, // Unbound Spirit - 247207, // Blackmaw Behemoth 247209, // Elder Shaman Bloodmane + 247207, // Blackmaw Behemoth 247234, // Varrox Bleakhoof }; - // 1:1 with `bosses`: their spawn spots (2026_11_19_70_world_forever_blackmaw_hold.sql). + // 1:1 with `bosses`: live's spawn spots (2026_11_26_41_world_forever_blackmaw_hold_live_spawns.sql). a.progression_waypoints = { - { 3694.7f, 3428.0f, 302.4f }, // Withermaw - { 3386.7f, 3370.7f, 249.98f }, // Bonesnout the Unbroken - { 3320.0f, 3578.7f, 343.74f }, // Impaan the Imprisoner - { 3265.0f, 2920.0f, 205.09f }, // Unbound Spirit (Elder Bramblesnap stands 14 y away) - { 3665.0f, 2905.0f, 172.26f }, // Blackmaw Behemoth - { 3484.98f, 2968.62f, 138.75f }, // Elder Shaman Bloodmane - { 3556.27f, 2819.47f, 175.98f }, // Varrox Bleakhoof + { 3734.3f, 3369.2f, 284.2f }, // Withermaw (by her grotto; the Tunnelweb Matriarch stands 98 y north-west) + { 3297.8f, 3409.8f, 250.0f }, // Bonesnout the Unbroken + { 3348.1f, 3641.9f, 342.9f }, // Impaan the Imprisoner + { 3249.1f, 2911.5f, 204.9f }, // Unbound Spirit (Elder Bramblesnap stands 45 y away) + { 3681.3f, 2868.8f, 172.2f }, // Elder Shaman Bloodmane (the east cave) + { 3479.6f, 2962.0f, 136.6f }, // Blackmaw Behemoth (low in the west hall, Clawbert with him) + { 3482.4f, 3001.0f, -62.5f }, // Varrox Bleakhoof (the chamber below the hall, by the Instance Portal) }; return a; } diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/BlackwingLairScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/BlackwingLairScript.cpp index 93f27611fb..fdf3b278ef 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/BlackwingLairScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/BlackwingLairScript.cpp @@ -18,6 +18,13 @@ public: uint32_t map_id() const override { return 469; } char const* name() const override { return "blackwing_lair"; } + std::vector scripted_spawn_bosses() const override + { + return { + 11583, // Nefarian: summoned by Lord Victor Nefarius (classic_boss_victor_nefarius) + }; + } + DungeonAdvice get_advice(BotSnapshotView const& /*s*/) const override { DungeonAdvice a; diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/DeadminesScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/DeadminesScript.cpp index 2a28f94778..07250cd12d 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/DeadminesScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/DeadminesScript.cpp @@ -63,7 +63,7 @@ DungeonAdvice DeadminesClassicAdvice() { -22.8f, -797.3f, 20.4f }, // Mr. Smite { -69.0f, -808.0f, 40.8f }, // Captain Greenskin { -87.4f, -819.9f, 39.3f }, // Edwin VanCleef - { -67.6f, -853.7f, 17.1f }, // Cookie + { -110.0f, -844.9f, 16.9f }, // Cookie (his spawn; the old spot was 43 y off it) }; return a; } diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/DireMaulScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/DireMaulScript.cpp index 411885a6f9..75e137ee8b 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/DireMaulScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/DireMaulScript.cpp @@ -103,7 +103,7 @@ public: 11467, // Tsu'zee 11496, // Immol'thar 11486 }, // Prince Tortheldrin (West final) - { { 13.5f, 478.3f, -23.3f }, { -106.3f, 551.3f, -4.4f }, { -14.6f, 542.1f, 28.6f }, { 128.6f, 561.8f, -4.3f }, + { { 13.5f, 478.3f, -23.3f }, { 41.5f, 577.9f, -3.6f }, { -14.6f, 542.1f, 28.6f }, { 128.6f, 561.8f, -4.3f }, { -40.5f, 811.1f, -29.4f }, { 132.6f, 625.9f, -48.4f } }, { 33.1083f, 158.977f, -3.47126f } }, { { 14326, // Guard Mol'dar diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/ExcavationSiteScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/ExcavationSiteScript.cpp index 70b700b83d..8e5e9c6a4d 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/ExcavationSiteScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/ExcavationSiteScript.cpp @@ -1,6 +1,6 @@ // ExcavationSiteScript - Excavation Site: Wetlands (Forever, map 2998, levels 25-30). // Encounters (DungeonEncounter.db2): Saltspine, Shadetooth, Highland Horror, Relic Guardian (last). The Relic Guardian sleeps -// uninteractible until someone uses the Archival Panel (classic_instance_excavation_site_wetlands.cpp). +// uninteractible until someone uses the Archival Panel (classic_instance_excavation_site_wetlands.cpp); the tank uses it. // // Without a script the tank had no boss to walk to: it cleared every pack it could see, walking north away from Saltspine // (-3935,-2019) and never closer than about 100 y to him, until the priest was dry from 20 minutes of trash fights @@ -26,14 +26,19 @@ public: 260322, // Saltspine 260325, // Shadetooth 260808, // Highland Horror + 260326, // Relic Guardian (last) }; - // The Relic Guardian (260326) is left out: he cannot be attacked until the Archival Panel is used. // The waypoints are the boss spawns (world DB), index for index with the bosses above. a.progression_waypoints = { { -3935.1f, -2019.2f, 146.2f }, // Saltspine { -3826.9f, -1824.0f, 137.1f }, // Shadetooth { -3782.6f, -1634.0f, 134.0f }, // Highland Horror + { -3987.7f, -1917.2f, 163.2f }, // Relic Guardian }; + // The Relic Guardian sleeps (uninteractible) until someone uses the Archival Panel 18 y from him, as players do. Walking to + // his waypoint brings the tank within reach of the panel, and idle:dungeon_use_gate_lever uses it while he is alive; he + // wakes and attacks whoever used it. Without this the bots stopped after the Highland Horror and the run never ended. + a.use_go_entries = { 640041 }; // Archival Panel return a; } }; diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/LowerBlackrockSpireScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/LowerBlackrockSpireScript.cpp index 7af0af17e0..baea301920 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/LowerBlackrockSpireScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/LowerBlackrockSpireScript.cpp @@ -28,6 +28,13 @@ public: }; } + std::vector scripted_spawn_bosses() const override + { + return { + 10339, // Gyth: summoned by Lord Victor Nefarius after the stadium waves (classic_instance_blackrock_spire) + }; + } + DungeonAdvice get_advice(BotSnapshotView const& s) const override { DungeonAdvice a; diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/MoltenCoreScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/MoltenCoreScript.cpp index 390f72757b..06c1fe1a0e 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/MoltenCoreScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/MoltenCoreScript.cpp @@ -18,6 +18,14 @@ public: uint32_t map_id() const override { return 409; } char const* name() const override { return "molten_core"; } + std::vector scripted_spawn_bosses() const override + { + return { + 12018, // Majordomo Executus: summoned when the eight runes are out (classic_instance_molten_core) + 11502, // Ragnaros: summoned by Majordomo's event (classic_boss_majordomo_executus) + }; + } + DungeonAdvice get_advice(BotSnapshotView const& /*s*/) const override { DungeonAdvice a; diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/NaxxramasScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/NaxxramasScript.cpp index 9514d6766f..4b4a5241f4 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/NaxxramasScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/NaxxramasScript.cpp @@ -22,6 +22,13 @@ public: uint32_t map_id() const override { return 533; } char const* name() const override { return "naxxramas"; } + std::vector scripted_spawn_bosses() const override + { + return { + 15989, // Sapphiron: summoned by the instance (classic_instance_naxxramas) + }; + } + DungeonAdvice get_advice(BotSnapshotView const& /*s*/) const override { DungeonAdvice a; @@ -164,8 +171,10 @@ public: { 2642.1f, -3387.0f, 285.5f }, // Gothik the Harvester { 2520.5f, -2955.4f, 245.6f }, // Four Horsemen room // Construct Quarter - { 3256.4f, -3230.3f, 294.1f }, // Patchwerk - { 3227.6f, -3378.3f, 311.3f }, // Grobbulus + // Patchwerk and Grobbulus stood at other spots (3256.4,-3230.3 and 3227.6,-3378.3), 52 y and 44 y from their Classic spawns + // (af59c boss smoketest, DungeonBossSpawns); every other boss here sits on its spawn. Both spawns are reachable on the mesh. + { 3308.5f, -3232.1f, 294.2f }, // Patchwerk + { 3205.4f, -3341.9f, 320.2f }, // Grobbulus { 3283.1f, -3157.0f, 297.8f }, // Gluth { 3513.8f, -2926.6f, 302.9f }, // Thaddius // Frostwyrm Lair diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/RazorfenDownsScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/RazorfenDownsScript.cpp index a5c4a1e484..48229dc330 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/RazorfenDownsScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/RazorfenDownsScript.cpp @@ -87,7 +87,7 @@ public: { 2468.7f, 1006.8f, 23.8f }, // Glutton { 2466.6f, 671.4f, 63.5f }, // Mordresh Fire Eye { 2403.4f, 960.9f, 55.1f }, // Amnennar the Coldbringer - { 2413.0f, 1025.9f, 37.9f }, // Ragglesnout + { 2453.3f, 947.5f, 36.0f }, // Ragglesnout (his spawn; the old spot was 88 y off it) }; return a; } diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/RuinsOfLordaeronScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/RuinsOfLordaeronScript.cpp index 7087730d4d..3927f4b560 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/RuinsOfLordaeronScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/RuinsOfLordaeronScript.cpp @@ -20,6 +20,13 @@ public: uint32_t map_id() const override { return 2999; } char const* name() const override { return "ruinsoflordaeron"; } + std::vector scripted_spawn_bosses() const override + { + return { + 250631, // The Abandoned: comes out of the statue (classic_instance_ruins_of_lordaeron) + }; + } + DungeonAdvice get_advice(BotSnapshotView const& /*s*/) const override { DungeonAdvice a; diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/ShadowfangKeepScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/ShadowfangKeepScript.cpp index 2e2be21ce8..f7af658a41 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/ShadowfangKeepScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/ShadowfangKeepScript.cpp @@ -44,6 +44,15 @@ DungeonAdvice ShadowfangKeepClassicAdvice() }; // Fenrus the Devourer's Toxic Saliva (spell_template: periodic damage, poison), cleansed first. a.dispel_priority_spells = { 7125 }; + // The Courtyard Door to Razorclaw opens when a prisoner of Rethilgore's cells is freed: a player talks to him once Rethilgore is + // dead (gossip 301 / 302, the first option), he walks to the door and opens it (his waypoint script sets the instance's free-NPC + // data). Sorcerer Ashcrombe speaks to the Alliance, Deathstalker Adamant to the Horde; the other one is hostile and is left + // alone. Spawns from the Classic creature data (map 33). Nobody talked to them, so the party walked back and forth at the shut + // door for 45 minutes (sfk_full af58). + a.door_talks = { + { 3850, -240.9f, 2122.6f, 81.3f, 3886, { 3914 } }, // Sorcerer Ashcrombe + { 3849, -243.7f, 2113.7f, 81.3f, 3886, { 3914 } }, // Deathstalker Adamant + }; a.bosses = { 3914, // Rethilgore 3886, // Razorclaw the Butcher diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/ShapersTerraceScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/ShapersTerraceScript.cpp index 40625b6079..c80c3568cf 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/ShapersTerraceScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/ShapersTerraceScript.cpp @@ -1,9 +1,12 @@ // ShapersTerraceScript - per-dungeon advice for The Shaper's Terrace (map 3001, Classic 1.60 Forever, levels 58-60). // The creatures and the boss fights are in classic_instance_shapers_terrace.cpp and 2026_11_19_72_world_forever_shapers_terrace.sql; -// the route (playerbot_dungeon_routes, 0045_shapers_terrace_route.sql) and this file follow the same boss order: Venomridge, Bolt, -// Cinder, Tor'Rel and Izha'Rel, Snowtalon, Vitrix, Titanosaur, Thunderhoof, King Op, the Direhorn Matriarch, Nanaya (the shortest -// walk from the landing that ends at Nanaya, about 4150 y; the journal's order would be 10100 y; every leg was path-checked on the -// 3001 navmesh). +// the route (playerbot_dungeon_routes, 0070_shapers_terrace_route_not_through_the_titanic_door.sql) and this file follow the same boss +// order, one wing at a time from live's landing ledge (the bots jump off it into the pool, a nav link): the north (Cinder, Snowtalon, +// Vitrix), the middle (Tor'Rel and Izha'Rel, Venomridge, Bolt), the south (Thunderhoof, King Op, the Direhorn Matriarch), +// then Nanaya (the shortest walk from the pool that ends at Nanaya, about 4140 y; every leg was path-checked on the 3001 navmesh). +// The standing bosses are at live's spots (world 2026_11_25_82, Karrz's capture of 25 Nov 2026); the five live summons at their +// panels stand at ours, Snowtalon beside his ice panel. The Titanosaur is not a boss of the dungeon: he stands behind the Titanic +// Door, live's locked raid gate (Karrz used it 12 times, it never opened), and a closed door is not walked through. #include "../DungeonScript.h" @@ -29,32 +32,43 @@ public: 1291380, // Chain Lightning (Nanaya, yellow panel) 8364, // Blizzard (Nanaya, blue panel) }; + // Cinder's Conflagration confuses a player who is not the tank for 4 s and every second burns every ally within 5 y of them + // for 300 (16806, radius index 8; the area check adds the 1.5 y combat reach of whoever it hits). shapers_full af61 (22 Nov): + // the five stood within 5 y of each other at Cinder and the mage died to it. The others keep 7 y from its carrier. + a.keep_clear_of_carriers = { + { 1310512, 7.0f }, // Conflagration (Cinder) + }; + // Vitrix's Poison Shock (1312870, instant, radius index 13: 10 y round its target) hit two of the group for 1269 and 1470 in + // one cast at 6.5 and 10.1 y from him (shapers_full af63, 23 Nov), and the priest, healing the stack through every cast, ran + // out of mana. The ranged and the healer spread 10 y from everyone. + a.spread_from_bosses = { + { 272561, 10.0f }, // Vitrix + }; a.bosses = { - 261813, // Venomridge - 262081, // Bolt 261974, // Cinder - 261811, // Tor'Rel (with Izha'Rel) 262297, // Snowtalon 272561, // Vitrix - 253201, // Titanosaur + 261811, // Tor'Rel (with Izha'Rel) + 261813, // Venomridge + 262081, // Bolt 261812, // Thunderhoof 261993, // King Op 262127, // Direhorn Matriarch 261809, // Nanaya }; - // 1:1 with `bosses`: their spawn spots (2026_11_19_72_world_forever_shapers_terrace.sql). + // 1:1 with `bosses`: their spawn spots (2026_11_25_82_world_forever_shapers_terrace_live_spawns.sql; the summoned five from + // 2026_11_22_79, Snowtalon moved by 82). a.progression_waypoints = { - { -5912.5f, -1220.8f, 8.88f }, // Venomridge - { -5935.0f, -1181.8f, 9.05f }, // Bolt - { -5904.2f, -862.5f, 112.81f }, // Cinder - { -5687.5f, -745.8f, 25.93f }, // Tor'Rel - { -5687.5f, -604.2f, 13.02f }, // Snowtalon - { -5520.8f, -845.8f, 22.18f }, // Vitrix - { -5662.5f, -1454.2f, 36.37f }, // Titanosaur - { -6020.8f, -1554.2f, 9.37f }, // Thunderhoof - { -6020.8f, -1829.2f, 57.07f }, // King Op - { -5729.2f, -1762.5f, 34.07f }, // Direhorn Matriarch - { -5854.2f, -1587.5f, 37.14f }, // Nanaya + { -5904.2f, -862.5f, 113.15f }, // Cinder + { -5443.1f, -792.4f, 21.75f }, // Snowtalon + { -5520.8f, -845.8f, 22.67f }, // Vitrix + { -5628.3f, -1223.8f, 33.84f }, // Tor'Rel + { -5908.8f, -1192.2f, 6.80f }, // Venomridge + { -5933.0f, -1183.3f, 9.12f }, // Bolt + { -5952.4f, -1463.5f, 8.57f }, // Thunderhoof + { -6107.1f, -1971.4f, 43.60f }, // King Op + { -5862.1f, -1739.6f, 13.21f }, // Direhorn Matriarch + { -5854.2f, -1587.5f, 37.31f }, // Nanaya }; return a; } diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/StratholmeScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/StratholmeScript.cpp index beb6c3417e..6123739d1b 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/StratholmeScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/StratholmeScript.cpp @@ -30,6 +30,13 @@ public: }; } + std::vector scripted_spawn_bosses() const override + { + return { + 10439, // Ramstein the Gorger: summoned by the instance after the abominations (classic_instance_stratholme) + }; + } + DungeonAdvice get_advice(BotSnapshotView const& s) const override { DungeonAdvice a; diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/TempleOfAhnQirajScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/TempleOfAhnQirajScript.cpp index 02beaf65ec..7d3f109796 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/TempleOfAhnQirajScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/TempleOfAhnQirajScript.cpp @@ -112,7 +112,7 @@ public: // creature row — skipped); Eye/Body of C'Thun share a spawn. a.progression_waypoints = { { -8346.0f, 2081.0f, 125.7f }, // Prophet Skeram - { -8598.5f, 2165.3f, -4.0f }, // Bug Trio chamber (Vem spawn) + { -8598.5f, 2165.3f, -4.0f }, // Bug Trio chamber: node 14 of Vem's patrol (path 800876030), 11 y from Yauj { -8302.5f, 1657.7f, -29.8f }, // Battleguard Sartura { -8085.4f, 1196.7f, -92.0f }, // Fankriss the Unyielding { -7992.4f, 908.2f, -52.6f }, // Viscidus diff --git a/src/modules/PlayerbotV2/Bot/Formation.cpp b/src/modules/PlayerbotV2/Bot/Formation.cpp index e0e48aa2f3..fa9e9fd8a2 100644 --- a/src/modules/PlayerbotV2/Bot/Formation.cpp +++ b/src/modules/PlayerbotV2/Bot/Formation.cpp @@ -139,7 +139,9 @@ FormationOffset ComputeOwnerSlotOffset(FormationType type, uint32_t index, uint3 // Concentric rings round the owner, inner rings first (tanks and melee, the order the caller sorted by), each ring // holding as many bots as fit `spacing` apart on its circumference. 40 bots make four compact rings instead of one // 25 y circle. The outer ring is spread evenly over the bots it actually has; odd rings are turned half a step so - // nobody stands directly behind another. Slot 0 is directly behind the owner. + // nobody stands directly behind another. Each ring fills from the front: slot 0 ahead of the owner, then left and + // right in turn towards his back, so the tanks (sorted first) lead and the healers (sorted last) close the ring + // behind him. Before, slot 0 was directly behind the owner and the tank trailed the whole group (row 348). uint32_t ring = 0, first = 0, in_ring = 0; float radius = 0.0f; for (;; ++ring) @@ -153,7 +155,10 @@ FormationOffset ComputeOwnerSlotOffset(FormationType type, uint32_t index, uint3 } uint32_t const pos = index - first; float const step = 2.0f * kPi / float(in_ring); - float const a = kPi + step * (float(pos) + (ring % 2 ? 0.5f : 0.0f)) + jit(21, 0.25f * step); + // Even rings: 0, +1, -1, +2, -2 ... steps; odd rings (half a step turned): -0.5, +0.5, -1.5, +1.5 ... (+ = the owner's left). + float const a = (ring % 2 == 0) + ? (pos % 2 == 1 ? 1.0f : -1.0f) * step * float((pos + 1) / 2) + jit(21, 0.25f * step) + : (pos % 2 == 1 ? 1.0f : -1.0f) * step * (float(pos / 2) + 0.5f) + jit(21, 0.25f * step); float const r = radius + jit(22, 0.2f * spacing); return FromLocal(r * std::cos(a), r * std::sin(a)); } diff --git a/src/modules/PlayerbotV2/Bot/PackPullGate.h b/src/modules/PlayerbotV2/Bot/PackPullGate.h index 707c4a3eb6..e9d5fba12c 100644 --- a/src/modules/PlayerbotV2/Bot/PackPullGate.h +++ b/src/modules/PlayerbotV2/Bot/PackPullGate.h @@ -31,14 +31,16 @@ public: return it->second.gated ? Verdict::Gated : Verdict::Walkable; } - void Note(std::uint64_t pack, bool gated, std::uint32_t now_ms) + // `gated_ms`: how long a gated verdict stands. A pack the tank could not pull at all (no opener spot, or an opener and a hand pull + // that never woke it: a door or a wall between) is passed by for longer than one it can only walk to the long way round. + void Note(std::uint64_t pack, bool gated, std::uint32_t now_ms, std::uint32_t gated_ms = kGatedMs) { for (auto it = entries_.begin(); it != entries_.end();) { if (std::int32_t(now_ms - it->second.until_ms) >= 0) it = entries_.erase(it); else ++it; } - entries_[pack] = Entry{ now_ms + (gated ? kGatedMs : kWalkableMs), gated }; + entries_[pack] = Entry{ now_ms + (gated ? gated_ms : kWalkableMs), gated }; } void Clear() { entries_.clear(); } diff --git a/src/modules/PlayerbotV2/Bot/PullDelay.h b/src/modules/PlayerbotV2/Bot/PullDelay.h new file mode 100644 index 0000000000..32938d25b4 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/PullDelay.h @@ -0,0 +1,83 @@ +// PullDelay - the damage dealers' short wait after their tank's pull (PlayerbotV2.Threat.PartyPullDelayMs). +// +// VempirE, Discord 2026-11-22: "dps bots wait a few seconds after the tank pulls". In a group led by a player, with a tank bot +// in it and outside the raid rules, a damage dealer starts its first attack of a fight only once the wait has run, whatever +// threat the tank has built (at low level one hit is the whole opening lead, and the DPS opened with it). +// +// The wait sits in BotIntentEmitter::start_attack, the one call every engage path goes through: the dev run of af76 had the +// rogue open 0.1 s after the tank by a path that never asked the combat state's threat hold. State_InCombat asks it as well, +// so a bot already swinging stops, and its group-fight pick does not start the attack it would stop on the next tick. +// +// One wait per fight and bot, not per mob: the clock starts at the bot's first held start and restarts when the bot has not +// been held for kPullDelayGapMs. Never held: a mob on this bot, on another member or on a member's pet (self-defence), a mob +// of someone outside the group, the leader's Attack or /focus on that mob, tanks and healers. + +#pragma once + +#include "BotAI.h" +#include "BotSnapshot.h" +#include "BotSnapshotView.h" +#include "../Services.h" +#include "Util/ConfigReader.h" +#include "Log.h" +#include +#include + +namespace Playerbot { + +constexpr uint32 kPullDelayGapMs = 8000; + +inline bool PartyPullDelayHolds(BotAI const& ai, BotSnapshotView const& s, ObjectGuid target) +{ + uint32 const delay = Services::Config().threat_party_pull_delay_ms(); + if (!delay || target.IsEmpty() || !target.IsCreatureOrVehicle()) return false; + if (!s.is_led_by_player() || s.raid_rules() || s.in_battleground()) return false; + ObjectGuid const tank = s.group_tank(); + if (tank.IsEmpty() || tank == s.guid()) return false; + Role const role = ai.effective_role(s); + if (role == Role::Tank || role == Role::Healer) return false; + if (NearbyUnit const* u = s.hostile_unit(target)) + { + if (u->hp <= 0) return false; + switch (ThreatVictim(u->victim_kind)) + { + case ThreatVictim::Me: + case ThreatVictim::Member: + case ThreatVictim::MemberPet: + case ThreatVictim::Other: + return false; + default: + break; + } + } + uint32 const now = s.published_at_ms(); + if (ai.focus_target() == target || + (ai.is_manual_mode(now) && ai.owner_command() == BotAI::OwnerCommand::Engage && ai.owner_target() == target)) + return false; + + struct Clock { uint32 first_ms; uint32 last_ms; }; + static std::mutex mu; + static std::unordered_map clocks; + uint64 const key = s.guid().GetCounter(); + std::lock_guard lock(mu); + if (clocks.size() > 2048) + for (auto it = clocks.begin(); it != clocks.end();) + it = (now - it->second.last_ms > 60'000u) ? clocks.erase(it) : std::next(it); + auto [it, inserted] = clocks.try_emplace(key, Clock{ now, now }); + if (!inserted) + { + if (now - it->second.last_ms > kPullDelayGapMs) + { + it->second.first_ms = now; + inserted = true; + } + it->second.last_ms = now; + } + bool const holds = now - it->second.first_ms < delay; + if (inserted) + TC_LOG_INFO("playerbot.v2", "[pull_delay] {} waits {} ms after the tank's pull before attacking {}", s.name(), delay, + target.ToString()); + return holds; +} + +} // namespace Playerbot diff --git a/src/modules/PlayerbotV2/Bot/Quest/CompanionQuest.cpp b/src/modules/PlayerbotV2/Bot/Quest/CompanionQuest.cpp index a7a424c9ea..d9de1b9aca 100644 --- a/src/modules/PlayerbotV2/Bot/Quest/CompanionQuest.cpp +++ b/src/modules/PlayerbotV2/Bot/Quest/CompanionQuest.cpp @@ -6,6 +6,7 @@ #include "Bot/QuestDoable.h" #include "Bot/QuestObjectiveLocations.h" #include "Services.h" +#include "Fleet/OwnerRegistry.h" #include "Util/ConfigReader.h" #include "Player.h" #include "GameObject.h" @@ -21,6 +22,7 @@ #include #include #include +#include namespace Playerbot { namespace CompanionQuest { @@ -34,7 +36,8 @@ constexpr float kBotReachYd = 40.0f; // Quest objects: near the owner, without a long detour for the bot. constexpr float kObjectOwnerYd = 25.0f; constexpr float kObjectBotYd = 30.0f; -// Owner within this of a quest object he needs too: he is about to click it himself, leave it to him. +// Owner within this of a quest object that goes away when used and that he still needs: he is about to click it himself, leave it +// to him. constexpr float kObjectOwnerAtYd = 6.0f; constexpr size_t kMaxPerList = 6; @@ -65,6 +68,24 @@ bool FindGiverPos(BotSnapshot const& snap, ObjectGuid guid, float& x, float& y) return false; } +// "[cq]" line, at most every 15 s per bot: what the companion quest help saw (or why it stopped) for a bot that has quests and a +// quest partner. Without it a companion that never accepts, hands in or clicks leaves no trace of which gate held it. +void Trace(Player const* bot, CompanionQuestState const& cq, char const* why) +{ + static std::mutex mtx; + static std::unordered_map last; + uint32 const now = GameTime::GetGameTimeMS(); + { + std::lock_guard lk(mtx); + if (last.size() > 4096) last.clear(); + uint32& at = last[bot->GetGUID().GetCounter()]; + if (at != 0 && now - at < 15000u) return; + at = now; + } + TC_LOG_INFO("playerbot.v2", "[cq] {} {}: accept {} turn_in {} share {} objects {}, bot in combat {}", bot->GetName(), why, + cq.accept.size(), cq.turn_in.size(), cq.share.size(), cq.objects.size(), bot->IsInCombat() ? 1 : 0); +} + bool ListHas(std::vector const& v, ObjectGuid giver, uint32 quest_id) { for (auto const& a : v) @@ -72,19 +93,41 @@ bool ListHas(std::vector const& v, ObjectGuid giver, uint3 return false; } +bool ObjectiveOpen(QuestObjectiveEntry const& o) +{ + if (o.amount <= 0 || o.progress >= o.amount) return false; + return !(o.flags & (QUEST_OBJECTIVE_FLAG_HIDDEN | QUEST_OBJECTIVE_FLAG_OPTIONAL)); +} + // Is the bot's open objective served by this game object? GAMEOBJECT objectives name the entry; ITEM // objectives are served by a chest / node / prop whose loot (or gameobject_questitem row) yields the item. bool ObjectServesObjective(QuestObjectiveEntry const& o, NearbyObject const& go) { - if (o.amount <= 0 || o.progress >= o.amount) return false; - if (o.flags & (/*HIDDEN*/ QUEST_OBJECTIVE_FLAG_HIDDEN | /*OPTIONAL*/ QUEST_OBJECTIVE_FLAG_OPTIONAL)) return false; - if (o.type == /*GAMEOBJECT*/ 2) + if (!ObjectiveOpen(o)) return false; + if (o.type == QUEST_OBJECTIVE_GAMEOBJECT) return uint32(o.object_id) == go.entry; - if (o.type == /*ITEM*/ 1) + if (o.type == QUEST_OBJECTIVE_ITEM) return o.object_id > 0 && QuestItemDropsFromGameObject(uint32(o.object_id), go.entry); return false; } +// The open objective of `q` this object serves, or nullptr. Beside the objectives above: an object that is there for this +// quest (its template names the quest: a goober, a prop, a chest only a holder of the quest can use) serves the quest's first +// open objective of any other kind. Those are the "use the X" objectives that a script or the object's spell credits as a +// kill or an event (a summoned alt stood beside such objects and never used them, row 240). +QuestObjectiveEntry const* ServedObjective(QuestEntry const& q, NearbyObject const& go, GameObjectTemplate const* tmpl) +{ + for (auto const& o : q.objectives) + if (ObjectServesObjective(o, go)) + return &o; + if (!tmpl || tmpl->GetQuestID() != q.quest_id) + return nullptr; + for (auto const& o : q.objectives) + if (ObjectiveOpen(o) && o.type != QUEST_OBJECTIVE_GAMEOBJECT && o.type != QUEST_OBJECTIVE_ITEM) + return &o; + return nullptr; +} + } // namespace void ArmLatch(uint64 bot_low, Latch which, uint32 now_ms, uint32 window_ms) @@ -121,6 +164,25 @@ std::string QuestLabel(uint32 quest_id) return "quest " + std::to_string(quest_id); } +bool QuestStartedByItemOnly(uint32 quest_id) +{ + static std::unordered_set item_only; + static std::once_flag built; + std::call_once(built, [] + { + std::unordered_set given; // quests a creature or game object hands out + for (auto const& [giver, q] : *sObjectMgr->GetCreatureQuestRelationMapHACK()) + given.insert(q); + for (auto const& [giver, q] : *sObjectMgr->GetGOQuestRelationMapHACK()) + given.insert(q); + for (auto const& [entry, tmpl] : sObjectMgr->GetItemTemplateStore()) + if (uint32 const q = tmpl.GetStartQuest()) + if (!given.contains(q)) + item_only.insert(q); + }); + return item_only.contains(quest_id); +} + bool BotCanTake(Player* bot, uint32 quest_id) { return bot && bot->SatisfyQuestLog(false) && BotCanStillTakeQuestForHub(bot, quest_id); @@ -133,8 +195,14 @@ void BuildState(Player* bot, BotAI* ai, BotSnapshot& snap) // The quest partner is the owner, or, for a world bot a player invited (no owner), the player who leads the group: he gets the same // accept / turn-in / share / quest-object help (a grouped world bot used to leave a finished quest unrewarded). ObjectGuid const partner = snap.owner_in_group ? snap.owner_guid : (snap.led_by_player ? snap.controller_guid : ObjectGuid::Empty); - if (!bot || partner.IsEmpty() || !bot->IsAlive()) + if (!bot || partner.IsEmpty()) return; + bool const trace = !snap.quest_log.quests.empty() && Services::Owners().OwnerCharacter(bot->GetGUID().GetCounter()) != 0; + if (!bot->IsAlive()) + { + if (trace) Trace(bot, cq, "dead"); + return; + } if (bot->InBattleground() || bot->InArena()) return; ConfigReader const& cfg = Services::Config(); @@ -147,7 +215,10 @@ void BuildState(Player* bot, BotAI* ai, BotSnapshot& snap) Player* owner = ObjectAccessor::FindConnectedPlayer(partner); if (!owner || !owner->IsInWorld() || owner->GetMapId() != bot->GetMapId() || owner == bot) + { + if (trace) Trace(bot, cq, owner == bot ? "partner is the bot itself" : "partner offline or on another map"); return; + } cq.owner_here = true; cq.owner_x = owner->GetPositionX(); cq.owner_y = owner->GetPositionY(); @@ -172,7 +243,9 @@ void BuildState(Player* bot, BotAI* ai, BotSnapshot& snap) if (ListHas(cq.accept, giver, qid)) continue; if (bot->GetQuestStatus(qid) != QUEST_STATUS_NONE) continue; QuestStatus const os = owner->GetQuestStatus(qid); - bool const owner_holds = os == QUEST_STATUS_INCOMPLETE; + // Complete counts: a quest with nothing to do but hand it in (a note found at a camp, quest 79008) is complete + // the moment the owner takes it, and the companion never followed him into it. + bool const owner_holds = os == QUEST_STATUS_INCOMPLETE || os == QUEST_STATUS_COMPLETE; if (!owner_holds && !accept_all) continue; // The player holds the quest: the companion takes it too, whatever other bots elsewhere gave up on. if (ai && ai->quest_blacklisted(qid, now_ms, /*fleet_memory*/ !owner_holds)) continue; @@ -194,6 +267,27 @@ void BuildState(Player* bot, BotAI* ai, BotSnapshot& snap) if (o.go_type != GAMEOBJECT_TYPE_QUESTGIVER) continue; consider(o.guid, o.x, o.y, sObjectMgr->GetGOQuestRelations(o.entry)); } + // A quest an item starts (a crest from a dungeon boss, a note): no giver to walk to, and the one item went to the owner. + // On his "accept" the companion takes it from him like a shared quest (row 240: Crest of Lordaeron 95189). + if (accept_all && Dist2d(bx, by, cq.owner_x, cq.owner_y) <= kBotReachYd) + { + for (uint16 slot = 0; slot < MAX_QUEST_LOG_SIZE && cq.accept.size() < kMaxPerList; ++slot) + { + uint32 const qid = owner->GetQuestSlotQuestId(slot); + if (qid == 0 || !QuestStartedByItemOnly(qid)) continue; + QuestStatus const os = owner->GetQuestStatus(qid); + if (os != QUEST_STATUS_INCOMPLETE && os != QUEST_STATUS_COMPLETE) continue; + if (bot->GetQuestStatus(qid) != QUEST_STATUS_NONE) continue; + if (ListHas(cq.accept, owner->GetGUID(), qid)) continue; + if (ai && ai->quest_blacklisted(qid, now_ms, /*fleet_memory*/ false)) continue; + if (!BotCanTake(bot, qid)) continue; + CompanionQuestAction a; + a.giver = owner->GetGUID(); + a.quest_id = qid; + a.via_order = true; + cq.accept.push_back(a); + } + } } // ---- turn in: the bot's quest is complete and the owner is at the ender ---------------------------------- @@ -288,21 +382,26 @@ void BuildState(Player* bot, BotAI* ai, BotSnapshot& snap) { if (cq.objects.size() >= kMaxPerList) break; if (go.go_type != GAMEOBJECT_TYPE_CHEST && go.go_type != GAMEOBJECT_TYPE_GOOBER && - go.go_type != GAMEOBJECT_TYPE_GATHERING_NODE && go.go_type != GAMEOBJECT_TYPE_GENERIC) + go.go_type != GAMEOBJECT_TYPE_GATHERING_NODE && go.go_type != GAMEOBJECT_TYPE_GENERIC && + go.go_type != GAMEOBJECT_TYPE_BUTTON) continue; if (Dist2d(bx, by, go.x, go.y) > kObjectBotYd) continue; float const od = Dist2d(cq.owner_x, cq.owner_y, go.x, go.y); if (od > kObjectOwnerYd) continue; + GameObjectTemplate const* tmpl = sObjectMgr->GetGameObjectTemplate(go.entry); for (auto const& q : snap.quest_log.quests) { if (q.state == 1) continue; - bool served = false; - for (auto const& o : q.objectives) - if (ObjectServesObjective(o, go)) { served = true; break; } + QuestObjectiveEntry const* served = ServedObjective(q, go, tmpl); if (!served) continue; - // The owner is standing at it on the same quest: he clicks it first (a quest prop can despawn - // for everyone); the bot takes it once he steps away, or at once when he does not need it. - if (od <= kObjectOwnerAtYd && owner->GetQuestStatus(q.quest_id) == QUEST_STATUS_INCOMPLETE) continue; + // The owner is standing at an object that goes away when used and still needs it for the same objective: he + // clicks it first; the bot takes it once he steps away or has his credit. An object every holder of the quest + // can use (most quest props and goobers) is used at once: an owner who clicked it and then waited beside it for + // his summoned alt held the alt back for good (row 240). + if (od <= kObjectOwnerAtYd && tmpl && tmpl->IsDespawnAtAction() && + owner->GetQuestStatus(q.quest_id) == QUEST_STATUS_INCOMPLETE && + !owner->IsQuestObjectiveComplete(q.quest_id, served->id)) + continue; CompanionQuestObject co; co.go = go.guid; co.entry = go.entry; @@ -312,6 +411,8 @@ void BuildState(Player* bot, BotAI* ai, BotSnapshot& snap) } } } + if (trace) + Trace(bot, cq, owner->IsInCombat() ? "built, partner in combat" : "built"); } } // namespace CompanionQuest diff --git a/src/modules/PlayerbotV2/Bot/Quest/CompanionQuest.h b/src/modules/PlayerbotV2/Bot/Quest/CompanionQuest.h index 94193656b7..b9c95ab8ea 100644 --- a/src/modules/PlayerbotV2/Bot/Quest/CompanionQuest.h +++ b/src/modules/PlayerbotV2/Bot/Quest/CompanionQuest.h @@ -85,6 +85,11 @@ bool BotCanTake(Player* bot, uint32 quest_id); // "[Title]" for logs and whispers: the quest's log title, or "quest " when unknown. Static data, any thread. std::string QuestLabel(uint32 quest_id); +// True for a quest that an item starts (the item's StartQuest names it: a dropped crest, a note) and that no creature or game +// object hands out. A group mate who holds one can pass it to his companion (API::accept_quest with a player giver). Static +// data; the first call builds the table from the item templates (world thread at the latest). +bool QuestStartedByItemOnly(uint32 quest_id); + } // namespace CompanionQuest } // namespace Playerbot diff --git a/src/modules/PlayerbotV2/Bot/Quest/QuestOrders.cpp b/src/modules/PlayerbotV2/Bot/Quest/QuestOrders.cpp index 40b4fb966b..45436e2cb3 100644 --- a/src/modules/PlayerbotV2/Bot/Quest/QuestOrders.cpp +++ b/src/modules/PlayerbotV2/Bot/Quest/QuestOrders.cpp @@ -246,8 +246,16 @@ std::vector AcceptAll(Player* sender, Player* bot, std::string_view ++taken; } + // A quest an item started that the sender holds ("accept "): no giver has it, I take it from him (the same rule). + bool const from_sender = want && sender && taken == 0 && CompanionQuest::QuestStartedByItemOnly(want) && + (sender->GetQuestStatus(want) == QUEST_STATUS_INCOMPLETE || sender->GetQuestStatus(want) == QUEST_STATUS_COMPLETE); + if (from_sender) + { + CompanionQuest::ArmLatch(t.id, CompanionQuest::Latch::AcceptAll, GameTime::GetGameTimeMS(), kOrderWindowMs); + out.push_back(fmt::format("I'll take {} from you.", CompanionQuest::QuestLabel(want))); + } // Walk to the NPCs close to me and take what they offer (the idle:companion_quest_accept rule), for 45 s. - if (want == 0 && needle.empty()) + else if (want == 0 && needle.empty()) { CompanionQuest::ArmLatch(t.id, CompanionQuest::Latch::AcceptAll, GameTime::GetGameTimeMS(), kOrderWindowMs); if (taken == 0) diff --git a/src/modules/PlayerbotV2/Bot/QuestLoot.h b/src/modules/PlayerbotV2/Bot/QuestLoot.h index bf0bb397ed..4a8acdfc0f 100644 --- a/src/modules/PlayerbotV2/Bot/QuestLoot.h +++ b/src/modules/PlayerbotV2/Bot/QuestLoot.h @@ -1,18 +1,55 @@ // A quest drop this bot is allowed to take. A bot a player leads loots nothing else: the player takes the rest, but each member with the -// quest has to loot its own quest items (they appear on the corpse for that member alone). +// quest has to loot its own quest items. #pragma once +#include "Diagnostics/ScenarioHuman.h" +#include "Group.h" #include "Loot.h" #include "Player.h" namespace Playerbot { +// A quest drop there is one of for the whole group (not ITEM_FLAG_MULTI_DROP: the first member to loot it takes it from the others) that +// a player of the group may loot from this corpse and still needs. It is his: the bot leaves it, as a member who also has the quest leaves +// a group's single quest drop to the player (Discord 2026-11-22, Guard: "my bots grab quest items before me, I don't even get to loot"). +// A drop each member gets for himself (multi-drop), a player who has enough, or one who is not on this corpse's looter list (personal +// loot, out of range at the kill) does not hold it. +[[nodiscard]] inline bool QuestLootIsAPlayers(Player const* bot, Loot const* loot, LootItem const& it) +{ + if (it.freeforall || !loot) + return false; + Group const* g = bot->GetGroup(); + if (!g) + return false; + for (GroupReference const& ref : g->GetMembers()) + { + Player const* m = ref.GetSource(); + if (!m || m == bot || !Scenario::PlaysAsHuman(m) || !m->IsInWorld()) + continue; + if (it.HasAllowedLooter(m->GetGUID()) && m->HasQuestForItem(it.itemid)) + return true; + } + return false; +} + +// The first quest drop on this loot that would be the bot's but is left for a player (QuestLootIsAPlayers), 0 when none. +[[nodiscard]] inline uint32 QuestLootLeftForPlayer(Player const* p, Loot const* loot) +{ + if (!loot) + return 0; + for (LootItem const& it : loot->items) + if (it.needs_quest && !it.is_looted && !it.is_blocked && it.HasAllowedLooter(p->GetGUID()) && QuestLootIsAPlayers(p, loot, it)) + return it.itemid; + return 0; +} + [[nodiscard]] inline bool IsPendingQuestLoot(Player* p, Loot* loot, uint8 slot) { NotNormalLootItem* ffa = nullptr; LootItem* it = loot->LootItemInSlot(slot, p, &ffa); - return it && it->needs_quest && !it->is_looted && !it->is_blocked && !(ffa && ffa->is_looted) && it->HasAllowedLooter(p->GetGUID()); + return it && it->needs_quest && !it->is_looted && !it->is_blocked && !(ffa && ffa->is_looted) && it->HasAllowedLooter(p->GetGUID()) && + !QuestLootIsAPlayers(p, loot, *it); } } // namespace Playerbot diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidAdvice.cpp b/src/modules/PlayerbotV2/Bot/Raid/RaidAdvice.cpp index ee72356660..2ea9afc859 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidAdvice.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidAdvice.cpp @@ -14,6 +14,8 @@ void ApplyRaidAdvice(uint32_t mapId, DungeonAdvice& advice) advice.bosses = rules->bosses; advice.dangerous_auras.clear(); advice.spread_on_self_auras.clear(); + advice.keep_clear_of_carriers.clear(); // the raid rules keep clear of carriers themselves (avoidCarrier) + advice.spread_from_bosses.clear(); // and spread by their own raid positions advice.kite_creature_entries.clear(); advice.soak_spells.clear(); advice.stack_on_cast_spells.clear(); diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidBrain.cpp b/src/modules/PlayerbotV2/Bot/Raid/RaidBrain.cpp index e0cd518b28..b7f020ae29 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidBrain.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidBrain.cpp @@ -31,6 +31,7 @@ #include "../ThreatLimits.h" #include "../Dungeon/PveGroupCoordinator.h" #include "../../Group/GroupSnapshot.h" +#include "../../Fleet/BotAccountMgr.h" // is_pool_account: a player's own character keeps its raid role #include "../../Fleet/BotIdentityRegistry.h" #include "../../Services.h" #include "../../Threading/SnapshotPublisher.h" @@ -993,6 +994,15 @@ std::unordered_map g_lastSpread; std::unordered_map g_lastSpreadLog; std::unordered_map g_lastTankFace; std::unordered_map g_lastFaceAway; +constexpr float kFaceAwayReach = 10.0f; // the face-away step turns an enemy within this many yards of its tank +// Lead away (RaidRules::leadAway): when the victim last chose a spot, and that spot. +struct LeadSpot { float x, y, z; uint32_t at; }; +std::unordered_map g_leadSpot; +std::unordered_map g_lastLeadLog; +constexpr uint32_t kLeadEveryMs = 2000; // a victim picks a new spot at most this often +constexpr float kLeadApexBack = 2.5f; // the enemy stops about this far short of its victim: the cone's apex +constexpr float kLeadPathClear = 6.0f; // a raider this close to the enemy's walk may be taken on the way (its melee reach and a margin) +constexpr float kLeadConeMarginDeg = 10.0f; std::unordered_map g_lastRearStep; std::unordered_map g_lastCarrierLog; std::unordered_map g_lastBombLog; @@ -1001,6 +1011,8 @@ std::unordered_map g_lastDragOutLog; std::unordered_map g_lastIdleHoldLog; std::unordered_map g_lastOutOfReachLog; // [raid_target] a melee bot leaving an enemy it cannot get to, per bot constexpr float kMeleeChaseMargin = 5.0f; // a chasing melee bot stops this far from its target +constexpr float kRangedNearReach = 30.0f; // rangedNearFirst: a ranged pick past this is ranked after every nearer one +constexpr float kRangedFarDrop = 38.0f; // rangedNearFirst: a ranged bot on a target past this leaves it for a near pick std::unordered_map g_lastSafeCrossLog; // The idle pack whose aggro reach a melee bot at (bx, by) walks into on its way to an enemy at (vx, vy), or -1. The chase stops @@ -1507,6 +1519,7 @@ constexpr float kGuardRiseScan = 100.0f; // GuardRise: the bones within std::unordered_map g_guardRiseLog; // bot -> last [raid_guard_rise] line (ms) std::unordered_map g_postHazardLog; // bot -> last [raid_post] "the post is in a hazard" line (ms) constexpr float kFixedSpotFreshScan = 100.0f; // ... and the adds just spawned within this reach, in nobody's combat yet, are off limits too +constexpr float kFaceAwaySlotSlack = 12.0f; // ... and one holding a FaceAway add from its far side stays this close to its slot (HoldsFacedAway) // An add of a fixed row that has reached the raid: it stands in melee with a raider, wherever that raider is (another tank's pile, a melee DPS // beside it, a healer). bwl_nefarian 1109y: a drakonid held at a neighbour's pile (on the arc's far side, 23-26 y from the centre) or on a @@ -1522,6 +1535,13 @@ bool EnemyInFight(Plan const& plan, uint32_t entry) }); } +// The enemy has a FaceAway rule whose tank may stand well off the line (FaceAway::maxTurnDeg past 30). +bool TurnedFromTheSide(Plan const& plan, uint32_t entry) +{ + return plan.rules && std::any_of(plan.rules->faceAway.begin(), plan.rules->faceAway.end(), + [&](FaceAway const& fa) { return fa.enemy == entry && fa.maxTurnDeg > 30.0f; }); +} + bool ReachedRaid(Plan const& plan, Unit* add) { Unit* const v = add->GetVictim(); @@ -1546,6 +1566,42 @@ bool ReachedRaid(Plan const& plan, Unit* add) // same way at 124 s and 145 s, and the raid never reached phase three. FetchesAdd kept every add on another tank off limits, so nobody // relieved it. constexpr size_t kHandOffFrom = 3, kHandOffKeep = 2; + +// TankSpot::skipClassMask: a tank of a skipped class is left out of the row while a live tank of another class has a hand free (holds none of +// the row's adds). Once every other tank holds one, a further add is better on the bear than on a healer. naxx_kelthuzad kt70g (1125): at +// 291-313 s six Abominations were up, the three warriors held one each, two or three walked through the camp (#1589 on the healers for 20 s) +// while the bear stood at its slot with nothing, and the raid went from 33 alive to 28 before Kel'Thuzad came down. +bool OnEndEnemy(Plan const& plan, TankSpot const& rule, Player const* p); + +// Stand::endEnemy and endAfterEnemy: whether the post has ended. With endAfterEnemy the next phase's enemy ends it only once the post's own +// enemy is gone from the fight. naxx_kelthuzad kt74b (1125): Kel'Thuzad came down at 316 s with four Soul Weavers at 100% still walking in; +// the camp posts ended, the ranged and healers spread round him east of the camp, and one Weaver (3745,-5089) killed 16 with one Wail of +// Souls at 322 s, 15 of them 22-38 y from the camp. kt74a: Wail of Souls 18 of the dead, all in phase 2. +bool StandEnded(Plan const& plan, Stand const& rule) +{ + if (!EnemyInFight(plan, rule.endEnemy)) + return false; + if (!rule.endAfterEnemy) + return true; + return std::none_of(plan.enemies.begin(), plan.enemies.end(), [&](Unit* e) { return e->IsAlive() && e->GetEntry() == rule.enemy; }); +} + +bool RowSkips(Plan const& plan, TankSpot const& rule, Player const* p) +{ + auto const skipped = [&](Player const* q) { return (rule.skipClassMask & (1u << (q->GetClass() - 1))) != 0; }; + if (!skipped(p)) + return false; + for (Member const& m : plan.members) + { + if (!m.tank || !m.p->IsAlive() || skipped(m.p) || OnEndEnemy(plan, rule, m.p)) + continue; + if (std::none_of(plan.enemies.begin(), plan.enemies.end(), [&](Unit* e) + { return e->IsAlive() && InTankSpot(rule, e->GetEntry()) && e->GetVictim() == m.p; })) + return true; + } + return false; +} + bool HandedOffTo(Plan const& plan, TankSpot const& rule, Player* bot, Unit* add) { std::vector idle; @@ -1560,15 +1616,20 @@ bool HandedOffTo(Plan const& plan, TankSpot const& rule, Player* bot, Unit* add) held.push_back(enemy); if (held.empty()) { - if (m.bot) + if (m.bot && !RowSkips(plan, rule, m.p) && !OnEndEnemy(plan, rule, m.p)) // skipClassMask (while another tank is free), endAfterAdds idle.push_back(m.p); continue; } - if (held.size() < kHandOffFrom) + // TankSpot::handOffFrom: from that many, keeping one. naxx_kelthuzad kt70a (1124): Mctankwa held two Abominations (99%, 100%) and + // a Soul Weaver at 100 s, two Abominations to 106 s, while Mctankwb stood at its slot with nothing at 97-100 s; Mortal Wound killed + // Mctankwa at 109 s. + size_t const from = rule.handOffFrom ? size_t(rule.handOffFrom) : kHandOffFrom; + size_t const keep = rule.handOffFrom ? size_t(1) : kHandOffKeep; + if (held.size() < from) continue; std::sort(held.begin(), held.end(), [](Unit* a, Unit* b) { return a->GetHealth() != b->GetHealth() ? a->GetHealth() < b->GetHealth() : a->GetGUID() < b->GetGUID(); }); - pool.insert(pool.end(), held.begin() + kHandOffKeep, held.end()); + pool.insert(pool.end(), held.begin() + keep, held.end()); } std::sort(pool.begin(), pool.end(), [](Unit* a, Unit* b) { return a->GetHealth() != b->GetHealth() ? a->GetHealth() > b->GetHealth() : a->GetGUID() < b->GetGUID(); }); @@ -1587,10 +1648,29 @@ bool FetchesAdd(Plan const& plan, TankSpot const& rule, Player* bot, Unit* add) // from 24 s to 57 s at (-7555,-1199), north of every place, and all four tanks died there at 188-208 s. if (Unit* const v = add->GetVictim(); v && v != bot && v->IsAlive()) if (Player* const vp = v->ToPlayer()) - if (std::any_of(plan.members.begin(), plan.members.end(), [&](Member const& m) { return m.p == vp && m.tank; })) + // (A tank the row skips, TankSpot::skipClassMask and RowSkips, counts as a raider: an add sent at the bear is fetched off it.) + if (std::any_of(plan.members.begin(), plan.members.end(), [&](Member const& m) + { return m.p == vp && m.tank && !RowSkips(plan, rule, m.p); })) return HandedOffTo(plan, rule, bot, add); // ... unless that tank holds too many and this one none if (ReachedRaid(plan, add)) return true; + // TankSpot::fetchMax: a loose add that has not reached anybody yet is not fetched out at the edge of the room. naxx_kelthuzad kt69c + // (1124): a tank went 15 y out from its slot to a Soul Weaver at the alcove keep-out rim (3700,-5079, 31 y from the camp), found no + // spot on its far side (inside the keep-out), and the Weaver faced the camp from there: its Wail of Souls killed 28. One in melee with + // a raider is fetched wherever it is (above): kt69e, with this check first, an Abomination sent at a warrior 25 y from the camp was + // left on him and killed him 8 s later (Mortal Wound, 9,642). + // A FaceAway add turned from the side (maxTurnDeg past 30) is met where it is: it walks in slowly, facing the raider it was sent at + // across the camp (kt69f: a Weaver was on its tank 50 s, 36 y from the raid's centre, with no spot found; one at 3694,-5083 killed 8). + // TankSpot::fetchTurned: such an add is met once it is that close to (x, y), wherever the tank stands, and not before. The reach test + // below (within 15 y of the tank as well) left the tanks at their slots while it walked on to its victim at the camp: naxx_kelthuzad + // kt69o (1124): at 87 s three Weavers were in the fight, one on a tank and two on casters, at 90 s none on a tank, and at 93 s one + // 29 y south of the camp (3709,-5134) killed twelve. Further out it is still in an alcove's mouth, among the resting adds (kt69o: no spot behind a Weaver + // at 3704,-5169, "idle pack 27"). + if (rule.fetchTurned > 0.0f && TurnedFromTheSide(plan, add->GetEntry())) + return Dist2D(add->GetPositionX(), add->GetPositionY(), rule.x, rule.y) <= rule.fetchTurned; + if (rule.fetchMax > 0.0f && Dist2D(add->GetPositionX(), add->GetPositionY(), rule.x, rule.y) > rule.fetchMax && + !TurnedFromTheSide(plan, add->GetEntry())) + return false; if (rule.reach <= 0.0f) return bot->IsWithinDistInMap(add, kFixedSpotFetchReach); float const fromCentre = Dist2D(add->GetPositionX(), add->GetPositionY(), rule.x, rule.y); @@ -1751,11 +1831,44 @@ float SeenArcAngle(Plan const& plan, TankSpot const& rule, Player* bot, uint32_t } // waitFor (fixed rows): set to the loose add this tank waits for at its slot instead of walking out to it. +// A fixed row holds while its anchor is in the fight, or any of the adds it is for: Kel'Thuzad's phase 1 has no enemy that is always in the +// raid's combat (he is immune; each sent Soldier lives a few seconds), and the row came and went with the Soldiers. +bool FixedRowUp(Plan const& plan, TankSpot const& rule) +{ + return std::any_of(plan.enemies.begin(), plan.enemies.end(), [&](Unit* e) + { + return e->IsAlive() && (e->GetEntry() == rule.anchor || InTankSpot(rule, e->GetEntry())); + }); +} + +// TankSpot::endEnemy and endAfterAdds: whether the row has ended. With endAfterAdds the next phase's enemy ends it only once the last of the +// row's adds is dead. naxx_kelthuzad kt72a (1125): Kel'Thuzad came down at 315 s with 16 phase 1 adds up (an Abomination on a tank, Soul +// Weavers, Soldiers); the row and its forbids ended at once, the tanks took Soldiers and Weavers (Mctankwa on a Soldier with an Abomination +// assigned, a Weaver on it), and in the next 60 s Dark Blast killed 5 at once and Wail of Souls 3. +bool RowEnded(Plan const& plan, TankSpot const& rule) +{ + if (!EnemyInFight(plan, rule.endEnemy)) + return false; + if (!rule.endAfterAdds) + return true; + return std::none_of(plan.enemies.begin(), plan.enemies.end(), [&](Unit* e) { return e->IsAlive() && InTankSpot(rule, e->GetEntry()); }); +} + +// TankSpot::endAfterAdds: this tank holds the next phase's enemy (Kel'Thuzad) while the row still holds the last adds: it has no slot, +// takes none of the row's adds, and counts as busy for the bear (RowSkips) and the hand-off (HandedOffTo). +bool OnEndEnemy(Plan const& plan, TankSpot const& rule, Player const* p) +{ + if (!rule.endAfterAdds || !rule.endEnemy || !EnemyInFight(plan, rule.endEnemy)) + return false; + Unit* const v = p->GetVictim(); + return v && v->IsAlive() && v->GetEntry() == rule.endEnemy; +} + bool TankSpotFor(Plan const& plan, TankSpot const& rule, Player* bot, uint32_t now, float& outX, float& outY, Unit** waitFor = nullptr) { uint64_t const key = (plan.groupLow << 32) ^ rule.anchor; TankSpotLock& lock = g_tankSpot[key]; - if (EnemyInFight(plan, rule.endEnemy)) + if (RowEnded(plan, rule) || OnEndEnemy(plan, rule, bot)) return false; if (rule.fixed) { @@ -1772,11 +1885,7 @@ bool TankSpotFor(Plan const& plan, TankSpot const& rule, Player* bot, uint32_t n if (waitFor) *waitFor = v; } - bool anchorUp = false; - for (Unit* enemy : plan.enemies) - if (enemy->GetEntry() == rule.anchor && enemy->IsAlive()) - anchorUp = true; - if (!anchorUp) + if (!FixedRowUp(plan, rule)) return false; float const along = rule.rowDeg * (float(M_PI) / 180.0f); lock = { rule.x - rule.reach * std::cos(along + float(M_PI) * 0.5f), rule.y - rule.reach * std::sin(along + float(M_PI) * 0.5f), @@ -1824,7 +1933,7 @@ bool TankSpotFor(Plan const& plan, TankSpot const& rule, Player* bot, uint32_t n { holders.clear(); for (Member const& m : plan.members) - if (m.tank && m.p && m.p->IsAlive()) + if (m.tank && m.p && m.p->IsAlive() && !OnEndEnemy(plan, rule, m.p)) holders.push_back(m.p->GetGUID().GetCounter()); std::sort(holders.begin(), holders.end()); } @@ -1854,8 +1963,13 @@ bool FaceAxisFor(Plan const& plan, Unit* enemy, uint32_t now, float& axis, float axis = fixedBearingDeg * (float(M_PI) / 180.0f); return true; } - uint64_t const key = (plan.groupLow << 32) ^ enemy->GetEntry(); + // One lock per creature, not per entry: Kel'Thuzad's Soul Weavers (several at once, each on its own tank round the camp) shared one + // lock and threw it away for one another every pass. + uint64_t const key = (plan.groupLow << 32) ^ enemy->GetGUID().GetCounter(); float const ex = enemy->GetPositionX(), ey = enemy->GetPositionY(); + if (g_faceAxis.size() > 256) + for (auto it = g_faceAxis.begin(); it != g_faceAxis.end();) + it = (now - it->second.seenMs > 2 * kAxisStaleMs) ? g_faceAxis.erase(it) : std::next(it); FaceAxisLock& lock = g_faceAxis[key]; if (lock.seenMs && now - lock.seenMs < kAxisStaleMs && geo::AxisHolds(lock.bossX, lock.bossY, ex, ey, kAxisDrift)) { @@ -1881,6 +1995,28 @@ bool FaceAxisFor(Plan const& plan, Unit* enemy, uint32_t now, float& axis, float return true; } +// The tank holds an add of the fixed row that has a FaceAway rule, and stands on its far side from the raid (the face-away step's own +// 30 degree test), so that add's back is to the raid. +bool HoldsFacedAway(Plan const& plan, RaidRules const& rules, TankSpot const& row, Player* bot, uint32_t now) +{ + for (FaceAway const& fa : rules.faceAway) + { + if (!InTankSpot(row, fa.enemy)) + continue; + for (Unit* enemy : plan.enemies) + { + if (enemy->GetEntry() != fa.enemy || !enemy->IsAlive() || enemy->GetVictim() != bot || !InPhase(enemy, fa.hpMax, fa.hpMin)) + continue; + float axis; + if (FaceAxisFor(plan, enemy, now, axis, fa.bearingDeg) && + geo::TankOnAxis(enemy->GetPositionX(), enemy->GetPositionY(), bot->GetPositionX(), bot->GetPositionY(), axis, + fa.maxTurnDeg * (float(M_PI) / 180.0f))) + return true; + } + } + return false; +} + // Whether (x,y) lies inside a frontal cone of as it faces now, widened by the rule's margin, for a bot like . The same sector test // the cone step (2b) uses, so a stand point this rejects is one that step would walk the bot out of again. bool InAnyLiveCone(RaidRules const& rules, Plan const& plan, Member const& self, Unit const* enemy, float x, float y) @@ -2525,7 +2661,7 @@ int TanksSeenFrom(Player* bot, std::vector const& tanks, float x, float } SightSpot HealerSightSpot(Plan const& plan, Stand const& rule, std::vector const& circles, uint32_t now, Player* bot, - float& outX, float& outY, float& outZ) + float& outX, float& outY, float& outZ, float roam = kSightRoam) { std::vector tanks; for (Member const& m : plan.members) @@ -2535,7 +2671,7 @@ SightSpot HealerSightSpot(Plan const& plan, Stand const& rule, std::vectorGetPositionX(), by = bot->GetPositionY(); - bool const inRoam = Dist2D(bx, by, rule.x, rule.y) <= kSightRoam; + bool const inRoam = Dist2D(bx, by, rule.x, rule.y) <= roam; // kSightRoam, or a wider post's (Stand::fightTolerance) int const here = inRoam && !InsideAny(circles, bx, by, 0.0f) ? TanksSeenFrom(bot, tanks, bx, by, bot->GetPositionZ()) : -1; if (here == int(tanks.size())) return SightSpot::Here; @@ -2964,24 +3100,44 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< bool const stayHidden = HidingFromBreath(plan, self, enemy, now); // Leave through the nearer edge, a few degrees past it, keeping roughly the same distance from the boss (never closer than 6 yards). float const side = toBot >= 0.0f ? 1.0f : -1.0f; - float const ring = std::max(distance, 6.0f); + // An enemy that turns a lot sweeps whoever stands just past its edge: one no tank holds (it faces each new victim) or one its tank + // turns from the side (FaceAway::maxTurnDeg past 30, a step round it every few seconds). The way out from it keeps 12 y and never + // steps nearer. naxx_kelthuzad kt69h (1124): four healers left the cone of a Soul Weaver their tank could not turn (its far side + // in the keep-out of the alcove at 3768,-5072) onto its flank, 8 y from it (3739-3743,-5084); one Wail of Souls killed some and threw the + // rest 26 y (its knockback) to the north alcove. + Unit* const coneVictim = enemy->GetVictim(); + bool const loose = TurnedFromTheSide(plan, enemy->GetEntry()) || !coneVictim || + std::none_of(plan.members.begin(), plan.members.end(), [&](Member const& m) { return m.tank && m.p == coneVictim; }); + float const ring = std::max(distance, loose ? 12.0f : 6.0f); + // The way out stays out of the keep-out circles while another way out is found (pass 0), as the hazard escape's does: the + // keep-out escape (2a) walks a bot that ends inside one straight back out, into the cone again. naxx_kelthuzad kt66a (1124): + // the mages and healers by the alcoves alternated "leave cone" and "leave hazard" every second under a Soul Weaver (488 and + // 474 such steps, kt66b 683 and 621) and cast little. Pass 0 also tries a ring nearer the enemy, off the room's rim. int pathChecks = 0; + for (int pass = 0; pass < 2; ++pass) + for (float r : { ring, std::max(ring * 0.6f, 6.0f) }) for (float extra : { 0.12f, 0.30f, 0.55f }) for (float flip : { 1.0f, -1.0f }) { + if (pass == 1 && r != ring) + continue; // the second pass is the old search, keep-out circles allowed + if (loose && r < ring) + continue; float const angle = facing + side * flip * (half + extra); - float const px = enemy->GetPositionX() + ring * std::cos(angle); - float const py = enemy->GetPositionY() + ring * std::sin(angle); + float const px = enemy->GetPositionX() + r * std::cos(angle); + float const py = enemy->GetPositionY() + r * std::sin(angle); if (!circles.empty() && InsideAny(circles, px, py, 1.0f)) continue; + if (pass == 0 && InsideAny(g_keepOut, px, py, 1.0f)) + continue; // The way out goes round him, never across his face: the walk to the far edge runs past his front (naxx_sapphiron r27: // three bots 25 y off his flank took the far edge when the near one was no use, passed 3-6 y from him and his Cleave // killed all three; four more died that way). A straight line that comes nearer to him than most of the ring is not // taken. if (SegmentDist2D(bot->GetPositionX(), bot->GetPositionY(), px, py, enemy->GetPositionX(), enemy->GetPositionY()) < - 0.8f * std::min(distance, ring)) + 0.8f * std::min(distance, r)) continue; - if (++pathChecks > 6) + if (++pathChecks > 10) break; float pz = 0.0f; if (!Usable(bot, px, py, bot->GetPositionZ(), pz, /*urgent*/ true, /*hazard*/ true)) @@ -3056,6 +3212,164 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< } } + // 2c. Lead away (RaidRules::leadAway): the raider an untanked enemy is on stands where its frontal cast hits nobody else. The enemy + // walks up to its victim and faces it, so the victim decides where the cone points: out of the raid, with the raid behind the enemy. + // naxx_kelthuzad kt70e (1125, script19ac): a Soul Weaver walked up to the healer Mchealse in the camp, 19 y from its centre, and at 3% + // health its Wail of Souls killed 13 standing behind the healer; with the Soldiers' Dark Blast the raid went from 31 alive to 5. + // A tank leads one too while it holds none of a fixed row's adds: the enemy takes whoever is in its melee reach on its way in (a Soul + // Weaver whose victim is out of it), and a tank standing at its slot has the camp behind it. naxx_kelthuzad kt77a (1125): a Weaver on + // the bear (which takes no Abomination while a warrior is free) in 14 samples, another in 4, one on Mctankwc in 2; kt77b one on + // Mctankwa in about 11. + bool const holdsRowAdd = self.tank && std::any_of(plan.enemies.begin(), plan.enemies.end(), [&](Unit* e) + { + return e->IsAlive() && e->GetVictim() == bot && + std::any_of(rules.tankSpot.begin(), rules.tankSpot.end(), [&](TankSpot const& row) { return row.fixed && InTankSpot(row, e->GetEntry()); }); + }); + if (!holdsRowAdd) + for (LeadAway const& rule : rules.leadAway) + for (Unit* enemy : plan.enemies) + { + if (enemy->GetEntry() != rule.enemy || !enemy->IsAlive() || enemy->GetVictim() != bot || + !bot->IsWithinDistInMap(enemy, rule.maxDist)) + continue; + float const ex = enemy->GetPositionX(), ey = enemy->GetPositionY(); + float const bx = bot->GetPositionX(), by = bot->GetPositionY(); + std::vector> spots; + for (Player* p : others) + if (p->IsAlive()) + { + float px, py; + PlannedAt(p, px, py); + spots.emplace_back(px, py); + } + float const cosHalf = std::cos((rule.halfDeg + kLeadConeMarginDeg) * (float(M_PI) / 180.0f)); + // The raiders the enemy hits (in) and passes within reach of (near) when its victim stands at (sx, sy): it walks there from + // where it is, facing the victim, and casts from anywhere on that walk once the victim is within the cone's range, from + // range - 2 yards out (or where it stands, if nearer) down to kLeadApexBack short of it. Both ends of that walk count. + // naxx_kelthuzad kt76a (1125): a Weaver 23 y north-east of the camp (3736,-5094) cast at its victim in the camp and threw + // the camp 26 y west, 20 dead; the step had counted the cone from 2.5 y short of the victim only, as for an enemy that casts + // in melee ("Mchealpd leads Soul Weaver (29 y off) 14 y" a second before). + auto exposed = [&](float sx, float sy, int& in, int& near) + { + in = near = 0; + float const d = Dist2D(ex, ey, sx, sy); + float const ux = d > 0.1f ? (sx - ex) / d : std::cos(enemy->GetOrientation()); + float const uy = d > 0.1f ? (sy - ey) / d : std::sin(enemy->GetOrientation()); + float const nearBack = std::min(kLeadApexBack, d); + float const farBack = std::min(d, std::max(kLeadApexBack, rule.range - 2.0f)); + float const ax = sx - ux * nearBack, ay = sy - uy * nearBack; + float const fx = sx - ux * farBack, fy = sy - uy * farBack; + auto const inCone = [&](float apexX, float apexY, float px, float py) + { + float const dx = px - apexX, dy = py - apexY; + float const pd = std::sqrt(dx * dx + dy * dy); + return pd <= rule.range + 2.0f && (pd < 1.0f || (dx * ux + dy * uy) / pd >= cosHalf); + }; + for (auto const& s : spots) + { + if (inCone(ax, ay, s.first, s.second) || inCone(fx, fy, s.first, s.second)) + ++in; + else if (SegmentDist2D(ex, ey, ax, ay, s.first, s.second) < kLeadPathClear) + ++near; + } + }; + int hereIn = 0, hereNear = 0; + exposed(bx, by, hereIn, hereNear); + uint64_t const key = bot->GetGUID().GetCounter(); + if (hereIn == 0 && hereNear == 0) + { + out.at_post = true; // the formation walk and the role post leave the victim where it is + return; + } + auto const last = g_leadSpot.find(key); + if (last != g_leadSpot.end() && now - last->second.at < kLeadEveryMs) + { + if (Dist2D(bx, by, last->second.x, last->second.y) > 1.5f) + { + SetMove(out, last->second.x, last->second.y, last->second.z, "lead away", hereIn > 0 && Dist2D(bx, by, ex, ey) < 12.0f); + Remember(bot, out, now); + } + else + out.at_post = true; + return; + } + // Out of the raid first: from the centre of the others through the victim. + float cx = 0.0f, cy = 0.0f; + for (auto const& s : spots) { cx += s.first; cy += s.second; } + float const outward = spots.empty() ? geo::Bearing(ex, ey, bx, by) + : geo::Bearing(cx / float(spots.size()), cy / float(spots.size()), bx, by); + struct Cand { float x, y; int in, near; float reach, offDeg; }; + std::vector cands; + for (float reach : { 6.0f, 10.0f, 14.0f, 20.0f }) + for (int k = -5; k <= 6; ++k) + { + float const off = float(k) * 30.0f; + float const b = outward + off * (float(M_PI) / 180.0f); + float const sx = bx + reach * std::cos(b), sy = by + reach * std::sin(b); + int in = 0, near = 0; + exposed(sx, sy, in, near); + if (in * 2 + near < hereIn * 2 + hereNear) + cands.push_back({ sx, sy, in, near, reach, std::fabs(off) }); + } + std::sort(cands.begin(), cands.end(), [](Cand const& a, Cand const& b) + { + int const sa = a.in * 2 + a.near, sb = b.in * 2 + b.near; + if (sa != sb) return sa < sb; + if (a.reach != b.reach) return a.reach < b.reach; + return a.offDeg < b.offDeg; + }); + std::map refused; + int probes = 0; + for (Cand const& c : cands) + { + if (probes >= 8) + break; + if (!circles.empty() && InsideAny(circles, c.x, c.y, 0.5f)) + { + ++refused["hazard circle"]; + continue; + } + if (rule.knockback > 0.0f) + { + float const d = Dist2D(ex, ey, c.x, c.y); + float const lx = d > 0.1f ? c.x + (c.x - ex) / d * rule.knockback : c.x; + float const ly = d > 0.1f ? c.y + (c.y - ey) / d * rule.knockback : c.y; + if (InsideAny(g_keepOut, lx, ly, 0.0f) || InsideAny(g_idleHostiles, lx, ly, 0.0f)) + { + ++refused["knockback lands in a keep-out"]; + continue; + } + } + ++probes; + float pz = 0.0f; + if (!Usable(bot, c.x, c.y, bot->GetPositionZ(), pz, /*urgent*/ true)) + { + ++refused[UsableWhyName(g_usableWhy)]; + continue; + } + g_leadSpot[key] = { c.x, c.y, pz, now ? now : 1u }; + bool const urgent = hereIn > 0 && Dist2D(bx, by, ex, ey) < 12.0f; + SetMove(out, c.x, c.y, pz, "lead away", urgent); + Remember(bot, out, now); + TC_LOG_INFO("playerbot.v2.raid", "[raid_lead] {} leads {} ({:.0f} y off) {:.0f} y, {:.0f} deg off the raid's outward line: {} in its " + "cone and {} by its way here, {} and {} there", bot->GetName(), enemy->GetName(), Dist2D(bx, by, ex, ey), c.reach, + c.offDeg, hereIn, hereNear, c.in, c.near); + return; + } + g_leadSpot[key] = { bx, by, bot->GetPositionZ(), now ? now : 1u }; + uint32_t& logged = g_lastLeadLog[key]; + if (now - logged >= 10000) + { + logged = now; + std::string why; + for (auto const& r : refused) + why += (why.empty() ? "" : ", ") + r.first + " " + std::to_string(r.second); + TC_LOG_INFO("playerbot.v2.raid", "[raid_lead] {} has {} ({:.0f} y off) with {} in its cone and {} by its way here: no better spot " + "({} better, {})", bot->GetName(), enemy->GetName(), Dist2D(bx, by, ex, ey), hereIn, hereNear, cands.size(), + why.empty() ? "none refused" : why); + } + } + // 3. Spread: keep distance from the nearest raid member while the boss is up and open to attack. A boss the raid cannot touch yet casts // nothing the spread is for: Kel'Thuzad sits immune on his throne through phase 1 while the adds come, and naxx_kelthuzad r25 spent 287 // "spread" steps of the ranged and healers on him ("wants 10 y from the raid at Kel'Thuzad ... no spot"), each one a cast not made. @@ -3094,11 +3408,16 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< if (enemy->GetEntry() != rule.enemy || !enemy->IsAlive() || enemy->GetVictim() != bot || !InPhase(enemy, rule.hpMax, rule.hpMin)) continue; + // Only one the tank has in reach: an add still walking in to it is met first. naxx_kelthuzad kt69o (1124): a Soul Weaver + // just sent at Mctankwa from the south alcove (3704,-5169) had it as its victim, and the tank, 77 y off at its slot, + // looked for a spot behind it on every pass for 40 s, each one in the alcove's resting adds' reach ("idle pack 27"). + if (!bot->IsWithinDistInMap(enemy, kFaceAwayReach)) + continue; float const ex = enemy->GetPositionX(), ey = enemy->GetPositionY(); float axis; if (!FaceAxisFor(plan, enemy, now, axis, rule.bearingDeg)) continue; - if (geo::TankOnAxis(ex, ey, bot->GetPositionX(), bot->GetPositionY(), axis, 30.0f * (float(M_PI) / 180.0f))) + if (geo::TankOnAxis(ex, ey, bot->GetPositionX(), bot->GetPositionY(), axis, rule.maxTurnDeg * (float(M_PI) / 180.0f))) continue; uint32_t& at = g_lastFaceAway[bot->GetGUID().GetCounter()]; if (now - at < 5000) @@ -3109,18 +3428,55 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< // raid), and the tank then never found a spot. bool found = false; float px = 0.0f, py = 0.0f, pz = 0.0f; + // The spot behind an add of a fixed row is the encounter's place, like the row's slots (Usable's fixedPlace): ground, path + // and detour count (keep-outs and idle packs too), the fight area round the main tank does not: the tank's place is set by + // the add it holds. naxx_kelthuzad kt69k (1124): a Soul Weaver's tank on the west of Kel'Thuzad's arc "found no spot on the + // axis behind" it on every pass from 90 s, 20-22 y from the camp and clear of the alcove keep-outs; the line gave no reason. + // Each failed probe now says why (refused). + bool const rowAdd = std::any_of(rules.tankSpot.begin(), rules.tankSpot.end(), + [&](TankSpot const& row) { return row.fixed && InTankSpot(row, rule.enemy); }); + std::map refused; + // FaceAway::maxTurnDeg past 30: when the line itself has no spot (the far side of a Soul Weaver at Kel'Thuzad's alcove rim lies + // in the alcove's keep-out), a spot further round, toward the side. naxx_kelthuzad kt69c / kt69f (1124): 3 and 11 "found no + // spot" a run, the Weaver went on facing its tank and the camp behind it, 26 and 28 dead to Wail of Souls. + std::vector turns = { 0.0f, 15.0f, -15.0f, 28.0f, -28.0f }; + for (float wide : { 50.0f, 75.0f }) + if (wide <= rule.maxTurnDeg - 5.0f) + { + turns.push_back(wide); + turns.push_back(-wide); + } for (float reach : { 3.5f, 2.8f, 2.2f }) { - for (float turnDeg : { 0.0f, 15.0f, -15.0f, 28.0f, -28.0f }) + for (float turnDeg : turns) { geo::AxisSpot(ex, ey, axis, reach, turnDeg * (float(M_PI) / 180.0f), px, py); if (!circles.empty() && InsideAny(circles, px, py, 0.5f)) + { + ++refused["hazard circle"]; continue; - if (Usable(bot, px, py, enemy->GetPositionZ(), pz, /*urgent*/ true)) + } + // FaceAway::knockback: where the enemy's cast throws the tank from that spot, straight away from the enemy. Not into + // a keep-out or an idle pack's reach. naxx_kelthuzad kt70a (1124): Mctankwa stepped behind a Soul Weaver 26 y north of + // the camp, Wail of Souls threw it 26 y on to 3735,-5057 at the north alcove's rim, and it held that Weaver, an + // Abomination and a Soldier there, 50 y from the healers' post, at 97-100 s (44-49% health); it died at 109 s. + if (rule.knockback > 0.0f) + { + float const d = Dist2D(ex, ey, px, py); + float const lx = d > 0.1f ? px + (px - ex) / d * rule.knockback : px; + float const ly = d > 0.1f ? py + (py - ey) / d * rule.knockback : py; + if (InsideAny(g_keepOut, lx, ly, 0.0f) || InsideAny(g_idleHostiles, lx, ly, 0.0f)) + { + ++refused["knockback lands in a keep-out"]; + continue; + } + } + if (Usable(bot, px, py, enemy->GetPositionZ(), pz, /*urgent*/ true, /*hazard*/ false, /*fixedPlace*/ rowAdd)) { found = true; break; } + ++refused[UsableWhyName(g_usableWhy)]; } if (found) break; @@ -3128,7 +3484,11 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< at = now; if (!found) { - TC_LOG_INFO("playerbot.v2.raid", "[raid_face] {} found no spot on the axis behind {}", bot->GetName(), enemy->GetName()); + std::string why; + for (auto const& [reason, n] : refused) + why += fmt::format("{}{} {}", why.empty() ? "" : ", ", reason, n); + TC_LOG_INFO("playerbot.v2.raid", "[raid_face] {} found no spot on the axis behind {} at ({:.0f},{:.0f}): {}", bot->GetName(), + enemy->GetName(), ex, ey, why); continue; } TC_LOG_INFO("playerbot.v2.raid", "[raid_face] {} steps behind {} to turn it away from the raid", bot->GetName(), enemy->GetName()); @@ -3256,8 +3616,7 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< // tank whose victim died turned on the nearest one at the door (bwl_nefarian 1109c run 2: Mctankwc "attacks ... 14263 ... mob // in_combat 0", then "takes Bronze Drakonid on Mctankwc dist=54y why=already_on_it"; the first tank to die in each run was 35-48 y // from the camp centre). - if (rule.fixed && self.tank && !EnemyInFight(plan, rule.endEnemy) && - std::any_of(plan.enemies.begin(), plan.enemies.end(), [&](Unit* e) { return e->GetEntry() == rule.anchor && e->IsAlive(); })) + if (rule.fixed && self.tank && !RowEnded(plan, rule) && FixedRowUp(plan, rule)) { std::vector adds(plan.enemies.begin(), plan.enemies.end()); std::list fresh; @@ -3267,8 +3626,18 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< for (Creature* c : fresh) if (!c->IsInCombat()) adds.push_back(c); + // TankSpot::skipClassMask: a tank of such a class takes none of the row's adds and keeps its slot. naxx_kelthuzad kt70c (1124): + // the bear (10,153 health, 6,241 armour on its sheet; the warriors 12,119 and 9,617) died to single Mortal Wounds of 9,007 from + // 72% at 95 s, 9,056 from full at 126 s and 8,112 at 193 s. + // Only while another tank has a hand free (RowSkips): kt70g, six Abominations up and the bear idle. + bool const skipsRow = RowSkips(plan, rule, bot) || OnEndEnemy(plan, rule, bot); for (Unit* enemy : adds) { + if (skipsRow && enemy->IsAlive() && InTankSpot(rule, enemy->GetEntry())) + { + out.forbidden_targets.push_back(enemy->GetGUID()); + continue; + } // An add already on this tank but still far out is waited for too: it walks to the tank at its slot. The rotation's chase // walked the tank out to meet it, and the next one, and the one after (bwl_nefarian 1110b: "takes Bronze Drakonid on Mctankwa // dist=39y why=already_on_it", then its melee spot at -7544,-1185; from 25 s on every tank fought 40-67 y from the camp @@ -3299,6 +3668,34 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< } if (Dist2D(bot->GetPositionX(), bot->GetPositionY(), tx, ty) < 3.0f) continue; + // TankSpot::holdSlack: a tank in melee with an add of the row that is on it stays this close to its slot. The walk turns its back + // to the add, and a blow from behind cannot be parried, dodged or blocked. naxx_kelthuzad kt70c (1124): Mctankwc walked to its + // slot from 3 y off with an Abomination behind it (facing 152 degrees off), and the Abomination's next swing killed it at 135 s. + if (rule.holdSlack > 0.0f && Dist2D(bot->GetPositionX(), bot->GetPositionY(), tx, ty) < rule.holdSlack && + std::any_of(plan.enemies.begin(), plan.enemies.end(), [&](Unit* e) + { + return e->IsAlive() && InTankSpot(rule, e->GetEntry()) && e->GetVictim() == bot && e->IsWithinMeleeRange(bot); + })) + continue; + // A tank that holds a FaceAway add of the row and already stands on its far side from the raid stays, a few yards off its slot: the + // face-away step put it there, and the walk back to the slot took it past the add, which turned to the raid again, and the next step + // took it out again (Kel'Thuzad's Soul Weavers, Wail of Souls in front of them). + if (HoldsFacedAway(plan, rules, rule, bot, now) && Dist2D(bot->GetPositionX(), bot->GetPositionY(), tx, ty) < kFaceAwaySlotSlack) + continue; + // One turned from the side (FaceAway::maxTurnDeg past 30, met wherever it was) is fought where it is, turned away or not yet: the + // walk to the slot takes the tank out of the Weaver's melee reach (it turns to the nearest raider in reach, or the top of its + // threat), and only the face-away step moves that tank. naxx_kelthuzad kt69k (1124): a Weaver's tank found no spot behind it at + // 3692,-5120 and walked toward its slot 14 y west of the camp; a second later the Weaver was on another raider 11 y from the tank + // ([tank_loose]), and one Wail of Souls killed seven healers at 92 s (3684,-5106), the start of the wipe. + if (std::any_of(rules.faceAway.begin(), rules.faceAway.end(), [&](FaceAway const& fa) + { + return fa.maxTurnDeg > 30.0f && InTankSpot(rule, fa.enemy) && + std::any_of(plan.enemies.begin(), plan.enemies.end(), [&](Unit* e) + { + return e->GetEntry() == fa.enemy && e->IsAlive() && e->GetVictim() == bot && InPhase(e, fa.hpMax, fa.hpMin); + }); + })) + continue; uint32_t& at = g_lastTankSpot[bot->GetGUID().GetCounter()]; if (now - at < 3000) { @@ -3540,7 +3937,7 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< } for (Stand const& rule : rules.stand) { - if (!Matches(rule.who, self, plan.mainTank) || EnemyInFight(plan, rule.endEnemy)) + if (!Matches(rule.who, self, plan.mainTank) || StandEnded(plan, rule)) continue; if (rule.share) { @@ -3580,10 +3977,12 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< if (rule.needOtherEnemy ? !other : (rule.needVictimIsMe && boss->GetVictim() != bot)) continue; out.post_enemy = boss->GetGUID(); + bool const fightPost = rule.fightTolerance > 0.0f && EnemyInFight(plan, rule.endEnemy); + float const tolerance = fightPost ? rule.fightTolerance : rule.tolerance; if (rule.who == Who::Healer && self.healer) { float sx = 0.0f, sy = 0.0f, sz = 0.0f; - SightSpot const spot = HealerSightSpot(plan, rule, circles, now, bot, sx, sy, sz); + SightSpot const spot = HealerSightSpot(plan, rule, circles, now, bot, sx, sy, sz, std::max(kSightRoam, tolerance)); if (spot == SightSpot::Here) { out.at_post = true; @@ -3596,7 +3995,7 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< } } float const offPost = Dist2D(bot->GetPositionX(), bot->GetPositionY(), rule.x, rule.y); - if (offPost <= rule.tolerance) + if (offPost <= tolerance) { out.at_post = true; continue; @@ -3604,7 +4003,7 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< // Near its post a healer with a hurt tank in reach heals, and a ranged DPS with its victim in reach casts, before it walks back: a hard // cast is refused while the bot moves (bwl_nefarian 1108h: the healers walked "role position" for 30 s and more at 97-100% mana, one // of twelve casting, while all four tanks died 45-80 s in). The post holds it there as if it stood on it. - if (offPost <= rule.tolerance + kPostCastSlack) + if (offPost <= tolerance + kPostCastSlack) { bool castsFirst = false; if (self.healer) @@ -3641,6 +4040,19 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< } return; } + // Stand::fightTolerance: back to just inside the wider post, along the line from its centre, not to the centre (the spread would + // walk the bot straight out again). + if (fightPost && offPost > 0.1f) + { + float const f = (tolerance - 3.0f) / offPost; + float const px = rule.x + (bot->GetPositionX() - rule.x) * f, py = rule.y + (bot->GetPositionY() - rule.y) * f; + float pz = 0.0f; + if (Usable(bot, px, py, rule.z, pz)) + { + SetMove(out, px, py, pz, "role position"); + return; + } + } SetMove(out, rule.x, rule.y, rule.z, "role position"); return; } @@ -4717,6 +5129,18 @@ void PublishTargets(Plan& plan, std::unordered_map& orders, return Matches(Who::Melee, m, plan.mainTank) && enemy->GetVictim() != m.p && IdleReachOnApproach(m.p->GetPositionX(), m.p->GetPositionY(), enemy->GetPositionX(), enemy->GetPositionY()) >= 0; }; + // A ranged DPS in a near-first encounter (RaidRules::rangedNearFirst) ranks an enemy past its spell range after every enemy inside it, and + // drops one past kRangedFarDrop for a near pick. naxx_kelthuzad af55 (1121) kt2af55 run 1: the Soldiers (ranged priority 6) are picked as + // they leave the alcoves 40-50 y off; the mages sat on them out of range, "classic_mage:auto_attack" 42 times against 9 nukes, cast_fail + // API_BEYOND_RANGE / OUT_OF_RANGE every few seconds, raid damage near 2,000 a second while the adds piled up on the tanks. + bool rangedNearFirst = false; + for (Unit* enemy : plan.enemies) + if (std::find(rules.rangedNearFirst.begin(), rules.rangedNearFirst.end(), enemy->GetEntry()) != rules.rangedNearFirst.end()) + rangedNearFirst = true; + auto const rangedFar = [&](Member const& m, Unit* enemy, float reach) + { + return rangedNearFirst && Matches(Who::Ranged, m, plan.mainTank) && enemy->GetVictim() != m.p && m.p->GetExactDist2d(enemy) > reach; + }; auto const bestFor = [&](Member const& m) -> Unit* { uint8_t const schools = MemberDamageSchools(m, plan.mainTank); @@ -4725,6 +5149,7 @@ void PublishTargets(Plan& plan, std::unordered_map& orders, bool bestHurts = false; bool bestHeld = false; bool bestReach = false; + bool bestInRange = false; for (size_t i = 0; i < candidates.size(); ++i) { Unit* enemy = candidates[i]; @@ -4742,11 +5167,14 @@ void PublishTargets(Plan& plan, std::unordered_map& orders, continue; bool const hurts = (schools & ~candidateAvoid[i]) != 0; bool const reach = !meleeOutOfReach(m, enemy); + bool const inRange = !rangedFar(m, enemy, kRangedNearReach); bool better = !best || (hurts && !bestHurts); if (!better && hurts == bestHurts) { if (reach != bestReach) better = reach; + else if (inRange != bestInRange) + better = inRange; else if (held != bestHeld) better = held; else if (priority != bestPriority) @@ -4763,6 +5191,7 @@ void PublishTargets(Plan& plan, std::unordered_map& orders, bestHurts = hurts; bestHeld = held; bestReach = reach; + bestInRange = inRange; } } return best; @@ -4776,6 +5205,28 @@ void PublishTargets(Plan& plan, std::unordered_map& orders, continue; RaidOrder& o = it->second; o.forbidden_targets.insert(o.forbidden_targets.end(), forbiddenAll.begin(), forbiddenAll.end()); + // An enemy no tank holds (RaidRules::noTank) is the DPS's, wherever it runs: while a fixed tank row holds, its tanks hit one only when + // it is on the tank or next to it. naxx_kelthuzad kt69a (1124, the camp script): the tanks' victims were Soldiers of the Frozen Wastes + // 14-50 y away (sent at random raiders, 2,000 health), so the tanks chased them off their slots (58 slot walks, most "NO PROGRESS, + // generator 5"), and the Abominations and Soul Weavers walked loose into the camp. Set here, in every pass: set in the tank spot step + // (kt69d), it was missing whenever an earlier step of the movement pass gave the tank a move, and the tank planner still handed far + // Soldiers to free tanks ("takes Soldier of the Frozen Wastes ... dist=42-56y why=nearest / loose_nearest", 13 of 38 slot walks). + // kt69g (script5): a Soldier sent at the tank itself was still its own (its victim was this tank), and the planner gave it to + // the tank 44-59 y out ("takes Soldier ... on Mctankwa dist=53y why=on_main_tank"), as it gave one sent this tick, before this + // pass listed it (20 of 31 slot walks had a Soldier as the tank's victim). Every one is off now, near or far, on the tank or not: + // the DPS kill them, and no_tank_off tells the planner before the list has the new ones. + // RaidRules::noTankWholeFight: row or not. naxx_kelthuzad kt76b (1125): the last Abomination died at about 330 s in phase 2, the row + // ended, and three tanks took a Soul Weaver each at once; the one Mctankwb held 21 y west of the camp (3695,-5101) faced it and the + // camp behind it, and its Wails of Souls killed 5 at 359 s and 13 at 363 s, 0-13 y from the camp. + bool const rowUp = std::any_of(rules.tankSpot.begin(), rules.tankSpot.end(), + [&](TankSpot const& row) { return row.fixed && !RowEnded(plan, row) && FixedRowUp(plan, row); }); + if (m.tank && (rowUp || rules.noTankWholeFight)) + { + o.no_tank_off = true; + for (Unit* enemy : plan.enemies) + if (enemy->IsAlive() && NoTank(plan.mapId, enemy->GetEntry())) + o.forbidden_targets.push_back(enemy->GetGUID()); + } if (!m.tank) o.forbidden_targets.insert(o.forbidden_targets.end(), forbiddenDps.begin(), forbiddenDps.end()); if (Matches(Who::Melee, m, plan.mainTank)) @@ -4798,7 +5249,8 @@ void PublishTargets(Plan& plan, std::unordered_map& orders, // over, and the focus is its pick again once it walks out. if (!focus.IsEmpty()) for (Unit* enemy : candidates) - if (enemy->GetGUID() == focus && !shieldForbids(m, enemy) && !meleeOutOfReach(m, enemy)) + if (enemy->GetGUID() == focus && !shieldForbids(m, enemy) && !meleeOutOfReach(m, enemy) && + !rangedFar(m, enemy, kRangedNearReach)) pick = enemy; if (!pick) pick = bestFor(m); @@ -4828,6 +5280,22 @@ void PublishTargets(Plan& plan, std::unordered_map& orders, } } } + // A ranged member on an enemy far past its spell range leaves it for a pick inside it (rangedNearFirst), the kill focus too: the + // synchronized focus is most often a Soul Weaver still walking in from its alcove. The drop distance is above the pick's so a + // target walking in and out of range is not swapped back and forth. + if (pick && !rangedFar(m, pick, kRangedNearReach)) + if (Unit* const victim = m.p->GetVictim(); victim && victim != pick && + rangedFar(m, victim, kRangedFarDrop)) + { + o.forbidden_targets.push_back(victim->GetGUID()); + uint32_t& at = g_lastOutOfReachLog[m.p->GetGUID().GetCounter()]; + if (getMSTime() - at >= 10000u) + { + at = getMSTime(); + TC_LOG_INFO("playerbot.v2.raid", "[raid_target] {} leaves {} {:.0f} y off for {} {:.0f} y off, inside its range", + m.p->GetName(), victim->GetName(), m.p->GetExactDist2d(victim), pick->GetName(), m.p->GetExactDist2d(pick)); + } + } // A member already on an enemy it cannot hurt leaves it while there is one it can: the fallback alone only steers a member // with no target. uint8_t const schools = MemberDamageSchools(m, plan.mainTank); @@ -6414,8 +6882,10 @@ static void FillRaidRoles(uint64_t key, detail::Plan const& plan, uint32_t now_m b.guid = m.p->GetGUID().GetCounter(); b.cls = m.p->GetClass(); b.role = m.tank ? RosterRole::Tank : m.healer ? RosterRole::Healer : RosterRole::Dps; - // Humans and bots nobody owns keep what they have. - b.role_set = !m.bot || owners.GetOwner(b.guid).account_id == 0 || owners.DeclaredRole(b.guid) != Role::Unknown; + // Humans, bots nobody owns and a player's own character brought as a bot keep what they have. + WorldSession const* sess = m.p->GetSession(); + bool const own_character = sess && !Services::Accounts().is_pool_account(sess->GetAccountId()); + b.role_set = !m.bot || own_character || owners.GetOwner(b.guid).account_id == 0 || owners.DeclaredRole(b.guid) != Role::Unknown; roster.push_back(b); byGuid[b.guid] = m.p; } diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_NAXX.cpp b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_NAXX.cpp index ea76f8cd7f..39967d603c 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_NAXX.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_NAXX.cpp @@ -215,12 +215,17 @@ namespace Playerbot::Raid { // cloud's 9 y), 36% of his health in 90 s, and the tanks died at 88-104 s. His tank leads him out of them. // A cloud's reach grows from 2 y to 20 y over its aura 28158 (classic_spell_grobbulus_cloud_poison); his tank leads him by that. r.dragOut.push_back({ 15931, 16363, 11.0f, 28158, 2.0f, 20.0f }); - r.avoidFrontal.push_back({ 15931, 20.0f, 50.0f, Who::NonTank }); + // Slime Spray reaches 45 y (bot_death spell_data radius=45), not 20, and his tank turns him every few seconds while it leads him out + // of the clouds (dragOut): the cone is kept to its full reach and 15 degrees wider on each side. naxx_grobbulus r3af55-2: the first + // spray (25 s) caught Mchealsd and Mcshadb, 7-15 y from him and still on a "leave cone" step from his last turn; their two Fallout + // Slimes killed eight healers by 57 s and the raid wiped at 54%. + constexpr float kGrobSprayReach = 45.0f, kGrobSprayHalfDeg = 50.0f, kGrobSprayMarginDeg = 15.0f; + r.avoidFrontal.push_back({ 15931, kGrobSprayReach, kGrobSprayHalfDeg, Who::NonTank, 0.0f, 100.0f, 0.0f, true, kGrobSprayMarginDeg }); // Every player the spray hits leaves a Fallout Slime where it stands (classic_boss_grobbulus.cpp SpellHitTarget, one each), so // the main tank is the only one in front of him: the off tanks keep the Fallout Slimes from his flank. naxx_grobbulus 1115a: all // four tanks stood on him in front from 69 s, one spray at 160 s put six slimes on them at once, the four tanks died to the slimes // in 11 s and the slimes then killed 30 of the raid. - r.avoidFrontal.push_back({ 15931, 20.0f, 50.0f, Who::OffTank }); + r.avoidFrontal.push_back({ 15931, kGrobSprayReach, kGrobSprayHalfDeg, Who::OffTank, 0.0f, 100.0f, 0.0f, true, kGrobSprayMarginDeg }); r.priority.push_back({ 16290, 3 }); // Fallout Slime // --------------------------------------------------------------------------------------------------------------- @@ -299,16 +304,88 @@ namespace Playerbot::Raid { r.spread.push_back({ 15990, 10.0f, Who::Ranged }); r.spread.push_back({ 15990, 10.0f, Who::Healer }); // Phase 1 adds (naxx/classic_naxxramas.h:123-126). Guardians of Icecrown (phase 3) are shackled. - r.priority.push_back({ 16429, 4 }); // Soul Weaver - // Soldiers explode (Dark Blast 28457) when they reach somebody, so the ranged shoot them down on the way in; the melee keep - // the Soul Weavers and the Abominations (first matching row per bot wins, so the ranged row comes first). + // Kill order (first matching row per bot wins, so the ranged and melee rows come first). Soldiers explode (Dark Blast 28457) when + // they reach somebody, so the ranged shoot them down on the way in, then the Soul Weavers (Wail of Souls), then the Abominations. + // The melee take the Abominations first: the tanks hold them, and an Abomination left alive stacks Mortal Wound 28467 on its tank + // until the tank dies and it walks into the raid. naxx_kelthuzad af55 (1121), 4 of 4 wipes with the Abominations last (2): kt2af55 + // run 1 lost 13 of 40 to Mortal Wound (200% weapon damage, 8,224-11,015 a hit on cloth), all three warrior tanks dead by 151 s with + // the Abominations at 89-98%, then 11 to Wail of Souls from the Weavers they had held. r.priority.push_back({ 16427, 6, Who::Ranged }); + r.priority.push_back({ 16429, 5, Who::Ranged }); + r.priority.push_back({ 16428, 4, Who::Ranged }); + r.priority.push_back({ 16428, 5, Who::Melee }); + // The unconditional rows are the tanks' order: an Abomination before a Soul Weaver, so a tank holding one never drops it for a loose + // Weaver (af600/af601: "priority 4 over 3", and the loose Abominations killed 37-38 of the 40-43 dead). + r.priority.push_back({ 16428, 5 }); // Unstoppable Abomination (the highest unconditional row: the synchronized kill focus) + r.priority.push_back({ 16429, 4 }); // Soul Weaver r.priority.push_back({ 16427, 3 }); // Soldier of the Frozen Wastes // No tank holds a Soldier: each one is sent at a random raider and blows up on arrival (classic_kt_p1AddAI, Dark Blast 28457), so // the raid shoots them on the way in and the tanks keep the Abominations (naxx-kt-1114e: the tanks chased Soldiers 26-59 y out and // the DPS held their damage waiting for them, 0 damage a second for 18 s). r.noTank.push_back(16427); - r.priority.push_back({ 16428, 2 }); // Unstoppable Abomination + // A Soul Weaver is tanked, and turned away from the raid: Wail of Souls 28459 (4,250 shadow and a knockback in front of it) goes + // wherever it faces, and an untanked one faces its victim, in the middle of the raid. It has 70,000 health (classic_boss_kelthuzad.cpp + // Reset), too much for the ranged to burn on the way in. r1 (1122) had left it to the DPS because its tank could not reach it at an alcove's + // keep-out rim; r3 (1123) lets a tank fight a target there from outside the circle. naxx_kelthuzad kt67a / kt67b (1124), untanked: + // 16 and 25 dead to Wail of Souls, four melee at once 1-1.4 y from one Weaver, and 768-792 of the 1,028-1,132 forced moves a bot + // switching between "leave cone" and "leave hazard" (the cone's way out in an alcove circle, the circle's way out in the cone). + // Its tank may stand up to 80 degrees off the line from the camp through it (FaceAway::maxTurnDeg): the cone is 60 degrees each + // side, so the camp stays 100 degrees and more off its middle. At the alcove rim the far side lies in the keep-out. + // AzerothCore-style variant (kt-af61 script17ac, after mod-playerbots NaxxActions_Kelthuzad.cpp, GPL-2.0-or-later): the Weavers + // are not tanked at all. The ranged burn them inside 30 y of the camp, the tanks and melee keep to the Abominations, and nobody + // steps out of a Weaver's cone: the raid stays stacked at the camp (no faceAway row, no avoidFrontal row, noTank below). + // Tried against script16 (tanked and turned, 1124): kt69k-r had a Weaver on a raider in 70-75% of the samples anyway. + r.noTank.push_back(16429); + r.noTankWholeFight = true; // phase 2 too, after the row ends (RaidBrain PublishTargets, kt76b) + // Phase 1 is fought from one camp in the middle of the room, under Kel'Thuzad's dais, where the Nefarian fight's camp is the model + // (RaidEncounterData_BWL_Movement.cpp): the ranged DPS and the healers hold 7 y round it, the tanks hold the Abominations and Weavers + // on an arc 14 y round it, 12 y apart (out of one another's Weaver cones), and the DPS take one focus (the Kel'Thuzad fight script, + // RaidFightScript.h). A Weaver's tank stands on its far side from the camp (FaceAway), so Wail of Souls goes out toward the empty + // ground between the arc and the alcove keep-outs (32 y from the centre), never into the camp; its knockback has 10 y and more there. + // The arc opens west (168 degrees), away from the gap in the alcove ring at the room's east side (alcoves at 33-304 degrees round + // him, every 45). The layout ends when Kel'Thuzad can be hit (phase 2: endEnemy, EnemyInFight leaves an immune enemy out). + // naxx_kelthuzad kt67a / kt67b (1124), without it: the raid stood over the whole floor between the keep-outs and the cones, and + // 768-792 of each run's 1,028-1,132 forced moves were a bot sent from one to the other and back. + // The row and the posts hold while any phase 1 add is in the raid's combat (each sent add is put in it as it is sent): Kel'Thuzad + // himself is immune all of phase 1, and one Soldier lives a few seconds. The healers' first post names the Soldier, the row's + // anchor: the arc's slots are laid on ground that post sees (SeenArcAngle). + constexpr float kKtCampX = 3716.0f, kKtCampY = -5106.0f, kKtFloorZ = 142.0f; + // A tank goes after a loose add only within 22 y of the camp (fetchMax): its far side then lies 25-26 y out, well inside the alcove + // keep-outs (32 y), and the face-away step finds it. The adds walk in to the raider they were sent at, past the arc. + // The row holds the Abominations only (AzerothCore-style variant: the Weavers are not tanked, see the faceAway note above). A tank + // holding two of them hands one to an empty-handed tank (handOffFrom 2): Mortal Wound on two Abominations at once kills a tank in + // seconds. + // The bear takes no Abomination while a warrior has a hand free (skipClassMask: druid; RowSkips), and a tank holding one stays + // within 6 y of its slot (holdSlack). + // When Kel'Thuzad comes down (on a timer, 5:35 into the pull, whatever is still alive) the row holds the last Abominations: the tank + // that takes him leaves the row, the others keep their slots, and the row ends with the last Abomination (endAfterAdds). + r.tankSpot.push_back({ 16427, 16428, 14.0f, 12.0f, true, kKtCampX, kKtCampY, 168.0f, {}, 15990, 22.0f, 0.0f, 2, + 1u << (11 - 1) /* druid */, 6.0f, true }); + // An Abomination's Mortal Wound takes a full tank to a quarter: its tank's healers keep a heal going on it (burstTank). + r.burstTank.push_back(16428); + for (uint32_t add : { 16427u, 16428u, 16429u }) + { + // The posts hold into phase 2 while adds of their entry are left (endAfterEnemy): a raid spread round Kel'Thuzad stood in the + // way of the last Soul Weavers walking in (kt74b, see StandEnded). There they hold within 20 y of the camp (fightTolerance), + // where the ranged and healers spread 10 y apart against Frost Blast: kt79a (1125), kept within 7 y, one Frost Blast stunned + // 21 of the camp at 412 s and killed 18 in 5 s. + r.stand.push_back({ add, Who::Healer, kKtCampX, kKtCampY, kKtFloorZ, 7.0f, false, 0, 100.0f, 0.0f, 0, 15990, 0.0f, true, 20.0f }); + r.stand.push_back({ add, Who::Ranged, kKtCampX, kKtCampY, kKtFloorZ, 7.0f, false, 0, 100.0f, 0.0f, 0, 15990, 0.0f, true, 20.0f }); + } + // The adds walk in from seven alcoves at once and the ranged priority (Soldiers) is most often a fresh one at the far wall: the ranged + // take what is inside their spell range first (RaidRules::rangedNearFirst), while any phase 1 add or Kel'Thuzad is up. + r.rangedNearFirst.push_back(15990); + r.rangedNearFirst.push_back(16427); + r.rangedNearFirst.push_back(16428); + r.rangedNearFirst.push_back(16429); + // Mortal Wound 28467 stacks on the Abomination's tank (-10% healing a stack, 200% weapon damage a hit): another tank takes it at 5, + // the taker may carry 2 itself (with several Abominations up no tank stays clean). Each tanked Abomination also counts a taker + // for the tank roster (PveGroupCoordinator), so the fourth tank (Mctankda) is on it from the second Abomination, not off it. + r.tankSwap.push_back({ 16428, 28467, 5, 2 }); + // Abominations come the whole of phase 1 (44 s, then every 17-30 s: ktAbominationSpawnMs), each needing a tank and a taker: + // all four tanks are on the roster from the first sent Soldier (RaidRules::allTanks), not from the second engaged Abomination. + r.allTanks.push_back(15990); + r.allTanks.push_back(16427); // The seven alcoves are out of bounds (naxx-kt-1114d: the tanks met the first Soldier at the south alcove, 3704,-5170, pulled its // 3 Abominations and its Soul Weaver and the raid died in 18 s). Each alcove keeps 10 Soldiers wandering within 14 y of its // centre, 3 Abominations and a Soul Weaver (classic_boss_kelthuzad.cpp:518-556); they wake for anyone within their own aggro @@ -325,7 +402,19 @@ namespace Playerbot::Raid { // Soul Weaver: Wail of Souls 28459, damage and a knockback in front of it. This build's spell data gives it a 32 y radius // ([bot_death] spell_data radius=32), not the vanilla 30: naxx_kelthuzad af52 sweep 1 killed a healer standing 30.7 y from the // Weaver. 34 y and a 10 degree margin: a Weaver loose on the raid turns from one victim to the next and casts as it turns. - r.avoidFrontal.push_back({ 16429, 34.0f, 60.0f, Who::NonTank, 0.0f, 100.0f, 0.0f, true, 10.0f }); + // AzerothCore-style variant: no cone row for the Weaver (see the faceAway note above). With it, the healers made 74 "leave cone" + // moves in kt69r (1124) and ended north of the camp by the alcoves, where the Soldiers and Abominations picked them off. + // The melee DPS keep 8 y from a Weaver that is not on them, out of its melee reach: one whose victim steps out of that reach takes + // the nearest raider in it (classic_soul_weaver_ai), and the melee beside it took it from its tank (kt69p, 1124: on a raider in 73 + // of 94 samples). They do not attack it either (Fight::meleeOff, RaidFightScript.h). + r.avoidEnemy.push_back({ 16429, 8.0f, Who::Melee }); + // The raider a Weaver is on leads it (RaidRules::leadAway): it walks to where the Weaver, coming up to it, faces out of the camp + // with nobody else in the cone, and the 26 y knockback (kt70a) lands short of the alcove keep-outs. naxx_kelthuzad kt70e (1125): + // one Weaver on a healer in the camp killed 13 with one Wail of Souls. Only within 40 y: a Weaver walks in slowly from its alcove, and + // a victim 40-49 y from it moved every 2 s for nothing (kt73b: the healers Mchealse and Mchealsc led Weavers 39-49 y off for 25 s); + // but it casts from the cone's range, not from melee (kt76a: from 23 y), so the lead starts before that (25 y in script25ac was + // too late). + r.leadAway.push_back({ 16429, 32.0f, 60.0f, 25.9f, 40.0f }); // Shackle at most 3 Guardians: a 4th frees them all (classic_boss_kelthuzad.cpp:1027-1100). r.crowdControl.push_back({ 16441, CcKind::Shackle, 0, 3 }); // A Guardian that is tanked stacks Blood Tap 28470 on its tank (+damage, +size per stack, classic_boss_kelthuzad.cpp:104): diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounters.cpp b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounters.cpp index 1484a48b91..afd38961ad 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounters.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounters.cpp @@ -90,6 +90,12 @@ bool RulesPlaceTank(uint32_t mapId, uint32_t boss) return false; } +bool HitsTankHard(uint32_t mapId, uint32_t entry) +{ + RaidRules const* rules = RulesForMap(mapId); + return rules && std::find(rules->burstTank.begin(), rules->burstTank.end(), entry) != rules->burstTank.end(); +} + bool OwnsAura(uint32_t mapId, uint32_t aura) { RaidRules const* rules = RulesForMap(mapId); diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounters.h b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounters.h index 5760b7fdd8..a0a019e60d 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounters.h +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounters.h @@ -118,8 +118,11 @@ struct Spread { uint32_t enemy; float radius; Who who; float hpMax = 100.0f; flo struct Stand { uint32_t enemy; Who who; float x, y, z; float tolerance; bool needVictimIsMe; uint32_t needOtherEnemy; float hpMax = 100.0f; float hpMin = 0.0f; uint8_t share = 0; // share 1 / 2: only the even / odd numbered of the members this rule matches (by guid order), so one rule list can split e.g. the off-tanks between two posts uint32_t endEnemy = 0; // the post ends once this enemy is in the fight (EnemyInFight): a phase's layout that the next phase must not keep - float maxFromEnemy = 0.0f; }; // > 0: the post holds only while the enemy is within this many yards of it (a boss pulled + float maxFromEnemy = 0.0f; // > 0: the post holds only while the enemy is within this many yards of it (a boss pulled // somewhere else is fought where he is, not from posts across the room); 0 = always + bool endAfterEnemy = false; // endEnemy ends the post only once no is left alive in the fight (StandEnded) + float fightTolerance = 0.0f; }; // > 0: once endEnemy is in the fight (the post kept by endAfterEnemy), the post holds within + // this many yards instead, and a bot past it walks back to just inside it (room to spread) // While is alive and fighting, a member carrying stands yards from the enemy's live position // along the fixed world bearing (radians) and holds within (Thaddius' Positive / Negative Charge @@ -289,7 +292,18 @@ struct StayNear { uint32_t enemy; float radius; Who who; float hpMax = 100.0f; f // the back of the lair, wherever the raid stands (the raid enters from the west and spreads; a bearing taken from where it stood at the pull // put the tank on the wrong side once the raid moved). constexpr float kNoBearing = 1000.0f; -struct FaceAway { uint32_t enemy; float hpMax = 100.0f; float hpMin = 0.0f; float bearingDeg = kNoBearing; }; +// maxTurnDeg: how far off that line the tank may stand (its spot, and the check that it is already there). Past 30 degrees only for an +// enemy whose frontal hazard is narrow enough that a turn that far still keeps the raid behind it (Kel'Thuzad's Soul Weavers). +struct FaceAway { uint32_t enemy; float hpMax = 100.0f; float hpMin = 0.0f; float bearingDeg = kNoBearing; float maxTurnDeg = 30.0f; + float knockback = 0.0f; }; // > 0: the enemy's frontal cast throws its tank this far straight back; a spot whose landing + // lies in a keep-out or an idle pack's reach is refused + +// While an untanked is on a raider, that raider leads it (Kel'Thuzad's Soul Weavers): it stands where the enemy, walking up to it, +// faces nobody else with its frontal cast (a cone of yards, degrees each side of its facing), where its walk there passes +// nobody (an enemy that takes the nearest raider in its melee reach while its victim is out of it), and where the cast's knockback +// ( yards straight on, 0 for none) lands clear of the keep-outs and the idle packs. A victim already in such a place holds it. +// Only for an enemy within yards of its victim, and never a tank holding an add of a fixed row (its place is its slot). +struct LeadAway { uint32_t enemy; float range; float halfDeg; float knockback = 0.0f; float maxDist = 45.0f; }; // While is fighting, the players that hold an stand yards past the spot the anchor stood on when the fight began, away from the // raid's centre at that moment, side by side yards apart (Majordomo: his tank drags him out, each Elite tank one Elite, all visibly apart). @@ -298,7 +312,17 @@ struct FaceAway { uint32_t enemy; float hpMax = 100.0f; float hpMin = 0.0f; floa // middle of the arc on bearing rowDeg (a camp at (x, y) then has every tank's pile at the same distance). also: further entries whose holders share the one row (adds of any colour), so no two tanks get the same slot. // endEnemy: the row ends once this enemy is in the fight (EnemyInFight), as Stand::endEnemy. struct TankSpot { uint32_t anchor; uint32_t enemy; float reach; float spacing; bool fixed = false; float x = 0.0f, y = 0.0f, rowDeg = 0.0f; - std::vector also = {}; uint32_t endEnemy = 0; }; + std::vector also = {}; uint32_t endEnemy = 0; + float fetchMax = 0.0f; // > 0 (fixed row): a tank goes after a loose add only within this many yards of (x, y) + float fetchTurned = 0.0f; // > 0 (fixed row): a FaceAway add turned from the side (maxTurnDeg past 30) is met + // once it is within this many yards of (x, y), wherever the tank stands, and not before + uint8_t handOffFrom = 0; // > 0 (fixed row): a tank holding this many of the row's adds hands all but its most hurt + // one to an empty-handed tank of the row (0: from 3, keeping 2) + uint32_t skipClassMask = 0; // fixed row: tanks of these classes (1 << (class - 1)) take none of the row's adds + float holdSlack = 0.0f; // > 0 (fixed row): a tank in melee with one of the row's adds on it stays when it is this + // close to its slot (the walk turns its back to the add) + bool endAfterAdds = false; }; // endEnemy ends the row only once none of the row's adds is alive; until then the tank that + // holds the endEnemy is out of the row and the others keep their slots (RowEnded, OnEndEnemy) inline bool InTankSpot(TankSpot const& rule, uint32_t entry) { return entry == rule.enemy || std::find(rule.also.begin(), rule.also.end(), entry) != rule.also.end(); @@ -379,9 +403,14 @@ struct RaidRules std::vector killTogether; std::vector stayNear; std::vector faceAway; + std::vector leadAway; std::vector tankSpot; std::vector standBehind; std::vector guardRise; + // While any of these enemies is alive and in the fight, every live tank is on the raid's tank roster (PveGroupCoordinator): an + // encounter that sends tanked adds the whole time (Kel'Thuzad's Abominations, each with a Mortal Wound swap) cannot wait for the + // engaged count to grow the roster one add at a time. + std::vector allTanks; std::vector standFlank; std::vector resistPotion; std::vector carrierPotion; @@ -390,6 +419,11 @@ struct RaidRules std::vector threatDrop; // bosses that cut their tank's threat on a schedule (ThreatDropFraction) std::vector noDispel; // auras nobody removes (removing them hurts: Wyvern Sting, Mutating Injection) std::vector noTank; // summoned adds the DPS burns down: tanks hold every other mob first and never count them as a roster need + // The tanks keep off the noTank adds for the whole fight, not only while a fixed tank row holds (Kel'Thuzad: a Soul Weaver a tank holds + // faces the tank, and the camp behind it). + bool noTankWholeFight = false; + std::vector burstTank; // adds whose single hits take a full tank to a quarter (Kel'Thuzad's Abominations): their tank's healers + // pre-heal it as they would under a boss, whoever else is hurt (HitsTankHard) std::vector tankOrder; // mobs the tanks take in this order, first listed first (Majordomo: Healers, then Elites); unlisted mobs come after std::vector tankLast; // a mob the tanks take only when no other free mob is left (Majordomo: he does little damage and cannot die) std::vector offTankMob; // a boss the second tank holds from the first second (Majordomo); no area taunt while he is up, the tanks keep their mobs @@ -398,6 +432,10 @@ struct RaidRules // then the higher priority, then the most hurt one: wave fights where adds keep coming, an untanked one only means a threat hold, and // the raid has to finish one before the next (Victor Nefarius' drakonids). std::vector focusHeldLowest; + // Encounters (an enemy entry that is up during them) where a ranged DPS looking for a target takes one inside its spell range before + // any farther one, whatever the priority, and leaves a far one it is on for a near one: adds that keep walking in from all sides, where + // the top priority is most often a fresh one at the far wall (Kel'Thuzad's Soldiers from the alcoves). + std::vector rangedNearFirst; }; // How long the corridor of a cast breath stays open from the first sighting of the cast. Onyxia's damage is one instant at the end of the 5 s cast @@ -456,6 +494,10 @@ size_t InterruptOrder(uint32_t mapId, uint32_t spell); // tank such a mob only when no other engaged mob is free, and the tank roster does not grow for it. bool NoTank(uint32_t mapId, uint32_t entry); +// True when the map's rules list as an add whose hits take a full tank to a quarter (burstTank): the tank pre-heal treats +// one on the tank as a boss and keeps a heal going on it whoever else is hurt. Static data, safe on the bot worker threads. +bool HitsTankHard(uint32_t mapId, uint32_t entry); + // RaidRules::tankOrder: the position of in the map's tank order (0 = first), or UINT32_MAX when it is not listed. uint32_t TankOrder(uint32_t mapId, uint32_t entry); diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidFightScript.cpp b/src/modules/PlayerbotV2/Bot/Raid/RaidFightScript.cpp index 3abe5f261f..b8de0b7509 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidFightScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidFightScript.cpp @@ -228,7 +228,8 @@ void ApplyFightScript(Plan& plan, std::unordered_map& order // Fight::heldFirst: the enemies a tank of the raid holds. std::vector held; - if (fight->heldFirst) + bool const anyTankAlive = std::any_of(plan.members.begin(), plan.members.end(), [](Member const& tm) { return tm.tank && tm.p->IsAlive(); }); + if (fight->heldFirst || fight->heldOnly || fight->meleeHeldOnly) for (Unit* enemy : mine) if (Unit* v = enemy->GetVictim()) if (Player* vp = v->ToPlayer()) @@ -305,6 +306,27 @@ void ApplyFightScript(Plan& plan, std::unordered_map& order continue; } + // Fight::meleeOff: off limits for a melee DPS bot (see RaidFightScript.h, Kel'Thuzad). + if (fight->meleeOff && !m.ranged) + for (Unit* enemy : mine) + if (enemy->GetEntry() == fight->meleeOff) + o.forbidden_targets.push_back(enemy->GetGUID()); + // Fight::meleeCampReach: the melee DPS fight at the camp, beside the tanks and in the healers' reach; an add further out is met there. + // The tanks of the row go no further than its fetchMax (22 y) for an add that has reached nobody. naxx_kelthuzad kt71a (1125): an + // Abomination sent at Mcwarra was met by four melee 32-35 y north-east of the camp (3737-3744,-5081), at the alcove rim, with the four + // tanks at their slots holding nothing; its melee and Mortal Wound killed three of them in 2 s at 58-60 s, a Wail of Souls the fourth. + if (fight->meleeCampReach > 0.f && fight->campReach > 0.f && !m.ranged) + for (Unit* enemy : mine) + if (Dist2D(enemy->GetPositionX(), enemy->GetPositionY(), fight->campX, fight->campY) > fight->meleeCampReach) + o.forbidden_targets.push_back(enemy->GetGUID()); + // Fight::meleeHeldOnly: a later-rank add no tank holds is off limits for a melee DPS bot while a tank of the raid lives (see + // RaidFightScript.h, Kel'Thuzad). With every tank dead it is hit again: nobody else will take it off the raid. + if (fight->meleeHeldOnly && !m.ranged && anyTankAlive) + for (Unit* enemy : mine) + if (enemy->GetEntry() != fight->boss && enemy->GetEntry() != fight->untanked && Script::RankOf(*fight, enemy->GetEntry()) > 0 && + std::find(held.begin(), held.end(), enemy) == held.end()) + o.forbidden_targets.push_back(enemy->GetGUID()); + // Skull only: everything else of the fight, marked or sheeped or not, is off limits for this bot. if (fight->skullOnly) for (Unit* enemy : mine) @@ -315,6 +337,22 @@ void ApplyFightScript(Plan& plan, std::unordered_map& order // every enemy it can reach resists those, all its class's schools count again. uint8_t const allSchools = fight->schoolAware ? MemberDamageSchools(m, plan.mainTank) : uint8_t(0); uint8_t const mainSchools = fight->schoolAware ? MemberMainSchools(m, plan.mainTank) : uint8_t(0); + // Fight::firstRankSquad: this bot is one of the first ranged DPS bots of the raid (plan.members is sorted by guid). + bool inSquad = false; + size_t squadIndex = 0; + if (fight->firstRankSquad && m.ranged) + { + size_t before = 0; + for (Member const& other : plan.members) + { + if (other.p == m.p) + break; + if (other.bot && other.ranged) + ++before; + } + inSquad = before < fight->firstRankSquad; + squadIndex = before; + } std::vector view; view.reserve(mine.size()); for (size_t i = 0; i < mine.size(); ++i) @@ -330,6 +368,17 @@ void ApplyFightScript(Plan& plan, std::unordered_map& order e.eligible = enemy->IsAlive() && !forbidden && !(c && c->IsInEvadeMode()) && enemy->IsVisible() && !enemy->IsUninteractible() && !enemy->HasUnitFlag(UNIT_FLAG_NON_ATTACKABLE); e.held = std::find(held.begin(), held.end(), enemy) != held.end(); + // Fight::firstRankSquad: the first rank is for the squad only (see RaidFightScript.h, Kel'Thuzad). + if (fight->firstRankSquad && e.eligible && !inSquad && Script::RankOf(*fight, e.entry) == 0) + e.eligible = false; + // Fight::heldOnly: after the first rank, only one a tank holds (see RaidFightScript.h, Kel'Thuzad). + if (fight->heldOnly && e.eligible && !e.held && enemy->GetEntry() != fight->boss && enemy->GetEntry() != fight->untanked && + Script::RankOf(*fight, e.entry) > 0) + e.eligible = false; + // Fight::meleeFirstReach: a melee DPS bot takes a first-rank enemy only when it is next to it (see RaidFightScript.h, Kel'Thuzad). + if (fight->meleeFirstReach > 0.f && !m.ranged && e.eligible && Script::RankOf(*fight, e.entry) == 0 && + !m.p->IsWithinDistInMap(enemy, fight->meleeFirstReach)) + e.eligible = false; view.push_back(e); } // Before the camp filter, as before: a bot whose schools the camp's enemies all resist still finds one in its reach. @@ -348,6 +397,7 @@ void ApplyFightScript(Plan& plan, std::unordered_map& order // Fight::campReach: only the enemies at the camp this bot can see, while there is one (see RaidFightScript.h, Nefarian). // Else the ones in its sight and spell reach (it is not sent walking: its post would walk it back), else every one. uint64_t const raidFocus = st.focus.IsEmpty() ? 0 : st.focus.GetCounter(); + bool outOfReach = false; // Fight::campHold: nothing in this bot's reach, it waits at its post if (fight->campReach > 0.f) { std::vector atCamp(view.size(), false), seen(view.size(), false); @@ -364,6 +414,8 @@ void ApplyFightScript(Plan& plan, std::unordered_map& order if (anyAtCamp || anySeen) for (size_t i = 0; i < view.size(); ++i) view[i].eligible = anyAtCamp ? atCamp[i] : seen[i]; + else if (fight->campHold) + outOfReach = true; } // The raid's focus is this bot's previous pick while it can take it; a bot that cannot keeps its own pick until that one dies. uint64_t previous = raidFocus; @@ -378,6 +430,46 @@ void ApplyFightScript(Plan& plan, std::unordered_map& order if (auto own = g_ownPick.find(self); own != g_ownPick.end()) previous = own->second; } + // Fight::campHold, nothing in reach: a bot that would wait for a far first-rank enemy (a Soldier at its alcove) takes an add of a + // later rank instead when there is one (a tanked Abomination), and walks to its reach of it. naxx_kelthuzad kt69k (1124): the + // Soldier squad (Mcmagea-e, Mclocka-c) waited 13-23 s at a time "raid:threat_hold / no target" while the tanks fought 21-41 y out; + // Mcmagea cast for 11 s of the 155 s pull (76/s). + if (outOfReach) + { + bool laterRank = false; + for (Script::Enemy const& e : view) + if (e.eligible && Script::RankOf(*fight, e.entry) > 0) + laterRank = true; + if (laterRank) + for (Script::Enemy& e : view) + if (Script::RankOf(*fight, e.entry) == 0) + e.eligible = false; + } + // Fight::squadPerEnemy: the squad splits over the first rank, nearest the camp first, so the bots of the squad do not all shoot one + // Soldier (see RaidFightScript.h, Kel'Thuzad). The share is the raid's, the same list for every bot (alive, within campReach of the + // camp, by distance to it, then guid); a bot that cannot take its own share (out of its reach or sight) picks as before. + if (inSquad && fight->squadPerEnemy > 0) + { + std::vector> firsts; + for (size_t i = 0; i < mine.size(); ++i) + if (mine[i]->IsAlive() && Script::RankOf(*fight, view[i].entry) == 0) + { + float const d = fight->campReach > 0.f ? Dist2D(mine[i]->GetPositionX(), mine[i]->GetPositionY(), fight->campX, fight->campY) + : m.p->GetExactDist2d(mine[i]); + if (fight->campReach <= 0.f || d <= fight->campReach) + firsts.emplace_back(d, i); + } + std::sort(firsts.begin(), firsts.end(), [&](auto const& a, auto const& b) + { return a.first != b.first ? a.first < b.first : view[a.second].guid < view[b.second].guid; }); + if (firsts.size() > 1) + { + size_t const mineAt = firsts[(squadIndex / fight->squadPerEnemy) % firsts.size()].second; + if (view[mineAt].eligible) + for (auto const& f : firsts) + if (f.second != mineAt) + view[f.second].eligible = false; + } + } uint64_t const pick = Script::PickFocus(*fight, view.data(), view.size(), ownerMark.IsEmpty() ? 0 : ownerMark.GetCounter(), previous); if (fight->schoolAware) { @@ -403,6 +495,23 @@ void ApplyFightScript(Plan& plan, std::unordered_map& order } continue; // nothing the script can name for this bot: the generic rules keep it } + // Fight::campHold: the pick is out of this bot's reach. It holds on it at its post instead of walking out after it (see + // RaidFightScript.h, Kel'Thuzad), and its pick does not count for the raid's focus. Only for a first-rank pick (a Soldier still on + // its way in from an alcove): an add a tank holds is in the room, and the bot goes to its reach of it as usual. kt69j (1124): held + // for every pick, raid:threat_hold was 931 of 2,976 rule samples of the DPS bots (about 28 s a caster in a 146 s pull), while the + // tanks fought Abominations 41-45 y from the camp. + bool firstRankPick = false; + for (Script::Enemy const& e : view) + if (e.guid == pick && Script::RankOf(*fight, e.entry) == 0) + firstRankPick = true; + if (outOfReach && firstRankPick) + { + o.script_owns = true; + o.script_focus = focus; + o.fallback_target = focus; + o.hold_target = focus; + continue; + } o.script_owns = true; o.script_focus = focus; diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidFightScript.h b/src/modules/PlayerbotV2/Bot/Raid/RaidFightScript.h index d9498c6e12..e1e6cdc8d6 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidFightScript.h +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidFightScript.h @@ -34,6 +34,15 @@ struct Fight uint32_t freeAura = 0; // a DPS bot carrying this aura is left to the generic rules (Delusions of Jin'do: only it sees the Shades) float campX = 0.f, campY = 0.f; // campReach > 0: the raid fights from one camp (Nefarian); an enemy counts for a DPS bot only within campReach float campReach = 0.f; // of it and in the bot's line of sight, while any enemy of the fight is (else every enemy counts again) + float meleeFirstReach = 0.f; // > 0: the first rank counts for a melee DPS bot only within this many yards of it (Kel'Thuzad's Soldiers) + bool campHold = false; // campReach > 0: a DPS bot with only a first-rank enemy, out of its sight and spell reach, holds at its post + bool heldOnly = false; // the kill order after its first rank counts only while a tank holds it (the boss excepted) + uint8_t firstRankSquad = 0; // > 0: only this many ranged DPS bots (the first by guid) take the first rank; the rest skip it + uint32_t meleeOff = 0; // a creature entry no melee DPS bot attacks (off limits for it, the generic rules included) + uint32_t untanked = 0; // heldOnly: this entry counts though no tank holds it (nobody tanks it) + float meleeCampReach = 0.f; // campReach > 0: an enemy farther than this from the camp is off limits for a melee DPS bot (Kel'Thuzad) + uint8_t squadPerEnemy = 0; // firstRankSquad: > 0, the squad splits over the first rank, this many bots on each enemy (Kel'Thuzad) + bool meleeHeldOnly = false; // a later-rank enemy no tank holds is off limits for a melee DPS bot, its own rules too (Kel'Thuzad) }; // Lucifron (MC 409): the two Flamewaker Protectors first, then Lucifron. The start wait is the raid's one boss opening wait (Playerbot::kRaidBossOpenWaitMs, 8 s: the main tank takes a while to run in); there is no threat cap after @@ -83,6 +92,45 @@ struct Fight // with no script the Priority rows only steered a DPS bot with no target, so the bots already on Fankriss or a Hatchling stayed there // ("on the focus 0", 13-21 of 24 on one other enemy); the Spawns lived 12-25 s, each at 93-95% 6-8 s in, and from 215 s the enraged // ones killed 39 of the 40. Fankriss himself has no enrage: his tank keeps him while the adds die. +// Kel'Thuzad (Naxxramas 533): phase 1 is Kel'Thuzad immune on his dais sending adds from the seven alcoves at random raiders +// (classic_boss_kelthuzad.cpp): a Soldier of the Frozen Wastes (16427, 2,000 health) every 3.75 s down to 2 s, which blows up on arrival +// (Dark Blast 28457, 1,750 to the whole room), Unstoppable Abominations (16428, 90,000, Mortal Wound on the tank) and Soul Weavers +// (16429, 70,000, Wail of Souls in front of them). The raid fights from one camp in the middle of the room (RaidEncounterData_NAXX.cpp), +// the tanks hold the Abominations and Weavers on an arc round it. The order: a Soldier that has come in to the camp first (one dies to a +// single volley), then an Abomination a tank holds, then a Weaver, then Kel'Thuzad himself (phases 2 and 3; the Guardians of Icecrown are +// shackled and not on the list). No start wait: the first Soldier is on its way at the pull. A melee DPS bot leaves a Soldier further than +// 8 y from it to the ranged (meleeFirstReach): sent at a random raider it can be anywhere in the camp, and the melee walked from the tanks +// to it and back. naxx_kelthuzad kt67a / kt67b (1124), no script: each DPS bot took its own pick by the generic rows, the raid stood spread +// over the whole room between the alcove keep-outs and the Weavers' cones (768-792 of 1,028-1,132 forced moves a run were that ping-pong), +// and 16 and 25 raiders died to Wail of Souls. +// campReach is 36 y, the whole floor inside the alcove keep-outs: a bot at the camp (7 y round it) then takes a Soldier as soon as it is in +// its 30 y spell reach. At 28 y (kt69a, 1124) a Soldier counted only 2-3 s before it reached the tanks' arc and blew up there: 20 of the 42 +// dead were Dark Blast. +// campHold: a DPS bot with no enemy in its 30 y sight and spell reach waits at its post. Without it every enemy counted again, the pick was a +// Soldier just sent from an alcove 35-42 y off, and the ranged walked out after it (kt69b, 1124: "[hunter_chase] ... dist 40-42", a +// "role position" walk back every 1-2 s, 364 "leave hazard" at the keep-out rims); the raid drifted north, and 23 raiders 3-30 y from a +// Soul Weaver at 3702,-5079 (31 y from the camp) died to its Wail of Souls in 8 s. +// firstRankSquad: eight ranged DPS bots shoot the Soldiers, the others stay on the held Abomination. kt69i (1124), every DPS bot on the +// squadPerEnemy: the squad splits two to a Soldier, nearest the camp first. The whole squad on one Soldier (2,000 health) put most of its +// casts into one already dead: kt73a (1125), 7-13 bots on the top target in the samples from 218 s, loose mobs 14 -> 24 in 40 s, and +// Soldiers reaching the camp together killed 8 with Dark Blast at 258-261 s, 27 of the 43 dead in all. +// first rank: 45 of the 63 focus changes went to a Soldier, 232 of 290 script attacks were on one (each dies to the first hits and +// a new one comes every 2-3.75 s, so the casters spent the pull starting casts on the next), the focus was an Abomination 4 times, +// raid damage was 1,528/s, and the Abominations killed all four tanks with Mortal Wound. +// meleeOff: no melee DPS bot attacks a Soul Weaver (it has no melee of its own; the ranged and its tank kill it), and the encounter keeps them +// 8 y from one (RaidEncounterData_NAXX.cpp). A Weaver whose victim is out of its melee reach turns to the nearest raider in it +// (classic_soul_weaver_ai), so the melee beside it took it from its tank: kt69p (1124), a Weaver was on a tank in 4 of 94 [raid_fight] +// samples and on a raider in 73, most often a warrior or rogue (Mcwarra, Mcwarrb, Mcwarrc, Mcrogued, Mcreta), and 29 died to Wail of Souls. +// AzerothCore-style variant (script17ac): the Weavers are not tanked (RaidEncounterData_NAXX.cpp). The order is Soldier, Weaver, Abomination, +// Kel'Thuzad: the eight squad bots take the Soldiers, the other ranged the Weaver nearest the camp's 36 y, the melee (meleeOff) the held +// Abomination; untanked lets a Weaver count under heldOnly. +// heldOnly: an Abomination or Weaver counts only while a tank holds it. A Soul Weaver turns on whoever is nearest in its melee reach when its +// victim is not (classic_soul_weaver_ai), so DPS bots that ran out to a loose one at the alcove rim could hold it there, facing the camp +// (kt69c, 1124: 28 dead to Wail of Souls from a Weaver at 3697-3701,-5079, 31 y from the camp; the camp reach of 36 y counts it). +// meleeHeldOnly: heldOnly steers the script's focus only; a melee DPS bot's own rules still went for a loose Abomination walking in, met it +// 13-23 y from the camp (the row's tanks fetch one only within 22 y of it, and 15 y of themselves), took it off the raider it was sent at +// and died to its Mortal Wound: naxx_kelthuzad kt80a-c (1125), 11 of the 21 deaths to an Abomination before 200 s were melee DPS bots on +// a fresh one (97-100%) sent at another raider, no tank on it. inline constexpr Fight kFights[] = { { 409, 12118, { 12119, 12118, 0, 0 }, kRaidBossOpenWaitMs, "Lucifron" }, { 409, 12057, { 12057, 0, 0, 0 }, kRaidBossOpenWaitMs, "Garr" }, @@ -106,6 +154,8 @@ inline constexpr Fight kFights[] = { { 309, 15084, { 15084, 0, 0, 0 }, kRaidBossOpenWaitMs, "Renataki" }, { 309, 15085, { 15085, 0, 0, 0 }, kRaidBossOpenWaitMs, "Wushoolay" }, { 531, 15510, { 15630, 15962, 15510, 0 }, kRaidBossOpenWaitMs, "Fankriss the Unyielding" }, + { 533, 15990, { 16427, 16429, 16428, 15990, 0 }, 0, "Kel'Thuzad", false, 0, true, 0, false, 0, 3716.0f, -5106.0f, 36.0f, 8.0f, true, true, 8, 16429, + 16429, 26.0f, 2, true }, }; // The fight an engaged enemy belongs to on this map (nullptr: none). diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidMechanics_Naxx.cpp b/src/modules/PlayerbotV2/Bot/Raid/RaidMechanics_Naxx.cpp index b0716e417d..fc393d306d 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidMechanics_Naxx.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidMechanics_Naxx.cpp @@ -183,9 +183,18 @@ std::vector HeiganDoors(Unit* heigan) return doors; } -// True when (x, y) lies on his side of both doors, kDoorClear inside them. +// His leash (classic_instance_naxxramas.cpp HandleEvadeOutOfHome): he evades the moment he stands east of x 2825 or south of y -3737, and +// he walks to whoever he goes for. naxx_heigan r3af55-1: a druid healing from 2830.8,-3681.7 drew him there and he evaded at 32 s, 97%. +// So a spot off the field stays inside those lines by a melee reach and a margin, wherever the doors stand. +constexpr float kHeiganLeashX = 2825.0f; +constexpr float kHeiganLeashY = -3737.0f; +constexpr float kHeiganLeashClear = 6.0f; + +// True when (x, y) lies on his side of both doors, kDoorClear inside them, and inside his leash. bool InHeiganRoom(std::vector const& doors, float x, float y) { + if (x > kHeiganLeashX - kHeiganLeashClear || y < kHeiganLeashY + kHeiganLeashClear) + return false; for (DoorPlane const& d : doors) if (((x - d.x) * d.nx + (y - d.y) * d.ny) * d.side < kDoorClear) return false; @@ -1036,6 +1045,12 @@ struct RazOpenSpot bool goingIn = false; // the priest was last sent to the cast spot (for the log) }; std::unordered_map g_razOpenSpot; // instance -> the opener's spots, kept while the priest and target stay +// Cast spots the spell refused for line of sight with the priest standing on them: no search picks a spot this close to one again. +// naxx_razuvious rbaf56-1: the spot (2735.4,-3111.5) passed the search's sight test (2 y above the ground, then the understudy's own height +// again on top) and the cast check (the priest's eyes to the understudy, every model counted), and Mind Control failed LINE_OF_SIGHT on +// each of seven goes in 2.5 min; the fallback pull at 170 s sent the main tank in on an understudy. +constexpr float kRazBlockedNear = 2.0f; +std::unordered_map>> g_razCastBlocked; // instance -> refused cast spots // The nearest his walk comes to (x, y): the legs of his waypoint path, closed into a loop, and where he stands (he is off the path while // he walks back to it). With no path, where he stands. @@ -1374,7 +1389,8 @@ void NaxxPrePullRazuvious(Plan& plan, std::unordered_map& o float const run = std::max(priest->GetSpeed(MOVE_RUN), 1.0f); struct Candidate { Creature* us; float sx, sy, sz, wx, wy, score, window, need; bool fits; }; std::vector candidates; - int inReach = 0, noGround = 0, noWait = 0, walkFailed = 0; + int inReach = 0, noGround = 0, noWait = 0, walkFailed = 0, refused = 0; + std::vector> const& blocked = g_razCastBlocked[instance]; for (Creature* c : understudies) for (int k = 0; k < 24; ++k) { @@ -1389,11 +1405,20 @@ void NaxxPrePullRazuvious(Plan& plan, std::unordered_map& o continue; } float sz = 0.0f; - if (!RazFloor(priest, sx, sy, c->GetPositionZ(), sz) || !c->IsWithinLOS(sx, sy, sz + 2.0f)) + // The sight test the spell makes (Spell::CheckCast, Spell::IsWithinLOS with the target as the source): from the understudy's + // hit sphere to the priest standing on the spot at the understudy's height above its feet, M2 models ignored. + if (!RazFloor(priest, sx, sy, c->GetPositionZ(), sz) || + !c->IsWithinLOS(sx, sy, sz, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2)) { ++noGround; continue; } + if (std::any_of(blocked.begin(), blocked.end(), + [&](std::pair const& b) { return Dist2D(b.first, b.second, sx, sy) < kRazBlockedNear; })) + { + ++refused; + continue; + } int j = 1; for (; j <= kRazWaitSteps; ++j) { @@ -1459,8 +1484,8 @@ void NaxxPrePullRazuvious(Plan& plan, std::unordered_map& o spot.failedMs = std::max(now, 1u); if (g_razOpenLogged.insert(instance).second) TC_LOG_WARN("playerbot.v2.raid", "[raid_razuvious] {} finds no Mind Control spot with a wait spot out of his sight ({:.0f} y) " - "and a clear walk: {} spots inside an understudy's reach, {} without ground or sight, {} with no wait spot, " - "{} walks refused", priest->GetName(), sight, inReach, noGround, noWait, walkFailed); + "and a clear walk: {} spots inside an understudy's reach, {} without ground or sight, {} refused the cast before, " + "{} with no wait spot, {} walks refused", priest->GetName(), sight, inReach, noGround, refused, noWait, walkFailed); return; } us = best->us; @@ -1530,7 +1555,21 @@ void NaxxPrePullRazuvious(Plan& plan, std::unordered_map& o "{:.0f} y needed ({:.0f} y to walk, a {:.1f} s cast), him at ({:.1f},{:.1f}) walking {:.1f} y/s", priest->GetName(), closest, seconds, sight, left, castS, raz->GetPositionX(), raz->GetPositionY(), speed); spot.goingIn = true; - if (left <= 1.5f && priest->GetExactDist(us) <= mcReach(us) - 0.5f && priest->IsWithinLOSInMap(us) && !priest->isMoving()) + if (left <= 1.5f && priest->GetExactDist(us) <= mcReach(us) - 0.5f && !priest->isMoving() && + !us->IsWithinLOSInMap(priest, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2)) + { + // On the spot and the spell's own sight test fails: the spot is dropped for good and the next pass looks for another. + g_razCastBlocked[instance].emplace_back(spot.sx, spot.sy); + TC_LOG_INFO("playerbot.v2.raid", "[raid_razuvious] {} stands on its cast spot ({:.1f},{:.1f},{:.1f}) {:.1f} y from the understudy and " + "the understudy cannot see it as Mind Control checks it: the spot is dropped, another is looked for", + priest->GetName(), priest->GetPositionX(), priest->GetPositionY(), priest->GetPositionZ(), priest->GetExactDist(us)); + float const wx = spot.wx, wy = spot.wy, wz = spot.wz; + spot = RazOpenSpot{}; + SetMove(o, wx, wy, wz, "razuvious: wait out of his sight"); + o.prepull_wait = true; + return; + } + if (left <= 1.5f && priest->GetExactDist(us) <= mcReach(us) - 0.5f && Ready(priest, rank, us, true) && !priest->isMoving()) { o.move = false; o.cast_kind = RaidOrder::CastKind::CrowdControl; @@ -4385,6 +4424,8 @@ void NaxxPrePull(Plan& plan, std::unordered_map& orders, st g_razOpener.clear(); if (g_razOpenLogged.size() > 64) g_razOpenLogged.clear(); + if (g_razCastBlocked.size() > 64) + g_razCastBlocked.clear(); if (g_gothDraw.size() > 64) g_gothDraw.clear(); if (g_gothSplitSince.size() > 64) diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidOrder.h b/src/modules/PlayerbotV2/Bot/Raid/RaidOrder.h index e86632e877..30d537cba9 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidOrder.h +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidOrder.h @@ -57,6 +57,9 @@ struct RaidOrder // (non-tanks), crowd-controlled adds, Majordomo's reflecting adds, the // swap enemy for a tank that carries its debuff. std::vector forbidden_targets; + // A tank of a fixed tank row while the row holds: no enemy the map's rules leave untanked (RaidRules::noTank) is its own, whatever + // the forbidden list of the last pass says (the tank planner reads this before the brain has seen an add sent this tick). + bool no_tank_off = false; // Where a DPS bot goes when its victim is forbidden (empty = stop). ObjectGuid fallback_target; // Where an off-tank goes when the enemy it holds becomes forbidden (a banished add): the raid's main target, instead of diff --git a/src/modules/PlayerbotV2/Bot/SpellFamily.h b/src/modules/PlayerbotV2/Bot/SpellFamily.h index b1266379e3..5babb03a04 100644 --- a/src/modules/PlayerbotV2/Bot/SpellFamily.h +++ b/src/modules/PlayerbotV2/Bot/SpellFamily.h @@ -8,6 +8,7 @@ // its ranks ascend by base level. A real chain wins where there is one. #pragma once +#include "DB2Structure.h" #include "Define.h" #include "Log.h" #include "SpellInfo.h" @@ -40,6 +41,20 @@ inline std::string KeyOf(SpellInfo const* si, LocaleConstant loc) std::to_string(uint32(e0.ApplyAuraName)) + '|' + (si->IsPassive() ? 'p' : 'a'); } +// A spell the class can never learn: it has skill line abilities and every one of them is NeverLearned. The Forever client +// carries no-rank copies of some class spells next to their real ranks (Holy Light 19968/19980/19981/19982 with 1 healing, +// Flash of Light 19993): same name, family and first effect, so without this they joined the family as its "highest" rank. +inline bool IsNeverLearned(uint32 spell_id) +{ + SkillLineAbilityMapBounds const bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spell_id); + if (bounds.first == bounds.second) + return false; + for (auto it = bounds.first; it != bounds.second; ++it) + if (it->second->GetAcquireMethod() != SkillLineAbilityAcquireMethod::NeverLearned) + return false; + return true; +} + inline Index const& GetIndex() { static Index idx; @@ -69,6 +84,19 @@ inline Index const& GetIndex() uint32 const la = sa ? sa->BaseLevel : 0, lb = sb ? sb->BaseLevel : 0; return la != lb ? la < lb : a < b; }); + // Never-learnable copies leave a family that has a learnable rank (they keep pointing at it through family_of, so a copy + // a bot already has in its book still resolves to the real ranks). The Forever client's 1-point Holy Light 19981 sorted + // after rank 2 639 (both base level 6) and paladin bots healed for 1 (VempirE, Dumpins, y_dem, Discord 2026-11-24). + uint32 dropped = 0; + for (auto& f : idx.families) + { + if (f.size() < 2 || std::all_of(f.begin(), f.end(), IsNeverLearned)) + continue; + size_t const before = f.size(); + std::erase_if(f, IsNeverLearned); + dropped += uint32(before - f.size()); + } + TC_LOG_INFO("playerbot.v2", "[spell_data] {} never-learnable spell copies left out of their rank families", dropped); // [spell_data] (client moves 70205 -> 70291): which of the curses and tank / raid debuff spells the loaded DB2 data carries and how // many ranks each family has, once at the first lookup. Curse of the Elements 1490 and Curse of Shadow 17862 were missing in 70205. for (uint32 const id : { 704u, 702u, 980u, 1490u, 17862u, 1714u, 8647u, 7386u, 20271u, 1130u }) @@ -85,6 +113,8 @@ inline Index const& GetIndex() } // namespace detail +using detail::IsNeverLearned; + // Ranks of the spell, lowest first: the spell data's chain ranks together with every spell of the same family. The two overlap for // most spells and differ for some: Mark of the Wild 1126 has a chain that holds only part of its ranks, and a bot that cast a rank // outside the chain never saw the aura as "its" buff (MC Garr 2026-10-10: the druids recast it for ever, the tracked list stayed empty). diff --git a/src/modules/PlayerbotV2/Bot/States/MaintainHelpers.h b/src/modules/PlayerbotV2/Bot/States/MaintainHelpers.h index 3da4db3b94..62dfc930ff 100644 --- a/src/modules/PlayerbotV2/Bot/States/MaintainHelpers.h +++ b/src/modules/PlayerbotV2/Bot/States/MaintainHelpers.h @@ -37,6 +37,12 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, BotIntentEmitter& emit, DungeonAdvice const& advice); +// Up for air, on the server's breath timer (Swim::BreathGoesUp), in every state: idle:surface_to_breathe, the dungeon preempt and the +// fight. BreathDue updates the bot's latch and logs [breath] when it goes up and when its breath is full again; SurfaceForAir swims it +// straight up and holds it at the surface until then (true = the tick is spent). Definitions in State_Idle.cpp. +bool BreathDue(BotSnapshotView const& s, BotAI& ai); +bool SurfaceForAir(BotSnapshotView const& s, BotAI& ai, BotIntentEmitter& emit, char const* rule); + // Off-mesh-aware single step toward a dungeon target (the tank), GUID-keyed with // float out-params. Resolves the bot from self_guid, then returns the next // navmesh waypoint (capped at maxStep) toward (tx,ty,tz); sets is_offmesh when diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/AmbientRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/AmbientRules.cpp index 9b6f8d312f..3ec171193a 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/AmbientRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/AmbientRules.cpp @@ -19,6 +19,7 @@ #include "Bot/BotSnapshotView.h" #include "Bot/BotIntentEmitter.h" #include "Bot/BotIntent.h" +#include "Bot/BotTextMgr.h" #include "DB2Stores.h" #include "World.h" #include "Util/ConfigReader.h" @@ -31,9 +32,15 @@ #include "Bot/TownErrand.h" #include "Bot/TownErrandConfig.h" #include "Bot/ClassicUpkeep.h" +#include "Bot/RecipeDifficulty.h" #include "Combat/Apl/ApClassicHeal.h" // idle:kind_heal: the class heal and its rank #include "ClassicSpec.h" // Classic::IsSingleSpecClass #include "SharedDefines.h" +#include "Player.h" // EQUIPMENT_SLOT_MAINHAND for the station-tool swap +#include "GameObjectData.h" +#include "ObjectMgr.h" +#include "SpellInfo.h" +#include "SpellMgr.h" #include "Fleet/GateDuels.h" #include "Fleet/Gathering.h" #include "Fleet/StrangerBoard.h" @@ -920,9 +927,10 @@ bool InnRestFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, InnLog(s, "inn is full, goes on errands", bx, by); return false; } - // Stand a few yards from the innkeeper, on the side the bot comes from, each bot in its own slot of a fan so they stand side by side. + // Stand a few yards from the innkeeper on its customer side (the spawn's facing — the innkeeper looks at the + // room, never into the counter or a wall), each bot in its own slot of a fan so they stand side by side. float tx, ty; - TE::StandPoint(inn->x, inn->y, bx, by, kInnStandYards + float(slot / 5u) * 1.5f, slot, tx, ty); + TE::StandPoint(inn->x, inn->y, bx, by, kInnStandYards + float(slot / 5u) * 1.5f, slot, tx, ty, inn->orientation); // The stand point is a straight line from the innkeeper and can sit behind a wall; the inn is the goal, so a bot that is within a // few yards of the innkeeper, or that cannot get closer than a room's width, rests where it is. float const to_inn = std::hypot(bx - inn->x, by - inn->y); @@ -994,10 +1002,12 @@ bool MailboxFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, // ---------- idle:town_errand ---------- // A capital's residents go about their business (Bot/TownErrand.h): each runs to a real place anywhere in the city (the auction house, -// the bank, its class trainer, the inn, a mailbox, the flight master, a vendor, now and then the city gate), stops there a few seconds -// facing the NPC, and runs straight on to the next place. The walk is one pathed move to the place, so the bot runs a smooth line -// through the streets and past the player, instead of the 25 y random wander hops with a stop and a turn at each. Every place holds a -// few bots at once (SpotCap); a bot finding one full picks another. +// the bank, its class trainer, the inn, a mailbox, the flight master, a vendor, a craft station, now and then the city gate), stops +// there a while — a few seconds at a trainer, half a minute at the bank or the auction house, a minute working at an anvil — and +// runs straight on to the next place. The walk is one pathed move to the place, so the bot runs a smooth line through the streets +// and past the player, instead of the 25 y random wander hops with a stop and a turn at each. Every place holds a few bots at once +// (SpotCap); a bot finding one full picks another. The Fixture.* counts keep a guaranteed share of bots at the places a living +// city never leaves empty — always someone at the bank, never the same someone for long. constexpr uint32 kErrandWalkTimeoutMs = 120000u; constexpr uint32 kErrandStaleMs = 180000u; constexpr uint64 kGateKeyBase = 0xE0000000ull; @@ -1019,6 +1029,20 @@ static uint32 PlaceCap(TE::Kind k) return c.spot_cap; } +// The bot's own trade skill makes the station it can really work at the more convincing visit (and lets the linger +// cast a real recipe): a smith at the anvil, a cook at the fire, a tailor at the loom or moonwell. +static bool CraftKindMatch(TE::Kind k, BotSnapshotView const& s) +{ + switch (k) + { + case TE::Kind::Forge: return s.has_skill(164) || s.has_skill(202) || s.has_skill(186); // blacksmithing, engineering, mining + case TE::Kind::Cookfire: return s.has_skill(185); // cooking + case TE::Kind::Loom: return s.has_skill(197); // tailoring needs no station — the loom is a shop, not a requirement + case TE::Kind::Moonwell: return s.skill_value(197) >= 250; // moonwell work starts at Mooncloth (Tailoring 250) + default: return false; + } +} + // The places of the city within ErrandRadius of (bx, by) that this bot has a reason to go to. static void TownDests(BotSnapshotView const& s, float bx, float by, float bz, std::vector& out) { @@ -1042,13 +1066,23 @@ static void TownDests(BotSnapshotView const& s, float bx, float by, float bz, st else if ((f & UNIT_NPC_FLAG_TRAINER) && n.trainer_class != 0 && n.trainer_class == s.cls()) k = TE::Kind::Trainer; else if (f & (UNIT_NPC_FLAG_VENDOR_MASK | UNIT_NPC_FLAG_REPAIR)) { k = TE::Kind::Vendor; if (need_vendor) boost = 5.0f; } if (k == TE::Kind::None) return; - out.push_back({ k, n.spawn_id, n.entry, n.x, n.y, n.z, TE::BaseWeight(k) * boost }); + out.push_back({ k, n.spawn_id, n.entry, n.x, n.y, n.z, TE::BaseWeight(k) * boost, 0u, n.orientation }); }); ::Playerbot::V2::Travel::TownNpcIndex::Instance().ForEachMailboxNear(s.map_id(), bx, by, c.radius, [&](::Playerbot::V2::Travel::TownNpc const& n) { if (std::fabs(n.z - bz) > kLayerYards) return; out.push_back({ TE::Kind::Mailbox, n.spawn_id, 0u, n.x, n.y, n.z, TE::BaseWeight(TE::Kind::Mailbox) }); }); + // The craft stations (anvil, forge, cooking fire, loom, moonwell) the town's gameobjects carry: a bot stops + // there to work like a player does — but only a bot with the trade for it, so the smith at the anvil is a + // real smith (the tool in hand, a recipe it can really cast), never a priest miming. + ::Playerbot::V2::Travel::TownNpcIndex::Instance().ForEachFocusNear(s.map_id(), bx, by, c.radius, [&](::Playerbot::V2::Travel::TownNpc const& n) + { + if (!n.focus_kind || std::fabs(n.z - bz) > kLayerYards) return; + TE::Kind const k = TE::Kind(n.focus_kind); + if (!CraftKindMatch(k, s)) return; + out.push_back({ k, n.spawn_id, 0u, n.x, n.y, n.z, TE::BaseWeight(k) * 2.5f, n.focus_type }); + }); if (c.exits) { V2::GateDuels::GateSpot gate; @@ -1058,12 +1092,34 @@ static void TownDests(BotSnapshotView const& s, float bx, float by, float bz, st } } -static void EndErrand(BotSnapshotView const& s, TE::State& st, bool done) +static uint32 StationToolEntry(TE::Kind kind, BotSnapshotView const& s); // defined below with the recipe table + +static void EndErrand(BotSnapshotView const& s, BotIntentEmitter& emit, TE::State& st, bool done) { + if (st.work_emote) + emit.perform_emote(EMOTE_STATE_NONE); // a looped work emote stops when the bot moves off + if (st.tool_in_hand) + { + // The swap back: the displaced weapon sits in the tool's bag slot. An empty slot means the + // mainhand was empty when the tool went in — nothing to restore. The slot holding the tool + // itself means a gear rule already put the weapon back on — leave it alone. + for (auto const& it : s.raw().inventory.bag_items) + if (it.bag == st.tool_bag && it.slot == st.tool_slot && it.entry != StationToolEntry(st.kind, s)) + { + emit.equip_item(st.tool_bag, st.tool_slot, EQUIPMENT_SLOT_MAINHAND); + break; + } + emit.set_sheath(SHEATH_STATE_UNARMED); // the show drew the weapons; hands away again at idle + } if (st.place) TE::Spots::Get().Release(st.place, s.bot_id()); if (st.key) st.recent.add(st.key); if (done) ++st.errands; + bool const had_show = st.work_emote; st.Clear(); + // A visit that ran the work show ends on a beat — the smith wipes his hands before + // he walks. Without it the next pick's move_to lands the same tick the emote drops + // and the client slides him out of a mid-swing pose. + if (had_show) st.pause_until_ms = s.published_at_ms() + 1500u; } // A bot placed in the town by the spawner (TownPct) is in its profession mode for 45-90 minutes and lives there. Any other bot in a @@ -1079,6 +1135,36 @@ static bool TownTime(BotSnapshotView const& s, BotAI& ai, uint32 now_ms) constexpr uint32 kLeaveMs = 10u * 60u * 1000u; // out at the gate: this long with no errands, grind_roam leads the bot off +// Claim a stand slot at `d` and open the errand there. False when the place filled in the meantime. +static bool TakeErrand(BotSnapshotView const& s, TE::State& st, TE::Dest const& d, bool leaving, uint32 now_ms) +{ + float bx, by, bz; + s.position(bx, by, bz); + uint64 const place = TE::Spots::PlaceKey(s.map_id(), d.x, d.y); + uint32 slot = 0; + if (!TE::Spots::Get().Claim(place, s.bot_id(), now_ms, kSpotHoldMs, PlaceCap(d.kind), &slot)) + return false; + st.Clear(); + if (d.kind == TE::Kind::Vendor) st.want_vendor = false; // the sell the last visit couldn't do + st.kind = d.kind; st.key = d.key; st.place = place; st.entry = d.entry; st.slot = slot; + st.focus_type = d.focus_type; + st.leaving = leaving; + st.nx = d.x; st.ny = d.y; st.nz = d.z; + float ring = 3.5f + float(slot / 5u) * 1.5f; + if (d.kind == TE::Kind::Mailbox) ring = 2.5f; + else if (d.kind == TE::Kind::Exit) ring = 3.0f + float(slot % 6u) * 1.5f; + else if (TE::IsCraftKind(d.kind)) ring = 2.8f + float(slot % 3u) * 0.7f; // right at the anvil: two smiths share the fire + TE::StandPoint(d.x, d.y, bx, by, ring, slot, st.tx, st.ty, d.orientation); + st.tz = d.z; + st.phase = 1; + st.phase_start_ms = now_ms; + // One bot in 16 logs its errands, so a soak shows where residents go without a line per errand of every bot. + if (s.bot_id() % 16u == 0u) + TC_LOG_INFO("playerbot.v2", "[town] {} -> {} ({:.0f},{:.0f}) {:.0f} y slot {} (zone {})", + s.name(), TE::KindName(d.kind), d.x, d.y, std::hypot(d.x - bx, d.y - by), slot, s.zone_id()); + return true; +} + // Choose the next place and claim a stand slot there. False when the city offers nothing. static bool PickErrand(BotSnapshotView const& s, BotAI& ai, TE::State& st, uint32 now_ms) { @@ -1092,6 +1178,11 @@ static bool PickErrand(BotSnapshotView const& s, BotAI& ai, TE::State& st, uint3 && std::any_of(dests.begin(), dests.end(), [](TE::Dest const& d) { return d.kind == TE::Kind::Exit; }); if (leaving) std::erase_if(dests, [](TE::Dest const& d) { return d.kind != TE::Kind::Exit; }); + // A kit visit that couldn't start for full bags sent the bot to sell first: the next + // errand is a vendor when one's in reach (cleared when the vendor errand is taken). + if (!leaving && st.want_vendor + && std::any_of(dests.begin(), dests.end(), [](TE::Dest const& d) { return d.kind == TE::Kind::Vendor; })) + std::erase_if(dests, [](TE::Dest const& d) { return d.kind != TE::Kind::Vendor; }); if (dests.empty()) return false; uint64 const bot = s.bot_id(); uint32 const map = s.map_id(); @@ -1102,30 +1193,323 @@ static bool PickErrand(BotSnapshotView const& s, BotAI& ai, TE::State& st, uint3 if (!leaving && ai.hearth_rebind_due(s.zone_id()) && std::any_of(dests.begin(), dests.end(), [&](TE::Dest const& d) { return d.kind == TE::Kind::Inn && !full(d); })) std::erase_if(dests, [](TE::Dest const& d) { return d.kind != TE::Kind::Inn; }); + // Fixture places (Playerbot.World.Town.Fixture.*): a bank, auction house or craft station below its guaranteed share of bots + // draws the next errand before the usual weighted pick. The claim still decides: once `want` bots hold the place (bots on + // their way there count), the steering stops, so the fill cannot over-shoot and the crowd at a place keeps rotating. + if (!leaving) + { + std::vector under; + for (TE::Dest const& d : dests) + { + uint32 want = TE::FixtureTarget(TE::Cfg(), d.kind); + if (!want) continue; + uint64 const place = TE::Spots::PlaceKey(map, d.x, d.y); + if (TE::Spots::Get().Count(place, now_ms) >= std::min(want, PlaceCap(d.kind))) continue; + if (full(d)) continue; + under.push_back(d); + } + if (!under.empty()) + { + int const k = TE::Pick(under, bx, by, TE::Cfg().radius, st.recent, float(ai.rng().unit()), + [](TE::Dest const&) { return false; }); + if (k >= 0 && TakeErrand(s, st, under[size_t(k)], leaving, now_ms)) + return true; + } + } int const k = TE::Pick(dests, bx, by, TE::Cfg().radius, leaving ? TE::Recent{} : st.recent, float(ai.rng().unit()), full); if (k < 0) return false; - TE::Dest const& d = dests[size_t(k)]; - uint64 const place = TE::Spots::PlaceKey(map, d.x, d.y); - uint32 slot = 0; - if (!TE::Spots::Get().Claim(place, bot, now_ms, kSpotHoldMs, PlaceCap(d.kind), &slot)) - return false; - st.Clear(); - st.kind = d.kind; st.key = d.key; st.place = place; st.entry = d.entry; st.slot = slot; - st.leaving = leaving; - st.nx = d.x; st.ny = d.y; st.nz = d.z; - float const ring = d.kind == TE::Kind::Mailbox ? 2.5f : d.kind == TE::Kind::Exit ? 3.0f + float(slot % 6u) * 1.5f : 3.5f + float(slot / 5u) * 1.5f; - TE::StandPoint(d.x, d.y, bx, by, ring, slot, st.tx, st.ty); - st.tz = d.z; - st.phase = 1; - st.phase_start_ms = now_ms; - // One bot in 16 logs its errands, so a soak shows where residents go without a line per errand of every bot. - if (s.bot_id() % 16u == 0u) - TC_LOG_INFO("playerbot.v2", "[town] {} -> {} ({:.0f},{:.0f}) {:.0f} y slot {} (zone {})", - s.name(), TE::KindName(d.kind), d.x, d.y, std::hypot(d.x - bx, d.y - by), slot, s.zone_id()); - return true; + return TakeErrand(s, st, dests[size_t(k)], leaving, now_ms); } -// At the place: face the NPC, sell the junk or repair at a vendor, one gesture now and then, and stop a few seconds. +// A station of this focus type really stands within its spell-focus reach of the bot — the same check +// idle:craft_skillup makes before a real cast (SPELL_FOCUS gameobject whose type and radius fit). +static bool FocusInReach(BotSnapshotView const& s, uint32 focus_type) +{ + float bx = 0.f, by = 0.f, bz = 0.f; + s.position(bx, by, bz); + for (auto const& go : s.raw().world_objects.nearby_objects) + { + GameObjectTemplate const* info = sObjectMgr->GetGameObjectTemplate(go.entry); + if (!info || info->type != GAMEOBJECT_TYPE_SPELL_FOCUS || uint32(info->GetSpellFocusType()) != focus_type) + continue; + float const dx = go.x - bx, dy = go.y - by, dz = go.z - bz; + float const r = float(info->GetSpellFocusRadius()); + if (dx * dx + dy * dy + dz * dz <= r * r) + return true; + } + return false; +} + +// The best recipe the bot knows for this station: needs this focus — or none, a no-station recipe casts +// anywhere — still gives skill (orange over yellow over green), not on cooldown. Reagents are NOT part of the pick — the caller stocks the bags for the +// chosen recipe (a worker's kit is conjured once per visit), so a recipe it knows always leads to a real cast. +// 0 = no usable recipe at all — the station show then falls back to the work emote. +// The station's own trade only: a smith at the anvil casts smithing, never the leatherworking she +// also knows — the recipe needing no focus at all is not a license to work a foreign craft on this +// fixture (a leatherwork anim at the anvil while the smithing kit clangs was the tell). Same +// station -> skill mapping as CraftKindMatch. +static bool StationSkillMatch(TE::Kind k, uint32 skill_line) +{ + switch (k) + { + case TE::Kind::Forge: return skill_line == 164 || skill_line == 202 || skill_line == 186; + case TE::Kind::Cookfire: return skill_line == 185; + case TE::Kind::Loom: + case TE::Kind::Moonwell: return skill_line == 197; + default: return false; + } +} + +static uint32 PickCraftSpell(BotSnapshotView const& s, uint32 focus_type, TE::Kind kind) +{ + if (!FocusInReach(s, focus_type)) + return 0; + uint32 best = 0; + RecipeColor best_color = RecipeColor::Unknown; + uint16 best_skill = 0xFFFFu; + for (uint32 spell_id : s.raw().spellbook.known_recipes) + { + RecipeMeta const* meta = FindRecipeMeta(spell_id); + if (!meta || s.is_skill_capped(meta->skill_line_id)) continue; + if (!StationSkillMatch(kind, meta->skill_line_id)) continue; + SpellInfo const* si = sSpellMgr->GetSpellInfo(spell_id, DIFFICULTY_NONE); + if (!si) continue; + // The station's own focus — or none: vanilla recipes that need no station (the bolts, + // the bandages) cast fine standing anywhere, so a tailor at the loom works for real. + uint32 const need_focus = uint32(si->RequiresSpellFocus); + if (need_focus != 0 && need_focus != focus_type) continue; + uint16 const cur = s.skill_value(meta->skill_line_id); + RecipeColor const c = ResolveRecipeColor(spell_id, cur); + if (c == RecipeColor::Gray || c == RecipeColor::Unknown) continue; + // Cooldown only — NOT is_ready: is_ready folds in has_reagents, and + // missing reagents is precisely the case the caller conjures stock + // for. The other readiness gates (casting / GCD / moving) are + // re-checked on the cast beat itself. + if (s.cd_remaining(spell_id).count() > 0) continue; + bool const better = best == 0 || uint8(c) < uint8(best_color) || (c == best_color && cur < best_skill); + if (better) { best = spell_id; best_color = c; best_skill = cur; } + } + return best; +} + +// The tool of the trade in hand while it works: a smith hammers with a hammer, not a sword and an empty fist. +// The equip swap leaves the weapon in the tool's bag slot, so the same equip_item call in EndErrand puts the +// battle kit back on. A bot set up before the tool grant (DoLearnProfessions) has the skill but no tool: it is +// conjured into the bags once (a worker carries their own), and the next use-beat equips it. +static uint32 StationToolEntry(TE::Kind kind, BotSnapshotView const& s) +{ + if (kind != TE::Kind::Forge) return 0; // cookfire, loom, moonwell need no tool in vanilla + if (s.has_skill(164)) return 5956; // Blacksmith Hammer + if (s.has_skill(202)) return 6219; // Arclight Spanner + if (s.has_skill(186)) return 2901; // Mining Pick — smelting + return 0; +} + +// The one starter recipe a station's trade casts from conjured stock, taught lazily at the station via a +// learn_spell intent — bots set up before DoLearnProfessions' grants (or whose grant missed) still craft +// for real. Mirrors CraftKindMatch's station -> skill mapping. +static uint32 StationRecipeEntry(TE::Kind kind, BotSnapshotView const& s) +{ + switch (kind) + { + case TE::Kind::Forge: + if (s.has_skill(164)) return 2660; // Rough Sharpening Stone + if (s.has_skill(202)) return 3918; // Rough Blasting Powder + if (s.has_skill(186)) return 2657; // Smelt Copper + return 0; + case TE::Kind::Cookfire: return s.has_skill(185) ? 8604 : 0; // Herb Baked Egg + case TE::Kind::Loom: return s.has_skill(197) ? 2963 : 0; // Bolt of Linen Cloth + case TE::Kind::Moonwell: return s.has_skill(197) ? 18560 : 0; // Mooncloth + default: return 0; + } +} + +enum class KitResult { Working, Ready, Abort }; + +// The kit of the trade: the station's tool in the hand. The emit can't report an outcome — a refused +// give or swap is invisible to the bot thread — so the bags are the truth: an item that left the bags +// went into the hand (an equipment slot is not a bag), which is what confirms the swap, and an item +// still in the bags means the last emit didn't land and goes out again. Full bags make the give +// impossible outright: the worker goes to sell first (want_vendor steers the next errand to a vendor). +static KitResult StationKit(BotSnapshotView const& s, BotIntentEmitter& emit, TE::State& st) +{ + uint32 const tool_entry = StationToolEntry(st.kind, s); + if (!tool_entry || st.tool_in_hand) return KitResult::Ready; + // Already in the hand — left on from an earlier visit's empty-mainhand end. Counts as a + // confirmed kit; without this the bags scan finds nothing and conjures a second tool. + if (s.raw().inventory.equipped.size() > EQUIPMENT_SLOT_MAINHAND && + s.raw().inventory.equipped[EQUIPMENT_SLOT_MAINHAND].entry == tool_entry) + { + st.tool_in_hand = true; + emit.set_sheath(SHEATH_STATE_MELEE); + emit.emote_text("hefts their hammer."); // debug anchor: the kit confirmed — the hand should show the tool now + return KitResult::Ready; + } + for (auto const& it : s.raw().inventory.bag_items) + if (it.entry == tool_entry) + { + // A swap is already in flight: only the tracked item counts — a second same-entry + // tool in the bags (or the swap-back's spare) must not keep re-triggering swaps. + if (st.tool_guid != 0) + { + if (it.guid.GetCounter() == st.tool_guid) + { + if (emit.equip_item(it.bag, it.slot, EQUIPMENT_SLOT_MAINHAND)) + { + st.tool_bag = it.bag; + st.tool_slot = it.slot; + } + return KitResult::Working; + } + continue; // not our tool — keep looking + } + if (emit.equip_item(it.bag, it.slot, EQUIPMENT_SLOT_MAINHAND)) + { + st.tool_bag = it.bag; + st.tool_slot = it.slot; + st.tool_guid = it.guid.GetCounter(); + } + return KitResult::Working; + } + if (st.tool_bag != 0xFF) // a swap went out and the tool left the bags: it's the hand now + { + st.tool_in_hand = true; + emit.set_sheath(SHEATH_STATE_MELEE); // hands stay sheathed at idle: draw the tool or the show looks empty-handed + emit.emote_text("hefts their hammer."); // debug anchor: the kit confirmed — the hand should show the tool now + return KitResult::Ready; + } + if (s.bag_free_slots() < 2u) + { + // Nowhere for the kit to land — a worker with full bags sells before he stocks up. + st.want_vendor = true; + return KitResult::Abort; + } + if (emit.give_item(tool_entry)) + TC_LOG_INFO("playerbot.v2", "[town] {} has no tool: item {} given for the {}", s.name(), tool_entry, TE::KindName(st.kind)); + return KitResult::Working; +} + +// A bot at a craft station "uses" it every 8-15 s of the linger: cast a known recipe that needs this focus when +// it can (the real smith hammering is the most convincing look there is; CraftCast=0 turns that off), else hold +// the looped work emote for the station. +static void CraftUse(BotSnapshotView const& s, BotAI& ai, BotIntentEmitter& emit, TE::State& st, uint32 now_ms) +{ + // The kit comes first, on a quicker cadence than the use-beat: a give or swap the + // server refuses leaves no trace the bot thread can see, so each check retries the + // step that's still short. A few failures and the visit ends — a worker who can't + // get set up walks off; miming the station with empty hands was the tell. + if (!st.kit_ready) + { + if (now_ms < st.next_kit_ms) return; + st.next_kit_ms = now_ms + 2000u; + KitResult const kit = StationKit(s, emit, st); + TC_LOG_INFO("playerbot.v2", "[town-kit] {} attempt={} result={} kind={} guid={}", s.name(), + uint32(st.kit_attempts), kit == KitResult::Ready ? "ready" : kit == KitResult::Abort ? "abort" : "working", + TE::KindName(st.kind), st.tool_guid); + if (kit == KitResult::Ready) + st.kit_ready = true; + else if (kit == KitResult::Abort || ++st.kit_attempts >= 6u) + { + EndErrand(s, emit, st, false); + return; + } + else + return; // the kit's still coming together — the work show waits for it + } + // The tool displaces the weapon for the whole visit: keep the upgrade rule off the mainhand + // the way the skillup path does — a staff swapped back in mid-hammer was the tell. + if (st.tool_guid != 0 || st.tool_in_hand) + ai.station_prop_extend(now_ms); + // The work sound while the emote loops: the kit is a one-shot, so re-push it on the animation's + // strike period (conf-tuned: the clang should land on the visible hit, a fixed period, no jitter). + if (st.work_emote && now_ms >= st.next_sound_ms) + { + static int32 const beat_ms = sConfigMgr->GetIntDefault("Playerbot.World.Town.CraftSoundBeatMs", 1000, true); + st.next_sound_ms = now_ms + uint32(beat_ms > 200 ? beat_ms : 200); + if (uint32 const kit = TE::SoundKitFor(TE::Cfg(), st.kind)) + emit.emit(PlaySoundIntent{ kit }); + } + if (now_ms < st.next_use_ms) return; + st.next_use_ms = now_ms + 8000u + uint32(ai.rng().int_range(0, 70)) * 100u; + // The work sound: the real cast carries whatever audio its visual kit owns, but the emote beats are + // silent — push the station's own tradeskill kit (anvil clang, pot, loom) to earshot once a beat. + if (uint32 const kit = TE::SoundKitFor(TE::Cfg(), st.kind)) + emit.emit(PlaySoundIntent{ kit }); + if (TE::Cfg().craft_cast) + if (uint32 const spell = PickCraftSpell(s, st.focus_type, st.kind)) + { + if (s.has_reagents(spell)) + { + if (s.is_ready(spell)) + { + if (st.work_emote) + { + emit.perform_emote(EMOTE_STATE_NONE); + st.work_emote = false; + } + if (s.bot_id() % 16u == 0u) + TC_LOG_INFO("playerbot.v2", "[town] {} crafts spell {} at the {}", s.name(), spell, TE::KindName(st.kind)); + emit.cast(spell); + return; + } + } + // The stock of the trade: enough reagents for a few casts, conjured into the bags once per visit + // like the tool (a smith's bag holds the bars). What the visit leaves is the worker's kit — the + // next station visit casts with it; what it makes the bot sells at its next vendor stop. + else if (!st.stock_given) + { + bool all = true; + if (SpellInfo const* si = sSpellMgr->GetSpellInfo(spell, DIFFICULTY_NONE)) + { + for (uint8 r = 0; r < MAX_SPELL_REAGENTS; ++r) + if (si->Reagent[r] > 0 && si->ReagentCount[r] > 0) + all &= emit.give_item(uint32(si->Reagent[r]), uint16(si->ReagentCount[r] * 3u)); + if (s.bot_id() % 16u == 0u) + TC_LOG_INFO("playerbot.v2", "[town] {} stocked for spell {} at the {}", s.name(), spell, TE::KindName(st.kind)); + } + else + all = true; // unknown spell — don't retry every beat + st.stock_given = all; // a full intent queue just retries next beat + } + // This beat falls to the emote; the next one has the stock and casts for real. + } + // No usable recipe for this station: teach the starter once per visit. Covers bots set up + // before DoLearnProfessions' grants — the recipe lands next drain and the next beat picks it. + else if (!st.recipe_given) + if (uint32 const recipe = StationRecipeEntry(st.kind, s)) + // Once per visit either way: a recipe already in the book is why the pick came + // back empty (grey-capped or on cooldown) — nothing to teach it then. + st.recipe_given = s.knows_spell(recipe) ? true : emit.learn_spell(recipe); + if (!st.work_emote) + if (uint32 const e = TE::WorkEmoteFor(st.kind)) + { + emit.perform_emote(e); + st.work_emote = true; + } +} + +// Half-way through a long stop at a banker or auctioneer the bot faces the NPC once more and talks at it — +// the "still doing business" tell of a player paging through bags at the counter. +static void FidgetAt(BotSnapshotView const& s, BotAI& ai, BotIntentEmitter& emit, TE::State& st, uint32 now_ms) +{ + if (!st.entry || !st.next_use_ms || now_ms < st.next_use_ms) return; + st.next_use_ms = 0; // once per stay + for (auto const& u : s.nearby_friends()) + { + if (u.is_player || u.entry != st.entry || std::hypot(u.x - st.nx, u.y - st.ny) > 15.0f) continue; + emit.face_target(u.guid); + if (ai.rng().chance(0.5)) + { + static constexpr uint32 kTalk[] = { EMOTE_ONESHOT_TALK, EMOTE_ONESHOT_TALK, EMOTE_ONESHOT_QUESTION, EMOTE_ONESHOT_POINT }; + emit.perform_emote(kTalk[ai.rng().int_range(0, int32(std::size(kTalk)))], u.guid); + } + break; + } +} + +// At the place: face the NPC, sell the junk or repair at a vendor, one gesture now and then, and stop a while — +// how long depends on the place: an errand is seconds, the bank or the auction house half a minute, working at a +// craft station a minute or so (Playerbot.World.Town.Linger*Sec). static void ArriveErrand(BotSnapshotView const& s, BotAI& ai, BotIntentEmitter& emit, TE::State& st, uint32 now_ms) { float bx, by, bz; @@ -1140,10 +1524,10 @@ static void ArriveErrand(BotSnapshotView const& s, BotAI& ai, BotIntentEmitter& emit.face_target(u.guid); uint64 const low = u.guid.GetCounter(); bool const in_reach = std::hypot(u.x - bx, u.y - by) <= 5.0f; - if (in_reach && (u.npc_flags & UNIT_NPC_FLAG_VENDOR_MASK) && HasGreyJunkItem(s) + if (in_reach && (u.npc_flags & UNIT_NPC_FLAG_VENDOR_MASK) && !ai.action_recently_tried(BotAI::ActionKind::SellTrash, low, now_ms)) { - emit.vendor_sell_trash(u.guid); + emit.vendor_sell_trash(u.guid); // junk AND craft surplus — sell_trash decides what moves ai.note_action_retry(BotAI::ActionKind::SellTrash, low, now_ms); } if (in_reach && (u.npc_flags & UNIT_NPC_FLAG_REPAIR) && s.lowest_equipped_durability_pct() < 100 && s.gold() > 0 @@ -1161,14 +1545,39 @@ static void ArriveErrand(BotSnapshotView const& s, BotAI& ai, BotIntentEmitter& } } auto const& c = TE::Cfg(); - uint32 linger = c.linger_min_ms; - if (c.linger_max_ms > c.linger_min_ms) - linger += uint32(ai.rng().int_range(0, int32((c.linger_max_ms - c.linger_min_ms) / 100u) + 1)) * 100u; + uint32 lmin = 0, lmax = 0; + TE::LingerRange(c, st.kind, lmin, lmax); + uint32 linger = lmin; + if (lmax > lmin) + linger += uint32(ai.rng().int_range(0, int32((lmax - lmin) / 100u) + 1)) * 100u; if (st.kind == TE::Kind::Exit || st.kind == TE::Kind::Mailbox) linger /= 2u; // a look out of the gate, a letter posted st.phase = 2; st.phase_start_ms = now_ms; st.linger_until_ms = now_ms + linger; st.near_player_ms = 0; + // The first "use the place" beat: a craft station's first cast or work emote lands a breath after arrival; a + // bank or auction-house stop repeats the face-and-talk gesture about halfway through the linger. + if (TE::IsCraftKind(st.kind)) + { + // Right at the station and turned to it: the nearest gameobject of the station's focus type is the anvil + // the bot works at (face_target resolves gameobjects — the same SetFacingToObject the spell path uses). + ObjectGuid station; + float best_d2 = 12.0f * 12.0f; + for (auto const& go : s.raw().world_objects.nearby_objects) + { + GameObjectTemplate const* info = sObjectMgr->GetGameObjectTemplate(go.entry); + if (!info || uint32(info->GetSpellFocusType()) != st.focus_type) continue; + float const dx = go.x - st.nx, dy = go.y - st.ny; + float const d2 = dx * dx + dy * dy; + if (d2 < best_d2) { best_d2 = d2; station = go.guid; } + } + if (!station.IsEmpty()) + emit.face_target(station); + st.next_kit_ms = now_ms; // the kit run starts on the first linger tick: give -> swap -> confirm + st.next_use_ms = now_ms + 2000u + uint32(ai.rng().int_range(0, 20)) * 100u; + } + else if (st.entry) + st.next_use_ms = now_ms + linger / 2u; V2::TownLife::Counters().errands.fetch_add(1, std::memory_order_relaxed); } @@ -1197,7 +1606,10 @@ bool TownErrandFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const auto& st = ai.town_errand(); // An errand left long ago (a fight, a quest, a show took over) is not resumed: the next place is chosen from here. if (st.phase != 0 && now_ms - st.phase_start_ms > kErrandStaleMs) - EndErrand(s, st, false); + EndErrand(s, emit, st, false); + + // Settle beat: a show that just ended stands a moment before the next errand starts. + if (int32(st.pause_until_ms - now_ms) > 0) return true; if (st.phase == 2) { @@ -1206,10 +1618,14 @@ bool TownErrandFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const if (nudged) V2::TownLife::Counters().player_nudges.fetch_add(1, std::memory_order_relaxed); if (now_ms < st.linger_until_ms && !nudged) { + if (TE::IsCraftKind(st.kind)) + CraftUse(s, ai, emit, st, now_ms); + else + FidgetAt(s, ai, emit, st, now_ms); ai.set_last_rule_fired("idle:town_linger"); return true; } - EndErrand(s, st, true); // done: straight on to the next place, this tick + EndErrand(s, emit, st, true); // done: straight on to the next place, this tick } if (st.phase == 0 && !PickErrand(s, ai, st, now_ms)) @@ -1234,7 +1650,7 @@ bool TownErrandFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const V2::TownLife::Counters().errand_gave_up.fetch_add(1, std::memory_order_relaxed); if (s.bot_id() % 16u == 0u) TC_LOG_INFO("playerbot.v2", "[town] {} gave up on the {} at ({:.0f},{:.0f}), {:.0f} y short", s.name(), TE::KindName(st.kind), st.nx, st.ny, d_npc); - EndErrand(s, st, false); + EndErrand(s, emit, st, false); return false; } } @@ -1243,7 +1659,7 @@ bool TownErrandFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const // Out of the gate: no stop, the bot runs on to level (grind_roam, which lets it through the capital's edge until then). st.leave_until_ms = now_ms + kLeaveMs; V2::TownLife::Counters().errands.fetch_add(1, std::memory_order_relaxed); - EndErrand(s, st, true); + EndErrand(s, emit, st, true); return false; } if (there) @@ -1804,8 +2220,14 @@ bool KindHealFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, } if (urand(0, 3) == 0) { - static constexpr char const* kLines[] = { "there you go", "patched you up", "heal inc", "careful out there", "you looked like you needed that" }; - emit.say_world(kLines[urand(0, uint32(std::size(kLines)) - 1)]); + // Migration 0067: the text table's say_kindness_heal key first; the builtin pool otherwise. + std::string line = BotTextMgr::instance().Get("say_kindness_heal"); + if (line.empty()) + { + static constexpr char const* kLines[] = { "there you go", "patched you up", "heal inc", "careful out there", "you looked like you needed that" }; + line = kLines[urand(0, uint32(std::size(kLines)) - 1)]; + } + emit.say_world(std::move(line)); } board.heals.fetch_add(1, std::memory_order_relaxed); TC_LOG_INFO("playerbot.v2", "[kindness] {} heals a passing player (guid {}) at {}% with {}", s.name(), t->guid, t->hp_pct, rank); @@ -1870,8 +2292,14 @@ bool KindRezFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, ObjectGuid const target = ObjectGuid::Create(t->guid); emit.face_target(target); if (!emit.cast(KindRezSpell(s.cls()), target)) return false; - static constexpr char const* kLines[] = { "rez inc", "hold on, rezzing you", "got you", "rez coming", "don't release, rezzing" }; - emit.say_world(kLines[urand(0, uint32(std::size(kLines)) - 1)]); + // Migration 0067: the text table's say_kindness_rez key first; the builtin pool otherwise. + std::string rez_line = BotTextMgr::instance().Get("say_kindness_rez"); + if (rez_line.empty()) + { + static constexpr char const* kLines[] = { "rez inc", "hold on, rezzing you", "got you", "rez coming", "don't release, rezzing" }; + rez_line = kLines[urand(0, uint32(std::size(kLines)) - 1)]; + } + emit.say_world(std::move(rez_line)); board.rezzes.fetch_add(1, std::memory_order_relaxed); TC_LOG_INFO("playerbot.v2", "[kindness] {} resurrects a player (guid {})", s.name(), t->guid); ai.set_last_rule_fired("idle:kind_rez"); diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/CompanionQuestRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/CompanionQuestRules.cpp index dc71e00fa6..3a885c66af 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/CompanionQuestRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/CompanionQuestRules.cpp @@ -40,6 +40,14 @@ constexpr uint64 kObjectKeyBit = uint64(1) << 41; bool FindPos(BotSnapshotView const& s, ObjectGuid guid, float& x, float& y, float& z) { + // A player giver is the owner passing on a quest an item started (CompanionQuest::BuildState); his spot is in the state. + if (guid.IsPlayer()) + { + auto const& cq = s.raw().companion_quest; + if (!cq.owner_here) return false; + x = cq.owner_x; y = cq.owner_y; z = cq.owner_z; + return true; + } for (auto const& u : s.raw().combat.nearby_friends) if (u.guid == guid) { x = u.x; y = u.y; z = u.z; return true; } for (auto const& o : s.raw().world_objects.nearby_objects) diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/CoreFlowRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/CoreFlowRules.cpp index b52201e07b..6f5c95ef5c 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/CoreFlowRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/CoreFlowRules.cpp @@ -119,7 +119,9 @@ bool SoakTravelFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const bool SwimStuckGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, uint32) { const uint32 swim_now_ms = s.published_at_ms(); - ai.update_swim_state(s.is_swimming(), swim_now_ms); + // Swimming with the player who leads it (a fight on the Vile Reef, a dive for a quest item) is not being stuck in the water: the + // clock starts when he is out and the bot is still in. + ai.update_swim_state(s.is_swimming() && !s.leader_in_water(), swim_now_ms); if (!ai.swim_stuck(swim_now_ms)) return false; return !s.in_battleground() && !s.is_in_dungeon(); } @@ -159,9 +161,12 @@ bool SwimStuckFire(BotSnapshotView const& s, BotAI& ai, // escalation takes over (its gate still runs every tick and updates the swim // timer). Once the bot is on land the builder clears water_escape_valid and the // normal rules (now-correct travel) resume. +// A bot whose leading player is in the water near it stays with him (BotSnapshot::leader_in_water): the way out raced the follow, the +// bot went to the bank and back down between fights, and it missed the fights (vile_reef_fight af60, Discord 2026-11-22 Egod). It gets +// out once he does; its breath is the surfacing rule's (SurvivalRules.cpp). bool WaterEscapeGate(BotSnapshotView const& s, BotAI&, GroupSnapshotView const&, uint32) { - return s.water_escape_valid() + return s.water_escape_valid() && !s.leader_in_water() && s.is_alive() && !s.in_combat() && !s.is_casting() && !s.on_transport() && !s.in_battleground() && !s.is_in_dungeon(); diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/GuildRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/GuildRules.cpp index cc58589a30..e1a54487b7 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/GuildRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/GuildRules.cpp @@ -23,6 +23,7 @@ #include "Bot/BotSnapshotView.h" #include "Bot/BotIntentEmitter.h" #include "Bot/BotIntent.h" +#include "Bot/BotTextMgr.h" #include "Services.h" #include "Fleet/BotGuildMgr.h" #include "Fleet/BotGuildEvent.h" @@ -423,10 +424,35 @@ bool GuildChatQuietGate(BotSnapshotView const& s, BotAI&, GroupSnapshotView cons return true; } +// Migration 0067 moved the chat pools below into the shared text table (guild_* keys), so a realm +// can rewrite guild speech without rebuilding. GuildLine returns a table line for `key` when the +// table carries any; a `pool` line otherwise (placeholders filled the same way), so a server +// without the rows talks exactly as before. +std::string GuildLine(char const* key, BotAI& ai, char const* const* pool, size_t pool_n, + TextPlaceholders const& ph = {}) +{ + if (std::string line = BotTextMgr::instance().Get(key, ph); !line.empty()) + return line; + std::string line = pool[ai.rng().int_range(0, int32_t(pool_n))]; + BotTextMgr::Fill(line, ph); + return line; +} + +// A /g line needs a real guild member online to hear it: without one, guild chat is bots talking to an +// empty channel — the gate stays closed so the line waits for an audience instead of being spent unheard. +// RecruitChannelGate keeps the plain QuietGate on purpose: its post goes to a public channel, where +// recruiting for a bot-only guild is the point. The event HoldGates keep it too: the gathering itself +// still happens, only the chatter waits. +bool GuildChatAudienceGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, uint32 now_ms) +{ + if (!GuildChatQuietGate(s, ai, g, now_ms)) return false; + return s.guild_online_human_member_count() > 0; +} + // ---------- idle:guild_chat:ding ---------- bool ChatDingGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, uint32 now_ms) { - if (!GuildChatQuietGate(s, ai, g, now_ms)) return false; + if (!GuildChatAudienceGate(s, ai, g, now_ms)) return false; return s.level() > ai.guild_chat_last_ding_level(); } @@ -439,11 +465,10 @@ bool ChatDingFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& return false; } static constexpr char const* kDingVariants[] = { - "Ding {}!", "{} achieved", "hit {} :)", "Level {}!", "ding {}", + "Ding %my_level!", "%my_level achieved", "hit %my_level :)", "Level %my_level!", "ding %my_level", }; - const int32_t n_dings = static_cast(sizeof(kDingVariants) / sizeof(*kDingVariants)); - const size_t idx = static_cast(ai.rng().int_range(0, n_dings)); - emit.guild_chat(fmt::format(fmt::runtime(kDingVariants[idx]), s.level())); + emit.guild_chat(GuildLine("guild_ding", ai, kDingVariants, std::size(kDingVariants), + { { "%my_level", std::to_string(s.level()) } })); // Party-chat ding is handled separately in BotAI::tick (the // pending_ding_level_ stagger path) — don't double-emit here. ai.set_guild_chat_last_ding_level(s.level()); @@ -454,7 +479,7 @@ bool ChatDingFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& // ---------- idle:guild_chat:login_greet ---------- bool ChatLoginGreetGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, uint32 now_ms) { - if (!GuildChatQuietGate(s, ai, g, now_ms)) return false; + if (!GuildChatAudienceGate(s, ai, g, now_ms)) return false; return ai.guild_chat_login_greeted_ms() == 0 && s.guild_online_member_count() >= 2; } @@ -465,9 +490,7 @@ bool ChatLoginGreetFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView c "hi all", "hey :)", "o/", "hello!", "evening", "yo", "hi guild", "hey hey", "o/ everyone", "back online", }; - const int32_t n_greets = static_cast(sizeof(kGreetVariants) / sizeof(*kGreetVariants)); - const size_t idx = static_cast(ai.rng().int_range(0, n_greets)); - emit.guild_chat(kGreetVariants[idx]); + emit.guild_chat(GuildLine("guild_login_greet", ai, kGreetVariants, std::size(kGreetVariants))); ai.note_guild_chat_login_greet(GameTime::GetGameTimeMS()); (void)s; ai.set_last_rule_fired("idle:guild_chat:login_greet"); @@ -477,12 +500,7 @@ bool ChatLoginGreetFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView c // ---------- idle:guild_chat:smalltalk ---------- bool ChatSmalltalkGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, uint32 now_ms) { - if (!GuildChatQuietGate(s, ai, g, now_ms)) return false; - // SC-P3c: require at least one ONLINE human guildmate. Smalltalk is - // self-initiated ambient chatter; with no human in the guild it's bots - // babbling to each other, which is pointless traffic and reads as a tell. - // Reactive announces (ding/login_greet/quest_brag) stay unconditional. - if (s.guild_online_human_member_count() < 1) return false; + if (!GuildChatAudienceGate(s, ai, g, now_ms)) return false; if (s.guild_online_member_count() < 3) return false; const uint32 gc_now_ms = GameTime::GetGameTimeMS(); if (ai.guild_chat_last_smalltalk_ms() != 0 && @@ -510,9 +528,7 @@ bool ChatSmalltalkFire(BotSnapshotView const&, BotAI& ai, GroupSnapshotView cons "this rep grind...", "soloing dungeons for chests", "wow my repair bill", "good music tonight, share recs", }; - const int32_t n_st = static_cast(sizeof(kSmalltalkVariants) / sizeof(*kSmalltalkVariants)); - const size_t idx = static_cast(ai.rng().int_range(0, n_st)); - emit.guild_chat(kSmalltalkVariants[idx]); + emit.guild_chat(GuildLine("guild_smalltalk", ai, kSmalltalkVariants, std::size(kSmalltalkVariants))); ai.note_guild_chat_smalltalk(GameTime::GetGameTimeMS()); ai.set_last_rule_fired("idle:guild_chat:smalltalk"); return true; @@ -521,11 +537,8 @@ bool ChatSmalltalkFire(BotSnapshotView const&, BotAI& ai, GroupSnapshotView cons // ---------- idle:guild_chat:tavern_hangout ---------- bool ChatTavernHangoutGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, uint32 now_ms) { - if (!GuildChatQuietGate(s, ai, g, now_ms)) return false; - // SC-P3c: the tavern-hangout pitch is broadcast to /g, so it needs a - // human audience to be worth sending. (The cluster check below only - // confirms 2+ guildmates are physically nearby — those can all be bots.) - if (s.guild_online_human_member_count() < 1) return false; + if (!GuildChatAudienceGate(s, ai, g, now_ms)) return false; + // The cluster check below confirms 2+ guildmates are physically nearby — those can all be bots. const uint32 gc_now_ms = GameTime::GetGameTimeMS(); if (ai.guild_chat_last_hangout_ms() != 0 && gc_now_ms - ai.guild_chat_last_hangout_ms() <= 60u * 60u * 1000u) @@ -547,7 +560,8 @@ bool ChatTavernHangoutFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotVie const auto kHFaction = FactionOf(s); char const* venue = (kHFaction == ::Playerbot::V2::BotGuildMgr::FACTION_ALLIANCE) ? "Pig & Whistle" : "Wyvern's Tail"; - emit.guild_chat(fmt::format("anyone want to hit the tavern? {}", venue)); + static constexpr char const* kHangoutLine[] = { "anyone want to hit the tavern? %venue" }; + emit.guild_chat(GuildLine("guild_tavern_hangout", ai, kHangoutLine, std::size(kHangoutLine), { { "%venue", venue } })); ai.note_guild_chat_hangout(GameTime::GetGameTimeMS()); ai.set_last_rule_fired("idle:guild_chat:tavern_hangout"); return true; @@ -556,7 +570,7 @@ bool ChatTavernHangoutFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotVie // ---------- idle:guild_chat:rival_banter ---------- bool ChatRivalBanterGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, uint32 now_ms) { - if (!GuildChatQuietGate(s, ai, g, now_ms)) return false; + if (!GuildChatAudienceGate(s, ai, g, now_ms)) return false; if (s.guild_rival_id() == 0) return false; const uint32 gc_now_ms = GameTime::GetGameTimeMS(); if (ai.guild_chat_last_smalltalk_ms() != 0 && @@ -579,9 +593,7 @@ bool ChatRivalBanterFire(BotSnapshotView const&, BotAI& ai, GroupSnapshotView co "watch the rivals here", "let's outperform them", "rival in sight, on guard", "amateurs", }; - const int32_t n_rv = sizeof(kRivalLines) / sizeof(*kRivalLines); - const size_t ri = static_cast(ai.rng().int_range(0, n_rv)); - emit.guild_chat(kRivalLines[ri]); + emit.guild_chat(GuildLine("guild_rival", ai, kRivalLines, std::size(kRivalLines))); ai.note_guild_chat_smalltalk(GameTime::GetGameTimeMS()); ai.set_last_rule_fired("idle:guild_chat:rival_banter"); return true; @@ -590,7 +602,7 @@ bool ChatRivalBanterFire(BotSnapshotView const&, BotAI& ai, GroupSnapshotView co // ---------- idle:guild_chat:quest_brag ---------- bool ChatQuestBragGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, uint32 now_ms) { - if (!GuildChatQuietGate(s, ai, g, now_ms)) return false; + if (!GuildChatAudienceGate(s, ai, g, now_ms)) return false; const uint16 quest_count_now = s.completed_quest_count(); if (ai.guild_chat_last_seen_quest_count() == 0xFFFF) { @@ -624,9 +636,7 @@ bool ChatQuestBragFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView co "easy gold", "quest hub clear", "love a good quest chain", "rolling through quests", }; - const int32_t n_br = sizeof(kBragVariants) / sizeof(*kBragVariants); - const size_t bi = static_cast(ai.rng().int_range(0, n_br)); - emit.guild_chat(kBragVariants[bi]); + emit.guild_chat(GuildLine("guild_quest_brag", ai, kBragVariants, std::size(kBragVariants))); ai.note_guild_chat_brag(GameTime::GetGameTimeMS()); ai.set_last_rule_fired("idle:guild_chat:quest_brag"); return true; @@ -635,7 +645,7 @@ bool ChatQuestBragFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView co // ---------- idle:guild_chat:lfm_pulse ---------- bool ChatLfmPulseGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, uint32 now_ms) { - if (!GuildChatQuietGate(s, ai, g, now_ms)) return false; + if (!GuildChatAudienceGate(s, ai, g, now_ms)) return false; const uint32 gc_now_ms = GameTime::GetGameTimeMS(); if (!s.lfg_in_queue()) { @@ -656,7 +666,8 @@ bool ChatLfmPulseGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView con bool ChatLfmPulseFire(BotSnapshotView const&, BotAI& ai, GroupSnapshotView const& g, BotIntentEmitter& emit, uint32) { - emit.guild_chat("LFM for a dungeon, anyone?"); + static constexpr char const* kLfmLine[] = { "LFM for a dungeon, anyone?" }; + emit.guild_chat(GuildLine("guild_lfm", ai, kLfmLine, std::size(kLfmLine))); ai.note_guild_chat_lfm(GameTime::GetGameTimeMS()); ai.set_last_rule_fired("idle:guild_chat:lfm_pulse"); return true; @@ -665,7 +676,7 @@ bool ChatLfmPulseFire(BotSnapshotView const&, BotAI& ai, GroupSnapshotView const // ---------- idle:guild_event:announce ---------- bool EventAnnounceGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, uint32 now_ms) { - if (!GuildChatQuietGate(s, ai, g, now_ms)) return false; + if (!GuildChatAudienceGate(s, ai, g, now_ms)) return false; return s.guild_has_pending_callout() && s.guild_rank_id() <= 1; } @@ -684,7 +695,11 @@ bool EventAnnounceFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView co case ::Playerbot::V2::GuildEventKind::BgNight: event_label = "BG night"; break; default: break; } - emit.guild_chat(fmt::format("{} starts in {} min!", event_label, mins_until)); + std::string line = BotTextMgr::instance().Get("guild_event_announce", + { { "%event_label", event_label }, { "%mins_until", std::to_string(mins_until) } }); + if (line.empty()) + line = fmt::format("{} starts in {} min!", event_label, mins_until); + emit.guild_chat(std::move(line)); ai.set_last_rule_fired("idle:guild_event:announce"); return true; } @@ -785,12 +800,14 @@ bool EventStagingHoldFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView // ---------- idle:guild_event:tavern (dance / chat, in its place) ---------- bool EventTavernGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, uint32 now_ms) { + // The dance is seen by anyone in the tavern, so it keeps the plain QuietGate; only the /g line + // in EventTavernFire waits for a human guildmate. if (!GuildChatQuietGate(s, ai, g, now_ms)) return false; EventPlace p; return GuildEventPlace(s, /*tavern*/ true, p) && p.dist <= kEventPlaceReach; } -bool EventTavernFire(BotSnapshotView const&, BotAI& ai, GroupSnapshotView const&, BotIntentEmitter& emit, uint32) +bool EventTavernFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, BotIntentEmitter& emit, uint32) { static constexpr uint32 kPartyEmotes[] = { 10, 4, 3, 5, 71, @@ -803,17 +820,15 @@ bool EventTavernFire(BotSnapshotView const&, BotAI& ai, GroupSnapshotView const& ai.set_last_rule_fired("idle:guild_event:tavern_dance"); return true; } - if (ai.rng().int_range(0, 20) == 0) + if (s.guild_online_human_member_count() > 0 && ai.rng().int_range(0, 20) == 0) { static constexpr char const* kPartyChat[] = { "this is fun", "cheers everyone", "/dance", "best night of the week", "love these party nights", - "more bots should hit the tavern", "great turnout", + "more people should hit the tavern", "great turnout", "tavern night incoming", "rolling tipsy", "/toast", }; - const int32_t n_pc = sizeof(kPartyChat) / sizeof(*kPartyChat); - const size_t pi = static_cast(ai.rng().int_range(0, n_pc)); - emit.guild_chat(kPartyChat[pi]); + emit.guild_chat(GuildLine("guild_tavern_chat", ai, kPartyChat, std::size(kPartyChat))); ai.set_last_rule_fired("idle:guild_event:tavern_chat"); return true; } @@ -823,7 +838,7 @@ bool EventTavernFire(BotSnapshotView const&, BotAI& ai, GroupSnapshotView const& // ---------- idle:guild_event:staging (chat, in its place) ---------- bool EventStagingGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, uint32 now_ms) { - if (!GuildChatQuietGate(s, ai, g, now_ms)) return false; + if (!GuildChatAudienceGate(s, ai, g, now_ms)) return false; EventPlace p; return GuildEventPlace(s, /*tavern*/ false, p) && p.dist <= kEventPlaceReach; } @@ -833,35 +848,38 @@ bool EventStagingFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView con const uint8 active_kind = s.guild_active_event_kind(); if (ai.rng().int_range(0, 30) == 0) { - char const* line = "anyone joining?"; + static constexpr char const* kGeneric[] = { "anyone joining?" }; + static constexpr char const* kRaidLines[] = { + "raid night, who's in?", "rolling for raid spots", + "/g raid in 10", "looking for one more dps", + "loot reservations open", + }; + static constexpr char const* kDungeonLines[] = { + "dungeon night, who's down?", "lf2m for keys", + "let's chain some 5-mans", "got a healer?", + "rolling tank dual spec", + }; + static constexpr char const* kBgLines[] = { + "BG night! /join wsg", "premade rolling", + "honor cap incoming", "anyone seen the queue times?", + "rated arena later maybe", + }; + char const* key = "guild_staging_generic"; + char const* const* pool = kGeneric; + size_t pool_n = 1; if (active_kind == static_cast(::Playerbot::V2::GuildEventKind::RaidNight)) { - static constexpr char const* kRaidLines[] = { - "raid night, who's in?", "rolling for raid spots", - "/g raid in 10", "looking for one more dps", - "loot reservations open", - }; - line = kRaidLines[ai.rng().int_range(0, 5)]; + key = "guild_staging_raid"; pool = kRaidLines; pool_n = std::size(kRaidLines); } else if (active_kind == static_cast(::Playerbot::V2::GuildEventKind::DungeonNight)) { - static constexpr char const* kDungeonLines[] = { - "dungeon night, who's down?", "lf2m for keys", - "let's chain some 5-mans", "got a healer?", - "rolling tank dual spec", - }; - line = kDungeonLines[ai.rng().int_range(0, 5)]; + key = "guild_staging_dungeon"; pool = kDungeonLines; pool_n = std::size(kDungeonLines); } - else + else if (active_kind == static_cast(::Playerbot::V2::GuildEventKind::BgNight)) { - static constexpr char const* kBgLines[] = { - "BG night! /join wsg", "premade rolling", - "honor cap incoming", "anyone seen the queue times?", - "rated arena later maybe", - }; - line = kBgLines[ai.rng().int_range(0, 5)]; + key = "guild_staging_bg"; pool = kBgLines; pool_n = std::size(kBgLines); } - emit.guild_chat(line); + emit.guild_chat(GuildLine(key, ai, pool, pool_n)); ai.set_last_rule_fired("idle:guild_event:staging_chat"); return true; } @@ -933,10 +951,15 @@ bool ChatBabbleFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const "Just dinged again — slow grind.", "Hope to see folks at the next raid night.", }; - constexpr uint32 kPoolSize = sizeof(kPhrases) / sizeof(kPhrases[0]); - const uint32 bucket = now_ms / kBabbleThrottleMs; - const uint32 sel = (s.bot_id() ^ bucket) % kPoolSize; - emit.emit(ChatIntent{GuildChatIntent{std::string(kPhrases[sel])}}); + std::string line = BotTextMgr::instance().Get("guild_babble"); + if (line.empty()) + { + // No table rows: the builtin pool, with its deterministic per-bot pick kept as it was. + constexpr uint32 kPoolSize = sizeof(kPhrases) / sizeof(kPhrases[0]); + const uint32 bucket = now_ms / kBabbleThrottleMs; + line = kPhrases[(s.bot_id() ^ bucket) % kPoolSize]; + } + emit.emit(ChatIntent{GuildChatIntent{std::move(line)}}); ai.set_last_guild_babble_ms(now_ms); ai.set_last_rule_fired("idle:guild_chat_babble"); return true; diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/LootDrainRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/LootDrainRules.cpp index 2b382031d2..6ee3d31e6d 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/LootDrainRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/LootDrainRules.cpp @@ -157,7 +157,16 @@ bool LootDrainFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& Creature* c = ObjectAccessor::GetCreature(*p, q.front()); if (!c || !c->IsInWorld()) { q.pop_front(); continue; } // Led by a player: a corpse with nothing of the bot's quest on it is the player's, never walked to. - if (quest_only && !HasPendingQuestLoot(p, c) && !(skin_for_player && SkinnableForBot(p, c))) { q.pop_front(); continue; } + if (quest_only && !HasPendingQuestLoot(p, c) && !(skin_for_player && SkinnableForBot(p, c))) + { + // Say so when it is a quest drop of the bot's that it leaves to the player (row 308): the corpse is dropped from the + // queue without a walk or a loot call, so nothing else in the log shows the bot had a share in it. + if (uint32 const left = QuestLootLeftForPlayer(p, c->GetLootForPlayer(p))) + TC_LOG_INFO("playerbot.v2", "[loot_quest] {} corpse={} leaves item {} for the player (one for the group, he needs it)", + s.name(), c->GetGUID().GetCounter(), left); + q.pop_front(); + continue; + } const float dx = c->GetPositionX() - bx; const float dy = c->GetPositionY() - by; const float dz = c->GetPositionZ() - bz; diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/OocConsumableRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/OocConsumableRules.cpp index d69f12d5d6..ec0054e04c 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/OocConsumableRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/OocConsumableRules.cpp @@ -308,11 +308,12 @@ int32 OocDrinkStart(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const } // A player's bots (grouped, led by him) rest only when they need it and until full (Classic::LedMaySitDown); every other bot keeps the -// personality's food mark and the pull-ready drink marks. With the tank leading a dungeon ("lead on") the tank's pull gate sets the -// pace, as in a group of bots alone, so they drink to its marks between pulls. +// personality's food mark and the pull-ready drink marks. With the tank leading a five-man ("lead on") they still do: the lead mode +// (2026-11-14) put them back on the pull gate's marks, and the healer drank at 80-89 % with the group stopped at nearly every pack, +// what the owner had ruled out on 2026-10-15 and 2026-10-29 (GitHub #23, 2026-11-22). A raid under the lead keeps the raid marks. bool LedRest(BotSnapshotView const& s, BotAI const& ai) { - return s.in_group() && s.is_led_by_player() && !ai.tank_leads_here(s); + return s.in_group() && s.is_led_by_player() && (!ai.tank_leads_here(s) || !s.is_in_raid()); } Classic::RecoveryPick OocRecoveryPick(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, uint32 now_ms) @@ -341,6 +342,9 @@ bool OocEatFoodGate(BotSnapshotView const& s, BotAI& ai, if (s.recently_in_combat(5000)) return false; if (s.raw().movement.is_mounted) return false; if (s.is_encounter_in_progress()) return false; + // Not with the head under water: a player eats on the bank or at the surface, not on the lake floor with the breath bar running + // (the Vile Reef mage sat down 25 y deep after its fight and drowned there, vile_reef_fight af64). + if (s.is_underwater()) return false; if (!Classic::SafeToRecover(s, &g)) return false; // A solo quester does not sit down with its quest kill targets ready to engage in scan range; a grouped bot goes at the // group's pace, so this never applies to it. diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/PrologueRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/PrologueRules.cpp index 0b4765bd35..93fef047db 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/PrologueRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/PrologueRules.cpp @@ -1046,10 +1046,15 @@ bool PullBackTick(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, if (p.map != s.map_id()) return finish("left the map"); using Phase = BotAI::PullBackPhase; constexpr uint32 kTimeoutMs = 30000u, kHoldCapMs = 300000u; + constexpr uint32 kUnpullableGateMs = 120000u; // a pack no pull from here could wake (PackPullGate::Note) auto tag = [&](char const* idle_tag, char const* combat_tag) { ai.set_last_rule_fired(in_combat_state ? combat_tag : idle_tag); }; if (p.phase != Phase::Hold && now_ms - p.started_ms > kTimeoutMs) { + // A pull that never woke its target is no pull from here: the pack is passed by for a while, like an unreachable one + // (see go_home_and_finish below), or the next pick takes the same mob again. + if (p.phase == Phase::Pull) + ai.pack_pull_gate().Note(p.target.GetCounter(), /*gated*/ true, now_ms, kUnpullableGateMs); // Don't stand where the pull left us (a ledge, the lava edge): walk back to the return point once, off the mob. if (!s.victim().IsEmpty()) emit.stop_attack(); if (s.is_casting()) emit.cancel_cast(); @@ -1296,18 +1301,42 @@ bool PullBackTick(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, if (!tu && d <= 38.0f) return finish("target left the scan"); - auto go_home_and_finish = [&](char const* why) + auto go_home_and_finish = [&](char const* why, uint32 gate_ms = PackPullGate::kGatedMs) { if (!s.victim().IsEmpty()) emit.stop_attack(); if (s.is_casting()) emit.cancel_cast(); emit.move_to(p.rx, p.ry, p.rz, true); TC_LOG_INFO("playerbot.v2", "[pull_back] {} unreachable: {} -> back to the return point ({:.1f},{:.1f})", s.name(), why, p.rx, p.ry); + // No opener spot leads to this target from here: the pack is no pull for this tank yet, the same verdict the pack stop + // gives a pack it can only walk to the long way round (PackPullGate), so the advance passes it by and the route reaches it + // from its own side. The path to it can be short while every spot in the opener's window lies over a drop: alcaz_full af66, + // the tank on the main hall's upper floor took a Prisoner in a cell on the level below for the next pack, found no pull spot, + // walked out to the balcony's edge on short steps toward it, gave up, and the pack stop handed it the same Prisoner one + // second later, four times in ten seconds. + ai.pack_pull_gate().Note(p.target.GetCounter(), /*gated*/ true, now_ms, gate_ms); finish("unreachable"); tag("idle:pull_back_retreat", "combat:pull_back_retreat"); return true; }; + // The opener went out and neither it nor the hand pull after it woke the target: it still stands idle 8 s on. Something the + // snapshot's sight check does not see stands between (sfk_full af70c 2026-11-25: Throw refused LINE_OF_SIGHT x2 on a Shadowfang + // Ragetooth 12 y off behind the courtyard wall, no path to it, "in sight yes"; the order re-threw for its full 30 s, the next pick + // took the same mob, four times, and the run stalled). The pack is passed by for 2 minutes: the advance and the next pull go on to + // a pack the tank can reach, and the route brings it to this one from its own side. + if (opener_failed && now_ms - p.opened_ms > 8000u && tu && tu->victim.IsEmpty() && !tu->unit_in_combat) + { + for (auto const& u : s.raw().combat.nearby_enemies) + { + if (u.hp <= 0 || !u.victim.IsEmpty() || u.unit_in_combat) continue; + float const px = u.x - tx, py = u.y - ty, pz = u.z - tz; + if (px * px + py * py + pz * pz <= 18.0f * 18.0f) + ai.pack_pull_gate().Note(u.guid.GetCounter(), /*gated*/ true, now_ms, kUnpullableGateMs); + } + return go_home_and_finish("the opener and the hand pull did not wake it in 8 s", kUnpullableGateMs); + } + if (!p.stand_pull && (d > reach - 2.0f || d < near_min)) { // Close to / back off to an in-window spot on the line target -> return point (the raid side; never into an @@ -1506,9 +1535,14 @@ bool PullBackTick(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, if (NearbyUnit const* u = pack_on_group_at_point()) return finish_for_pack(*u); const float td2 = d2xy(bx, by, tu->x, tu->y); - bool others = false; // something besides the pull target is on us + // Something besides the pull target hits the tank here, in melee: the fight has come to the return point. A caster of the pack + // that casts at the tank from where it stands is not that: it stays off and is the line-of-sight pull's to bring in. Counting it + // handed the fight to the rotation the moment the Defias Squallshaper's first bolt landed, and the auto attack walked the tank up + // the gangplank after the Pirate it had pulled (scan66 deadmines_full: Hold at 1484 s, up on the deck at 1490 s with the mage + // behind it, the parrot, a Blackguard and Mr. Smite on the group, the priest dry at 1553 s, the warrior dead at 1561 s). + bool others = false; for (auto const& u : s.raw().combat.attackers) - if (u.guid != p.target && u.hp > 0) { others = true; break; } + if (u.guid != p.target && u.hp > 0 && d2xy(bx, by, u.x, u.y) <= 8.0f * 8.0f) { others = true; break; } // A caster on the tank that stays where it stands (Deadmines' Defias Squallshaper up on the ship's deck) does not come to the return // point: the tank waits here, still, so the line-of-sight pull can start (PveGroupCoordinator::PlanSightPull sees a mob of the fight // stand off while the tank holds at its return point), and the 8 s cap below still hands the fight on. Handing it to the rotation at diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/SurvivalRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/SurvivalRules.cpp index 2de15640b6..9d79fce437 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/SurvivalRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/SurvivalRules.cpp @@ -10,6 +10,8 @@ #include "Bot/BotAI.h" #include "Bot/BotSnapshotView.h" #include "Bot/BotIntentEmitter.h" +#include "Bot/States/MaintainHelpers.h" // BreathDue / SurfaceForAir +#include "Log.h" #include @@ -18,17 +20,27 @@ namespace Playerbot { namespace { // ---------- idle:flee_hazard ---------- +// Inside a hazard as the core tests it: a trap fires on a unit within its radius in 3D (GameObject::Update, IsWithinDist), so a +// bonfire on the floor below a ledge is no hazard to a bot standing on the ledge. The flat test ignored the height +// (lbrs_full af58: on the ledge above the lower hall the tank walked back and forth, the route stepping it south and this +// rule sending it north; the [flee_hazard] line names the object a bot leaves). +bool InsideHazard(float bx, float by, float bz, BotSnapshot::NearbyObject const& obj, float& out_d) +{ + if (!obj.is_hazard || obj.hazard_radius <= 0.0f) return false; + const float dx = bx - obj.x, dy = by - obj.y, dz = bz - obj.z; + const float d2 = dx*dx + dy*dy + dz*dz; + if (d2 >= obj.hazard_radius * obj.hazard_radius) return false; + out_d = std::sqrt(d2); + return true; +} + bool FleeHazardGate(BotSnapshotView const& s, BotAI&, GroupSnapshotView const&,uint32) { float bx, by, bz; s.position(bx, by, bz); + float d = 0.0f; for (auto const& obj : s.raw().world_objects.nearby_objects) - { - if (!obj.is_hazard || obj.hazard_radius <= 0.0f) continue; - const float dx = bx - obj.x; - const float dy = by - obj.y; - if (dx*dx + dy*dy < obj.hazard_radius * obj.hazard_radius) + if (InsideHazard(bx, by, bz, obj, d)) return true; - } return false; } @@ -39,12 +51,9 @@ bool FleeHazardFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const float worst_overlap = 0.0f; for (auto const& obj : s.raw().world_objects.nearby_objects) { - if (!obj.is_hazard || obj.hazard_radius <= 0.0f) continue; - const float dx = bx - obj.x; - const float dy = by - obj.y; - const float d2 = dx*dx + dy*dy; - if (d2 >= obj.hazard_radius * obj.hazard_radius) continue; - const float overlap = obj.hazard_radius - std::sqrt(d2); + float d3 = 0.0f; + if (!InsideHazard(bx, by, bz, obj, d3)) continue; + const float overlap = obj.hazard_radius - d3; if (overlap > worst_overlap) { worst_overlap = overlap; worst = &obj; } } if (!worst) return false; @@ -52,8 +61,16 @@ bool FleeHazardFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const const float dy = by - worst->y; const float d = std::max(0.5f, std::sqrt(dx*dx + dy*dy)); const float scale = (worst->hazard_radius + 5.0f) / d; - emit.move_to(worst->x + dx * scale, worst->y + dy * scale, bz); + const float fx = worst->x + dx * scale, fy = worst->y + dy * scale; + emit.move_to(fx, fy, bz); ai.set_last_rule_fired("idle:flee_hazard"); + static uint32 s_flee_hazard_log_ms = 0; // all bots, one line per 2 s + if (s.published_at_ms() - s_flee_hazard_log_ms > 2000u) + { + s_flee_hazard_log_ms = s.published_at_ms(); + TC_LOG_INFO("playerbot.v2", "[flee_hazard] {} at ({:.1f},{:.1f},{:.1f}) leaves entry {} at ({:.1f},{:.1f},{:.1f}) radius {:.1f} -> ({:.1f},{:.1f})", + s.name(), bx, by, bz, worst->entry, worst->x, worst->y, worst->z, worst->hazard_radius, fx, fy); + } return true; } @@ -88,28 +105,20 @@ bool FleeDamagingLiquidFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotVi } // ---------- idle:surface_to_breathe ---------- -// Breath lasts 60 s (Player::getMaxTimer BREATH_TIMER). A player swimming under water to the shore keeps going and comes up only when -// the breath runs short; the rule used to lift every submerged bot to the surface at once, and the swim to dry land (idle:water_escape, -// idle:leave_water), whose path runs along the bottom, took it under again the next tick: r10 12 Nov, 23 leave_water and 14 water_escape -// flips, bots bobbing in place instead of reaching the bank. Up after 35 s under water, with 25 s of breath to spare. -constexpr uint32 kSurfaceAfterUnderwaterMs = 35000u; - +// A player swimming under water to the shore, or fighting there, keeps going and comes up only when the breath runs short; the rule +// used to lift every submerged bot to the surface at once, and the swim to dry land (idle:water_escape, idle:leave_water), whose path +// runs along the bottom, took it under again the next tick: r10 12 Nov, 23 leave_water and 14 water_escape flips, bots bobbing in place +// instead of reaching the bank. It went on a 35 s clock of its own after that, which counted only the time out of combat: a mage that +// fought on the Vile Reef sat down to eat 25 y deep afterwards and drowned (vile_reef_fight af64). Now the server's own breath timer +// decides, in every state (SurfaceForAir): up with 25 s left, and up there until the bar is full. bool SurfaceToBreatheGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, uint32) { - bool const under = s.is_underwater() && s.water_surface_z() != 0.0f; - uint32 const under_ms = ai.note_underwater(under, s.published_at_ms()); - if (!under) return false; - float bx, by, bz; s.position(bx, by, bz); - if (bz >= s.water_surface_z() - 0.5f) return false; - return under_ms >= kSurfaceAfterUnderwaterMs; + return States::BreathDue(s, ai); } bool SurfaceToBreatheFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&,BotIntentEmitter& emit, uint32) { - float bx, by, bz; s.position(bx, by, bz); - emit.move_to(bx, by, s.water_surface_z() + 0.5f, /*run*/ true); - ai.set_last_rule_fired("idle:surface_to_breathe"); - return true; + return States::SurfaceForAir(s, ai, emit, "idle:surface_to_breathe"); } // ---------- idle:res_sick_wait ---------- diff --git a/src/modules/PlayerbotV2/Bot/States/State_Dead.cpp b/src/modules/PlayerbotV2/Bot/States/State_Dead.cpp index c4712c1cb9..a4d171ed3a 100644 --- a/src/modules/PlayerbotV2/Bot/States/State_Dead.cpp +++ b/src/modules/PlayerbotV2/Bot/States/State_Dead.cpp @@ -244,10 +244,16 @@ void DispatchDead(BotAI& ai, { if (s_last_wipe_chat_ms.compare_exchange_strong(last, wnow ? wnow : 1u)) { - static constexpr char const* kWipe[] = { - "well, that went badly", "wipe :(", "ouch", "ok that one is on me", "and we're all dead", - }; - emit.say(kWipe[ai.rng().int_range(0, int32_t(sizeof(kWipe) / sizeof(*kWipe)))]); + // Migration 0067: the text table's banter_raid_wipe key first; the builtin pool otherwise. + std::string wipe_line = BotTextMgr::instance().Get("banter_raid_wipe"); + if (wipe_line.empty()) + { + static constexpr char const* kWipe[] = { + "well, that went badly", "wipe :(", "ouch", "ok that one is on me", "and we're all dead", + }; + wipe_line = kWipe[ai.rng().int_range(0, int32_t(sizeof(kWipe) / sizeof(*kWipe)))]; + } + emit.say(std::move(wipe_line)); } } } diff --git a/src/modules/PlayerbotV2/Bot/States/State_Idle.cpp b/src/modules/PlayerbotV2/Bot/States/State_Idle.cpp index b6696552f8..958dc1ec10 100644 --- a/src/modules/PlayerbotV2/Bot/States/State_Idle.cpp +++ b/src/modules/PlayerbotV2/Bot/States/State_Idle.cpp @@ -83,6 +83,7 @@ #include "PlayerbotMovement.h" // BotMovement::SehSafeCalculatePath (tile-race guard) #include "PlayerbotAPI.h" // PathBudget::HasBudget (dungeon scan gating) #include +#include #include #include #include @@ -123,14 +124,37 @@ static bool RecipeFocusNear(BotSnapshotView const& s, uint32 spell_id) return false; } +// The trade tool a station recipe is cast with, by skill line — the same prop the +// town-errand show puts in the hand. Zero means the skill has no hand tool. +static uint32 SkillupToolEntry(uint16 skill_line_id) +{ + switch (skill_line_id) + { + case 164: return 5956; // Blacksmith Hammer + case 202: return 6219; // Arclight Spanner + case 186: return 2901; // Mining Pick (smelting) + default: return 0; + } +} + // The mana wait before a pull. A party with a player in it has none (playtest 2026-10-15: the player watches the mana); a raid keeps it, // and so does a group of bots alone, where nobody else would hold the pull for the healer's drink (deadmines_full n57: the priest -// went into every fight at 1-5 % mana). With the tank leading the dungeon ("lead on") the tank holds it, the player's own mana too: -// the player follows and no longer watches the pulls. -static bool PullManaGate(BotSnapshotView const& s, BotAI const& ai, GroupSnapshotView const& g) +// went into every fight at 1-5 % mana). The tank leading a player's five-man ("lead on") has none on trash either, as a group of +// players plays: the lead mode (2026-11-14) brought the wait back with the 90 % party mark and the tank said "waiting for mana" at +// nearly every pack (GitHub #23, 2026-11-22; the owner: "like in retail, like if you were playing with people"). Only before a boss +// does the leading tank wait, for a healer under the mark his bots drink at (PullHealerManaMark). +// The healer mana the tank's pull waits for. Leading a player's five-man ("lead on"), the mark his bots drink at +// (Classic::kLedDrinkBelowManaPct): a healer above it does not sit down, so a higher mark only stands the group still. +static int64 PullHealerManaMark(BotSnapshotView const& s, BotAI const& ai) +{ + if (!s.is_in_raid() && ai.tank_leads_here(s)) + return Classic::kLedDrinkBelowManaPct; + return Classic::PullReadyHealerManaPct(s); +} + +static bool PullManaGate(BotSnapshotView const& s, BotAI const& /*ai*/, GroupSnapshotView const& g) { if (s.is_in_raid()) return true; - if (ai.tank_leads_here(s)) return true; auto const* members = g.members(); if (!members) return false; for (auto const& m : *members) @@ -845,6 +869,17 @@ bool MaintainAutoEquipUpgrades(BotSnapshotView const& s, BotAI& ai, // Defense-in-depth: builder clamps equip_slot to <19, but indexing // equipped[19+] is UB (bag slots are 30-33) — never walk past it. if (dst >= raw.inventory.equipped.size()) continue; + // A station errand's tool show owns the main hand for the visit — the smith's + // hammer is the prop. Don't undo the swap mid-show; EndErrand restores the kit. + // Bound it by linger_until: a bot carried off mid-show (party invite, combat) + // keeps the latched flag with no errand running — the expiry lifts the gate and + // this very rule puts the real weapon back on, hammer to the bags. + auto const& te = ai.town_errand(); + // tool_guid != 0 covers acquisition too: a kit swap in flight would otherwise get + // ping-ponged back out by this very rule before the confirm ever sees the hand. + if (dst == EQUIPMENT_SLOT_MAINHAND && + (((te.tool_in_hand || te.tool_guid != 0) && int32_t(te.linger_until_ms - s.published_at_ms()) > 0) || + ai.station_prop_out(s.published_at_ms()))) continue; if (it.item_level == 0) continue; if (it.quality == 0) continue; // Per-entry retry throttle (shared with idle:equip_upgrade). When the @@ -978,6 +1013,10 @@ bool MaintainBagUpgrade(BotSnapshotView const& s, BotAI& ai, bool MaintainContextTalents(BotSnapshotView const& s, BotAI& ai, BotIntentEmitter& emit) { + // A player's own character keeps the talents its player bought (none of the three talent rules touch it; an owner's "talents" + // order still does). Each summon is a new bot logic, so this rule re-bought the build of the pinned spec over the player's own on + // every summon (RU general 11-21, Alex Black Cat: a protection paladin and a discipline priest re-talented each time). + if (s.raw().players_own_character) return false; if (s.in_combat()) return false; if (s.is_casting()) return false; auto const& raw = s.raw(); @@ -1019,6 +1058,7 @@ bool MaintainContextTalents(BotSnapshotView const& s, BotAI& ai, bool MaintainStarterTalents(BotSnapshotView const& s, BotAI& ai, BotIntentEmitter& emit) { + if (s.raw().players_own_character) return false; // its player's talents (MaintainContextTalents) if (s.in_combat()) return false; if (s.is_casting()) return false; // Specs + talents start at L10 (retail): below that there is no trait @@ -1053,6 +1093,7 @@ bool MaintainStarterTalents(BotSnapshotView const& s, BotAI& ai, bool MaintainStarterTalentsExtend(BotSnapshotView const& s, BotAI& ai, BotIntentEmitter& emit) { + if (s.raw().players_own_character) return false; // its player's talents (MaintainContextTalents) if (s.in_combat()) return false; if (s.is_casting()) return false; if (!s.is_starter_build()) return false; @@ -1423,6 +1464,7 @@ static bool DungeonTargetReachableAndStep(Player* self, float tx, float ty, // DungeonTargetReachableAndStep, whose PathGenerator call shape it copies. struct DungeonDetourVerdict; static DungeonDetourVerdict DungeonTankDetour(Player* tank, float tx, float ty, float tz); +static DungeonDetourVerdict DungeonWalkDetourFrom(Player* pather, float sx, float sy, float sz, float tx, float ty, float tz); static bool DungeonDetourExcessive(DungeonDetourVerdict const& v); // Forward declaration: scalar-out wrapper around DungeonTankDetour + // DungeonDetourExcessive (2026-07-02, Task 3) for callers positioned ahead @@ -1434,6 +1476,9 @@ static bool DungeonDetourExcessive(DungeonDetourVerdict const& v); static bool DungeonTankDetourExcessiveVerbose(Player* tank, float tx, float ty, float tz, float& out_beeline, float& out_path_len, float& out_ratio, bool& out_complete); +static bool DungeonWalkDetourExcessiveVerboseFrom(Player* pather, float sx, float sy, float sz, float tx, float ty, float tz, + float& out_beeline, float& out_path_len, + float& out_ratio, bool& out_complete); // Forward declaration: rule (-1) at the top of DungeonCombatPositioning recovers // an off-mesh-stranded dungeon bot WHILE IN COMBAT (the idle DungeonDispatch nudge // can't run when the FSM has routed the bot to State_InCombat). Definition further @@ -1974,10 +2019,37 @@ bool DungeonHonorCross(BotSnapshotView const& s, BotAI& ai, s.name(), walking_to_hop ? "still a walk away" : "stalled", uint32(dist_to_exit)); ai.set_cross_fight_yield(true); ai.set_dungeon_cross(tgx, tgy, tgz, now_ms + 12000); // keep the commitment for after the fight + // The stall clocks do not run through the fight: a fight longer than 10 s left the episode clock over its cap, and the + // first tick out of combat set the bot down at the exit at once, however far the fight had carried it from the crossing + // (sfk_full 21 Nov: the tank went 85 y in one step to Razorclaw and left the group behind). + ai.cross_episode_reset(); + ai.cross_hold_reset(); + ai.cross_frozen_reset(); + ai.cross_window_reset(); ai.set_last_rule_fired("dungeon_offmesh_cross_yield_fight"); return false; } const bool can_teleport = !s.in_combat() && !s.is_casting(); + // A set-down finishes a hop the bot stands at. An exit further off than a hop is long is walked to, and one out of the + // group's reach is given up (the advance plans the way again with the group). + // A nav-link hop is given up only further off than its link is long, from the mouth's radius: The Shaper's Terrace's landing + // ledge link is 66 y long, and with a flat 40 y the tank gave up its fall on the first tick, every tick, and walked off the ledge + // onto a lip 6 y down (shapers_full af81, 25 Nov). + constexpr float kCrossRelocateMaxYd = 25.0f; + constexpr float kCrossGiveUpYd = 40.0f; + float const give_up_yd = std::max(kCrossGiveUpYd, ai.dungeon_cross_link_len() + 15.0f); + if (can_teleport && dist_to_exit > give_up_yd) + { + TC_LOG_INFO("playerbot.v2", "[dungeon_cross] {} gives up its crossing: the exit ({:.1f},{:.1f},{:.1f}) is {} y away", + s.name(), tgx, tgy, tgz, uint32(dist_to_exit)); + ai.clear_dungeon_cross(); + ai.cross_episode_reset(); + ai.cross_hold_reset(); + ai.cross_frozen_reset(); + ai.cross_window_reset(); + return false; + } + const bool can_relocate = can_teleport && dist_to_exit <= kCrossRelocateMaxYd; if (!can_teleport) { if (cross_episode > kCrossEpisodeMs) ai.cross_episode_reset(); @@ -1985,9 +2057,10 @@ bool DungeonHonorCross(BotSnapshotView const& s, BotAI& ai, if (cross_frozen > kCrossFrozenMs) ai.cross_frozen_reset(); ai.cross_window_reset(); // stale baseline must not insta-trip post-combat } - if (can_teleport && + if (can_relocate && cross_episode > kCrossEpisodeMs && Playerbot::PathBudget::HasBudget(now_ms)) { + TC_LOG_INFO("playerbot.v2", "[dungeon_cross] {} is set down at the exit ({:.1f},{:.1f},{:.1f}), {} y away", s.name(), tgx, tgy, tgz, uint32(dist_to_exit)); emit.near_teleport_to(tgx, tgy, tgz, s.raw().position.o); ai.clear_dungeon_cross(); ai.cross_hold_reset(); @@ -1996,9 +2069,10 @@ bool DungeonHonorCross(BotSnapshotView const& s, BotAI& ai, ai.set_last_rule_fired("dungeon_offmesh_cross_relocate_episode"); return true; } - if (can_teleport && + if (can_relocate && hold_stuck > kCrossStuckMs && Playerbot::PathBudget::HasBudget(now_ms)) { + TC_LOG_INFO("playerbot.v2", "[dungeon_cross] {} is set down at the exit ({:.1f},{:.1f},{:.1f}), {} y away", s.name(), tgx, tgy, tgz, uint32(dist_to_exit)); emit.near_teleport_to(tgx, tgy, tgz, s.raw().position.o); ai.clear_dungeon_cross(); ai.cross_hold_reset(); @@ -2016,8 +2090,9 @@ bool DungeonHonorCross(BotSnapshotView const& s, BotAI& ai, // bot in place). Force-complete the committed crossing onto its far exit — a real // navmesh poly on solid ground (same primitive/semantics as the stale-spline // relocate above; the off-mesh hop is an instantaneous jump, not a content skip). - if (can_teleport && cross_frozen > kCrossFrozenMs) // constant hoisted above + if (can_relocate && cross_frozen > kCrossFrozenMs) // constant hoisted above { + TC_LOG_INFO("playerbot.v2", "[dungeon_cross] {} is set down at the exit ({:.1f},{:.1f},{:.1f}), {} y away", s.name(), tgx, tgy, tgz, uint32(dist_to_exit)); emit.near_teleport_to(tgx, tgy, tgz, s.raw().position.o); ai.clear_dungeon_cross(); ai.cross_hold_reset(); @@ -2036,8 +2111,9 @@ bool DungeonHonorCross(BotSnapshotView const& s, BotAI& ai, // it jitters within it. Force-complete onto the exit (same primitive/semantics // as the relocates above; the off-mesh hop is an instantaneous jump). dist>6 // here always (past the landed check) so the detector ticks every honored frame. - if (can_teleport && ai.cross_window_noprogress(dist_to_exit, now_ms, 8000u, 9.0f)) + if (can_relocate && ai.cross_window_noprogress(dist_to_exit, now_ms, 8000u, 9.0f)) { + TC_LOG_INFO("playerbot.v2", "[dungeon_cross] {} is set down at the exit ({:.1f},{:.1f},{:.1f}), {} y away", s.name(), tgx, tgy, tgz, uint32(dist_to_exit)); emit.near_teleport_to(tgx, tgy, tgz, s.raw().position.o); ai.clear_dungeon_cross(); ai.cross_hold_reset(); @@ -2063,7 +2139,7 @@ bool DungeonHonorCross(BotSnapshotView const& s, BotAI& ai, // SKIPPED for a DIRECT (nav-link) crossing: NOPATH toward the exit is EXPECTED // across a real navmesh split — the straight no-pathfind spline below handles it, // and relocating here would replace the intended walk with a teleport. - if (can_teleport && !s.is_moving() && !ai.dungeon_cross_direct() && + if (can_relocate && !s.is_moving() && !ai.dungeon_cross_direct() && Playerbot::PathBudget::HasBudget(now_ms)) { if (Player* self = ObjectAccessor::FindConnectedPlayer(s.raw().guid)) @@ -2073,7 +2149,8 @@ bool DungeonHonorCross(BotSnapshotView const& s, BotAI& ai, PathType const pt = pg.GetPathType(); if (pt & (PATHFIND_NOPATH | PATHFIND_FARFROMPOLY)) { - emit.near_teleport_to(tgx, tgy, tgz, s.raw().position.o); + TC_LOG_INFO("playerbot.v2", "[dungeon_cross] {} is set down at the exit ({:.1f},{:.1f},{:.1f}), {} y away", s.name(), tgx, tgy, tgz, uint32(dist_to_exit)); + emit.near_teleport_to(tgx, tgy, tgz, s.raw().position.o); ai.clear_dungeon_cross(); ai.cross_hold_reset(); ai.set_last_rule_fired("dungeon_offmesh_cross_relocate"); @@ -2091,9 +2168,10 @@ bool DungeonHonorCross(BotSnapshotView const& s, BotAI& ai, // MovePoint spline — a pathfound move toward the far side of a real navmesh // split would NoPath and refuse (see MoveToIntent::direct). ai.set_dungeon_cross(tgx, tgy, tgz, now_ms + 12000); - emit.move_to(tgx, tgy, tgz, /*run=*/true, ai.dungeon_cross_direct()); - ai.set_last_rule_fired(ai.dungeon_cross_direct() ? "dungeon_navlink_cross_hold" - : "dungeon_offmesh_cross_hold"); + emit.move_to(tgx, tgy, tgz, /*run=*/true, ai.dungeon_cross_direct(), /*drop=*/ai.dungeon_cross_drop()); + ai.set_last_rule_fired(ai.dungeon_cross_drop() ? "dungeon_navlink_cross_fall" + : ai.dungeon_cross_direct() ? "dungeon_navlink_cross_hold" + : "dungeon_offmesh_cross_hold"); return true; } @@ -2153,31 +2231,13 @@ static bool DungeonTryUseGateGo(BotSnapshotView const& s, BotAI& ai, if (!advice.bosses.empty()) { bool boss_near_lever = false; - if (Player* scanner = ObjectAccessor::FindConnectedPlayer(s.raw().guid)) + // An alive listed boss within 40 y of the lever (the builder's scan_bosses; no grid walk on this thread). + for (auto const& b : s.raw().dungeon_exec.scan_bosses) { - struct AliveBossNearGo - { - std::vector const& entries; - float gx, gy, gz, r2; - bool operator()(Creature* c) const - { - if (!c || !c->IsAlive()) return false; - for (uint32_t e : entries) - if (c->GetEntry() == e) - { - const float ex = c->GetPositionX() - gx; - const float ey = c->GetPositionY() - gy; - const float ez = c->GetPositionZ() - gz; - return ex*ex + ey*ey + ez*ez <= r2; - } - return false; - } - }; - std::list bfound; - AliveBossNearGo bchk{advice.bosses, go.x, go.y, go.z, 40.0f * 40.0f}; - Trinity::CreatureListSearcher bsr(scanner, bfound, bchk); - Cell::VisitAllObjects(scanner, bsr, 80.0f); - boss_near_lever = !bfound.empty(); + if (std::find(advice.bosses.begin(), advice.bosses.end(), b.entry) == advice.bosses.end()) + continue; + const float ex = b.x - go.x, ey = b.y - go.y, ez = b.z - go.z; + if (ex * ex + ey * ey + ez * ez <= 40.0f * 40.0f) { boss_near_lever = true; break; } } // Latch the sighting through the caged boss's scan flicker. SFK // Baron Ashbury (a throne vehicle behind the closed Cell Door 18934) @@ -2276,28 +2336,112 @@ static bool DungeonTryUseGateGo(BotSnapshotView const& s, BotAI& ai, // path for the whole group. He clicks from the spot itself, not on the way to it: af39 clicked from the snapshot 6 y out while still // running in, the door stayed shut, and the one click per 5 min left him at it for the rest of the run. A door still shut 5 s after // a click is clicked again (BotAI DungeonHandDoor lockout); the refusals his route met at the shut door are forgotten with the click. +// A door the dungeon's route goes through is opened from farther off: the route's crumbs on either side of it can be consumed before +// the tank is within kHandDoorReachYd, and the next crumb, past the shut door, has no path. hot_full af61 (22 Nov): the tank stood +// 120 s at (297.8,-5.4), 15.5 y from the Vault Door 645393, every path to the crumb past it NoPath, and the run stalled. static constexpr float kHandDoorReachYd = 12.0f; // the tank stood 6-7 y from each Heavy Door when his path ended there static constexpr float kHandDoorFrontYd = 2.5f; // the spot he clicks from, this far from the door's centre on his side static constexpr float kHandDoorUseYd = 1.0f; // he clicks standing on that spot (the door's interaction reach is 5 y past its model) +static constexpr float kHandDoorRouteReachYd = 30.0f; +static constexpr float kHandDoorOnRouteYd = 5.0f; // the door's centre this close to a crumb-to-crumb leg: the route goes through it + +// Whether a leg of the dungeon's route passes through the door at (x, y, z). +static bool HandDoorOnRoute(std::vector const& route, float x, float y, float z) +{ + for (size_t i = 1; i < route.size(); ++i) + { + auto const& a = route[i - 1]; + auto const& b = route[i]; + if (std::fabs(a.z - z) > 6.0f && std::fabs(b.z - z) > 6.0f) + continue; + float const lx = b.x - a.x, ly = b.y - a.y; + float const l2 = lx * lx + ly * ly; + float t = l2 > 0.01f ? ((x - a.x) * lx + (y - a.y) * ly) / l2 : 0.f; + t = std::clamp(t, 0.f, 1.f); + float const ex = a.x + lx * t - x, ey = a.y + ly * t - y; + if (ex * ex + ey * ey <= kHandDoorOnRouteYd * kHandDoorOnRouteYd) + return true; + } + return false; +} + +// Whether (ax, ay) and (bx, by) are on the two sides of a door: the way through it runs along its facing (NearbyObject::o). +static bool AcrossDoor(BotSnapshot::NearbyObject const& go, float ax, float ay, float bx, float by) +{ + float const nx = std::cos(go.o), ny = std::sin(go.o); + float const da = (ax - go.x) * nx + (ay - go.y) * ny; + float const db = (bx - go.x) * nx + (by - go.y) * ny; + return (da < 0.f) != (db < 0.f); +} // A door that opens only to a key (NearbyObject::key_item: Dire Maul North's Gordok Courtyard and Inner Doors) is opened by the bot // that carries the key, whatever its role: the key goes to whoever looted it, and the tank's route ends at the shut door with the -// party beside him. The bot uses the key on the door from the same spot, as a player's right-click does. -static bool DungeonOpenHandDoor(BotSnapshotView const& s, BotAI& ai, BotIntentEmitter& emit, uint32 now_ms, bool tank) +// party beside him. The bot uses the key on the door from the same spot, as a player's right-click does. A door whose lock takes +// Lockpicking (NearbyObject::pick_lock: Alcaz Prison's Maximum Security Door) is opened the same way by the bot that has the skill, +// the rogue, with Pick Lock (API::use_game_object casts it; 5 s, and the bot holds still for it), as Karrz's rogue did on live. +// A door that shuts by itself (NearbyObject::auto_close: Alcaz Prison's Prison Gate 649552, shut again 3 s after a use) does not stay +// open for the party behind the tank: on live every player of the group opened it for himself (capture 26 Nov: eight opens in 2 min). +// The tank opens it only while the crumb he walks to lies beyond it (once through, the shut gate behind him is not his business), and +// each other bot opens it when it stands at it with the tank on the far side. +static bool DungeonOpenHandDoor(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, BotIntentEmitter& emit, + DungeonAdvice const& advice, uint32 now_ms, bool tank) { if (s.in_combat()) return false; + auto const& objects = s.raw().world_objects.nearby_objects; + // Picking the lock: hold still until the cast ends (a move breaks it). + if (s.is_casting() && !s.current_cast_object().IsEmpty()) + for (auto const& go : objects) + if (go.guid == s.current_cast_object() && go.pick_lock) + { + ai.set_last_rule_fired("idle:dungeon_pick_lock"); + return true; + } float sx = 0.f, sy = 0.f, sz = 0.f; s.position(sx, sy, sz); - for (auto const& go : s.raw().world_objects.nearby_objects) + for (auto const& go : objects) { if (!go.hand_door) continue; - if (!tank && go.key_item == 0) - continue; + bool const own = go.key_item != 0 || go.pick_lock; // a door only this bot opens: its key or its skill float const dx = sx - go.x, dy = sy - go.y; float const d = std::sqrt(dx * dx + dy * dy); - if (d > kHandDoorReachYd || std::fabs(sz - go.z) > 6.0f) + if (d > kHandDoorRouteReachYd || std::fabs(sz - go.z) > 6.0f) + continue; + if (go.auto_close && !own) + { + if (tank) + { + int32_t const cur = ai.dungeon_route_wp(s.map_id()); + if (cur < 0 || cur >= int32_t(advice.route_waypoints.size())) + continue; + auto const& wp = advice.route_waypoints[size_t(cur)]; + if (!AcrossDoor(go, sx, sy, wp.x, wp.y)) + continue; + } + else + { + if (d > kHandDoorReachYd) + continue; + GroupMemberSummary const* lead = nullptr; + if (auto const* members = g.members()) + for (GroupMemberSummary const& m : *members) + if (m.guid == s.group_tank() && m.online && m.map_id == s.map_id()) + lead = &m; + if (!lead || !AcrossDoor(go, sx, sy, lead->x, lead->y)) + continue; + } + } + else if (!tank && !own) + continue; + // Past kHandDoorReachYd only a door on the route, or, in a dungeon with no route (boss spots only), a door this bot owns with + // a boss spot beyond it: stratud_full (fullruns-1127) stalled 120 s with the tank 15.5 y from the Service Entrance Gate + // (175368, lock 879: the Key to the City he carries), Barthilas and the whole Undead wing on the far side, as his path to + // them ended short of the shut gate. + if (d > kHandDoorReachYd && !HandDoorOnRoute(advice.route_waypoints, go.x, go.y, go.z) && + !(own && advice.route_waypoints.empty() && + std::any_of(advice.progression_waypoints.begin(), advice.progression_waypoints.end(), + [&](DungeonAdvice::ProgressionPoint const& p) { return AcrossDoor(go, sx, sy, p.x, p.y); }))) continue; uint64 const go_low = go.guid.GetCounter(); if (ai.action_recently_tried(BotAI::ActionKind::DungeonHandDoor, go_low, now_ms)) @@ -2318,8 +2462,8 @@ static bool DungeonOpenHandDoor(BotSnapshotView const& s, BotAI& ai, BotIntentEm ai.note_action_retry(BotAI::ActionKind::DungeonHandDoor, go_low, now_ms); ai.clear_move_refusals(); ai.set_last_rule_fired("idle:dungeon_open_hand_door"); - TC_LOG_INFO("playerbot.v2", "[hand_door] {} opens entry={} guid={} at ({:.1f},{:.1f},{:.1f}) d={:.1f} key={}", - s.name(), go.entry, go_low, go.x, go.y, go.z, d, go.key_item); + TC_LOG_INFO("playerbot.v2", "[hand_door] {} opens entry={} guid={} at ({:.1f},{:.1f},{:.1f}) d={:.1f} key={} pick={} auto_close={}", + s.name(), go.entry, go_low, go.x, go.y, go.z, d, go.key_item, int(go.pick_lock), int(go.auto_close)); return true; } return false; @@ -2386,29 +2530,13 @@ static bool DungeonTryPortalHop(BotSnapshotView const& s, BotAI& ai, BotIntentEm Player* self = ObjectAccessor::FindConnectedPlayer(s.raw().guid); if (!self) continue; - // The boss beyond must still be alive and every boss that opens the portal dead: one map-wide scan (the instance is small; - // the same 500 y reach as the boss-priority advance). - struct HopBossCheck - { - DungeonAdvice::PortalHop const& hop; - bool operator()(Creature* c) const - { - if (!c || !c->IsAlive()) return false; - if (c->GetEntry() == hop.boss_entry) return true; - for (uint32_t e : hop.opened_by) - if (c->GetEntry() == e) return true; - return false; - } - }; - std::list found; - HopBossCheck chk{hop}; - Trinity::CreatureListSearcher searcher(self, found, chk); - Cell::VisitAllObjects(self, searcher, 500.0f); + // The boss beyond must still be alive and every boss that opens the portal dead: the builder's scan_bosses (500 y, the same + // reach as the boss-priority advance). bool beyond_alive = false, opener_alive = false; - for (Creature* c : found) + for (auto const& c : s.raw().dungeon_exec.scan_bosses) { - if (c->GetEntry() == hop.boss_entry) beyond_alive = true; - else opener_alive = true; + if (c.entry == hop.boss_entry) beyond_alive = true; + else if (std::find(hop.opened_by.begin(), hop.opened_by.end(), c.entry) != hop.opened_by.end()) opener_alive = true; } if (!beyond_alive || opener_alive) continue; @@ -2483,6 +2611,8 @@ static bool DungeonTryDoorTalk(BotSnapshotView const& s, BotAI& ai, BotIntentEmi if (!is_npc && !is_boss) opener_alive = true; } if (!npc || !beyond_alive || opener_alive) continue; + // A creature that speaks to one faction only is the other's enemy (Shadowfang Keep's two prisoners): nothing to say to it. + if (self->IsValidAttackTarget(npc)) continue; // A talk that waits for a door: the door must stand open (Bly after the End Door Weegli blows). if (talk.after_door) { @@ -2879,12 +3009,18 @@ static float PackAggroReach(BotSnapshotView const& s, NearbyUnit const& u) // false. With `ai`, also skip what idle:tank_pull_next refuses to pull (the // opener give-up shield, a refused StartAttack, a mob crowd-controlled by an // ally), so a mob the pull will never take cannot hold the advance forever. +// A boss is told by its flags or the dungeon's tactics table (IsKnownBossUnit, +// as the pull tells it): a five-man boss carries no boss flag (the loader +// strips it), only its tactics entry, and held as a pack it stopped the very +// advance and boss approach that would have opened it (rfd_full af58: +// Mordresh Fire Eye 26 y off, "advance yields to the pull" every 3 s, the +// pull refusing him as a boss, nobody moved for 120 s). static bool UnpulledPackMob(BotSnapshotView const& s, NearbyUnit const& u, DungeonAdvice const* advice, bool need_los, BotAI const* ai, uint32 now_ms) { if (u.hp <= 0 || u.is_player || u.untargetable || u.is_pacified || u.no_xp_kill) return false; if (!u.victim.IsEmpty() || u.unit_in_combat) return false; - if (Classic::IsBossUnit(u)) return false; + if (IsKnownBossUnit(s.map_id(), u)) return false; if (need_los && !u.in_los) return false; if (advice) for (uint32_t ie : advice->ignore_entries) @@ -4693,15 +4829,27 @@ static std::mutex g_pull_spot_mu; struct PullSpotWalk { uint64 pack = 0; uint32 since = 0; uint32 last = 0; }; static std::unordered_map g_pull_spot_walk; constexpr uint32 kPullSpotGapMs = 10000u; -// A listed boss the bot can fight now: alive, and a valid attack target for it. A boss that stands immune or unselectable until an -// event the bots do not run is not the next pull: with it in the boss scans the tank walked up to it and "pulled" it every 30 s -// while the attack never took (the snapshot has no such enemy). eea74327b3 uldaman_revelosh: Baelog (6906, the Lost Dwarves) at -// 23 y in sight, 120 s group_stalled; b3ca0b4b67 st_mijan: Weaver (5720), whom the Classic troll-guard event frees, 120 s stalled. -// Left out of the scans, the owed-boss waiver (8 s at its waypoint, unsighted) moves the route on, and a boss that turns -// attackable is back in the scans and owed again. -static bool BossFightable(Player const* origin, Creature const* c) +// The earliest boss of `bosses` (authored in encounter order) the bot can fight now within `range` yards: the builder's scan_bosses +// (DungeonExecState::ScanUnit, collected while no map updates; the rules run on the bot workers, where a grid walk races the map +// thread). A boss that stands immune or unselectable until an event the bots do not run is not fightable (BotSnapshotBuilder +// BossFightable), so it is no pull; a boss asleep until a player comes near (Rath'mael 250657) is. +static DungeonExecState::ScanUnit const* EarliestFightableBoss(BotSnapshotView const& s, std::vector const& bosses, + float range, int* idx_out = nullptr) { - return c && c->IsAlive() && origin->IsValidAttackTarget(c); + float sx, sy, sz; s.position(sx, sy, sz); + auto const& found = s.raw().dungeon_exec.scan_bosses; + for (int bi = 0; bi < static_cast(bosses.size()); ++bi) + for (auto const& u : found) + { + if (!u.fightable || u.entry != bosses[bi]) + continue; + const float dx = u.x - sx, dy = u.y - sy, dz = u.z - sz; + if (dx * dx + dy * dy + dz * dz > range * range) + continue; + if (idx_out) *idx_out = bi; + return &u; + } + return nullptr; } static uint32 PullSpotWalkFor(ObjectGuid tank, uint64 pack, uint32 now_ms) { @@ -4982,6 +5130,35 @@ static bool RaidFrontalConeStep(BotSnapshotView const& s, BotAI& ai, GroupSnapsh return false; } +bool BreathDue(BotSnapshotView const& s, BotAI& ai) +{ + bool const was = ai.breath_refilling(); + bool const up = s.is_alive() && ai.needs_air(s.breath_left_ms()); + if (up != was) + { + float bx, by, bz; s.position(bx, by, bz); + if (up) + TC_LOG_INFO("playerbot.v2", "[breath] {} goes up for air: {} ms of breath left at z {:.1f} (surface {:.1f}){}", s.name(), + s.breath_left_ms(), bz, s.water_surface_z(), s.in_combat() ? ", in a fight" : ""); + else + TC_LOG_INFO("playerbot.v2", "[breath] {} has its breath back at z {:.1f}", s.name(), bz); + } + return up; +} + +bool SurfaceForAir(BotSnapshotView const& s, BotAI& ai, BotIntentEmitter& emit, char const* rule) +{ + if (!BreathDue(s, ai)) + return false; + float bx, by, bz; s.position(bx, by, bz); + if (s.is_underwater() && s.water_surface_z() != 0.0f && bz < s.water_surface_z() - 0.5f) + emit.move_to(bx, by, s.water_surface_z() + 0.5f, /*run*/ true); + else if (s.is_moving()) + emit.stop_movement(); // head out: it stays up until the bar is full (3.5 s from 25 s left), not straight back down + ai.set_last_rule_fired(rule); + return true; +} + bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, BotIntentEmitter& emit, @@ -5003,20 +5180,13 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, // the idle dispatch AND the top of DispatchInCombat, so re-admitting the // surface move HERE makes it preempt all positioning/advance/combat — drowning // kills regardless of combat state, so it must run first. Surfaces in place - // (same XY, just above the water line); the bot then swims the surface instead - // of sinking. Mirrors SurvivalRules SurfaceToBreatheGate/Fire. (Latent-bug fix + // (same XY, just above the water line). On the server's breath timer, like + // idle:surface_to_breathe (SurfaceForAir): it used to lift every submerged bot + // at once, whatever breath it had left. (Latent-bug fix // found chasing the Deadmines harbor wall — which turned out NOT to be water, // but this is still correct for any future water dungeon.) - if (s.is_underwater() && s.water_surface_z() != 0.0f) - { - float sbx, sby, sbz; s.position(sbx, sby, sbz); - if (sbz < s.water_surface_z() - 0.5f) - { - emit.move_to(sbx, sby, s.water_surface_z() + 0.5f, /*run=*/true); - ai.set_last_rule_fired("idle:dungeon_surface_to_breathe"); - return true; - } - } + if (SurfaceForAir(s, ai, emit, "idle:dungeon_surface_to_breathe")) + return true; // SURVIVAL PREEMPT — REPAIR BROKEN GEAR (2026-06-29). A self-repair rule // already exists, but it sits at the FAR TAIL of the dungeon idle dispatch @@ -5078,7 +5248,7 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, DungeonEnterAreaTriggers(s, ai, emit, advice, now_ms); if (tank && DungeonOpenKeyChest(s, ai, emit, now_ms)) return true; - if (DungeonOpenHandDoor(s, ai, emit, now_ms, tank)) + if (DungeonOpenHandDoor(s, ai, g, emit, advice, now_ms, tank)) return true; if (DungeonTryKeyUse(s, ai, emit, advice, now_ms, tank)) return true; @@ -5122,6 +5292,203 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, if (RaidHazardStepOut(s, ai, g, emit)) return true; + // (-0.55) Keep clear of a carrier (DungeonAdvice::keep_clear_of_carriers): a member carrying an aura that hurts whoever stands + // next to it, and cannot walk off itself. shapers_full af61 (22 Nov): all five stood within 5 y of Cinder, his Conflagration + // 1310512 confused one of them for 4 s, every second burned every ally within 5 y of that one for 300, and the mage died at + // 8% health. Everyone else steps out to radius + 2 y on the line away from the carrier; the carrier is left to it. + if (!advice.keep_clear_of_carriers.empty() && g.exists() && !s.is_rooted() && !HeldByOwner(ai, s)) + { + bool self_carries = false; + for (auto const& rule : advice.keep_clear_of_carriers) + if (s.has_aura(rule.aura)) { self_carries = true; break; } + auto const* cmems = g.members(); + if (!self_carries && cmems) + { + float kx, ky, kz; s.position(kx, ky, kz); + GroupMemberSummary const* carrier = nullptr; + float carrier_r = 0.f, carrier_d2 = 0.f; + uint32 carrier_aura = 0; + for (auto const& m : *cmems) + { + if (m.guid == s.guid() || !m.online || !m.is_alive || m.map_id != s.map_id()) + continue; + for (auto const& rule : advice.keep_clear_of_carriers) + { + bool carries = false; + for (auto const& d : m.debuffs) + if (d.spell_id == rule.aura) { carries = true; break; } + if (!carries) + continue; + float const cdx = kx - m.x, cdy = ky - m.y; + float const d2 = cdx * cdx + cdy * cdy; + if (d2 < rule.radius * rule.radius && (!carrier || d2 < carrier_d2)) + { carrier = &m; carrier_r = rule.radius; carrier_d2 = d2; carrier_aura = rule.aura; } + } + } + if (carrier) + { + float ax = kx - carrier->x, ay = ky - carrier->y; + float alen = std::sqrt(ax * ax + ay * ay); + if (alen < 0.5f) + { + // On top of the carrier: out on the side away from what it fights (the bot's target), else any side. + ax = 1.f; ay = 0.f; alen = 1.f; + if (NearbyUnit const* foe = s.target_info() ? s.target_info() : s.victim_info()) + { + float const fx = carrier->x - foe->x, fy = carrier->y - foe->y, fl = std::sqrt(fx * fx + fy * fy); + if (fl > 0.5f) { ax = fx; ay = fy; alen = fl; } + } + } + float const out = carrier_r + 2.0f; + float const tx = carrier->x + ax / alen * out, ty = carrier->y + ay / alen * out; + emit.move_to(tx, ty, kz, /*run=*/true); + static std::mutex s_clearLogMu; + static std::unordered_map s_clearLogAt; + { + std::lock_guard lk(s_clearLogMu); + uint32& at = s_clearLogAt[s.guid().GetCounter()]; + if (at == 0 || now_ms - at >= 3000u) + { + at = now_ms ? now_ms : 1u; + TC_LOG_INFO("playerbot.v2", "[carrier_clear] {} steps {:.1f} y clear of a member carrying {} ({:.1f} y from it) -> ({:.1f},{:.1f})", + s.name(), out, carrier_aura, std::sqrt(carrier_d2), tx, ty); + } + } + ai.set_last_rule_fired("dungeon:keep_clear_of_carrier"); + return true; + } + } + } + + // (-0.5) Spread from a boss's splash (DungeonAdvice::spread_from_bosses): the boss's spell lands on one player and hurts every + // ally within the radius of that player. shapers_full af63 (23 Nov): Vitrix's Poison Shock 1312870 hit the priest at 6.5 y and + // the mage at 10.1 y from him for 1269 and 1470 in one cast, after the priest had healed the whole stack through every cast + // before it (out of mana at 1790 s). The ranged members and the healer stand on a ring round the boss, radius + 2 y from every + // other member and from the spots the others are walking to; the tank and the melee stay on the boss. + if (!advice.spread_from_bosses.empty() && s.in_combat() && g.exists() && !s.is_rooted() && !HeldByOwner(ai, s) && + InstanceRangedOrHealer(s, ai)) + { + NearbyUnit const* sboss = nullptr; + float sradius = 0.f; + for (auto const* list : { &s.raw().combat.attackers, &s.raw().combat.nearby_enemies }) + { + for (NearbyUnit const& u : *list) + { + if (u.hp <= 0) + continue; + for (auto const& rule : advice.spread_from_bosses) + if (u.entry == rule.boss) { sboss = &u; sradius = rule.radius; break; } + if (sboss) break; + } + if (sboss) break; + } + auto const* smems = g.members(); + Player* sself = sboss && smems ? ObjectAccessor::FindConnectedPlayer(s.raw().guid) : nullptr; + if (sself) + { + // Where each bot of the group is walking to for the spread, so two of them do not pick the same patch of the ring. + struct SpreadSpot { float x = 0.f, y = 0.f; uint32 ms = 0; uint64 group = 0; }; + static std::mutex s_spreadMu; + static std::unordered_map s_spreadSpots; + constexpr uint32 kSpotKeepMs = 6000u; + uint64 const gkey = s.group_guid().GetCounter(); + uint64 const me = s.guid().GetCounter(); + float sx, sy, sz; s.position(sx, sy, sz); + float const keep = sradius + 2.0f; + std::vector> others; // the other members' spots: where they stand, and where they are going + for (auto const& m : *smems) + if (m.guid != s.guid() && m.online && m.is_alive && m.map_id == s.map_id()) + others.emplace_back(m.x, m.y); + SpreadSpot mine; + { + std::lock_guard lk(s_spreadMu); + for (auto const& [who, spot] : s_spreadSpots) + { + if (spot.group != gkey || now_ms - spot.ms >= kSpotKeepMs) + continue; + if (who == me) mine = spot; + else others.emplace_back(spot.x, spot.y); + } + } + auto clear_of_others = [&](float x, float y, float need) { + for (auto const& [ox, oy] : others) + if ((x - ox) * (x - ox) + (y - oy) * (y - oy) < need * need) + return false; + return true; + }; + // Standing clear now (the radius itself, so a member passing 1 y too near does not set off a walk): nothing to do. A spot + // still being walked to that is still clear is kept, so the bot does not swap spots on every tick of the walk. + bool const here_clear = clear_of_others(sx, sy, sradius); + bool const spot_kept = mine.ms != 0 && clear_of_others(mine.x, mine.y, keep) && + (mine.x - sx) * (mine.x - sx) + (mine.y - sy) * (mine.y - sy) > 2.0f * 2.0f; + if (!here_clear && !spot_kept) + { + // The ring: 16 bearings at three distances from the boss, inside every class's spell range of it (30 y less the + // margin), nearest to the bot first; the first that is clear of the others, has ground near the boss's level, is in + // sight of the boss and can be walked to is taken. + struct Cand { float x, y, d2; }; + std::vector cands; + float const rings[] = { std::max(keep + 2.0f, 14.0f), 20.0f, 25.0f }; + for (float r : rings) + for (int k = 0; k < 16; ++k) + { + float const a = float(k) * 0.39269908f; // pi / 8 + float const cx = sboss->x + r * std::cos(a), cy = sboss->y + r * std::sin(a); + if (!clear_of_others(cx, cy, keep)) + continue; + cands.push_back({ cx, cy, (cx - sx) * (cx - sx) + (cy - sy) * (cy - sy) }); + } + std::sort(cands.begin(), cands.end(), [](Cand const& a, Cand const& b) { return a.d2 < b.d2; }); + int tries = 0; + for (Cand const& c : cands) + { + if (++tries > 6) + break; + float floor_z = 0.f; + if (!BotMovement::ProbeGround(sself, c.x, c.y, sboss->z + 2.0f, floor_z) || std::fabs(floor_z - sboss->z) > 4.0f) + continue; + if (!BotMovement::LineIsClear(sself, c.x, c.y, floor_z + 1.5f, sboss->x, sboss->y, sboss->z + 1.5f)) + continue; + G3D::Vector3 step; + if (!DungeonTargetReachableAndStep(sself, c.x, c.y, floor_z, 30.0f, step)) + continue; + { + std::lock_guard lk(s_spreadMu); + s_spreadSpots[me] = { c.x, c.y, now_ms ? now_ms : 1u, gkey }; + } + emit.move_to(step.x, step.y, step.z, /*run=*/true); + static std::mutex s_spreadLogMu; + static std::unordered_map s_spreadLogAt; + { + std::lock_guard lk(s_spreadLogMu); + uint32& at = s_spreadLogAt[me]; + if (at == 0 || now_ms - at >= 3000u) + { + at = now_ms ? now_ms : 1u; + TC_LOG_INFO("playerbot.v2", "[boss_spread] {} spreads from {} ({:.0f} y splash): ({:.1f},{:.1f}) -> ({:.1f},{:.1f}), " + "{:.1f} y from the boss", s.name(), sboss->entry, sradius, sx, sy, c.x, c.y, + std::sqrt((c.x - sboss->x) * (c.x - sboss->x) + (c.y - sboss->y) * (c.y - sboss->y))); + } + } + ai.set_last_rule_fired("dungeon:spread_from_boss"); + return true; + } + } + else if (!here_clear && spot_kept) + { + G3D::Vector3 step; + float floor_z = sz; + BotMovement::ProbeGround(sself, mine.x, mine.y, sboss->z + 2.0f, floor_z); + if (DungeonTargetReachableAndStep(sself, mine.x, mine.y, floor_z, 30.0f, step)) + { + emit.move_to(step.x, step.y, step.z, /*run=*/true); + ai.set_last_rule_fired("dungeon:spread_from_boss"); + return true; + } + } + } + } + // (-0.4) Dungeon FALSE-COMBAT escape — LAST-RESORT safety net. The whole COHERED // group can be held InCombat indefinitely by attackers with NO seedable victim // among them: every attacker IGNORED, UNTARGETABLE, or IMMUNE. In Deadmines the @@ -5194,10 +5561,10 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, // single residual/re-introduced mis-authored faction can never again // pin the whole group InCombat with nothing killable. Checked before // the (expensive) reachability probe so immune attackers short-circuit. - if (self_seed) - if (Unit* au = ObjectAccessor::GetUnit(*self_seed, a.guid)) - if (!self_seed->IsValidAttackTarget(au)) - { immune_present = true; continue; } + // The builder reads IsValidAttackTarget (NearbyUnit::valid_attack_target): this rule runs on a bot worker, where + // looking the unit up in the map's object store races the map thread. + if (!a.valid_attack_target) + { immune_present = true; continue; } if (self_seed) { G3D::Vector3 _seed_step; @@ -5409,12 +5776,12 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, bool const probe_due = now_ms - ai.untankable_probe_last_ms() >= 3000u; if (!trivially_close && probe_due) - if (Player* tkp = ObjectAccessor::FindConnectedPlayer(tk->guid)) + if (Player* selfp = ObjectAccessor::FindConnectedPlayer(s.guid())) { ai.touch_untankable_probe(now_ms); float dv_beeline = 0.f, dv_path_len = 0.f, dv_ratio = 0.f; bool dv_complete = false; - if (DungeonTankDetourExcessiveVerbose(tkp, vu->x, vu->y, vu->z, + if (DungeonWalkDetourExcessiveVerboseFrom(selfp, tk->x, tk->y, tk->z, vu->x, vu->y, vu->z, dv_beeline, dv_path_len, dv_ratio, dv_complete)) { @@ -5476,33 +5843,20 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, { if (Player* self_pb = ObjectAccessor::FindConnectedPlayer(s.raw().guid)) { - struct PushBossCheck - { - Player const* origin; - std::vector const& entries; - float range; - bool operator()(Creature* c) const - { - if (!BossFightable(origin, c)) return false; - for (uint32_t e : entries) - if (c->GetEntry() == e) - return origin->IsWithinDistInMap(c, range); - return false; - } - }; // Commit range: only push in-combat when the boss is genuinely close. // The long OOC approach (waypoints / idle boss-nav) covers the rest. + // The builder's scan_bosses: no grid walk on this thread (see DungeonExecState::ScanUnit). constexpr float kPbScanR = 150.0f; - std::list pb_cre; - PushBossCheck pb_chk{self_pb, advice.bosses, kPbScanR}; - Trinity::CreatureListSearcher pb_search(self_pb, pb_cre, pb_chk); - Cell::VisitAllObjects(self_pb, pb_search, kPbScanR); - Creature* pb_boss = nullptr; + float pbsx, pbsy, pbsz; s.position(pbsx, pbsy, pbsz); + DungeonExecState::ScanUnit const* pb_boss = nullptr; int pb_idx = -1; for (int bi = 0; bi < static_cast(advice.bosses.size()) && !pb_boss; ++bi) - for (Creature* bc : pb_cre) - if (bc && bc->GetEntry() == advice.bosses[bi] && bc->IsAlive()) - { pb_boss = bc; pb_idx = bi; break; } + for (auto const& bc : s.raw().dungeon_exec.scan_bosses) + { + const float ux = bc.x - pbsx, uy = bc.y - pbsy, uz = bc.z - pbsz; + if (bc.fightable && bc.entry == advice.bosses[bi] && ux * ux + uy * uy + uz * uz <= kPbScanR * kPbScanR) + { pb_boss = &bc; pb_idx = bi; break; } + } // Only the boss the tank owes, as the boss navigator below has it (bosses[bosses_done_count], raised by the owed-boss // waiver). A later boss in the scan while the owed one is out of it is the navigator's case: it walks to the owed boss's // waypoint and waives it there. Pushing to the later boss here pulled the tank the other way on every other tick @@ -5520,7 +5874,7 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, { if (RaidLogDue(RaidLogKey(s, RaidLogKind::Los) ^ 0x6f776564u, now_ms, 10000u)) TC_LOG_INFO("playerbot.v2", "[boss_push] {} no push to boss {} (idx {}): owed boss idx {} (entry {}) is not in sight", - s.name(), pb_boss->GetEntry(), pb_idx, pb_owed, advice.bosses[pb_owed]); + s.name(), pb_boss->entry, pb_idx, pb_owed, advice.bosses[pb_owed]); pb_boss = nullptr; } } @@ -5528,9 +5882,9 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, { if (s.is_in_raid()) Classic::NoteBossPullWait(s.group_guid()); // the healers drink to the boss mark while the tank waits - const float pbx = pb_boss->GetPositionX(); - const float pby = pb_boss->GetPositionY(); - const float pbz = pb_boss->GetPositionZ(); + const float pbx = pb_boss->x; + const float pby = pb_boss->y; + const float pbz = pb_boss->z; float sx0, sy0, sz0; s.position(sx0, sy0, sz0); const float ddx = pbx - sx0, ddy = pby - sy0, ddz = pbz - sz0; const float bd2 = ddx * ddx + ddy * ddy + ddz * ddz; @@ -5576,7 +5930,9 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, const float mdx = m.x - sx0, mdy = m.y - sy0; const float d2 = mdx * mdx + mdy * mdy; if (d2 < healer_d2) healer_d2 = d2; - if (PullManaGate(s, ai, g) && m.max_mana > 0 && int64(m.mana) * 100 < int64(m.max_mana) * Classic::PullReadyHealerManaPct(s)) + // Before a boss the leading tank of a player's five-man waits for a dry healer too (PullManaGate has no trash wait there). + if ((PullManaGate(s, ai, g) || ai.tank_leads_here(s)) && m.max_mana > 0 && + int64(m.mana) * 100 < int64(m.max_mana) * PullHealerManaMark(s, ai)) { healer_dry = true; healer_dry_name = m.name; @@ -5627,7 +5983,7 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, int near_hostiles = 0; for (auto const& u : s.raw().combat.nearby_enemies) { - if (u.hp <= 0 || u.no_xp_kill || u.is_pacified || Classic::IsBossUnit(u) || u.untargetable) + if (u.hp <= 0 || u.no_xp_kill || u.is_pacified || IsKnownBossUnit(s.map_id(), u) || u.untargetable) continue; bool ign = false; for (uint32_t ie : advice.ignore_entries) @@ -5643,23 +5999,23 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, // the gauntlet (no trigger units there), so no pull-pacing change. const bool pack_clear = s.fightable_attackers_count() < 3 && near_hostiles < 4 && s.hp_pct() > 35; - if (bd2 <= kPbEngageR2 && self_pb->IsWithinLOSInMap(pb_boss)) + if (bd2 <= kPbEngageR2 && pb_boss->in_los) { // On top of the boss: pull it (start the encounter) — but only // with the healer in range so the tank isn't soloing the open. // When the healer lags it falls through and holds near the boss // until heals arrive, then pulls. // Only a hold: with the tank already in a fight nothing is being pulled, and the line read as a pull below the mark. - if (healer_dry && !s.in_combat() && s.victim() != pb_boss->GetGUID() && ai.tank_diag_due(now_ms)) + if (healer_dry && !s.in_combat() && s.victim() != pb_boss->guid && ai.tank_diag_due(now_ms)) TC_LOG_INFO("playerbot.v2", "[pull_gate] {} holds the boss pull: healer {} at {}% mana (needs {}%); the tank is {:.0f}y from the boss", - s.name(), healer_dry_name, healer_dry_pct, Classic::PullReadyHealerManaPct(s), std::sqrt(bd2)); + s.name(), healer_dry_name, healer_dry_pct, PullHealerManaMark(s, ai), std::sqrt(bd2)); // One start_attack per lockout window: with the trash already on the group the victim is not the boss on // any tick, so the pull re-fired every tick (deadmines_full run 9: 42 "pulls the boss" lines) and fought // the loose-mob pick-up for the tank's victim. - uint64 const pull_key = pb_boss->GetGUID().GetCounter(); + uint64 const pull_key = pb_boss->guid.GetCounter(); // The mana users' wait: at most kBossDpsDrinkCapMs from the first tick the tank stood at the boss. bool dps_wait = false; - if (boss_dps_dry && s.victim() != pb_boss->GetGUID()) + if (boss_dps_dry && s.victim() != pb_boss->guid) { constexpr uint32 kBossDpsDrinkCapMs = 60000; static std::mutex boss_wait_mu; @@ -5677,7 +6033,7 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, // The hold is made away from the boss: standing at its door (deadmines_full@sneed: 4-5 y from the Shredder, "holds the boss // pull" while the fight went on) keeps the group in combat range, and nobody can sit and drink there. The tank walks back // to the dry healer, out of the room, and the advance stays shut until she is above the mark (healer_in_adv). - if (healer_dry && !s.in_combat() && s.victim() != pb_boss->GetGUID()) + if (healer_dry && !s.in_combat() && s.victim() != pb_boss->guid) { const float bx = healer_dry_x - sx0, by = healer_dry_y - sy0; if (bx * bx + by * by > 8.0f * 8.0f && emit.move_to(healer_dry_x, healer_dry_y, healer_dry_z, /*run*/ false)) @@ -5692,22 +6048,22 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, // A boss not yet in the fight is pulled once the trash on the tank is dead, not on top of it: sfk_rethilgore RC3, // the tank pulled Rethilgore three times with a Whitescalp and a Bleak Worg still on it, the boss came in at 18:08:23 // with both adds alive, and the priest went from 100 % to 28 % mana in 30 s (healer_oom at 110 s and 134 s). - const bool trash_on_tank = !pb_boss->IsInCombat() && s.fightable_attackers_count() > 0; - if (trash_on_tank && healer_in_pull && s.victim() != pb_boss->GetGUID() && ai.tank_diag_due(now_ms)) + const bool trash_on_tank = !pb_boss->in_combat && s.fightable_attackers_count() > 0; + if (trash_on_tank && healer_in_pull && s.victim() != pb_boss->guid && ai.tank_diag_due(now_ms)) TC_LOG_INFO("playerbot.v2", "[pull_gate] {} holds the boss pull: {} mob(s) still on the tank", s.name(), s.fightable_attackers_count()); // Raid lead: the boss is the player's to pull (LeadHoldsBossPull). - if (healer_in_pull && !dps_wait && !trash_on_tank && s.victim() != pb_boss->GetGUID() && - LeadHoldsBossPull(s, ai, emit, pb_boss->GetGUID(), now_ms)) + if (healer_in_pull && !dps_wait && !trash_on_tank && s.victim() != pb_boss->guid && + LeadHoldsBossPull(s, ai, emit, pb_boss->guid, now_ms)) return true; - if (healer_in_pull && !dps_wait && !trash_on_tank && s.victim() != pb_boss->GetGUID() && + if (healer_in_pull && !dps_wait && !trash_on_tank && s.victim() != pb_boss->guid && !ai.action_recently_tried(BotAI::ActionKind::PveTargetSwitch, pull_key, now_ms) && - emit.start_attack(pb_boss->GetGUID())) + emit.start_attack(pb_boss->guid)) { ai.note_action_retry(BotAI::ActionKind::PveTargetSwitch, pull_key, now_ms); TC_LOG_INFO("playerbot.v2", "[pull_gate] {} pulls the boss: {} healer in range, healer mana {}%", s.name(), have_healer ? "a" : "no", healer_min_pct > 100 ? -1 : healer_min_pct); - ai.note_engage(pb_boss->GetGUID(), now_ms); + ai.note_engage(pb_boss->guid, now_ms); ai.set_last_rule_fired("idle:dungeon_combat_pull_boss"); return true; } @@ -5916,36 +6272,11 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, { if (Player* self_w = ObjectAccessor::FindConnectedPlayer(s.raw().guid)) { - struct WideBossCheck - { - Player const* origin; - std::vector const& entries; - float range; - bool operator()(Creature* c) const - { - if (!BossFightable(origin, c)) return false; - for (uint32_t e : entries) - if (c->GetEntry() == e) - return origin->IsWithinDistInMap(c, range); - return false; - } - }; constexpr float kWideScanR = 500.0f; // whole-dungeon constexpr float kWedgeStep = 20.0f; // matches kMaxAdvanceStep - std::list wcre; - WideBossCheck wchk{self_w, advice.bosses, kWideScanR}; - Trinity::CreatureListSearcher wsearch(self_w, wcre, wchk); - Cell::VisitAllObjects(self_w, wsearch, kWideScanR); // Earliest live boss in progression order (advice.bosses authored - // in encounter order) — never skip ahead to a later boss. - Creature* wboss = nullptr; - for (uint32_t bentry : advice.bosses) - { - for (Creature* bc : wcre) - if (bc && bc->GetEntry() == bentry && bc->IsAlive()) - { wboss = bc; break; } - if (wboss) break; - } + // in encounter order), never skipping ahead to a later boss. + DungeonExecState::ScanUnit const* wboss = EarliestFightableBoss(s, advice.bosses, kWideScanR); if (wboss) { float wsx, wsy, wsz; s.position(wsx, wsy, wsz); @@ -6088,9 +6419,9 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, (!harbor_floor || s.fightable_attackers_count() == 0); if (!harbor_hold && (ghost_push || segmented_push)) { - const float wbx = wboss->GetPositionX(); - const float wby = wboss->GetPositionY(); - const float wbz = wboss->GetPositionZ(); + const float wbx = wboss->x; + const float wby = wboss->y; + const float wbz = wboss->z; // Incremental off-mesh-aware progress step (idle navigator's // far-boss tier). The net-progress gate inside the helper // keeps this INERT at a true navmesh disconnect. @@ -7633,27 +7964,50 @@ static bool DungeonNavLinkHop(Player* self, G3D::Vector3& step_out, bool* step_i End const ends[2] = { { l.ax, l.ay, l.az, l.bx, l.by, l.bz }, { l.bx, l.by, l.bz, l.ax, l.ay, l.az } }; int const n = l.bidirectional ? 2 : 1; + // The bot hops from the mouth it stands at: the end nearer to it, and only when the far end is further off than that + // mouth. A link shorter than its radius has the bot inside both mouths' radius (WC's Serpentis cliff link 1: its ends + // are 10.6 y apart, radius 12): the first end in the row won, and a bot standing on the far end "hopped" to where it + // stood, which spent its hop cooldown, and never crossed (wc_full chain69b, 23 Nov: the four behind the tank hopped + // (-289.1,3.2)->(-288.2,-6.2) standing at (-288.2,-6.2), then followed incomplete paths away; the run stalled). + int from = -1; + float from_d2 = 0.f; for (int d = 0; d < n; ++d) { const float dx = sx - ends[d].x, dy = sy - ends[d].y, dz = sz - ends[d].z; - if (dx*dx + dy*dy + dz*dz > l.radius * l.radius) continue; - if (!Playerbot::Services::Dungeons().TryClaimLinkHop( - self->GetGUID().GetCounter(), l.id, now_ms)) - continue; - if (Playerbot::BotAI* ai = Playerbot::Services::Registry().ai( - self->GetGUID().GetCounter())) - { - ai->set_dungeon_cross(ends[d].ox, ends[d].oy, ends[d].oz, now_ms + 12000); - ai->set_dungeon_cross_direct(true); - } - step_out = G3D::Vector3(ends[d].ox, ends[d].oy, ends[d].oz); - *step_is_offmesh = true; - TC_LOG_INFO("playerbot.v2", - "[nav_link] {} hop link {} reason={} ({:.1f},{:.1f},{:.1f})->({:.1f},{:.1f},{:.1f})", - self->GetName(), l.id, reason, ends[d].x, ends[d].y, ends[d].z, - ends[d].ox, ends[d].oy, ends[d].oz); - return true; + const float d2 = dx*dx + dy*dy + dz*dz; + if (d2 > l.radius * l.radius) continue; + if (from < 0 || d2 < from_d2) { from = d; from_d2 = d2; } } + if (from >= 0) + { + const float fx = sx - ends[from].ox, fy = sy - ends[from].oy, fz = sz - ends[from].oz; + if (fx*fx + fy*fy + fz*fz <= from_d2) + from = -1; // already at (or beyond) the far end: no crossing to make from here + } + if (from < 0) + continue; + End const& e = ends[from]; + if (!Playerbot::Services::Dungeons().TryClaimLinkHop( + self->GetGUID().GetCounter(), l.id, now_ms)) + continue; + if (Playerbot::BotAI* ai = Playerbot::Services::Registry().ai( + self->GetGUID().GetCounter())) + { + ai->set_dungeon_cross(e.ox, e.oy, e.oz, now_ms + 12000); + ai->set_dungeon_cross_direct(true); + // A one-way link that goes down a long way is a jump off a ledge: the bot falls it (a jump spline under gravity), as a + // player does. The Shaper's Terrace lands players on a ledge 54 y over a pool; a straight walk to the pool took 9 s + // through the air. A short one-way step down (WC's serpentine ledge, 14 y) keeps the straight move it was verified with. + constexpr float kLinkFallMinDrop = 20.0f; + ai->set_dungeon_cross_drop(!l.bidirectional && e.z - e.oz >= kLinkFallMinDrop); + ai->set_dungeon_cross_link_len(std::sqrt((e.ox - e.x) * (e.ox - e.x) + (e.oy - e.y) * (e.oy - e.y) + (e.oz - e.z) * (e.oz - e.z))); + } + step_out = G3D::Vector3(e.ox, e.oy, e.oz); + *step_is_offmesh = true; + TC_LOG_INFO("playerbot.v2", + "[nav_link] {} hop link {} reason={} ({:.1f},{:.1f},{:.1f})->({:.1f},{:.1f},{:.1f})", + self->GetName(), l.id, reason, e.x, e.y, e.z, e.ox, e.oy, e.oz); + return true; } return false; } @@ -7721,13 +8075,17 @@ static bool DungeonTargetReachableAndStep(Player* self, float tx, float ty, floa self->GetPositionY() > -560.0f && self->GetPositionY() < -500.0f; auto gapLog = [&](char const* where, float sx, float sy, float sz, bool off) { - if (!gapDbg) return; + // Any map: an off-mesh step more than 30 y from the bot, which the caller commits as a crossing (sfk_full af59: a crossing to + // Razorclaw's spot 135 y off, and nothing said which branch made it). + const float fx = sx - self->GetPositionX(), fy = sy - self->GetPositionY(), fz = sz - self->GetPositionZ(); + bool const far_off = off && fx * fx + fy * fy + fz * fz > 30.0f * 30.0f; + if (!gapDbg && !far_off) return; static uint32 s_gms = 0; const uint32 gn = GameTime::GetGameTimeMS(); if (gn - s_gms < 1000u) return; s_gms = gn; TC_LOG_INFO("playerbot.v2", - "[gap_step] {} ret={} t=0x{:X} step=({:.1f},{:.1f},{:.1f}) off={} " + "[gap_step] {} ret={} t=0x{:X} pts={} step=({:.1f},{:.1f},{:.1f}) off={} " "self=({:.1f},{:.1f},{:.1f}) tgt=({:.1f},{:.1f},{:.1f})", - self->GetName(), where, uint32(t), sx, sy, sz, off, + self->GetName(), where, uint32(t), pg.GetPath().size(), sx, sy, sz, off, self->GetPositionX(), self->GetPositionY(), self->GetPositionZ(), tx, ty, tz); }; // Why a dungeon step was refused, once per bot per 5 s: the path type, its points and where it ended. sfk_rethilgore (0.1.26 @@ -7876,7 +8234,12 @@ static bool DungeonTargetReachableAndStep(Player* self, float tx, float ty, floa // step to the Glutton, 165 y off down the hill, came back as such a line, and the tank walked the whole hill // under dungeon_offmesh_cross_hold, a crossing that never yields to a fight while it moves, and died to the ghouls behind it in // 23 s without a swing. Only a path over the navmesh has jumps in it. - const bool meshPath = !(t & PATHFIND_NOT_USING_PATH); + // The same holds for a path of only its two ends: over the navmesh a path breaks at every polygon portal and the smoothing + // steps it every few yards, so a two-point path longer than a step is a straight line drawn without the mesh, whatever its + // type bits. SFK courtyard (two navmesh floors 3.7 y apart, sfk_rethilgore 0.1.26 RC10: every path there came back as a + // straight line): such a line from the floor pocket at (-241.8,2124.7) to Razorclaw's spot, 135 y off, is the likeliest source of + // the af59 crossing that ran to (-202.6,2258.0) and set the tank down there; the far-step line above shows it next run. + const bool meshPath = !(t & PATHFIND_NOT_USING_PATH) && pts.size() > 2; for (size_t i = 1; i < pts.size(); ++i) { const float segx = pts[i].x - pts[i-1].x; @@ -7911,7 +8274,7 @@ static bool DungeonTargetReachableAndStep(Player* self, float tx, float ty, floa // unchanged: ANY > 15y smoothed segment is an off-mesh jump. Either signal // flags the crossing and returns its far vertex. constexpr float kOffMeshJumpYards = 15.0f; - if (meshPath && (seg > kOffMeshJumpYards || segOffMesh)) + if ((meshPath && seg > kOffMeshJumpYards) || segOffMesh) // the generator's own off-mesh landing counts on any path { if (step_is_offmesh) *step_is_offmesh = true; step_out = G3D::Vector3(pts[i].x, pts[i].y, pts[i].z); @@ -7996,8 +8359,19 @@ struct DungeonDetourVerdict static DungeonDetourVerdict DungeonTankDetour(Player* tank, float tx, float ty, float tz) { - DungeonDetourVerdict v; if (!tank || !tank->IsInWorld()) + return DungeonDetourVerdict{}; + return DungeonWalkDetourFrom(tank, tank->GetPositionX(), tank->GetPositionY(), tank->GetPositionZ(), tx, ty, tz); +} + +// The walk from (sx,sy,sz) to the target on `pather`'s map. Another member's walk is measured with the caller's own Player +// (its own tick's object, the same instance) from where that member stands in the group summary: the live Player of +// another bot belongs to that bot's tick, and its map can have changed since the summary was taken. +static DungeonDetourVerdict DungeonWalkDetourFrom(Player* pather, float sx, float sy, float sz, + float tx, float ty, float tz) +{ + DungeonDetourVerdict v; + if (!pather || !pather->IsInWorld()) return v; // Same guard the wedge watchdog uses (and this file's own // DungeonTargetReachableAndStep just above). Honest scope (final-review @@ -8011,12 +8385,11 @@ static DungeonDetourVerdict DungeonTankDetour(Player* tank, if (!Playerbot::PathBudget::HasBudget(GameTime::GetGameTimeMS())) return v; - float sx = tank->GetPositionX(), sy = tank->GetPositionY(), sz = tank->GetPositionZ(); float const dx = tx - sx, dy = ty - sy, dz = tz - sz; v.beeline = std::sqrt(dx * dx + dy * dy + dz * dz); - PathGenerator pg(tank); - v.ran = BotMovement::SehSafeCalculatePath(pg, tx, ty, tz); + PathGenerator pg(pather); + v.ran = BotMovement::SehSafeCalculatePathFrom(pg, sx, sy, sz, tx, ty, tz); PathType const pt = pg.GetPathType(); v.computed = true; v.type = uint32(pt); @@ -8062,6 +8435,19 @@ static bool DungeonTankDetourExcessiveVerbose(Player* tank, float tx, float ty, return DungeonDetourExcessive(v); } +// The same for another member's walk, measured on the caller's own Player from that member's spot (DungeonWalkDetourFrom). +static bool DungeonWalkDetourExcessiveVerboseFrom(Player* pather, float sx, float sy, float sz, float tx, float ty, float tz, + float& out_beeline, float& out_path_len, + float& out_ratio, bool& out_complete) +{ + DungeonDetourVerdict const v = DungeonWalkDetourFrom(pather, sx, sy, sz, tx, ty, tz); + out_beeline = v.beeline; + out_path_len = v.path_len; + out_ratio = v.ratio; + out_complete = v.complete; + return DungeonDetourExcessive(v); +} + // ── Off-mesh recovery for a stranded dungeon bot ────────────────────────────── // A bot that lands OFF the navmesh in a bridge gap (Deadmines Gap-1: the z51 hole // at ~(-213,-537) over genuine void, srcpoly=0) can path nowhere — every move_to @@ -8075,10 +8461,15 @@ static bool DungeonTankDetourExcessiveVerbose(Player* tank, float tx, float ty, // carries the bot across the few yards of void to the solid poly even though no // ground spans the gap (a spline does not fall mid-flight) — the next tick then // re-paths from real mesh. No-op for any on-mesh bot (the FARFROMPOLY gate). +// A bot ON the mesh, but on a scrap of it that no path leaves (BotMovement::MeshIslandExit: a few polygons of a slope Recast kept +// apart from the floor), walks the yard or two off it straight, as it walked on. blackmaw_full af61 (22 Nov): the tank ended a +// fight on 6 polygons of the slope at (3589.1,3348.0,274.2), every path from there ended on their edge 6 y away, and the group +// stood 120 s (group_stalled). A crossing under way (dungeon_cross) lands where it lands and is left alone. static bool DungeonNudgeOntoMesh(Player* self, BotIntentEmitter& emit, BotAI& ai) { if (!self) return false; - if (!Playerbot::PathBudget::HasBudget(GameTime::GetGameTimeMS())) + uint32 const nudge_now = GameTime::GetGameTimeMS(); + if (!Playerbot::PathBudget::HasBudget(nudge_now)) return false; Position on_mesh; if (!BotMovement::NearestNavPoint(self, self->GetPositionX(), self->GetPositionY(), @@ -8094,7 +8485,35 @@ static bool DungeonNudgeOntoMesh(Player* self, BotIntentEmitter& emit, BotAI& ai BotMovement::SehSafeCalculatePath(pg, on_mesh.GetPositionX(), on_mesh.GetPositionY(), on_mesh.GetPositionZ()); if (!(pg.GetPathType() & PATHFIND_FARFROMPOLY)) - return false; // on-mesh — nothing to recover + { + // On the mesh: on a scrap of it? + if (ai.dungeon_cross_active(nudge_now) || self->isMoving()) + return false; + constexpr float kIslandStepYd = 8.0f; // blackmaw: the floor 5.9 y from the scrap + Position off_scrap; + int scrap_polys = 0; + if (!BotMovement::MeshIslandExit(self, kIslandStepYd, off_scrap, &scrap_polys)) + return false; // on-mesh — nothing to recover + emit.move_to(off_scrap.GetPositionX(), off_scrap.GetPositionY(), off_scrap.GetPositionZ(), + /*run=*/true, /*direct=*/true); + static std::mutex s_scrapLogMu; + static std::unordered_map s_scrapLogAt; + { + std::lock_guard lk(s_scrapLogMu); + uint32& at = s_scrapLogAt[self->GetGUID().GetCounter()]; + if (at == 0 || nudge_now - at >= 5000u) + { + at = nudge_now ? nudge_now : 1u; + TC_LOG_INFO("playerbot.v2", + "[mesh_scrap] {} stands on a scrap of navmesh ({} polygons) at ({:.1f},{:.1f},{:.1f}) map {}: walks {:.1f} y off it to ({:.1f},{:.1f},{:.1f})", + self->GetName(), scrap_polys, self->GetPositionX(), self->GetPositionY(), self->GetPositionZ(), + self->GetMapId(), self->GetExactDist2d(off_scrap.GetPositionX(), off_scrap.GetPositionY()), + off_scrap.GetPositionX(), off_scrap.GetPositionY(), off_scrap.GetPositionZ()); + } + } + ai.set_last_rule_fired("idle:dungeon_mesh_scrap_step"); + return true; + } } emit.move_to(on_mesh.GetPositionX(), on_mesh.GetPositionY(), on_mesh.GetPositionZ(), /*run=*/true); @@ -8693,6 +9112,54 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, for (auto const& m : *mems) if (!m.is_bot && m.online && m.map_id == s.map_id()) { human_in_instance = true; break; } + bool const run_done_with_player = s.dungeon_complete() && human_in_instance; + // A finder run that a player is in ends like a player's own: once the dungeon is done, each bot in turn says goodbye in + // party chat, hearths and leaves the group (Karrz, 2026-11-24: "once the raid is completed, I would like the bots to leave, + // to just start hearthing out, to make it look real"). Finder run = LFGMgr has the bot in the matched dungeon or done with + // it; a party the player made by hand keeps its bots (they follow and fight until the player says otherwise). Turns are + // spread 4-24 s apart by bot id, so they leave one by one. Playerbot.Dungeon.FinderGoodbye (default 1) turns it off. + static bool const finder_goodbye_on = sConfigMgr->GetBoolDefault("Playerbot.Dungeon.FinderGoodbye", true); + BotAI::FinderGoodbye& goodbye = ai.finder_goodbye(); + if (!s.dungeon_complete()) + goodbye = {}; + else if (finder_goodbye_on && human_in_instance && g.exists() && + (s.lfg_in_dungeon() || s.lfg_finished_dungeon()) && + !s.in_combat() && !s.is_casting() && !ai.holding_position(now_ms)) + { + uint32 const inst = s.raw().position.instance_id; + if (goodbye.map != s.map_id() || goodbye.instance != inst) + { + uint32 const turn_ms = 4000u + (uint32(ai.bot_id()) * 2654435761u >> 8) % 20000u; + goodbye = { s.map_id(), inst, (now_ms ? now_ms : 1u) + turn_ms, 0 }; + TC_LOG_INFO("playerbot.v2", "[finder_goodbye] {} dungeon {} done with a player in the group: goodbye in {} s", + s.name(), s.map_id(), turn_ms / 1000u); + } + if (goodbye.stage == 0 && now_ms >= goodbye.at_ms) + { + char const* phrases[] = { "thanks for the run, all", "ty all, gg", "gg, thanks", "thanks all, take care", + "nice run, thanks", "ty for the group" }; + emit.say(phrases[uint32(ai.bot_id()) % (sizeof(phrases) / sizeof(phrases[0]))]); + goodbye.stage = 1; + goodbye.at_ms = now_ms + 2500u; + ai.set_last_rule_fired("idle:finder_goodbye_say"); + return true; + } + if (goodbye.stage == 1 && now_ms >= goodbye.at_ms) + { + // The hearth carries the bot out; leaving the group in the same tick ends its part in the run whether the + // hearth is ready or not (without one the instance sends a bot that left the group out on its own). + bool const hearth = s.can_hearth(); + if (hearth) + emit.hearth(); + emit.group_leave(); + ai.set_dungeon_run_mode(BotAI::DungeonRunMode::Off); + goodbye.stage = 2; + TC_LOG_INFO("playerbot.v2", "[finder_goodbye] {} leaves the group{}", s.name(), hearth ? " and hearths" : " (no hearth ready)"); + ai.set_last_rule_fired("idle:finder_goodbye_leave"); + return true; + } + } + // Not under an owner Hold / Stay: a bot told to hold its spot does not leave the instance (zg_thekal 2026-10-20: the tank // hearthed from the landing in the tick between the scenario Hold lapsing at the order time and its renewal by the mana wait, // after the trash clearing had killed Hakkar and marked the raid's final encounter done). @@ -8798,11 +9265,14 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, // through to idle:dungeon_regroup_follow_tank and rejoins the group. bool cc_cohered = true; bool tank_fighting = false; // the script list is for mobs before the pull, not once the tank is in a fight + ObjectGuid cc_tank; // whose walk decides if an idle mob of the list is a pull at all (below) + float cc_tank_x = 0.f, cc_tank_y = 0.f, cc_tank_z = 0.f; // where it stands (the group summary) if (GroupMemberSummary const* cctk = GroupAnchorTank(s, ai, g)) if (cctk->online && cctk->guid != s.guid() && cctk->map_id == s.map_id()) { tank_fighting = cctk->in_combat; + if (cctk->is_alive) { cc_tank = cctk->guid; cc_tank_x = cctk->x; cc_tank_y = cctk->y; cc_tank_z = cctk->z; } float ccx, ccy, ccz; s.position(ccx, ccy, ccz); const float ex = cctk->x - ccx, ey = cctk->y - ccy, ez = cctk->z - ccz; // 22y MUST match the regroup_follow_tank trigger (>22y, line @@ -8911,14 +9381,52 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, for (uint32_t e : advice.cc_priority_entries) if (e == u.entry) { c.in_priority_list = true; break; } c.is_kill_focus = !kill_focus.IsEmpty() && u.guid == kill_focus; + c.tank_cannot_pull = !u.unit_in_combat && u.victim.IsEmpty() && + ai.pack_pull_gate().Get(u.guid.GetCounter(), now_ms) == PackPullGate::Verdict::Gated; cands.push_back(c); cand_guids.push_back(u.guid); cand_spells.push_back(sp); } // The group's kill focus (the most dangerous engaged caster of the list) first, else the first eligible add // (Bot/CcPick.h). - if (size_t const at = PickCcTarget(cands); at != kNoCcTarget) + // Crowd control on an idle mob pulls its pack, so an idle pick must be a mob the tank can walk to: the + // tank's pack stop passes by a pack it can only reach the long way round (PackPullGate.h), and a sheep on + // one brings it to the group with nobody to hold it (lbrs_full af58: the mage on the ledge sheeped 9240, 13 y + // below and a 210 y walk for the tank; the pack came up, the tank went down after it into two more and the + // priest died). The tank's walk is measured as the pack stop measures it, at most once per verdict window + // per mob (the caster's own PackPullGate), and an unmeasured walk never holds the cast (fail-open). + // The walk is measured on the caster's own Player from the tank's spot in the group summary, never on the + // tank's live Player, which belongs to the tank's own tick. + Player* const cc_self_p = !cc_tank.IsEmpty() && Services::Config().pull_gate_enabled() + ? ObjectAccessor::FindConnectedPlayer(s.guid()) : nullptr; + for (int tries = 0; tries < 4 && pick.IsEmpty(); ++tries) { + size_t const at = PickCcTarget(cands); + if (at == kNoCcTarget) + break; + NearbyUnit const* pu = nullptr; + for (auto const& u : s.raw().combat.nearby_enemies) + if (u.guid == cand_guids[at]) { pu = &u; break; } + uint64 const low = cand_guids[at].GetCounter(); + if (pu && cc_self_p && !pu->unit_in_combat && pu->victim.IsEmpty() && + ai.pack_pull_gate().Get(low, now_ms) == PackPullGate::Verdict::Unknown) + { + DungeonDetourVerdict const dv = + DungeonWalkDetourFrom(cc_self_p, cc_tank_x, cc_tank_y, cc_tank_z, pu->x, pu->y, pu->z); + if (dv.computed) + { + bool const gated = DungeonDetourExcessive(dv); + ai.pack_pull_gate().Note(low, gated, now_ms); + if (gated) + { + TC_LOG_INFO("playerbot.v2", + "[pull_gate] SKIP rule=auto_cc bot={} entry {} ({}): beeline={:.1f} path={:.1f} ratio={:.2f} complete={}", + s.name(), pu->entry, low, dv.beeline, dv.path_len, dv.ratio, dv.complete ? 1 : 0); + cands[at].tank_cannot_pull = true; + continue; + } + } + } pick = cand_guids[at]; cc = cand_spells[at]; } @@ -8936,7 +9444,7 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, // reach from here", so the tank's 8 s wait ran out with nobody walking in (smlibrary_loksey 0.1.28b: "the held mob 13 // was not held after 8105 ms", five mobs came at once). PrePullCc::Request pr; - if (!moon.IsEmpty() && PrePullCc::Get(s.group_guid().GetCounter(), now_ms, pr) && !pr.done_ms && pr.mob == moon && + if (!moon.IsEmpty() && PrePullCc::Get(s.group_guid().GetCounter(), now_ms, pr) && !pr.done_ms && !pr.on_pull && pr.mob == moon && pr.caster_low == s.guid().GetCounter()) for (auto const& u : s.raw().combat.nearby_enemies) { @@ -9671,7 +10179,7 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, const int ready_hp_pct = tight_engage ? 85 : 70; // Shared with the drink rules (ClassicUpkeep.h): a grouped healer in an // instance starts drinking below this, so it never holds the pull dry. - const int64 kReadyHealerManaPct = Classic::PullReadyHealerManaPct(s); + const int64 kReadyHealerManaPct = PullHealerManaMark(s, ai); const float ready_other_y = tight_engage ? 25.0f : 50.0f; // "Tank leads" ("lead on" / "lead pause"; BotAI::TankLead): what the leading tank waits for, for its word to the group below // (nullptr: not held for a reason the player can act on). @@ -10175,40 +10683,14 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, { // Earliest live boss in progression order (advice.bosses is // authored in encounter order), whole-dungeon scan radius. - struct CatchupBossCheck - { - Player const* origin; - std::vector const& entries; - float range; - bool operator()(Creature* c) const - { - if (!BossFightable(origin, c)) return false; - for (uint32_t e : entries) - if (c->GetEntry() == e) - return origin->IsWithinDistInMap(c, range); - return false; - } - }; constexpr float kCuScanR = 500.0f; - std::list cu_bcre; - CatchupBossCheck cu_chk{self_cu, advice.bosses, kCuScanR}; - Trinity::CreatureListSearcher cu_search( - self_cu, cu_bcre, cu_chk); - Cell::VisitAllObjects(self_cu, cu_search, kCuScanR); - Creature* cu_boss = nullptr; - for (uint32_t be : advice.bosses) - { - for (Creature* bc : cu_bcre) - if (bc && bc->GetEntry() == be && bc->IsAlive()) - { cu_boss = bc; break; } - if (cu_boss) break; - } + DungeonExecState::ScanUnit const* cu_boss = EarliestFightableBoss(s, advice.bosses, kCuScanR); if (cu_boss) { float tcx, tcy, tcz; s.position(tcx, tcy, tcz); - const float cbx = cu_boss->GetPositionX(); - const float cby = cu_boss->GetPositionY(); - const float cbz = cu_boss->GetPositionZ(); + const float cbx = cu_boss->x; + const float cby = cu_boss->y; + const float cbz = cu_boss->z; // 2D progress toward the boss: who has advanced furthest down // the corridor. The boss sits on the z19 floor while the tank // is on a z51 ledge — vertical separation must NOT count as @@ -10266,7 +10748,7 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, TC_LOG_INFO("playerbot.v2", "[tank_catchup] {} boss={} tank_dist={:.1f} " "fwd_dist={:.1f} via={}", - s.name(), cu_boss->GetEntry(), + s.name(), cu_boss->entry, std::sqrt(tank_db2), std::sqrt(fwd_db2), via); ai.set_last_rule_fired("idle:dungeon_tank_catchup_boss"); return true; @@ -10292,6 +10774,10 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, !pve_off_tank && s.is_in_dungeon() && !s.is_encounter_in_progress() && + // The run is done and a player is in the group: the tank no longer leads to trash; the player says what else is + // cleared (alcaz af70c, 2026-11-24: after Blazeroar the tank walked 70 y back across the prison to pull a pack it had + // passed, and Karrz read it as the run going somewhere else). + !run_done_with_player && // G-P1a: mirror tank_pull_next's gates so a paused or phase-locked // tank doesn't keep marching the group into the next pack — a real // tank stops when the leader says "wait"/"inc" and never advances @@ -10665,6 +11151,11 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, // each hop short enough for followers to track without stranding // on a harbor z-transition. constexpr float kMaxAdvanceStep = 20.0f; + // Off the mesh, or on a scrap of it no path leaves: back onto the floor first, or every advance below is refused + // from where he stands (blackmaw_full af61: 120 s on a 6-polygon scrap of the slope after a fight). + if (Player* self_nm = ObjectAccessor::FindConnectedPlayer(s.raw().guid)) + if (DungeonNudgeOntoMesh(self_nm, emit, ai)) + return true; // Diagnostic accumulators — filled by each advance branch; // reported once in the [tank_adv_diag] NO-TARGET log below. int diag_s150_cand = 0; @@ -10741,40 +11232,12 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, // Glubtok's spot, Helix reach=0, never reaching the foundry // approach where Helix becomes reach=1). Beyond this, defer. constexpr float kBossApproachR = 30.0f; - struct BossEntryCheck - { - Player const* origin; - std::vector const& entries; - float range; - // Every LIVING boss of the list, fightable or not: a boss that cannot be fought yet (the Unbound - // Spirit of Blackmaw Hold until Elder Bramblesnap's ritual has run) is still there, so it is owed and - // must not be waived; only a fightable one is a target (the pick below). - bool operator()(Creature* c) const - { - if (!c || !c->IsAlive()) return false; - for (uint32_t e : entries) - if (c->GetEntry() == e) - return origin->IsWithinDistInMap(c, range); - return false; - } - }; - std::list bcre; - BossEntryCheck bchk{self_be, advice.bosses, kBossScanR}; - Trinity::CreatureListSearcher bsearch(self_be, bcre, bchk); - Cell::VisitAllObjects(self_be, bsearch, kBossScanR); - // Commit to the EARLIEST live boss in progression order // (advice.bosses is authored in encounter order). Once // chosen, never skip ahead to a later boss this tick. - Creature* boss_target = nullptr; int found_idx = -1; - for (int bi = 0; bi < static_cast(advice.bosses.size()); ++bi) - { - for (Creature* bc : bcre) - if (bc && bc->GetEntry() == advice.bosses[bi] && BossFightable(self_be, bc)) - { boss_target = bc; found_idx = bi; break; } - if (boss_target) break; - } + DungeonExecState::ScanUnit const* boss_target = + EarliestFightableBoss(s, advice.bosses, kBossScanR, &found_idx); // Boss-target hysteresis (SFK Baron Ashbury flicker, // 2026-07-25). The earliest UN-KILLED boss is // bosses[bosses_done_count]; it is definitionally alive, so @@ -10815,8 +11278,8 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, auto owed_alive_in_scan = [&](int idx) -> bool { if (idx < 0 || idx >= static_cast(advice.bosses.size())) return false; - for (Creature* bc : bcre) - if (bc && bc->GetEntry() == advice.bosses[idx]) return true; + for (auto const& bc : s.raw().dungeon_exec.scan_bosses) + if (bc.entry == advice.bosses[idx]) return true; return false; }; // No fightable boss within the scan while a boss is still owed: the owed boss and every later one @@ -10885,11 +11348,11 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, // cell ledge (z73.8). DISABLE engage (null creature) so we // never pull the stand-in; once the tank closes and the caged // boss enters scan, found_idx == done_idx restores the live pull. - Creature* engage_target = boss_target; - const uint32 nav_entry = boss_target ? boss_target->GetEntry() : advice.bosses[done_idx]; - float btx = boss_target ? boss_target->GetPositionX() : 0.f; - float bty = boss_target ? boss_target->GetPositionY() : 0.f; - float btz = boss_target ? boss_target->GetPositionZ() : 0.f; + DungeonExecState::ScanUnit const* engage_target = boss_target; + const uint32 nav_entry = boss_target ? boss_target->entry : advice.bosses[done_idx]; + float btx = boss_target ? boss_target->x : 0.f; + float bty = boss_target ? boss_target->y : 0.f; + float btz = boss_target ? boss_target->z : 0.f; if ((!boss_target || found_idx > done_idx) && done_idx >= 0 && done_idx < static_cast(advice.progression_waypoints.size())) { @@ -10897,6 +11360,10 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, btx = wp.x; bty = wp.y; btz = wp.z; engage_target = nullptr; } + // The boss the tank goes for: the live one it can engage, or the owed one whose waypoint it steers to + // (logs and the boss-headway watch; boss_target may be a later stand-in). + uint32 const owed_entry = engage_target ? engage_target->entry + : (done_idx >= 0 && done_idx < static_cast(advice.bosses.size()) ? uint32(advice.bosses[done_idx]) : 0u); adv_have_boss = true; adv_boss_x = btx; adv_boss_y = bty; @@ -10906,7 +11373,7 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, const float bdz = btz - bz_adv; const float bd2 = bdx*bdx + bdy*bdy + bdz*bdz; const bool in_los = - engage_target && self_be->IsWithinLOSInMap(engage_target); + engage_target && engage_target->in_los; G3D::Vector3 boss_step; bool boss_step_offmesh = false; const bool reachable = DungeonTargetReachableAndStep( @@ -10987,12 +11454,12 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, if (engage_target && bd2 <= kBossEngageR2 && in_los) { // Raid lead: the tank stands here until the player pulls or says "go" (LeadHoldsBossPull). - if (LeadHoldsBossPull(s, ai, emit, engage_target->GetGUID(), now_ms)) + if (LeadHoldsBossPull(s, ai, emit, engage_target->guid, now_ms)) return true; // Pull: stationary boss, chasing can't overshoot. - if (!emit.start_attack(engage_target->GetGUID())) + if (!emit.start_attack(engage_target->guid)) return false; - ai.note_engage(engage_target->GetGUID(), now_ms); + ai.note_engage(engage_target->guid, now_ms); ai.set_last_rule_fired("idle:dungeon_engage_boss"); return true; } @@ -11009,7 +11476,24 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, { uint32 const stuck_ms = ai.stride_note(s.map_id(), boss_step.x, boss_step.y, boss_step.z, bx_adv, by_adv, bz_adv, now_ms); - if (stuck_ms >= BotAI::kStrideStallMs) + // And toward the boss itself: a dead end entered and left by turns restarts the step watch + // (BotAI::stride_boss_note). Measured to the point the tank steers to (btx, bty, btz): the owed + // boss's waypoint while a later boss stands in for it, never the stand-in, which is not where the + // tank is going (and is not there at all when the owed boss is out of the scan: exc_full af69i + // crashed on boss_target->entry here). + uint32 const boss_stuck_ms = ai.stride_boss_note(s.map_id(), owed_entry, bx_adv, by_adv, bz_adv, + btx, bty, btz, now_ms); + if (boss_stuck_ms >= BotAI::kStrideBossStallMs) + { + stride_dead = true; + ai.note_move_refused(boss_step.x, boss_step.y, boss_step.z, now_ms); + TC_LOG_INFO("playerbot.v2", + "[boss_nav] {} boss={} strides got no closer than {:.1f} y in {} ms (now {:.1f} y, step " + "({:.1f},{:.1f},{:.1f})): stride refused, the route and the other steps take over", + s.name(), owed_entry, ai.stride_boss_best(), boss_stuck_ms, std::sqrt(bd2), + boss_step.x, boss_step.y, boss_step.z); + } + else if (stuck_ms >= BotAI::kStrideStallMs) { stride_dead = true; ai.note_move_refused(boss_step.x, boss_step.y, boss_step.z, now_ms); @@ -11822,6 +12306,7 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, if (u.guid == ai.last_engage_target() && now_ms - ai.last_engage_at_ms() < ai.last_engage_shield_ms()) continue; if (ai.start_attack_recently_refused(u.guid.GetCounter(), now_ms)) continue; + if (ai.pack_pull_gate().Get(u.guid.GetCounter(), now_ms) == PackPullGate::Verdict::Gated) continue; // as tank_pull_next const float dx = u.x - bx_adv; const float dy = u.y - by_adv; const float dz = u.z - bz_adv; @@ -11981,13 +12466,9 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, { if (Player* self = ObjectAccessor::FindConnectedPlayer(s.raw().guid)) { - constexpr float kTrashScanRadius = 150.0f; - std::list hostiles; - Trinity::AnyUnfriendlyUnitInObjectRangeCheck chk( - self, self, kTrashScanRadius); - Trinity::UnitListSearcher - searcher(self, hostiles, chk); - Cell::VisitAllObjects(self, searcher, kTrashScanRadius); + // The builder's scan_hostiles (DungeonExecState::kScanHostileYd = 150 y): alive creatures the bot may + // attack, not critters, totems or companion pets. No grid walk on this thread. + auto const& hostiles = s.raw().dungeon_exec.scan_hostiles; // Pick the NEAREST hostile Detour can actually walk to. // Cell::VisitAllObjects is a 2D GRID scan — it returns @@ -11997,22 +12478,17 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, // a real walkable path; if none is reachable we leave nearest // null and fall through to boss/waypoint progression. The // path test runs only until the first reachable hit. - std::vector> cand; + std::vector> cand; cand.reserve(hostiles.size()); - for (Unit* u : hostiles) + for (DungeonExecState::ScanUnit const& hu : hostiles) { - if (!u || !u->IsAlive()) continue; - if (u->IsCritter() || u->IsTotem()) continue; - if (u->GetCreatureType() == CREATURE_TYPE_NON_COMBAT_PET) - continue; - if (!self->IsValidAttackTarget(u)) continue; + DungeonExecState::ScanUnit const* u = &hu; // Skip per-dungeon environmental encounter objects. { bool env_ignored = false; - if (Creature const* c = u->ToCreature()) - for (uint32_t ie : advice.ignore_entries) - if (ie == c->GetEntry()) - { env_ignored = true; break; } + for (uint32_t ie : advice.ignore_entries) + if (ie == u->entry) + { env_ignored = true; break; } if (env_ignored) continue; } // Directional: skip BACKWARD trash (farther from the boss @@ -12023,36 +12499,36 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, // Gap-1 NE oscillation to the crime scene, 2026-06-26). if (adv_have_boss) { - const float cbx = adv_boss_x - u->GetPositionX(); - const float cby = adv_boss_y - u->GetPositionY(); + const float cbx = adv_boss_x - u->x; + const float cby = adv_boss_y - u->y; const float tbx = adv_boss_x - bx_adv; const float tby = adv_boss_y - by_adv; if (cbx*cbx + cby*cby > tbx*tbx + tby*tby + 15.0f*15.0f) continue; } - const float dxu = u->GetPositionX() - bx_adv; - const float dyu = u->GetPositionY() - by_adv; - const float dzu = u->GetPositionZ() - bz_adv; + const float dxu = u->x - bx_adv; + const float dyu = u->y - by_adv; + const float dzu = u->z - bz_adv; cand.emplace_back(dxu * dxu + dyu * dyu + dzu * dzu, u); } std::sort(cand.begin(), cand.end(), [](auto const& a, auto const& b) { return a.first < b.first; }); G3D::Vector3 scan_step; - Unit* nearest = nullptr; + DungeonExecState::ScanUnit const* nearest = nullptr; for (auto const& cu : cand) { if (DungeonTargetReachableAndStep( self, - cu.second->GetPositionX(), - cu.second->GetPositionY(), - cu.second->GetPositionZ(), + cu.second->x, + cu.second->y, + cu.second->z, kMaxAdvanceStep, scan_step)) { nearest = cu.second; break; } } diag_s150_cand = (int)cand.size(); diag_s150_reach = nearest != nullptr; if (!cand.empty()) - diag_s150_first = cand.front().second->GetEntry(); + diag_s150_first = cand.front().second->entry; if (nearest) { // Use the navmesh path's own waypoints (scan_step) @@ -12098,36 +12574,17 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, if (Player* self = ObjectAccessor::FindConnectedPlayer(s.raw().guid)) { constexpr float kBossScanRadius = 500.0f; - Creature* next_boss = nullptr; - // Perf 2026-05-22: was M× Cell::VisitAllObjects - // (one per boss entry). 1000 bots × 5Hz × M=5 - // bosses = 25K 500y grid walks/sec. Replaced - // with a single visit + inline entry-set - // membership check. Same correctness; M× CPU - // win. The match check is hot — pass entries - // by reference and break on first hit. - struct AliveBossEntryCheck + DungeonExecState::ScanUnit const* next_boss = nullptr; + // The builder's scan_bosses (DungeonExecState::ScanUnit): no grid walk on this thread. + float nbx, nby, nbz; s.position(nbx, nby, nbz); + std::vector creatures; + for (auto const& u : s.raw().dungeon_exec.scan_bosses) { - Player const* origin; - std::vector const& entries; - float range; - AliveBossEntryCheck(Player const* o, std::vector const& e, float r) - : origin(o), entries(e), range(r) {} - bool operator()(Creature* c) const - { - if (!BossFightable(origin, c)) return false; - bool match = false; - for (uint32_t e : entries) - if (c->GetEntry() == e) { match = true; break; } - if (!match) return false; - return origin->IsWithinDistInMap(c, range); - } - }; - std::list creatures; - AliveBossEntryCheck chk(self, advice.bosses, kBossScanRadius); - Trinity::CreatureListSearcher - searcher(self, creatures, chk); - Cell::VisitAllObjects(self, searcher, kBossScanRadius); + const float dx = u.x - nbx, dy = u.y - nby, dz = u.z - nbz; + if (u.fightable && dx * dx + dy * dy + dz * dz <= kBossScanRadius * kBossScanRadius && + std::find(advice.bosses.begin(), advice.bosses.end(), u.entry) != advice.bosses.end()) + creatures.push_back(&u); + } // Pick the EARLIEST boss in progression order (advice.bosses // is authored in the instance's encounter order) that has a // live creature Detour can actually WALK to — NOT @@ -12147,11 +12604,11 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, static_cast(ai.dungeon_owed_floor(self->GetMapId(), s.raw().dungeon_exec.bosses_done_count))); for (int bi = 0; bi < static_cast(advice.bosses.size()); ++bi) { - for (Creature* c : creatures) - if (c && c->GetEntry() == advice.bosses[bi] && + for (DungeonExecState::ScanUnit const* c : creatures) + if (c->entry == advice.bosses[bi] && DungeonTargetReachableAndStep( self, - c->GetPositionX(), c->GetPositionY(), c->GetPositionZ(), + c->x, c->y, c->z, kMaxAdvanceStep, boss_step)) { next_boss = c; next_boss_idx = bi; break; } if (next_boss) break; @@ -12176,6 +12633,37 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, } } + // A dungeon with a route: the last-resort step is the route's next crumb, never the boss waypoint straight. The + // boss waypoint's straight path can run the other way from the route (drowned_full af70c 2026-11-25: after Deathless + // Marrow the route goes north round the flooded quarter to the Primeval Elemental, the navmesh path to its spawn goes + // south; for the last 1400 s of the run the tank stepped north on the route, then south on this fallback, between + // y 3036 and 3054, and the group stood. Every navigator above declined on the in-between ticks). + if (!close_target && !far_target && !advice.route_waypoints.empty()) + { + int32_t const rcur = ai.dungeon_route_wp(s.map_id()); + if (rcur >= 0) + { + size_t const ni = std::min(size_t(rcur) + 1, advice.route_waypoints.size() - 1); + auto const& rw = advice.route_waypoints[ni]; + const float dxr = rw.x - bx_adv, dyr = rw.y - by_adv, dzr = rw.z - bz_adv; + const float dr = std::sqrt(dxr * dxr + dyr * dyr + dzr * dzr); + if (dr > 3.0f) + { + G3D::Vector3 rstep; + Player* rself = ObjectAccessor::FindConnectedPlayer(s.raw().guid); + if (rself && DungeonTargetReachableAndStep(rself, rw.x, rw.y, rw.z, kMaxAdvanceStep, rstep)) + emit.move_to(rstep.x, rstep.y, rstep.z, /*run=*/true); + else if (dr > kMaxAdvanceStep) + emit.move_to(bx_adv + dxr * (kMaxAdvanceStep / dr), by_adv + dyr * (kMaxAdvanceStep / dr), + bz_adv + dzr * (kMaxAdvanceStep / dr), /*run=*/true); + else + emit.move_to(rw.x, rw.y, rw.z, /*run=*/true); + ai.set_last_rule_fired("idle:dungeon_tank_route_fallback"); + return true; + } + } + } + // Waypoint-driven progression — last-resort fallback for // dungeons whose bosses[] is empty / unset (the boss // scan above is now the primary cross-room navigator). @@ -12524,12 +13012,12 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, if (Services::Config().pull_gate_enabled()) { if (!pick.IsEmpty() && dtk->online && dtk->is_alive && dtk->map_id == s.map_id()) - if (Player* tkp = ObjectAccessor::FindConnectedPlayer(dtk->guid)) + if (Player* selfp = ObjectAccessor::FindConnectedPlayer(s.guid())) for (auto const& u : s.raw().combat.nearby_enemies) { if (u.guid != pick) continue; DungeonDetourVerdict const dv = - DungeonTankDetour(tkp, u.x, u.y, u.z); + DungeonWalkDetourFrom(selfp, dtk->x, dtk->y, dtk->z, u.x, u.y, u.z); if (DungeonDetourExcessive(dv)) { ai.note_engage(pick, s.published_at_ms(), 15000u); @@ -12554,12 +13042,12 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, // [detour] READ-ONLY stage (Task 1): measure, log, never block. // Kept alive so diagnosis survives the kill switch. if (!pick.IsEmpty() && dtk->online && dtk->is_alive && dtk->map_id == s.map_id()) - if (Player* tkp = ObjectAccessor::FindConnectedPlayer(dtk->guid)) + if (Player* selfp = ObjectAccessor::FindConnectedPlayer(s.guid())) for (auto const& u : s.raw().combat.nearby_enemies) { if (u.guid != pick) continue; DungeonDetourVerdict const dv = - DungeonTankDetour(tkp, u.x, u.y, u.z); + DungeonWalkDetourFrom(selfp, dtk->x, dtk->y, dtk->z, u.x, u.y, u.z); static uint32 s_detour_dbg_focus_ms = 0; uint32 const dnow = s.published_at_ms(); if (dv.computed && dnow - s_detour_dbg_focus_ms > 1500u) @@ -12658,10 +13146,10 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, bool gated = false; if (GroupMemberSummary const* tk2 = g.tank()) if (tk2->online && tk2->is_alive && tk2->map_id == s.map_id()) - if (Player* tkp = ObjectAccessor::FindConnectedPlayer(tk2->guid)) + if (Player* selfp = ObjectAccessor::FindConnectedPlayer(s.guid())) { DungeonDetourVerdict const dv = - DungeonTankDetour(tkp, u.x, u.y, u.z); + DungeonWalkDetourFrom(selfp, tk2->x, tk2->y, tk2->z, u.x, u.y, u.z); if (DungeonDetourExcessive(dv)) { ai.note_engage(u.guid, s.published_at_ms(), 15000u); @@ -12687,10 +13175,10 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, // block. Kept alive so diagnosis survives the kill switch. if (GroupMemberSummary const* tk2 = g.tank()) if (tk2->online && tk2->is_alive && tk2->map_id == s.map_id()) - if (Player* tkp = ObjectAccessor::FindConnectedPlayer(tk2->guid)) + if (Player* selfp = ObjectAccessor::FindConnectedPlayer(s.guid())) { DungeonDetourVerdict const dv = - DungeonTankDetour(tkp, u.x, u.y, u.z); + DungeonWalkDetourFrom(selfp, tk2->x, tk2->y, tk2->z, u.x, u.y, u.z); static uint32 s_detour_dbg_dps_ms = 0; uint32 const dnow = s.published_at_ms(); if (dv.computed && dnow - s_detour_dbg_dps_ms > 1500u) @@ -12727,6 +13215,7 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, // wraps a full encounter-context check. if (s.is_alive() && !s.is_casting() && !s.in_combat() && ai.effective_role(s) == Role::Tank && + !run_done_with_player && // see the tank advance: after the last boss the player picks any more pulls // PvE-coordinator gate: only the designated MAIN tank starts // pulls (raid off-tanks follow + taunt-swap; a 5-man's // second tank-spec member acts as DPS). See pve_off_tank @@ -12843,6 +13332,10 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, // anyway; skipping here prevents selecting it as `best` and // hitting the failed-start_attack return-false path every tick. if (ai.start_attack_recently_refused(u.guid.GetCounter(), now_ms)) continue; + // A pack the pull-back order found it could not pull from here (no opener spot, or an opener that never woke it: + // PrologueRules' pull-back) is passed by, as the advance passes it (UnpulledPackMob). Without this the pull took the + // same mob behind the Shadowfang courtyard wall four times running (sfk_full af70c). + if (ai.pack_pull_gate().Get(u.guid.GetCounter(), now_ms) == PackPullGate::Verdict::Gated) continue; // Real tanks pull what they can SEE. The 40y enemy scan // returns mobs through dungeon walls; opening on one // wedges the whole party into "not in line of sight" @@ -13050,10 +13543,21 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, for (auto const& m : *mems) if (m.online && m.is_alive && m.is_bot && m.cls == CLASS_MAGE && m.level >= 8 && m.map_id == s.map_id()) { mage = &m; break; } - if (mage && PrePullCc::Open(s.group_guid().GetCounter(), cc_mob->guid, mage->guid.GetCounter(), now_ms)) + // A mob whose formation comes into the fight with it: the Polymorph on it is the pull, with the tank not + // yet in it. lbrs_full af59 (t=11 s): the mage stepped up level with the tank and sheeped Scarshield + // Legionnaire 182; its formation (181, 179) ran at the mage, the tank had 5 rage and its Taunt went on + // cooldown on the first, the healer was still walking up from the landing, and the mage died. Such a mob + // is held "on the pull": the tank pulls, the mage sheeps it in the fight as it runs in. + bool linked = false; + if (cc_mob->engage_calls_formation && cc_mob->formation_leader) + for (NearbyUnit const* o : idle_mobs) + if (o != cc_mob && o->hp > 0 && !o->is_cc_locked && o->formation_leader == cc_mob->formation_leader) + { linked = true; break; } + if (mage && PrePullCc::Open(s.group_guid().GetCounter(), cc_mob->guid, mage->guid.GetCounter(), now_ms, linked)) { - TC_LOG_INFO("playerbot.v2", "[raid_pull] {} asks {} to hold entry {} ({}) before the pull: {} mobs in the pack (18y of the target, chained 10y)", - s.name(), mage->name, cc_mob->entry, cc_mob->guid.GetCounter(), pack_n); + TC_LOG_INFO("playerbot.v2", "[raid_pull] {} asks {} to hold entry {} ({}) {}: {} mobs in the pack (18y of the target, chained 10y)", + s.name(), mage->name, cc_mob->entry, cc_mob->guid.GetCounter(), + linked ? "on the pull, its formation comes with it" : "before the pull", pack_n); // The wait is a wait where the tank stands. The advance this pull pre-empted can still have a // spline running: alcaz_full af46-2 (t=616 s) asked for the moon on pack 26 while the boss walk // carried the tank on east, past the pack and onto Ca'zass 27 y away; she, her pack and its @@ -13065,7 +13569,22 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, } } bool precc_wait = false; - if (have_pcc && !pcc.done_ms) + // On the pull: the wait is only for the moon to go on (so the DPS leave the mob be), then the tank pulls. + if (have_pcc && !pcc.done_ms && pcc.on_pull) + { + bool mob_alive = false; + for (auto const& u : s.raw().combat.nearby_enemies) + if (u.guid == pcc.mob) { mob_alive = u.hp > 0; break; } + uint32 const waited_ms = uint32(now_ms - pcc.requested_ms); + if (mob_alive && pcc.state == PrePullCc::State::Pending && waited_ms < PrePullCc::kMarkWaitMs) + precc_wait = true; + else if (ai.last_rule_fired() != nullptr && std::string_view(ai.last_rule_fired()) == "idle:tank_precc_wait") + TC_LOG_INFO("playerbot.v2", "[raid_pull] {} pulls: {} holds {} in the fight ({} after {} ms)", s.name(), + pcc.caster_low, pcc.mob.GetCounter(), + pcc.state == PrePullCc::State::Marked ? "marked" : pcc.state == PrePullCc::State::Refused ? "refused" : "not marked", + waited_ms); + } + else if (have_pcc && !pcc.done_ms) { bool held = false; bool mob_alive = false; @@ -13345,7 +13864,8 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, // drinks like his other bots (OocRecoveryPick / Classic::LedMaySitDown), below kLedDrinkBelowManaPct, to full, and not // while he walks on. The pull-gate mark (90 % in a party) started a drink at 74-85 % at every stop and the next step // stood her up: 15 drinks and four members held on healer_mana in one Wailing Caverns run, which timed out (0.1.26 RC2). - bool const led = s.in_group() && s.is_led_by_player() && !ai.tank_leads_here(s); // "lead on": the pull gate's pace + // "lead on" in a five-man too (LedRest, GitHub #23); a raid under the lead keeps the pull gate's pace. + bool const led = s.in_group() && s.is_led_by_player() && (!ai.tank_leads_here(s) || !s.is_in_raid()); bool const led_may_sit = !led || Classic::LedMaySitDown({ Classic::IsDrinking(s), ai.since_rest_broken_ms(now_ms), ai.since_anchor_moved_ms(now_ms) }); if (hdx * hdx + hdy * hdy + hdz * hdz <= 45.0f * 45.0f && led_may_sit) @@ -21603,6 +22123,30 @@ bool AutoactDispatch(BotSnapshotView const& s, BotAI& ai, } if (best_spell != 0) { + // The station prop: a recipe that needs a focus is cast at the station with the + // trade's tool in the hand — same look as the town-errand smith. The swap puts + // the real weapon in the tool's bag slot; the upgrade rule leaves the hand alone + // while the cast run is live (station_prop_out), then restores the weapon after. + // The draw is hold-free: the 3 s idle resheath cleans the pose up itself when the + // casts stop, so nothing here can wedge the sheath or the swap suppression. + if (SpellInfo const* fsi = sSpellMgr->GetSpellInfo(best_spell, DIFFICULTY_NONE); + fsi && fsi->RequiresSpellFocus) + { + RecipeMeta const* fm = FindRecipeMeta(best_spell); + uint32 const tool = fm ? SkillupToolEntry(fm->skill_line_id) : 0; + if (tool) + { + bool have = s.raw().inventory.equipped.size() > EQUIPMENT_SLOT_MAINHAND && + s.raw().inventory.equipped[EQUIPMENT_SLOT_MAINHAND].entry == tool; + if (!have) + for (auto const& it : s.raw().inventory.bag_items) + if (it.entry == tool) { have = emit.equip_item(it.bag, it.slot, EQUIPMENT_SLOT_MAINHAND); break; } + if (!have && s.bag_free_slots() >= 1) + emit.give_item(tool); + emit.set_sheath(SHEATH_STATE_MELEE, 0); + ai.station_prop_extend(s.published_at_ms()); + } + } emit.cast(best_spell); ai.set_last_rule_fired("idle:craft_skillup"); return true; @@ -22336,6 +22880,10 @@ void DispatchIdle(BotAI& ai, auto& te = ai.town_errand(); if (te.place) ::Playerbot::V2::TownErrand::Spots::Get().Release(te.place, s.guid().GetCounter()); if (te.key) te.recent.add(te.key); + // EndErrand doesn't run on this abort: put away a drawn tool and clear a + // looping work emote or the dropped show follows the bot around town. + if (te.work_emote) emit.perform_emote(EMOTE_STATE_NONE); + if (te.tool_in_hand) emit.set_sheath(SHEATH_STATE_UNARMED); te.Clear(); ::Playerbot::V2::TownLife::Counters().idle_town.fetch_add(1, std::memory_order_relaxed); TC_LOG_INFO("playerbot.v2", "[idle] bot={} lvl={} map={} zone={} stationary {}s last_rule={} strikes={} -> new errand", diff --git a/src/modules/PlayerbotV2/Bot/States/State_InCombat.cpp b/src/modules/PlayerbotV2/Bot/States/State_InCombat.cpp index 4cebb317cb..8fbd0a0027 100644 --- a/src/modules/PlayerbotV2/Bot/States/State_InCombat.cpp +++ b/src/modules/PlayerbotV2/Bot/States/State_InCombat.cpp @@ -20,6 +20,7 @@ #include "Bot/MarkGate.h" // Playerbot.Behavior.MarksNeedOrder #include "Bot/RacialRules.h" // EscapeArtistWanted #include "Bot/ThreatDiscipline.h" // opening lead + [raid_threat] / [raid_pull] log pacing +#include "Bot/PullDelay.h" // the damage dealers' wait after the tank's pull #include "Bot/ThreatLimits.h" // hard threat ratios shared with the raid brain #include "ClassicSpec.h" // Classic::IsSingleSpecClass — combat:pve_heal_focus #include "Bot/Dungeon/MarkCc.h" // MarkCc::TryCast - combat:marked_cc @@ -760,6 +761,8 @@ ThreatHold EvaluateThreatHold(BotAI& ai, BotSnapshotView const& s, ObjectGuid ta if (ai.effective_role(s) == Role::Tank) return ThreatHold::None; // A boss fight script owns this bot's start and target (RaidFightScript.h): its start wait is the only hold. if (s.raw().raid_order.active && s.raw().raid_order.script_owns) return ThreatHold::None; + // The damage dealers' wait after the tank's pull (Bot/PullDelay.h), also for a mob not yet in this bot's scan. + if (PartyPullDelayHolds(ai, s, target)) return ThreatHold::TankOpening; NearbyUnit const* u = s.hostile_unit(target); if (!u) return ThreatHold::None; @@ -1069,6 +1072,11 @@ bool LooseMobEscape(BotAI& ai, BotSnapshotView const& s, GroupSnapshotView const for (NearbyUnit const& u : s.attackers()) consider(u); for (NearbyUnit const& u : s.nearby_enemies()) consider(u); if (!mob) return false; + // An add no tank holds (RaidRules::noTank: Kel'Thuzad's Soldiers and Soul Weavers, sent at a raider) is shed by neither: no tank comes + // for it, so a threat drop only hands it to the next raider and the walk to the tank carries it (and a Weaver's Wail of Souls cone) + // into the tanks' fight while the bot stops casting. naxx_kelthuzad kt61a / kt61b (1122): 34 / 55 "stepping to tank" + // lines on Soldiers and 4 / 10 on Weavers (logged once in 4 s a bot). + if (s.is_in_raid() && Raid::NoTank(s.map_id(), mob->entry)) return false; constexpr uint32 FEIGN_DEATH = 5384, VANISH = 1856, FEINT = 1966, FADE = 586, FROST_NOVA = 122; if (s.cls() == CLASS_HUNTER && s.has_aura(FEIGN_DEATH)) @@ -1134,11 +1142,17 @@ bool LooseMobEscape(BotAI& ai, BotSnapshotView const& s, GroupSnapshotView const // In the group's fight outside the raid rules the bot keeps hitting and its tank takes the mob (GroupFight.h rule 5): the walk to the // tank stopped the damage (UBRS 2026-10-28: [raid_escape] "stepping to tank" on Jaidal, Gun, Elentinari through every pull). if (ai.group_fight() && !s.raid_rules()) + { + note("the group fights: keeps hitting, the tank takes it"); return false; + } // Step toward the tank so it can taunt / body-pull the mob off us. GroupMemberSummary const* tk = GroupAnchorTank(s, ai, g); if (!tk || !tk->online || !tk->is_alive || tk->guid == s.guid() || tk->map_id != s.map_id() || s.is_rooted()) + { + note(!tk ? "no anchor tank" : s.is_rooted() ? "rooted" : "the tank is gone, dead or on another map"); return false; + } // The tank is feared / stunned: it picks nothing up, and a feared one runs off, so the walk toward it only drags the mob with us // and costs the casts (Deadmines 627eb082: the priest "stepping to tank" with Terrify on the tank, 25 y away). Stand and cast. if (tk->is_controlled) @@ -1148,7 +1162,12 @@ bool LooseMobEscape(BotAI& ai, BotSnapshotView const& s, GroupSnapshotView const } const float dx = tk->x - bx, dy = tk->y - by, dz = tk->z - bz; const float d2 = dx * dx + dy * dy + dz * dz; - if (d2 <= 6.0f * 6.0f || d2 > 80.0f * 80.0f) return false; // already on the tank / not this fight's tank + if (d2 <= 6.0f * 6.0f || d2 > 80.0f * 80.0f) // already on the tank / not this fight's tank + { + if (d2 > 80.0f * 80.0f) + note("the tank is over 80 y away"); + return false; + } const float dist = std::sqrt(d2); const float step = std::min(15.0f, dist - 4.0f); // A healer keeps healing on the run: instant heals / HoTs / Power Word: @@ -1172,10 +1191,21 @@ bool LooseMobEscape(BotAI& ai, BotSnapshotView const& s, GroupSnapshotView const // rotation keeps the bot alive in place (and the drops above already ran). // Nor into an idle pack's aggro reach (raid): the tank comes for the mob // instead (its taunt / pick-up), a step into the next pack adds one. - if (RaidStandPointBlocked(s, sx, sy, sz) || RaidPointInUnpulledReach(s, sx, sy, sz)) return false; + // exc_full af66: Shadetooth feared the mage away four times and killed her 80 y from the group in 90 s, and no line told which of + // these gates kept her from walking it back. Each one says so now (paced with the others, 4 s). + if (RaidStandPointBlocked(s, sx, sy, sz) || RaidPointInUnpulledReach(s, sx, sy, sz)) + { + note(fmt::format("the step to the tank, {:.0f} y away, is blocked ({:.1f},{:.1f},{:.1f}): {}", dist, sx, sy, sz, + RaidStandPointBlocked(s, sx, sy, sz) ? "hazard or avoid circle" : "an idle pack's reach").c_str()); + return false; + } if (!emit.move_to(sx, sy, sz, /*run*/ true)) { - if (!s.has_path_destination()) return false; + if (!s.has_path_destination()) + { + note(fmt::format("the step to the tank, {:.0f} y away, was refused ({:.1f},{:.1f},{:.1f})", dist, sx, sy, sz).c_str()); + return false; + } heal_on_the_run(); // same step already under way: keep it return true; } @@ -1348,11 +1378,20 @@ bool PreemptiveTankHeal(BotAI& ai, BotSnapshotView const& s, GroupSnapshotView c if (CH::Dist2(tk->x, tk->y, tk->z, bx, by, bz) > CH::kHealRange * CH::kHealRange || !CH::InLos(s, tk->guid)) return false; CH::Patient const tank = CH::MakePatient(s, tk->guid, tk->hp, tk->max_hp, tk->x, tk->y, tk->z, true); - if (tank.actual_pct <= 65 || tank.incoming <= 0) return false; + // An add of the map's burstTank list on the tank (Raid::HitsTankHard) is one whose single hit takes the tank from full to a quarter: + // it counts as a boss, and its healers keep a heal going whoever else is hurt and however full the tank is. naxx_kelthuzad kt70c + // (1124): an Unstoppable Abomination's Mortal Wound (200% weapon damage, 7,500-9,000 on a tank) killed the bear from 72% and from + // full, the healers at 95-99% mana cast nothing from 73 s to 94 s ("hurt tanks 0"), and the pre-heal ran 12 times in the pull. The + // Soldiers' Dark Blast (1,750 to the whole room every few seconds) leaves somebody under 80% most of the time, which stands the + // pre-heal down below. + bool burst = false; + for (NearbyUnit const& u : s.nearby_enemies()) + if (u.hp > 0 && u.victim == tank.guid && Raid::HitsTankHard(s.map_id(), u.entry)) { burst = true; break; } + if (tank.actual_pct <= 65 || (tank.incoming <= 0 && !burst)) return false; // No top-off on a tank near full unless the swings on it would take it under the spike mark (a boss on the tank hits every // 2 s; a heal per hit was the largest mana sink of the Garr kill, MC 2026-10-10). - if (tank.actual_pct >= CH::kRaidTankSpikeFloorPct && tank.hp_pct >= CH::kRaidTankSpikePct) return false; - bool boss = false; + if (!burst && tank.actual_pct >= CH::kRaidTankSpikeFloorPct && tank.hp_pct >= CH::kRaidTankSpikePct) return false; + bool boss = burst; for (NearbyUnit const& u : s.nearby_enemies()) if (u.hp > 0 && u.victim == tank.guid && Classic::IsBossUnit(u)) { boss = true; break; } if (!boss && tank.incoming * 20 < tank.max_hp) return false; // light trash hits: the rotation's @@ -1360,14 +1399,18 @@ bool PreemptiveTankHeal(BotAI& ai, BotSnapshotView const& s, GroupSnapshotView c // pull was most of the level-21 priest's mana (deadmines_full run 10). In a raid it stays for mana of 70% and up. if (!boss && (!s.is_in_raid() || CH::ManaPct(s) < 70)) return false; CH::Patient const best = CH::PickPatient(s, g); - if (best.valid && best.guid != tank.guid && best.hp_pct < 80) return false; + if (!burst && best.valid && best.guid != tank.guid && best.hp_pct < 80) return false; if (Classic::PickDispel(s, g).spell) return false; const uint32 top = s.resolve_rank(spell); SpellInfo const* si = top ? sSpellMgr->GetSpellInfo(top, DIFFICULTY_NONE) : nullptr; const int32 cast_ms = si && si->CastTimeEntry ? std::max(si->CastTimeEntry->Base, 0) : 2500; const float swings = std::max(1.0f, float(cast_ms) / 2000.0f); - const float want = float(tank.max_hp - tank.hp) + float(tank.incoming) * swings; + float want = float(tank.max_hp - tank.hp) + float(tank.incoming) * swings; + // A burst add's next hit is a quarter of the tank or more: the heal is sized for that hit, landed or not yet (CancelOverheal stops it + // in its last half-second when the tank is still full). + if (burst) + want = std::max(want, float(tank.max_hp) * 0.5f); // Only when the swings expected over the cast take the tank clearly under // full: at 100% a 10% hit leaves it at 90% and the heal lands as an // overheal (MC 2026-10-06: pre-heals on a 100% tank, cancelled or not, @@ -1378,7 +1421,7 @@ bool PreemptiveTankHeal(BotAI& ai, BotSnapshotView const& s, GroupSnapshotView c constexpr float kPreHealProjectedPct = 85.0f; constexpr float kPreHealBossProjectedPct = 95.0f; float const projected_limit = boss ? kPreHealBossProjectedPct : kPreHealProjectedPct; - if ((float(tank.hp) - float(tank.incoming) * swings) * 100.0f >= float(tank.max_hp) * projected_limit) return false; + if (!burst && (float(tank.hp) - float(tank.incoming) * swings) * 100.0f >= float(tank.max_hp) * projected_limit) return false; // Another healer's pre-heal already on its way covers the deficit. if (CH::HealClaimsOn()) // Playerbot.Behavior.HealClaims { @@ -1392,7 +1435,7 @@ bool PreemptiveTankHeal(BotAI& ai, BotSnapshotView const& s, GroupSnapshotView c CH::NoteHealClaim(s, tank.guid, plan.rank ? plan.rank : top, plan.est > 0.0f ? plan.est : plan.want); if (RaidLogDue(CH::HealLogKey(s, CH::HealLogKind::PreHeal), s.published_at_ms(), 5000u)) TC_LOG_INFO("playerbot.v2", "[raid_heal] {} pre-heals tank {} at {}% ({} incoming{}) with {} (want {:.0f}, est {:.0f}, mana {}%)", - s.name(), tank.guid.GetCounter(), tank.actual_pct, tank.incoming, boss ? ", boss" : "", + s.name(), tank.guid.GetCounter(), tank.actual_pct, tank.incoming, burst ? ", burst add" : boss ? ", boss" : "", plan.rank ? plan.rank : top, plan.want, plan.est, CH::ManaPct(s)); ai.set_last_rule_fired("combat:raid_preheal_tank"); return true; @@ -2452,6 +2495,10 @@ static bool GroupFightPick(BotAI& ai, BotSnapshotView const& s, GroupSnapshotVie } if (units[pick]->guid == cur) return false; + // The pull delay (Bot/PullDelay.h): no start on the tank's mob before it is over, or the victim hold below stops the attack + // on the next tick and the pick starts it again. Melee walk up meanwhile (ThreatHoldWait). + if (role != Role::Tank && PartyPullDelayHolds(ai, s, units[pick]->guid)) + return ThreatHoldWait(ai, s, emit, units[pick]->guid, ThreatHold::TankOpening, IsMeleeSpec(s.cls(), s.spec())); uint32& last = ai.group_fight_pick_ms(); if (last != 0 && now - last < 2000u && cur_ok) return false; @@ -2864,7 +2911,8 @@ void DispatchInCombat(BotAI& ai, // A bot in tar, lava or a slime with a spell walks to the nearest dry ground (the builder's water_escape point) before anything // below moves it or roots it in a cast, everywhere: idle:flee_damaging_liquid only runs out of combat. shapers_full af51 (20 Nov): // the rogue chased an Ironhide Ravasaur into the Tar Pits and swung at it there until the tar killed her (killer=self). The melee - // gap-close does not follow a victim standing in such a liquid (chase_blocked below), so the bot stays on the bank. + // gap-close does not follow a victim standing in such a liquid (chase_blocked below): the bot stays on the bank, or walks to a + // dry bank spot inside its reach (victim_bank). if (snapshot.is_in_damaging_liquid() && snapshot.water_escape_valid() && snapshot.is_alive() && !snapshot.is_rooted() && !snapshot.on_transport()) { @@ -2876,6 +2924,13 @@ void DispatchInCombat(BotAI& ai, return; } + // ---- Up for air ([breath], SurfaceForAir) ---- + // A fight under water uses up the breath as a swim does, and the idle rule never ran during one: the Vile Reef mage fought on the + // reef, then sat down 25 y deep to eat and drowned before the idle clock got to 35 s (vile_reef_fight af64). On the server's + // breath timer: up with 25 s left, back down to the fight once the bar is full. + if (SurfaceForAir(snapshot, ai, emit, "combat:surface_to_breathe")) + return; + // ---- Out of a fighting mob's area attack ([area_attack_step], State_Idle.cpp) ---- // A healer or ranged bot in reach of a mob's Frost Nova / Thunderclap that is not on it steps out before anything below roots it // in a cast (rol_full af52: The Abandoned). Instances only. @@ -4596,11 +4651,45 @@ void DispatchInCombat(BotAI& ai, // An owner Stay / Hold keeps the bot at its spot too: a mob out of reach is not chased (a mob on the bot lifts the hold). // Nor is a victim standing in a burning liquid (tar, lava), anywhere: the bot waits on the bank for the mob to come out // to it, as a player does ([liquid_escape] above takes it out if it is in already). + // ...unless there is a bank in reach of it: a dry spot inside the bot's melee reach, reached by a dry path (the snapshot's + // victim_bank). The bot walks there and swings from it, as a player does. Ragnaros never leaves his lava: with only the wait, + // every melee bot stood 37-40 y off for the whole fight, 0 hits on him (mc_ragnaros af53 1120, BUGS-ALL 312). const bool victim_in_burning_liquid = snapshot.raw().combat.victim_in_damaging_liquid; + const bool victim_bank = victim_in_burning_liquid && snapshot.raw().combat.victim_bank_known; + // The bot fights from its own side of the victim, at melee reach, not on the victim's centre: the test is where it would + // stand. A victim on the rim of a circle is fought from outside it, a victim deep inside is still waited for. + // naxx_kelthuzad kt62a (1123): an Abomination stood 29.5 y from an alcove's centre (keep-out 30 y, +2 y margin) and 10 y + // from its tank, which stood outside the circle and held ("combat:melee_hold_hazard") for 18 s while the Abomination killed + // five DPS; Taunt is melee range. A victim in a burning liquid with a bank keeps the bank test (the bank is the stand spot). + float stop_x = vu->x, stop_y = vu->y; + bool stand_off_victim = false; + bool chase_hazard = false; + if (victim_bank) + { + chase_hazard = snapshot.is_in_instance() && !snapshot.in_battleground() && + RaidStandPointBlocked(snapshot, snapshot.raw().combat.victim_bank_x, snapshot.raw().combat.victim_bank_y, + snapshot.raw().combat.victim_bank_z); + } + else if (d2 > kMeleeRange * kMeleeRange && snapshot.is_in_instance() && !snapshot.in_battleground() && + RaidStandPointBlocked(snapshot, vu->x, vu->y, vu->z)) + { + chase_hazard = true; + const float d2d = std::sqrt(dx * dx + dy * dy); + const float stand = std::max(kMeleeRange - 1.0f, 1.0f); + if (d2d > stand + 0.5f) + { + stop_x = vu->x - dx / d2d * stand; + stop_y = vu->y - dy / d2d * stand; + if (!RaidStandPointBlocked(snapshot, stop_x, stop_y, vu->z)) + { + chase_hazard = false; + stand_off_victim = true; + } + } + } const bool chase_blocked = d2 > kMeleeRange * kMeleeRange && - ((snapshot.is_in_instance() && !snapshot.in_battleground() && - RaidStandPointBlocked(snapshot, vu->x, vu->y, vu->z)) || - victim_in_burning_liquid || + (chase_hazard || + (victim_in_burning_liquid && !victim_bank) || HeldByOwner(ai, snapshot)); // Stuck-chase tracking: count ticks where we're out of melee // range with the same victim. Reset on different victim or once @@ -4637,10 +4726,15 @@ void DispatchInCombat(BotAI& ai, } else if (d2 > kMeleeRange * kMeleeRange) { - if (ai.stuck_chase_victim() == snapshot.victim()) - ai.set_stuck_chase(snapshot.victim(), ai.stuck_chase_ticks() + 1); - else - ai.set_stuck_chase(snapshot.victim(), 1); + // A bot walking to the bank of a victim in a burning liquid is not stuck: the bank can be 40 y off (the melee pre-pull + // spot at Ragnaros), more than the 5 s cap at run speed. + if (!(victim_bank && snapshot.is_moving())) + { + if (ai.stuck_chase_victim() == snapshot.victim()) + ai.set_stuck_chase(snapshot.victim(), ai.stuck_chase_ticks() + 1); + else + ai.set_stuck_chase(snapshot.victim(), 1); + } // A tank never gives up a mob that is on a group member: dropping it leaves the mob killing the healer // (deadmines_full run 8: Rhahk'Zor on the priest for 57 s, the warrior silent after its 5 s chase cap). Its // chase ends when the mob is in reach (Taunt / melee) or dies; a victim it truly cannot path to is handled @@ -4727,7 +4821,9 @@ void DispatchInCombat(BotAI& ai, while (diff < -float(M_PI)) diff += 2.0f * float(M_PI); in_front_of_victim = std::fabs(diff) < 0.5f * float(M_PI); } - if (Services::Config().behavior_spread_out() && in_front_of_victim && + // Not round a victim in a burning liquid: its spread spot is in the liquid, and the bank the bot stands on is the only + // dry footing in reach. + if (Services::Config().behavior_spread_out() && in_front_of_victim && !victim_in_burning_liquid && vu->victim != snapshot.guid() && ai.effective_role(snapshot) != Role::Tank && !snapshot.is_rooted() && !snapshot.is_casting() && !snapshot.has_path_destination() && !ai.action_recently_tried(BotAI::ActionKind::RaidSpacing, 0, snapshot.published_at_ms())) @@ -4768,7 +4864,7 @@ void DispatchInCombat(BotAI& ai, else { // Default: gap-close to the victim. - float cx = vu->x, cy = vu->y, cz = vu->z; + float cx = stand_off_victim ? stop_x : vu->x, cy = stand_off_victim ? stop_y : vu->y, cz = vu->z; // Travel-through-combat (2026-06-15): when the bot has a FAR // same-map travel objective it is IN TRANSIT — incidental aggro // must not pull it off-course chasing mobs. Live: Somi drifted @@ -4810,6 +4906,17 @@ void DispatchInCombat(BotAI& ai, constexpr float kReplanRange = 3.0f; if (pd2 < kReplanRange * kReplanRange) already_pathing = true; } + // A victim in a burning liquid: its bank spot, not its centre (the move gate refuses a point in the liquid). + if (victim_bank) + { + cx = snapshot.raw().combat.victim_bank_x; + cy = snapshot.raw().combat.victim_bank_y; + cz = snapshot.raw().combat.victim_bank_z; + if (RaidLogDue(RaidLogKey(snapshot, RaidLogKind::ThreatHold) ^ 0x62616e6bu, snapshot.published_at_ms(), 5000u)) + TC_LOG_INFO("playerbot.v2", "[liquid_bank] {} walks to ({:.1f},{:.1f},{:.1f}) to hit entry {} in a burning liquid from the bank ({:.1f} y from it, reach {:.1f} y)", + snapshot.name(), cx, cy, cz, vu->entry, std::sqrt((cx - vu->x) * (cx - vu->x) + (cy - vu->y) * (cy - vu->y) + (cz - vu->z) * (cz - vu->z)), + kMeleeRange); + } // SpreadOut: walk to this bot's own spot round the victim's back / sides, not its centre. if (cx == vu->x && cy == vu->y) { diff --git a/src/modules/PlayerbotV2/Bot/States/State_InGroup.cpp b/src/modules/PlayerbotV2/Bot/States/State_InGroup.cpp index 82f1ba292a..8ed57af5f0 100644 --- a/src/modules/PlayerbotV2/Bot/States/State_InGroup.cpp +++ b/src/modules/PlayerbotV2/Bot/States/State_InGroup.cpp @@ -218,7 +218,9 @@ void DispatchInGroup(BotAI& ai, // When THIS bot is leader AND any non-bot human is in the group, // hand over leadership. Picks the first non-bot human in the // member list (stable enough; could be refined to prefer owner). - if (group.leader() == snapshot.raw().guid) + // A self bot is that human: it keeps the lead (selfbot-loot af59c: it handed the group to the other player at once, then counted + // as led by him and left every corpse of the party). + if (group.leader() == snapshot.raw().guid && !snapshot.raw().plays_as_human) { BotRegistry& reg_promote = Services::Registry(); ObjectGuid promote_target; diff --git a/src/modules/PlayerbotV2/Bot/TownErrand.h b/src/modules/PlayerbotV2/Bot/TownErrand.h index 5b5227b3a3..e0812b6d55 100644 --- a/src/modules/PlayerbotV2/Bot/TownErrand.h +++ b/src/modules/PlayerbotV2/Bot/TownErrand.h @@ -15,13 +15,15 @@ #include #include #include +#include #include #include namespace Playerbot::V2::TownErrand { -enum class Kind : std::uint8_t { None = 0, Auction, Bank, Trainer, Inn, Mailbox, Flight, Vendor, Battlemaster, Stable, Exit }; +enum class Kind : std::uint8_t { None = 0, Auction, Bank, Trainer, Inn, Mailbox, Flight, Vendor, Battlemaster, Stable, Exit, + Forge, Cookfire, Loom, Moonwell }; inline char const* KindName(Kind k) { @@ -37,21 +39,66 @@ inline char const* KindName(Kind k) case Kind::Battlemaster: return "battlemaster"; case Kind::Stable: return "stable master"; case Kind::Exit: return "city gate"; + case Kind::Forge: return "forge"; + case Kind::Cookfire: return "cooking fire"; + case Kind::Loom: return "loom"; + case Kind::Moonwell: return "moonwell"; default: return "-"; } } +// A station a bot can pretend to work at (or really craft at), not an NPC errand. +inline bool IsCraftKind(Kind k) +{ + return k == Kind::Forge || k == Kind::Cookfire || k == Kind::Loom || k == Kind::Moonwell; +} + +// The SpellFocusObject.dbc name of a station's focus type -> its errand kind. Classification is by name, not id, so the +// mapping survives the focus ids differing between cores and expansions. Kind::None = not a station we send bots to. +inline Kind KindForFocusName(std::string_view name) +{ + char lower[64]; + std::size_t const n = name.size() < sizeof(lower) - 1 ? name.size() : sizeof(lower) - 1; + for (std::size_t i = 0; i < n; ++i) + lower[i] = char(name[i] | 0x20); // ASCII lowercase + lower[n] = '\0'; + std::string_view const s(lower, n); + auto has = [&](std::string_view w) { return s.find(w) != std::string_view::npos; }; + if (has("anvil") || has("forge") || has("smelt") || has("furnace")) return Kind::Forge; + if (has("cook") || has("stove") || has("bonfire") || has("campfire")) return Kind::Cookfire; + if (has("loom")) return Kind::Loom; + if (has("moonwell") || has("moon well")) return Kind::Moonwell; + return Kind::None; +} + +// The looped "using the station" emote state played while lingering at a craft kind when the bot has nothing it can +// really craft (EMOTE_STATE_* ids; a real craft cast overrides this). Kind::None callers get 0. +inline std::uint32_t WorkEmoteFor(Kind k) +{ + switch (k) + { + case Kind::Forge: return 173; // EMOTE_STATE_WORK: hammering loop + case Kind::Cookfire: return 69; // EMOTE_STATE_USE_STANDING: crouched at the fire + case Kind::Loom: return 173; // EMOTE_STATE_WORK + case Kind::Moonwell: return 68; // EMOTE_STATE_KNEEL + default: return 0; + } +} + struct Dest { Kind kind = Kind::None; std::uint64_t key = 0; // the NPC or mailbox spawn id; for the gate, a fixed key - std::uint32_t entry = 0; // creature entry, to face the live NPC on arrival (0 = a mailbox or the gate) + std::uint32_t entry = 0; // creature entry, to face the live NPC on arrival (0 = a mailbox, station or the gate) float x = 0.f, y = 0.f, z = 0.f; float weight = 0.f; // how much this place draws a bot right now (BaseWeight, raised by a need) + std::uint32_t focus_type = 0; // craft kinds only: the station's SpellFocusObject id, to match recipes against + float orientation = -1.f; // NPC kinds: the spawn's facing — the customer side for StandPoint (-1 = none) }; // How much each kind of place draws a resident. The bank and the auction house are where a city's crowd is; a bot's own trainer and -// the flight master are errands with a purpose; vendors are many, so each draws little. +// the flight master are errands with a purpose; vendors are many, so each draws little. The craft stations draw little on their +// own — the fixture steering (Playerbot.World.Town.Fixture.*) is what keeps them occupied, not the roll. inline float BaseWeight(Kind k) { switch (k) @@ -66,6 +113,10 @@ inline float BaseWeight(Kind k) case Kind::Battlemaster: return 1.5f; case Kind::Stable: return 1.5f; case Kind::Exit: return 2.0f; + case Kind::Forge: return 1.0f; + case Kind::Cookfire: return 0.8f; + case Kind::Loom: return 0.3f; + case Kind::Moonwell: return 0.3f; default: return 0.0f; } } @@ -122,11 +173,15 @@ inline int Pick(std::vector const& dests, float bx, float by, float max_ya // Where a bot stands at a place: on the side it comes from, at `ring` yards, turned by its slot so the bots at one place stand side by // side instead of on one point. `slot` 0.. (the order the place was claimed in). -inline void StandPoint(float px, float py, float bx, float by, float ring, std::uint32_t slot, float& sx, float& sy) +// The point on the place's ring a bot stands at. `face` is the direction the place faces its customers +// (an NPC's spawn orientation — a banker faces the queue, an auctioneer the hall); a negative value is +// none, and the near side to the walking bot is used (right for a round prop: mailbox, anvil, gate). +inline void StandPoint(float px, float py, float bx, float by, float ring, std::uint32_t slot, float& sx, float& sy, + float face = -100.0f) { float const dx = bx - px, dy = by - py, len = std::hypot(dx, dy); - float base = len > 0.5f ? std::atan2(dy, dx) : 0.0f; - // 0, +0.55, -0.55, +1.1, -1.1 ... radians: a fan on the near side + float base = face >= 0.0f ? face : (len > 0.5f ? std::atan2(dy, dx) : 0.0f); + // 0, +0.55, -0.55, +1.1, -1.1 ... radians: a fan on the facing side float const step = float((slot + 1u) / 2u) * 0.55f; base += (slot % 2u) ? step : -step; sx = px + std::cos(base) * ring; @@ -244,9 +299,26 @@ struct State bool issued = false; // the move to the place has gone out bool leaving = false; // this errand is the walk out of the city (the bot's town time is over) std::uint32_t leave_until_ms = 0; // out at the gate: no errands, the bot heads off to level until then + std::uint32_t focus_type = 0; // craft kinds: the station's SpellFocusObject id, for matching recipes + std::uint32_t next_use_ms = 0; // the next "use the place" beat (craft cast, work emote, mid-linger fidget) + bool work_emote = false; // a looped work emote is up: clear it when the errand ends + std::uint32_t next_sound_ms = 0; // next one-shot sound push while the work emote loops + std::uint8_t tool_bag = 0xFF; // the bag slot the profession tool came out of for the station show + std::uint8_t tool_slot = 0xFF; // (the swap put the weapon there: equipping it back restores the kit) + std::uint64_t tool_guid = 0; // the swap's item (raw guid) — two same-entry tools (one equipped, one bagged) ping-pong forever on entry matching alone + bool kit_ready = false; // the kit is confirmed: the tool's in hand, or the station needs none + bool tool_in_hand = false; // the swap landed — the tool was seen leaving the bags, not just pushed + std::uint8_t kit_attempts = 0; // failed acquisition checks — a few and the visit is abandoned + std::uint32_t next_kit_ms = 0; // the next kit check (a quicker cadence than the use-beat) + bool stock_given = false; // reagents for the recipe were conjured once this errand + bool recipe_given = false; // the station's starter recipe was taught once this errand (pre-pipeline bots) + bool want_vendor = false; // a kit visit that couldn't start (full bags) steers the next errand to a vendor + std::uint32_t pause_until_ms = 0; // settle beat set by EndErrand after Clear: stand a moment before the next pick walks off (no mid-swing slide) Recent recent; - void Clear() { kind = Kind::None; key = 0; place = 0; entry = 0; phase = 0; near_player_ms = 0; issued = false; leaving = false; prog_ms = 0; } + // want_vendor outlives the errand that set it — it's the reason for the next one. + void Clear() { kind = Kind::None; key = 0; place = 0; entry = 0; phase = 0; near_player_ms = 0; issued = false; leaving = false; prog_ms = 0; + focus_type = 0; next_use_ms = 0; work_emote = false; next_sound_ms = 0; tool_bag = tool_slot = 0xFF; tool_guid = 0; kit_ready = false; tool_in_hand = false; kit_attempts = 0; next_kit_ms = 0; stock_given = false; recipe_given = false; pause_until_ms = 0; } }; // Has the walking bot stopped getting closer? It counts as progress to move `yards` in `window_ms`. diff --git a/src/modules/PlayerbotV2/Bot/TownErrandConfig.h b/src/modules/PlayerbotV2/Bot/TownErrandConfig.h index c1cce61b42..812b595787 100644 --- a/src/modules/PlayerbotV2/Bot/TownErrandConfig.h +++ b/src/modules/PlayerbotV2/Bot/TownErrandConfig.h @@ -3,6 +3,7 @@ #pragma once #include "Config.h" +#include "Bot/TownErrand.h" #include #include @@ -16,6 +17,23 @@ struct Config float radius = 300.0f; // ErrandRadius: how far across the city the next place may be std::uint32_t linger_min_ms = 4000; // LingerMinSec / LingerMaxSec: the stop at a place std::uint32_t linger_max_ms = 12000; + std::uint32_t linger_bank_min_ms = 20000; // LingerBankMinSec / LingerBankMaxSec: the bank visit + std::uint32_t linger_bank_max_ms = 40000; + std::uint32_t linger_ah_min_ms = 20000; // LingerAhMinSec / LingerAhMaxSec: the auction-house visit + std::uint32_t linger_ah_max_ms = 40000; + std::uint32_t linger_craft_min_ms = 45000; // LingerCraftMinSec / LingerCraftMaxSec: working at a station + std::uint32_t linger_craft_max_ms = 90000; + std::uint32_t fixture_bank = 3; // Fixture.*: bots guaranteed at each place (0 = no fixture for the kind) + std::uint32_t fixture_ah = 3; + std::uint32_t fixture_forge = 2; + std::uint32_t fixture_cookfire = 1; + std::uint32_t fixture_loom = 0; + std::uint32_t fixture_moonwell = 0; + bool craft_cast = true; // CraftCast: really craft a known recipe at a station (0 = work-emote show only) + std::uint32_t craft_sound_forge = 4614; // CraftSound.*: the sound kit pushed to earshot each work + std::uint32_t craft_sound_cookfire = 7035; // beat (the real Tradeskills kits; 0 = silent like vanilla + std::uint32_t craft_sound_loom = 6425; // emote work). 1166 smelt is under Forge; enchanting has + std::uint32_t craft_sound_moonwell = 0; // no dedicated kit. std::uint32_t spot_cap = 5; // SpotCap: bots at one place (a bank, an auction house, a trainer) at once std::uint32_t inn_cap = 4; // InnCap: bots resting at one inn at once std::uint32_t mailbox_cap = 2; // MailboxCap: bots at one mailbox at once @@ -29,6 +47,47 @@ struct Config std::uint32_t field_idle_ms = 30000; // Playerbot.World.IdleSec: the same anywhere else (the idle watch, Bot/IdleWatch.h) }; +// The linger range a place of `kind` gets (the dedicated stays; the generic pair covers everything else). +inline void LingerRange(Config const& c, Kind k, std::uint32_t& min_ms, std::uint32_t& max_ms) +{ + switch (k) + { + case Kind::Bank: min_ms = c.linger_bank_min_ms; max_ms = c.linger_bank_max_ms; return; + case Kind::Auction: min_ms = c.linger_ah_min_ms; max_ms = c.linger_ah_max_ms; return; + case Kind::Forge: case Kind::Cookfire: case Kind::Loom: case Kind::Moonwell: + min_ms = c.linger_craft_min_ms; max_ms = c.linger_craft_max_ms; return; + default: min_ms = c.linger_min_ms; max_ms = c.linger_max_ms; return; + } +} + +// How many bots a place of `kind` keeps occupied through the fixture steering (0 = no fixture). +inline std::uint32_t FixtureTarget(Config const& c, Kind k) +{ + switch (k) + { + case Kind::Bank: return c.fixture_bank; + case Kind::Auction: return c.fixture_ah; + case Kind::Forge: return c.fixture_forge; + case Kind::Cookfire: return c.fixture_cookfire; + case Kind::Loom: return c.fixture_loom; + case Kind::Moonwell: return c.fixture_moonwell; + default: return 0; + } +} + +// The SoundKit pushed to earshot on each work beat at a place of a kind (0 = silent). +inline std::uint32_t SoundKitFor(Config const& c, Kind k) +{ + switch (k) + { + case Kind::Forge: return c.craft_sound_forge; + case Kind::Cookfire: return c.craft_sound_cookfire; + case Kind::Loom: return c.craft_sound_loom; + case Kind::Moonwell: return c.craft_sound_moonwell; + default: return 0; + } +} + inline Config const& Cfg() { static Config const c = [] @@ -39,6 +98,26 @@ inline Config const& Cfg() k.linger_min_ms = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.LingerMinSec", 4, true), 0, 300)) * 1000u; k.linger_max_ms = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.LingerMaxSec", 12, true), 0, 600)) * 1000u; k.linger_max_ms = std::max(k.linger_max_ms, k.linger_min_ms); + k.linger_bank_min_ms = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.LingerBankMinSec", 20, true), 0, 300)) * 1000u; + k.linger_bank_max_ms = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.LingerBankMaxSec", 40, true), 0, 600)) * 1000u; + k.linger_bank_max_ms = std::max(k.linger_bank_max_ms, k.linger_bank_min_ms); + k.linger_ah_min_ms = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.LingerAhMinSec", 20, true), 0, 300)) * 1000u; + k.linger_ah_max_ms = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.LingerAhMaxSec", 40, true), 0, 600)) * 1000u; + k.linger_ah_max_ms = std::max(k.linger_ah_max_ms, k.linger_ah_min_ms); + k.linger_craft_min_ms = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.LingerCraftMinSec", 45, true), 0, 300)) * 1000u; + k.linger_craft_max_ms = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.LingerCraftMaxSec", 90, true), 0, 600)) * 1000u; + k.linger_craft_max_ms = std::max(k.linger_craft_max_ms, k.linger_craft_min_ms); + k.fixture_bank = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.Fixture.Bank", 3, true), 0, 50)); + k.fixture_ah = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.Fixture.Ah", 3, true), 0, 50)); + k.fixture_forge = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.Fixture.Forge", 2, true), 0, 50)); + k.fixture_cookfire = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.Fixture.Cookfire", 1, true), 0, 50)); + k.fixture_loom = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.Fixture.Loom", 0, true), 0, 50)); + k.fixture_moonwell = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.Fixture.Moonwell", 0, true), 0, 50)); + k.craft_cast = sConfigMgr->GetBoolDefault("Playerbot.World.Town.CraftCast", true, true); + k.craft_sound_forge = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.CraftSound.Forge", 4614, true), 0, 100000)); + k.craft_sound_cookfire = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.CraftSound.Cookfire", 7035, true), 0, 100000)); + k.craft_sound_loom = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.CraftSound.Loom", 6425, true), 0, 100000)); + k.craft_sound_moonwell = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.CraftSound.Moonwell", 0, true), 0, 100000)); k.spot_cap = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.SpotCap", 5, true), 1, 100)); k.inn_cap = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.InnCap", 4, true), 0, 100)); k.mailbox_cap = std::uint32_t(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.Town.MailboxCap", 2, true), 0, 100)); diff --git a/src/modules/PlayerbotV2/Bot/World/HunterPetsByRace.h b/src/modules/PlayerbotV2/Bot/World/HunterPetsByRace.h index 7db43a03f6..3448449b89 100644 --- a/src/modules/PlayerbotV2/Bot/World/HunterPetsByRace.h +++ b/src/modules/PlayerbotV2/Bot/World/HunterPetsByRace.h @@ -32,8 +32,8 @@ uint32 HunterPetEntryForRace(uint32 race); constexpr uint32 GenericAllianceHunterPet = 299; // Young Wolf (Elwynn Forest) constexpr uint32 GenericHordeHunterPet = 3099; // Dire Mottled Boar (Valley of Trials; 5826 was Geolord Mottle, a quilboar) -// A world (ambient) hunter's own first pet, stable per bot: one of the faction's classic starter beasts picked by guid, so a street of -// hunters is not all one race's beast. Creature entries of HunterPetEntryForRace's classic races; the caller's tameable check still +// A hunter bot's own first pet, stable per bot: one of the faction's classic starter beasts picked by guid, so a street of hunters, or +// a player's hired ones, is not all one race's beast. Creature entries of HunterPetEntryForRace's classic races; the caller's tameable check still // decides whether the pick exists as a beast in this data. `fallback` (the race's pet) is returned for an owned bot (guid 0). inline uint32 VariedHunterPetEntry(bool alliance, uint64 guid, uint32 fallback) { diff --git a/src/modules/PlayerbotV2/Bot/World/ZonePicker.cpp b/src/modules/PlayerbotV2/Bot/World/ZonePicker.cpp index fd15a58ae6..3948686f1e 100644 --- a/src/modules/PlayerbotV2/Bot/World/ZonePicker.cpp +++ b/src/modules/PlayerbotV2/Bot/World/ZonePicker.cpp @@ -561,18 +561,29 @@ std::vector const& GrindSpotsFor(bool alliance) continue; if ((t->flags_extra & CREATURE_FLAG_EXTRA_CIVILIAN) || uint64(data.npcflag.value_or(t->npcflag)) != 0) continue; - CreatureDifficulty const* cd = t->GetDifficulty(DIFFICULTY_NONE); - if (!cd) - continue; - Optional lv = sDB2Manager.GetContentTuningData(cd->ContentTuningID, {}); - if (!lv || lv->MinLevel <= 0) + // The level the creature spawns at, read as Creature::ApplyLevelScaling does: the Classic range (the spawn's own, then the + // entry's) first, ContentTuning only for a creature without one. The client's ContentTuning store has about a hundred rows + // and most Classic creatures have none in it: the index kept 347 of some 55,000 spawns and every leveling zone sat at the + // mob supply floor (ForeverCore issue #385, sqmagellan). + std::pair const* classic = sObjectMgr->GetCreatureClassicSpawnLevel(spawn_id); + if (!classic) + classic = sObjectMgr->GetCreatureClassicLevel(data.id); + uint32 level = 0; + if (classic) + level = (uint32(classic->first) + std::max(classic->first, classic->second)) / 2; + else if (CreatureDifficulty const* cd = t->GetDifficulty(DIFFICULTY_NONE)) + { + Optional lv = sDB2Manager.GetContentTuningData(cd->ContentTuningID, {}); + if (lv && lv->MinLevel > 0) + level = uint32((lv->MinLevel + std::max(lv->MinLevel, lv->MaxLevel)) / 2); + } + if (!level) continue; FactionTemplateEntry const* ft = sFactionTemplateStore.LookupEntry(t->faction); if (!ft) continue; ++mobs; - GrindSample smp{ data.mapId, data.spawnPoint.GetPositionX(), data.spawnPoint.GetPositionY(), data.spawnPoint.GetPositionZ(), - uint32((lv->MinLevel + std::max(lv->MinLevel, lv->MaxLevel)) / 2) }; + GrindSample smp{ data.mapId, data.spawnPoint.GetPositionX(), data.spawnPoint.GetPositionY(), data.spawnPoint.GetPositionZ(), level }; for (int side = 0; side < 2; ++side) if (ft_side[side] && (ft->IsHostileTo(ft_side[side]) || ft_side[side]->IsHostileTo(ft))) samples[side].push_back(smp); diff --git a/src/modules/PlayerbotV2/Combat/Apl/ApClassicHeal.h b/src/modules/PlayerbotV2/Combat/Apl/ApClassicHeal.h index 3b146eb3dd..c6dc4e13cf 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/ApClassicHeal.h +++ b/src/modules/PlayerbotV2/Combat/Apl/ApClassicHeal.h @@ -266,8 +266,10 @@ inline bool InLos(BotSnapshotView const& s, ObjectGuid guid) return true; } +// aura_due: what the patient's own periodic auras deal it before a slow heal lands (GroupMemberSummary::aura_damage_due), counted +// whole with the swings (armour does not take it). inline Patient MakePatient(BotSnapshotView const& s, ObjectGuid guid, int64 hp, int64 max_hp, - float x, float y, float z, bool tank) + float x, float y, float z, bool tank, int64 aura_due = 0) { Patient p; p.guid = guid; @@ -279,7 +281,7 @@ inline Patient MakePatient(BotSnapshotView const& s, ObjectGuid guid, int64 hp, return p; // Swings are pre-armour; a tank in plate (or bear form) takes roughly half of that. int64 const swings = IncomingMelee(s, guid, x, y, z); - p.incoming = std::min(tank ? swings / 2 : swings, hp); + p.incoming = std::min((tank ? swings / 2 : swings) + std::max(aura_due, 0), hp); p.actual_pct = int32(hp * 100 / max_hp); p.hp_pct = int32((hp - p.incoming) * 100 / max_hp); return p; @@ -289,11 +291,12 @@ inline Patient MakePatient(BotSnapshotView const& s, ObjectGuid guid, int64 hp, inline Patient SelfPatient(BotSnapshotView const& s, GroupSnapshotView const& g) { bool tank = false; + int64 aura_due = 0; if (auto const* members = g.members()) for (GroupMemberSummary const& m : *members) - if (m.guid == s.guid()) { tank = IsTank(s, m); break; } + if (m.guid == s.guid()) { tank = IsTank(s, m); aura_due = m.aura_damage_due; break; } float x, y, z; s.position(x, y, z); - return MakePatient(s, s.guid(), s.hp(), s.max_hp(), x, y, z, tank); + return MakePatient(s, s.guid(), s.hp(), s.max_hp(), x, y, z, tank, aura_due); } // Patient data for a specific unit (the bot or a group member). @@ -305,7 +308,7 @@ inline Patient PatientFor(BotSnapshotView const& s, GroupSnapshotView const& g, { for (GroupMemberSummary const& m : *members) if (m.guid == guid) - return MakePatient(s, m.guid, m.hp, m.max_hp, m.x, m.y, m.z, IsTank(s, m)); + return MakePatient(s, m.guid, m.hp, m.max_hp, m.x, m.y, m.z, IsTank(s, m), m.aura_damage_due); // A member's pet (PickPatient pet case). for (GroupMemberSummary const& m : *members) if (m.pet_alive && m.pet_guid == guid) @@ -714,7 +717,7 @@ inline Patient PickPatient(BotSnapshotView const& s, GroupSnapshotView const& g, bool const tank = IsTank(s, m); int32 const pct = m.hp_pct(); if (!tank && pct >= kEmergencyPct && !InLos(s, m.guid)) continue; - Patient const mp = MakePatient(s, m.guid, m.hp, m.max_hp, m.x, m.y, m.z, tank); + Patient const mp = MakePatient(s, m.guid, m.hp, m.max_hp, m.x, m.y, m.z, tank, m.aura_damage_due); // A warlock's own Life Tap is intentional damage: not a reason for a heal until he is low (playtest, live MC 2026-10-10). if (raid && LifeTapSkip(m.cls == CLASS_WARLOCK, tank, mp.actual_pct, mp.incoming)) continue; diff --git a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Paladin.cpp b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Paladin.cpp index 34a9f934e5..d03f8d6c06 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Paladin.cpp +++ b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Paladin.cpp @@ -598,10 +598,29 @@ void DoSaveAlly(ApPredicateContext const& ctx, BotIntentEmitter& e) ClassicHeal::EmitHeal(ctx.bot, ctx.group, e, FastHeal(ctx), ClassicHeal::PickPatient(ctx)); } +// A protection paladin heals itself when nobody else will (VempirE, row 382: "as tank, not even self-heals"; the tank rules had +// no heal but Lay on Hands): at 35 % or under, with mana for it and no living healer of its group on its map, the fast heal +// (Flash of Light, before level 20 Holy Light) on itself. With a healer there the tank keeps hitting and the healer heals it. +bool ShouldTankSelfHeal(ApPredicateContext const& ctx) +{ + if (ctx.bot.hp_pct() > 35 || ManaPct(ctx) < 15 || !Ready(ctx, FastHeal(ctx))) + return false; + if (auto const* members = ctx.group.members()) + for (GroupMemberSummary const& m : *members) + if (m.guid != ctx.bot.raw().guid && m.role == Role::Healer && m.online && m.is_alive && m.map_id == ctx.bot.map_id()) + return false; + return true; +} +void DoTankSelfHeal(ApPredicateContext const& ctx, BotIntentEmitter& e) +{ + e.cast(FastHeal(ctx), ctx.bot.raw().guid); +} + ApRule const kTankRules[] = { { ShouldDivineShield, DoDivineShield, "classic_pal_tank:divine_shield" }, { ShouldDivineProtection, DoDivineProtection, "classic_pal_tank:divine_protection" }, { ShouldSelfLayOnHands, DoSelfLayOnHands, "classic_pal_tank:lay_on_hands" }, + { ShouldTankSelfHeal, DoTankSelfHeal, "classic_pal_tank:self_heal" }, { ShouldSaveAlly, DoSaveAlly, "classic_pal_tank:save_ally" }, { ShouldRighteousFury, DoRighteousFury, "classic_pal_tank:righteous_fury" }, { ShouldPaladinAura, DoPaladinAura, "classic_pal_tank:aura" }, diff --git a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Warrior.cpp b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Warrior.cpp index c7fed247af..2fc10a7ac4 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Warrior.cpp +++ b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Warrior.cpp @@ -686,6 +686,44 @@ void DoTankThunderClap(ApPredicateContext const& ctx, BotIntentEmitter& e) } } +// -- Charge opener in the open world -- +// Out of combat with a live target 8-25 y away (Charge's window): Defensive -> Battle -> Charge -> Defensive, the vanilla tank's +// opener, which also brings the first rage. Before, Charge was only in the arms / fury / low-level list, so a Protection bot walked +// to every mob (RU bug list 11-23, row 349). Not in a dungeon or raid: there the pull is planned (the pull back with a ranged opener, +// the pre-pull crowd control) and a Charge into the pack would break it. Never at a crowd-controlled target. +bool ProtChargeWanted(ApPredicateContext const& ctx) +{ + if (ctx.bot.in_combat() || ctx.bot.is_in_instance() || !HasLiveTarget(ctx) || !ctx.bot.knows_spell(CHARGE)) + return false; + NearbyUnit const* v = ctx.bot.victim_info(); + if (!v || v->is_cc_locked || !v->in_los) return false; + float const d = DistToVictim(ctx); + return d >= 8.f && d <= 25.f; +} + +bool ShouldChargeStance(ApPredicateContext const& ctx) +{ + return Services::Config().behavior_warrior_stance_dance() // off: a Protection warrior never leaves Defensive Stance + && !StanceForced(ctx) && InStance(ctx, DEFENSIVE_STANCE) && !DanceLockedOut(ctx) + && Ready(ctx, CHARGE) && StanceReady(ctx, BATTLE_STANCE) && ProtChargeWanted(ctx); +} +void DoChargeStance(ApPredicateContext const& ctx, BotIntentEmitter& e) +{ + if (e.cast(BATTLE_STANCE)) + DanceBegin(ctx, CHARGE); +} + +bool ShouldProtCharge(ApPredicateContext const& ctx) +{ + return InStance(ctx, BATTLE_STANCE) && DanceActive(ctx, CHARGE) && Ready(ctx, CHARGE) + && ctx.bot.victim_in_spell_range(CHARGE) && ProtChargeWanted(ctx); +} +void DoProtCharge(ApPredicateContext const& ctx, BotIntentEmitter& e) +{ + if (e.cast(CHARGE, ctx.bot.victim())) + DanceEnd(ctx); // back to Defensive Stance on the next tick +} + // Stay in Battle Stance only while the dance's ability is still wanted and // waits on nothing but the GCD (the stance change's own); any other case // ends the dance at once. @@ -696,6 +734,8 @@ bool DanceHold(ApPredicateContext const& ctx) return OffOwnCooldown(ctx, MOCKING_BLOW) && Rage(ctx) >= kMockingBlowRage && MockingBlowTarget(ctx) != nullptr; if (DanceActive(ctx, THUNDER_CLAP)) return OffOwnCooldown(ctx, THUNDER_CLAP) && Rage(ctx) >= kThunderClapRage && ThunderClapWorth(ctx); + if (DanceActive(ctx, CHARGE)) + return OffOwnCooldown(ctx, CHARGE) && ProtChargeWanted(ctx); return false; } @@ -1026,6 +1066,8 @@ ApRule const kTankRules[] = { { ShouldFearDanceRage, DoFearDanceRage, "classic_prot:fear_berserker_rage" }, { ShouldFearDanceStance, DoFearDanceStance, "classic_prot:fear_berserker_stance" }, { ShouldMockingBlow, DoMockingBlow, "classic_prot:mocking_blow" }, + { ShouldProtCharge, DoProtCharge, "classic_prot:charge" }, + { ShouldChargeStance, DoChargeStance, "classic_prot:charge_stance" }, { ShouldTankThunderClap, DoTankThunderClap, "classic_prot:thunder_clap" }, { ShouldDefensiveStance, DoDefensiveStance, "classic_prot:defensive_stance" }, { ShouldChallengingShout, DoChallengingShout, "classic_prot:challenging_shout" }, diff --git a/src/modules/PlayerbotV2/Combat/LazyKey.h b/src/modules/PlayerbotV2/Combat/LazyKey.h new file mode 100644 index 0000000000..d14a71fb5d --- /dev/null +++ b/src/modules/PlayerbotV2/Combat/LazyKey.h @@ -0,0 +1,635 @@ +// One-button rotation for every class but the warlock (which keeps its own Combat/LazyLock.h): the decision, on plain numbers. +// +// `.playerbot lazy` (the add-on's "Lazy key") gives the single next spell for the player's class, role and target, from what the +// player knows, what is ready, what is already on the target and the resources. Session/LazyKey.cpp gathers those facts from the live +// Player and casts the answer; this header holds no game objects, so the order of the rules is unit-tested (tests/game/ClassicLazyKey.cpp). +// +// Spell ids are rank 1 of the vanilla (1.12) spells; the caller casts and checks the highest rank the player knows. +// Roles: the player's spec decides (tank / healer spec), `.playerbot lazy dps|tank|heal` overrides it for that press. +// heal the most hurt group member in reach (or the player) gets the heal that fits the gap; with nobody hurt the press fights. +// tank stance / form first, a taunt when the target is on someone else, the threat spells, then the rage dump. +// dps procs and executes, cooldowns on fights that last (bosses, players), dots kept up, the filler. +// Out of combat with nothing selected a press keeps the class's self buffs up. +// `blocked` lets the caller take a spell out of the choice for a while (it was refused): the rest of the list moves up. +#pragma once + +#include +#include +#include +#include + +namespace Playerbot::LazyKey { + +enum class Role : uint8_t { Dps, Tank, Heal }; +enum class Form : uint8_t { None, Bear, Cat, Moonkin, Battle, Defensive, Berserker, Shadow, Stealth }; +enum class At : uint8_t { Target, Self, Healee }; + +// Vanilla classes (ChrClasses ids). +constexpr uint8_t kWarrior = 1, kPaladin = 2, kHunter = 3, kRogue = 4, kPriest = 5, kShaman = 7, kMage = 8, kDruid = 11; + +namespace Id { +// Shared +constexpr uint32_t Shoot = 5019, AutoShot = 75, WeakenedSoul = 6788; +// Warrior +constexpr uint32_t HeroicStrike = 78, Rend = 772, Charge = 100, ThunderClap = 6343, Overpower = 7384, Revenge = 6572, + SunderArmor = 7386, ShieldBlock = 2565, Execute = 5308, Bloodthirst = 23881, MortalStrike = 12294, Whirlwind = 1680, + Cleave = 845, ShieldSlam = 23922, DemoralizingShout = 1160, BattleShout = 6673, Bloodrage = 2687, Taunt = 355, + ShieldBash = 72, Pummel = 6552, SweepingStrikes = 12292, LastStand = 12975, BattleStance = 2457, + DefensiveStance = 71; +// Paladin +constexpr uint32_t SealOfRighteousness = 21084, SealOfCommand = 20375, SealOfTheCrusader = 21082, Judgement = 20271, + HolyLight = 635, FlashOfLight = 19750, HolyShock = 20473, Consecration = 26573, HolyShield = 20925, Exorcism = 879, + HammerOfWrath = 24275, HammerOfJustice = 853, BlessingOfMight = 19740, BlessingOfWisdom = 19742, + DevotionAura = 465, RetributionAura = 7294, RighteousFury = 25780, DivineShield = 642, LayOnHands = 633; +// Hunter +constexpr uint32_t HuntersMark = 1130, SerpentSting = 1978, ArcaneShot = 3044, MultiShot = 2643, AimedShot = 19434, + RaptorStrike = 2973, MongooseBite = 1495, WingClip = 2974, RapidFire = 3045, BestialWrath = 19574, + AspectOfTheHawk = 13165, AspectOfTheMonkey = 13163, TrueshotAura = 19506; +// Rogue +constexpr uint32_t SinisterStrike = 1752, Eviscerate = 2098, SliceAndDice = 5171, Backstab = 53, Kick = 1766, Hemorrhage = 16511, + AdrenalineRush = 13750, BladeFlurry = 13877, ColdBlood = 14177, Riposte = 14251, GhostlyStrike = 14278, + Evasion = 5277, Ambush = 8676, CheapShot = 1833; +// Priest +constexpr uint32_t Smite = 585, ShadowWordPain = 589, MindBlast = 8092, PowerWordShield = 17, Renew = 139, LesserHeal = 2050, + Heal = 2054, FlashHeal = 2061, GreaterHeal = 2060, MindFlay = 15407, Shadowform = 15473, InnerFire = 588, + PowerWordFortitude = 1243, VampiricEmbrace = 15286, HolyFire = 14914, PrayerOfHealing = 596, PsychicScream = 8122, + Silence = 15487; +// Shaman +constexpr uint32_t LightningBolt = 403, EarthShock = 8042, FlameShock = 8050, LightningShield = 324, RockbiterWeapon = 8017, + FlametongueWeapon = 8024, WindfuryWeapon = 8232, HealingWave = 331, LesserHealingWave = 8004, ChainHeal = 1064, + ChainLightning = 421, Stormstrike = 17364, ElementalMastery = 16166, ShamanSwiftness = 16188; +// Mage +constexpr uint32_t Fireball = 133, Frostbolt = 116, ArcaneMissiles = 5143, FireBlast = 2136, ArcaneExplosion = 1449, FrostNova = 122, + ArcaneIntellect = 1459, FrostArmor = 168, IceArmor = 7302, MageArmor = 6117, Combustion = 11129, + ArcanePower = 12042, PresenceOfMind = 12043, IceBarrier = 11426, Counterspell = 2139; +// Druid +constexpr uint32_t Wrath = 5176, Moonfire = 8921, Rejuvenation = 774, HealingTouch = 5185, Regrowth = 8936, MarkOfTheWild = 1126, + Thorns = 467, BearForm = 5487, DireBearForm = 9634, CatForm = 768, Maul = 6807, Swipe = 779, + DemoralizingRoar = 99, Claw = 1082, Rake = 1822, Rip = 1079, FerociousBite = 22568, Shred = 5221, + FaerieFire = 770, FaerieFireFeral = 16857, InsectSwarm = 5570, Starfire = 2912, Enrage = 5229, Growl = 6795, + Bash = 5211, Swiftmend = 18562, DruidSwiftness = 17116, FrenziedRegeneration = 22842; +} // namespace Id + +// Every spell a class's rules look at: the caller fills known / ready / auras for these only. +inline std::vector const& Spells(uint8_t cls) +{ + using namespace Id; + static std::vector const none; + static std::vector const warrior = { HeroicStrike, Rend, Charge, ThunderClap, Overpower, Revenge, SunderArmor, ShieldBlock, + Execute, Bloodthirst, MortalStrike, Whirlwind, Cleave, ShieldSlam, DemoralizingShout, BattleShout, Bloodrage, Taunt, ShieldBash, + Pummel, SweepingStrikes, LastStand, BattleStance, DefensiveStance }; + static std::vector const paladin = { SealOfRighteousness, SealOfCommand, SealOfTheCrusader, Judgement, HolyLight, + FlashOfLight, HolyShock, Consecration, HolyShield, Exorcism, HammerOfWrath, HammerOfJustice, BlessingOfMight, BlessingOfWisdom, + DevotionAura, RetributionAura, RighteousFury, DivineShield, LayOnHands }; + static std::vector const hunter = { AutoShot, HuntersMark, SerpentSting, ArcaneShot, MultiShot, AimedShot, RaptorStrike, + MongooseBite, WingClip, RapidFire, BestialWrath, AspectOfTheHawk, AspectOfTheMonkey, TrueshotAura }; + static std::vector const rogue = { SinisterStrike, Eviscerate, SliceAndDice, Backstab, Kick, Hemorrhage, AdrenalineRush, + BladeFlurry, ColdBlood, Riposte, GhostlyStrike, Evasion, Ambush, CheapShot }; + static std::vector const priest = { Shoot, Smite, ShadowWordPain, MindBlast, PowerWordShield, Renew, LesserHeal, Heal, + FlashHeal, GreaterHeal, MindFlay, Shadowform, InnerFire, PowerWordFortitude, VampiricEmbrace, HolyFire, PrayerOfHealing, + PsychicScream, Silence }; + static std::vector const shaman = { LightningBolt, EarthShock, FlameShock, LightningShield, RockbiterWeapon, + FlametongueWeapon, WindfuryWeapon, HealingWave, LesserHealingWave, ChainHeal, ChainLightning, Stormstrike, ElementalMastery, + ShamanSwiftness }; + static std::vector const mage = { Shoot, Fireball, Frostbolt, ArcaneMissiles, FireBlast, ArcaneExplosion, FrostNova, + ArcaneIntellect, FrostArmor, IceArmor, MageArmor, Combustion, ArcanePower, PresenceOfMind, IceBarrier, Counterspell }; + static std::vector const druid = { Wrath, Moonfire, Rejuvenation, HealingTouch, Regrowth, MarkOfTheWild, Thorns, BearForm, + DireBearForm, CatForm, Maul, Swipe, DemoralizingRoar, Claw, Rake, Rip, FerociousBite, Shred, FaerieFire, FaerieFireFeral, + InsectSwarm, Starfire, Enrage, Growl, Bash, Swiftmend, DruidSwiftness, FrenziedRegeneration }; + switch (cls) + { + case kWarrior: return warrior; + case kPaladin: return paladin; + case kHunter: return hunter; + case kRogue: return rogue; + case kPriest: return priest; + case kShaman: return shaman; + case kMage: return mage; + case kDruid: return druid; + default: return none; + } +} + +// Cast without the global cooldown (or on the next swing): the caller casts it and picks again in the same press. +// Not the wand's Shoot: any spell cast after it stops the wand, so the press that starts it ends there (a priest dry of mana started +// the wand and the same press went on to Vampiric Embrace or Shadow Word: Pain, which stopped it again). Auto Shot runs beside the shots. +constexpr bool OffGlobalCooldown(uint32_t id) +{ + using namespace Id; + return id == HeroicStrike || id == Cleave || id == Maul || id == RaptorStrike || id == Bloodrage || id == LastStand || + id == ColdBlood || id == PresenceOfMind || id == ArcanePower || id == Combustion || id == ElementalMastery || + id == ShamanSwiftness || id == DruidSwiftness || id == BestialWrath || id == RapidFire || id == AutoShot || + id == Enrage || id == Evasion; +} + +// The talent tree (1-3, 0 = unknown) of a ChrSpecialization id; a druid's Guardian (104) plays the Feral tree. +constexpr int TreeOfSpec(uint8_t cls, uint32_t spec) +{ + switch (cls) + { + case kWarrior: return spec == 71 ? 1 : spec == 72 ? 2 : spec == 73 ? 3 : 0; + case kPaladin: return spec == 65 ? 1 : spec == 66 ? 2 : spec == 70 ? 3 : 0; + case kHunter: return spec == 253 ? 1 : spec == 254 ? 2 : spec == 255 ? 3 : 0; + case kRogue: return spec == 259 ? 1 : spec == 260 ? 2 : spec == 261 ? 3 : 0; + case kPriest: return spec == 256 ? 1 : spec == 257 ? 2 : spec == 258 ? 3 : 0; + case kShaman: return spec == 262 ? 1 : spec == 263 ? 2 : spec == 264 ? 3 : 0; + case kMage: return spec == 62 ? 1 : spec == 63 ? 2 : spec == 64 ? 3 : 0; + case kDruid: return spec == 102 ? 1 : (spec == 103 || spec == 104) ? 2 : spec == 105 ? 3 : 0; + default: return 0; + } +} + +struct Input +{ + std::vector known; // in the spellbook (any rank) + std::vector ready; // off cooldown and global cooldown + std::vector blocked; // refused lately (no mana, wrong state, ...): leave it out + std::vector on_target; // this player's aura of the spell is on the target (dots, debuffs) + std::vector on_self; // the aura is on the player (buffs, seals, shields; Weakened Soul from anyone) + std::vector on_healee; // on the heal target: this player's HoTs, Weakened Soul from anyone + + uint8_t cls = 0; + Role role = Role::Dps; + Form form = Form::None; + int tree = 0; // talent tree 1-3 of the player's spec, 0 = unknown + + bool casting = false; // a cast or channel is going + bool in_combat = false; + bool has_target = false; // a living enemy is selected + bool target_in_melee = false; // within melee reach + bool target_in_range = true; // within spell range (30y) + bool target_behind = false; // the player stands behind the target + bool target_casting = false; // the target is casting or channelling + bool target_boss = false; + bool target_player = false; + bool target_on_me = false; // the target attacks the player + bool target_undead_or_demon = false; + bool target_attacking = false; // the target attacks someone (a tank's taunt check) + bool stealthed = false; + bool auto_shooting = false; // Auto Shot / wand on auto-repeat + bool wand = false; // a wand in the ranged slot + bool has_pet = false; + bool weapon_imbued = false; // a temporary enchant on the main hand (shaman imbues) + + int level = 60; + int hp_pct = 100; + int mana_pct = 100; + int rage = 0; + int energy = 100; + int combo = 0; + int target_hp_pct = 100; + int attackers_close = 0; // enemies attacking the player within 8 yards + + // Healing: the most hurt friendly player in reach (the player included). + bool has_healee = false; + bool healee_is_self = false; + int healee_hp_pct = 100; + int hurt_count = 0; // group members in reach below 75 % +}; + +struct Choice +{ + uint32_t spell = 0; // 0 = nothing this press + At at = At::Target; + char const* why = ""; + bool cancel_form = false; // leave the shapeshift form first (a druid healing out of a form) +}; + +inline bool In(std::vector const& v, uint32_t id) { return std::find(v.begin(), v.end(), id) != v.end(); } +inline bool Knows(Input const& in, uint32_t id) { return In(in.known, id); } +inline bool Can(Input const& in, uint32_t id) { return Knows(in, id) && In(in.ready, id) && !In(in.blocked, id); } +inline bool OnTarget(Input const& in, uint32_t id) { return In(in.on_target, id); } +inline bool OnSelf(Input const& in, uint32_t id) { return In(in.on_self, id); } + +// A fight worth a cooldown or a long dot: a boss, a player, or a target still above half health. +inline bool LongFight(Input const& in) { return in.target_boss || in.target_player || in.target_hp_pct >= 50; } + +inline Choice Cast(uint32_t id, At at, char const* why) { Choice c; c.spell = id; c.at = at; c.why = why; return c; } +inline Choice Nothing(char const* why) { Choice c; c.why = why; return c; } + +// The first of `ids` that can be cast now, or 0. +inline uint32_t FirstCan(Input const& in, std::initializer_list ids) +{ + for (uint32_t id : ids) + if (Can(in, id)) return id; + return 0; +} + +// ---------------------------------------------------------------------------------------------------------------------------- healing + +struct HealKit +{ + uint32_t hot = 0; // kept on the healee + uint32_t fast = 0; // emergencies + uint32_t main = 0; // the efficient heal + uint32_t big = 0; // the large heal, when known + uint32_t group = 0; // several hurt + uint32_t shield = 0; // absorb, not while Weakened Soul + uint32_t instant = 0; // instant emergency heal (Holy Shock, Swiftmend) +}; + +inline HealKit KitOf(uint8_t cls) +{ + using namespace Id; + HealKit k; + switch (cls) + { + case kPaladin: k.fast = FlashOfLight; k.main = HolyLight; k.instant = HolyShock; break; + case kPriest: k.hot = Renew; k.fast = FlashHeal; k.main = Heal; k.big = GreaterHeal; k.group = PrayerOfHealing; k.shield = PowerWordShield; break; + case kShaman: k.fast = LesserHealingWave; k.main = HealingWave; k.group = ChainHeal; break; + case kDruid: k.hot = Rejuvenation; k.fast = Regrowth; k.main = HealingTouch; k.instant = Swiftmend; break; + default: break; + } + return k; +} + +inline bool CanHeal(uint8_t cls) { return cls == kPaladin || cls == kPriest || cls == kShaman || cls == kDruid; } + +// The heal for the most hurt group member, or nothing when nobody needs one. +inline Choice PickHeal(Input const& in) +{ + using namespace Id; + if (!in.has_healee || !CanHeal(in.cls)) + return Nothing("nobody to heal"); + HealKit const k = KitOf(in.cls); + int const h = in.healee_hp_pct; + if (h >= 95) + return Nothing("everyone is healthy"); + // Heals need the caster form. + if (in.cls == kDruid && in.form != Form::None && in.form != Form::Moonkin && h <= 70) + { + Choice c = Nothing("leave form to heal"); + c.cancel_form = true; + return c; + } + At const at = in.healee_is_self ? At::Self : At::Healee; + bool const lesser_known = Knows(in, LesserHeal) && !Knows(in, Heal); + uint32_t const main = Knows(in, k.main) ? k.main : (in.cls == kPriest && lesser_known ? LesserHeal : k.main); + + if (h <= 35) + { + if (k.shield && Can(in, k.shield) && !In(in.on_healee, WeakenedSoul) && !In(in.on_healee, k.shield)) return Cast(k.shield, at, "emergency: shield"); + if (k.instant && Can(in, k.instant) && (k.instant != Swiftmend || In(in.on_healee, Rejuvenation) || In(in.on_healee, Regrowth))) + return Cast(k.instant, at, "emergency: instant heal"); + if (in.cls == kShaman && Can(in, ShamanSwiftness)) return Cast(ShamanSwiftness, At::Self, "emergency: Nature's Swiftness"); + if (in.cls == kDruid && Can(in, DruidSwiftness)) return Cast(DruidSwiftness, At::Self, "emergency: Nature's Swiftness"); + if (k.fast && Can(in, k.fast)) return Cast(k.fast, at, "emergency: fast heal"); + if (Can(in, main)) return Cast(main, at, "emergency: main heal"); + } + if (in.hurt_count >= 3 && k.group && Can(in, k.group) && in.mana_pct >= 20) + return Cast(k.group, k.group == ChainHeal ? at : At::Self, "three or more hurt: group heal"); + if (h <= 85 && k.hot && Can(in, k.hot) && !In(in.on_healee, k.hot)) + return Cast(k.hot, at, "HoT missing"); + if (h <= 85 && k.shield && in.cls == kPriest && h <= 60 && Can(in, k.shield) && !In(in.on_healee, WeakenedSoul) && !In(in.on_healee, k.shield)) + return Cast(k.shield, at, "shield before the heal"); + if (h <= 50 && k.big && Can(in, k.big) && in.mana_pct >= 30) return Cast(k.big, at, "big gap: large heal"); + if (h <= 75 && Can(in, main)) return Cast(main, at, "gap: main heal"); + if (h <= 75 && k.fast && Can(in, k.fast)) return Cast(k.fast, at, "gap: fast heal (main not ready)"); + return Nothing("small gap: no heal yet"); +} + +// ------------------------------------------------------------------------------------------------------------------------- classes + +inline Choice Warrior(Input const& in) +{ + using namespace Id; + bool const tank = in.role == Role::Tank; + if (tank && in.form != Form::Defensive && Can(in, DefensiveStance)) return Cast(DefensiveStance, At::Self, "tank: Defensive Stance"); + if (!tank && in.form == Form::Defensive && in.rage <= 25 && Can(in, BattleStance)) return Cast(BattleStance, At::Self, "damage: Battle Stance"); + if (!in.has_target) + { + if (!in.in_combat && !OnSelf(in, BattleShout) && Can(in, BattleShout)) return Cast(BattleShout, At::Self, "no target: Battle Shout"); + return Nothing("no target"); + } + if (!in.in_combat && !in.target_in_melee && in.form == Form::Battle && Can(in, Charge)) return Cast(Charge, At::Target, "opener: Charge"); + if (in.target_casting && in.target_in_melee) + { + if (Can(in, ShieldBash)) return Cast(ShieldBash, At::Target, "interrupt: Shield Bash"); + if (Can(in, Pummel)) return Cast(Pummel, At::Target, "interrupt: Pummel"); + } + if (in.in_combat && in.rage < 20 && in.hp_pct >= 40 && Can(in, Bloodrage)) return Cast(Bloodrage, At::Self, "low rage: Bloodrage"); + if (!in.target_in_melee) return Nothing("target out of melee"); + + if (tank) + { + if (in.hp_pct <= 25 && Can(in, LastStand)) return Cast(LastStand, At::Self, "tank low: Last Stand"); + if (in.in_combat && in.target_attacking && !in.target_on_me && Can(in, Taunt)) return Cast(Taunt, At::Target, "target on someone else: Taunt"); + if (in.target_on_me && in.rage >= 10 && Can(in, ShieldBlock)) return Cast(ShieldBlock, At::Self, "tanking: Shield Block"); + if (Can(in, Revenge)) return Cast(Revenge, At::Target, "Revenge"); + if (in.rage >= 20 && Can(in, ShieldSlam)) return Cast(ShieldSlam, At::Target, "Shield Slam"); + if (in.rage >= 30 && Can(in, Bloodthirst)) return Cast(Bloodthirst, At::Target, "Bloodthirst"); + if (in.attackers_close >= 2 && in.rage >= 20 && Can(in, ThunderClap)) return Cast(ThunderClap, At::Self, "two or more on me: Thunder Clap"); + if (!OnTarget(in, DemoralizingShout) && in.rage >= 10 && in.in_combat && Can(in, DemoralizingShout)) + return Cast(DemoralizingShout, At::Self, "Demoralizing Shout"); + if (in.rage >= 50 && Can(in, HeroicStrike)) return Cast(HeroicStrike, At::Target, "rage to spare: Heroic Strike"); + if (in.rage >= 15 && Can(in, SunderArmor)) return Cast(SunderArmor, At::Target, "threat: Sunder Armor"); + return Nothing("tank: waiting for rage"); + } + + if (in.target_hp_pct <= 20 && in.rage >= 15 && Can(in, Execute)) return Cast(Execute, At::Target, "execute range: Execute"); + if (Can(in, Overpower)) return Cast(Overpower, At::Target, "Overpower"); + if (in.rage >= 30 && Can(in, MortalStrike)) return Cast(MortalStrike, At::Target, "Mortal Strike"); + if (in.rage >= 30 && Can(in, Bloodthirst)) return Cast(Bloodthirst, At::Target, "Bloodthirst"); + if (in.rage >= 25 && Can(in, Whirlwind)) return Cast(Whirlwind, At::Self, "Whirlwind"); + if (in.attackers_close >= 2 && in.rage >= 30 && Can(in, SweepingStrikes)) return Cast(SweepingStrikes, At::Self, "two or more: Sweeping Strikes"); + if (!OnSelf(in, BattleShout) && in.rage >= 10 && Can(in, BattleShout)) return Cast(BattleShout, At::Self, "Battle Shout"); + if (!OnTarget(in, Rend) && !in.target_undead_or_demon && in.target_hp_pct >= 40 && !Knows(in, MortalStrike) && !Knows(in, Bloodthirst) && + in.rage >= 10 && Can(in, Rend)) + return Cast(Rend, At::Target, "Rend"); + bool const strike_known = Knows(in, MortalStrike) || Knows(in, Bloodthirst); + if (in.attackers_close >= 2 && in.rage >= 40 && Can(in, Cleave)) return Cast(Cleave, At::Target, "two or more: Cleave"); + if (in.rage >= (strike_known ? 60 : 15) && Can(in, HeroicStrike)) return Cast(HeroicStrike, At::Target, "rage dump: Heroic Strike"); + return Nothing("waiting for rage"); +} + +inline Choice Paladin(Input const& in) +{ + using namespace Id; + bool const tank = in.role == Role::Tank; + if (in.hp_pct <= 15 && Can(in, LayOnHands)) return Cast(LayOnHands, At::Self, "dying: Lay on Hands"); + if (in.hp_pct <= 20 && in.in_combat && !tank && Can(in, DivineShield)) return Cast(DivineShield, At::Self, "dying: Divine Shield"); + if (tank && !OnSelf(in, RighteousFury) && Can(in, RighteousFury)) return Cast(RighteousFury, At::Self, "tank: Righteous Fury"); + if (!in.in_combat) + { + uint32_t const blessing = (in.role == Role::Heal || tank) ? BlessingOfWisdom : BlessingOfMight; + if (!OnSelf(in, blessing) && Can(in, blessing)) return Cast(blessing, At::Self, "out of combat: blessing"); + uint32_t const aura = (in.role == Role::Dps && Knows(in, RetributionAura)) ? RetributionAura : DevotionAura; + if (!OnSelf(in, aura) && Can(in, aura)) return Cast(aura, At::Self, "out of combat: aura"); + } + if (!in.has_target) return Nothing("no target"); + if (in.target_casting && Can(in, HammerOfJustice) && !in.target_boss) return Cast(HammerOfJustice, At::Target, "interrupt: Hammer of Justice"); + if (in.target_hp_pct <= 20 && Can(in, HammerOfWrath)) return Cast(HammerOfWrath, At::Target, "execute range: Hammer of Wrath"); + if (in.target_undead_or_demon && Can(in, Exorcism)) return Cast(Exorcism, At::Target, "undead / demon: Exorcism"); + if (tank && in.in_combat && !OnSelf(in, HolyShield) && Can(in, HolyShield)) return Cast(HolyShield, At::Self, "tank: Holy Shield"); + if (in.in_combat && in.attackers_close >= (tank ? 1 : 3) && in.mana_pct >= 30 && Can(in, Consecration)) + return Cast(Consecration, At::Self, "enemies around me: Consecration"); + bool const seal_up = OnSelf(in, SealOfRighteousness) || OnSelf(in, SealOfCommand) || OnSelf(in, SealOfTheCrusader); + if (!seal_up) + { + uint32_t const seal = (!tank && Knows(in, SealOfCommand)) ? SealOfCommand : SealOfRighteousness; + if (Can(in, seal)) return Cast(seal, At::Self, "no seal: seal"); + } + if (seal_up && in.target_in_melee && in.in_combat && Can(in, Judgement)) return Cast(Judgement, At::Target, "seal up: Judgement"); + return Nothing("melee swings"); +} + +inline Choice Hunter(Input const& in) +{ + using namespace Id; + bool const hawk_or_monkey = OnSelf(in, AspectOfTheHawk) || OnSelf(in, AspectOfTheMonkey); + if (!hawk_or_monkey) + { + if (Can(in, AspectOfTheHawk)) return Cast(AspectOfTheHawk, At::Self, "no aspect: Aspect of the Hawk"); + if (Can(in, AspectOfTheMonkey)) return Cast(AspectOfTheMonkey, At::Self, "no aspect: Aspect of the Monkey"); + } + if (!in.in_combat && Knows(in, TrueshotAura) && !OnSelf(in, TrueshotAura) && Can(in, TrueshotAura)) return Cast(TrueshotAura, At::Self, "Trueshot Aura"); + if (!in.has_target) return Nothing("no target"); + if (in.target_in_melee) + { + if (Can(in, MongooseBite)) return Cast(MongooseBite, At::Target, "melee: Mongoose Bite"); + if (in.target_on_me && !OnTarget(in, WingClip) && Can(in, WingClip)) return Cast(WingClip, At::Target, "melee: Wing Clip"); + if (Can(in, RaptorStrike)) return Cast(RaptorStrike, At::Target, "melee: Raptor Strike"); + return Nothing("melee swings"); + } + if (!in.target_in_range) return Nothing("target out of range"); + if (!in.auto_shooting && Can(in, AutoShot)) return Cast(AutoShot, At::Target, "Auto Shot"); + if (!OnTarget(in, HuntersMark) && LongFight(in) && Can(in, HuntersMark)) return Cast(HuntersMark, At::Target, "Hunter's Mark"); + if (in.in_combat && in.has_pet && LongFight(in) && Can(in, BestialWrath)) return Cast(BestialWrath, At::Self, "long fight: Bestial Wrath"); + if (in.in_combat && (in.target_boss || in.target_player) && Can(in, RapidFire)) return Cast(RapidFire, At::Self, "boss: Rapid Fire"); + if (!OnTarget(in, SerpentSting) && in.target_hp_pct >= 30 && in.mana_pct >= 15 && Can(in, SerpentSting)) + return Cast(SerpentSting, At::Target, "Serpent Sting"); + if (in.mana_pct >= 30 && Can(in, AimedShot)) return Cast(AimedShot, At::Target, "Aimed Shot"); + if (in.mana_pct >= 40 && Can(in, MultiShot)) return Cast(MultiShot, At::Target, "Multi-Shot"); + if (in.mana_pct >= 40 && Can(in, ArcaneShot)) return Cast(ArcaneShot, At::Target, "Arcane Shot"); + return Nothing("Auto Shot does the rest"); +} + +inline Choice Rogue(Input const& in) +{ + using namespace Id; + if (!in.has_target) return Nothing("no target"); + if (in.stealthed) + { + if (in.target_behind && Can(in, Ambush)) return Cast(Ambush, At::Target, "stealth, behind: Ambush"); + if (Can(in, CheapShot)) return Cast(CheapShot, At::Target, "stealth: Cheap Shot"); + } + if (!in.target_in_melee) return Nothing("target out of melee"); + if (in.target_casting && in.energy >= 25 && Can(in, Kick)) return Cast(Kick, At::Target, "interrupt: Kick"); + if (in.hp_pct <= 40 && in.target_on_me && Can(in, Evasion)) return Cast(Evasion, At::Self, "low health: Evasion"); + if (Can(in, Riposte)) return Cast(Riposte, At::Target, "Riposte"); + if (in.in_combat && (in.target_boss || in.target_player) && Can(in, AdrenalineRush)) return Cast(AdrenalineRush, At::Self, "boss: Adrenaline Rush"); + if (in.attackers_close >= 2 && Can(in, BladeFlurry)) return Cast(BladeFlurry, At::Self, "two or more: Blade Flurry"); + if (in.combo >= 2 && !OnSelf(in, SliceAndDice) && in.target_hp_pct >= 30 && in.energy >= 25 && Can(in, SliceAndDice)) + return Cast(SliceAndDice, At::Self, "Slice and Dice"); + if ((in.combo >= 5 || (in.combo >= 3 && in.target_hp_pct <= 25))) + { + if (in.combo >= 4 && Can(in, ColdBlood)) return Cast(ColdBlood, At::Self, "finisher: Cold Blood"); + if (in.energy >= 35 && Can(in, Eviscerate)) return Cast(Eviscerate, At::Target, "finisher: Eviscerate"); + return Nothing("waiting for energy (finisher)"); + } + if (in.energy >= 40 && Can(in, GhostlyStrike)) return Cast(GhostlyStrike, At::Target, "Ghostly Strike"); + if (in.energy >= 35 && Can(in, Hemorrhage)) return Cast(Hemorrhage, At::Target, "builder: Hemorrhage"); + if (in.target_behind && in.energy >= 60 && Can(in, Backstab)) return Cast(Backstab, At::Target, "behind: Backstab"); + if (in.energy >= 45 && Can(in, SinisterStrike)) return Cast(SinisterStrike, At::Target, "builder: Sinister Strike"); + return Nothing("waiting for energy"); +} + +inline Choice Priest(Input const& in) +{ + using namespace Id; + bool const shadow = in.form == Form::Shadow; + if (!in.in_combat && !shadow) + { + if (!OnSelf(in, PowerWordFortitude) && Can(in, PowerWordFortitude)) return Cast(PowerWordFortitude, At::Self, "out of combat: Fortitude"); + if (!OnSelf(in, InnerFire) && Can(in, InnerFire)) return Cast(InnerFire, At::Self, "out of combat: Inner Fire"); + } + if (in.role == Role::Dps && !shadow && Can(in, Shadowform)) return Cast(Shadowform, At::Self, "Shadowform"); + if (in.hp_pct <= 50 && in.target_on_me && !OnSelf(in, PowerWordShield) && !OnSelf(in, WeakenedSoul) && Can(in, PowerWordShield)) + return Cast(PowerWordShield, At::Self, "hit: Power Word: Shield"); + if (!in.has_target) return Nothing("no target"); + if (!in.target_in_range) return Nothing("target out of range"); + if (in.target_casting && Can(in, Silence)) return Cast(Silence, At::Target, "interrupt: Silence"); + if (in.attackers_close >= 2 && in.hp_pct <= 40 && !in.target_boss && Can(in, PsychicScream)) + return Cast(PsychicScream, At::Self, "surrounded: Psychic Scream"); + if (in.wand && !in.auto_shooting && in.mana_pct < 10 && Can(in, Shoot)) return Cast(Shoot, At::Target, "out of mana: wand"); + if (!OnTarget(in, VampiricEmbrace) && LongFight(in) && Can(in, VampiricEmbrace)) return Cast(VampiricEmbrace, At::Target, "Vampiric Embrace"); + if (!OnTarget(in, ShadowWordPain) && (in.target_hp_pct >= 25 || in.target_boss) && Can(in, ShadowWordPain)) + return Cast(ShadowWordPain, At::Target, "Shadow Word: Pain"); + if (in.mana_pct >= 20 && Can(in, MindBlast)) return Cast(MindBlast, At::Target, "Mind Blast"); + if (in.mana_pct >= 15 && Can(in, MindFlay)) return Cast(MindFlay, At::Target, "Mind Flay"); + if (!shadow) + { + if (!OnTarget(in, HolyFire) && in.mana_pct >= 30 && Can(in, HolyFire)) return Cast(HolyFire, At::Target, "Holy Fire"); + if (Can(in, Smite)) return Cast(Smite, At::Target, "Smite"); + } + if (in.wand && !in.auto_shooting && Can(in, Shoot)) return Cast(Shoot, At::Target, "wand"); + return Nothing("nothing ready"); +} + +inline Choice Shaman(Input const& in) +{ + using namespace Id; + if (!in.in_combat) + { + if (!OnSelf(in, LightningShield) && Can(in, LightningShield)) return Cast(LightningShield, At::Self, "out of combat: Lightning Shield"); + if (!in.weapon_imbued) + if (uint32_t const imbue = FirstCan(in, { WindfuryWeapon, FlametongueWeapon, RockbiterWeapon })) + return Cast(imbue, At::Self, "out of combat: weapon imbue"); + } + if (!in.has_target) return Nothing("no target"); + if (in.target_casting && Can(in, EarthShock)) return Cast(EarthShock, At::Target, "interrupt: Earth Shock"); + bool const melee = in.tree == 2 || Knows(in, Stormstrike); + if (melee) + { + if (!in.target_in_melee) return Nothing("target out of melee"); + if (Can(in, Stormstrike)) return Cast(Stormstrike, At::Target, "Stormstrike"); + if (!OnTarget(in, FlameShock) && in.target_hp_pct >= 40 && in.mana_pct >= 30 && Can(in, FlameShock)) return Cast(FlameShock, At::Target, "Flame Shock"); + if (in.mana_pct >= 40 && Can(in, EarthShock)) return Cast(EarthShock, At::Target, "Earth Shock"); + return Nothing("melee swings"); + } + if (!in.target_in_range) return Nothing("target out of range"); + if (in.in_combat && LongFight(in) && Can(in, ElementalMastery)) return Cast(ElementalMastery, At::Self, "Elemental Mastery"); + if (in.attackers_close >= 2 && in.mana_pct >= 30 && Can(in, ChainLightning)) return Cast(ChainLightning, At::Target, "two or more: Chain Lightning"); + if (!OnTarget(in, FlameShock) && in.target_hp_pct >= 30 && in.mana_pct >= 20 && Can(in, FlameShock)) return Cast(FlameShock, At::Target, "Flame Shock"); + if (Can(in, LightningBolt)) return Cast(LightningBolt, At::Target, "Lightning Bolt"); + return Nothing("nothing ready"); +} + +inline Choice Mage(Input const& in) +{ + using namespace Id; + if (!in.in_combat) + { + if (!OnSelf(in, ArcaneIntellect) && Can(in, ArcaneIntellect)) return Cast(ArcaneIntellect, At::Self, "out of combat: Arcane Intellect"); + bool const armor_up = OnSelf(in, IceArmor) || OnSelf(in, FrostArmor) || OnSelf(in, MageArmor); + if (!armor_up) + if (uint32_t const armor = FirstCan(in, { IceArmor, FrostArmor, MageArmor })) + return Cast(armor, At::Self, "out of combat: armor"); + } + if (in.target_on_me && in.target_in_melee && Can(in, FrostNova)) return Cast(FrostNova, At::Self, "enemy in melee: Frost Nova"); + if (in.hp_pct <= 40 && in.in_combat && !OnSelf(in, IceBarrier) && Can(in, IceBarrier)) return Cast(IceBarrier, At::Self, "hit: Ice Barrier"); + if (!in.has_target) return Nothing("no target"); + if (in.target_casting && Can(in, Counterspell)) return Cast(Counterspell, At::Target, "interrupt: Counterspell"); + if (in.attackers_close >= 3 && in.mana_pct >= 30 && Can(in, ArcaneExplosion)) + return Cast(ArcaneExplosion, At::Self, "three or more around me: Arcane Explosion"); + if (!in.target_in_range) return Nothing("target out of range"); + if (in.wand && !in.auto_shooting && in.mana_pct < 10 && Can(in, Shoot)) return Cast(Shoot, At::Target, "out of mana: wand"); + if (in.in_combat && (in.target_boss || in.target_player)) + { + if (Can(in, ArcanePower)) return Cast(ArcanePower, At::Self, "boss: Arcane Power"); + if (Can(in, Combustion)) return Cast(Combustion, At::Self, "boss: Combustion"); + if (Can(in, PresenceOfMind)) return Cast(PresenceOfMind, At::Self, "boss: Presence of Mind"); + } + if (in.mana_pct >= 15 && Can(in, FireBlast)) return Cast(FireBlast, At::Target, "Fire Blast"); + if (in.tree == 1 && in.mana_pct >= 50 && Can(in, ArcaneMissiles)) return Cast(ArcaneMissiles, At::Target, "Arcane Missiles"); + if (in.tree == 2 && Can(in, Fireball)) return Cast(Fireball, At::Target, "Fireball"); + if (Can(in, Frostbolt)) return Cast(Frostbolt, At::Target, "Frostbolt"); + if (Can(in, Fireball)) return Cast(Fireball, At::Target, "Fireball"); + if (in.wand && !in.auto_shooting && Can(in, Shoot)) return Cast(Shoot, At::Target, "wand"); + return Nothing("nothing ready"); +} + +inline Choice Druid(Input const& in) +{ + using namespace Id; + bool const tank = in.role == Role::Tank; + bool const bear_form = in.form == Form::Bear; + bool const cat_form = in.form == Form::Cat; + // The form the role wants. + if (tank && !bear_form) + if (uint32_t const bear = FirstCan(in, { DireBearForm, BearForm })) + return Cast(bear, At::Self, "tank: Bear Form"); + if (in.role == Role::Dps && in.tree == 2 && !cat_form && !bear_form && Can(in, CatForm)) return Cast(CatForm, At::Self, "feral: Cat Form"); + + if (bear_form) + { + if (!in.has_target) return Nothing("no target"); + if (in.target_casting && in.rage >= 10 && Can(in, Bash)) return Cast(Bash, At::Target, "interrupt: Bash"); + if (in.in_combat && in.target_attacking && !in.target_on_me && Can(in, Growl)) return Cast(Growl, At::Target, "target on someone else: Growl"); + if (in.hp_pct <= 30 && Can(in, FrenziedRegeneration)) return Cast(FrenziedRegeneration, At::Self, "low: Frenzied Regeneration"); + if (in.in_combat && in.rage < 10 && in.hp_pct >= 50 && Can(in, Enrage)) return Cast(Enrage, At::Self, "low rage: Enrage"); + if (!in.target_in_melee) return Nothing("target out of melee"); + if (in.in_combat && !OnTarget(in, DemoralizingRoar) && in.rage >= 10 && Can(in, DemoralizingRoar)) + return Cast(DemoralizingRoar, At::Self, "Demoralizing Roar"); + if (in.attackers_close >= 2 && in.rage >= 20 && Can(in, Swipe)) return Cast(Swipe, At::Target, "two or more: Swipe"); + if (!OnTarget(in, FaerieFireFeral) && Can(in, FaerieFireFeral)) return Cast(FaerieFireFeral, At::Target, "Faerie Fire (Feral)"); + if (in.rage >= 15 && Can(in, Maul)) return Cast(Maul, At::Target, "Maul"); + return Nothing("waiting for rage"); + } + if (cat_form) + { + if (!in.has_target) return Nothing("no target"); + if (!in.target_in_melee) return Nothing("target out of melee"); + if (in.combo >= 5) + { + if (!OnTarget(in, Rip) && in.target_hp_pct >= 40 && in.energy >= 30 && Can(in, Rip)) return Cast(Rip, At::Target, "finisher: Rip"); + if (in.energy >= 35 && Can(in, FerociousBite)) return Cast(FerociousBite, At::Target, "finisher: Ferocious Bite"); + if (!Knows(in, FerociousBite) && !OnTarget(in, Rip) && Can(in, Rip)) return Cast(Rip, At::Target, "finisher: Rip"); + return Nothing("waiting for energy (finisher)"); + } + if (!OnTarget(in, FaerieFireFeral) && in.target_boss && Can(in, FaerieFireFeral)) return Cast(FaerieFireFeral, At::Target, "Faerie Fire (Feral)"); + if (!OnTarget(in, Rake) && in.target_hp_pct >= 30 && in.energy >= 40 && Can(in, Rake)) return Cast(Rake, At::Target, "Rake"); + if (in.target_behind && in.energy >= 60 && Can(in, Shred)) return Cast(Shred, At::Target, "behind: Shred"); + if (in.energy >= 45 && Can(in, Claw)) return Cast(Claw, At::Target, "builder: Claw"); + return Nothing("waiting for energy"); + } + // Caster or Moonkin. + if (!in.in_combat && in.form == Form::None) + { + if (!OnSelf(in, MarkOfTheWild) && Can(in, MarkOfTheWild)) return Cast(MarkOfTheWild, At::Self, "out of combat: Mark of the Wild"); + if (!OnSelf(in, Thorns) && Can(in, Thorns)) return Cast(Thorns, At::Self, "out of combat: Thorns"); + } + if (in.form == Form::None && in.hp_pct <= 40 && in.in_combat && !OnSelf(in, Rejuvenation) && Can(in, Rejuvenation)) + return Cast(Rejuvenation, At::Self, "hit: Rejuvenation on me"); + if (!in.has_target) return Nothing("no target"); + if (!in.target_in_range) return Nothing("target out of range"); + if (!OnTarget(in, FaerieFire) && (in.target_boss || in.target_player) && Can(in, FaerieFire)) return Cast(FaerieFire, At::Target, "Faerie Fire"); + if (!OnTarget(in, Moonfire) && in.target_hp_pct >= 20 && Can(in, Moonfire)) return Cast(Moonfire, At::Target, "Moonfire"); + if (!OnTarget(in, InsectSwarm) && in.target_hp_pct >= 30 && Can(in, InsectSwarm)) return Cast(InsectSwarm, At::Target, "Insect Swarm"); + if (in.tree == 1 && in.mana_pct >= 30 && Can(in, Starfire)) return Cast(Starfire, At::Target, "Starfire"); + if (Can(in, Wrath)) return Cast(Wrath, At::Target, "Wrath"); + return Nothing("nothing ready"); +} + +// The next spell for this press, and in `why` the rule that chose it. +inline Choice Pick(Input const& in) +{ + if (in.casting) + return Nothing("busy casting"); + if (in.role == Role::Heal && CanHeal(in.cls)) + { + Choice const heal = PickHeal(in); + if (heal.spell || heal.cancel_form) + return heal; + // Nobody needs a heal: fight, but keep mana for the next heal. + if (in.in_combat && in.mana_pct < 40 && in.has_target) + return Nothing("healer: saving mana"); + } + switch (in.cls) + { + case kWarrior: return Warrior(in); + case kPaladin: return Paladin(in); + case kHunter: return Hunter(in); + case kRogue: return Rogue(in); + case kPriest: return Priest(in); + case kShaman: return Shaman(in); + case kMage: return Mage(in); + case kDruid: return Druid(in); + default: return Nothing("class has no lazy rotation"); + } +} + +// Melee classes and forms start their swing with the press (the caller turns auto attack on). +inline bool WantsAutoAttack(Input const& in) +{ + switch (in.cls) + { + case kWarrior: case kPaladin: case kRogue: return true; + case kShaman: return in.tree == 2 || Knows(in, Id::Stormstrike) || in.level < 10; + case kDruid: return in.form == Form::Bear || in.form == Form::Cat; + case kHunter: return in.target_in_melee; + default: return false; + } +} + +} // namespace Playerbot::LazyKey diff --git a/src/modules/PlayerbotV2/Commands/cs_playerbot_v2.cpp b/src/modules/PlayerbotV2/Commands/cs_playerbot_v2.cpp index 98ae88aeaf..677207684c 100644 --- a/src/modules/PlayerbotV2/Commands/cs_playerbot_v2.cpp +++ b/src/modules/PlayerbotV2/Commands/cs_playerbot_v2.cpp @@ -104,6 +104,7 @@ #include "Bot/BotSnapshot.h" #include "Bot/BotSnapshotView.h" #include "Session/AddonControl.h" +#include "Session/LazyKey.h" #include "Session/LazyLock.h" #include "World/WorldMetadata.h" #include "ObjectMgr.h" @@ -269,6 +270,7 @@ uint8 ParseClass(std::string const& token) // 2. Every boss creature_template entry resolves via sObjectMgr. // 3. Every mandatory_interrupt_spells id resolves via sSpellMgr. // 4. Every dangerous_auras id resolves via sSpellMgr. +// 0. A script whose map is not in this client's Map.db2 is not checked; the scripts are named on one "Not on this client" line. // 5. progression_waypoints[i] is the spot of bosses[i]: the owed-boss navigator steers to waypoints[i] for bosses[i], so a list // with an entrance spot first, or a boss with no waypoint in the middle, sends the tank to the wrong boss's room. Each pair is // checked against the boss's spawns on the map (wp_far: more than 40 y from every spawn; no_spawn: a boss with no spawn that @@ -296,6 +298,9 @@ bool RunDungeonValidation(ChatHandler* handler, uint32 only_map) uint32 fail_count = 0; std::vector fail_lines; std::vector warn_lines; + // Scripts for maps this client's Map.db2 does not have (the later expansions' dungeons a Classic realm never ships): they + // cannot run here, so they are named on one line and not checked. A Classic map that shows up there is a typo in its script. + std::vector skipped; // Boss spawns by (map, entry), one pass over the creature store. std::map, std::vector> spawns; @@ -309,6 +314,11 @@ bool RunDungeonValidation(ChatHandler* handler, uint32 only_map) mgr.for_each_script([&](Playerbot::DungeonScript const& script) { if (only_map != 0 && script.map_id() != only_map) return; + if (!sMapStore.LookupEntry(script.map_id())) + { + skipped.push_back(fmt::format("{} ({})", script.name(), script.map_id())); + return; + } ++total_scripts; // We don't have a real snapshot to pass, but most scripts don't @@ -327,13 +337,6 @@ bool RunDungeonValidation(ChatHandler* handler, uint32 only_map) ++local_warn; detail += "no_bosses "; } - // Map_id sanity — catches typos (LostCityOfTolvir 754→755 bug - // class). Map.db2 lookup is cheap. - if (!sMapStore.LookupEntry(script.map_id())) - { - ++local_fail; - detail += fmt::format("bad_map_id={} ", script.map_id()); - } for (uint32 e : a.bosses) { if (!sObjectMgr->GetCreatureTemplate(e)) @@ -344,7 +347,9 @@ bool RunDungeonValidation(ChatHandler* handler, uint32 only_map) } // 5. waypoints[i] belongs to bosses[i]. { - std::vector const summoned = script.event_summoned_bosses(); + std::vector summoned = script.event_summoned_bosses(); + for (uint32_t e : script.scripted_spawn_bosses()) + summoned.push_back(e); constexpr float kWpFar = 40.0f; for (size_t i = 0; i < a.bosses.size(); ++i) { @@ -364,12 +369,21 @@ bool RunDungeonValidation(ChatHandler* handler, uint32 only_map) if (nearest < 0.0f || d < nearest) nearest = d; } + // A boss beyond a portal (portal_hops) has the portal as its waypoint: no navmesh joins his room to the rest. + bool portal_wp = false; + if (has_wp) + for (auto const& h : a.portal_hops) + { + auto const& w = a.progression_waypoints[i]; + if (h.boss_entry == e && (h.x - w.x) * (h.x - w.x) + (h.y - w.y) * (h.y - w.y) + (h.z - w.z) * (h.z - w.z) <= 5.0f * 5.0f) + portal_wp = true; + } if (sp.empty() && !is_summoned) { ++local_warn; detail += fmt::format("no_spawn[{}]={} ", i, e); } - else if (has_wp && nearest > kWpFar) + else if (has_wp && nearest > kWpFar && !portal_wp) { ++local_warn; detail += fmt::format("wp_far[{}]={}:{:.0f}y ", i, e, nearest); @@ -435,6 +449,11 @@ bool RunDungeonValidation(ChatHandler* handler, uint32 only_map) } }); + if (total_scripts == 0 && !skipped.empty()) + { + handler->PSendSysMessage("Map %u is not in this client's Map.db2: its script %s is not checked.", only_map, skipped.front().c_str()); + return true; + } if (total_scripts == 0) { handler->PSendSysMessage( @@ -446,6 +465,13 @@ bool RunDungeonValidation(ChatHandler* handler, uint32 only_map) handler->PSendSysMessage( "==== Dungeon validation: %u scripts | PASS=%u WARN=%u FAIL=%u ====", total_scripts, pass_count, warn_count, fail_count); + if (!skipped.empty()) + { + std::string line = fmt::format("Not on this client ({} scripts, map not in Map.db2, not checked):", skipped.size()); + for (std::string const& n : skipped) + line += " " + n; + handler->SendSysMessage(line); + } for (auto const& l : fail_lines) handler->SendSysMessage(l); for (auto const& l : warn_lines) handler->SendSysMessage(l); if (fail_count == 0 && warn_count == 0) @@ -453,7 +479,9 @@ bool RunDungeonValidation(ChatHandler* handler, uint32 only_map) if (tsv) handler->PSendSysMessage("Boss waypoints and spawns written to %s", tsv_path.c_str()); - return fail_count == 0; + // The check ran and printed its result: a FAIL is in the output, not a misuse of the command (returning false printed + // the command's usage text under every run that had a FAIL). + return true; } // Static-validation pass for `.playerbot smoketest bg`. Walks each @@ -941,14 +969,14 @@ public: } } - // The caller's own race when it can be this class, else a random race of the caller's faction that can. + // A random race of the caller's faction that can be this class, his own among them. It used to be his own race whenever it could + // be the class: a Tauren player's hunters were all Tauren, each with the Tauren's Plainstrider (Discord 2026-11-24, Gabriel, + // "hunter is pets"). A party of other players is of mixed races. static uint8 PickCompanionRace(Player const* owner, uint8 cls) { // Legal on this realm, not merely present in the retail-derived PlayerInfo: a Gnome/Undead owner has // PlayerInfo for a hunter but no Forever hunter, and BotComposition::Roll refuses it. using Playerbot::V2::BotComposition; - if (BotComposition::IsLegalRaceClass(owner->GetRace(), cls)) - return owner->GetRace(); std::vector races; for (uint8 race : { RACE_HUMAN, RACE_ORC, RACE_DWARF, RACE_NIGHTELF, RACE_UNDEAD_PLAYER, RACE_TAUREN, RACE_GNOME, RACE_TROLL }) if (Player::TeamForRace(race) == owner->GetTeam() && BotComposition::IsLegalRaceClass(race, cls)) @@ -1615,6 +1643,12 @@ public: if (ids.empty()) { handler->PSendSysMessage("No companion of yours called '%s'. `.bot list` shows them.", who.c_str()); return false; } uint32 regeared = 0; + // BiS and the tier sets only exist at the level cap (Gear::Owned::EffectiveMode): below it a companion gears like "match", so + // the regear line says so instead of leaving the old weapon unexplained (AveenZero, playerbots #12 11-24: "gear t3" and + // Regear all, the priest kept its level 39 weapon). + using Playerbot::V2::Gear::Owned::GearMode; + GearMode const owner_mode = GearMode(Playerbot::Services::Owners().OwnerGearMode(sess->GetAccountId())); + bool const cap_mode = Playerbot::V2::Gear::Owned::IsCapMode(owner_mode); for (Playerbot::BotId id : ids) { std::string const name = CompanionName(id); @@ -1631,7 +1665,11 @@ public: case Reroll::Done: Playerbot::Services::Owners().MarkGearVaried(id); ++regeared; - handler->PSendSysMessage("%s: %u slot(s) regeared.", name.c_str(), changed); + if (cap_mode && bot->GetLevel() < Playerbot::MaxPlayerLevel()) + handler->PSendSysMessage("%s: %u slot(s) regeared. Gear %s starts at level %u; below that it wears gear for its level (match).", + name.c_str(), changed, Playerbot::V2::Gear::Owned::ModeName(owner_mode), uint32(Playerbot::MaxPlayerLevel())); + else + handler->PSendSysMessage("%s: %u slot(s) regeared.", name.c_str(), changed); break; case Reroll::NotNow: handler->PSendSysMessage("%s is in combat or dead, try again later.", name.c_str()); @@ -8491,8 +8529,18 @@ public: // logger "playerbot.v2.smoketest". The command returns immediately; // re-run with the "result" sub-command to print the final report once // the worker logs PASS/FAIL. - static bool HandleSmoketest(ChatHandler* handler, Optional arg) + // The whole rest of the line: "dungeon all", "dungeon 36" and "bglive 10" are two words, and a one-word argument made the + // command parser refuse every one of them with the usage line (af59 bossspawns: ".playerbot smoketest dungeon all" printed + // only the usage). + static bool HandleSmoketest(ChatHandler* handler, Tail tail) { + Optional arg; + { + std::string_view t = tail; + while (!t.empty() && t.front() == ' ') t.remove_prefix(1); + while (!t.empty() && t.back() == ' ') t.remove_suffix(1); + if (!t.empty()) arg = std::string(t); + } if (!Playerbot::Services::Initialized()) { handler->SendSysMessage("PlayerbotV2 not initialized."); return false; } @@ -8865,9 +8913,10 @@ public: // // Status sub-form prints whether bot logic is currently attached to self // without changing anything, useful for verifying the toggle. - // `.playerbot lazy`: one press casts the next spell of the warlock rotation on the target (the add-on's "Lazy lock" key runs this - // line as a secure macro, so it works in combat). - static bool HandleLazy(ChatHandler* handler) + // `.playerbot lazy [dps|tank|heal]`: one press casts the next spell of the player's rotation on the target (the add-on's "Lazy key" + // runs this line as a secure macro, so it works in combat). The warlock has its own rotation (Session/LazyLock.h), every other class + // the one in Session/LazyKey.h; the role word overrides the role of the player's spec for that press. + static bool HandleLazy(ChatHandler* handler, Optional role) { Playerbot::BotLanguage::LocalizedHandler localized(handler); handler = localized.Get(); // replies in the player's language WorldSession* sess = handler->GetSession(); @@ -8876,7 +8925,15 @@ public: handler->SendSysMessage("`.playerbot lazy` is in-game only (needs your character)."); return false; } - std::string const msg = Playerbot::LazyLockPress(sess->GetPlayer()); + Player* me = sess->GetPlayer(); + std::string word = role ? *role : std::string(); + for (char& c : word) if (c >= 'A' && c <= 'Z') c = char(c + 32); + if (!word.empty() && word != "dps" && word != "damage" && word != "tank" && word != "heal" && word != "healer") + { + handler->SendSysMessage("Usage: .playerbot lazy [dps|tank|heal]"); + return false; + } + std::string const msg = me->GetClass() == CLASS_WARLOCK ? Playerbot::LazyLockPress(me) : Playerbot::LazyKeyPress(me, word); if (!msg.empty()) handler->SendSysMessage(msg.c_str()); return true; diff --git a/src/modules/PlayerbotV2/Diagnostics/ScenarioDefs.h b/src/modules/PlayerbotV2/Diagnostics/ScenarioDefs.h index c2fa497151..d8227ec931 100644 --- a/src/modules/PlayerbotV2/Diagnostics/ScenarioDefs.h +++ b/src/modules/PlayerbotV2/Diagnostics/ScenarioDefs.h @@ -143,6 +143,10 @@ struct ScenarioDef // like the owner: he walks the dungeon's route, stops at the next pack, says "pull back" with it selected (the tank pulls it to him), // "attack" once the tank has it, fights the tank's target, and walks on when the group has its health and mana back. bool player_lead = false; + // "Tank leads" (`lead on`): the stand-in is made the group leader and a player as above, but plays the player who follows his tank + // (PlayStandIn) while the bot tank leads the run. The run fails if the tank ever holds a trash pull for mana (limits.no_mana_hold): + // a player's five-man waits for mana only before a boss, for a healer low on it (GitHub #23, 2026-11-22). + bool tank_lead = false; // Checkpoint starts (`scenario run @`): the squad enters at the entrance as usual, then is moved to a spot in sight of the first // spawn of the checkpoint's creature (a boss or a pack's mob) and plays on from there, bot-led and with no Hold, so a run does not replay // the part that is already solved. The goal and the first-death rule stay. Earlier bosses stay alive in the instance. @@ -843,8 +847,11 @@ inline constexpr RaidBossRow kNaxxBosses[] = { 15952, "Maexxna", 20 }, 48.f), // sees 40 y { "naxx_noth", "Naxxramas: 40 level 60 raiders to Noth the Plaguebringer (the curse dispelled first, spread, balcony adds)", 15954, "Noth the Plaguebringer", 20 }, - { "naxx_heigan", "Naxxramas: 40 level 60 raiders to Heigan the Unclean (the eruption dance, Decrepit Fever, Mana Burn range)", - 15936, "Heigan the Unclean", 20 }, + // The ring search landed the raid at 2827.0,-3685.0 (40 y east of him): in his doorway, past his leash line (he evades east of x 2825, + // classic_instance_naxxramas.cpp HandleEvadeOutOfHome) and past the entrance that shuts 15 s into the fight. naxx_heigan r3af55-1: a + // druid there drew him over the line and he evaded at 32 s. The raid lands inside, 40 y north of him on the room's floor. + Staged({ "naxx_heigan", "Naxxramas: 40 level 60 raiders to Heigan the Unclean (the eruption dance, Decrepit Fever, Mana Burn range)", + 15936, "Heigan the Unclean", 20 }, 2800.0f, -3668.0f, 273.8f), { "naxx_loatheb", "Naxxramas: 40 level 60 raiders to Loatheb (spores, Corrupted Mind heal rotation)", 16011, "Loatheb", 25 }, // The fight opens on a priest's Mind Control on an understudy (RaidMechanics_Naxx.cpp, NaxxPrePullRazuvious); the main tank's order is @@ -1265,6 +1272,21 @@ inline std::vector const& ScenarioCatalogue() // Ragefire, 40 minutes: RC10 reached route point 50 of 54 at 1737 s of its 1800, 54 of its 62 waits on the 60 % led rest. if (base == "rfc_oggleflint") l.timeout_ms = 40u * 60u * 1000u; + // The same run with the bot tank leading and the rogue following it: rfc_oggleflint_tanklead. + if (base == "rfc_oggleflint") + { + ScenarioDef t = v[plain_at]; + s_led_names.push_back(base + "_tanklead"); + s_led_names.push_back(std::string(r.summary) + ", the tank leads (lead on): no stop for mana on trash"); + t.name = s_led_names[s_led_names.size() - 2].c_str(); + t.summary = s_led_names.back().c_str(); + t.stand_in = "Scnrogue"; + t.tank_lead = true; + t.limits.no_mana_hold = true; + t.limits.pull_ready_mana_pct = 60.f; // a player's bots drink below 60 % (Classic::kLedDrinkBelowManaPct) + t.timeout_ms = 40u * 60u * 1000u; + v.push_back(std::move(t)); + } v.push_back(std::move(l)); } // The Library at 36 with an owner's two orders a bot-only squad never gets (test items 4 and 19 of the dungeon list): the @@ -1316,6 +1338,18 @@ inline std::vector const& ScenarioCatalogue() d.checkpoints = { { "witherfang", 250483 }, { "baron", 250660 }, { "rathmael", 250657 }, { "bjork", 256097 } }; v.push_back(std::move(d)); } + // Excavation Site: Wetlands (Forever, map 2998), the entrance to the Relic Guardian: Saltspine, Shadetooth, the Highland Horror, + // then the Relic Guardian, whom the tank wakes at the Archival Panel (ExcavationSiteScript's order). Bot-led, at 30. + // Until now only exc_saltspine ran here, so no bot group had ever finished the dungeon. + { + static constexpr DungeonRow kExc = { "exc_full", "Excavation Site: Wetlands: level 30 party, entrance to the Relic Guardian", + 2998, -3698.41f, -2355.64f, 165.531f, 296.f, 30, 260326, "Relic Guardian", 60 }; + ScenarioDef d = MakeDungeonScenario(kExc); + d.full_clear = true; + // No route yet, so no route crumbs to stage on: the runner searches a ring round each boss. + d.checkpoints = { { "saltspine", 260322 }, { "shadetooth", 260325 }, { "horror", 260808 }, { "guardian", 260326 } }; + v.push_back(std::move(d)); + } // The Drowned City (Forever, map 2970), the cave landing to Min'loth the Serpent: Zul'Alai, Var'Taka, Captain Dreadrise, // Deathless Marrow, the Primeval Elemental in the flooded quarter's pool, Min'loth (the 0047 route and DrownedCityScript's // order; the spawns are the live kill spots of 2026_11_19_67). Bot-led, at 38. @@ -1572,6 +1606,10 @@ inline std::vector const& ScenarioCatalogue() { "smite", 646, -2.585f, -766.284f, 6.172f }, // [41] the ramp up to the ship { "greenskin", 647, -89.643f, -781.119f, 29.200f }, // [47] the gangway { "vancleef", 639, -49.167f, -795.944f, 38.956f } }; // [50] the deck + // Greenskin's gangway and VanCleef's deck are one fight as often as not: VanCleef came down into the Greenskin pull and died + // first, with Greenskin 4 y from the tank, and the run ended as "Greenskin skipped" (deadmines_full af58). The goal counts once + // the checkpoint bosses are dead too, in any order. + d.goal_after_checkpoints = true; // The same clear with the rogue played like the owner's own: it follows the tank and hits the tank's target, nothing else. ScenarioDef p = d; p.name = "deadmines_player"; @@ -1580,64 +1618,68 @@ inline std::vector const& ScenarioCatalogue() v.push_back(std::move(d)); v.push_back(std::move(p)); } - // Alcaz Prison (Forever, map 2994), the landing on the entrance stair to Blazeroar: Overseer Wrex, Katerina the Cleaner, The - // Questioner, Tidemistress Ca'zass, Blazeroar (the route and AlcazPrisonScript's order). Bot-led, the standard five at 53. + // Alcaz Prison (Forever, map 2994), live's landing on the entrance stair to The Questioner, in live's kill order (Karrz's capture, + // 26 Nov): Overseer Wrex, then the Maximum Security Door (the rogue picks it, as Karrz did) to Katerina the Cleaner and + // Blazeroar, then the self-closing Prison Gate to The Questioner (the route and AlcazPrisonScript's order). Tidemistress Ca'zass + // is not spawned (live has her nowhere). Bot-led, the standard five at 53 (live's bosses are 50-53). { - static constexpr DungeonRow kAlcaz = { "alcaz_full", "Alcaz Prison: level 53 party, entrance to Blazeroar", - 2994, -8796.8f, 2838.1f, 29.9f, 90.f, 53, 255702, "Blazeroar", 45 }; + static constexpr DungeonRow kAlcaz = { "alcaz_full", "Alcaz Prison: level 53 party, entrance to The Questioner", + 2994, -8796.59f, 2838.67f, 28.77f, 89.2f, 53, 256236, "The Questioner", 45 }; ScenarioDef d = MakeDungeonScenario(kAlcaz); - // The prison's creature spawns span x -8916..-8728, y 2838..3003, z 5..30; 50 y around them. - d.limits.bounds = { true, -8966.f, -8678.f, 2788.f, 3053.f, -20.f, 80.f }; + // Live's creature and object spawns span x -8927..-8723, y 2826..3007, z 6..32; 50 y around them. + d.limits.bounds = { true, -8977.f, -8673.f, 2776.f, 3057.f, -44.f, 82.f }; d.full_clear = true; - // Staging spots: crumbs of the 0043 route 30-40 y of walk before each boss. - d.checkpoints = { { "wrex", 255391, -8762.13f, 2882.13f, 15.31f }, - { "katerina", 257016, -8823.64f, 2889.6f, 15.58f }, - { "questioner", 256236, -8852.4f, 2889.38f, 14.02f }, - { "cazass", 255997, -8763.29f, 2924.71f, 6.69f }, - { "blazeroar", 255702, -8837.6f, 2968.53f, 7.04f } }; + // Staging spots: crumbs of the 0071 route 33-45 y of walk before each boss. + d.checkpoints = { { "wrex", 255391, -8873.15f, 2887.47f, 14.2f }, + { "katerina", 257016, -8807.93f, 2949.0f, 7.22f }, + { "blazeroar", 255702, -8858.47f, 2966.2f, 7.22f }, + { "questioner", 256236, -8764.98f, 2887.64f, 15.13f } }; + // The goal counts once the checkpoint bosses are dead too. + d.goal_after_checkpoints = true; v.push_back(std::move(d)); } - // Blackmaw Hold (Forever, map 2974), the landing in the entrance tunnel to Varrox Bleakhoof: Withermaw, Bonesnout the - // Unbroken, Impaan the Imprisoner, the Unbound Spirit (Elder Bramblesnap's ritual starts when the party comes near), the - // Blackmaw Behemoth with Clawbert, Elder Shaman Bloodmane, Varrox (the route and BlackmawHoldScript's order). Bot-led, at 57. + // Blackmaw Hold (Forever, map 2974), live's landing at the tunnel's north end to Varrox Bleakhoof: Withermaw, Bonesnout the + // Unbroken, Impaan the Imprisoner, the Unbound Spirit (Elder Bramblesnap's ritual starts when the party comes near), Elder + // Shaman Bloodmane, the Blackmaw Behemoth with Clawbert, then the 200 y fall into the pool and Varrox in the chamber below + // (the route and BlackmawHoldScript's order). Bot-led, at 60: live's bosses are 57-60 (world 2026_11_26_42). { - static constexpr DungeonRow kBlackmaw = { "blackmaw_full", "Blackmaw Hold: level 57 party, entrance to Varrox Bleakhoof", - 2974, 3470.f, 3690.f, 301.9f, 90.f, 57, 247234, "Varrox Bleakhoof", 75 }; + static constexpr DungeonRow kBlackmaw = { "blackmaw_full", "Blackmaw Hold: level 60 party, entrance to Varrox Bleakhoof", + 2974, 3375.09f, 3822.24f, 306.98f, 274.3f, 60, 247234, "Varrox Bleakhoof", 75 }; ScenarioDef d = MakeDungeonScenario(kBlackmaw); - // The hold's creature spawns span x 3255..3745, y 2819..3712, z 136..361; 50 y around them. - d.limits.bounds = { true, 3205.f, 3795.f, 2769.f, 3762.f, 86.f, 411.f }; + // Live's creature and object spawns and the landing span x 3238..3749, y 2789..3830, z -62..360; 50 y round them. + d.limits.bounds = { true, 3188.f, 3799.f, 2739.f, 3880.f, -112.f, 410.f }; d.full_clear = true; - // Staging spots: crumbs of the 0044 route 35-60 y of walk before each boss. - d.checkpoints = { { "withermaw", 247195, 3701.07f, 3371.38f, 289.5f }, - { "bonesnout", 247198, 3424.16f, 3379.36f, 254.1f }, - { "impaan", 247206, 3317.33f, 3529.87f, 347.07f }, - { "spirit", 247231, 3293.4f, 2942.53f, 210.16f }, - { "behemoth", 247207, 3622.4f, 2892.76f, 172.65f }, - { "bloodmane", 247209, 3521.33f, 2971.67f, 146.29f }, - { "varrox", 247234, 3571.87f, 2869.2f, 169.49f } }; + // Staging spots: crumbs of the 0069 route 39-48 y of walk before each boss (Varrox's is on the shore below the fall). + d.checkpoints = { { "withermaw", 247195, 3697.27f, 3359.0f, 287.47f }, + { "bonesnout", 247198, 3338.67f, 3402.67f, 251.34f }, + { "impaan", 247206, 3318.31f, 3616.27f, 343.98f }, + { "spirit", 247231, 3276.0f, 2933.81f, 207.41f }, + { "bloodmane", 247209, 3637.33f, 2868.27f, 172.74f }, + { "behemoth", 247207, 3510.08f, 2977.12f, 145.17f }, + { "varrox", 247234, 3463.84f, 2962.83f, -63.1f } }; v.push_back(std::move(d)); } - // The Shaper's Terrace (Forever, map 3001), the landing beside the client's trigger of the dungeon to Nanaya: Venomridge, Bolt, - // Cinder, Tor'Rel and Izha'Rel, Snowtalon, Vitrix, Titanosaur, Thunderhoof, King Op, the Direhorn Matriarch, Nanaya (the route - // and ShapersTerraceScript's order). Bot-led, at 59. + // The Shaper's Terrace (Forever, map 3001), live's landing ledge to Nanaya: the jump into the pool, then Cinder, + // Snowtalon, Vitrix, Tor'Rel and Izha'Rel, Venomridge, Bolt, Thunderhoof, King Op, the Direhorn Matriarch, Nanaya (the route + // and ShapersTerraceScript's order). Bot-led, at 60: live's bosses are 61-62 (world 2026_11_25_83/84), made for a party at 60. + // Not the Titanosaur: he stands behind the Titanic Door, live's locked raid gate. { - static constexpr DungeonRow kShapers = { "shapers_full", "The Shaper's Terrace: level 59 party, entrance to Nanaya", - 3001, -5792.65f, -1252.98f, -5.95f, 75.f, 59, 261809, "Nanaya", 90 }; + static constexpr DungeonRow kShapers = { "shapers_full", "The Shaper's Terrace: level 60 party, entrance to Nanaya", + 3001, -5921.34f, -975.49f, 63.26f, 75.f, 60, 261809, "Nanaya", 90 }; ScenarioDef d = MakeDungeonScenario(kShapers); - // The terrace's creature spawns span x -6038..-5496, y -1829..-554, z -6..113; 50 y around them. - d.limits.bounds = { true, -6088.f, -5446.f, -1879.f, -504.f, -56.f, 163.f }; + // Live's creature spawns span x -6112..-5418, y -1971..-555, z -8..152 (the fliers over the hills left out); 50 y round them. + d.limits.bounds = { true, -6162.f, -5368.f, -2021.f, -505.f, -58.f, 202.f }; d.full_clear = true; - // Staging spots: crumbs of the 0045 route 35-55 y of walk before each boss. - d.checkpoints = { { "venomridge", 261813, -5882.29f, -1233.07f, 6.88f }, - { "bolt", 262081, -5920.0f, -1226.67f, 9.37f }, - { "cinder", 261974, -5909.07f, -821.07f, 98.06f }, - { "torrel", 261811, -5728.0f, -736.0f, 31.33f }, - { "snowtalon", 262297, -5685.33f, -650.67f, 20.0f }, - { "vitrix", 272561, -5536.91f, -820.75f, 18.66f }, - { "titanosaur", 253201, -5664.93f, -1409.13f, 30.66f }, - { "thunderhoof", 261812, -5983.73f, -1547.64f, 7.57f }, - { "kingop", 261993, -5988.62f, -1808.44f, 44.53f }, - { "direhorn", 262127, -5770.35f, -1758.24f, 21.19f }, + // Staging spots: crumbs of the route 26-56 y of walk before each boss (Bolt's is Venomridge's spot, 25 y from him). + d.checkpoints = { { "cinder", 261974, -5907.38f, -828.89f, 104.17f }, + { "snowtalon", 262297, -5483.11f, -809.87f, 20.62f }, + { "vitrix", 272561, -5484.2f, -813.07f, 19.0f }, + { "torrel", 261811, -5644.64f, -1205.6f, 34.6f }, + { "venomridge", 261813, -5854.45f, -1186.03f, -0.71f }, + { "bolt", 262081, -5908.77f, -1192.19f, 6.76f }, + { "thunderhoof", 261812, -5962.67f, -1418.67f, 10.77f }, + { "kingop", 261993, -6061.24f, -1946.13f, 48.8f }, + { "direhorn", 262127, -5900.84f, -1738.36f, 14.04f }, { "nanaya", 261809, -5813.33f, -1589.33f, 37.33f } }; v.push_back(std::move(d)); } diff --git a/src/modules/PlayerbotV2/Diagnostics/ScenarioMonitor.h b/src/modules/PlayerbotV2/Diagnostics/ScenarioMonitor.h index a456ad836d..da05fec89b 100644 --- a/src/modules/PlayerbotV2/Diagnostics/ScenarioMonitor.h +++ b/src/modules/PlayerbotV2/Diagnostics/ScenarioMonitor.h @@ -56,9 +56,10 @@ struct ScenarioSample bool deep_water = false; // over water deeper than its height (BotMovement::SwimLevel) bool head_under = false; // its head is under the water (LIQUID_MAP_UNDER_WATER) bool swim_flag = false; // it has the swimming movement flag + bool mana_hold = false; // a leading tank that told the group "waiting for mana" this second (BotAI::tank_lead_said) }; -enum class ScenarioFailKind : std::uint8_t { Idle, Stray, OutOfBounds, WrongMap, HealerOom, Death, GroupStalled, Wipe, Timeout, SetupFailed, GroupBroken, BossReset, DpsHold, HealerNoRest, SupportMissing, GroupIdle, FollowLost, Water, BossSkipped }; +enum class ScenarioFailKind : std::uint8_t { Idle, Stray, OutOfBounds, WrongMap, HealerOom, Death, GroupStalled, Wipe, Timeout, SetupFailed, GroupBroken, BossReset, DpsHold, HealerNoRest, SupportMissing, GroupIdle, FollowLost, Water, BossSkipped, ManaHold }; inline char const* ToString(ScenarioFailKind k) { @@ -83,6 +84,7 @@ inline char const* ToString(ScenarioFailKind k) case ScenarioFailKind::FollowLost: return "follow_lost"; case ScenarioFailKind::Water: return "water"; case ScenarioFailKind::BossSkipped: return "boss_skipped"; + case ScenarioFailKind::ManaHold: return "mana_hold"; } return "?"; } @@ -134,6 +136,7 @@ struct ScenarioLimits float recover_mana_pct = 40.f; std::uint32_t rest_ms = 90000; // a healer under pull_ready_mana_pct this long out of a fight is not drinking back float pull_ready_mana_pct = 75.f; // the tank waits for its healer to reach this (Classic::kPullReadyHealerManaPct) + bool no_mana_hold = false; // a tank holding a trash pull for mana fails the run (ScenarioDef::tank_lead) float stray_yards = 70.f; std::uint32_t stray_ms = 20000; float oom_pct = 10.f; @@ -323,7 +326,13 @@ public: { b.anchor_x = s.x; b.anchor_y = s.y; b.anchor_ms = now_ms; b.has_anchor = true; b.idle_reported = false; } - else if (!b.idle_reported && now_ms - b.anchor_ms >= limits_.idle_ms && SomeoneElseWalking(samples, s.id, now_ms)) + // The clock runs only while someone else walks: a squad standing together (the tank too) is waiting, for a scripted + // door, a patrol or an event, and the group_stalled rule judges that wait. Counted from the start of a shared wait, + // the moment the tank set off again read as a bot left standing (sfk_full af59: the four stood 60 s with the tank + // while Ashcrombe walked to the Courtyard Door, "stood 68 s while the group moved on" one second after the door opened). + else if (!SomeoneElseWalking(samples, s.id, now_ms)) + b.anchor_ms = now_ms; + else if (!b.idle_reported && now_ms - b.anchor_ms >= limits_.idle_ms) { b.idle_reported = true; Fail(ScenarioFailKind::Idle, s.name, "stood " + std::to_string((now_ms - b.anchor_ms) / 1000u) + " s at " + Pos(s) + " while the group moved on", now_ms); @@ -399,6 +408,12 @@ public: b.oom_reported = false; } + // a leading tank that holds a trash pull for mana: a player's five-man does not stop for it. + if (limits_.no_mana_hold && s.mana_hold && !b.mana_hold_reported) + { + b.mana_hold_reported = true; + Fail(ScenarioFailKind::ManaHold, s.name, "the leading tank holds the pull for mana (\"waiting for mana\")", now_ms); + } // healer that does not rest: below the tank's pull-ready mana, out of a fight, for rest_ms. The squad waits for it (that is // not idle, above), so a healer that never drinks is reported here and not as the tank's idleness. if (s.role == ScenarioRoleKind::Healer && !s.in_combat && !any_combat && s.mana_pct >= 0.f && s.mana_pct < limits_.pull_ready_mana_pct) @@ -611,6 +626,7 @@ private: std::uint32_t rest_since_ms = 0; bool rest_active = false; bool rest_reported = false; + bool mana_hold_reported = false; bool oob_reported = false; bool wrong_map_reported = false; bool died = false; // dead at some point of this run: where it stands afterwards (a graveyard, a spirit healer) is its death's doing diff --git a/src/modules/PlayerbotV2/Diagnostics/ScenarioRunner.cpp b/src/modules/PlayerbotV2/Diagnostics/ScenarioRunner.cpp index 3f128373b4..418c6cdb17 100644 --- a/src/modules/PlayerbotV2/Diagnostics/ScenarioRunner.cpp +++ b/src/modules/PlayerbotV2/Diagnostics/ScenarioRunner.cpp @@ -148,6 +148,8 @@ constexpr float kPatrolEtaOrderYards = 90.f; namespace Owned = ::Playerbot::V2::Gear::Owned; constexpr std::size_t kStageBatch = 4; // squads over five: members set up per step, so the world thread keeps ticking +constexpr float kStageSpotYd = 60.f; // a member further than this from its staging spot is sent to it +constexpr std::uint32_t kStageHoldMs = 60u * 1000u; // a ready member holds its spot this long, renewed every staging step enum class Phase : std::uint8_t { Idle, Stage, Enter, Arrive, Run, Parity }; @@ -249,7 +251,11 @@ struct Run std::uint32_t patrol_home_ms = 0; // run_ms of that sample (one a second: a tick's step is too small to compare) bool patrol_homeward = false; // the last two samples had him nearer home float patrol_speed = 0.f; // his measured walking speed toward home (yards a second; 0 = not measured yet) - float patrol_tank_route = -1.f; // the main tank's route length from where it waits to the boss's spawn; -1 = not measured yet + float patrol_tank_route = -1.f; // the main tank's route length from where it waits to the patrol's meeting spot; -1 = not measured yet + // Where the raid meets a patrolling boss: his spawn, or the low end of his patrol when the landing was found round it (his spawn is on a + // raised walk above the room he is fought in). Set by PickArrival; patrol_meet_set false = his spawn. + bool patrol_meet_set = false; + float patrol_meet_x = 0.f, patrol_meet_y = 0.f, patrol_meet_z = 0.f; bool kits_stocked = false; // the role kits (flask, elixirs, food) went into the bags at 'in place' (StockRaidKits) bool trash_cleared = false; // The boss pull's statistics ([pull_stats]): started at the boss's first combat, reported 90 s later and when the run ends. @@ -519,6 +525,20 @@ bool StageMember(Run& run, Member& m) run.stage_status += fmt::format("{}=revive ", m.def.name); return false; } + // A squad is set up at its staging spot, not wherever the character logged in or its idle rules took it: alcaz_full af69i staged a mage + // that was grinding in Burning Steppes, it died to a Firegut Ogre Mage 15 s before the entry teleport, landed as a ghost, and the squad + // held for the dead member until the 120 s stall. A parity run has its own spot and flat-ground step (the Stage phase's parity branches). + if (!def.parity && !p->IsBeingTeleported()) + { + std::uint32_t stage_map; float sx, sy, sz; + StagePoint(p, stage_map, sx, sy, sz); + if (p->GetMapId() != stage_map || p->GetDistance2d(sx, sy) > kStageSpotYd) + { + SendToStage(p); + run.stage_status += fmt::format("{}=tostage ", m.def.name); + return false; + } + } if (!::Playerbot::Services::Registry().has(id)) { run.stage_status += fmt::format("{}=noai ", m.def.name); @@ -694,6 +714,17 @@ void FormGroup(Run& run) group->BroadcastGroupUpdate(); } +// The staging Hold (the Stage phase) is taken back when the squad leaves for the scenario's map: a dungeon run is bot-led from its first +// second, and a raid takes its own Hold at the landing (Phase::Arrive). +void ReleaseStageHold(Run& run) +{ + if (run.def->parity) + return; + for (Member const& m : run.members) + if (BotAI* ai = ::Playerbot::Services::Registry().ai(m.id); ai && ai->holding_position(GameTime::GetGameTimeMS())) + ai->exit_manual(); +} + // The squad's group is whole: every member is in it and it holds the whole squad. A member found in another group (or none) is // put back into the squad's group, and what was found is logged once: the group_broken invariant must report the bots' play, not // a setup that never finished (mc_garr: 24 bots in a group of 2 one second into the run). False while anything is still wrong. @@ -1750,7 +1781,13 @@ bool PickArrival(Run& run, Player* leader) run.boss_x = sx; run.boss_y = sy; run.boss_z = sz; if (found) { - TC_LOG_INFO("playerbot.v2", "[scenario] {} landing found round the low end of the patrol of creature {} at {:.1f},{:.1f},{:.1f} ({:.1f} y below its spawn)", + // The attack meets him there too, not at the spawn on the walk: naxx_grobbulus af60-1 ordered the main tank so it met him at + // his spawn (3205.4,-3341.9,320.2), 27 y above the floor the raid landed on; the tank held him on the walk, the healers on + // the floor had no line of sight to it ([raid_los] every 2 s, 12 healers casting 0 in the first 27 s) and it died at 33 s. + run.patrol_meet_set = true; + run.patrol_meet_x = low->X; run.patrol_meet_y = low->Y; run.patrol_meet_z = low->Z; + TC_LOG_INFO("playerbot.v2", "[scenario] {} landing found round the low end of the patrol of creature {} at {:.1f},{:.1f},{:.1f} ({:.1f} y below its spawn); " + "the attack meets him there", run.def->name, run.arrive_entry, low->X, low->Y, low->Z, sz - low->Z); return true; } @@ -2074,11 +2111,27 @@ void GiveSquadOrders(Run& run, bool on) void TakeLead(Run& run) { Player* p = StandIn(run); - if (!p || !run.def->player_lead || !run.stand_in_detached) + if (!p || !(run.def->player_lead || run.def->tank_lead) || !run.stand_in_detached) return; ::Playerbot::Scenario::MarkHuman(p->GetGUID().GetCounter(), true); if (Group* g = p->GetGroup(); g && g->GetLeaderGUID() != p->GetGUID()) g->ChangeLeader(p->GetGUID()); + if (run.def->tank_lead) + { + // "lead on" as BotCommandParser gives it: the lead replaces the follow and fall-back orders and re-arms the run. The stand-in + // follows the tank (PlayStandIn). + for (Member const& m : run.members) + if (BotAI* ai = ::Playerbot::Services::Registry().ai(m.id)) + { + ai->set_tank_lead(BotAI::TankLead::On); + ai->exit_manual(); + ai->release_owner_lead(false); + if (ai->dungeon_run_mode() != BotAI::DungeonRunMode::Active) + ai->set_dungeon_run_mode(BotAI::DungeonRunMode::Active); + } + LeadLog(run, fmt::format("{} is the player of the group and follows; the tank leads (lead on)", p->GetName())); + return; + } run.lead_route = ::Playerbot::Services::Dungeons().RouteFor(p->GetMapId(), uint32(p->GetMap()->GetDifficultyID())); // The route point nearest the entrance is where he starts. run.lead_wp = 0; @@ -2095,10 +2148,15 @@ void TakeLead(Run& run) void DropLead(Run& run) { - if (!run.def->player_lead) + if (!run.def->player_lead && !run.def->tank_lead) return; for (Member const& m : run.members) + { ::Playerbot::Scenario::MarkHuman(m.id, false); + if (run.def->tank_lead) + if (BotAI* ai = ::Playerbot::Services::Registry().ai(m.id)) + ai->set_tank_lead(BotAI::TankLead::Off); + } } // The nearest mob he would have to fight to walk on: alive, hostile, not fighting, in sight, within kLeadPullYd. @@ -3335,6 +3393,59 @@ std::string MemberState(Member const& m) return s; } +// The instance's view of its fights at a failure: each boss state that is IN_PROGRESS or SPECIAL, and every living creature of the +// instance that is engaged, wherever it stands, with what it is fighting. An encounter held in progress shuts the tank's advance +// (gate encounter_in_progress), and a creature far from the squad that holds it is not in any bot's log (blackmaw_full af84 +// 2026-11-26: the squad stood 120 s at (3418,3080,244) behind encounter_in_progress, every bot out of combat, no boss near). +std::string InstanceFightState(Run const& run) +{ + Player* p = nullptr; + for (Member const& m : run.members) + if (Player* mp = Find(m.id); mp && mp->IsInWorld()) + { + p = mp; + break; + } + InstanceMap* im = p ? p->GetMap()->ToInstanceMap() : nullptr; + if (!im) + return {}; + std::string text; + if (InstanceScript* is = im->GetInstanceScript()) + { + std::string states; + for (uint32 i = 0; i < is->GetEncounterCount(); ++i) + if (EncounterState const st = is->GetBossState(i); st == IN_PROGRESS || st == SPECIAL) + states += fmt::format(" boss {} {}", i, st == IN_PROGRESS ? "IN_PROGRESS" : "SPECIAL"); + text += fmt::format("\n[scenario] report instance encounter_in_progress={}{}", is->IsEncounterInProgress() ? 1 : 0, + states.empty() ? std::string(" (no boss state in progress)") : states); + } + uint32 shown = 0; + for (auto const& [spawnId, c] : im->GetCreatureBySpawnIdStore()) + { + if (!c->IsAlive() || !c->IsEngaged()) + continue; + if (++shown > 20) + break; + Unit* v = c->GetVictim(); + std::string refs; + uint32 nrefs = 0; + for (auto const& [guid, ref] : c->GetCombatManager().GetPvECombatRefs()) + { + Unit* o = ref->GetOther(c); + if (++nrefs <= 3 && o) + refs += fmt::format(" {}{}({}) at {:.1f},{:.1f},{:.1f}", o->IsPlayer() ? "player " : "", o->GetName(), o->GetEntry(), + o->GetPositionX(), o->GetPositionY(), o->GetPositionZ()); + } + text += fmt::format("\n[scenario] report engaged {} ({}) guid {} at {:.1f},{:.1f},{:.1f} combat={} victim={} threat_list={} pve_refs={}{} evade={}", + c->GetName(), c->GetEntry(), spawnId, c->GetPositionX(), c->GetPositionY(), c->GetPositionZ(), + c->IsInCombat() ? 1 : 0, v ? fmt::format("{}({})", v->GetName(), v->GetEntry()) : std::string("none"), + c->GetThreatManager().GetThreatListSize(), nrefs, refs, c->IsInEvadeMode() ? 1 : 0); + } + if (!shown) + text += "\n[scenario] report engaged: no living creature of the instance is engaged"; + return text; +} + std::string FailureReport(Run const& run) { std::string text; @@ -3344,6 +3455,7 @@ std::string FailureReport(Run const& run) run.run_ms / 1000u, first_ms / 1000u); for (Member const& m : run.members) text += "\n[scenario] report state " + MemberState(m); + text += InstanceFightState(run); for (std::string const& l : LogLinesSince(run, from_ms)) text += "\n[scenario] report log " + l; // The first death, when it came before the window above: how the fight was lost, not how it ended. @@ -3608,6 +3720,9 @@ void Sample(Run& run, std::vector& out) // damage dealers 40-53 y after the tank's pull while the autopilot expected them to wait, and the tank died to the extra // Earthborers they woke. The idle check reads 0 here unless a squad is ever led by a player. s.group_idle_ms = ai->group_idle_ms(GameTime::GetGameTimeMS()); + // The tank's "waiting for mana" (State_Idle's lead_wait), said this second. + if (char const* said = ai->tank_lead_said(); said && std::string_view(said) == "mana") + s.mana_hold = GameTime::GetGameTimeMS() - ai->tank_lead_said_ms() < 1500u; } if (p->GetPowerType() == POWER_MANA && p->GetMaxPower(POWER_MANA) > 0) s.mana_pct = 100.f * float(p->GetPower(POWER_MANA)) / float(p->GetMaxPower(POWER_MANA)); @@ -3960,6 +4075,26 @@ static void TickRun(Run& run, std::uint32_t diff_ms) std::size_t budget = run.members.size() > 5 ? kStageBatch : run.members.size(); for (Member& m : run.members) { + // A member set up stays set up only while it is still fit to go in: alive, out of combat and on its staging spot. Until the + // whole squad is ready it holds that spot, so its idle rules do not take it off grinding (alcaz_full af69i: the ready mage + // walked into Burning Steppes and died there 15 s before the entry teleport). The Hold is renewed every step and taken + // back when the squad leaves (ReleaseStageHold). + if (m.ready && !run.def->parity) + { + Player* p = Find(m.id); + std::uint32_t stage_map = kStageMap; float sx = kStageX, sy = kStageY, sz = kStageZ; + if (p) + StagePoint(p, stage_map, sx, sy, sz); + if (!p || !p->IsInWorld() || !p->IsAlive() || p->IsInCombat() || + (!p->IsBeingTeleported() && (p->GetMapId() != stage_map || p->GetDistance2d(sx, sy) > kStageSpotYd))) + { + TC_LOG_INFO("playerbot.v2", "[scenario] {} {} was ready but is {}: set up again", run.def->name, m.def.name, + !p || !p->IsInWorld() ? "out of the world" : !p->IsAlive() ? "dead" : p->IsInCombat() ? "in combat" : "off its staging spot"); + m.ready = false; + } + else if (BotAI* ai = ::Playerbot::Services::Registry().ai(m.id)) + ai->enter_manual(BotAI::OwnerCommand::Hold, ObjectGuid::Empty, GameTime::GetGameTimeMS(), kStageHoldMs); + } if (m.ready) continue; if (!budget) { @@ -4125,6 +4260,7 @@ static void TickRun(Run& run, std::uint32_t diff_ms) } if (all) { + ReleaseStageHold(run); ResetLocks(run); FormGroup(run); ForgetRecentInstance(run); @@ -4153,6 +4289,19 @@ static void TickRun(Run& run, std::uint32_t diff_ms) // (bwl_razorgore 4f7b18e3: Mcwarra reached the entrance one second before the landing and stayed there, 39 of 40 arrived). if (p && p->IsInWorld() && p->GetMapId() == run.def->map && !p->IsBeingTeleported()) { + // The run starts from a whole, living squad: a member that died between the staging check and the entry teleport + // lands as a ghost, and the others hold for it until the stall check ends the run with no boss tried (alcaz_full af69i). + // This is the setup's revive, before the run's first second, as the staging's own is. + if (!p->IsAlive()) + { + p->ResurrectPlayer(1.0f); + p->SpawnCorpseBones(); + p->SetFullHealth(); + if (p->GetPowerType() == POWER_MANA) + p->SetPower(POWER_MANA, p->GetMaxPower(POWER_MANA)); + TC_LOG_WARN("playerbot.v2", "[scenario] {} {} landed dead on map {}: revived before the run starts", run.def->name, m.def.name, + run.def->map); + } if (!m.arrival_logged) { m.arrival_logged = true; @@ -4747,7 +4896,11 @@ static void TickRun(Run& run, std::uint32_t diff_ms) { // From his spawn point, not GetHomePosition: waypoint movement moves the home along with him (every wait line in // naxx_patchwerk 1115f said "0 y from his home", so every one counted as walking home). - float const home_d = std::hypot(boss->GetPositionX() - run.boss_x, boss->GetPositionY() - run.boss_y); + // The meeting spot stands for his home where the landing was found round the low end of his patrol (patrol_meet_set). + float const meet_x = run.patrol_meet_set ? run.patrol_meet_x : run.boss_x; + float const meet_y = run.patrol_meet_set ? run.patrol_meet_y : run.boss_y; + float const meet_z = run.patrol_meet_set ? run.patrol_meet_z : run.boss_z; + float const home_d = std::hypot(boss->GetPositionX() - meet_x, boss->GetPositionY() - meet_y); if (run.patrol_home_dist < 0.f || run.run_ms - run.patrol_home_ms >= 1000u) { run.patrol_homeward = run.patrol_home_dist >= 0.f && home_d < run.patrol_home_dist - 0.5f; @@ -4762,8 +4915,8 @@ static void TickRun(Run& run, std::uint32_t diff_ms) // as 1.5 x the straight line. PathGenerator pg(tank); ::Playerbot::BotMovement::SehSafeCalculatePathFrom(pg, tank->GetPositionX(), tank->GetPositionY(), tank->GetPositionZ(), - run.boss_x, run.boss_y, run.boss_z); - float const straight = std::hypot(run.boss_x - tank->GetPositionX(), run.boss_y - tank->GetPositionY()); + meet_x, meet_y, meet_z); + float const straight = std::hypot(meet_x - tank->GetPositionX(), meet_y - tank->GetPositionY()); run.patrol_tank_route = (pg.GetPathType() & (PATHFIND_NOPATH | PATHFIND_FARFROMPOLY | PATHFIND_INCOMPLETE)) ? straight * 1.5f : std::max(pg.GetPathLength(), straight); } diff --git a/src/modules/PlayerbotV2/Fleet/BotComposition.cpp b/src/modules/PlayerbotV2/Fleet/BotComposition.cpp index 7c32a96b4e..a54217387f 100644 --- a/src/modules/PlayerbotV2/Fleet/BotComposition.cpp +++ b/src/modules/PlayerbotV2/Fleet/BotComposition.cpp @@ -480,7 +480,21 @@ BotComposition::Pick BotComposition::Roll(uint8 race_hint, uint8 cls_hint, } else { - p.name = Fleet::BotNamePool::Acquire(p.gender, race); + // A pool name is checked as RollUniqueName checks its own: the pool was filtered for length and letters, not for the + // client's reserved names (NamesReserved: lore names such as Zuljin), and the character create refuses those. A refused + // name was popped and marked used, so the next one is drawn (TestPlayer rotgrip-1121: `.bot add priest healer` failed + // with "CheckPlayerName rejected 'Zuljin' with code=104"). + for (int draw = 0; draw < 8 && p.name.empty(); ++draw) + { + std::string name = Fleet::BotNamePool::Acquire(p.gender, race); + if (name.empty()) + break; + ResponseCodes const code = ObjectMgr::CheckPlayerName(name, LOCALE_enUS, true); + if (code == CHAR_NAME_SUCCESS && !sCharacterCache->GetCharacterCacheByName(name)) + p.name = std::move(name); + else + TC_LOG_INFO("playerbot.v2", "[BotComposition] pool name '{}' refused (code {}), drawing another", name, uint32(code)); + } if (p.name.empty()) p.name = RollUniqueName(); } diff --git a/src/modules/PlayerbotV2/Fleet/BotGuildNamePool.cpp b/src/modules/PlayerbotV2/Fleet/BotGuildNamePool.cpp index 39ed1fcdcd..aa4b219aaf 100644 --- a/src/modules/PlayerbotV2/Fleet/BotGuildNamePool.cpp +++ b/src/modules/PlayerbotV2/Fleet/BotGuildNamePool.cpp @@ -5,6 +5,7 @@ #include "DatabaseEnv.h" #include "GuildMgr.h" #include "Log.h" +#include "ObjectMgr.h" #include @@ -14,16 +15,17 @@ namespace { // Per-faction static name pools. Mix of theme variations + capital // references so a populated server feels like organic guild diversity. -// Roughly 30 per faction. All names < 24 chars (TC's guild name limit -// is 24 with most clients; we leave a buffer). +// Roughly 30 per faction. Every name at most MAX_CHARTER_NAME (24) characters, the client's limit and the width of `guild`.`name` +// (varchar 24): three names of 25-26 made guilds the server could not save (guild 20 "Shadowblades of Silvermoon", DBErrors +// "[1406] Data too long for column 'name'", Discord 2026-11-22). PickAndReserve checks each name with the server's own charter rule. std::vector const kAllianceNames = { "Iron Hearts", "Stormwind Vanguard", "Lionhearts of Azeroth", - "Knights of the Silver Hand", + "Silver Hand Knights", "Westfall Brigade", "Wintergrasp Veterans", - "Stranglethorn Adventurers", + "Stranglethorn Explorers", "Eastvale Rangers", "Goldshire Regulars", "Theramore Loyalists", @@ -59,7 +61,7 @@ std::vector const kHordeNames = { "Orgrimmar Reavers", "Bloodspear Tribe", "Sons of Doomhammer", - "Shadowblades of Silvermoon", + "Silvermoon Shadowblades", "Sindorei Magisters", "Darkspear Rebellion", "Maghar Outcasts", @@ -133,6 +135,15 @@ std::string BotGuildNamePool::PickAndReserve(Faction f, uint64 founder_low) if (sGuildMgr->GetGuildByName(candidate)) continue; + // A name the server would refuse a player's charter for (too long for `guild`.`name`, characters the realm does not allow): + // the guild would live in memory only, its save failing on every write. + if (!ObjectMgr::IsValidCharterName(candidate)) + { + TC_LOG_ERROR("playerbot.v2", "[BotGuildNamePool] '{}' is not a valid guild name (at most {} characters, realm name rules)", + candidate, MAX_CHARTER_NAME); + continue; + } + // Skip if currently reserved by another in-flight charter. if (std::find(reserved_.begin(), reserved_.end(), candidate) != reserved_.end()) continue; diff --git a/src/modules/PlayerbotV2/Fleet/BotPopulationManager.cpp b/src/modules/PlayerbotV2/Fleet/BotPopulationManager.cpp index e0dfb0a4e8..004c5b5a75 100644 --- a/src/modules/PlayerbotV2/Fleet/BotPopulationManager.cpp +++ b/src/modules/PlayerbotV2/Fleet/BotPopulationManager.cpp @@ -1650,6 +1650,30 @@ Role BotPopulationManager::ApplyCompanionRole(Player* bot, Role requested, char uint8 const cls = bot->GetClass(); OwnerRegistry& owners = Services::Owners(); + // A player's own character brought as a bot (`.playerbot summon`) plays the spec its own talents say, and nothing here changes + // it: no class default spec, no spec or role stored from an earlier call, no raid quota role. Before, every summon pinned one + // (a Beast Mastery hunter came as Marksmanship, a protection paladin as a healer) and the talent rules then bought that spec's + // talents over the player's own (RU general 11-21: by_hoy_, Alex Black Cat). An owner's /setrole still works for the session + // (DeclareRole). At login a spec pinned by an earlier summon is let go. + if (IsPlayersOwnCharacter(bot)) + { + bool const login = std::strcmp(where, "login") == 0; + if (login) + { + ::Playerbot::Classic::SetSpecOverride(bot, 0); + if (BotAI* ai = Services::Registry().ai(id)) + ai->set_role_override(Role::Unknown); + } + uint32 const own_spec = ::Playerbot::Classic::EffectiveSpecId(bot); + Role const own_role = IsTankSpec(cls, uint16(own_spec)) ? Role::Tank : IsHealerSpec(cls, uint16(own_spec)) ? Role::Healer : Role::Dps; + if (login || requested != Role::Unknown) + TC_LOG_INFO("playerbot.v2", "[role] {} is a player's own character: keeps spec {} ({}), nothing pinned ({}{}{})", bot->GetName(), + own_spec, own_role == Role::Tank ? "tank" : own_role == Role::Healer ? "healer" : "dps", where, + requested != Role::Unknown ? ", asked for " : "", + requested == Role::Tank ? "tank" : requested == Role::Healer ? "healer" : requested == Role::Dps ? "dps" : ""); + return own_role; + } + // 1. what the owner asked for now, 2. what is stored with the companion, 3. what its talents say. Only 1 and 2 are pinned and // stored; 3 is a guess about a build that may not be bought yet and is never kept (Fleet/CompanionRole.h). Role const declared = owners.DeclaredRole(id); @@ -4065,6 +4089,35 @@ PopulationSnapshot BotPopulationManager::Snapshot() const return snap; } +// The offline-candidate SELECT: up to 2*cap rows for EACH side, least recently seen first. It used to take 2*cap rows of both sides +// together; with last_seen_at NULL for every bot (only the queue filler writes it) the order never changed, the window held the same rows +// every cycle, and a side with none of its bots in them got no logins at all: reconcile stopped at 148/150 Alliance and 145/150 Horde +// with 3,052 bot characters (ForeverCore issue #386, sqmagellan). One query, two LIMITed halves, so the async path stays one callback. +static std::string OfflineCandidateSql(uint8 lo, uint8 hi, uint32 cap) +{ + static std::string const alliance_races = [] + { + std::string list; + for (uint32 race = 1; race < 128; ++race) + if (RaceIsAlliance(race)) + list += (list.empty() ? "" : ",") + std::to_string(race); + return list; + }(); + auto half = [&](char const* in) + { + return Trinity::StringFormat( + "(SELECT pv.character_guid_low, c.level, c.race FROM playerbot_v2_character pv " + "JOIN characters c ON c.guid = pv.character_guid_low " + "WHERE c.level BETWEEN {} AND {} " + "AND c.online = 0 " + "AND pv.distribution_level > 0 " + "AND c.race {} ({}) " + "ORDER BY pv.last_seen_at ASC LIMIT {})", + uint32(lo), uint32(hi), in, alliance_races, cap * 2); + }; + return half("IN") + " UNION ALL " + half("NOT IN"); +} + void BotPopulationManager::QueueOfflineCandidateFetch(size_t fill_index, uint8 lo, uint8 hi, uint32 cap) { // Query characters table for V2-marked bots with level ∈ [lo, hi]. @@ -4087,14 +4140,7 @@ void BotPopulationManager::QueueOfflineCandidateFetch(size_t fill_index, uint8 l // refuses to start while reconcile_in_progress_, so a bucket can never have // two of these outstanding. ++reconcile_inflight_; - queries_.AddCallback(CharacterDatabase.AsyncQuery(Trinity::StringFormat( - "SELECT pv.character_guid_low, c.level, c.race FROM playerbot_v2_character pv " - "JOIN characters c ON c.guid = pv.character_guid_low " - "WHERE c.level BETWEEN {} AND {} " - "AND c.online = 0 " - "AND pv.distribution_level > 0 " - "ORDER BY pv.last_seen_at ASC LIMIT {}", - uint32(lo), uint32(hi), cap * 2).c_str()) + queries_.AddCallback(CharacterDatabase.AsyncQuery(OfflineCandidateSql(lo, hi, cap).c_str()) .WithCallback([this, fill_index, gen = reconcile_gen_](QueryResult res) { // Rows from a cycle the watchdog abandoned: drop them rather than file @@ -4127,14 +4173,7 @@ BotPopulationManager::FetchOfflineCandidatesSync(uint8 lo, uint8 hi, uint32 cap) { std::vector rows; SLOW_CALL("FetchOfflineCandidatesSync (database)"); - auto res = CharacterDatabase.PQuery( - "SELECT pv.character_guid_low, c.level, c.race FROM playerbot_v2_character pv " - "JOIN characters c ON c.guid = pv.character_guid_low " - "WHERE c.level BETWEEN {} AND {} " - "AND c.online = 0 " - "AND pv.distribution_level > 0 " - "ORDER BY pv.last_seen_at ASC LIMIT {}", - uint32(lo), uint32(hi), cap * 2); + auto res = CharacterDatabase.Query(OfflineCandidateSql(lo, hi, cap).c_str()); if (!res) return rows; do { Field* f = res->Fetch(); @@ -4151,17 +4190,16 @@ std::vector BotPopulationManager::FilterOfflineCandidates(std::vector const& rows, bool alliance, uint32 cap) { - // Exactly the client-side filter the synchronous version did, including the - // 2*cap row window: the old query's `LIMIT cap*2` is a PREFIX of `rows` - // (same ORDER BY, wider limit), so walking only the first 2*cap entries - // reproduces its result row for row. + // The side's own 2*cap window (OfflineCandidateSql returns up to that many rows per side, each side least recently seen first): + // the first 2*cap rows of this side, then the cap. std::vector out; if (!cap) return out; - size_t const window = std::min(rows.size(), size_t(cap) * 2); - for (size_t i = 0; i < window; ++i) + size_t const window = size_t(cap) * 2; + size_t seen = 0; + for (OfflineCandidate const& c : rows) { - OfflineCandidate const& c = rows[i]; if (c.alliance != alliance) continue; + if (++seen > window) break; if (Pool::IsScenarioBot(c.char_guid)) continue; // a scenario test character is never part of the world population out.push_back(c); if (out.size() >= cap) break; diff --git a/src/modules/PlayerbotV2/Fleet/BotPopulationManager.h b/src/modules/PlayerbotV2/Fleet/BotPopulationManager.h index db82eb4949..b1b59e089a 100644 --- a/src/modules/PlayerbotV2/Fleet/BotPopulationManager.h +++ b/src/modules/PlayerbotV2/Fleet/BotPopulationManager.h @@ -503,16 +503,13 @@ private: // Offline bot characters that could be logged back in, used for the // "prefer login of existing bot" path. The rows come back from the async - // query in last_seen_at order and are NOT faction-filtered (the query - // never was); FilterOfflineCandidates applies the faction and the cap the - // way the old synchronous call did. + // query as two halves, up to 2*cap of each side in last_seen_at order; + // FilterOfflineCandidates takes the side's rows and its cap. struct OfflineCandidate { uint64 char_guid; uint8 level; bool alliance; }; // Issues the offline-candidate SELECT for one bucket. `cap` is the largest - // number of logins either faction could use this cycle; the row limit is - // 2*cap exactly as before, and FilterOfflineCandidates re-applies the - // smaller per-side cap as a prefix so the selection is identical to the - // per-side query it replaces. + // number of logins either faction could use this cycle; each side gets up + // to 2*cap rows (issue #386: one window over both sides starved one). void QueueOfflineCandidateFetch(size_t fill_index, uint8 lo, uint8 hi, uint32 cap); // Starts the async cold load of one bot's pipeline row into diff --git a/src/modules/PlayerbotV2/Fleet/BotSetupPipeline.cpp b/src/modules/PlayerbotV2/Fleet/BotSetupPipeline.cpp index adc4161296..cb7f58d708 100644 --- a/src/modules/PlayerbotV2/Fleet/BotSetupPipeline.cpp +++ b/src/modules/PlayerbotV2/Fleet/BotSetupPipeline.cpp @@ -294,8 +294,30 @@ void BotSetupPipeline::LearnLevelKit(Player* bot) uint32 const quest_spells = api.learn_class_quest_spells_free(); uint32 const spells = api.learn_trainer_spells_free(); uint32 const weapon_skills = api.learn_weapon_skills_free(); - TC_LOG_INFO("playerbot.v2", "[BotSetupPipeline] {} levelled to {}: {} class quest spells, {} trainer spells, {} weapon skills", - bot->GetName(), uint32(target_level), quest_spells, spells, weapon_skills); + // Lockpicking at the level's cap (level x 5), as the rogue a player levels has it: a player raises it on the boxes and doors on the + // way, which a bot does not pick, and Player::LearnSpell sets it full only once, at the level Pick Lock was learned. The scenario + // rogue is re-levelled from row to row (the Deadmines row is 21: 105), so at 53 it can stand short of Alcaz Prison's Maximum + // Security Door (250): in alcaz_full on af94 (27 Nov) the party stood at that door to the end and the rogue never tried it. + uint16 lockpicking = 0; + if (bot->HasSkill(SKILL_LOCKPICKING)) + { + uint16 const cap = bot->GetMaxSkillValueForLevel(); + if (bot->GetPureSkillValue(SKILL_LOCKPICKING) < cap) + bot->SetSkill(SKILL_LOCKPICKING, bot->GetSkillStep(SKILL_LOCKPICKING), cap, cap); + lockpicking = bot->GetPureSkillValue(SKILL_LOCKPICKING); + } + // Pick Lock (1804) asks for Thieves' Tools (5060) in the bags (SpellTotems Totem1), which a rogue buys from a trade vendor (15 silver). + // Without them every cast fails SPELL_FAILED_TOTEMS (153): alcaz_full on af98 (27 Nov) cast it 298 times on the + // Maximum Security Door, result 153 each time. A bot does not shop, so it carries the tools from the day it learns the spell. + constexpr uint32 kPickLock = 1804, kThievesTools = 5060; + if (bot->HasSpell(kPickLock) && !bot->HasItemCount(kThievesTools, 1, true)) + { + ItemPosCountVec dest; + if (bot->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, kThievesTools, 1) == EQUIP_ERR_OK) + bot->StoreNewItem(dest, kThievesTools, true); + } + TC_LOG_INFO("playerbot.v2", "[BotSetupPipeline] {} levelled to {}: {} class quest spells, {} trainer spells, {} weapon skills, lockpicking {}", + bot->GetName(), uint32(target_level), quest_spells, spells, weapon_skills, lockpicking); TC_LOG_INFO("playerbot.v2", "[BotSetupPipeline] {} trait spells: {}", bot->GetName(), api.describe_trait_spells()); } @@ -625,6 +647,34 @@ bool BotSetupPipeline::DoLearnProfessions(Player* bot) grant_skill(pair.gather_skill, pair.gather_apprentice); grant_skill(pair.craft_skill, pair.craft_apprentice); + // The tool of each granted skill in the bags: the real mechanics want it + // there (Spell::EffectOpenLock refuses an ore vein without a Mining Pick, + // craft spells check for the hammer), and the station show + // (idle:town_errand craft lingers) puts it in the bot's hand. + auto grant_tool = [&](uint32 entry) + { + if (!sObjectMgr->GetItemTemplate(entry) || bot->GetItemCount(entry)) return; + ItemPosCountVec dest; + if (bot->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, entry, 1) == EQUIP_ERR_OK) + bot->StoreNewItem(dest, entry, true); + }; + if (pair.gather_skill == 186) grant_tool(2901); // Mining Pick + if (pair.craft_skill == 164) grant_tool(5956); // Blacksmith Hammer + if (pair.craft_skill == 202) grant_tool(6219); // Arclight Spanner + if (pair.gather_skill == 393) grant_tool(7005); // Skinning Knife + + // One real starter recipe per station craft so a station visit casts for + // real (idle:town_errand CraftUse) — the trainer teaches the rest. + auto grant_recipe = [&](uint32 spell_id) + { + if (sSpellMgr->GetSpellInfo(spell_id, DIFFICULTY_NONE) && !bot->HasSpell(spell_id)) + bot->LearnSpell(spell_id, /*dependent=*/false); + }; + if (pair.craft_skill == 164) grant_recipe(2660); // Rough Sharpening Stone + if (pair.craft_skill == 202) grant_recipe(3918); // Rough Blasting Powder + if (pair.gather_skill == 186) grant_recipe(2657); // Smelt Copper + if (pair.craft_skill == 197) grant_recipe(2963); // Bolt of Linen Cloth + // Secondaries — every bot gets Cooking + Fishing, regardless of class // pick. First Aid (skill 129) was removed in BfA 8.0, so it's not // granted here even though bandages still exist as items. Apprentice @@ -634,6 +684,8 @@ bool BotSetupPipeline::DoLearnProfessions(Player* bot) if (!bot->HasSpell(818) && sSpellMgr->GetSpellInfo(818, DIFFICULTY_NONE)) bot->LearnSpell(818, /*dependent=*/false); grant_skill(/*Fishing*/ 356, 7732); + grant_tool(6256); // Fishing Pole + grant_recipe(8604); // Herb Baked Egg // Classic 1.60: vanilla has First Aid (removed only in BfA) and no // per-expansion profession skill lines, so a vanilla bot gets First Aid @@ -744,10 +796,10 @@ bool BotSetupPipeline::DoAcquireMount(Player* bot) // none here, and the pet rules give it one when it reaches 10. if (bot->GetClass() == CLASS_HUNTER && bot->GetLevel() >= 10 && bot->GetPetGUID().IsEmpty()) { - uint32 pet_entry = World::HunterPetEntryForRace(bot->GetRace()); - // A hunter nobody owns (world / pool bot) gets its own beast, stable per bot, instead of its race's one. - if (::Playerbot::Services::Owners().GetOwner(bot->GetGUID().GetCounter()).account_id == 0) - pet_entry = World::VariedHunterPetEntry(bot->GetTeam() == ALLIANCE, bot->GetGUID().GetCounter(), pet_entry); + // Every hunter gets its own beast, stable per bot, instead of its race's one: a player's hired hunters used to all bring the + // race's starter pet (Discord 2026-11-24, Gabriel: every hunter the same Plainstrider). A world bot did already. + uint32 pet_entry = World::VariedHunterPetEntry(bot->GetTeam() == ALLIANCE, bot->GetGUID().GetCounter(), + World::HunterPetEntryForRace(bot->GetRace())); if (!pet_entry) { // Unmapped race (allied) — fall back to faction-generic. diff --git a/src/modules/PlayerbotV2/Fleet/OwnerRegistry.cpp b/src/modules/PlayerbotV2/Fleet/OwnerRegistry.cpp index 77b8ec54ce..9e8b42b983 100644 --- a/src/modules/PlayerbotV2/Fleet/OwnerRegistry.cpp +++ b/src/modules/PlayerbotV2/Fleet/OwnerRegistry.cpp @@ -1,6 +1,10 @@ #include "OwnerRegistry.h" #include "Bot/CcDeny.h" +#include "BotAccountMgr.h" +#include "CharacterCache.h" #include "DatabaseEnv.h" +#include "ObjectGuid.h" +#include "Services.h" #include "Log.h" #include #include @@ -170,7 +174,12 @@ uint64 OwnerRegistry::OwnerCharacter(BotId bot) const if (it->second.player_guid != 0) return it->second.player_guid; auto online = online_owner_character_.find(it->second.account_id); - return online == online_owner_character_.end() ? 0 : online->second; + // A character never owns itself. A self bot (.playerbot self) is bound to its own account, and the character online on that account + // is the self bot: taken as its own owner, it counted as "its owner is in the group" in every group it was in, so it looted like a + // companion (only its own quest drops) and left every corpse of the party (selfbot-loot af59 check, BUGS-ALL #207). + if (online == online_owner_character_.end() || online->second == bot) + return 0; + return online->second; } void OwnerRegistry::SetOwner(BotId bot, uint32 account_id, uint64 player_guid) @@ -203,6 +212,12 @@ void OwnerRegistry::SetOwner(BotId bot, uint32 account_id, uint64 player_guid) "SET owner_account_id = {}, owner_player_guid = {}, companion_saved = {}, companion_saved_by = {} " "WHERE character_guid_low = {}", account_id, player_guid, saved ? 1 : 0, saved_by, bot); + // A pool bot let go (dismissed for good, unmarked, owner cleared) drops its last owner's standing orders: back in the world it + // would otherwise roll on everything and gather for nobody, and its next owner would inherit them. A player's own alt keeps + // them: they are its player's, and a dismissed alt is summoned again with them (row 245). + if (account_id == 0 && player_guid == 0 && Services::Initialized() && + Services::Accounts().is_pool_account(sCharacterCache->GetCharacterAccountIdByGuid(ObjectGuid::Create(bot)))) + SaveOwnerOrders(bot, 0); } bool OwnerRegistry::SavedBy(BotId bot, uint64 character) const @@ -623,9 +638,15 @@ OwnerRegistry::SquadState OwnerRegistry::SquadStateFromFields(Field const* f) out.formation_slot = f[1].GetUInt8(); out.follow_distance = f[2].GetFloat(); out.owner_verbose = f[3].GetBool(); + out.owner_orders = f[4].GetUInt8(); return out; } +void OwnerRegistry::SaveOwnerOrders(BotId bot, uint8 orders) const +{ + Db().DirectPExecute("UPDATE playerbot_v2_character SET owner_orders = {} WHERE character_guid_low = {}", uint32(orders), bot); +} + void OwnerRegistry::SaveSquadState(BotId bot, SquadState const& s) const { Db().DirectPExecute( diff --git a/src/modules/PlayerbotV2/Fleet/OwnerRegistry.h b/src/modules/PlayerbotV2/Fleet/OwnerRegistry.h index 612dfc3e6b..68bc43f9e2 100644 --- a/src/modules/PlayerbotV2/Fleet/OwnerRegistry.h +++ b/src/modules/PlayerbotV2/Fleet/OwnerRegistry.h @@ -171,20 +171,30 @@ public: uint8 formation_slot = 0; float follow_distance = 5.0f; bool owner_verbose = false; + // The owner's standing orders (kOwnerOrder* bits): read with the squad state, written by SaveOwnerOrders only, so a SaveSquadState + // from a freshly built SquadState never clears them. + uint8 owner_orders = 0; }; + // playerbot_v2_character.owner_orders bits (migration 0060). + static constexpr uint8 kOwnerOrderLootAll = 0x01; // "loot all": rolls on everything, greys included + static constexpr uint8 kOwnerOrderGather = 0x02; // "gather on": picks herbs and ore, skins the group's kills // Pull the persisted squad state for a bot. Used at bot register // time so the in-memory BotAI starts with the owner's saved // preferences instead of defaulting every relog. SquadState LoadSquadState(BotId bot) const; + // The owner's standing orders ("loot all", "gather on"), kept across relog, `.bot call` and restart (Alex Black Cat, RU general + // 11-21: an alt's gather and loot all were gone after every relog). kOwnerOrder* bits. + void SaveOwnerOrders(BotId bot, uint8 orders) const; // Column list LoadSquadState selects, in the order SquadStateFromFields // reads them. A caller that already reads the bot's playerbot_v2_character // row (the bot-login path) selects these alongside its own columns and // parses them with SquadStateFromFields instead of a second round trip. static constexpr char const* kSquadStateColumns = - "formation_type, formation_slot, follow_distance_yd, owner_verbose"; - // Parse the four kSquadStateColumns fields starting at `f`. + "formation_type, formation_slot, follow_distance_yd, owner_verbose, owner_orders"; + static constexpr uint32 kSquadStateFieldCount = 5; + // Parse the kSquadStateFieldCount kSquadStateColumns fields starting at `f`. static SquadState SquadStateFromFields(Field const* f); // Persist the in-memory squad state back to the DB. Called from diff --git a/src/modules/PlayerbotV2/Group/GroupSnapshot.h b/src/modules/PlayerbotV2/Group/GroupSnapshot.h index 0060adae33..15177f6294 100644 --- a/src/modules/PlayerbotV2/Group/GroupSnapshot.h +++ b/src/modules/PlayerbotV2/Group/GroupSnapshot.h @@ -42,6 +42,11 @@ struct GroupMemberSummary float damage_taken_per_s = 0.f; // The largest single hit it took in the last ClassicHeal::kSpikeWindowMs (DamageSpike): the next hit can be that big again. int32 damage_spike = 0; + // The damage the member's own harmful periodic auras deal it in the next ClassicHeal::kAuraDueHorizonMs: their damage ticks, and the + // ticks of a triggered spell whose damage takes in the member itself (Cinder's Conflagration 1310512: 300 a second on its carrier, + // and its Conflagration 16806 another 300 to every ally within 5 y, the carrier too: 600 a second for 4 s on a 2.5k cloth). Kept in + // 5-man instances (not raids). The healers count it with the swings coming (ClassicHeal::MakePatient). + int32 aura_damage_due = 0; int32 mana = 0; // Power index 0 (mana) only. int32 max_mana = 0; bool online = false; diff --git a/src/modules/PlayerbotV2/Group/GroupSnapshotBuilder.cpp b/src/modules/PlayerbotV2/Group/GroupSnapshotBuilder.cpp index c16b5a011b..3c1688639e 100644 --- a/src/modules/PlayerbotV2/Group/GroupSnapshotBuilder.cpp +++ b/src/modules/PlayerbotV2/Group/GroupSnapshotBuilder.cpp @@ -15,11 +15,13 @@ #include "ObjectAccessor.h" #include "Map.h" #include "SpellAuras.h" +#include "SpellAuraEffects.h" // AuraDamageDue: the periodic effects of a member's auras #include "SpellInfo.h" #include "SpellMgr.h" #include "Spell.h" #include "LFG.h" #include "Log.h" +#include #include #include #include @@ -156,6 +158,69 @@ uint32 TrackedRaidBuffId(uint32 spell_id) return m.recorded_as; } +// GroupMemberSummary::aura_damage_due. A triggered spell counts when the member casts it itself (the periodic trigger's caster is the +// aura's target unless the spell needs the aura's caster) and one of its damage effects takes in the caster: the caster itself, or an +// area of allies or party round it or its target (the member). +static int64 TriggeredSelfDamage(SpellInfo const* aura, uint32 trigger_id, Difficulty diff, Unit const* u) +{ + SpellInfo const* t = trigger_id ? sSpellMgr->GetSpellInfo(trigger_id, diff) : nullptr; + if (!t || t->NeedsToBeTriggeredByCaster(aura)) + return 0; + auto const hits_self = [](Targets tg) + { + switch (tg) + { + case TARGET_UNIT_CASTER: case TARGET_UNIT_CASTER_AREA_PARTY: case TARGET_UNIT_CASTER_AREA_RAID: + case TARGET_UNIT_SRC_AREA_ALLY: case TARGET_UNIT_DEST_AREA_ALLY: case TARGET_UNIT_SRC_AREA_PARTY: case TARGET_UNIT_DEST_AREA_PARTY: + return true; + default: + return false; + } + }; + int64 dmg = 0; + for (SpellEffectInfo const& e : t->GetEffects()) + if (e.IsEffect(SPELL_EFFECT_SCHOOL_DAMAGE) && (hits_self(e.TargetA.GetTarget()) || hits_self(e.TargetB.GetTarget()))) + dmg += std::max(e.CalcValueAsInt(u), 0); + return dmg; +} + +// The damage `u`'s own harmful periodic auras deal it in the next `horizon_ms` (GroupMemberSummary::aura_damage_due): each damage tick +// that falls inside it, and inside what is left of the aura, at the effect's amount (stacks included; before resistances). +static int32 AuraDamageDue(Unit const* u, int32 horizon_ms) +{ + int64 due = 0; + for (auto const& [id, app] : u->GetAppliedAuras()) + { + if (!app || app->IsPositive()) + continue; + Aura const* base = app->GetBase(); + if (!base) + continue; + int32 const window = base->IsPermanent() ? horizon_ms : std::min(base->GetDuration(), horizon_ms); + if (window <= 0) + continue; + for (AuraEffect const* eff : base->GetAuraEffects()) + { + if (!eff || !app->HasEffect(eff->GetEffIndex()) || !eff->IsPeriodic()) + continue; + int32 const period = eff->GetPeriod(); + if (period <= 0) + continue; + int32 const first = std::max(period - eff->GetPeriodicTimer(), 1); // the timer counts up from the last tick + if (first > window) + continue; + int64 const ticks = 1 + (window - first) / period; + int64 per_tick = 0; + if (eff->GetAuraType() == SPELL_AURA_PERIODIC_DAMAGE) + per_tick = std::max(eff->GetAmountAsInt(), 0); + else if (eff->GetAuraType() == SPELL_AURA_PERIODIC_TRIGGER_SPELL) + per_tick = TriggeredSelfDamage(base->GetSpellInfo(), eff->GetSpellEffectInfo().TriggerSpell, base->GetCastDifficulty(), u); + due += per_tick * ticks; + } + } + return int32(std::min(due, std::numeric_limits::max())); +} + // Single-walk filler for both tracked raid buffs and harmful debuffs on // `u`. Replaces a prior two-pass design that walked GetAppliedAuras // twice; at 40-member raids × N grouped bots × snapshot cadence this @@ -447,6 +512,8 @@ std::shared_ptr GroupSnapshotBuilder::Build(Player* p, Snap } } CopyMemberAuras(mp, m.buffs, m.debuffs); + if (Map const* mm = mp->GetMap(); mm && mm->IsDungeon() && !mm->IsRaid()) + m.aura_damage_due = AuraDamageDue(mp, Combat::ClassicHeal::kAuraDueHorizonMs); for (size_t i = 0; i < sizeof(kGroupClassBuffSpells) / sizeof(kGroupClassBuffSpells[0]); ++i) if (mp->HasSpell(kGroupClassBuffSpells[i])) m.known_class_buffs |= uint8(1u << i); diff --git a/src/modules/PlayerbotV2/PlayerbotV2.cpp b/src/modules/PlayerbotV2/PlayerbotV2.cpp index 946fc0fe4b..6e15038b23 100644 --- a/src/modules/PlayerbotV2/PlayerbotV2.cpp +++ b/src/modules/PlayerbotV2/PlayerbotV2.cpp @@ -919,6 +919,16 @@ void Module::Init() TC_LOG_ERROR("server.loading", "[PlayerbotV2] Schema migration failed; module disabled."); return; } + // The newest migration this build's queries need. run_all applies the files it finds in sql/playerbot_v2/ under the + // SourceDirectory; a deploy whose folder lacks a newer file would start with an old schema, and every bot login would fail on + // the missing column. Say so once, here, and stay off. + constexpr uint32 kRequiredCharactersMigration = 60; // 0060_companion_owner_orders.sql: playerbot_v2_character.owner_orders + if (!migrations.applied_versions(MigrationTarget::Characters).contains(kRequiredCharactersMigration)) + { + TC_LOG_ERROR("server.loading", "[PlayerbotV2] Bot migration {} is not applied: sql/playerbot_v2/ under SourceDirectory is older " + "than this worldserver. Copy the new sql/playerbot_v2/ folder and restart; module disabled.", kRequiredCharactersMigration); + return; + } // The bots' speech lines (shared DB, migration 0019). Loaded before any bot can tick; read-only // afterwards, so bot workers and the world thread read it without a lock. @@ -3698,8 +3708,8 @@ void Module::OnPlayerLogin(Player* p) // archetype). Previously each ran its own SELECT of the same row - // three sync round trips per bot, ~120 when 40 companions log in // together. Stays synchronous: formation state has no not-loaded gate. - // Columns: [0..3] squad state (OwnerRegistry::kSquadStateColumns order), - // [4..8] leveling target, [9] archetype_id. No row -> the same defaults + // Columns: [0..4] squad state (OwnerRegistry::kSquadStateColumns order, kSquadStateFieldCount), + // then 5 leveling target columns, then archetype_id. No row -> the same defaults // each consumer used when its own read came back empty. SLOW_CALL("bot login row read (database)"); QueryResult const row = CharacterDatabase.PQuery( @@ -3716,6 +3726,13 @@ void Module::OnPlayerLogin(Player* p) ai->set_formation_slot(s.formation_slot); ai->set_follow_distance(s.follow_distance); ai->set_verbose_logging(s.owner_verbose); + // The standing orders are an owner's: a bot with none (a world bot that once was a companion) logs in without them. + uint8 const orders = Services::Owners().GetOwner(id).account_id != 0 ? s.owner_orders : uint8(0); + ai->set_loot_all((orders & OwnerRegistry::kOwnerOrderLootAll) != 0); + ai->set_gather_ordered((orders & OwnerRegistry::kOwnerOrderGather) != 0); + if (orders) + TC_LOG_INFO("playerbot.v2", "[owner_orders] {} back with its stored orders: loot all {}, gather {}", p->GetName(), + ai->loot_all() ? "on" : "off", ai->gather_ordered() ? "on" : "off"); // The role the owner gave a companion lives in the bot logic and the Classic virtual spec, both memory only: pin it // again so a relog (or a restart) does not hand the bot's role back to a talent inference. @@ -3732,7 +3749,7 @@ void Module::OnPlayerLogin(Player* p) // builder won't clobber a persisted choice. hub_id 0 = never picked. if (rf) { - Field const* const f = rf + 4; + Field const* const f = rf + OwnerRegistry::kSquadStateFieldCount; BotAI::LevelingZoneTarget t; t.hub_id = f[0].GetUInt32(); t.map_id = f[1].GetUInt32(); @@ -3762,7 +3779,7 @@ void Module::OnPlayerLogin(Player* p) ai->set_archetype(rolled); bool need_write = true; - if (rf && rf[9].GetUInt8() == rolled.archetype_id) + if (rf && rf[OwnerRegistry::kSquadStateFieldCount + 5].GetUInt8() == rolled.archetype_id) need_write = false; if (need_write) CharacterDatabase.PExecute( @@ -5066,8 +5083,13 @@ void Module::OnBGInvitationReceived(Player* player, uint32 bg_instance_id, uint3 bool const is_bot = player->GetSession() && player->GetSession()->IsBot(); if (!is_bot) { - std::lock_guard lk(pending_bg_ports_mtx_); - ++bg_invite_state_[bg_instance_id].expected_humans; + { + std::lock_guard lk(pending_bg_ports_mtx_); + // The ~20 s reminder fires this hook again for the same invite: count the human once. + std::vector& humans = bg_invite_state_[bg_instance_id].invited_humans; + if (std::find(humans.begin(), humans.end(), player->GetGUID()) == humans.end()) + humans.push_back(player->GetGUID()); + } return; } @@ -5131,8 +5153,25 @@ void Module::FireDueBgPorts() } auto state_it = bg_invite_state_.find(it->bg_instance_id); + // A human counts while the invite is open or the human is inside. One who declined, let the invite run out or logged + // off is dropped: before, the count never went down, so the bots waited for nobody and the instance sat in + // preparation with every place invited (Nick-A 11-24, bgfill-1124 on af69i). + if (state_it != bg_invite_state_.end() && !state_it->second.invited_humans.empty()) + { + uint32 const inst = it->bg_instance_id; + auto& humans = state_it->second.invited_humans; + size_t const before = humans.size(); + std::erase_if(humans, [inst](ObjectGuid const& g) + { + Player const* h = ObjectAccessor::FindConnectedPlayer(g); + return !h || !(h->IsInvitedForBattlegroundInstance(inst) || (h->InBattleground() && h->GetBattlegroundId() == inst)); + }); + if (humans.empty() && before) + TC_LOG_INFO("playerbot.v2", "[bg_port] bg_inst={}: the invited player(s) did not come in (declined, invite ran out or " + "logged off): the bots go in", inst); + } uint32 const expected_humans = (state_it != bg_invite_state_.end()) - ? state_it->second.expected_humans : 0u; + ? uint32(state_it->second.invited_humans.size()) : 0u; bool human_in_bg = (state_it != bg_invite_state_.end()) ? state_it->second.any_human_seen : false; diff --git a/src/modules/PlayerbotV2/PlayerbotV2.h b/src/modules/PlayerbotV2/PlayerbotV2.h index 5cb44ffc93..505f1cdea1 100644 --- a/src/modules/PlayerbotV2/PlayerbotV2.h +++ b/src/modules/PlayerbotV2/PlayerbotV2.h @@ -227,6 +227,9 @@ private: // instance, then fire bots staggered 0-1500ms. // - Hard expiry: drop the deferred entry if invite age > 80s (TC's // 90s INVITE_ACCEPT_WAIT_TIME minus a 10s safety margin). + // - A human counts only while the invite is still open (or the human is inside): one who declines or lets it run out + // no longer holds the bots, or the instance stays in preparation with every place invited and nobody inside + // (Nick-A 11-24, bgfill-1124 on af69i: WSG 0/10 v 0/10 with 10/10 invited for minutes). struct PendingBgPort { uint32 created_at_ms; uint32 bg_instance_id; @@ -237,7 +240,7 @@ private: std::vector pending_bg_ports_; // Per-instance invite-state for human-first gating. Keyed by bg_instance_id. struct BgInviteState { - uint32 expected_humans = 0; + std::vector invited_humans; // humans invited to this instance; FireDueBgPorts drops the lapsed ones bool any_human_seen = false; // sticky once a human is detected in-bg }; std::unordered_map bg_invite_state_; diff --git a/src/modules/PlayerbotV2/Session/BotSession.cpp b/src/modules/PlayerbotV2/Session/BotSession.cpp index 49036649d5..2274193cce 100644 --- a/src/modules/PlayerbotV2/Session/BotSession.cpp +++ b/src/modules/PlayerbotV2/Session/BotSession.cpp @@ -3,6 +3,8 @@ #include "LoginQueryHolder.h" #include "Log.h" #include "Group.h" +#include "Item.h" +#include "Loot.h" #include "Player.h" #include "WorldPacket.h" #include "WorldSocket.h" @@ -46,6 +48,51 @@ uint32 ResolveBnetAccountId(uint32 gameAccountId) cache[gameAccountId] = bnet; return bnet; } + +// A headless bot has no client to take the result of its own Disenchanting, Prospecting or Milling and close the loot window. The window +// stayed open on the item for ever; the bot then cast the same spell on the same item again, which replaced the loot and (through the +// release of the old one) destroyed the item under the running spell. Do what the client does for these: take what fits, close the window. +void CloseItemLootWindows(Player* p) +{ + std::vector lootGuids; + for (auto const& [lootGuid, loot] : p->GetAELootView()) + if (loot->GetOwnerGUID().IsItem() && + (loot->loot_type == LOOT_DISENCHANTING || loot->loot_type == LOOT_PROSPECTING || loot->loot_type == LOOT_MILLING)) + lootGuids.push_back(lootGuid); + + for (ObjectGuid const& lootGuid : lootGuids) + { + auto const& view = p->GetAELootView(); + auto itr = view.find(lootGuid); + if (itr == view.end()) + continue; + Loot* loot = itr->second; + + ObjectGuid const owner = loot->GetOwnerGUID(); + for (uint8 slot = 0; slot < loot->items.size(); ++slot) + { + NotNormalLootItem* ffaItem = nullptr; + LootItem* it = loot->LootItemInSlot(slot, p, &ffaItem); + if (!it || it->is_looted || it->is_blocked) + continue; + if (ffaItem && ffaItem->is_looted) + continue; + ItemPosCountVec dest; + if (p->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, it->itemid, it->count) != EQUIP_ERR_OK) + continue; + p->StoreLootItem(owner, slot, loot); + } + if (loot->gold > 0) + { + p->ModifyMoney(loot->gold); + loot->gold = 0; + } + + // The release destroys the item and may free the loot: nothing below reads it. + if (WorldSession* sess = p->GetSession()) + sess->DoLootRelease(loot); + } +} } // namespace BotSession::BotSession(uint32 accountId, std::string name) @@ -159,6 +206,9 @@ bool BotSession::Update(uint32 /*diff*/, PacketFilter& updater) // login + any deferred work) and return true. ProcessQueryCallbacks(); + if (_player && _player->IsInWorld() && !m_playerLogout && !forceExit && !_player->GetAELootView().empty()) + CloseItemLootWindows(_player); + // Sign guild charters players offered to this bot (see SendPacket). if (!_offeredCharters.empty()) { diff --git a/src/modules/PlayerbotV2/Session/LazyKey.cpp b/src/modules/PlayerbotV2/Session/LazyKey.cpp new file mode 100644 index 0000000000..c9be282271 --- /dev/null +++ b/src/modules/PlayerbotV2/Session/LazyKey.cpp @@ -0,0 +1,304 @@ +// One-button rotation for every class but the warlock: gathers the facts for LazyKey::Pick (Combat/LazyKey.h) from the live Player and +// casts the answer through the bot API (highest known rank, range / facing / stun / silence gates). World thread only (the command and +// add-on handlers run there). +// +// A spell the server refuses (no mana, no proc, wrong stance or weapon) is taken out of the choice for a few seconds and the press picks +// again, so a missing proc or resource never holds the rotation back. A cast that costs no global cooldown (Heroic Strike, Maul, trinket-like +// cooldowns, Auto Shot) is followed by the next pick in the same press. Melee classes start their swing and the pet joins the fight. + +#include "LazyKey.h" + +#include "Api/ClassicSpec.h" +#include "Bot/ClassTables.h" +#include "Combat/LazyKey.h" +#include "Creature.h" +#include "DB2Stores.h" +#include "GameTime.h" +#include "Group.h" +#include "Item.h" +#include "ItemTemplate.h" +#include "Log.h" +#include "Map.h" +#include "Pet.h" +#include "PlayerbotAPI.h" +#include "Player.h" +#include "SharedDefines.h" +#include "Spell.h" +#include "SpellAuraDefines.h" +#include "SpellInfo.h" +#include "SpellMgr.h" +#include "World.h" + +#include + +namespace Playerbot { + +namespace { + +constexpr float kSpellRange = 30.0f; +constexpr float kShotRange = 35.0f; // Auto Shot / Hunter shots +constexpr float kHealRange = 40.0f; +constexpr float kCloseRange = 8.0f; // an enemy this near is on the player +constexpr uint32 kBlockMs = 3000; // how long a refused spell stays out of the choice +constexpr int kMaxPicks = 6; + +int32 Pct(int64 value, int64 max) { return max > 0 ? int32(value * 100 / max) : 100; } + +// Power in the units the client shows (TC keeps rage x10): the rules compare against "15 rage". +int32 DisplayPower(Player const* p, Powers power) +{ + int32 raw = p->GetPower(power); + if (PowerTypeEntry const* pt = sDB2Manager.GetPowerTypeEntry(power)) + if (pt->DisplayModifier > 1) + raw /= pt->DisplayModifier; + return raw; +} + +// Per player: spell id -> game time (ms) until which the spell is left out. +std::unordered_map> s_blocked; + +char const* SpellText(uint32 id) +{ + SpellInfo const* info = sSpellMgr->GetSpellInfo(id, DIFFICULTY_NONE); + char const* name = info && info->SpellName ? (*info->SpellName)[sWorld->GetDefaultDbcLocale()] : nullptr; + return name && *name ? name : "spell"; +} + +LazyKey::Form FormOf(Player const* p) +{ + using LazyKey::Form; + switch (p->GetShapeshiftForm()) + { + case FORM_BEAR_FORM: + case FORM_DIRE_BEAR_FORM: return Form::Bear; + case FORM_CAT_FORM: return Form::Cat; + case FORM_MOONKIN_FORM: return Form::Moonkin; + case FORM_BATTLE_STANCE: return Form::Battle; + case FORM_DEFENSIVE_STANCE: return Form::Defensive; + case FORM_BERSERKER_STANCE: return Form::Berserker; + case FORM_SHADOWFORM: return Form::Shadow; + case FORM_STEALTH: return Form::Stealth; + default: return Form::None; + } +} + +LazyKey::Role RoleOf(Player const* p, std::string const& arg, uint32 spec) +{ + using LazyKey::Role; + if (arg == "tank") + return Role::Tank; + if (arg == "heal" || arg == "healer") + return Role::Heal; + if (arg == "dps" || arg == "damage") + return Role::Dps; + uint8 const cls = p->GetClass(); + if (IsTankSpec(cls, uint16(spec))) + return Role::Tank; + if (IsHealerSpec(cls, uint16(spec))) + return Role::Heal; + return Role::Dps; +} + +bool HasWand(Player const* p) +{ + Item const* ranged = p->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED); + ItemTemplate const* tmpl = ranged ? ranged->GetTemplate() : nullptr; + return tmpl && tmpl->GetClass() == ITEM_CLASS_WEAPON && tmpl->GetSubClass() == ITEM_SUBCLASS_WEAPON_WAND; +} + +bool MainHandImbued(Player const* p) +{ + Item const* mh = p->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND); + return mh && mh->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT) != 0; +} + +} // namespace + +std::string LazyKeyPress(Player* p, std::string const& roleArg) +{ + if (!p || !p->IsAlive() || !p->GetMap()) + return {}; + uint8 const cls = p->GetClass(); + std::vector const& spells = LazyKey::Spells(cls); + if (spells.empty()) + return "Lazy key: there is no rotation for your class."; + + API api(p); + + Unit* target = p->GetSelectedUnit(); + bool const valid_target = target && target->IsAlive() && p->IsValidAttackTarget(target); + + uint32 const spec = ::Playerbot::Classic::EffectiveSpecId(p); + LazyKey::Input in; + in.cls = cls; + in.role = RoleOf(p, roleArg, spec); + in.form = FormOf(p); + in.tree = LazyKey::TreeOfSpec(cls, spec); + + // The heal target: the most hurt friendly player in reach, the player included. + Player const* healee = nullptr; + int32 lowest = 101; + auto consider = [&](Player const* m) + { + if (!m || !m->IsAlive() || m->GetMap() != p->GetMap()) + return; + if (m != p && (p->GetDistance(m) > kHealRange || !p->IsWithinLOSInMap(m) || !p->IsValidAssistTarget(m))) + return; + int32 const pct = Pct(m->GetHealth(), m->GetMaxHealth()); + if (pct < 75) + ++in.hurt_count; + if (pct < lowest) + { + lowest = pct; + healee = m; + } + }; + consider(p); + if (Group const* g = p->GetGroup()) + for (GroupReference const& ref : g->GetMembers()) + if (Player const* m = ref.GetSource(); m && m != p) + consider(m); + + for (uint32 id : spells) + { + uint32 const rank = api.highest_known_rank(id); + if (p->HasSpell(rank)) + in.known.push_back(id); + if (api.cast_ready_in_ms(id) == 0) + in.ready.push_back(id); + if (p->HasAura(rank)) + in.on_self.push_back(id); + if (valid_target && target->HasAura(rank, p->GetGUID())) + in.on_target.push_back(id); + if (healee && healee->HasAura(rank, p->GetGUID())) + in.on_healee.push_back(id); + } + if (p->HasAura(LazyKey::Id::WeakenedSoul)) + in.on_self.push_back(LazyKey::Id::WeakenedSoul); + if (healee && healee->HasAura(LazyKey::Id::WeakenedSoul)) + in.on_healee.push_back(LazyKey::Id::WeakenedSoul); + + in.has_healee = healee != nullptr; + in.healee_is_self = healee == p; + in.healee_hp_pct = healee ? lowest : 100; + + in.casting = p->IsNonMeleeSpellCast(false, false, true); + in.in_combat = p->IsInCombat(); + in.has_target = valid_target; + in.stealthed = p->HasStealthAura(); + in.auto_shooting = p->GetCurrentSpell(CURRENT_AUTOREPEAT_SPELL) != nullptr; + in.wand = HasWand(p); + in.has_pet = p->GetPet() && p->GetPet()->IsAlive(); + in.weapon_imbued = MainHandImbued(p); + in.level = int32(p->GetLevel()); + in.hp_pct = Pct(p->GetHealth(), p->GetMaxHealth()); + in.mana_pct = Pct(p->GetPower(POWER_MANA), p->GetMaxPower(POWER_MANA)); + in.rage = DisplayPower(p, POWER_RAGE); + in.energy = DisplayPower(p, POWER_ENERGY); + in.combo = p->GetPower(POWER_COMBO_POINTS); + + if (valid_target) + { + Creature const* c = target->ToCreature(); + float const dist = p->GetDistance(target); + in.target_in_melee = p->IsWithinMeleeRange(target); + in.target_in_range = dist <= (cls == CLASS_HUNTER ? kShotRange : kSpellRange); + in.target_behind = target->isInBackInMap(p, kCloseRange); + in.target_casting = target->IsNonMeleeSpellCast(false, false, true); + in.target_boss = (c && (c->IsDungeonBoss() || c->isWorldBoss())) || target->GetMaxHealth() >= 100000; + in.target_player = target->IsPlayer(); + in.target_on_me = target->GetVictim() == p; + in.target_attacking = target->GetVictim() != nullptr; + in.target_undead_or_demon = (target->GetCreatureTypeMask() & CREATURE_TYPEMASK_DEMON_OR_UNDEAD) != 0; + in.target_hp_pct = Pct(target->GetHealth(), target->GetMaxHealth()); + for (Unit const* attacker : p->getAttackers()) + if (attacker->IsAlive() && p->GetDistance(attacker) <= kCloseRange) + ++in.attackers_close; + + // Melee swing and the pet join the fight; neither costs a global cooldown. + if (LazyKey::WantsAutoAttack(in) && in.target_in_melee && p->GetVictim() != target) + api.start_attack(target->GetGUID()); + Pet* pet = p->GetPet(); + if (pet && pet->IsAlive() && p->IsInCombat() && pet->GetVictim() != target) + api.pet_attack(target->GetGUID()); + } + else + { + for (Unit const* attacker : p->getAttackers()) + if (attacker->IsAlive() && p->GetDistance(attacker) <= kCloseRange) + ++in.attackers_close; + } + + uint32 const now = GameTime::GetGameTimeMS(); + std::unordered_map& blocked_until = s_blocked[p->GetGUID().GetCounter()]; + + std::string refused; + for (int attempt = 0; attempt < kMaxPicks; ++attempt) + { + in.blocked.clear(); + for (auto const& [id, until] : blocked_until) + if (until > now) + in.blocked.push_back(id); + + LazyKey::Choice const pick = LazyKey::Pick(in); + if (pick.cancel_form) + { + // A druid healing out of a form: leave it (no global cooldown) and pick the heal. + p->RemoveAurasByType(SPELL_AURA_MOD_SHAPESHIFT); + in.form = LazyKey::Form::None; + continue; + } + if (!pick.spell) + { + TC_LOG_DEBUG("playerbot.v2", "[lazykey] {}: nothing ({}) hp={} mana={} rage={} energy={} combo={} target_hp={}", p->GetName(), pick.why, + in.hp_pct, in.mana_pct, in.rage, in.energy, in.combo, in.target_hp_pct); + return refused; + } + + ObjectGuid cast_at; + switch (pick.at) + { + case LazyKey::At::Target: + cast_at = valid_target ? target->GetGUID() : ObjectGuid::Empty; + break; + case LazyKey::At::Healee: + cast_at = healee ? healee->GetGUID() : p->GetGUID(); + break; + case LazyKey::At::Self: + { + // A spell that needs a unit (a heal, a shield) goes on the player; the rest (stances, auras, area spells) takes none. + SpellInfo const* info = sSpellMgr->GetSpellInfo(pick.spell, DIFFICULTY_NONE); + cast_at = info && info->NeedsExplicitUnitTarget() ? p->GetGUID() : ObjectGuid::Empty; + break; + } + } + Result const r = api.cast_spell(pick.spell, cast_at); + TC_LOG_INFO("playerbot.v2", "[lazykey] {}: {} ({}) -> {} role={} tree={} hp={} mana={} rage={} energy={} combo={} target_hp={} healee_hp={}", + p->GetName(), SpellText(api.highest_known_rank(pick.spell)), pick.why, uint32(r), uint32(in.role), in.tree, in.hp_pct, + in.mana_pct, in.rage, in.energy, in.combo, in.target_hp_pct, in.healee_hp_pct); + if (r == Result::Ok && LazyKey::OffGlobalCooldown(pick.spell)) + { + // No global cooldown spent: the same press goes on to the next spell. + in.ready.erase(std::remove(in.ready.begin(), in.ready.end(), pick.spell), in.ready.end()); + continue; + } + switch (r) + { + case Result::Ok: + case Result::NotReady: + case Result::Locked: + case Result::OutOfRange: + return refused; + default: + // Refused (no mana, no proc, wrong stance or weapon...): leave it out for a few seconds and pick the next step. + blocked_until[pick.spell] = now + kBlockMs; + if (r == Result::NotEnoughResource && cls != CLASS_WARRIOR && cls != CLASS_ROGUE + && in.form != LazyKey::Form::Bear && in.form != LazyKey::Form::Cat) + refused = "Lazy key: out of mana or reagents for " + std::string(SpellText(api.highest_known_rank(pick.spell))) + ", skipping it."; + break; + } + } + return refused; +} + +} // namespace Playerbot diff --git a/src/modules/PlayerbotV2/Session/LazyKey.h b/src/modules/PlayerbotV2/Session/LazyKey.h new file mode 100644 index 0000000000..57fed443c4 --- /dev/null +++ b/src/modules/PlayerbotV2/Session/LazyKey.h @@ -0,0 +1,16 @@ +// One-button rotation for every class but the warlock: `.playerbot lazy [dps|tank|heal]` (the add-on's "Lazy key") casts the next spell +// of the player's class and role. The warlock keeps its own rotation (Session/LazyLock.h). +#pragma once + +#include "Define.h" +#include + +class Player; + +namespace Playerbot { + +// One press. `role` is "dps", "tank" or "heal" to override the role of the player's spec, empty for the spec's. Returns the text to show +// the player when the press failed in a way worth telling (empty when it cast, or when nothing was ready and the next press will try again). +std::string LazyKeyPress(Player* player, std::string const& role); + +} // namespace Playerbot diff --git a/src/modules/PlayerbotV2/Travel/TownNpcIndex.cpp b/src/modules/PlayerbotV2/Travel/TownNpcIndex.cpp index 2f8fd41597..9d56fae6b0 100644 --- a/src/modules/PlayerbotV2/Travel/TownNpcIndex.cpp +++ b/src/modules/PlayerbotV2/Travel/TownNpcIndex.cpp @@ -1,5 +1,6 @@ #include "TownNpcIndex.h" +#include "Bot/TownErrand.h" #include "CreatureData.h" #include "GameObjectData.h" #include "DB2Stores.h" @@ -9,12 +10,15 @@ #include "SpawnData.h" #include "UnitDefines.h" +#include #include #include #include namespace Playerbot::V2::Travel { +namespace TE = ::Playerbot::V2::TownErrand; + namespace { // Vanilla service NPCs only. Account/guild bankers, transmogrifiers, void @@ -39,6 +43,16 @@ bool Hostile(FactionTemplateEntry const* npc, FactionTemplateEntry const* player return npc->IsHostileTo(player) || player->IsHostileTo(npc); } +// The DBC name of a spell-focus type ("Anvil", "Cooking Fire", ...), or "" for +// an id the client's SpellFocusObject table does not carry. +char const* FocusName(uint32 focus_type) +{ + if (SpellFocusObjectEntry const* e = sSpellFocusObjectStore.LookupEntry(focus_type)) + if (char const* n = e->Name[LOCALE_enUS]) + return n; + return ""; +} + } // namespace TownNpcIndex& TownNpcIndex::Instance() @@ -85,6 +99,7 @@ void TownNpcIndex::Initialize() n.z = data.spawnPoint.GetPositionZ(); n.npc_flags = flags; n.trainer_class = uint8(tmpl->trainer_class); + n.orientation = data.spawnPoint.GetOrientation(); n.alliance_ok = ft && !Hostile(ft, alliance); n.horde_ok = ft && !Hostile(ft, horde); if (!n.alliance_ok && !n.horde_ok) @@ -100,6 +115,7 @@ void TownNpcIndex::Initialize() } size_t mailboxes = 0; + std::array focus_counts{}; // forge, cookfire, loom, moonwell — for the boot log for (auto const& [spawnId, data] : sObjectMgr->GetAllGameObjectData()) { MapEntry const* map = sMapStore.LookupEntry(data.mapId); @@ -108,7 +124,30 @@ void TownNpcIndex::Initialize() if (data.spawnGroupData && (data.spawnGroupData->flags & SPAWNGROUP_FLAG_MANUAL_SPAWN)) continue; GameObjectTemplate const* tmpl = sObjectMgr->GetGameObjectTemplate(data.id); - if (!tmpl || tmpl->type != GAMEOBJECT_TYPE_MAILBOX) + if (!tmpl) + continue; + if (tmpl->type == GAMEOBJECT_TYPE_MAILBOX) + { + TownNpc n; + n.spawn_id = spawnId; + n.entry = data.id; + n.map_id = data.mapId; + n.x = data.spawnPoint.GetPositionX(); + n.y = data.spawnPoint.GetPositionY(); + n.z = data.spawnPoint.GetPositionZ(); + n.alliance_ok = n.horde_ok = true; + _mail[n.map_id].push_back(n); + ++mailboxes; + continue; + } + // A craft station: any gameobject carrying a spell focus (anvils, + // forges, cooking fires, looms, moonwells). GetSpellFocusType also + // covers UI_LINK objects that carry one. + uint32 const focus_type = tmpl->GetSpellFocusType(); + if (!focus_type) + continue; + TE::Kind const fk = TE::KindForFocusName(FocusName(focus_type)); + if (fk == TE::Kind::None) continue; TownNpc n; n.spawn_id = spawnId; @@ -117,13 +156,21 @@ void TownNpcIndex::Initialize() n.x = data.spawnPoint.GetPositionX(); n.y = data.spawnPoint.GetPositionY(); n.z = data.spawnPoint.GetPositionZ(); + n.focus_type = focus_type; + n.focus_kind = uint8(fk); n.alliance_ok = n.horde_ok = true; - _mail[n.map_id].push_back(n); - ++mailboxes; + _focus[n.map_id].push_back(n); + if (fk == TE::Kind::Forge) ++focus_counts[0]; + if (fk == TE::Kind::Cookfire) ++focus_counts[1]; + if (fk == TE::Kind::Loom) ++focus_counts[2]; + if (fk == TE::Kind::Moonwell) ++focus_counts[3]; } _initialized.store(true, std::memory_order_release); TC_LOG_INFO("playerbot.v2", "[TownNpcIndex] {} mailbox objects.", mailboxes); + TC_LOG_INFO("playerbot.v2", "[TownNpcIndex] {} craft stations (forge {}, cookfire {}, loom {}, moonwell {}).", + focus_counts[0] + focus_counts[1] + focus_counts[2] + focus_counts[3], + focus_counts[0], focus_counts[1], focus_counts[2], focus_counts[3]); TC_LOG_INFO("playerbot.v2", "[TownNpcIndex] {} service NPC spawns on {} open-world maps in {} ms.", _count, _maps.size(), std::chrono::duration_cast(std::chrono::steady_clock::now() - t0).count()); @@ -237,6 +284,23 @@ void TownNpcIndex::ForEachMailboxNear(uint32 map, float x, float y, float radius } } +void TownNpcIndex::ForEachFocusNear(uint32 map, float x, float y, float radius, + std::function const& fn) const +{ + if (!_initialized.load(std::memory_order_acquire)) + return; + auto it = _focus.find(map); + if (it == _focus.end()) + return; + const float r2 = radius * radius; + for (TownNpc const& n : it->second) + { + const float dx = n.x - x, dy = n.y - y; + if (dx * dx + dy * dy <= r2) + fn(n); + } +} + bool TownNpcIndex::AuctioneerNear(uint32 map, float x, float y, float radius) const { bool found = false; diff --git a/src/modules/PlayerbotV2/Travel/TownNpcIndex.h b/src/modules/PlayerbotV2/Travel/TownNpcIndex.h index f626e7136e..0282f7e783 100644 --- a/src/modules/PlayerbotV2/Travel/TownNpcIndex.h +++ b/src/modules/PlayerbotV2/Travel/TownNpcIndex.h @@ -41,6 +41,15 @@ struct TownNpc uint8 trainer_class = 0; // creature_template.trainer_class (class trainers) bool alliance_ok = false; bool horde_ok = false; + // Gameobject craft stations (the _focus index) only: the SpellFocusObject id + // the object carries (anvil, forge, cooking fire, loom, moonwell) and its + // TownErrand::Kind as uint8 (0 = not a station we use). Plain NPC spawns + // and mailboxes leave both 0. + uint32 focus_type = 0; + uint8 focus_kind = 0; + // The way the spawn faces (creature spawns only, -1 = none): its customer side — a banker faces the queue, + // an auctioneer the hall. Stand points fan out on that side, never behind the counter. + float orientation = -1.f; bool usable_by(bool alliance) const { return alliance ? alliance_ok : horde_ok; } }; @@ -76,6 +85,13 @@ public: void ForEachMailboxNear(uint32 map, float x, float y, float radius, std::function const& fn) const; + // Calls fn for every craft-station object (a gameobject carrying a spell + // focus: anvils, forges, cooking fires, looms, moonwells) on `map` within + // `radius` (2D) of (x,y). Like mailboxes they are kept apart from the + // service NPCs so they never count as a town's NPCs. + void ForEachFocusNear(uint32 map, float x, float y, float radius, + std::function const& fn) const; + // True when any auctioneer spawn (either side) stands within `radius`. // Cheap gate for the snapshot builder's auction-house scan. bool AuctioneerNear(uint32 map, float x, float y, float radius) const; @@ -92,6 +108,7 @@ private: std::unordered_map _maps; std::unordered_map> _mail; // map -> mailbox object spawns + std::unordered_map> _focus; // map -> craft-station object spawns size_t _count = 0; std::atomic _initialized{false}; }; diff --git a/src/modules/PlayerbotV2/Util/BotLocaleRu.cpp b/src/modules/PlayerbotV2/Util/BotLocaleRu.cpp index a5965ec883..0b305bfee7 100644 --- a/src/modules/PlayerbotV2/Util/BotLocaleRu.cpp +++ b/src/modules/PlayerbotV2/Util/BotLocaleRu.cpp @@ -524,6 +524,11 @@ std::vector const& RussianEntries() { "Modes: match, best, bis, t1, t2, t3.", "Варианты: match, best, bis, t1, t2, t3." }, { "Regeared {#} companion(s).", "Переодето спутников: {}." }, { "{}: {#} slot(s) regeared.", "{}: переодето ячеек: {}." }, + { "{}: {#} slot(s) regeared. Gear {} starts at level {#}; below that it wears gear for its level (match).", + "{}: переодето ячеек: {}. Экипировка {} начинается с {}-го уровня; до него спутник носит экипировку по своему уровню (match)." }, + { "gear mode {}", "экипировка спутников: {}" }, + { "gear mode {} (this applies at level {#}; below that: match)", + "экипировка спутников: {} (действует с {}-го уровня; до него: match)" }, { "{} is a player's own character; its gear is left alone.", "{} — собственный персонаж игрока; его экипировку не трогаю." }, { "{} is in combat or dead, try again later.", "{}: в бою или мертв(а), попробуйте позже." }, { "{} is offline: `.bot call {}` first.", "{} не в сети: сначала `.bot call {}`." }, @@ -745,8 +750,8 @@ std::vector const& RussianEntries() { "None of your bots in the group is a tank: add one (.bot add warrior tank), then say 'lead on'.", "Ни один из ваших ботов в группе не танк: добавьте танка (.bot add warrior tank), затем скажите 'lead on'." }, { "Your tank does not lead now: say 'lead on' first.", "Ваш танк сейчас не ведет: сначала скажите 'lead on'." }, - { "{} leads the dungeon now: it pulls pack by pack and waits for mana and for you. Say 'lead pause' to hold, 'lead off' to lead yourself.", - "{} ведет группу по подземелью: пулит по одной группе мобов и ждет ману и вас. Скажите 'lead pause', чтобы он ждал, 'lead off', чтобы вести самому." }, + { "{} leads the dungeon now: it pulls pack by pack and waits for you, and before a boss for a healer low on mana. Say 'lead pause' to hold, 'lead off' to lead yourself.", + "{} ведет группу по подземелью: пулит по одной группе мобов и ждет вас, а перед боссом и лекаря, если у него мало маны. Скажите 'lead pause', чтобы он ждал, 'lead off', чтобы вести самому." }, { "{} leads once you are inside a dungeon or a raid. Say 'lead off' to lead yourself.", "{} поведет группу, когда вы войдете в подземелье или рейд. Скажите 'lead off', чтобы вести самому." }, { "{} holds here and pulls nothing until you say 'go'.", "{} ждет здесь и никого не пулит, пока вы не скажете 'go'." }, diff --git a/src/modules/PlayerbotV2/Util/ConfigReader.cpp b/src/modules/PlayerbotV2/Util/ConfigReader.cpp index bd99ae749a..8828a452a6 100644 --- a/src/modules/PlayerbotV2/Util/ConfigReader.cpp +++ b/src/modules/PlayerbotV2/Util/ConfigReader.cpp @@ -215,6 +215,8 @@ void ConfigReader::apply_from_loaded_config() c.GetIntDefault("PlayerbotV2.Threat.OpeningWaitBossMs", 6000, true)); threat_opening_wait_trash_ms_ = static_cast( c.GetIntDefault("PlayerbotV2.Threat.OpeningWaitTrashMs", 2000, true)); + threat_party_pull_delay_ms_ = static_cast( + std::clamp(c.GetIntDefault("PlayerbotV2.Threat.PartyPullDelayMs", 2000, true), 0, 4000)); bhv_owner_follow_hold_ = c.GetBoolDefault("Playerbot.Behavior.OwnerFollowHold", true, true); bhv_fallback_ = c.GetBoolDefault("Playerbot.Behavior.Fallback", true, true); diff --git a/src/modules/PlayerbotV2/Util/ConfigReader.h b/src/modules/PlayerbotV2/Util/ConfigReader.h index 4c2107b656..50329d37e8 100644 --- a/src/modules/PlayerbotV2/Util/ConfigReader.h +++ b/src/modules/PlayerbotV2/Util/ConfigReader.h @@ -341,6 +341,8 @@ public: float threat_opening_lead_trash() const { return threat_opening_lead_trash_; } uint32 threat_opening_wait_boss_ms() const { return threat_opening_wait_boss_ms_; } uint32 threat_opening_wait_trash_ms() const{ return threat_opening_wait_trash_ms_; } + // PlayerbotV2.Threat.PartyPullDelayMs: in a player-led group's fight the damage dealers open this long after it began (0: at once). + uint32 threat_party_pull_delay_ms() const { return threat_party_pull_delay_ms_; } // Behaviour switches (Playerbot.Behavior., default on = current behaviour). Each gate // makes its behaviour fall back to the previous simple path. Cached at load, so they are @@ -702,6 +704,7 @@ private: float threat_opening_lead_trash_ = 250.0f; uint32 threat_opening_wait_boss_ms_ = 6000; uint32 threat_opening_wait_trash_ms_ = 2000; + uint32 threat_party_pull_delay_ms_ = 2000; bool bhv_owner_follow_hold_ = true; bool bhv_fallback_ = true; diff --git a/src/modules/PlayerbotV2/conf/playerbot.conf.dist b/src/modules/PlayerbotV2/conf/playerbot.conf.dist index 1d70e6ab6d..1a5273591a 100644 --- a/src/modules/PlayerbotV2/conf/playerbot.conf.dist +++ b/src/modules/PlayerbotV2/conf/playerbot.conf.dist @@ -371,7 +371,8 @@ Playerbot.World.IdleSwapCooldownSec = 180 Playerbot.World.TownLife = 1 # Town errands: a capital's residents run from place to place across the city (the auction house, the bank, their class trainer, the -# inn, a mailbox, the flight master, a vendor, now and then the city gate), stop there LingerMinSec..LingerMaxSec facing the NPC and run +# inn, a mailbox, the flight master, a vendor, a craft station, now and then the city gate), stop there a while — LingerMinSec.. +# LingerMaxSec for a plain errand, the per-kind ranges below for the bank, the auction house and a craft station — and run # on to the next. Each walk is one pathed move, so they run smooth lines through the streets instead of short hops with a stop and a turn. # 0 = off (the old NPC-to-NPC visits within 60 yards and the random wander). Playerbot.World.Town.Errands = 1 @@ -379,6 +380,35 @@ Playerbot.World.Town.Errands = 1 Playerbot.World.Town.ErrandRadius = 300 Playerbot.World.Town.LingerMinSec = 4 Playerbot.World.Town.LingerMaxSec = 12 +# A stop at the bank or the auction house is a longer one: a player paging through bags or the auction list. +Playerbot.World.Town.LingerBankMinSec = 20 +Playerbot.World.Town.LingerBankMaxSec = 40 +Playerbot.World.Town.LingerAhMinSec = 20 +Playerbot.World.Town.LingerAhMaxSec = 40 +# Working at a craft station (anvil/forge, cooking fire, loom, moonwell) takes the longest of all. +Playerbot.World.Town.LingerCraftMinSec = 45 +Playerbot.World.Town.LingerCraftMaxSec = 90 +# 1 = a bot at a craft station really casts a recipe it knows that needs that station (and the reagents for); +# 0 = show only: it plays a looped work emote instead. +Playerbot.World.Town.CraftCast = 1 +# Sound kits pushed to nearby players on each station-work beat — the real Tradeskills kits (emote +# beats carry no audio on their own). Per station kind; 0 = silent like vanilla emote work. +Playerbot.World.Town.CraftSound.Forge = 4614 +Playerbot.World.Town.CraftSound.Cookfire = 7035 +Playerbot.World.Town.CraftSound.Loom = 6425 +Playerbot.World.Town.CraftSound.Moonwell = 0 +# The kits are one-shots: re-push period while the work emote loops, tuned so the clang lands +# on the hammer-strike frame. A fixed period, no jitter — lengthen it if the strike drifts. +Playerbot.World.Town.CraftSoundBeatMs = 1000 +# Fixture places: the bots a living city never leaves empty. While a kind's places hold fewer than its target, +# the next errand of a resident is drawn there before the usual weighted pick (bots on their way already count, +# and SpotCap still applies, so the fill cannot over-shoot and the crowd keeps rotating). 0 = no fixture for the kind. +Playerbot.World.Town.Fixture.Bank = 3 +Playerbot.World.Town.Fixture.Ah = 3 +Playerbot.World.Town.Fixture.Forge = 2 +Playerbot.World.Town.Fixture.Cookfire = 1 +Playerbot.World.Town.Fixture.Loom = 0 +Playerbot.World.Town.Fixture.Moonwell = 0 # Crowd caps: bots at one place at once (a bank, an auction house, a trainer), at one inn (resting or on an errand) and at one mailbox. # A bot that finds a place full goes somewhere else. InnCap = 0 or MailboxCap = 0 turns that show off. Playerbot.World.Town.SpotCap = 5 @@ -930,6 +960,10 @@ Playerbot.Behavior.OwnerMainTank = 1 Playerbot.Behavior.HealClaims = 1 Playerbot.Behavior.CastFacing = 1 Playerbot.Behavior.GroundSnap = 1 +# Dungeon.FinderGoodbye a dungeon finder run with a player in the group: once the last boss is dead, each bot in turn (4-24 s +# apart) says goodbye in party chat, hearths and leaves the group, like players do. A party made by hand keeps +# its bots. Default 1 (on). +Playerbot.Dungeon.FinderGoodbye = 1 Playerbot.Behavior.ReFace = 1 Playerbot.Behavior.AvoidCircles = 1 Playerbot.Behavior.PackStop = 1 @@ -1585,6 +1619,11 @@ PlayerbotV2.Threat.OpeningLeadBoss = 900 PlayerbotV2.Threat.OpeningLeadTrash = 250 PlayerbotV2.Threat.OpeningWaitBossMs = 6000 PlayerbotV2.Threat.OpeningWaitTrashMs = 2000 +# PlayerbotV2.Threat.PartyPullDelayMs in a group led by a player, damage dealer bots wait this long after the tank's pull +# (the start of the group's fight) before they open on a mob the tank holds, so the tank gets its threat first. A mob +# that hits them or another member, and the leader's Attack / focus on that mob, are answered at once. 0 = no wait. +# Limited to 0-4000 (a bot idle 5 s in its group's fight is a fault). Default 2000. +PlayerbotV2.Threat.PartyPullDelayMs = 2000 # Bot speech, carried over from the ike3 playerbot texts (shared DB table # playerbot_v2_bot_text, migration 0019). Covers greetings on joining a group, diff --git a/tests/game/ClassicBotBridge.cpp b/tests/game/ClassicBotBridge.cpp index 6aa400ac44..10cdc3f776 100644 --- a/tests/game/ClassicBotBridge.cpp +++ b/tests/game/ClassicBotBridge.cpp @@ -176,6 +176,21 @@ TEST_CASE("BotBridge: reply text becomes one safe chat line", "[BotBridge]") CHECK(cut == "При"); } +TEST_CASE("BotBridge: a speaker label a model copied from the talk goes", "[BotBridge]") +{ + std::vector const names = { "Doriando", "Beyonce" }; + CHECK(StripSpeakerLabel("Doriando: anyone up for wailing caverns", names) == "anyone up for wailing caverns"); + CHECK(StripSpeakerLabel("[Doriando ]: blablabla", names) == "blablabla"); // celguar 11-21 + CHECK(StripSpeakerLabel(" : lol ok", names) == "lol ok"); + CHECK(StripSpeakerLabel("Beyonce :", names) == "Beyonce :"); // nothing left: unchanged + CHECK(StripSpeakerLabel("note: bring water", names) == "note: bring water"); // not a speaker's name + CHECK(StripSpeakerLabel("time is 10:30", names) == "time is 10:30"); + std::vector const sp = TalkSpeakers("Doriando: hi\nBeyonce: hey there\nDoriando: sup\n"); + REQUIRE(sp.size() == 2); + CHECK(sp[0] == "Doriando"); + CHECK(sp[1] == "Beyonce"); +} + TEST_CASE("BotBridge: file names and times are UTC", "[BotBridge]") { // 2026-11-08 10:20:05 UTC diff --git a/tests/game/ClassicBotLocale.cpp b/tests/game/ClassicBotLocale.cpp index 1ae8ad0364..9cea0095d4 100644 --- a/tests/game/ClassicBotLocale.cpp +++ b/tests/game/ClassicBotLocale.cpp @@ -145,8 +145,8 @@ TEST_CASE("BotLocale: per-bot confirmations keep the bot's name", "[BotLocale]") TEST_CASE("BotLocale: the tank lead lines keep the tank's name", "[BotLocale]") { - CHECK(Translate(Lang::Ru, "Raveni leads the dungeon now: it pulls pack by pack and waits for mana and for you. Say 'lead pause' to hold, 'lead off' to lead yourself.") == - "Raveni ведет группу по подземелью: пулит по одной группе мобов и ждет ману и вас. Скажите 'lead pause', чтобы он ждал, 'lead off', чтобы вести самому."); + CHECK(Translate(Lang::Ru, "Raveni leads the dungeon now: it pulls pack by pack and waits for you, and before a boss for a healer low on mana. Say 'lead pause' to hold, 'lead off' to lead yourself.") == + "Raveni ведет группу по подземелью: пулит по одной группе мобов и ждет вас, а перед боссом и лекаря, если у него мало маны. Скажите 'lead pause', чтобы он ждал, 'lead off', чтобы вести самому."); CHECK(Translate(Lang::Ru, "Raveni holds here and pulls nothing until you say 'go'.") == "Raveni ждет здесь и никого не пулит, пока вы не скажете 'go'."); CHECK(Translate(Lang::Ru, "waiting for mana") == "жду ману"); CHECK(Translate(Lang::Ru, "You lead again: your bots follow you.") == "Снова ведете вы: ваши боты следуют за вами."); @@ -335,4 +335,16 @@ TEST_CASE("BotLocale: template syntax", "[BotLocale]") CHECK(c.Translate("level x!") == "level x!"); // {#} takes a number only } +TEST_CASE("BotLocale: the gear mode lines say the tier sets start at the level cap", "[BotLocale]") +{ + // AveenZero, playerbots #12 11-24: "gear t3" and Regear all on a priest below 60 left its weapon, and the English lines said nothing why. + CHECK(Translate(Lang::Ru, "Kelna: 3 slot(s) regeared. Gear t3 starts at level 60; below that it wears gear for its level (match).") == + "Kelna: переодето ячеек: 3. Экипировка t3 начинается с 60-го уровня; до него спутник носит экипировку по своему уровню (match)."); + CHECK(Translate(Lang::Ru, "Kelna: 3 slot(s) regeared.") == "Kelna: переодето ячеек: 3."); + CHECK(Translate(Lang::Ru, "Kelna: gear mode t3 (this applies at level 60; below that: match)") == + "Kelna: экипировка спутников: t3 (действует с 60-го уровня; до него: match)"); + CHECK(Translate(Lang::Ru, "gear mode best") == "экипировка спутников: best"); +} + + #endif diff --git a/tests/game/ClassicBotSwim.cpp b/tests/game/ClassicBotSwim.cpp index 55002a42c7..a34803e84c 100644 --- a/tests/game/ClassicBotSwim.cpp +++ b/tests/game/ClassicBotSwim.cpp @@ -138,3 +138,62 @@ TEST_CASE("BotSwim: a follower at the end of a lowered route stays in follow ran REQUIRE(d < reach + follow + 1.0f); } } + +TEST_CASE("BotSwim: a goal under the water is not snapped to the surface polygon over it", "[botswim]") +{ + float const swim = SwimZ(0.0f, kHuman); + // the rogue's melee spot by the Saltscale on the Vile Reef floor, 57 y under the surface + REQUIRE(IsUnderwaterGoal(-56.8f, swim)); + // at the swim z, or within the dive margin of it: a goal on the water, snapping is fine + REQUIRE_FALSE(IsUnderwaterGoal(swim, swim)); + REQUIRE_FALSE(IsUnderwaterGoal(swim - kDiveMargin, swim)); + REQUIRE_FALSE(IsUnderwaterGoal(0.0f, swim)); +} + +TEST_CASE("BotSwim: one straight swim goes as deep as the water, but no farther across than a pool", "[botswim]") +{ + // straight down from the surface to the reef: 57 y deep, 4 y across + REQUIRE(SwimLegFits(4.0f, std::sqrt(4.0f * 4.0f + 57.0f * 57.0f))); + // a pool across, as before + REQUIRE(SwimLegFits(38.0f, 38.0f)); + // across a lake: the router's trip + REQUIRE_FALSE(SwimLegFits(41.0f, 41.0f)); + REQUIRE_FALSE(SwimLegFits(30.0f, 95.0f)); + // nothing to swim + REQUIRE_FALSE(SwimLegFits(0.2f, 0.5f)); +} + +TEST_CASE("BotSwim: a bot down by its fight or its leader under the water stays down, one alone settles up", "[botswim]") +{ + float const swim = SwimZ(0.0f, kHuman); + // set down beside the leader on the reef floor + REQUIRE(HoldsDepth(-60.0f, swim, 9.0f, -60.0f)); + // the leader on the surface, or far off: it settles up as before + REQUIRE_FALSE(HoldsDepth(-60.0f, swim, 9.0f, swim)); + REQUIRE_FALSE(HoldsDepth(-60.0f, swim, kHoldDepthYards + 1.0f, -60.0f)); + // on top of the water: the settle down is never held + REQUIRE_FALSE(HoldsDepth(0.5f, swim, 3.0f, -60.0f)); +} + +TEST_CASE("BotSwim: up for air on the server's breath timer, and up there until the bar is full", "[botswim]") +{ + bool refilling = false; + // the timer is not running (full, water breathing): nothing to do + REQUIRE_FALSE(BreathGoesUp(-1, refilling)); + // under water with plenty left, whatever it is doing (a fight counts as much as a swim) + REQUIRE_FALSE(BreathGoesUp(60000, refilling)); + REQUIRE_FALSE(BreathGoesUp(BreathUpAtLeftMs + 1, refilling)); + // short: up + REQUIRE(BreathGoesUp(BreathUpAtLeftMs, refilling)); + REQUIRE(refilling); + // at the surface the bar fills again: it stays up, not straight back down at 26 s + REQUIRE(BreathGoesUp(BreathUpAtLeftMs + 10000, refilling)); + REQUIRE(BreathGoesUp(59000, refilling)); + // full (the server stops the timer): free to dive again + REQUIRE_FALSE(BreathGoesUp(-1, refilling)); + REQUIRE_FALSE(refilling); + REQUIRE_FALSE(BreathGoesUp(50000, refilling)); + // an undead's 4 minutes: no trip up after 35 s, only when 25 s are left + REQUIRE_FALSE(BreathGoesUp(240000 - 35000, refilling)); + REQUIRE(BreathGoesUp(24000, refilling)); +} diff --git a/tests/game/ClassicCcPick.cpp b/tests/game/ClassicCcPick.cpp index e7e8793aa0..678c7d1bb9 100644 --- a/tests/game/ClassicCcPick.cpp +++ b/tests/game/ClassicCcPick.cpp @@ -57,3 +57,11 @@ TEST_CASE("Locked, skull, wrong-type, unlisted and self-attacking adds are skipp CHECK(PickCcTarget({ locked, skull, wrong, hits, unlisted }) == kNoCcTarget); CHECK(PickCcTarget({ locked, skull, wrong, hits, unlisted, Eligible() }) == 5); } + +TEST_CASE("An idle add the tank cannot walk to is not crowd-controlled", "[ClassicCcPick]") +{ + // lbrs_full af58: the mage sheeped a mob 13 y below the ledge (a 210 y walk for the tank), the pack came up and the priest died. + CcCandidate below = Eligible(true); below.tank_cannot_pull = true; + CHECK(PickCcTarget({ below }) == kNoCcTarget); + CHECK(PickCcTarget({ below, Eligible() }) == 1); +} diff --git a/tests/game/ClassicFormation.cpp b/tests/game/ClassicFormation.cpp new file mode 100644 index 0000000000..49917b8f9a --- /dev/null +++ b/tests/game/ClassicFormation.cpp @@ -0,0 +1,75 @@ +/* + * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "tc_catch2.h" + +#ifdef TESTS_HAVE_PLAYERBOT_V2 + +#include "../../src/modules/PlayerbotV2/Bot/Formation.h" +#include +#include + +using namespace Playerbot; + +namespace +{ +constexpr float kPi = 3.14159265358979323846f; + +// Distance of an angle from straight ahead of the owner (0) in radians, 0 .. pi. +float OffFront(float a) +{ + a = std::fmod(a, 2.0f * kPi); + if (a < 0.0f) a += 2.0f * kPi; + return a > kPi ? 2.0f * kPi - a : a; +} +} + +TEST_CASE("Circle formation: the first slot leads, the last closes the ring behind the owner", "[ClassicFormation]") +{ + // Members are sorted tanks first, healers last (State_InGroup). Row 348: the tank stood directly behind the owner. + for (uint32_t count : { 2u, 4u, 5u, 9u }) + { + FormationOffset const tank = ComputeOwnerSlotOffset(FormationType::Circle, 0, count, 1, 3.0f); + FormationOffset const last = ComputeOwnerSlotOffset(FormationType::Circle, count - 1, count, 1, 3.0f); + CHECK(OffFront(tank.angle_radians) < 0.1f); + CHECK(OffFront(last.angle_radians) > OffFront(tank.angle_radians)); + // Each later slot of the first ring stands at least as far round towards the back as the one before it. + for (uint32_t i = 1; i < count && i < 5; ++i) + CHECK(OffFront(ComputeOwnerSlotOffset(FormationType::Circle, i, count, 1, 3.0f).angle_radians) + 1e-4f >= + OffFront(ComputeOwnerSlotOffset(FormationType::Circle, i - 1, count, 1, 3.0f).angle_radians)); + } + // With 5 bots the healer (last) is behind the owner's shoulders. + CHECK(OffFront(ComputeOwnerSlotOffset(FormationType::Circle, 4, 5, 1, 3.0f).angle_radians) > kPi / 2.0f); +} + +TEST_CASE("Circle formation: no two slots on the same spot", "[ClassicFormation]") +{ + for (uint32_t count : { 3u, 8u, 20u, 40u }) + { + std::set> spots; + for (uint32_t i = 0; i < count; ++i) + { + FormationOffset const o = ComputeOwnerSlotOffset(FormationType::Circle, i, count, 1, 3.0f); + CHECK(o.distance > 1.0f); + int const x = int(std::lround(o.distance * std::cos(o.angle_radians) * 4.0f)); + int const y = int(std::lround(o.distance * std::sin(o.angle_radians) * 4.0f)); + CHECK(spots.insert({ x, y }).second); + } + } +} + +#endif diff --git a/tests/game/ClassicLazyKey.cpp b/tests/game/ClassicLazyKey.cpp new file mode 100644 index 0000000000..89f829803e --- /dev/null +++ b/tests/game/ClassicLazyKey.cpp @@ -0,0 +1,246 @@ +/* + * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "tc_catch2.h" + +#include "../../src/modules/PlayerbotV2/Combat/LazyKey.h" + +using namespace Playerbot::LazyKey; + +namespace +{ +// A level 60 character of the class with every spell of its rules known and ready, in combat with a fresh target in melee and in range, +// full mana and energy, 50 rage, no combo points, nobody hurt. +Input Fresh(uint8_t cls, Role role = Role::Dps) +{ + Input in; + in.cls = cls; + in.role = role; + in.known = Spells(cls); + in.ready = Spells(cls); + in.in_combat = true; + in.has_target = true; + in.target_in_melee = true; + in.target_in_range = true; + in.target_on_me = true; + in.target_attacking = true; + in.rage = 50; + in.has_healee = true; + in.healee_is_self = true; + in.healee_hp_pct = 100; + return in; +} + +void Drop(std::vector& v, uint32_t id) { v.erase(std::remove(v.begin(), v.end(), id), v.end()); } +} + +TEST_CASE("Nothing happens while a cast is going", "[ClassicLazyKey]") +{ + Input in = Fresh(kMage); + in.casting = true; + CHECK(Pick(in).spell == 0); +} + +TEST_CASE("A warrior tank goes into Defensive Stance, then taunts a target that hits someone else", "[ClassicLazyKey]") +{ + Input in = Fresh(kWarrior, Role::Tank); + in.form = Form::Battle; + CHECK(Pick(in).spell == Id::DefensiveStance); + in.form = Form::Defensive; + in.target_on_me = false; + CHECK(Pick(in).spell == Id::Taunt); + in.target_on_me = true; + CHECK(Pick(in).spell == Id::ShieldBlock); + Drop(in.ready, Id::ShieldBlock); + CHECK(Pick(in).spell == Id::Revenge); +} + +TEST_CASE("A damage warrior executes, uses procs, then its strike, and dumps rage into Heroic Strike", "[ClassicLazyKey]") +{ + Input in = Fresh(kWarrior); + in.form = Form::Battle; + in.on_self.push_back(Id::BattleShout); + in.target_hp_pct = 15; + CHECK(Pick(in).spell == Id::Execute); + in.target_hp_pct = 80; + CHECK(Pick(in).spell == Id::Overpower); + in.blocked.push_back(Id::Overpower); // no dodge to overpower: refused, left out + CHECK(Pick(in).spell == Id::MortalStrike); + Drop(in.ready, Id::MortalStrike); + Drop(in.ready, Id::Bloodthirst); + Drop(in.ready, Id::Whirlwind); + in.rage = 70; + CHECK(Pick(in).spell == Id::HeroicStrike); + CHECK(OffGlobalCooldown(Id::HeroicStrike)); +} + +TEST_CASE("A low level warrior keeps Rend up and spends rage on Heroic Strike", "[ClassicLazyKey]") +{ + Input in = Fresh(kWarrior); + in.known = { Id::HeroicStrike, Id::Rend, Id::BattleShout, Id::Charge }; + in.ready = in.known; + in.form = Form::Battle; + in.on_self.push_back(Id::BattleShout); + in.rage = 20; + CHECK(Pick(in).spell == Id::Rend); + in.on_target.push_back(Id::Rend); + CHECK(Pick(in).spell == Id::HeroicStrike); +} + +TEST_CASE("A paladin seals, judges, and saves Exorcism for undead and demons", "[ClassicLazyKey]") +{ + Input in = Fresh(kPaladin); + Drop(in.known, Id::SealOfCommand); + CHECK(Pick(in).spell == Id::SealOfRighteousness); + in.on_self.push_back(Id::SealOfRighteousness); + CHECK(Pick(in).spell == Id::Judgement); + in.target_undead_or_demon = true; + CHECK(Pick(in).spell == Id::Exorcism); +} + +TEST_CASE("A hunter starts Auto Shot, marks, stings, and goes to melee strikes up close", "[ClassicLazyKey]") +{ + Input in = Fresh(kHunter); + in.on_self.push_back(Id::AspectOfTheHawk); + in.target_in_melee = false; + in.target_boss = true; + Drop(in.ready, Id::BestialWrath); + Drop(in.ready, Id::RapidFire); + CHECK(Pick(in).spell == Id::AutoShot); + in.auto_shooting = true; + CHECK(Pick(in).spell == Id::HuntersMark); + in.on_target.push_back(Id::HuntersMark); + CHECK(Pick(in).spell == Id::SerpentSting); + in.target_in_melee = true; + CHECK(Pick(in).spell == Id::MongooseBite); +} + +TEST_CASE("A rogue keeps Slice and Dice and spends five points on Eviscerate", "[ClassicLazyKey]") +{ + Input in = Fresh(kRogue); + Drop(in.ready, Id::Riposte); + Drop(in.ready, Id::AdrenalineRush); + Drop(in.known, Id::GhostlyStrike); + Drop(in.known, Id::Hemorrhage); + Drop(in.ready, Id::ColdBlood); + CHECK(Pick(in).spell == Id::SinisterStrike); + in.combo = 2; + CHECK(Pick(in).spell == Id::SliceAndDice); + in.on_self.push_back(Id::SliceAndDice); + in.combo = 5; + CHECK(Pick(in).spell == Id::Eviscerate); + in.energy = 20; + CHECK(Pick(in).spell == 0); +} + +TEST_CASE("A healer priest shields a dying member, then heals past Weakened Soul, and fights when nobody is hurt", "[ClassicLazyKey]") +{ + Input in = Fresh(kPriest, Role::Heal); + in.healee_is_self = false; + in.healee_hp_pct = 30; + Choice c = Pick(in); + CHECK(c.spell == Id::PowerWordShield); + CHECK(c.at == At::Healee); + in.on_healee.push_back(Id::WeakenedSoul); + CHECK(Pick(in).spell == Id::FlashHeal); + in.healee_hp_pct = 80; + CHECK(Pick(in).spell == Id::Renew); + in.hurt_count = 3; + CHECK(Pick(in).spell == Id::PrayerOfHealing); + in.hurt_count = 0; + in.healee_hp_pct = 100; + in.form = Form::None; + Drop(in.known, Id::Shadowform); + CHECK(Pick(in).spell == Id::VampiricEmbrace); // nobody hurt: the healer fights, Vampiric Embrace first on a fresh long fight +} + +TEST_CASE("A shaman healer uses Chain Heal on three hurt and Nature's Swiftness in an emergency", "[ClassicLazyKey]") +{ + Input in = Fresh(kShaman, Role::Heal); + in.healee_is_self = false; + in.healee_hp_pct = 60; + in.hurt_count = 3; + CHECK(Pick(in).spell == Id::ChainHeal); + in.hurt_count = 1; + in.healee_hp_pct = 30; + CHECK(Pick(in).spell == Id::ShamanSwiftness); + CHECK(OffGlobalCooldown(Id::ShamanSwiftness)); +} + +TEST_CASE("A mage novas an enemy in melee, then casts its tree's filler and wands when dry", "[ClassicLazyKey]") +{ + Input in = Fresh(kMage); + in.on_self = { Id::ArcaneIntellect, Id::IceArmor }; + CHECK(Pick(in).spell == Id::FrostNova); + in.target_on_me = false; + in.target_in_melee = false; + Drop(in.ready, Id::FireBlast); + in.tree = 3; + CHECK(Pick(in).spell == Id::Frostbolt); + in.tree = 2; + CHECK(Pick(in).spell == Id::Fireball); + in.mana_pct = 5; + in.wand = true; + CHECK(Pick(in).spell == Id::Shoot); +} + +TEST_CASE("A druid tank goes into Bear Form and growls; a druid healer leaves Cat Form to heal", "[ClassicLazyKey]") +{ + Input in = Fresh(kDruid, Role::Tank); + CHECK(Pick(in).spell == Id::DireBearForm); + in.form = Form::Bear; + in.target_on_me = false; + CHECK(Pick(in).spell == Id::Growl); + + Input heal = Fresh(kDruid, Role::Heal); + heal.form = Form::Cat; + heal.healee_is_self = false; + heal.healee_hp_pct = 50; + CHECK(Pick(heal).cancel_form); + heal.form = Form::None; + CHECK(Pick(heal).spell == Id::Rejuvenation); +} + +TEST_CASE("Out of combat with no target the press keeps the buffs up", "[ClassicLazyKey]") +{ + Input in = Fresh(kShaman); + in.in_combat = false; + in.has_target = false; + CHECK(Pick(in).spell == Id::LightningShield); + in.on_self.push_back(Id::LightningShield); + CHECK(Pick(in).spell == Id::WindfuryWeapon); + in.weapon_imbued = true; + CHECK(Pick(in).spell == 0); +} + +TEST_CASE("Specs map onto the three trees, Guardian onto Feral", "[ClassicLazyKey]") +{ + CHECK(TreeOfSpec(kWarrior, 73) == 3); + CHECK(TreeOfSpec(kMage, 62) == 1); + CHECK(TreeOfSpec(kDruid, 104) == 2); + CHECK(TreeOfSpec(kDruid, 105) == 3); + CHECK(TreeOfSpec(kPriest, 999) == 0); + CHECK(Spells(9).empty()); // the warlock has its own rotation +} + +TEST_CASE("The wand ends the press, Auto Shot does not", "[ClassicLazyKey]") +{ + // Any spell cast after the wand's Shoot stops it: the press that starts the wand ends there. + CHECK_FALSE(OffGlobalCooldown(Id::Shoot)); + // Auto Shot runs beside the shots: the press goes on to the next one. + CHECK(OffGlobalCooldown(Id::AutoShot)); +} diff --git a/tests/game/ClassicScenarioMonitor.cpp b/tests/game/ClassicScenarioMonitor.cpp index 731f4cefc9..b0a36d698f 100644 --- a/tests/game/ClassicScenarioMonitor.cpp +++ b/tests/game/ClassicScenarioMonitor.cpp @@ -135,6 +135,42 @@ TEST_CASE("ScenarioMonitor: a group that all waits is stalled, not idle, and end CHECK_FALSE(Has(m, ScenarioFailKind::Idle)); } +TEST_CASE("ScenarioMonitor: a squad that waited together is not idle when the tank sets off again", "[scenariomonitor]") +{ + // sfk_full af59: all five stood 60 s at the Courtyard Door while the prisoner walked to it; the tank left first. + ScenarioMonitor m(Limits()); + for (std::uint32_t t = 0; t <= 60000; t += 1000) + m.Feed(t, Squad(-100.f, -500.f), true); + for (std::uint32_t t = 61000; t <= 64000; t += 1000) + { + auto squad = Squad(-100.f, -500.f); + squad[0].x = -100.f - float(t - 60000) / 1000.f * 5.f; // only the tank walks on, the others follow a few seconds later + m.Feed(t, squad, true); + } + for (std::uint32_t t = 65000; t <= 90000; t += 1000) + m.Feed(t, Squad(-120.f - float(t - 65000) / 1000.f, -500.f), true); + CHECK_FALSE(Has(m, ScenarioFailKind::Idle)); +} + +TEST_CASE("ScenarioMonitor: a bot that stays behind after a shared wait is idle 45 seconds after the others set off", "[scenariomonitor]") +{ + ScenarioMonitor m(Limits()); + for (std::uint32_t t = 0; t <= 60000; t += 1000) + m.Feed(t, Squad(-100.f, -500.f), true); + std::uint32_t idle_at = 0; + for (std::uint32_t t = 61000; t <= 130000; t += 1000) + { + auto squad = Squad(-100.f - float(t - 60000) / 1000.f, -500.f); + squad[2].x = -108.f; squad[2].y = -497.f; // the mage never moves + m.Feed(t, squad, true); + for (ScenarioFailure const& f : m.failures()) + if (f.kind == ScenarioFailKind::Idle && !idle_at) + idle_at = f.at_ms; + } + CHECK(idle_at >= 105000); + CHECK(idle_at <= 108000); +} + TEST_CASE("ScenarioMonitor: a fight keeps a standing group from counting as stalled", "[scenariomonitor]") { ScenarioMonitor m(Limits()); @@ -1145,3 +1181,43 @@ TEST_CASE("ScenarioMonitor: water checks find a bot under the water, one that bo REQUIRE_FALSE(Has(m, ScenarioFailKind::Water)); } } + +TEST_CASE("ScenarioMonitor: a leading tank that holds a trash pull for mana fails mana_hold, once", "[scenariomonitor]") +{ + ScenarioLimits l = Limits(); + l.no_mana_hold = true; + + SECTION("no hold passes") + { + ScenarioMonitor m(l); + for (std::uint32_t t = 0; t <= 20000; t += 1000) + m.Feed(t, Squad(-100.f + float(t) * 0.001f, -500.f), true); + REQUIRE_FALSE(Has(m, ScenarioFailKind::ManaHold)); + } + SECTION("\"waiting for mana\" fails, once") + { + ScenarioMonitor m(l); + for (std::uint32_t t = 0; t <= 20000; t += 1000) + { + auto squad = Squad(-100.f + float(t) * 0.001f, -500.f); + squad[0].mana_hold = t >= 5000; + m.Feed(t, squad, true); + } + REQUIRE(Has(m, ScenarioFailKind::ManaHold, "Tank")); + std::size_t n = 0; + for (auto const& f : m.failures()) + if (f.kind == ScenarioFailKind::ManaHold) ++n; + REQUIRE(n == 1); + } + SECTION("off unless the scenario asks") + { + ScenarioMonitor m(Limits()); + for (std::uint32_t t = 0; t <= 20000; t += 1000) + { + auto squad = Squad(-100.f + float(t) * 0.001f, -500.f); + squad[0].mana_hold = true; + m.Feed(t, squad, true); + } + REQUIRE_FALSE(Has(m, ScenarioFailKind::ManaHold)); + } +} diff --git a/tests/game/ClassicTownErrand.cpp b/tests/game/ClassicTownErrand.cpp index 144691f234..d17010acb0 100644 --- a/tests/game/ClassicTownErrand.cpp +++ b/tests/game/ClassicTownErrand.cpp @@ -17,6 +17,7 @@ #include "tc_catch2.h" #include "../../src/modules/PlayerbotV2/Bot/TownErrand.h" +#include "../../src/modules/PlayerbotV2/Bot/TownErrandConfig.h" #include #include @@ -103,6 +104,19 @@ TEST_CASE("Bots at one place stand side by side on the near side", "[ClassicTown REQUIRE(seen.size() == 5); } +TEST_CASE("A place with a facing fans its bots out front; one without uses the approach side", "[ClassicTownErrand]") +{ + float sx, sy; + // A banker facing east (orientation 0): the queue stands in front, not behind. + StandPoint(0.f, 0.f, -50.f, 0.f, 4.f, 0, sx, sy, 0.0f); + REQUIRE(sx > 3.9f); + REQUIRE(std::fabs(sy) < 0.1f); + // No facing stored (-1 = none): the side the bot approaches from (+x) is used. + StandPoint(0.f, 0.f, 50.f, 0.f, 4.f, 0, sx, sy, -1.0f); + REQUIRE(sx > 3.9f); + REQUIRE(std::fabs(sy) < 0.1f); +} + TEST_CASE("A walk that stops getting closer is stalled after the window", "[ClassicTownErrand]") { State st; @@ -112,3 +126,95 @@ TEST_CASE("A walk that stops getting closer is stalled after the window", "[Clas REQUIRE_FALSE(Stalled(st, 5.5f, 0.f, 15000u)); REQUIRE(Stalled(st, 5.5f, 0.f, 16001u)); } + +TEST_CASE("A station's SpellFocusObject name maps to its errand kind", "[ClassicTownErrand]") +{ + REQUIRE(KindForFocusName("Anvil") == Kind::Forge); + REQUIRE(KindForFocusName("Forge") == Kind::Forge); + REQUIRE(KindForFocusName("Smelter") == Kind::Forge); + REQUIRE(KindForFocusName("Furnace") == Kind::Forge); + REQUIRE(KindForFocusName("Cooking Fire") == Kind::Cookfire); + REQUIRE(KindForFocusName("Cooking Stove") == Kind::Cookfire); + REQUIRE(KindForFocusName("Bonfire") == Kind::Cookfire); + REQUIRE(KindForFocusName("Loom") == Kind::Loom); + REQUIRE(KindForFocusName("Mana Loom") == Kind::Loom); + REQUIRE(KindForFocusName("Moonwell") == Kind::Moonwell); + REQUIRE(KindForFocusName("Alchemy Lab") == Kind::None); // needs no station in Classic + REQUIRE(KindForFocusName("Lexicon of Power") == Kind::None); + REQUIRE(KindForFocusName("") == Kind::None); // a focus id the client table does not name +} + +TEST_CASE("The craft kinds are stations, with a work emote each", "[ClassicTownErrand]") +{ + REQUIRE(IsCraftKind(Kind::Forge)); + REQUIRE(IsCraftKind(Kind::Cookfire)); + REQUIRE(IsCraftKind(Kind::Loom)); + REQUIRE(IsCraftKind(Kind::Moonwell)); + REQUIRE_FALSE(IsCraftKind(Kind::Bank)); + REQUIRE_FALSE(IsCraftKind(Kind::Mailbox)); + REQUIRE(WorkEmoteFor(Kind::Forge) == 173); // EMOTE_STATE_WORK + REQUIRE(WorkEmoteFor(Kind::Cookfire) == 69); // EMOTE_STATE_USE_STANDING + REQUIRE(WorkEmoteFor(Kind::Moonwell) == 68); // EMOTE_STATE_KNEEL + REQUIRE(WorkEmoteFor(Kind::Bank) == 0); + REQUIRE(std::string_view(KindName(Kind::Forge)) == "forge"); + REQUIRE(std::string_view(KindName(Kind::Cookfire)) == "cooking fire"); +} + +TEST_CASE("The linger and the fixture a kind gets come from its config", "[ClassicTownErrand]") +{ + Config c; // defaults: 20-40 s at the bank and the auction house, 45-90 s at a station + std::uint32_t lo = 0, hi = 0; + LingerRange(c, Kind::Vendor, lo, hi); + REQUIRE(lo == c.linger_min_ms); + REQUIRE(hi == c.linger_max_ms); + LingerRange(c, Kind::Bank, lo, hi); + REQUIRE(lo == 20000u); + REQUIRE(hi == 40000u); + LingerRange(c, Kind::Auction, lo, hi); + REQUIRE(lo == 20000u); + REQUIRE(hi == 40000u); + LingerRange(c, Kind::Forge, lo, hi); + REQUIRE(lo == 45000u); + REQUIRE(hi == 90000u); + LingerRange(c, Kind::Cookfire, lo, hi); + REQUIRE(lo == 45000u); + REQUIRE(hi == 90000u); + REQUIRE(FixtureTarget(c, Kind::Bank) == 3); + REQUIRE(FixtureTarget(c, Kind::Auction) == 3); + REQUIRE(FixtureTarget(c, Kind::Forge) == 2); + REQUIRE(FixtureTarget(c, Kind::Cookfire) == 1); + REQUIRE(FixtureTarget(c, Kind::Loom) == 0); // off by default: rarely seen in Classic + REQUIRE(FixtureTarget(c, Kind::Vendor) == 0); // no fixture for a plain errand +} + +TEST_CASE("An errand that ends clears its craft-station state", "[ClassicTownErrand]") +{ + State st; + st.focus_type = 7; + st.next_use_ms = 12345u; + st.work_emote = true; + st.tool_bag = 1; + st.tool_slot = 4; + st.kit_ready = true; + st.tool_in_hand = true; + st.kit_attempts = 3; + st.next_kit_ms = 999u; + st.stock_given = true; + st.recipe_given = true; + st.want_vendor = true; + st.Clear(); + REQUIRE(st.focus_type == 0); + REQUIRE(st.next_use_ms == 0); + REQUIRE_FALSE(st.work_emote); + // The tool swap is undone before Clear — the reset value is "no tool" (0xFF), not a bag slot. + REQUIRE(st.tool_bag == 0xFF); + REQUIRE(st.tool_slot == 0xFF); + REQUIRE_FALSE(st.kit_ready); + REQUIRE_FALSE(st.tool_in_hand); + REQUIRE(st.kit_attempts == 0); + REQUIRE(st.next_kit_ms == 0); + REQUIRE_FALSE(st.stock_given); + REQUIRE_FALSE(st.recipe_given); + // want_vendor outlives the errand that set it — it steers the next pick to a vendor. + REQUIRE(st.want_vendor); +}