/
ai_basenpc.h
3124 lines (2445 loc) · 107 KB
/
ai_basenpc.h
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
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Base NPC character with AI
//
//=============================================================================//
#ifndef AI_BASENPC_H
#define AI_BASENPC_H
#ifdef _WIN32
#pragma once
#endif
#include "simtimer.h"
#include "basecombatcharacter.h"
#include "ai_debug.h"
#include "ai_default.h"
#include "ai_schedule.h"
#include "ai_condition.h"
#include "ai_component.h"
#include "ai_task.h"
#include "ai_movetypes.h"
#include "ai_navtype.h"
#include "ai_namespaces.h"
#include "ai_npcstate.h"
#include "ai_hull.h"
#include "ai_utils.h"
#include "ai_moveshoot.h"
#include "entityoutput.h"
#include "utlvector.h"
#include "activitylist.h"
#include "bitstring.h"
#include "ai_basenpc.h"
#include "ai_navgoaltype.h" //GoalType_t enum
#include "eventlist.h"
#include "soundent.h"
#include "ai_navigator.h"
#include "tier1/functors.h"
#define PLAYER_SQUADNAME "player_squad"
class CAI_Schedule;
class CAI_Network;
class CAI_Route;
class CAI_Hint;
class CAI_Node;
class CAI_Navigator;
class CAI_Pathfinder;
class CAI_Senses;
class CAI_Enemies;
class CAI_Squad;
class CAI_Expresser;
class CAI_BehaviorBase;
class CAI_GoalEntity;
class CAI_Motor;
class CAI_MoveProbe;
class CAI_LocalNavigator;
class CAI_TacticalServices;
class CVarBitVec;
class CAI_ScriptedSequence;
class CSceneEntity;
class CBaseGrenade;
class CBaseDoor;
class CBasePropDoor;
struct AI_Waypoint_t;
class AI_Response;
class CBaseFilter;
typedef CBitVec<MAX_CONDITIONS> CAI_ScheduleBits;
// Used to control optimizations mostly dealing with pathfinding for NPCs
extern ConVar ai_strong_optimizations;
extern bool AIStrongOpt( void );
// AI_MONITOR_FOR_OSCILLATION defaults to OFF. If you build with this ON, you can flag
// NPC's and monitor them to detect oscillations in their schedule (circular logic and conditions bugs)
// DO NOT SHIP WITH THIS ON!
#undef AI_MONITOR_FOR_OSCILLATION
//=============================================================================
//
// Constants & enumerations
//
//=============================================================================
#define TURRET_CLOSE_RANGE 200
#define TURRET_MEDIUM_RANGE 500
#define COMMAND_GOAL_TOLERANCE 48 // 48 inches.
#define TIME_CARE_ABOUT_DAMAGE 3.0
#define ITEM_PICKUP_TOLERANCE 48.0f
// Max's of the box used to search for a weapon to pick up. 45x45x~8 ft.
#define WEAPON_SEARCH_DELTA Vector( 540, 540, 100 )
enum Interruptability_t
{
GENERAL_INTERRUPTABILITY,
DAMAGEORDEATH_INTERRUPTABILITY,
DEATH_INTERRUPTABILITY
};
//-------------------------------------
// Memory
//-------------------------------------
#define MEMORY_CLEAR 0
#define bits_MEMORY_PROVOKED ( 1 << 0 )// right now only used for houndeyes.
#define bits_MEMORY_INCOVER ( 1 << 1 )// npc knows it is in a covered position.
#define bits_MEMORY_SUSPICIOUS ( 1 << 2 )// Ally is suspicious of the player, and will move to provoked more easily
#define bits_MEMORY_TASK_EXPENSIVE ( 1 << 3 )// NPC has completed a task which is considered costly, so don't do another task this frame
//#define bits_MEMORY_ ( 1 << 4 )
#define bits_MEMORY_PATH_FAILED ( 1 << 5 )// Failed to find a path
#define bits_MEMORY_FLINCHED ( 1 << 6 )// Has already flinched
//#define bits_MEMORY_ ( 1 << 7 )
#define bits_MEMORY_TOURGUIDE ( 1 << 8 )// I have been acting as a tourguide.
//#define bits_MEMORY_ ( 1 << 9 )//
#define bits_MEMORY_LOCKED_HINT ( 1 << 10 )//
//#define bits_MEMORY_ ( 1 << 12 )
#define bits_MEMORY_TURNING ( 1 << 13 )// Turning, don't interrupt me.
#define bits_MEMORY_TURNHACK ( 1 << 14 )
#define bits_MEMORY_HAD_ENEMY ( 1 << 15 )// Had an enemy
#define bits_MEMORY_HAD_PLAYER ( 1 << 16 )// Had player
#define bits_MEMORY_HAD_LOS ( 1 << 17 )// Had LOS to enemy
#define bits_MEMORY_MOVED_FROM_SPAWN ( 1 << 18 )// Has moved since spawning.
#define bits_MEMORY_CUSTOM4 ( 1 << 28 ) // NPC-specific memory
#define bits_MEMORY_CUSTOM3 ( 1 << 29 ) // NPC-specific memory
#define bits_MEMORY_CUSTOM2 ( 1 << 30 ) // NPC-specific memory
#define bits_MEMORY_CUSTOM1 ( 1 << 31 ) // NPC-specific memory
//-------------------------------------
// Spawn flags
//-------------------------------------
#define SF_NPC_WAIT_TILL_SEEN ( 1 << 0 ) // spawnflag that makes npcs wait until player can see them before attacking.
#define SF_NPC_GAG ( 1 << 1 ) // no idle noises from this npc
#define SF_NPC_FALL_TO_GROUND ( 1 << 2 ) // used my NPC_Maker
#define SF_NPC_DROP_HEALTHKIT ( 1 << 3 ) // Drop a healthkit upon death
#define SF_NPC_START_EFFICIENT ( 1 << 4 ) // Set into efficiency mode from spawn
// ( 1 << 5 )
// ( 1 << 6 )
#define SF_NPC_WAIT_FOR_SCRIPT ( 1 << 7 ) // spawnflag that makes npcs wait to check for attacking until the script is done or they've been attacked
#define SF_NPC_LONG_RANGE ( 1 << 8 ) // makes npcs look far and relaxes weapon range limit
#define SF_NPC_FADE_CORPSE ( 1 << 9 ) // Fade out corpse after death
#define SF_NPC_ALWAYSTHINK ( 1 << 10 ) // Simulate even when player isn't in PVS.
#define SF_NPC_TEMPLATE ( 1 << 11 ) // This NPC will be used as a template by an npc_maker -- do not spawn.
#define SF_NPC_ALTCOLLISION ( 1 << 12 )
#define SF_NPC_NO_WEAPON_DROP ( 1 << 13 ) // This NPC will not actually drop a weapon that can be picked up
#define SF_NPC_NO_PLAYER_PUSHAWAY ( 1 << 14 )
// ( 1 << 15 )
// !! Flags above ( 1 << 15 ) are reserved for NPC sub-classes
//-------------------------------------
//
// Return codes from CanPlaySequence.
//
//-------------------------------------
enum CanPlaySequence_t
{
CANNOT_PLAY = 0, // Can't play for any number of reasons.
CAN_PLAY_NOW, // Can play the script immediately.
CAN_PLAY_ENQUEUED, // Can play the script after I finish playing my current script.
};
//-------------------------------------
// Weapon holstering
//-------------------------------------
enum DesiredWeaponState_t
{
DESIREDWEAPONSTATE_IGNORE = 0,
DESIREDWEAPONSTATE_HOLSTERED,
DESIREDWEAPONSTATE_HOLSTERED_DESTROYED, // Put the weapon away, then destroy it.
DESIREDWEAPONSTATE_UNHOLSTERED,
DESIREDWEAPONSTATE_CHANGING,
DESIREDWEAPONSTATE_CHANGING_DESTROY, // Destroy the weapon when this change is complete.
};
//-------------------------------------
//
// Efficiency modes
//
//-------------------------------------
enum AI_Efficiency_t
{
// Run at full tilt
AIE_NORMAL,
// Run decision process less often
AIE_EFFICIENT,
// Run decision process even less often, ignore other NPCs
AIE_VERY_EFFICIENT,
// Run decision process even less often, ignore other NPCs
AIE_SUPER_EFFICIENT,
// Don't run at all
AIE_DORMANT,
};
enum AI_MoveEfficiency_t
{
AIME_NORMAL,
AIME_EFFICIENT,
};
//-------------------------------------
//
// Sleep state
//
//-------------------------------------
enum AI_SleepState_t
{
AISS_AWAKE,
AISS_WAITING_FOR_THREAT,
AISS_WAITING_FOR_PVS,
AISS_WAITING_FOR_INPUT,
AISS_AUTO_PVS,
AISS_AUTO_PVS_AFTER_PVS, // Same as AUTO_PVS, except doesn't activate until/unless the NPC is IN the player's PVS.
};
#define AI_SLEEP_FLAGS_NONE 0x00000000
#define AI_SLEEP_FLAG_AUTO_PVS 0x00000001
#define AI_SLEEP_FLAG_AUTO_PVS_AFTER_PVS 0x00000002
//-------------------------------------
//
// Debug bits
//
//-------------------------------------
enum DebugBaseNPCBits_e
{
bits_debugDisableAI = 0x00000001, // disable AI
bits_debugStepAI = 0x00000002, // step AI
};
//-------------------------------------
//
// Base Sentence index for behaviors
//
//-------------------------------------
enum SentenceIndex_t
{
SENTENCE_BASE_BEHAVIOR_INDEX = 1000,
};
#ifdef AI_MONITOR_FOR_OSCILLATION
struct AIScheduleChoice_t
{
float m_flTimeSelected;
CAI_Schedule *m_pScheduleSelected;
};
#endif//AI_MONITOR_FOR_OSCILLATION
#define MARK_TASK_EXPENSIVE() \
if ( GetOuter() ) \
{ \
GetOuter()->Remember( bits_MEMORY_TASK_EXPENSIVE ); \
}
//=============================================================================
//
// Types used by CAI_BaseNPC
//
//=============================================================================
struct AIScheduleState_t
{
int iCurTask;
TaskStatus_e fTaskStatus;
float timeStarted;
float timeCurTaskStarted;
AI_TaskFailureCode_t taskFailureCode;
int iTaskInterrupt;
bool bTaskRanAutomovement;
bool bTaskUpdatedYaw;
bool bScheduleWasInterrupted;
DECLARE_SIMPLE_DATADESC();
};
// -----------------------------------------
// An entity that this NPC can't reach
// -----------------------------------------
struct UnreachableEnt_t
{
EHANDLE hUnreachableEnt; // Entity that's unreachable
float fExpireTime; // Time to forget this information
Vector vLocationWhenUnreachable;
DECLARE_SIMPLE_DATADESC();
};
//=============================================================================
// SCRIPTED NPC INTERACTIONS
//=============================================================================
// -----------------------------------------
// Scripted NPC interaction flags
// -----------------------------------------
#define SCNPC_FLAG_TEST_OTHER_ANGLES ( 1 << 1 )
#define SCNPC_FLAG_TEST_OTHER_VELOCITY ( 1 << 2 )
#define SCNPC_FLAG_LOOP_IN_ACTION ( 1 << 3 )
#define SCNPC_FLAG_NEEDS_WEAPON_ME ( 1 << 4 )
#define SCNPC_FLAG_NEEDS_WEAPON_THEM ( 1 << 5 )
#define SCNPC_FLAG_DONT_TELEPORT_AT_END_ME ( 1 << 6 )
#define SCNPC_FLAG_DONT_TELEPORT_AT_END_THEM ( 1 << 7 )
// -----------------------------------------
// Scripted NPC interaction trigger methods
// -----------------------------------------
enum
{
SNPCINT_CODE = 0,
SNPCINT_AUTOMATIC_IN_COMBAT = 1,
};
// -----------------------------------------
// Scripted NPC interaction loop breaking trigger methods
// -----------------------------------------
#define SNPCINT_LOOPBREAK_ON_DAMAGE ( 1 << 1 )
#define SNPCINT_LOOPBREAK_ON_FLASHLIGHT_ILLUM ( 1 << 2 )
// -----------------------------------------
// Scripted NPC interaction anim phases
// -----------------------------------------
enum
{
SNPCINT_ENTRY = 0,
SNPCINT_SEQUENCE,
SNPCINT_EXIT,
SNPCINT_NUM_PHASES
};
struct ScriptedNPCInteraction_Phases_t
{
string_t iszSequence;
int iActivity;
DECLARE_SIMPLE_DATADESC();
};
// Allowable delta from the desired dynamic scripted sequence point
#define DSS_MAX_DIST 6
#define DSS_MAX_ANGLE_DIFF 4
// Interaction Logic States
enum
{
NPCINT_NOT_RUNNING = 0,
NPCINT_RUNNING_ACTIVE, // I'm in an interaction that I initiated
NPCINT_RUNNING_PARTNER, // I'm in an interaction that was initiated by the other NPC
NPCINT_MOVING_TO_MARK, // I'm moving to a position to do an interaction
};
#define NPCINT_NONE -1
#define MAXTACLAT_IGNORE -1
// -----------------------------------------
// A scripted interaction between NPCs
// -----------------------------------------
struct ScriptedNPCInteraction_t
{
ScriptedNPCInteraction_t()
{
iszInteractionName = NULL_STRING;
iFlags = 0;
iTriggerMethod = SNPCINT_CODE;
iLoopBreakTriggerMethod = 0;
vecRelativeOrigin = vec3_origin;
bValidOnCurrentEnemy = false;
flDelay = 5.0;
flDistSqr = (DSS_MAX_DIST * DSS_MAX_DIST);
flNextAttemptTime = 0;
iszMyWeapon = NULL_STRING;
iszTheirWeapon = NULL_STRING;
for ( int i = 0; i < SNPCINT_NUM_PHASES; i++)
{
sPhases[i].iszSequence = NULL_STRING;
sPhases[i].iActivity = ACT_INVALID;
}
}
// Fill out these when passing to AddScriptedNPCInteraction
string_t iszInteractionName;
int iFlags;
int iTriggerMethod;
int iLoopBreakTriggerMethod;
Vector vecRelativeOrigin; // (forward, right, up)
QAngle angRelativeAngles;
Vector vecRelativeVelocity; // Desired relative velocity of the other NPC
float flDelay; // Delay before interaction can be used again
float flDistSqr; // Max distance sqr from the relative origin the NPC is allowed to be to trigger
string_t iszMyWeapon; // Classname of the weapon I'm holding, if any
string_t iszTheirWeapon; // Classname of the weapon my interaction partner is holding, if any
ScriptedNPCInteraction_Phases_t sPhases[SNPCINT_NUM_PHASES];
// These will be filled out for you in AddScriptedNPCInteraction
VMatrix matDesiredLocalToWorld; // Desired relative position / angles of the other NPC
bool bValidOnCurrentEnemy;
float flNextAttemptTime;
DECLARE_SIMPLE_DATADESC();
};
//=============================================================================
//
// Utility functions
//
//=============================================================================
Vector VecCheckToss ( CBaseEntity *pEdict, Vector vecSpot1, Vector vecSpot2, float flHeightMaxRatio, float flGravityAdj, bool bRandomize, Vector *vecMins = NULL, Vector *vecMaxs = NULL );
Vector VecCheckToss ( CBaseEntity *pEntity, ITraceFilter *pFilter, Vector vecSpot1, Vector vecSpot2, float flHeightMaxRatio, float flGravityAdj, bool bRandomize, Vector *vecMins = NULL, Vector *vecMaxs = NULL );
Vector VecCheckThrow( CBaseEntity *pEdict, const Vector &vecSpot1, Vector vecSpot2, float flSpeed, float flGravityAdj = 1.0f, Vector *vecMins = NULL, Vector *vecMaxs = NULL );
extern Vector g_vecAttackDir;
bool FBoxVisible ( CBaseEntity *pLooker, CBaseEntity *pTarget );
bool FBoxVisible ( CBaseEntity *pLooker, CBaseEntity *pTarget, Vector &vecTargetOrigin, float flSize = 0.0 );
// FIXME: move to utils?
float DeltaV( float v0, float v1, float d );
float ChangeDistance( float flInterval, float flGoalDistance, float flGoalVelocity, float flCurVelocity, float flIdealVelocity, float flAccelRate, float &flNewDistance, float &flNewVelocity );
//=============================================================================
//
// class CAI_Manager
//
// Central location for components of the AI to operate across all AIs without
// iterating over the global list of entities.
//
//=============================================================================
class CAI_Manager
{
public:
CAI_Manager();
CAI_BaseNPC ** AccessAIs();
int NumAIs();
void AddAI( CAI_BaseNPC *pAI );
void RemoveAI( CAI_BaseNPC *pAI );
bool FindAI( CAI_BaseNPC *pAI ) { return ( m_AIs.Find( pAI ) != m_AIs.InvalidIndex() ); }
private:
enum
{
MAX_AIS = 256
};
typedef CUtlVector<CAI_BaseNPC *> CAIArray;
CAIArray m_AIs;
};
//-------------------------------------
extern CAI_Manager g_AI_Manager;
//=============================================================================
//
// class CAI_BaseNPC
//
//=============================================================================
class CAI_BaseNPC : public CBaseCombatCharacter,
public CAI_DefMovementSink
{
DECLARE_CLASS( CAI_BaseNPC, CBaseCombatCharacter );
public:
//-----------------------------------------------------
//
// Initialization, cleanup, serialization, identity
//
CAI_BaseNPC();
~CAI_BaseNPC();
//---------------------------------
DECLARE_DATADESC();
DECLARE_SERVERCLASS();
virtual int Save( ISave &save );
virtual int Restore( IRestore &restore );
virtual void OnRestore();
void SaveConditions( ISave &save, const CAI_ScheduleBits &conditions );
void RestoreConditions( IRestore &restore, CAI_ScheduleBits *pConditions );
bool ShouldSavePhysics() { return false; }
virtual unsigned int PhysicsSolidMaskForEntity( void ) const;
virtual bool KeyValue( const char *szKeyName, const char *szValue );
//---------------------------------
virtual void PostConstructor( const char *szClassname );
virtual void Activate( void );
virtual void Precache( void ); // derived calls at start of Spawn()
virtual bool CreateVPhysics();
virtual void NPCInit( void ); // derived calls after Spawn()
void NPCInitThink( void );
virtual void PostNPCInit() {};// called after NPC_InitThink
virtual void StartNPC( void );
virtual bool IsTemplate( void );
virtual void CleanupOnDeath( CBaseEntity *pCulprit = NULL, bool bFireDeathOutput = true );
virtual void UpdateOnRemove( void );
virtual int UpdateTransmitState();
//---------------------------------
// Component creation factories
//
// The master call, override if you introduce new component types. Call base first
virtual bool CreateComponents();
// Components defined by the base AI class
virtual CAI_Senses * CreateSenses();
virtual CAI_MoveProbe * CreateMoveProbe();
virtual CAI_Motor * CreateMotor();
virtual CAI_LocalNavigator *CreateLocalNavigator();
virtual CAI_Navigator * CreateNavigator();
virtual CAI_Pathfinder *CreatePathfinder();
virtual CAI_TacticalServices *CreateTacticalServices();
//---------------------------------
virtual bool IsNPC( void ) const { return true; }
//---------------------------------
void TestPlayerPushing( CBaseEntity *pPlayer );
void CascadePlayerPush( const Vector &push, const Vector &pushOrigin );
void NotifyPushMove();
public:
//-----------------------------------------------------
//
// AI processing - thinking, schedule selection and task running
//
//-----------------------------------------------------
void CallNPCThink( void );
// Thinking, including core thinking, movement, animation
virtual void NPCThink( void );
// Core thinking (schedules & tasks)
virtual void RunAI( void );// core ai function!
// Called to gather up all relevant conditons
virtual void GatherConditions( void );
// Called immediately prior to schedule processing
virtual void PrescheduleThink( void );
// Called immediately after schedule processing
virtual void PostscheduleThink( void ) { return; };
// Notification that the current schedule, if any, is ending and a new one is being selected
virtual void OnScheduleChange( void );
// Notification that a new schedule is about to run its first task
virtual void OnStartSchedule( int scheduleType ) {};
// This function implements a decision tree for the NPC. It is responsible for choosing the next behavior (schedule)
// based on the current conditions and state.
virtual int SelectSchedule( void );
virtual int SelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode );
// After the schedule has been selected, it will be processed by this function so child NPC classes can
// remap base schedules into child-specific behaviors
virtual int TranslateSchedule( int scheduleType );
virtual void StartTask( const Task_t *pTask );
virtual void RunTask( const Task_t *pTask );
void ClearTransientConditions();
virtual void HandleAnimEvent( animevent_t *pEvent );
virtual bool IsInterruptable();
virtual void OnStartScene( void ) {} // Called when an NPC begins a cine scene (useful for clean-up)
virtual bool ShouldPlayerAvoid( void );
virtual void SetPlayerAvoidState( void );
virtual void PlayerPenetratingVPhysics( void );
virtual bool ShouldAlwaysThink();
void ForceGatherConditions() { m_bForceConditionsGather = true; SetEfficiency( AIE_NORMAL ); } // Force an NPC out of PVS to call GatherConditions on next think
virtual float LineOfSightDist( const Vector &vecDir = vec3_invalid, float zEye = FLT_MAX );
virtual void MakeTracer( const Vector &vecTracerSrc, const trace_t &tr, int iTracerType );
virtual const char *GetTracerType( void );
virtual void DoImpactEffect( trace_t &tr, int nDamageType );
enum
{
NEXT_SCHEDULE = LAST_SHARED_SCHEDULE,
NEXT_TASK = LAST_SHARED_TASK,
NEXT_CONDITION = LAST_SHARED_CONDITION,
};
protected:
// Used by derived classes to chain a task to a task that might not be the
// one they are currently handling:
void ChainStartTask( int task, float taskData = 0 ) { Task_t tempTask = { task, taskData }; StartTask( (const Task_t *)&tempTask ); }
void ChainRunTask( int task, float taskData = 0 ) { Task_t tempTask = { task, taskData }; RunTask( (const Task_t *) &tempTask ); }
void StartTaskOverlay();
void RunTaskOverlay();
void EndTaskOverlay();
virtual void PostRunStopMoving();
bool CheckPVSCondition();
private:
bool CanThinkRebalance();
void RebalanceThinks();
bool PreNPCThink();
void PostNPCThink();
bool PreThink( void );
void PerformSensing();
void CheckOnGround( void );
void MaintainSchedule( void );
void RunAnimation( void );
void PostRun( void );
void PerformMovement();
void PostMovement();
virtual int StartTask ( Task_t *pTask ) { DevMsg( "Called wrong StartTask()\n" ); StartTask( (const Task_t *)pTask ); return 0; } // to ensure correct signature in derived classes
virtual int RunTask ( Task_t *pTask ) { DevMsg( "Called wrong RunTask()\n" ); RunTask( (const Task_t *)pTask ); return 0; } // to ensure correct signature in derived classes
public:
//-----------------------------------------------------
//
// Schedules & tasks
//
//-----------------------------------------------------
void SetSchedule( CAI_Schedule *pNewSchedule );
bool SetSchedule( int localScheduleID );
void SetDefaultFailSchedule( int failSchedule ) { m_failSchedule = failSchedule; }
void ClearSchedule( const char *szReason );
CAI_Schedule * GetCurSchedule() { return m_pSchedule; }
bool IsCurSchedule( int schedId, bool fIdeal = true );
virtual CAI_Schedule *GetSchedule(int localScheduleID);
virtual int GetLocalScheduleId( int globalScheduleID ) { return AI_IdIsLocal( globalScheduleID ) ? globalScheduleID : GetClassScheduleIdSpace()->ScheduleGlobalToLocal( globalScheduleID ); }
virtual int GetGlobalScheduleId( int localScheduleID ) { return AI_IdIsGlobal( localScheduleID ) ? localScheduleID : GetClassScheduleIdSpace()->ScheduleLocalToGlobal( localScheduleID ); }
float GetTimeScheduleStarted() const { return m_ScheduleState.timeStarted; }
//---------------------------------
const Task_t* GetTask( void );
int TaskIsRunning( void );
virtual void TaskFail( AI_TaskFailureCode_t );
void TaskFail( const char *pszGeneralFailText ) { TaskFail( MakeFailCode( pszGeneralFailText ) ); }
void TaskComplete( bool fIgnoreSetFailedCondition = false );
void TaskInterrupt() { m_ScheduleState.iTaskInterrupt++; }
void ClearTaskInterrupt() { m_ScheduleState.iTaskInterrupt = 0; }
int GetTaskInterrupt() const { return m_ScheduleState.iTaskInterrupt; }
void TaskMovementComplete( void );
inline int TaskIsComplete( void ) { return (GetTaskStatus() == TASKSTATUS_COMPLETE); }
virtual const char *TaskName(int taskID);
float GetTimeTaskStarted() const { return m_ScheduleState.timeCurTaskStarted; }
virtual int GetLocalTaskId( int globalTaskId) { return GetClassScheduleIdSpace()->TaskGlobalToLocal( globalTaskId ); }
virtual const char *GetSchedulingErrorName() { return "CAI_BaseNPC"; }
protected:
static bool LoadSchedules(void);
virtual bool LoadedSchedules(void);
virtual void BuildScheduleTestBits( void );
//---------------------------------
// This is the main call to select/translate a schedule
virtual CAI_Schedule *GetNewSchedule( void );
virtual CAI_Schedule *GetFailSchedule( void );
//---------------------------------
virtual bool CanFlinch( void );
virtual void CheckFlinches( void );
virtual void PlayFlinchGesture( void );
int SelectFlinchSchedule( void );
virtual bool IsAllowedToDodge( void );
bool IsInChoreo() const;
private:
// This function maps the type through TranslateSchedule() and then retrieves the pointer
// to the actual CAI_Schedule from the database of schedules available to this class.
CAI_Schedule * GetScheduleOfType( int scheduleType );
bool FHaveSchedule( void );
bool FScheduleDone ( void );
CAI_Schedule * ScheduleInList( const char *pName, CAI_Schedule **pList, int listCount );
int GetScheduleCurTaskIndex() const { return m_ScheduleState.iCurTask; }
inline int IncScheduleCurTaskIndex();
inline void ResetScheduleCurTaskIndex();
void NextScheduledTask ( void );
bool IsScheduleValid ( void );
bool ShouldSelectIdealState( void );
// Selecting the ideal state
NPC_STATE SelectIdleIdealState();
NPC_STATE SelectAlertIdealState();
NPC_STATE SelectScriptIdealState();
// Various schedule selections based on NPC_STATE
int SelectIdleSchedule();
int SelectAlertSchedule();
int SelectCombatSchedule();
virtual int SelectDeadSchedule();
int SelectScriptSchedule();
int SelectInteractionSchedule();
void OnStartTask( void ) { SetTaskStatus( TASKSTATUS_RUN_MOVE_AND_TASK ); }
void SetTaskStatus( TaskStatus_e status ) { m_ScheduleState.fTaskStatus = status; }
TaskStatus_e GetTaskStatus() const { return m_ScheduleState.fTaskStatus; }
void DiscardScheduleState();
//---------------------------------
CAI_Schedule * m_pSchedule;
int m_IdealSchedule;
AIScheduleState_t m_ScheduleState;
int m_failSchedule; // Schedule type to choose if current schedule fails
bool m_bDoPostRestoreRefindPath;
bool m_bUsingStandardThinkTime;
float m_flLastRealThinkTime;
int m_iFrameBlocked;
bool m_bInChoreo;
static int gm_iNextThinkRebalanceTick;
static float gm_flTimeLastSpawn;
static int gm_nSpawnedThisFrame;
protected: // pose parameters
int m_poseAim_Pitch;
int m_poseAim_Yaw;
int m_poseMove_Yaw;
virtual void PopulatePoseParameters( void );
public:
inline bool HasPoseMoveYaw() { return ( m_poseMove_Yaw >= 0 ); }
// Return the stored pose parameter for "move_yaw"
inline int LookupPoseMoveYaw() { return m_poseMove_Yaw; }
//-----------------------------------------------------
//
// Hooks for CAI_Behaviors, *if* derived class supports them
//
//-----------------------------------------------------
template <class BEHAVIOR_TYPE>
bool GetBehavior( BEHAVIOR_TYPE **ppBehavior )
{
CAI_BehaviorBase **ppBehaviors = AccessBehaviors();
*ppBehavior = NULL;
for ( int i = 0; i < NumBehaviors(); i++ )
{
*ppBehavior = dynamic_cast<BEHAVIOR_TYPE *>(ppBehaviors[i]);
if ( *ppBehavior )
return true;
}
return false;
}
virtual CAI_BehaviorBase *GetRunningBehavior() { return NULL; }
virtual bool ShouldAcceptGoal( CAI_BehaviorBase *pBehavior, CAI_GoalEntity *pGoal ) { return true; }
virtual void OnClearGoal( CAI_BehaviorBase *pBehavior, CAI_GoalEntity *pGoal ) {}
// Notification that the status behavior ability to select schedules has changed.
// Return "true" to signal a schedule interrupt is desired
virtual bool OnBehaviorChangeStatus( CAI_BehaviorBase *pBehavior, bool fCanFinishSchedule ) { return false; }
private:
virtual CAI_BehaviorBase ** AccessBehaviors() { return NULL; }
virtual int NumBehaviors() { return 0; }
public:
//-----------------------------------------------------
//
// Conditions
//
//-----------------------------------------------------
virtual const char* ConditionName(int conditionID);
virtual void RemoveIgnoredConditions ( void );
void SetCondition( int iCondition /*, bool state = true*/ );
bool HasCondition( int iCondition );
bool HasCondition( int iCondition, bool bUseIgnoreConditions );
bool HasInterruptCondition( int iCondition );
bool HasConditionsToInterruptSchedule( int nLocalScheduleID );
void ClearCondition( int iCondition );
void ClearConditions( int *pConditions, int nConditions );
void SetIgnoreConditions( int *pConditions, int nConditions );
void ClearIgnoreConditions( int *pConditions, int nConditions );
bool ConditionInterruptsCurSchedule( int iCondition );
bool ConditionInterruptsSchedule( int schedule, int iCondition );
void SetCustomInterruptCondition( int nCondition );
bool IsCustomInterruptConditionSet( int nCondition );
void ClearCustomInterruptCondition( int nCondition );
void ClearCustomInterruptConditions( void );
bool ConditionsGathered() const { return m_bConditionsGathered; }
const CAI_ScheduleBits &AccessConditionBits() const { return m_Conditions; }
CAI_ScheduleBits & AccessConditionBits() { return m_Conditions; }
bool DidChooseEnemy() const { return !m_bSkippedChooseEnemy; }
private:
CAI_ScheduleBits m_Conditions;
CAI_ScheduleBits m_CustomInterruptConditions; //Bit string assembled by the schedule running, then
//modified by leaf classes to suit their needs
CAI_ScheduleBits m_ConditionsPreIgnore;
CAI_ScheduleBits m_InverseIgnoreConditions;
bool m_bForceConditionsGather;
bool m_bConditionsGathered;
bool m_bSkippedChooseEnemy;
public:
//-----------------------------------------------------
//
// NPC State
//
//-----------------------------------------------------
inline void SetIdealState( NPC_STATE eIdealState );
inline NPC_STATE GetIdealState();
virtual NPC_STATE SelectIdealState( void );
void SetState( NPC_STATE State );
virtual bool ShouldGoToIdleState( void ) { return ( false ); }
virtual void OnStateChange( NPC_STATE OldState, NPC_STATE NewState ) {/*Base class doesn't care*/};
NPC_STATE GetState( void ) { return m_NPCState; }
AI_Efficiency_t GetEfficiency() const { return m_Efficiency; }
void SetEfficiency( AI_Efficiency_t efficiency ) { m_Efficiency = efficiency; }
AI_MoveEfficiency_t GetMoveEfficiency() const { return m_MoveEfficiency; }
void SetMoveEfficiency( AI_MoveEfficiency_t efficiency ) { m_MoveEfficiency = efficiency; }
virtual void UpdateEfficiency( bool bInPVS );
void ForceDecisionThink() { m_flNextDecisionTime = 0; SetEfficiency( AIE_NORMAL ); }
bool IsFlaggedEfficient() const { return HasSpawnFlags( SF_NPC_START_EFFICIENT ); }
AI_SleepState_t GetSleepState() const { return m_SleepState; }
void SetSleepState( AI_SleepState_t sleepState ) { m_SleepState = sleepState; }
void AddSleepFlags( int flags ) { m_SleepFlags |= flags; }
void RemoveSleepFlags( int flags ) { m_SleepFlags &= ~flags; }
bool HasSleepFlags( int flags ) { return (m_SleepFlags & flags) == flags; }
void UpdateSleepState( bool bInPVS );
virtual void Wake( bool bFireOutput = true );
void Sleep();
bool WokeThisTick() const;
//---------------------------------
NPC_STATE m_NPCState; // npc's current state
float m_flLastStateChangeTime;
private:
NPC_STATE m_IdealNPCState; // npc should change to this state
AI_Efficiency_t m_Efficiency;
AI_MoveEfficiency_t m_MoveEfficiency;
float m_flNextDecisionTime;
AI_SleepState_t m_SleepState;
int m_SleepFlags;
float m_flWakeRadius;
bool m_bWakeSquad;
int m_nWakeTick;
public:
//-----------------------------------------------------
//
// Activities
//
//-----------------------------------------------------
Activity TranslateActivity( Activity idealActivity, Activity *pIdealWeaponActivity = NULL );
Activity NPC_TranslateActivity( Activity eNewActivity );
Activity GetActivity( void ) { return m_Activity; }
virtual void SetActivity( Activity NewActivity );
Activity GetIdealActivity( void ) { return m_IdealActivity; }
void SetIdealActivity( Activity NewActivity );
void ResetIdealActivity( Activity newIdealActivity );
void SetSequenceByName( const char *szSequence );
void SetSequenceById( int iSequence );
Activity GetScriptCustomMoveActivity( void );
int GetScriptCustomMoveSequence( void );
Activity GetStoppedActivity( void );
inline bool HaveSequenceForActivity( Activity activity );
inline bool IsActivityStarted(void);
virtual bool IsActivityFinished( void );
virtual bool IsActivityMovementPhased( Activity activity );
virtual void OnChangeActivity( Activity eNewActivity );
void MaintainActivity(void);
void ResetActivity(void) { m_Activity = ACT_RESET; }
void SetActivityAndSequence(Activity NewActivity, int iSequence, Activity translatedActivity, Activity weaponActivity);
private:
void AdvanceToIdealActivity(void);
void ResolveActivityToSequence(Activity NewActivity, int &iSequence, Activity &translatedActivity, Activity &weaponActivity);
Activity m_Activity; // Current animation state
Activity m_translatedActivity; // Current actual translated animation
Activity m_IdealActivity; // Desired animation state
int m_nIdealSequence; // Desired animation sequence
Activity m_IdealTranslatedActivity; // Desired actual translated animation state
Activity m_IdealWeaponActivity; // Desired weapon animation state
CNetworkVar(int, m_iDeathPose );
CNetworkVar(int, m_iDeathFrame );
public:
//-----------------------------------------------------
//
// Senses
//
//-----------------------------------------------------
CAI_Senses * GetSenses() { return m_pSenses; }
const CAI_Senses * GetSenses() const { return m_pSenses; }
void SetDistLook( float flDistLook );
virtual bool QueryHearSound( CSound *pSound );
virtual bool QuerySeeEntity( CBaseEntity *pEntity, bool bOnlyHateOrFearIfNPC = false );
virtual void OnLooked( int iDistance );
virtual void OnListened();
virtual void OnSeeEntity( CBaseEntity *pEntity ) {}
// If true, AI will try to see this entity regardless of distance.
virtual bool ShouldNotDistanceCull() { return false; }
virtual int GetSoundInterests( void );
virtual int GetSoundPriority( CSound *pSound );
CSound * GetLoudestSoundOfType( int iType );
virtual CSound * GetBestSound( int validTypes = ALL_SOUNDS );
virtual CSound * GetBestScent( void );
virtual float HearingSensitivity( void ) { return 1.0; }
virtual bool ShouldIgnoreSound( CSound * ) { return false; }
bool SoundIsVisible( CSound *pSound );
protected:
virtual void ClearSenseConditions( void );