-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlugin.cpp
More file actions
4434 lines (4347 loc) · 214 KB
/
Copy pathPlugin.cpp
File metadata and controls
4434 lines (4347 loc) · 214 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <Global.h>
#include <PCH.h>
// --- VARIABLES ---
// Actor Tracking variables
namespace ActorTracking {
std::mutex g_actorDataMutex;
std::vector<TrackedActorData> g_enemies;
std::vector<TrackedActorData> g_companions;
std::vector<TrackedActorData> g_neutralNPCs;
std::vector<TrackedActorData> g_enemies_prev;
std::vector<TrackedActorData> g_companions_prev;
std::vector<TrackedActorData> g_neutralNPCs_prev;
} // namespace ActorTracking
// companion flags storage
std::mutex ActorTracking::g_companionFlagsMutex;
std::unordered_map<RE::Actor*, std::unique_ptr<ActorTracking::CompanionFlags>> ActorTracking::g_companionFlags;
// Reload interval counter
int g_iniReloadCounter = 0;
// Global for max enemy health in cell initialized to 1.0 to avoid division by zero
std::atomic<float> g_enemyMaxHealthInCell = 1.0f;
// Global cell flags
bool g_isInSettlement = false;
bool g_isInEncounterZone = false;
bool g_isInInterior = false;
// Player state flags
bool g_playerInCombat = false;
bool g_playerIsSneaking = false;
// Main thread work pending flag
std::atomic<bool> g_isMainThreadWorkPending = false;
// Throttle XP awards to at most once per second
static std::mutex s_lastXpMutex;
static std::chrono::steady_clock::time_point s_lastXpTime = std::chrono::steady_clock::now() - std::chrono::seconds(2);
// Looted Items tracking
std::unordered_set<RE::TESFormID> g_lootedLooseWeapons;
// Component to Scrap Item mapping
std::unordered_map<RE::BGSComponent*, RE::TESObjectMISC*> g_componentToScrapMap;
// --- EVENTS ---
// Event handler for companion kill enemy events
RE::BSEventNotifyControl CompanionKillEventSink::ProcessEvent(const RE::TESDeathEvent& a_event, RE::BSTEventSource<RE::TESDeathEvent>* a_eventSource) {
if (!OTHER_SETTINGS || !XP_ENABLED)
return RE::BSEventNotifyControl::kContinue;
// Validate event data
if (!a_event.actorDying || !a_event.actorKiller) {
return RE::BSEventNotifyControl::kContinue;
}
// Only process death events where the actor is dead
if (!a_event.dead)
return RE::BSEventNotifyControl::kContinue;
// Check throttle timer
std::lock_guard<std::mutex> lk(s_lastXpMutex);
auto now = std::chrono::steady_clock::now();
if (now - s_lastXpTime < std::chrono::seconds(1)) {
if (DEBUGGING) {
REX::INFO("CompanionKillEventSink: XP award skipped — throttled (last award {:.3f}s ago).", std::chrono::duration<float>(now - s_lastXpTime).count());
}
return RE::BSEventNotifyControl::kContinue;
}
// Set new last XP time
s_lastXpTime = now;
// Get victim and killer actors
auto* victim = a_event.actorDying->As<RE::Actor>();
auto* killer = a_event.actorKiller->As<RE::Actor>();
auto* player = RE::PlayerCharacter::GetSingleton();
// Check if the killer is the player or a companion (companion kills also show player as killer)
if (!victim || !killer || !player || killer != player) {
return RE::BSEventNotifyControl::kContinue;
}
// Check if victim was hostile
if (!victim->GetHostileToActor(player)) {
return RE::BSEventNotifyControl::kContinue;
}
// Make a local copy under mutex protection
// Copy companion data
auto companionDataCopy = ActorTracking::GetCompanionData();
// Find the companion who is closest to the killer (i.e., likely the firing companion)
auto victimPos = victim->GetPosition();
RE::Actor* closestCompanion = nullptr;
float closestDistance = FLT_MAX;
for (auto& companionData : companionDataCopy) {
auto* companion = companionData.actor;
if (!companion)
continue;
// Check if companion is alive (essential actors need to pass false for isDead check)
if (!companionData.lifeState == ACTOR_STATE::ALIVE)
continue;
// Check if companion is in combat
if (!companionData.isAlerted)
continue;
// Calculate distance between COMPANION and VICTIM position
float distance = companionData.position.GetDistance(victimPos);
if (distance < closestDistance) {
closestDistance = distance;
closestCompanion = companion;
}
}
// Check if we found a firing companion
if (closestCompanion && closestDistance < XP_KILLER_TOLERANCE) {
// Companion kill - award XP!
if (DEBUGGING) {
REX::INFO("-------------------- Companion Kill Detected --------------------");
REX::INFO("CompanionKillEventSink: Companion {} kill detected!", closestCompanion->GetDisplayFullName());
}
// Calculate and award XP...
auto* victimNPC = victim->GetNPC();
if (victimNPC && victimNPC->actorData.level > 0) {
auto difficultyLevel = player->GetDifficultyLevel();
float awardedXP = victimNPC->actorData.level;
auto experienceReward = RE::GamePlayFormulas::GetExperienceReward(RE::GamePlayFormulas::EXPERIENCE_ACTIVITY::kKillNPC, difficultyLevel, awardedXP) * XP_RATIO;
auto clampedXP = std::clamp(experienceReward, 1.0f, 1000000.0f);
player->RewardExperience(clampedXP, true, victim, nullptr);
if (DEBUGGING) {
REX::INFO("CompanionKillEventSink: Awarded {:.0f} XP for level {} enemy", awardedXP, victimNPC->actorData.level);
REX::INFO("-----------------------------------------------------------------");
}
}
}
return RE::BSEventNotifyControl::kContinue;
}
// --- FUNCTIONS ---
// Main Update function
void Update_Internal() {
// Quick check to ensure we are in a game session
g_taskInterface->AddTask([]() {
auto* player = RE::PlayerCharacter::GetSingleton();
if (!player || !player->parentCell) {
// Not in a game session, skip update and cancel timer
if (DEBUGGING)
REX::INFO("Update_Internal: Not in a game session, skipping update and stopping timer.");
g_updateTimer.Stop();
return;
}
// Check if player is in a scene
if (IsActorInScene_Internal(player)) {
if (DEBUGGING)
REX::WARN("Update_Internal: Player is currently in a scene, cannot get actors");
return;
}
});
// Reload INI settings if the interval is set
if (INI_RELOAD_INTERVAL > 0) {
g_iniReloadCounter++;
if (g_iniReloadCounter >= INI_RELOAD_INTERVAL) {
// Load MCM config
LoadMCMConfig();
// Reset counter
g_iniReloadCounter = 0;
if (DEBUGGING)
REX::INFO("Update_Internal: Reloaded MCM INI configuration.");
}
}
// Initialize the global variables in case the game data wasn't ready yet
InitializeVariables_Internal();
// Check if the player paused the game
if (IsMenuOpen_Internal()) {
if (DEBUGGING)
REX::INFO("Update_Internal: Game is paused, skipping update.");
return;
}
// Continue with update
if (DEBUGGING)
REX::INFO("========================================================================");
// Check the current cell
g_isInSettlement = CheckIsCurrentCellSettlement_Internal();
g_isInEncounterZone = CheckIsCurrentCellEncounterZone_Internal();
g_isInInterior = CheckIsCurrentCellInterior_Internal();
if (DEBUGGING) {
REX::INFO("Update_Internal: Info - Current cell is {}a settlement.", g_isInSettlement ? "" : "not ");
REX::INFO("Update_Internal: Info - Current cell is {}an encounter zone.", g_isInEncounterZone ? "" : "not ");
REX::INFO("Update_Internal: Info - Current cell is {}an interior.", g_isInInterior ? "" : "not ");
}
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
if (DEBUGGING)
REX::INFO("Update_Internal: -------- Starting background work. --------");
// Make sure the global pointers are initialized
if (!g_companionFaction) {
// Try to get the TESFaction this is only run once per session
g_companionFaction = GetFormByFileAndID_Internal<RE::TESFaction>(CURRENT_COMPANION_FACTION_ID);
}
// Update global actor arrays and calculate threat levels
int actorCount = UpdateGlobalActorArrays_Internal();
if (DEBUGGING)
REX::INFO("Update_Internal: Actors - Found a total of {} actors in the current cell.", actorCount);
if (DEBUGGING)
REX::INFO("Update_Internal: -------- Background work completed --------");
// Log the counts of tracked actors and current threat tier distribution
auto companionData = ActorTracking::GetCompanionData();
if (companionData.size() == 0) {
if (DEBUGGING)
REX::INFO("Update_Internal: No companions detected, skipping main thread functions.");
if (DEBUGGING)
REX::INFO("========================================================================");
return;
}
if (DEBUGGING) {
auto neutralData = ActorTracking::GetNeutralNPCData();
auto enemyData = ActorTracking::GetEnemyData();
REX::INFO("Update_Internal: Actors - Current actor tracking summary:");
REX::INFO(" - Companions: {}", companionData.size());
REX::INFO(" - Neutral NPCs: {}", neutralData.size());
REX::INFO(" - Enemies: {}", enemyData.size());
if (enemyData.size() > 0) {
auto enemyTierCounts = EnemyActorAnalyzeThreatLevel_Internal(enemyData);
REX::INFO(" - Low Tier: {}", enemyTierCounts[ENEMY_TIER::LOW]);
REX::INFO(" - Medium Tier: {}", enemyTierCounts[ENEMY_TIER::MEDIUM]);
REX::INFO(" - High Tier: {}", enemyTierCounts[ENEMY_TIER::HIGH]);
}
}
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
// Only modify game data on the main thread
if (g_taskInterface && !g_isMainThreadWorkPending) {
g_isMainThreadWorkPending = true;
g_taskInterface->AddTask([companionData]() {
// Threadsafe work
auto* player = RE::PlayerCharacter::GetSingleton();
if (!player)
return;
g_playerInCombat = player->IsInCombat();
g_playerIsSneaking = player->IsSneaking();
if (DEBUGGING)
REX::INFO("Update_Internal: -------- Running functions on the main thread. --------");
if (DEBUGGING) {
REX::INFO("Update_Internal: Info - Player is currently {}in combat.", g_playerInCombat ? "" : "not ");
REX::INFO("Update_Internal: Info - Player is currently {}sneaking.", g_playerIsSneaking ? "" : "not ");
REX::INFO("Companion Global values:");
REX::INFO(" - iFollower_Com_Follow: {}", g_globalComFollow ? g_globalComFollow->value : -1);
REX::INFO(" - iFollower_Com_GoHome: {}", g_globalComGoHome ? g_globalComGoHome->value : -1);
REX::INFO(" - iFollower_Com_Wait: {}", g_globalComWait ? g_globalComWait->value : -1);
REX::INFO(" - iFollower_Com_DistFar: {}", g_globalComDistFar ? g_globalComDistFar->value : -1);
REX::INFO(" - iFollower_Com_DistMedium: {}", g_globalComDistMedium ? g_globalComDistMedium->value : -1);
REX::INFO(" - iFollower_Com_DistNear: {}", g_globalComDistNear ? g_globalComDistNear->value : -1);
REX::INFO(" - iFollower_Stance_Aggressive: {}", g_globalComStanceAggro ? g_globalComStanceAggro->value : -1);
REX::INFO(" - iFollower_Stance_CombatFalse: {}", g_globalComStanceCombatFalse ? g_globalComStanceCombatFalse->value : -1);
REX::INFO(" - iFollower_Stance_CombatTrue: {}", g_globalComStanceCombatTrue ? g_globalComStanceCombatTrue->value : -1);
REX::INFO(" - iFollower_Stance_Defensive: {}", g_globalComStanceDefensive ? g_globalComStanceDefensive->value : -1);
REX::INFO(" - Command_Dist_Far: {}", g_globalComDistFarVal ? g_globalComDistFarVal->value : -1);
REX::INFO(" - Command_Dist_Medium: {}", g_globalComDistMediumVal ? g_globalComDistMediumVal->value : -1);
REX::INFO(" - Command_Dist_Near: {}", g_globalComDistNearVal ? g_globalComDistNearVal->value : -1);
REX::INFO("-----------------------------------------------------------------------");
}
// Apply AI Aggression if enabled
if ((COMBAT_SETTINGS && AI_AGGRESSION_ENABLED) &&
(g_playerInCombat || (AI_AGGRESSION_ZONEAWARE && g_isInEncounterZone) || !AI_AGGRESSION_ZONEAWARE) &&
((AI_AGGRESSION_SNEAK && g_playerIsSneaking) || !g_playerIsSneaking)) {
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
if (DEBUGGING)
REX::INFO("Update_Internal: Aggression - Updating companion aggression states...");
ApplyAIAggression_Internal(companionData);
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
// Remove AI Aggression if disabled
} else {
if (DEBUGGING)
REX::INFO("Update_Internal: Aggression - AI aggression modification removed if present...");
RemoveAIAggression_Internal(companionData);
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
}
// Buff Companions
if (ATTRIBUTES_SETTINGS && BUFF_ENABLED) {
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
if (DEBUGGING)
REX::INFO("Update_Internal: Buff - Buffing companions...");
if (BUFF_SET_VALUES) {
BuffCompanionsSetValues_Internal(companionData);
} else {
BuffCompanionsMinValues_Internal(companionData);
}
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
}
if (ATTRIBUTES_SETTINGS && PERK_ENABLED) {
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
if (DEBUGGING)
REX::INFO("Update_Internal: Perk - Applying perks to companions...");
ApplyPerksToCompanions_Internal(companionData);
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
}
if (ATTRIBUTES_SETTINGS && KEYWORD_ENABLED) {
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
if (DEBUGGING)
REX::INFO("Update_Internal: Keyword - Applying keywords to companions...");
ApplyKeywordsToCompanions_Internal(companionData);
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
}
// Loot items by companions if enabled and not in settlement and the player is not in a menu (like container or inventory)
if (LOOTING_SETTINGS && LOOT_ENABLED && !g_isInSettlement) {
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
if (DEBUGGING)
REX::INFO("Update_Internal: Loot - Looting items by companions...");
auto itemcount = LootItems_Internal(companionData);
if (DEBUGGING)
REX::INFO("Update_Internal: Loot - Looted a total of {} objects by companions.", itemcount);
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
}
// Breakdown JUNK items into components for companion inventories
if (LOOTING_SETTINGS && LOOT_JUNK_BREAKDOWN) {
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
if (DEBUGGING)
REX::INFO("Update_Internal: Loot Breakdown - Breaking down JUNK items into components for companions...");
LootItemsBreakdown_Internal(companionData);
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
}
// Equip best items for companions
if (OTHER_SETTINGS && (AI_EQUIP_ARMOR || AI_EQUIP_WEAPON)) {
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
if (AI_EQUIP_ARMOR || AI_EQUIP_WEAPON) {
if (DEBUGGING)
REX::INFO("Update_Internal: Equip - Equipping best armor and weapons for companions...");
EquipCompanions_Internal(companionData);
}
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
}
if (COMBAT_SETTINGS && AI_EQUIP_AMMO_REFILL) {
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
if (DEBUGGING)
REX::INFO("Update_Internal: Equip - Equipping ammunition for companions...");
EquipAmmunition_Internal(companionData);
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
}
// Adjust Combatstyle settings for companions
if (COMBAT_SETTINGS && COMBATSTYLE_ENABLED) {
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
if (DEBUGGING)
REX::INFO("Update_Internal: Combatstyle - Adjusting combatstyle settings for companions...");
AdjustCombatStyle_Internal(companionData);
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
}
// Repair Power Armor if enabled
if (COMBAT_SETTINGS && PA_ENABLED) {
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
if (DEBUGGING)
REX::INFO("Update_Internal: Power Armor Repair - Repairing Power Armor for companions...");
HealActorPA_Internal(companionData);
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
}
// Adjust global follow distances
if (FOLLOW_SETTINGS && AI_DISTANCE_ENABLED) {
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
if (DEBUGGING)
REX::INFO("Update_Internal: Follow Distance - Adjusting global follow distances for near, medium and far...");
AdjustGlobalFollowDistances_Internal();
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
}
// Adjust Chatter frequency
if (OTHER_SETTINGS && CHATTER_ENABLED) {
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
if (DEBUGGING)
REX::INFO("Update_Internal: Chatter - Adjusting chatter frequency...");
AdjustChatterFrequency_Internal(companionData);
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
}
// Action Companions if not in settlement or if the player is in combat
if (!g_isInSettlement || g_playerInCombat) {
// Action Companions based on their states
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
if (DEBUGGING)
REX::INFO("Update_Internal: Action - Actioning companions...");
ActionCompanions_Internal(companionData);
if (DEBUGGING)
REX::INFO("-----------------------------------------------------------------------");
}
if (DEBUGGING)
REX::INFO("Update_Internal: -------- Finished main thread work. --------");
if (DEBUGGING)
REX::INFO("========================================================================");
});
g_isMainThreadWorkPending = false;
} else {
if (DEBUGGING)
REX::INFO("Update_Internal: Main thread work still pending, skipping main thread functions this update.");
}
}
// Action Companions based on their states
void ActionCompanions_Internal(std::vector<TrackedActorData> companionData) {
if (DEBUGGING)
REX::INFO("ActionCompanions_Internal: Function called.");
// Go over our companions
for (auto& companion : companionData) {
auto* comp = companion.actor;
if (!comp)
continue;
if (IsActorInScene_Internal(comp))
continue; // Skip if in a scene
auto* compInv = comp->inventoryList;
if (!compInv)
continue;
auto* player = RE::PlayerCharacter::GetSingleton();
if (!player)
continue;
// Action flags
bool usedStimpak = false;
bool fleeCombat = false;
RE::TESIdleForm* idleToPlay = nullptr;
// Pre-Check if the companion is out of action
if (CheckActorStatesMatch_Internal(comp, ACTOR_STATE::DEAD, ACTOR_STATE::ANY, ACTOR_STATE::ANY, ACTOR_STATE::ANY)
|| CheckActorStatesMatch_Internal(comp, ACTOR_STATE::BLEEDOUT, ACTOR_STATE::ANY, ACTOR_STATE::ANY, ACTOR_STATE::ANY)
|| CheckActorStatesMatch_Internal(comp, ACTOR_STATE::ESSENTIAL_DOWN, ACTOR_STATE::ANY, ACTOR_STATE::ANY, ACTOR_STATE::ANY)) {
if (COMBAT_SETTINGS && AI_AUTO_REVIVE) {
// Attempt to revive the companion
if (companion.usesStimpak) {
auto* invStimpak = ActorAddInventoryItem_Internal(comp, g_itemStimpak, 1);
if (DEBUGGING)
REX::INFO("ActionCompanions_Internal: Revive - Attempting to auto-revive human companion {} using a stimpak...", comp->GetDisplayFullName());
if (!invStimpak) {
if (DEBUGGING)
REX::WARN("ActionCompanions_Internal: Revive - Failed to add Stimpak to companion {}'s inventory for auto-revive.", comp->GetDisplayFullName());
continue;
}
// Heal and revive
HealActorHealth_Internal(comp, 100.0f);
HealActorLimbs_Internal(comp);
// Important to clear the HC downed flag
HealActorDowned_Internal(comp);
// Make it use the stimpak to get back up
EquipInventoryItem_Internal(comp, invStimpak);
// No more processing in this update needed, continue to next companion
continue;
} else {
auto* invRepairKit = ActorAddInventoryItem_Internal(comp, g_itemRepairKit, 1);
if (DEBUGGING)
REX::INFO("ActionCompanions_Internal: Revive - Attempting to auto-revive non-human companion {} using a repair kit...", comp->GetDisplayFullName());
if (!invRepairKit) {
if (DEBUGGING)
REX::WARN("ActionCompanions_Internal: Revive - Failed to add Repair Kit to companion {}'s inventory for auto-revive.", comp->GetDisplayFullName());
continue;
}
// Heal and revive
HealActorHealth_Internal(comp, 100.0f);
HealActorLimbs_Internal(comp);
// Important to clear the HC downed flag
HealActorDowned_Internal(comp);
// Make it use the repair kit to get back up
EquipInventoryItem_Internal(comp, invRepairKit);
// No more processing in this update needed, continue to next companion
continue;
}
if (DEBUGGING)
REX::INFO("ActionCompanions_Internal: Revive - Companion {} was revived automatically.", comp->GetDisplayFullName());
} else {
if (DEBUGGING)
REX::INFO("ActionCompanions_Internal: Revive - Actor {} is out of action. Skipping...", comp->GetDisplayFullName());
continue;
}
}
// Logging
RE::TESForm* pkgForm = nullptr;
if (comp->currentProcess) {
auto* runningPackage = comp->currentProcess->GetPackageThatIsRunning();
pkgForm = runningPackage ? runningPackage : nullptr;
}
if (DEBUGGING) {
REX::INFO("ActionCompanions_Internal: Logging - Processing companion {} with race {}...", comp->GetDisplayFullName(), comp->race ? comp->race->GetFullName() : "Unknown");
REX::INFO("ActionCompanions_Internal: Logging - Actor={} runningPkgID=0x{:08X} packageTypeName={}", comp->GetDisplayFullName(), pkgForm ? pkgForm->GetFormID() : 0, pkgForm && pkgForm->GetObjectTypeName());
if (comp->currentProcess) {
REX::INFO("ActionCompanions_Internal: Logging - followTarget==player? {} ; escortingPlayer={}, inCombat={}", (comp->currentProcess->followTarget == player->GetActorHandle()) ? "yes" : "no", comp->currentProcess->escortingPlayer ? "true" : "false", companion.isAlerted ? "true" : "false");
}
REX::INFO("ActionCompanions_Internal: Logging - The companions velocity is {:.2f} and is currently stuck: {}", ActorTracking::GetActorVelocityFast(comp), ActorTracking::GetActorStuckStatusFast(comp) ? "yes" : "no");
REX::INFO("ActionCompanions_Internal: Logging - The companion is stuck for {} updates.", ActorTracking::GetActorStuckCounterFast(comp));
REX::INFO("ActionCompanions_Internal: Logging - The companion is overshooting {}", companion.overshoot ? "yes" : "no");
REX::INFO("ActionCompanions_Internal: Logging - The companion AI current follow state is {}", companion.followerState);
REX::INFO("ActionCompanions_Internal: Logging - The companion AI current follow distance is {}", companion.followerDistance);
}
// Check if interacting
if (CheckActorStatesMatch_Internal(comp, ACTOR_STATE::ALIVE, ACTOR_STATE::ANY, ACTOR_STATE::ANY, ACTOR_STATE::INTERACTING)) {
if (DEBUGGING)
REX::INFO("ActionCompanions_Internal: Interacting - Actor {} is interacting. Skipping...", comp->GetDisplayFullName());
continue;
}
// Stimpak: The companion is in combat or alerted and low on health
if (COMBAT_SETTINGS && AI_USE_STIMPAK_ENABLED && companion.isAlerted && companion.healthPercent * 100.0f <= AI_HEALTH_THRESHOLD) {
if (DEBUGGING)
REX::INFO("ActionCompanions_Internal: Stimpak - Companion {} is alerted and low on health ({:.1f}%), checking for Stimpak or repair kit use...", comp->GetDisplayFullName(), companion.healthPercent * 100.0f);
if (AI_USE_STIMPAK_UNLIMITED || (CheckActorHasItem_Internal(comp, g_itemStimpak) && companion.usesStimpak) || (CheckActorHasItem_Internal(comp, g_itemRepairKit) && !companion.usesStimpak)) {
// Remove a Stimpak from the inventory if not set to unlimited
if (!AI_USE_STIMPAK_UNLIMITED && companion.usesStimpak) {
ActorRemoveInventoryItem_Internal(comp, g_itemStimpak, 1);
} else if (!AI_USE_STIMPAK_UNLIMITED && !companion.usesStimpak) {
ActorRemoveInventoryItem_Internal(comp, g_itemRepairKit, 1);
}
// Unlimited Stimpak use
HealActorHealth_Internal(comp, 100.0f);
HealActorLimbs_Internal(comp);
usedStimpak = true;
idleToPlay = g_idleStimpak;
if (DEBUGGING)
REX::INFO("ActionCompanions_Internal: Stimpak - Companion {} used stimpak or repair kit! Health was at {:.1f}%", comp->GetDisplayFullName(), companion.healthPercent * 100.0f);
} else {
if (AI_FLEE_COMBAT) {
fleeCombat = true;
if (DEBUGGING)
REX::INFO("ActionCompanions_Internal: Stimpak - Companion {} wants to use a Stimpak or repair kit but has none, will flee combat!", comp->GetDisplayFullName());
} else {
if (DEBUGGING)
REX::INFO("ActionCompanions_Internal: Stimpak - Companion {} wanted to use a Stimpak or repair kit but has none! Companion is not allowed to flee.", comp->GetDisplayFullName());
}
}
}
// Handle combat target setting
if (COMBAT_SETTINGS && COMBATSTYLE_ENABLED && companion.isAlerted) {
if (DEBUGGING)
REX::INFO("ActionCompanions_Internal: Combat Target - Setting target for companion {}...", comp->GetDisplayFullName());
// Set target for the companion if in combat
if (companion.isAlerted) {
auto enemyDataCopy = ActorTracking::GetEnemyData();
RE::Actor* enemyToTarget = nullptr;
switch (COMBATSTYLE_TARGET) {
case 0: { // closest target
float closestDistance = FLT_MAX;
for (auto& enemyData : enemyDataCopy) {
// Go over enemyData.distance to find the shortest one
if (enemyData.distanceToPlayer < closestDistance) {
closestDistance = enemyData.distanceToPlayer;
enemyToTarget = enemyData.actor;
}
}
break;
}
case 1: { // Lowest threat target
float lowestThreat = FLT_MAX;
for (auto& enemyData : enemyDataCopy) {
// Go over enemyData.threatLevel to find a LOW tier one
if (enemyData.tier == ENEMY_TIER::LOW) {
enemyToTarget = enemyData.actor;
} else if (enemyData.tier == ENEMY_TIER::MEDIUM && lowestThreat > 1.0f) {
lowestThreat = 1.0f;
enemyToTarget = enemyData.actor;
} else if (enemyData.tier == ENEMY_TIER::HIGH && lowestThreat > 2.0f) {
lowestThreat = 2.0f;
enemyToTarget = enemyData.actor;
}
}
break;
}
case 2: { // Highest threat target
float highestThreat = -1.0f;
for (auto& enemyData : enemyDataCopy) {
// Go over enemyData.threatLevel to find a HIGH tier one
if (enemyData.tier == ENEMY_TIER::HIGH) {
enemyToTarget = enemyData.actor;
break; // highest possible, break immediately
} else if (enemyData.tier == ENEMY_TIER::MEDIUM && highestThreat < 2.0f) {
highestThreat = 2.0f;
enemyToTarget = enemyData.actor;
} else if (enemyData.tier == ENEMY_TIER::LOW && highestThreat < 1.0f) {
highestThreat = 1.0f;
enemyToTarget = enemyData.actor;
}
}
break;
}
}
// Set the target
comp->currentCombatTarget = enemyToTarget ? enemyToTarget->As<RE::Actor>() : nullptr;
comp->UpdateCombat();
}
}
// Finally act on based on flags if not in power armor
// Use Stimpak idle if used
if (usedStimpak && idleToPlay && !RE::PowerArmor::ActorInPowerArmor(*comp)) {
// Play Stimpak idle
if (IsActorRaceHumanoid_Internal(comp)) {
if (comp && comp->currentProcess) {
comp->currentProcess->PlayIdle(*comp, idleToPlay, nullptr);
continue;
}
}
}
// Flee combat if needed
if (fleeCombat) {
// Flee combat to safe location
if (comp && comp->currentProcess) {
// Calculate a flee location AI_FLEE_DISTANCE units away from current position
float minDist = AI_FLEE_DISTANCE * 0.5f;
float maxDist = AI_FLEE_DISTANCE * 1.5f;
float fleeFromDist = minDist + static_cast<float>(std::rand()) / RAND_MAX * (maxDist - minDist);
float fleeToDist = fleeFromDist + static_cast<float>(std::rand()) / RAND_MAX * (maxDist - minDist);
// InitiateFlee(TESObjectREFR* a_fleeRef, bool a_runonce, bool a_knows, bool a_combatMode,
// TESObjectCELL* a_cell, TESObjectREFR* a_ref, float a_fleeFromDist, float a_fleeToDist)
auto* fleeTarget = comp->currentCombatTarget.get().get();
if (!fleeTarget) {
fleeTarget = player;
}
comp->InitiateFlee(fleeTarget, false, false, true, nullptr, nullptr, fleeFromDist, fleeToDist);
continue;
}
}
// Continue early if the companion is commanded or not following at the moment
if (IsActorCommanded_Internal(comp) || companion.followerState != FOLLOWER_STATE::FOLLOWER_STATE_FOLLOW) {
if (DEBUGGING)
REX::INFO("ActionCompanions_Internal: Follow, Distance, Speed and Stuck - Companion {} is currently not following, skipping.", comp->GetDisplayFullName());
// Remove from movement task list
MovementSystem::RemoveCompanionTask(comp);
continue;
}
// Adjust follow distances according to settings and interior/exterior
if (FOLLOW_SETTINGS && AI_DISTANCE_ENABLED) {
// Adjust actor follower distance AV based on interior/exterior
if (companion.followerDistance != AI_FOLLOW_DISTANCE_INTERIORS && g_isInInterior) {
if (DEBUGGING)
REX::INFO("ActionCompanions_Internal: Follow Distance - Setting interior follow distance for companion {}...", comp->GetDisplayFullName());
companion.actor->SetActorValue(*g_actorValueFollowerDistance, AI_FOLLOW_DISTANCE_INTERIORS);
} else if (companion.followerDistance != AI_FOLLOW_DISTANCE_GENERAL && !g_isInInterior) {
if (DEBUGGING)
REX::INFO("ActionCompanions_Internal: Follow Distance - Setting exterior follow distance for companion {}...", comp->GetDisplayFullName());
companion.actor->SetActorValue(*g_actorValueFollowerDistance, AI_FOLLOW_DISTANCE_GENERAL);
}
}
// Handle companion speed adjustments based on distance to player
if (FOLLOW_SETTINGS && AI_SPEED_ENABLED) {
auto speedMultAV = g_actorValueSingleton->speedMult;
float currentSpeedMult = companion.actor->GetActorValue(*speedMultAV);
// Companion is far away from player, increase speed (default 1500.0f)
if (companion.distanceToPlayer > g_globalComDistFarVal->value && currentSpeedMult < AI_FOLLOW_SPEED_FAR) {
comp->ModActorValue(RE::ACTOR_VALUE_MODIFIER::kTemporary, *speedMultAV, AI_FOLLOW_SPEED_FAR);
// Companion is at medium distance, set speed to medium (default 1000.0f)
} else if (companion.distanceToPlayer > g_globalComDistMediumVal->value && currentSpeedMult < AI_FOLLOW_SPEED_MEDIUM) {
comp->ModActorValue(RE::ACTOR_VALUE_MODIFIER::kTemporary, *speedMultAV, AI_FOLLOW_SPEED_MEDIUM);
// Companion is near the player, set speed to normal (default 500.0f)
} else {
comp->ModActorValue(RE::ACTOR_VALUE_MODIFIER::kTemporary, *speedMultAV, AI_FOLLOW_SPEED_NEAR);
}
}
// Add or remove from movement task list for stuck checking
if (FOLLOW_SETTINGS && AI_STUCK_ENABLED) {
// Add the companion to the movement task list for the next UPDATE_INTERVAL seconds
if (DEBUGGING)
REX::INFO("ActionCompanions_Internal: Stuck Check - Adding companion {} to movement task list for stuck checking.", comp->GetDisplayFullName());
MovementSystem::AddCompanionTask(comp, UPDATE_INTERVAL);
} else {
// Remove from movement task list
MovementSystem::RemoveCompanionTask(comp);
}
// Handle lost behaviour or stuck for more than 1 update (teleport to player)
if (FOLLOW_SETTINGS && AI_STUCK_ENABLED && (companion.lost || companion.distanceToPlayer > (AI_FOLLOW_DISTANCE_FAR * 2.0f))) {
if (DEBUGGING)
REX::INFO("ActionCompanions_Internal: Lost - Companion {} is lost - teleporting to player!", comp->GetDisplayFullName());
if (player) {
auto playerPos = player->GetPosition();
auto compPos = comp->GetPosition();
// Calculate the angle from player to companion's current position
float dx = compPos.x - playerPos.x;
float dy = compPos.y - playerPos.y;
float angle = std::atan2(dy, dx); // angle from player to companion
// Use 75% of the current distance
float currentDistance = std::sqrt(dx * dx + dy * dy);
float radius = currentDistance * 0.75f;
// Teleport companion to new position
RE::NiPoint3 newPos;
newPos.x = player->GetPosition().x + radius * std::cos(angle);
newPos.y = player->GetPosition().y + radius * std::sin(angle);
// Find a good Z position
newPos.z = player->GetPosition().z; // start with the player's Z
// Check runtime module for version-specific handling
if (MODULE_NAME == "CCBCL.dll") {
// Use the original version-specific code (keep collision checks / navmesh scans)
RE::CFilter filter;
filter.filter = player->GetCollisionFilter().filter;
// Get the xy position to a close object (position, filter, radiant steps, scan distance, move up distance)
RE::NiPoint3 closePos = GetPointXY_Internal(newPos, filter, 100.0f, 500.0f, 60.0f);
// Get ground Z at new position + 1.0f
newPos.z = GetPointZ_Internal(newPos, filter, 100.0f, 500.0f) + 1.0f; // Scan 100 up, 500 down
} else {
// Simpler fallback for other runtimes to avoid crashes
// Keep player's Z and rely on 75% radius XY placement (avoid GetPointZ_Internal/collision calls)
// newPos.z is already set to player's Z above.
}
// Nudge any running idles or stances to stop them
if (comp->currentProcess)
comp->currentProcess->StopCurrentIdle(comp, true, true);
// Set new position
comp->SetPosition(newPos, true);
}
continue;
}
// Handle overshoot behaviour (change follower AVs for distance temporarily)
if (FOLLOW_SETTINGS && AI_STUCK_ENABLED && companion.overshoot) {
if (DEBUGGING)
REX::INFO("ActionCompanions_Internal: Overshoot - Companion {} handling overshoot behaviour...", comp->GetDisplayFullName());
// Store original follower state
auto originalFollowerState = companion.actor->GetActorValue(*g_actorValueFollowerState);
// Ensure the companion is in FOLLOW state and restore exact state after delay
// the original may be 0 shortly after loading a save, so only restore if it was FOLLOW
if (static_cast<int>(originalFollowerState) == FOLLOWER_STATE::FOLLOWER_STATE_FOLLOW) {
// Tell the comapnion to wait and stop it in its tracks
companion.actor->SetActorValue(*g_actorValueFollowerState, FOLLOWER_STATE::FOLLOWER_STATE_WAIT);
// Schedule CCB_OneShotTimer to reset the overshoot flag after 1 second
auto resetAVTimer = std::make_shared<CCB_OneShotTimer>();
int delaySecs = 1;
// Pass all variables to keep them alive in the lambda
resetAVTimer->Start(delaySecs, [resetAVTimer, comp, originalFollowerState, delaySecs]() {
if (comp) {
if (DEBUGGING)
REX::INFO("ActionCompanions_Internal: Overshoot - Resetting overshoot status for companion {} after {}s duration.", comp->GetDisplayFullName(), delaySecs);
// Check in case the companion was removed in the meantime
comp->SetActorValue(*g_actorValueFollowerState, originalFollowerState);
ActorTracking::SetActorOvershootStatusFast(comp, false);
}
resetAVTimer->Cancel(); // optional cleanup
});
}
continue;
}
}
}
// Help Add item from actor's inventory
RE::BGSInventoryItem* ActorAddInventoryItem_Internal(RE::Actor* actor, RE::TESForm* itemForm, std::int32_t count) {
if (!actor || !itemForm || count <= 0)
return nullptr;
auto* invList = actor->inventoryList;
if (!invList) {
if (DEBUGGING)
REX::WARN("ActorAddInventoryItem_Internal: Actor inventory list is null");
return nullptr;
}
auto* itemObject = itemForm->As<RE::TESBoundObject>();
actor->AddObjectToContainer(itemObject, nullptr, 1, nullptr, RE::ITEM_REMOVE_REASON::kStoreContainer);
// Find and return the added item
for (auto& item : invList->data) {
// The item.object field is a RE::TESBoundObject*. We must compare it to our
// successfully cast itemObject to find the correct entry.
if (item.object == itemObject) {
// You are adding 'count' items. This item should have a count >= 'count'.
if (item.GetCount() >= count) {
// Return a pointer to the found item in the inventory data structure
return &item;
}
}
}
return nullptr;
}
// Help remove item from actor's inventory
void ActorRemoveInventoryItem_Internal(RE::Actor* actor, RE::TESForm* itemForm, std::int32_t count) {
if (!actor || !itemForm)
return;
auto* invList = actor->inventoryList;
if (!invList) {
if (DEBUGGING)
REX::WARN("RemoveActorInventoryItem_Internal: Actor inventory list is null");
return;
}
// Create RemoveItemData
RE::TESObjectREFR::RemoveItemData data(itemForm, count);
data.reason = RE::ITEM_REMOVE_REASON::kNone;
// Remove item
auto result = actor->RemoveItem(data);
}
// Helper function to adjust chatter frequency
void AdjustChatterFrequency_Internal(std::vector<TrackedActorData> companionData) {
if (companionData.empty())
return;
for (auto companion : companionData) {
auto* comp = companion.actor;
if (!comp)
return;
// Get current idle chatter AV values
auto* idleChatterMinAV = g_actorValueSingleton->idleChatterTimeMin;
auto* idleChatterMaxAV = g_actorValueSingleton->idleChatterTimeMAx;
auto idleChatterMin = comp->GetActorValue(*idleChatterMinAV);
auto idleChatterMax = comp->GetActorValue(*idleChatterMaxAV);
auto idleChatterBaseMin = comp->GetBaseActorValue(*idleChatterMinAV);
auto idleChatterBaseMax = comp->GetBaseActorValue(*idleChatterMaxAV);
float targetMin = 0.0f;
float targetMax = 0.0f;
// Adjust based on sneaking status
if (comp->IsSneaking()) {
targetMin = idleChatterBaseMin * CHATTER_MULTIPLIER_SNEAK;
targetMax = idleChatterBaseMax * CHATTER_MULTIPLIER_SNEAK;
} else {
targetMin = idleChatterBaseMin * CHATTER_MULTIPLIER;
targetMax = idleChatterBaseMax * CHATTER_MULTIPLIER;
}
// Apply changes if different from current
if (std::abs(idleChatterMin - targetMin) > 0.1f) {
comp->SetActorValue(*idleChatterMinAV, targetMin);
}
if (std::abs(idleChatterMax - targetMax) > 0.1f) {
comp->SetActorValue(*idleChatterMaxAV, targetMax);
}
}
}
// Helper function to set companion combat AI parameters
void AdjustCombatStyle_Internal(std::vector<TrackedActorData> companionData) {
if (companionData.empty())
return;
for (auto& companion : companionData) {
auto* comp = companion.actor;
if (!comp)
continue;
auto combatStyle = comp->GetCombatStyle();
if (!combatStyle)
return;
/* // General
if (DEBUGGING) REX::INFO("SetCompanionCombatAI_Internal: Setting combat style for companion {}", comp->GetDisplayFullName());
if (DEBUGGING) REX::INFO(" - Current Offensive Multiplier: {}", combatStyle->generalData.offensiveMult);
if (DEBUGGING) REX::INFO(" - Current Defensive Multiplier: {}", combatStyle->generalData.defensiveMult);
if (DEBUGGING) REX::INFO(" - Current Ranged Score Multiplier: {}", combatStyle->generalData.rangedScoreMult);
if (DEBUGGING) REX::INFO(" - Current Melee Score Multiplier: {}", combatStyle->generalData.meleeScoreMult);
// Ranged
if (DEBUGGING) REX::INFO(" - Current Ranged Adjust Range Multiplier: {}", combatStyle->longRangeData.adjustRangeMult);
if (DEBUGGING) REX::INFO(" - Current Ranged Crouch Multiplier: {}", combatStyle->longRangeData.crouchMult);
if (DEBUGGING) REX::INFO(" - Current Ranged Strafe Multiplier: {}", combatStyle->longRangeData.strafeMult);
if (DEBUGGING) REX::INFO(" - Current Ranged Wait Multiplier: {}", combatStyle->longRangeData.waitMult);
if (DEBUGGING) REX::INFO(" - Current Ranged Accuracy Multiplier: {}", combatStyle->rangedData.accuracyMult);
// Close-Quarters
if (DEBUGGING) REX::INFO(" - Current Close Fallback Multiplier: {}", combatStyle->closeRangeData.fallbackMult);
if (DEBUGGING) REX::INFO(" - Current Close Circle Multiplier: {}", combatStyle->closeRangeData.circleMult);
if (DEBUGGING) REX::INFO(" - Current Close Disengage Probability: {}", combatStyle->closeRangeData.disengageProbability);
if (DEBUGGING) REX::INFO(" - Current Close Flank Variance Multiplier: {}", combatStyle->closeRangeData.flankVarianceMult);
if (DEBUGGING) REX::INFO(" - Current Close Throw Max Targets: {}", combatStyle->closeRangeData.throwMaxTargets);
// Cover
if (DEBUGGING) REX::INFO(" - Current Cover Search Distance Multiplier: {}", combatStyle->coverData.coverSearchDistanceMult); */
// Apply new settings from INI
if (combatStyle->generalData.offensiveMult != COMBATSTYLE_OFFENSIVE && COMBATSTYLE_OFFENSIVE != 1.0f)
combatStyle->generalData.offensiveMult = COMBATSTYLE_OFFENSIVE;
if (combatStyle->generalData.defensiveMult != COMBATSTYLE_DEFENSIVE && COMBATSTYLE_DEFENSIVE != 1.0f)
combatStyle->generalData.defensiveMult = COMBATSTYLE_DEFENSIVE;
if (combatStyle->generalData.rangedScoreMult != COMBATSTYLE_RANGED_WEAPON && COMBATSTYLE_RANGED_WEAPON != 1.0f)
combatStyle->generalData.rangedScoreMult = COMBATSTYLE_RANGED_WEAPON;
if (combatStyle->generalData.meleeScoreMult != COMBATSTYLE_MELEE_WEAPON && COMBATSTYLE_MELEE_WEAPON != 1.0f)
combatStyle->generalData.meleeScoreMult = COMBATSTYLE_MELEE_WEAPON;
// Ranged
if (combatStyle->longRangeData.adjustRangeMult != COMBATSTYLE_RANGED_ADJUSTMENT && COMBATSTYLE_RANGED_ADJUSTMENT != 1.0f)
combatStyle->longRangeData.adjustRangeMult = COMBATSTYLE_RANGED_ADJUSTMENT;
if (combatStyle->longRangeData.crouchMult != COMBATSTYLE_RANGED_CROUCHING && COMBATSTYLE_RANGED_CROUCHING != 1.0f)
combatStyle->longRangeData.crouchMult = COMBATSTYLE_RANGED_CROUCHING;
if (combatStyle->longRangeData.strafeMult != COMBATSTYLE_RANGED_STRAFE && COMBATSTYLE_RANGED_STRAFE != 1.0f)
combatStyle->longRangeData.strafeMult = COMBATSTYLE_RANGED_STRAFE;
if (combatStyle->longRangeData.waitMult != COMBATSTYLE_RANGED_WAITING && COMBATSTYLE_RANGED_WAITING != 1.0f)
combatStyle->longRangeData.waitMult = COMBATSTYLE_RANGED_WAITING;
if (combatStyle->rangedData.accuracyMult != COMBATSTYLE_RANGED_ACCURACY && COMBATSTYLE_RANGED_ACCURACY != 1.0f)
combatStyle->rangedData.accuracyMult = COMBATSTYLE_RANGED_ACCURACY;
// Close-Quarters
if (combatStyle->closeRangeData.fallbackMult != COMBATSTYLE_CLOSE_FALLBACK && COMBATSTYLE_CLOSE_FALLBACK != 1.0f)
combatStyle->closeRangeData.fallbackMult = COMBATSTYLE_CLOSE_FALLBACK;
if (combatStyle->closeRangeData.circleMult != COMBATSTYLE_CLOSE_CIRCLE && COMBATSTYLE_CLOSE_CIRCLE != 1.0f)
combatStyle->closeRangeData.circleMult = COMBATSTYLE_CLOSE_CIRCLE;
if (combatStyle->closeRangeData.disengageProbability != COMBATSTYLE_CLOSE_DISENGAGE && COMBATSTYLE_CLOSE_DISENGAGE != 1.0f)
combatStyle->closeRangeData.disengageProbability = COMBATSTYLE_CLOSE_DISENGAGE;
if (combatStyle->closeRangeData.flankVarianceMult != COMBATSTYLE_CLOSE_FLANK && COMBATSTYLE_CLOSE_FLANK != 1.0f)
combatStyle->closeRangeData.flankVarianceMult = COMBATSTYLE_CLOSE_FLANK;
if (combatStyle->closeRangeData.throwMaxTargets != COMBATSTYLE_CLOSE_THROW_GRENADE && COMBATSTYLE_CLOSE_THROW_GRENADE != 1.0f)
combatStyle->closeRangeData.throwMaxTargets = COMBATSTYLE_CLOSE_THROW_GRENADE;
// Cover
if (combatStyle->coverData.coverSearchDistanceMult != COMBATSTYLE_COVER_DISTANCE && COMBATSTYLE_COVER_DISTANCE != 1.0f)
combatStyle->coverData.coverSearchDistanceMult = COMBATSTYLE_COVER_DISTANCE;
/* if (DEBUGGING) REX::INFO("SetCompanionCombatAI_Internal: Combat style for companion {} updated.", comp->GetDisplayFullName());
if (DEBUGGING) REX::INFO(" - New Offensive Multiplier: {}", combatStyle->generalData.offensiveMult);
if (DEBUGGING) REX::INFO(" - New Defensive Multiplier: {}", combatStyle->generalData.defensiveMult);
if (DEBUGGING) REX::INFO(" - New Ranged Score Multiplier: {}", combatStyle->generalData.rangedScoreMult);
if (DEBUGGING) REX::INFO(" - New Melee Score Multiplier: {}", combatStyle->generalData.meleeScoreMult);
// Ranged
if (DEBUGGING) REX::INFO(" - New Ranged Adjust Range Multiplier: {}", combatStyle->longRangeData.adjustRangeMult);
if (DEBUGGING) REX::INFO(" - New Ranged Crouch Multiplier: {}", combatStyle->longRangeData.crouchMult);
if (DEBUGGING) REX::INFO(" - New Ranged Strafe Multiplier: {}", combatStyle->longRangeData.strafeMult);
if (DEBUGGING) REX::INFO(" - New Ranged Wait Multiplier: {}", combatStyle->longRangeData.waitMult);
if (DEBUGGING) REX::INFO(" - New Ranged Accuracy Multiplier: {}", combatStyle->rangedData.accuracyMult);
// Close-Quarters
if (DEBUGGING) REX::INFO(" - New Close Fallback Multiplier: {}", combatStyle->closeRangeData.fallbackMult);
if (DEBUGGING) REX::INFO(" - New Close Circle Multiplier: {}", combatStyle->closeRangeData.circleMult);
if (DEBUGGING) REX::INFO(" - New Close Disengage Probability: {}", combatStyle->closeRangeData.disengageProbability);
if (DEBUGGING) REX::INFO(" - New Close Flank Variance Multiplier: {}", combatStyle->closeRangeData.flankVarianceMult);
if (DEBUGGING) REX::INFO(" - New Close Throw Max Targets: {}", combatStyle->closeRangeData.throwMaxTargets);
// Cover
if (DEBUGGING) REX::INFO(" - New Cover Search Distance Multiplier: {}", combatStyle->coverData.coverSearchDistanceMult); */
}
}
// Helper function to adjust global follow distances
void AdjustGlobalFollowDistances_Internal() {
if (g_globalComDistNearVal && g_globalComDistNearVal->value != static_cast<float>(AI_FOLLOW_DISTANCE_NEAR)) {
g_globalComDistNearVal->value = static_cast<float>(AI_FOLLOW_DISTANCE_NEAR);
}
if (g_globalComDistMediumVal && g_globalComDistMediumVal->value != static_cast<float>(AI_FOLLOW_DISTANCE_MEDIUM)) {
g_globalComDistMediumVal->value = static_cast<float>(AI_FOLLOW_DISTANCE_MEDIUM);
}
if (g_globalComDistFarVal && g_globalComDistFarVal->value != static_cast<float>(AI_FOLLOW_DISTANCE_FAR)) {
g_globalComDistFarVal->value = static_cast<float>(AI_FOLLOW_DISTANCE_FAR);
}
}
// Helper function to safely test if aiData is accessible (SEH-protected)
bool AIAccessTest_Internal(RE::TESNPC* npc) {
if (!npc)
return false;
#ifdef _MSC_VER
__try {
// Test read to verify memory is accessible
[[maybe_unused]] volatile auto testRead = npc->aiData.useAggroRadius;
return true; // Access succeeded
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false; // Access violation occurred
}
#else
// Non-MSVC: assume it's safe (no SEH available)
return true;
#endif
}
// Helper function to apply the aggression settings to the companions current package
void ApplyAIAggression_Internal(std::vector<TrackedActorData> companionData) {
// Go over our companions
for (auto& companion : companionData) {
auto* actor = companion.actor;
if (!actor)
continue;
// Change the actor value to be aggressive
if (static_cast<int>(actor->GetActorValue(*g_actorValueFollowerStance)) != FOLLOWER_STANCE::FOLLOWER_STANCE_AGGRESSIVE) {
actor->SetActorValue(*g_actorValueFollowerStance, static_cast<float>(FOLLOWER_STANCE::FOLLOWER_STANCE_AGGRESSIVE));
if (DEBUGGING)
REX::INFO("ApplyAIAggression_Internal: Setting follower stance to aggressive {} for companion {}.", static_cast<float>(FOLLOWER_STANCE::FOLLOWER_STANCE_AGGRESSIVE), actor->GetDisplayFullName());
}
if (companion.isAlerted)
continue; // do not apply when already in combat
auto* npc = actor->GetNPC();
if (!npc)
continue;
// Test if aiData is safely accessible
if (!AIAccessTest_Internal(npc)) {
continue;
}
// Log current aiData settings
if (npc) {
// commented this section as it is not sure the packages can be detected properly
// Disable when the standard follower package is not running and AI_AGGRESSION_ALL is false
//if (actor->currentProcess && actor->currentProcess->GetPackageThatIsRunning() && g_packFollowersCompanion && actor->currentProcess->GetPackageThatIsRunning()->GetFormID() != g_packFollowersCompanion->GetFormID() && !AI_AGGRESSION_ALL) {
// npc->aiData.useAggroRadius = static_cast<std::uint32_t>(0);
// npc->aiData.aggroRadius[0] = static_cast<std::uint16_t>(0);
// npc->aiData.aggroRadius[1] = static_cast<std::uint16_t>(0);
// npc->aiData.aggroRadius[2] = static_cast<std::uint16_t>(0);
// continue;
//}
// Changing settings at runtime if they do not match the INI settings
if (npc->aiData.useAggroRadius != static_cast<std::uint32_t>(AI_AGGRESSION_ENABLED)
|| npc->aiData.aggroRadius[0] != static_cast<std::uint16_t>(AI_AGGRESSION_RADIUS0)
|| npc->aiData.aggroRadius[1] != static_cast<std::uint16_t>(AI_AGGRESSION_RADIUS1)
|| npc->aiData.aggroRadius[2] != static_cast<std::uint16_t>(AI_AGGRESSION_RADIUS2)) {
npc->aiData.useAggroRadius = static_cast<std::uint32_t>(AI_AGGRESSION_ENABLED);
npc->aiData.aggroRadius[0] = static_cast<std::uint16_t>(AI_AGGRESSION_RADIUS0);
npc->aiData.aggroRadius[1] = static_cast<std::uint16_t>(AI_AGGRESSION_RADIUS1);
npc->aiData.aggroRadius[2] = static_cast<std::uint16_t>(AI_AGGRESSION_RADIUS2);
}
}
}
}
// Helper function to apply perks to companion actors
void ApplyPerksToCompanions_Internal(std::vector<TrackedActorData> companionData) {
// Go over our companions
for (auto& companion : companionData) {
auto* actor = companion.actor;
if (!actor)
continue;
// Apply each perk from the global list
for (auto perk : g_perkList) {
if (perk && actor->GetPerkRank(perk) <= 0) {
actor->AddPerk(perk);
if (DEBUGGING)
REX::INFO("ApplyPerksToCompanions: Adding perk {} for companion {}", perk->GetFormEditorID(), actor->GetDisplayFullName());
}
}
}
}
void ApplyKeywordsToCompanions_Internal(std::vector<TrackedActorData> companionData) {