Oolite
Loading...
Searching...
No Matches
AI Class Reference

#include <AI.h>

Inheritance diagram for AI:
Collaboration diagram for AI:

Instance Methods

(NSString *) - name
(NSString *) - associatedJS
(NSString *) - state
(void) - setStateMachine:withJSScript:
(void) - setState:
(void) - setStateMachine:afterDelay:
(void) - setState:afterDelay:
(id) - initWithStateMachine:andState:
(ShipEntity *) - owner
(void) - setOwner:
(void) - preserveCurrentStateMachine
(void) - restorePreviousStateMachine
(BOOL) - hasSuspendedStateMachines
(void) - exitStateMachineWithMessage:
(NSUInteger) - stackDepth
(void) - reactToMessage:context:
(void) - takeAction:
(void) - think
(void) - message:
(void) - dropMessage:
(NSSet *) - pendingMessages
(void) - debugDumpPendingMessages
(void) - setNextThinkTime:
(OOTimeAbsolute) - nextThinkTime
(void) - setThinkTimeInterval:
(OOTimeDelta) - thinkTimeInterval
(void) - clearStack
(void) - clearAllData
(void) - dumpState
(id) - init [implementation]
(void) - dealloc [implementation]
(NSString *) - descriptionComponents [implementation]
(NSString *) - shortDescriptionComponents [implementation]
(void) - reportStackOverflow [implementation]
(void) - performDeferredCall:withObject:afterDelay: [implementation]
(void) - refreshOwnerDesc [implementation]
(void) - directSetStateMachine:name: [implementation]
(void) - directSetState: [implementation]
(NSDictionary *) - loadStateMachine:jsName: [implementation]
(NSDictionary *) - cleanHandlers:forState:stateMachine: [implementation]
(NSArray *) - cleanActions:forHandler:state:stateMachine: [implementation]
Instance Methods inherited from OOWeakRefObject
(id) - weakSelf
(id) - weakRetain [implementation]
(void) - weakRefDied: [implementation]
Instance Methods inherited from <OOWeakReferenceSupport>
(id) - OO_RETURNS_RETAINED

Class Methods

(AI *) + currentlyRunningAI
(NSString *) + currentlyRunningAIDescription
(void) + deferredCallTrampolineWithInfo: [implementation]

Private Attributes

id _owner
NSString * ownerDesc
NSDictionary * stateMachine
NSString * stateMachineName
NSString * currentState
NSMutableSet * pendingMessages
NSMutableArray * aiStack
OOTimeAbsolute nextThinkTime
OOTimeDelta thinkTimeInterval
NSString * jsScript

Additional Inherited Members

Protected Attributes inherited from OOWeakRefObject
OOWeakReference * weakSelf

Detailed Description

Definition at line 35 of file AI.h.

Method Documentation

◆ associatedJS

- (NSString *) associatedJS

Definition at line 334 of file AI.m.

335{
336 return [stateMachine objectForKey:@"jsScript"];
337}

References associatedJS.

Referenced by associatedJS, and ShipEntity(LoadRestore)::savedShipDictionaryWithContext:.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ cleanActions:forHandler:state:stateMachine:

- (NSArray *) cleanActions: (NSArray*) actions
forHandler: (NSString*) handlerKey
state: (NSString*) stateKey
stateMachine: (NSString*) smName 
implementation

Provided by category AI(OOPrivate).

Definition at line 802 of file AI.m.

802 :(NSArray*)actions forHandler:(NSString*)handlerKey state:(NSString*)stateKey stateMachine:(NSString*)smName
803{
804 NSString* action = nil;
805 NSRange spaceRange;
806 NSString* selector = nil;
807 id aliasedSelector = nil;
808 NSMutableArray* result = nil;
809 static NSSet* whitelist = nil;
810 static NSDictionary* aliases = nil;
811 NSArray* whitelistArray1 = nil;
812 NSArray* whitelistArray2 = nil;
813
814 if (whitelist == nil) {
815 whitelistArray1 = [[ResourceManager whitelistDictionary] oo_arrayForKey:@"ai_methods"];
816 if (whitelistArray1 == nil)
817 whitelistArray1 = [NSArray array];
818 whitelistArray2 = [[ResourceManager whitelistDictionary] oo_arrayForKey:@"ai_and_action_methods"];
819 if (whitelistArray2 != nil)
820 whitelistArray1 = [whitelistArray1 arrayByAddingObjectsFromArray:whitelistArray2];
821
822 whitelist = [[NSSet alloc] initWithArray:whitelistArray1];
823 aliases = [[[ResourceManager whitelistDictionary] oo_dictionaryForKey:@"ai_method_aliases"] retain];
824 }
825
826 result = [NSMutableArray arrayWithCapacity:[actions count]];
827 foreach (action, actions) {
828 if (![action isKindOfClass:[NSString class]]) {
829 OOLogWARN(@"ai.invalidFormat.action", @"An action in handler \"%@\" for state \"%@\" in AI \"%@\" is not a string, ignoring.", handlerKey, stateKey, smName);
830 continue;
831 }
832
833 // Trim spaces from beginning and end.
834 action = [action stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
835
836 // Cut off parameters.
837 spaceRange = [action rangeOfString:@" "];
838 if (spaceRange.location == NSNotFound)
839 selector = action;
840 else
841 selector = [action substringToIndex:spaceRange.location];
842
843 // Look in alias table.
844 aliasedSelector = [aliases objectForKey:selector];
845 if (aliasedSelector != nil) {
846 if ([aliasedSelector isKindOfClass:[NSString class]]) {
847 // Change selector and action to use real method name.
848 selector = aliasedSelector;
849 if (spaceRange.location == NSNotFound)
850 action = aliasedSelector;
851 else
852 action = [aliasedSelector stringByAppendingString:[action substringFromIndex:spaceRange.location]];
853 } else if ([aliasedSelector isKindOfClass:[NSArray class]] && [aliasedSelector count] != 0) {
854 // Alias is complete expression, pretokenized in anticipation of a tokenized future.
855 action = [aliasedSelector componentsJoinedByString:@" "];
856 selector = [[aliasedSelector objectAtIndex:0] description];
857 }
858 }
859
860 // Check for selector in whitelist.
861 if (![whitelist containsObject:selector]) {
862 OOLog(@"ai.unpermittedMethod", @"Handler \"%@\" for state \"%@\" in AI \"%@\" uses \"%@\", which is not a permitted AI method.", handlerKey, stateKey, smName, selector);
863 continue;
864 }
865
866 [result addObject:action];
867 }
868
869 // Return immutable copy.
870 return [[result copy] autorelease];
871}
#define OOLogWARN(class, format,...)
Definition OOLogging.h:126
#define OOLog(class, format,...)
Definition OOLogging.h:84
unsigned count
return nil
NSDictionary * stateMachine
Definition AI.h:40
NSString * state()
Definition AI.m:339
NSDictionary * whitelistDictionary()

Referenced by AI(OOPrivate)::cleanHandlers:forState:stateMachine:.

Here is the caller graph for this function:

◆ cleanHandlers:forState:stateMachine:

- (NSDictionary *) cleanHandlers: (NSDictionary*) handlers
forState: (NSString*) stateKey
stateMachine: (NSString*) smName 
implementation

Provided by category AI(OOPrivate).

Definition at line 779 of file AI.m.

779 :(NSDictionary*)handlers forState:(NSString*)stateKey stateMachine:(NSString*)smName
780{
781 NSString* handlerKey = nil;
782 NSArray* handlerActions = nil;
783 NSMutableDictionary* result = nil;
784
785 result = [NSMutableDictionary dictionaryWithCapacity:[handlers count]];
786 foreachkey(handlerKey, handlers)
787 {
788 handlerActions = [handlers objectForKey:handlerKey];
789 if (![handlerActions isKindOfClass:[NSArray class]]) {
790 OOLogWARN(@"ai.invalidFormat.handler", @"Handler \"%@\" for state \"%@\" in AI \"%@\" is not an array, ignoring.", handlerKey, stateKey, smName);
791 continue;
792 }
793
794 handlerActions = [self cleanActions:handlerActions forHandler:handlerKey state:stateKey stateMachine:smName];
795 [result setObject:handlerActions forKey:handlerKey];
796 }
797
798 // Return immutable copy.
799 return [[result copy] autorelease];
800}
#define foreachkey(VAR, DICT)

Referenced by AI(OOPrivate)::loadStateMachine:jsName:.

Here is the caller graph for this function:

◆ clearAllData

- (void) clearAllData

Definition at line 609 of file AI.m.

610{
611 [aiStack removeAllObjects];
612 [pendingMessages removeAllObjects];
613
614 nextThinkTime += 36000.0; // should dealloc in under ten hours!
615}
OOTimeAbsolute nextThinkTime
Definition AI.m:586

References clearAllData, and nextThinkTime.

Referenced by clearAllData, PlayerEntity::resetAutopilotAI, ShipEntity::setAI:, and thinkTimeInterval.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ clearStack

- (void) clearStack

Definition at line 604 of file AI.m.

605{
606 [aiStack removeAllObjects];
607}

References clearStack.

Referenced by clearStack, WormholeEntity::suckInShip:, ShipEntity(AI)::switchAITo:, and thinkTimeInterval.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ currentlyRunningAI

+ (AI *) currentlyRunningAI

Definition at line 98 of file AI.m.

99{
100 return sCurrentlyRunningAI;
101}
static AI * sCurrentlyRunningAI
Definition AI.m:48

References currentlyRunningAI, and sCurrentlyRunningAI.

Referenced by currentlyRunningAI.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ currentlyRunningAIDescription

+ (NSString *) currentlyRunningAIDescription

Definition at line 103 of file AI.m.

104{
105 if (sCurrentlyRunningAI != nil) {
106 return [NSString stringWithFormat:@"%@ in state %@", [sCurrentlyRunningAI name], [sCurrentlyRunningAI state]];
107 } else {
108 return @"<no AI running>";
109 }
110}
Definition AI.h:35
NSString * name()
Definition AI.m:329

References currentlyRunningAIDescription, name, nil, sCurrentlyRunningAI, and state.

Referenced by currentlyRunningAIDescription.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ dealloc

- (void) dealloc
implementation

Reimplemented from OOWeakRefObject.

Definition at line 136 of file AI.m.

137{
138 if (sCurrentlyRunningAI == self) {
140 }
141
150
151 [super dealloc];
152}
#define DESTROY(x)
NSString * currentState
Definition AI.h:42
id _owner
Definition AI.h:37
NSMutableSet * pendingMessages
Definition AI.m:557
NSMutableArray * aiStack
Definition AI.h:45
NSString * ownerDesc
Definition AI.h:38
NSString * stateMachineName
Definition AI.h:41
NSString * jsScript
Definition AI.h:50

References _owner, aiStack, currentState, dealloc, OOWeakRefObject::dealloc, DESTROY, jsScript, nil, ownerDesc, pendingMessages, sCurrentlyRunningAI, stateMachine, and stateMachineName.

Referenced by dealloc.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ debugDumpPendingMessages

- (void) debugDumpPendingMessages

Definition at line 566 of file AI.m.

567{
568 NSArray* sortedMessages = nil;
569 NSString* displayMessages = nil;
570
571 if ([pendingMessages count] > 0) {
572 sortedMessages = [[pendingMessages allObjects] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
573 displayMessages = [sortedMessages componentsJoinedByString:@", "];
574 } else {
575 displayMessages = @"none";
576 }
577
578 OOLog(@"ai.debug.pendingMessages", @"Pending messages for AI %@: %@", [self descriptionComponents], displayMessages);
579}
NSString * descriptionComponents()
Definition AI.m:154

References count, debugDumpPendingMessages, descriptionComponents, nil, OOLog, and pendingMessages.

Referenced by debugDumpPendingMessages, and pendingMessages.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ deferredCallTrampolineWithInfo:

+ (void) deferredCallTrampolineWithInfo: (NSValue*) info
implementation

Provided by category AI(OOPrivate).

Definition at line 654 of file AI.m.

654 :(NSValue*)info
655{
656 OOAIDeferredCallTrampolineInfo infoStruct;
657
658 if (info != nil) {
659 assert(strcmp([info objCType], @encode(OOAIDeferredCallTrampolineInfo)) == 0);
660 [info getValue:&infoStruct];
661
662 [infoStruct.ai performSelector:infoStruct.selector withObject:infoStruct.parameter];
663
664 [infoStruct.ai release];
665 [infoStruct.parameter release];
666 }
667}

◆ descriptionComponents

- (NSString *) descriptionComponents
implementation

Definition at line 154 of file AI.m.

155{
156 return [NSString stringWithFormat:@"\"%@\" in state: \"%@\" for %@", stateMachineName, currentState, ownerDesc];
157}

References descriptionComponents.

Referenced by debugDumpPendingMessages, and descriptionComponents.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ directSetState:

- (void) directSetState: (NSString*) state
implementation

Provided by category AI(OOPrivate).

Definition at line 694 of file AI.m.

694 :(NSString*)state
695{
696 if (currentState != state) {
697 [currentState release];
698 currentState = [state copy];
699 }
700}

Referenced by restorePreviousStateMachine, setState:, and setStateMachine:withJSScript:.

Here is the caller graph for this function:

◆ directSetStateMachine:name:

- (void) directSetStateMachine: (NSDictionary*) newSM
name: (NSString*) name 
implementation

Provided by category AI(OOPrivate).

Definition at line 682 of file AI.m.

682 :(NSDictionary*)newSM name:(NSString*)name
683{
684 if (stateMachine != newSM) {
685 [stateMachine release];
686 stateMachine = [newSM copy];
687 }
688 if (stateMachineName != name) {
689 [stateMachineName release];
690 stateMachineName = [name copy];
691 }
692}

Referenced by restorePreviousStateMachine, and setStateMachine:withJSScript:.

Here is the caller graph for this function:

◆ dropMessage:

- (void) dropMessage: (NSString*) ms

Definition at line 552 of file AI.m.

552 :(NSString*)ms
553{
554 [pendingMessages removeObject:ms];
555}

◆ dumpState

- (void) dumpState

Definition at line 617 of file AI.m.

618{
619 OOLog(@"dumpState.ai", @"State machine name: %@", stateMachineName);
620 OOLog(@"dumpState.ai", @"Current state: %@", currentState);
621 OOLog(@"dumpState.ai", @"Next think time: %g", nextThinkTime);
622 OOLog(@"dumpState.ai", @"Next think interval: %g", thinkTimeInterval);
623}
OOTimeDelta thinkTimeInterval
Definition AI.m:599

References currentState, dumpState, nextThinkTime, OOLog, stateMachineName, and thinkTimeInterval.

Referenced by dumpState, and thinkTimeInterval.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ exitStateMachineWithMessage:

- (void) exitStateMachineWithMessage: (NSString*) message

Definition at line 268 of file AI.m.

268 :(NSString*)message
269{
270 if ([aiStack count] != 0) {
271 [self restorePreviousStateMachine];
272 if (message == nil)
273 message = @"RESTARTED";
274 [self reactToMessage:message context:@"suspended AI restart"];
275 }
276}

References aiStack, count, nil, reactToMessage:context:, and restorePreviousStateMachine.

Referenced by ShipEntity::behaviour_tractored:, ShipEntity::dumpItem:, ShipEntity::releaseCargoPodsDebris, ShipExitAI(), ShipExitAI(), and ShipEntity::update:.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ hasSuspendedStateMachines

- (BOOL) hasSuspendedStateMachines

Definition at line 263 of file AI.m.

264{
265 return [aiStack count] != 0;
266}

References hasSuspendedStateMachines.

Referenced by hasSuspendedStateMachines.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ init

- (id) init
implementation

Definition at line 112 of file AI.m.

113{
114 if ((self = [super init])) {
115 nextThinkTime = INFINITY; // don't think for a while
117
118 stateMachineName = @"<no AI>"; // no initial brain
119 }
120
121 return self;
122}
#define AI_THINK_INTERVAL
Definition AI.h:31
id init()
Definition AI.m:112

References AI_THINK_INTERVAL, init, nextThinkTime, stateMachineName, and thinkTimeInterval.

Referenced by init, and initWithStateMachine:andState:.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ initWithStateMachine:andState:

- (id) initWithStateMachine: (NSString*) smName
andState: (NSString*) stateName 

Definition at line 124 of file AI.m.

124 :(NSString*)smName andState:(NSString*)stateName
125{
126 if ((self = [self init])) {
127 if (smName != nil)
128 [self setStateMachine:smName withJSScript:@"oolite-nullAI.js"];
129 if (stateName != nil)
130 currentState = [stateName retain];
131 }
132
133 return self;
134}

References currentState, init, nil, and setStateMachine:withJSScript:.

Here is the call graph for this function:

◆ loadStateMachine:jsName:

- (NSDictionary *) loadStateMachine: (NSString*) smName
jsName: (NSString*) script 
implementation

Provided by category AI(OOPrivate).

Definition at line 702 of file AI.m.

702 :(NSString*)smName jsName:(NSString*)script
703{
704 NSDictionary* newSM = nil;
705 NSMutableDictionary* cleanSM = nil;
706 OOCacheManager* cacheMgr = [OOCacheManager sharedCache];
707 NSString* stateKey = nil;
708 NSDictionary* stateHandlers = nil;
709 NSAutoreleasePool* pool = nil;
710
711 if (![smName isEqualToString:@"nullAI.plist"]) {
712 // don't cache nullAI since they're different depending on associated JS AI
713 newSM = [cacheMgr objectForKey:smName inCache:@"AIs"];
714 if (newSM != nil && ![newSM isKindOfClass:[NSDictionary class]])
715 return nil; // catches use of @"nil" to indicate no AI found.
716 }
717
718 if (newSM == nil) {
719 pool = [[NSAutoreleasePool alloc] init];
720 OOLog(@"ai.load", @"Loading and sanitizing AI \"%@\"", smName);
722 OOLogIndentIf(@"ai.load");
723
724 @try {
725 // Load state machine and validate against whitelist.
726 NSString* aiPath = [ResourceManager pathForFileNamed:smName inFolder:@"AIs"];
727 if (aiPath != nil) {
728 newSM = OODictionaryFromFile(aiPath);
729 }
730 if (newSM == nil) {
731 [cacheMgr setObject:@"nil" forKey:smName inCache:@"AIs"];
732 NSString* fromString = @"";
733 if ([self state] != nil) {
734 fromString = [NSString stringWithFormat:@" from %@:%@", [self name], [self state]];
735 }
736 OOLog(@"ai.load.failed.unknownAI", @"Can't switch AI for %@%@ to \"%@\" - could not load file.", [[self owner] shortDescription], fromString, smName);
737 return nil;
738 }
739
740 cleanSM = [NSMutableDictionary dictionaryWithCapacity:[newSM count]];
741
742 foreachkey(stateKey, newSM)
743 {
744 stateHandlers = [newSM objectForKey:stateKey];
745 if (![stateHandlers isKindOfClass:[NSDictionary class]]) {
746 OOLogWARN(@"ai.invalidFormat.state", @"State \"%@\" in AI \"%@\" is not a dictionary, ignoring.", stateKey, smName);
747 continue;
748 }
749
750 stateHandlers = [self cleanHandlers:stateHandlers forState:stateKey stateMachine:smName];
751 [cleanSM setObject:stateHandlers forKey:stateKey];
752 }
753 [cleanSM setObject:script forKey:@"jsScript"];
754
755 // Make immutable.
756 newSM = [[cleanSM copy] autorelease];
757
758#if DEBUG_GRAPHVIZ
759 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"generate-ai-graphviz"]) {
760 GenerateGraphVizForAIStateMachine(newSM, smName);
761 }
762#endif
763
764 // Cache.
765 [cacheMgr setObject:newSM forKey:smName inCache:@"AIs"];
766 }
767 @finally {
769 }
770
771 [newSM retain];
772 [pool release];
773 [newSM autorelease];
774 }
775
776 return newSM;
777}
void OOLogPushIndent(void)
Definition OOLogging.m:301
void OOLogPopIndent(void)
Definition OOLogging.m:323
#define OOLogIndentIf(class)
Definition OOLogging.h:107
NSDictionary * OODictionaryFromFile(NSString *path)
ShipEntity * owner()
Definition AI.m:164
void setObject:forKey:inCache:(id inElement,[forKey] NSString *inKey,[inCache] NSString *inCacheKey)
id objectForKey:inCache:(NSString *inKey,[inCache] NSString *inCacheKey)
OOCacheManager * sharedCache()
NSString * pathForFileNamed:inFolder:(NSString *fileName,[inFolder] NSString *folderName)

Referenced by setStateMachine:withJSScript:.

Here is the caller graph for this function:

◆ message:

- (void) message: (NSString*) ms

Definition at line 536 of file AI.m.

536 :(NSString*)ms
537{
538 if ([[self owner] universalID] == NO_TARGET)
539 return; // don't think until launched
540
541 if (EXPECT_NOT([pendingMessages count] > 32)) {
542 // Generate the error, but don't crash Oolite! Fixes bug #18055 - Pending message overflow for thargoids, -> crash !
543 OOLogERR(@"ai.message.failed.overflow", @"AI message \"%@\" received by '%@' AI while pending messages stack full; message discarded. Pending messages:\n%@", ms, ownerDesc, pendingMessages);
544 } else {
545 if (pendingMessages == nil) {
546 pendingMessages = [[NSMutableSet alloc] init];
547 }
548 [pendingMessages addObject:ms];
549 }
550}
#define EXPECT_NOT(x)
#define OOLogERR(class, format,...)
Definition OOLogging.h:125
@ NO_TARGET
Definition OOTypes.h:169

References count, EXPECT_NOT, nil, NO_TARGET, OOLogERR, owner, ownerDesc, and pendingMessages.

Referenced by StationEntity::abortAllDockings, ShipEntity::acceptAsEscort:, StationEntity::acceptDockingClearanceRequestFrom:, StationEntity::autoDockShipsOnApproach, ShipEntity::behaviour_face_destination:, ShipEntity::behaviour_flee_target:, ShipEntity::behaviour_fly_from_destination:, ShipEntity::behaviour_fly_to_destination:, ShipEntity::behaviour_land_on_planet:, ShipEntity::broadcastAIMessage:, ShipEntity::checkForAegis, DockEntity::dockingInstructionsForShip:, ShipEntity::enterDock:, ShipEntity::enterWitchspace, ShipEntity::noteLostTarget, ShipEntity::noteTargetDestroyed:, StationEntity::sanityCheckShipsOnApproach, ShipEntity(PureAI)::scanForNearestShipMatchingPredicate:, ShipEntity::scoopUpProcess:processEvents:processMessages:, ShipEntity::sendAIMessage:, ShipEntity::setTargetToNearestStationIncludingHostiles:, ShipEntity(PureAI)::setTargetToPrimaryAggressor, ShipEntity::setTargetToSystemStation, WormholeEntity::suckInShip:, ShipEntity::transitionToAegisNone, ShipEntity::update:, StationEntity::update:, and ShipEntity::witchspaceLeavingEffects.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ name

- (NSString *) name

Definition at line 329 of file AI.m.

330{
331 return [[stateMachineName retain] autorelease];
332}

References name.

Referenced by currentlyRunningAIDescription, ShipEntity::hasNewAI, AI(OOPrivate)::loadStateMachine:jsName:, name, reactToMessage:context:, reportStackOverflow, ShipEntity(PureAI)::safeScriptActionOnTarget:, ShipEntity(LoadRestore)::savedShipDictionaryWithContext:, ShipEntity(PureAI)::scanForNearestShipMatchingPredicate:, ShipEntity(PureAI)::scriptActionOnTarget:, ShipGetProperty(), and ShipGetProperty().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ nextThinkTime

◆ owner

- (ShipEntity *) owner

Definition at line 164 of file AI.m.

165{
166 ShipEntity* owner = [_owner weakRefUnderlyingObject];
167 if (owner == nil) {
168 [_owner release];
169 _owner = nil;
170 }
171
172 return owner;
173}

References _owner, nil, and owner.

Referenced by message:, owner, preserveCurrentStateMachine, reactToMessage:context:, AI(OOPrivate)::refreshOwnerDesc, restorePreviousStateMachine, takeAction:, and think.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ pendingMessages

- (NSSet *) pendingMessages

References debugDumpPendingMessages, and pendingMessages.

Here is the call graph for this function:

◆ performDeferredCall:withObject:afterDelay:

- (void) performDeferredCall: (SEL) selector
withObject: (id) object
afterDelay: (NSTimeInterval) delay 
implementation

Provided by category AI(OOPrivate).

Definition at line 635 of file AI.m.

635 :(SEL)selector withObject:(id)object afterDelay:(NSTimeInterval)delay
636{
637 OOAIDeferredCallTrampolineInfo infoStruct;
638 NSValue* info = nil;
639
640 if (selector != NULL) {
641 infoStruct.ai = [self retain];
642 infoStruct.selector = selector;
643 infoStruct.parameter = object;
644
645 info = [[NSValue alloc] initWithBytes:&infoStruct objCType:@encode(OOAIDeferredCallTrampolineInfo)];
646
647 [[AI class] performSelector:@selector(deferredCallTrampolineWithInfo:)
648 withObject:info
649 afterDelay:delay];
650 [info release];
651 }
652}

Referenced by setState:afterDelay:, and setStateMachine:afterDelay:.

Here is the caller graph for this function:

◆ preserveCurrentStateMachine

- (void) preserveCurrentStateMachine

Definition at line 204 of file AI.m.

205{
206 if (stateMachine == nil)
207 return;
208
209 if (aiStack == nil) {
210 aiStack = [[NSMutableArray alloc] init];
211 }
212
213 if ([aiStack count] >= kStackLimiter) {
214 [self reportStackOverflow];
215
216 [NSException raise:@"OoliteException"
217 format:@"AI stack overflow for %@", _owner];
218 }
219
220 OOPreservedAIStateMachine* preservedMachine = [[OOPreservedAIStateMachine alloc]
221 initWithStateMachine:stateMachine
222 name:stateMachineName
223 state:currentState
224 pendingMessages:pendingMessages
225 jsScript:[stateMachine objectForKey:@"jsScript"]];
226
227#ifdef OO_DEBUG_MONITOR_ENABLED
228 if ([[self owner] reportAIMessages])
229 OOLog(@"ai.stack.push", @"Pushing state machine for %@", self);
230#endif
231
232 [aiStack addObject:preservedMachine]; // PUSH
233
234 [preservedMachine release];
235}
@ kStackLimiter
Definition AI.m:38

References aiStack, count, kStackLimiter, nil, OOLog, owner, preserveCurrentStateMachine, reportStackOverflow, and stateMachine.

Referenced by preserveCurrentStateMachine, and setStateMachine:withJSScript:.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ reactToMessage:context:

- (void) reactToMessage: (NSString*) message
context: (NSString*) debugContext 

Definition at line 363 of file AI.m.

363 :(NSString*)message context:(NSString*)debugContext
364{
365 unsigned i;
366 NSArray* actions = nil;
367 NSDictionary* messagesForState = nil;
368 ShipEntity* owner = [self owner];
369 static unsigned recursionLimiter = 0;
370 AI* previousRunning = sCurrentlyRunningAI;
371
372 /* CRASH in _freedHandler when called via -setState: __NSFireDelayedPerform (1.69, OS X/x86).
373 Analysis: owner invalid.
374 Fix: make owner an OOWeakReference.
375 -- Ahruman, 20070706
376 */
377 if (message == nil || owner == nil || [owner universalID] == NO_TARGET)
378 return;
379
380#ifndef NDEBUG
381 // Push debug stack frame.
382 if (debugContext == nil)
383 debugContext = @"unspecified";
384 AIStackElement stackElement = {
385 .back = sStack,
386 .owner = owner,
387 .aiName = [[stateMachineName retain] autorelease],
388 .state = [[currentState retain] autorelease],
389 .message = message,
390 .context = debugContext
391 };
392 sStack = &stackElement;
393#endif
394
395 /* CRASH when calling reactToMessage: FOO in state FOO causes infinite
396 recursion. (NB: there are other ways of triggering this.)
397 FIX: recursion limiter. Alternative is to explicitly catch this case
398 in takeAction:, but that could potentially miss indirect recursion via
399 scripts.
400 */
401 if (recursionLimiter > kRecursionLimiter) {
402 OOLogERR(@"ai.error.recursion", @"AI dispatch: hit stack depth limit in AI %@, state %@ handling message %@ in context \"%@\", aborting.", stateMachineName, currentState, message, debugContext);
403
404#ifndef NDEBUG
405 AIStackElement* stack = sStack;
406 unsigned depth = 0;
407 while (stack != NULL) {
408 OOLog(@"ai.error.recursion.stackTrace", @"%4u %@ - %@:%@.%@ (%@)", depth++, [stack->owner shortDescription], stack -> aiName, stack -> state, stack -> message, stack -> context);
409 stack = stack->back;
410 }
411
412 // unwind.
413 if (sStack != NULL)
414 sStack = sStack->back;
415#endif
416
417 return;
418 }
419
420 messagesForState = [stateMachine objectForKey:currentState];
421 if (messagesForState == nil)
422 return;
423
424#ifdef OO_DEBUG_MONITOR_ENABLED
425 if (currentState != nil && ![message isEqual:@"UPDATE"] && [owner reportAIMessages]) {
426 OOLog(@"ai.message.receive", @"AI %@ for %@ in state '%@' receives message '%@'. Context: %@, stack depth: %u", stateMachineName, ownerDesc, currentState, message, debugContext, recursionLimiter);
427 }
428#endif
429
430 actions = [[[messagesForState objectForKey:message] copy] autorelease];
431
432 sCurrentlyRunningAI = self;
433 if ([actions count] > 0) {
434 ++recursionLimiter;
435 @try {
436 for (i = 0; i < [actions count]; i++) {
437 [self takeAction:[actions objectAtIndex:i]];
438 }
439 }
440 @catch (NSException* exception) {
441 OOLog(kOOLogException, @"Squashing exception %@:%@ in AI handler %@:%@.%@", [exception name], [exception reason], stateMachineName, currentState, message);
442 }
443
444 --recursionLimiter;
445 } else {
446 if (currentState != nil) {
447 if ([owner respondsToSelector:@selector(interpretAIMessage:)]) {
448 [owner performSelector:@selector(interpretAIMessage:) withObject:message];
449 }
450 }
451 }
452
453 sCurrentlyRunningAI = previousRunning;
454#ifndef NDEBUG
455 // Unwind stack.
456 if (sStack != NULL)
457 sStack = sStack->back;
458#endif
459}
struct AIStackElement AIStackElement
Definition AI.m:350
static AIStackElement * sStack
Definition AI.m:360
@ kRecursionLimiter
Definition AI.m:37
NSString *const kOOLogException
Definition OOLogging.m:600
ShipEntity * owner
Definition AI.m:353
AIStackElement * back
Definition AI.m:352

References AIStackElement::back, count, currentState, kOOLogException, kRecursionLimiter, name, nil, NO_TARGET, OOLog, OOLogERR, owner, AIStackElement::owner, ownerDesc, sCurrentlyRunningAI, sStack, state, stateMachineName, and takeAction:.

Referenced by StationEntity::acceptDockingClearanceRequestFrom:, Universe::allShipsDoScriptEvent:andReactToAIMessage:, ShipEntity::behaviour_intercept_target:, ShipEntity::checkForAegis, StationEntity::dockingInstructionsForShip:, ShipEntity::enterWormhole:replacing:, exitStateMachineWithMessage:, PlayerEntity(Scripting)::messageShipAIs:, ShipEntity::noteLostTarget, ShipEntity::reactToAIMessage:context:, StationEntity::setAlertLevel:signallingScript:, setState:, setStateMachine:withJSScript:, think, and ShipEntity::update:.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ refreshOwnerDesc

- (void) refreshOwnerDesc
implementation

Provided by category AI(OOPrivate).

Definition at line 669 of file AI.m.

670{
671 ShipEntity* owner = [self owner];
672 [ownerDesc release];
673 if ([owner isPlayer]) {
674 ownerDesc = @"player autopilot";
675 } else if (owner != nil) {
676 ownerDesc = [[NSString alloc] initWithFormat:@"%@ %d", [owner name], [owner universalID]];
677 } else {
678 ownerDesc = @"no owner";
679 }
680}
OOUniversalID universalID
Definition Entity.m:522
NSString * name

Referenced by setOwner:, and setStateMachine:withJSScript:.

Here is the caller graph for this function:

◆ reportStackOverflow

- (void) reportStackOverflow
implementation

Definition at line 182 of file AI.m.

183{
184 if (OOLogWillDisplayMessagesInClass(@"ai.error.stackOverflow")) {
185 BOOL stackDump = OOLogWillDisplayMessagesInClass(@"ai.error.stackOverflow.dump");
186
187 NSString* trailer = stackDump ? @" -- stack:" : @".";
188 OOLogERR(@"ai.error.stackOverflow", @"AI stack overflow for %@ in %@: %@%@\n", [_owner shortDescription], stateMachineName, currentState, trailer);
189
190 if (stackDump) {
191 OOLogIndent();
192
193 NSUInteger count = [aiStack count];
194 while (count--) {
195 OOPreservedAIStateMachine* preservedMachine = [aiStack objectAtIndex:count];
196 OOLog(@"ai.error.stackOverflow.dump", @"%3zu: %@: %@", count, [preservedMachine name], [preservedMachine state]);
197 }
198
199 OOLogOutdent();
200 }
201 }
202}
BOOL OOLogWillDisplayMessagesInClass(NSString *inMessageClass)
Definition OOLogging.m:136
void OOLogOutdent(void)
Definition OOLogging.m:354
void OOLogIndent(void)
Definition OOLogging.m:345

References _owner, count, currentState, name, OOLog, OOLogERR, OOLogIndent(), OOLogOutdent(), OOLogWillDisplayMessagesInClass(), reportStackOverflow, state, and stateMachineName.

Referenced by preserveCurrentStateMachine, and reportStackOverflow.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ restorePreviousStateMachine

- (void) restorePreviousStateMachine

Definition at line 237 of file AI.m.

238{
239 if ([aiStack count] == 0)
240 return;
241
242 OOPreservedAIStateMachine* preservedMachine = [aiStack lastObject];
243
244#ifdef OO_DEBUG_MONITOR_ENABLED
245 if ([[self owner] reportAIMessages])
246 OOLog(@"ai.stack.pop", @"Popping previous state machine for %@", self);
247#endif
248
249 [self directSetStateMachine:[preservedMachine stateMachine]
250 name:[preservedMachine name]];
251
252 [self directSetState:[preservedMachine state]];
253
254 // restore JS script
255 [[self owner] setAIScript:[preservedMachine jsScript]];
256
257 [pendingMessages release];
258 pendingMessages = [[preservedMachine pendingMessages] mutableCopy]; // restore a MUTABLE set
259
260 [aiStack removeLastObject]; // POP
261}
NSString * name()
Definition AI.m:910
NSString * jsScript()
Definition AI.m:925
NSSet * pendingMessages()
Definition AI.m:920
NSString * state()
Definition AI.m:915
NSDictionary * stateMachine()
Definition AI.m:905

References aiStack, count, directSetState:, directSetStateMachine:name:, OOPreservedAIStateMachine::jsScript, OOPreservedAIStateMachine::name, OOLog, owner, OOPreservedAIStateMachine::pendingMessages, pendingMessages, restorePreviousStateMachine, ShipEntity::setAIScript:, OOPreservedAIStateMachine::state, and OOPreservedAIStateMachine::stateMachine.

Referenced by exitStateMachineWithMessage:, and restorePreviousStateMachine.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ setNextThinkTime:

- (void) setNextThinkTime: (OOTimeAbsolute) ntt

Definition at line 581 of file AI.m.

581 :(OOTimeAbsolute)ntt
582{
583 nextThinkTime = ntt;
584}
double OOTimeAbsolute
Definition OOTypes.h:192

References nextThinkTime.

Referenced by DockEntity::launchShip:, PlayerEntity::resetAutopilotAI, PlayerEntity(Scripting)::sendAllShipsAway, and Universe::update:.

Here is the caller graph for this function:

◆ setOwner:

- (void) setOwner: (ShipEntity*) ship

Definition at line 175 of file AI.m.

175 :(ShipEntity*)ship
176{
177 [_owner release];
178 _owner = [ship weakRetain];
179 [self refreshOwnerDesc];
180}

References _owner, refreshOwnerDesc, and OOWeakRefObject::weakRetain.

Referenced by Universe::addEntity:, PlayerEntity::resetAutopilotAI, and ShipEntity::setUpShipFromDictionary:.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ setState:

- (void) setState: (NSString*) stateName

Definition at line 303 of file AI.m.

303 :(NSString*)stateName
304{
305 if ([stateMachine objectForKey:stateName]) {
306 /* CRASH in objc_msgSend, apparently on [self reactToMessage:@"EXIT"] (1.69, OS X/x86).
307 Analysis: self corrupted. We're being called by __NSFireDelayedPerform, which doesn't go
308 through -[NSObject performSelector:withObject:], suggesting it's using IMP caching. An
309 invalid self is therefore possible.
310 Attempted fix: new delayed dispatch with trampoline, see -[AI setState:afterDelay:].
311 -- Ahruman, 20070706
312 */
313 [self reactToMessage:@"EXIT" context:@"changing state"];
314 [self directSetState:stateName];
315 [self reactToMessage:@"ENTER" context:@"changing state"];
316 }
317}

References directSetState:, reactToMessage:context:, and stateMachine.

Referenced by Universe::addEntity:, PlayerEntity::engageAutopilotToStation:, PlayerEntity::resetAutopilotAI, PlayerEntity(Scripting)::sendAllShipsAway, ShipEntity(PureAI)::setStateTo:, ShipEntity(Private)::setUpOneEscort:inGroup:withRole:atPosition:andCount:, ShipSetProperty(), and ShipSetProperty().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ setState:afterDelay:

- (void) setState: (NSString*) stateName
afterDelay: (NSTimeInterval) delay 

Definition at line 324 of file AI.m.

324 :(NSString*)stateName afterDelay:(NSTimeInterval)delay
325{
326 [self performDeferredCall:@selector(setState:) withObject:stateName afterDelay:delay];
327}

References performDeferredCall:withObject:afterDelay:.

Referenced by ShipEntity::dockEscorts.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ setStateMachine:afterDelay:

- (void) setStateMachine: (NSString*) smName
afterDelay: (NSTimeInterval) delay 

Definition at line 319 of file AI.m.

319 :(NSString*)smName afterDelay:(NSTimeInterval)delay
320{
321 [self performDeferredCall:@selector(setStateMachine:) withObject:smName afterDelay:delay];
322}

References performDeferredCall:withObject:afterDelay:.

Here is the call graph for this function:

◆ setStateMachine:withJSScript:

- (void) setStateMachine: (NSString*) smName
withJSScript: (NSString*) script 

Definition at line 278 of file AI.m.

278 :(NSString*)smName withJSScript:(NSString*)script
279{
280 NSDictionary* newSM = [self loadStateMachine:smName jsName:script];
281
282 if (newSM) {
283 [self preserveCurrentStateMachine];
284 [self directSetStateMachine:newSM name:smName];
285 [self directSetState:@"GLOBAL"];
286
287 nextThinkTime = 0.0; // think at next tick
288
289 /* CRASH in objc_msgSend, apparently on [self reactToMessage:@"ENTER"] (1.69, OS X/x86).
290 Analysis: self corrupted. We're being called by __NSFireDelayedPerform, which doesn't go
291 through -[NSObject performSelector:withObject:], suggesting it's using IMP caching. An
292 invalid self is therefore possible.
293 Attempted fix: new delayed dispatch with trampoline, see -[AI setStateMachine:afterDelay:].
294 -- Ahruman, 20070706
295 */
296 [self reactToMessage:@"ENTER" context:@"changing AI"];
297
298 // refresh name
299 [self refreshOwnerDesc];
300 }
301}

References directSetState:, directSetStateMachine:name:, loadStateMachine:jsName:, nextThinkTime, preserveCurrentStateMachine, reactToMessage:context:, and refreshOwnerDesc.

Referenced by initWithStateMachine:andState:, and ShipEntity(AI)::setAITo:.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ setThinkTimeInterval:

- (void) setThinkTimeInterval: (OOTimeDelta) tti

Definition at line 594 of file AI.m.

594 :(OOTimeDelta)tti
595{
596 thinkTimeInterval = tti;
597}
double OOTimeDelta
Definition OOTypes.h:193

References thinkTimeInterval.

◆ shortDescriptionComponents

- (NSString *) shortDescriptionComponents
implementation

Definition at line 159 of file AI.m.

160{
161 return [NSString stringWithFormat:@"%@:%@ / %@", stateMachineName, currentState, [stateMachine objectForKey:@"jsScript"]];
162}

References shortDescriptionComponents.

Referenced by shortDescriptionComponents.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ stackDepth

- (NSUInteger) stackDepth

Definition at line 344 of file AI.m.

345{
346 return [aiStack count];
347}

References stackDepth.

Referenced by stackDepth.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ state

- (NSString *) state

Definition at line 339 of file AI.m.

340{
341 return [[currentState retain] autorelease];
342}

References state.

Referenced by currentlyRunningAIDescription, AI(OOPrivate)::loadStateMachine:jsName:, reactToMessage:context:, reportStackOverflow, ShipEntity(PureAI)::safeScriptActionOnTarget:, ShipEntity(PureAI)::scriptActionOnTarget:, ShipGetProperty(), ShipGetProperty(), and state.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ takeAction:

- (void) takeAction: (NSString*) action

Definition at line 461 of file AI.m.

461 :(NSString*)action
462{
463 ShipEntity* owner = [self owner];
464
465#ifdef OO_DEBUG_MONITOR_ENABLED
466 BOOL report = [owner reportAIMessages];
467 if (report) {
468 OOLog(@"ai.takeAction", @"%@ to take action %@", ownerDesc, action);
469 OOLogIndent();
470 }
471#endif
472
473 NSArray* tokens = ScanTokensFromString(action);
474 NSUInteger tokenCount = [tokens count];
475
476 if (tokenCount != 0) {
477 NSString* selectorStr = [tokens objectAtIndex:0];
478
479 if (owner != nil) {
480 NSString* dataString = nil;
481
482 if (tokenCount == 2) {
483 dataString = [tokens objectAtIndex:1];
484 } else if ([tokens count] > 1) {
485 dataString = [[tokens subarrayWithRange:NSMakeRange(1, tokenCount - 1)] componentsJoinedByString:@" "];
486 }
487
488 SEL selector = NSSelectorFromString(selectorStr);
489 if ([owner respondsToSelector:selector]) {
490 if (dataString != nil)
491 [owner performSelector:selector withObject:dataString];
492 else
493 [owner performSelector:selector];
494 } else {
495 OOLogERR(@"ai.takeAction.badSelector", @"in AI %@ in state %@: %@ does not respond to %@", stateMachineName, currentState, ownerDesc, selectorStr);
496 }
497 } else {
498 OOLog(@"ai.takeAction.orphaned", @"***** AI %@, trying to perform %@, is orphaned (no owner)", stateMachineName, selectorStr);
499 }
500 } else {
501#ifdef OO_DEBUG_MONITOR_ENABLED
502 if (report)
503 OOLog(@"ai.takeAction.noAction", @"DEBUG: - no action '%@'", action);
504#endif
505 }
506
507#ifdef OO_DEBUG_MONITOR_ENABLED
508 if (report) {
509 OOLogOutdent();
510 }
511#endif
512}
NSMutableArray * ScanTokensFromString(NSString *values)
unsigned reportAIMessages

References count, currentState, nil, OOLog, OOLogERR, OOLogIndent(), OOLogOutdent(), owner, ownerDesc, ShipEntity::reportAIMessages, ScanTokensFromString(), and stateMachineName.

Referenced by reactToMessage:context:.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ think

- (void) think

Definition at line 514 of file AI.m.

515{
516 NSArray* ms_list = nil;
517 unsigned i;
518
519 if ([[self owner] universalID] == NO_TARGET || stateMachine == nil)
520 return; // don't think until launched
521
522 [self reactToMessage:@"UPDATE" context:@"periodic update"];
523
524 if ([pendingMessages count] > 0) {
525 ms_list = [pendingMessages allObjects];
526 [pendingMessages removeAllObjects];
527 }
528
529 if (ms_list != nil) {
530 for (i = 0; i < [ms_list count]; i++) {
531 [self reactToMessage:[ms_list objectAtIndex:i] context:@"handling deferred message"];
532 }
533 }
534}

References count, nil, NO_TARGET, owner, pendingMessages, reactToMessage:context:, stateMachine, and think.

Referenced by think, and Universe::update:.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ thinkTimeInterval

References clearAllData, clearStack, dumpState, and thinkTimeInterval.

Here is the call graph for this function:

Member Data Documentation

◆ _owner

- (id) _owner
private

Definition at line 37 of file AI.h.

Referenced by dealloc, owner, reportStackOverflow, and setOwner:.

◆ aiStack

- (NSMutableArray*) aiStack
private

◆ currentState

- (NSString*) currentState
private

◆ jsScript

- (NSString*) jsScript
private

Definition at line 50 of file AI.h.

Referenced by dealloc.

◆ nextThinkTime

- (OOTimeAbsolute) nextThinkTime
private

Definition at line 586 of file AI.m.

587{
588 if (!stateMachine)
589 return INFINITY;
590
591 return nextThinkTime;
592}

Referenced by clearAllData, dumpState, init, nextThinkTime, setNextThinkTime:, setStateMachine:withJSScript:, and Universe::update:.

◆ ownerDesc

- (NSString*) ownerDesc
private

Definition at line 38 of file AI.h.

Referenced by dealloc, message:, reactToMessage:context:, and takeAction:.

◆ pendingMessages

- (NSSet *) pendingMessages
private

Definition at line 557 of file AI.m.

558{
559 if (pendingMessages != nil) {
560 return [[pendingMessages copy] autorelease];
561 } else {
562 return [NSSet set];
563 }
564}

Referenced by dealloc, debugDumpPendingMessages, message:, pendingMessages, restorePreviousStateMachine, and think.

◆ stateMachine

- (NSDictionary*) stateMachine
private

Definition at line 40 of file AI.h.

Referenced by dealloc, preserveCurrentStateMachine, setState:, and think.

◆ stateMachineName

- (NSString*) stateMachineName
private

Definition at line 41 of file AI.h.

Referenced by dealloc, dumpState, init, reactToMessage:context:, reportStackOverflow, and takeAction:.

◆ thinkTimeInterval

- (OOTimeDelta) thinkTimeInterval
private

Definition at line 599 of file AI.m.

600{
601 return thinkTimeInterval;
602}

Referenced by dumpState, init, setThinkTimeInterval:, thinkTimeInterval, and Universe::update:.


The documentation for this class was generated from the following files: