File: ai_cast.c

package info (click to toggle)
iortcw 1.51.c%2Bdfsg1-7
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid, trixie
  • size: 25,304 kB
  • sloc: ansic: 457,326; cpp: 6,507; makefile: 4,737; sh: 1,292; asm: 1,176; xml: 31
file content (878 lines) | stat: -rw-r--r-- 24,134 bytes parent folder | download | duplicates (4)
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
/*
===========================================================================

Return to Castle Wolfenstein multiplayer GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company. 

This file is part of the Return to Castle Wolfenstein multiplayer GPL Source Code (“RTCW MP Source Code”).  

RTCW MP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

RTCW MP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with RTCW MP Source Code.  If not, see <http://www.gnu.org/licenses/>.

In addition, the RTCW MP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW MP Source Code.  If not, please request a copy in writing from id Software at the address below.

If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.

===========================================================================
*/

//===========================================================================
//
// Name:			ai_cast.c
// Function:		Wolfenstein AI Character Routines
// Programmer:		Ridah
// Tab Size:		4 (real tabs)
//===========================================================================

#include "g_local.h"
#include "../qcommon/q_shared.h"
#include "../botlib/botlib.h"      //bot lib interface
#include "../botlib/be_aas.h"
#include "../botlib/be_ea.h"
#include "../botlib/be_ai_gen.h"
#include "../botlib/be_ai_goal.h"
#include "../botlib/be_ai_move.h"
#include "../botlib/botai.h"          //bot ai interface

#include "ai_cast.h"

/*
The Wolfenstein AI uses the bot movement functions, and goal handling.

The actual core thinking and decision making is handled by the Cast AI,
typically within the ai_cast*.c files.

Some modifications to the botlib and botai are to be expected, the extent of those
changes is currently unknown.

Currently, this seems to the the best approach, since if we're going to
use the AAS for navigation, we want to avoid having to re-write the movement
routines which are heavily associated with the AAS information.
*/

//cast states (allocated at run-time)
cast_state_t    *caststates;
//number of characters
int numcast;
//
qboolean saveGamePending;
//
// minimum time between thinks (maximum is double this)
int aicast_thinktime;
// maximum number of character thinks at once
int aicast_maxthink;
// maximum clients
int aicast_maxclients;
// skill scale (0.0 -> 1.0)
float aicast_skillscale;

// cvar to enable aicast debugging, set higher for more levels of debugging
vmCvar_t aicast_debug;
vmCvar_t aicast_debugname;
vmCvar_t aicast_scripts;

// string versions of the attributes used for per-level, per-character definitions
char *castAttributeStrings[] =
{
	"RUNNING_SPEED", // max = 300	(running speed)
	"WALKING_SPEED", // max = 300	(walking speed)
	"CROUCHING_SPEED",   // max = 300	(crouching speed)
	"FOV",               // max = 360	(field of view)
	"YAW_SPEED",     // max = 300	(yaw speed)
	"LEADER",            // max = 1.0	(ability to lead an AI squadron)
	"AIM_SKILL",     // max = 1.0	(skill while aiming)
	"AIM_ACCURACY",      // max = 1.0	(accuracy of firing)
	"ATTACK_SKILL",      // max = 1.0	(ability to attack and do other things, like retreat)
	"REACTION_TIME", // max = 1.0	(upon seeing enemy, wait this long before reaction)
	"ATTACK_CROUCH", // max = 1.0	(likely to crouch while firing)
	"IDLE_CROUCH",       // max = 1.0	(likely to crouch while idling)
	"AGGRESSION",        // max = 1.0	(willingness to fight till the death)
	"TACTICAL",          // max = 1.0	(ability to use strategy to their advantage, also behaviour whilst hunting enemy, more likely to creep around)
	"CAMPER",            // max = 1.0	(set this to make them stay in the spot they are spawned)
	"ALERTNESS",     // max = 1.0	(ability to notice enemies at long range)
	"STARTING_HEALTH",
	"HEARING_SCALE",
	"INNER_DETECTION_RADIUS",
	"PAIN_THRESHOLD_SCALE",

	NULL
};

/*
============
AICast_Printf
============
*/
void AICast_Printf( int type, const char *fmt, ... ) {
	char str[2048];
	va_list ap;

	va_start( ap, fmt );
	Q_vsnprintf( str, sizeof( str ), fmt, ap );
	va_end( ap );

	switch ( type ) {
	case AICAST_PRT_ALWAYS: {
		G_Printf( "%s", str );
		break;
	}
	default: {
		if ( aicast_debug.integer >= type ) {
			G_Printf( "%s", str );
		}
		break;
	}
	}
}

/*
============
AICast_GetCastState
============
*/
cast_state_t *AICast_GetCastState( int entitynum ) {
	return &( caststates[ entitynum ] );
}

/*
==============
AICast_SetupClient
==============
*/
int AICast_SetupClient( int client ) {
	cast_state_t    *cs;
	bot_state_t     *bs;

	if ( !botstates[client] ) {
		botstates[client] = G_Alloc( sizeof( bot_state_t ) );
		memset( botstates[client], 0, sizeof( bot_state_t ) );
	}
	bs = botstates[client];

	if ( bs->inuse ) {
		BotAI_Print( PRT_FATAL, "client %d already setup\n", client );
		return qfalse;
	}

	cs = AICast_GetCastState( client );
	cs->bs = bs;

	//allocate a goal state
	bs->gs = trap_BotAllocGoalState( client );

	bs->inuse = qtrue;
	bs->client = client;
	bs->entitynum = client;
	bs->setupcount = qtrue;
	bs->entergame_time = trap_AAS_Time();
	bs->ms = trap_BotAllocMoveState();

	return qtrue;
}

/*
==============
AICast_ShutdownClient
==============
*/
int AICast_ShutdownClient( int client ) {
	cast_state_t    *cs;
	bot_state_t *bs;

	if ( !( bs = botstates[client] ) ) {
		return BLERR_NOERROR;
	}
	if ( !bs->inuse ) {
		BotAI_Print( PRT_ERROR, "client %d already shutdown\n", client );
		return BLERR_AICLIENTALREADYSHUTDOWN;
	}

	cs = AICast_GetCastState( client );
	//
	memset( cs, 0, sizeof( cast_state_t ) );
	numcast--;

	// now do the other bot stuff

#ifdef DEBUG
//	botai_import.DebugLineDelete(bs->debugline);
#endif //DEBUG

	trap_BotFreeMoveState( bs->ms );
	//free the goal state
	trap_BotFreeGoalState( bs->gs );
	//
	//clear the bot state
	memset( bs, 0, sizeof( bot_state_t ) );
	//set the inuse flag to qfalse
	bs->inuse = qfalse;
	//everything went ok
	return BLERR_NOERROR;
}

/*
============
AICast_AddCastToGame
============
*/
//----(SA) modified this for head separation
gentity_t *AICast_AddCastToGame( gentity_t *ent, char *castname, char *model, char *head, char *sex, char *color, char *handicap ) {
	int clientNum;
	gentity_t *bot;
	char userinfo[MAX_INFO_STRING];
	usercmd_t cmd;

	// create the bot's userinfo
	userinfo[0] = '\0';

	Info_SetValueForKey( userinfo, "name", castname );
	Info_SetValueForKey( userinfo, "rate", "25000" );
	Info_SetValueForKey( userinfo, "snaps", "20" );
	Info_SetValueForKey( userinfo, "handicap", handicap );
	Info_SetValueForKey( userinfo, "model", model );
	Info_SetValueForKey( userinfo, "head", head );
	Info_SetValueForKey( userinfo, "color", color );

	// have the server allocate a client slot
	clientNum = trap_BotAllocateClient();
	if ( clientNum == -1 ) {
		G_Printf( S_COLOR_RED "BotAllocateClient failed\n" );
		return NULL;
	}
	bot = &g_entities[ clientNum ];
	bot->r.svFlags |= SVF_BOT;
	bot->r.svFlags |= SVF_CASTAI;       // flag it for special Cast AI behaviour

	// register the userinfo
	trap_SetUserinfo( bot->s.number, userinfo );

	// have it connect to the game as a normal client
//----(SA) ClientConnect requires a third 'isbot' parameter.  setting to qfalse and noting
	ClientConnect( bot->s.number, qtrue, qfalse );
//----(SA) end

	// copy the origin/angles across
	VectorCopy( ent->s.origin, bot->s.origin );
	VectorCopy( ent->s.angles, bot->s.angles );

	memset( &cmd, 0, sizeof( cmd ) );
	ClientBegin( bot->s.number );

	// set up the ai
	AICast_SetupClient( bot->s.number );

	return bot;
}

/*
============
AICast_CheckLevelAttributes
============
*/
void AICast_CheckLevelAttributes( cast_state_t *cs, gentity_t *ent, char **ppStr ) {
	char    *s;
	int i;

	if ( !*ppStr ) {
		return;
	}

	while ( 1 ) {
		s = COM_Parse( ppStr );
		if ( !s[0] || !Q_strncmp( s, "}", 2 ) ) {    // end of attributes
			break;
		}
		//
		for ( i = 0; i < AICAST_MAX_ATTRIBUTES; i++ ) {
			if ( !Q_strcasecmp( s, castAttributeStrings[i] ) ) {
				// found a match, read in the value
				s = COM_Parse( ppStr );
				if ( !s[0] ) {    // end of attributes
					break;
				}
				// set the attribute
				cs->attributes[i] = atof( s );
				break;
			}
		}
	}
}

/*
============
AICast_SetAASIndex
============
*/
void AICast_SetAASIndex( cast_state_t *cs ) {
	if ( aiDefaults[cs->aiCharacter].bboxType == BBOX_SMALL ) {
		cs->aasWorldIndex = AASWORLD_STANDARD;
		cs->travelflags = AICAST_TFL_DEFAULT;
	} else if ( aiDefaults[cs->aiCharacter].bboxType == BBOX_LARGE ) {
		cs->aasWorldIndex = AASWORLD_LARGE;
		cs->travelflags = AICAST_TFL_DEFAULT & ~TFL_DONOTENTER_LARGE;
	} else {
		Com_Error( ERR_DROP, "AICast_SetAASIndex: unsupported bounds size (%i)", aiDefaults[cs->aiCharacter].bboxType );
	}

	if ( !cs->attributes[ATTACK_CROUCH] ) {
		cs->travelflags &= ~TFL_CROUCH;
	}
}

/*
============
AICast_CreateCharacter

  returns 0 if unable to create the character
============
*/
gentity_t *AICast_CreateCharacter( gentity_t *ent, float *attributes, cast_weapon_info_t *weaponInfo, char *castname, char *model, char *head, char *sex, char *color, char *handicap ) {
	gentity_t       *newent;
	gclient_t       *client;
	cast_state_t    *cs;
	char            **ppStr;
	int j;

	if ( g_gametype.integer != GT_SINGLE_PLAYER ) { // no cast AI in multiplayer
		return NULL;
	}
	// are bots enabled?
	if ( !trap_Cvar_VariableIntegerValue( "bot_enable" ) ) {
		G_Printf( S_COLOR_RED "ERROR: Unable to spawn %s, 'bot_enable' is not set\n", ent->classname );
		return NULL;
	}
	//
	// make sure we have a free slot for them
	//
	if ( level.numPlayingClients + 1 > aicast_maxclients ) {
		G_Error( "Exceeded sv_maxclients (%d), unable to create %s\n", aicast_maxclients, ent->classname );
		return NULL;
	}
	//
	// add it to the list (only do this if everything else passed)
	//

	newent = AICast_AddCastToGame( ent, castname, model, head, sex, color, handicap );

	if ( !newent ) {
		return NULL;
	}
	client = newent->client;
	//
	// setup the character..
	//
	cs = AICast_GetCastState( newent->s.number );
	//
	cs->aiCharacter = ent->aiCharacter;
	// setup the attributes
	memcpy( cs->attributes, attributes, sizeof( cs->attributes ) );
	ppStr = &ent->aiAttributes;
	AICast_CheckLevelAttributes( cs, ent, ppStr );
	//
	AICast_SetAASIndex( cs );
	// make sure they face the right direction
	VectorCopy( ent->s.angles, cs->bs->ideal_viewangles );
	// factor in the delta_angles
	for ( j = 0; j < 3; j++ ) {
		cs->bs->viewangles[j] = AngleMod( newent->s.angles[j] - SHORT2ANGLE( newent->client->ps.delta_angles[j] ) );
	}
	VectorCopy( ent->s.angles, newent->s.angles );
	VectorCopy( ent->s.origin, cs->startOrigin );
	//
	cs->lastEnemy = -1;
	cs->bs->enemy = -1;
	cs->leaderNum = -1;
	cs->castScriptStatus.scriptGotoEnt = -1;
	//
	newent->aiName = ent->aiName;
	newent->aiTeam = ent->aiTeam;
	newent->targetname = ent->targetname;
	//
	newent->AIScript_AlertEntity = ent->AIScript_AlertEntity;
	newent->aiInactive = ent->aiInactive;
	newent->aiCharacter = cs->aiCharacter;
	//
	// parse the AI script for this character (if applicable)
	cs->aiFlags |= AIFL_CORPSESIGHTING;     // this is on by default for all characters, disabled if they have a "friendlysightcorpse" script event
	AICast_ScriptParse( cs );
	//
	// setup bounding boxes
	//VectorCopy( mins, client->ps.mins );
	//VectorCopy( maxs, client->ps.maxs );
	AIChar_SetBBox( newent, cs );
	client->ps.friction = cs->attributes[RUNNING_SPEED] / 300.0;
	//
	// clear weapons/ammo
	client->ps.weapon = 0;
	memcpy( client->ps.weapons, weaponInfo->startingWeapons, sizeof( weaponInfo->startingWeapons ) );
	memcpy( client->ps.ammo, weaponInfo->startingAmmo, sizeof( client->ps.ammo ) );
	//
	// starting health
	if ( ent->health ) {
		newent->health = client->ps.stats[STAT_HEALTH] = client->ps.stats[STAT_MAX_HEALTH] = ent->health;
	} else {
		newent->health = client->ps.stats[STAT_HEALTH] = client->ps.stats[STAT_MAX_HEALTH] = cs->attributes[STARTING_HEALTH];
	}
	//
	cs->weaponInfo = weaponInfo;
	//
	cs->lastThink = level.time;
	//
	newent->pain = AICast_Pain;
	newent->die = AICast_Die;
	//
	//update the attack inventory values
	AICast_UpdateBattleInventory( cs, cs->bs->enemy );

//----(SA)	make sure all clips are loaded so we don't hear everyone loading up
//			(we don't want to do this inside AICast_UpdateBattleInventory(), only on spawn or giveweapon)
	for ( j = 0; j < MAX_WEAPONS; j++ ) {
		Fill_Clip( &client->ps, j );
	}
//----(SA)	end

	// select a weapon
	AICast_ChooseWeapon( cs, qfalse );

	//
	// set the default function, overwrite if necessary
	cs->aiFlags |= AIFL_JUST_SPAWNED;
	AIFunc_DefaultStart( cs );
	//
	numcast++;
	//
	return newent;
}

/*
============
AICast_Init

  called at each level start, before the world and it's entities have been spawned
============
*/
static int numSpawningCast;

void AICast_Init( void ) {
	vmCvar_t cvar;
	int i;

	numSecrets = 0;
	numcast = 0;
	numSpawningCast = 0;
	saveGamePending = qtrue;

	trap_Cvar_Register( &aicast_debug, "aicast_debug", "0", 0 );
	trap_Cvar_Register( &aicast_debugname, "aicast_debugname", "", 0 );
	trap_Cvar_Register( &aicast_scripts, "aicast_scripts", "1", 0 );

	// (aicast_thinktime / sv_fps) * aicast_maxthink = number of cast's to think between each aicast frame
	// so..
	// (100 / 20) * 6 = 30
	//
	// so if the level has more than 30 AI cast's, they could start to bunch up, resulting in slower thinks

	trap_Cvar_Register( &cvar, "aicast_thinktime", "50", 0 );
	aicast_thinktime = trap_Cvar_VariableIntegerValue( "aicast_thinktime" );

	trap_Cvar_Register( &cvar, "aicast_maxthink", "12", 0 );
	aicast_maxthink = trap_Cvar_VariableIntegerValue( "aicast_maxthink" );

	aicast_maxclients = trap_Cvar_VariableIntegerValue( "sv_maxclients" );

	aicast_skillscale = (float)trap_Cvar_VariableIntegerValue( "g_gameSkill" ) / (float)GSKILL_MAX;

	caststates = G_Alloc( aicast_maxclients * sizeof( cast_state_t ) );
	memset( caststates, 0, sizeof( *caststates ) );
	for ( i = 0; i < MAX_CLIENTS; i++ ) {
		caststates[i].entityNum = i;
	}

	// try and load in the AAS now, so we can interact with it during spawning of entities
	i = 0;
	trap_AAS_SetCurrentWorld( 0 );
	while ( !trap_AAS_Initialized() && ( i++ < 10 ) ) {
		trap_BotLibStartFrame( (float) level.time / 1000 );
	}
}

/*
===============
AICast_FindEntityForName
===============
*/
gentity_t *AICast_FindEntityForName( char *name ) {
	gentity_t *trav;
	int i;

	for ( trav = g_entities, i = 0; i < aicast_maxclients; i++, trav++ ) {
		if ( !trav->inuse ) {
			continue;
		}
		if ( !trav->client ) {
			continue;
		}
		if ( !trav->aiName ) {
			continue;
		}
		if ( strcmp( trav->aiName, name ) ) {
			continue;
		}
		return trav;
	}
	return NULL;
}

/*
===============
AICast_TravEntityForName
===============
*/
gentity_t *AICast_TravEntityForName( gentity_t *startent, char *name ) {
	gentity_t *trav;

	if ( !startent ) {
		trav = g_entities;
	} else {
		trav = startent + 1;
	}

	for ( ; trav < g_entities + aicast_maxclients; trav++ ) {
		if ( !trav->inuse ) {
			continue;
		}
		if ( !trav->client ) {
			continue;
		}
		if ( !trav->aiName ) {
			continue;
		}
		if ( strcmp( trav->aiName, name ) ) {
			continue;
		}
		return trav;
	}
	return NULL;
}

/*
============
AIChar_AIScript_AlertEntity

  triggered spawning, called from AI scripting
============
*/
void AIChar_AIScript_AlertEntity( gentity_t *ent ) {
	vec3_t mins, maxs;
	int numTouch, touch[10], i;
	cast_state_t    *cs;

	if ( !ent->aiInactive ) {
		return;
	}

	cs = AICast_GetCastState( ent->s.number );

	// if the current bounding box is invalid, then wait
	VectorAdd( ent->r.currentOrigin, ent->r.mins, mins );
	VectorAdd( ent->r.currentOrigin, ent->r.maxs, maxs );
	trap_UnlinkEntity( ent );

	numTouch = trap_EntitiesInBox( mins, maxs, touch, 10 );

	// check that another client isn't inside us
	if ( numTouch ) {
		for ( i = 0; i < numTouch; i++ ) {
			// RF, note we should only check against clients since zombies need to spawn inside func_explosive (so they dont clip into view after it explodes)
			if ( g_entities[touch[i]].client && g_entities[touch[i]].r.contents == CONTENTS_BODY ) {
				//if (g_entities[touch[i]].r.contents & MASK_PLAYERSOLID)
				break;
			}
		}
		if ( i == numTouch ) {
			numTouch = 0;
		}
	}

	if ( numTouch ) {
		// invalid location
		cs->aiFlags |= AIFL_WAITINGTOSPAWN;
		return;
	}

	// RF, has to disable this so I could test some maps which have erroneously placed alertentity calls
	//ent->AIScript_AlertEntity = NULL;
	cs->aiFlags &= ~AIFL_WAITINGTOSPAWN;
	ent->aiInactive = qfalse;
	trap_LinkEntity( ent );

	// trigger a spawn script event
	AICast_ScriptEvent( AICast_GetCastState( ent->s.number ), "spawn", "" );
	// make it think so we update animations/angles
	AICast_Think( ent->s.number, (float)FRAMETIME / 1000 );
	cs->lastThink = level.time;
	AICast_UpdateInput( cs, FRAMETIME );
	trap_BotUserCommand( cs->bs->client, &( cs->bs->lastucmd ) );
}


/*
================
AICast_DelayedSpawnCast
================
*/
void AICast_DelayedSpawnCast( gentity_t *ent, int castType ) {
	// ............................
	// head separation
	if ( !ent->aiSkin ) {
		G_SpawnString( "skin", "", &ent->aiSkin );
	}
	if ( !ent->aihSkin ) {
		G_SpawnString( "head", "default", &ent->aihSkin );
	}
	G_SpawnInt( "aiteam", "-1", &ent->aiTeam );
	// ............................


	// we have to wait a bit before spawning it, otherwise the server will just delete it, since it's treated like a client
	ent->think = AIChar_spawn;
	ent->nextthink = level.time + FRAMETIME * 4;  // have to wait more than 3 frames, since the server runs 3 frames before it clears all clients

	// we don't really want to start this character right away, but if we don't spawn the client
	// now, if the game gets saved after the character spawns in, when it gets re-loaded, the client
	// won't get spawned properly.
	if ( ent->spawnflags & 1 ) { // TriggerSpawn
		ent->AIScript_AlertEntity = AIChar_AIScript_AlertEntity;
		ent->aiInactive = qtrue;
	}

	// RF, had to move this down since some dev maps don't properly spawn the guys in, so we
	// get a crash when transitioning between levels after they all spawn at once (overloading
	// the client/server command buffers)
	ent->nextthink += FRAMETIME * ( ( numSpawningCast + 1 ) / 3 );    // space them out a bit so we don't overflow the client

	ent->aiCharacter = castType;
	numSpawningCast++;
}

/*
==================
AICast_CastScriptThink
==================
*/
void AICast_CastScriptThink( void ) {
	int i;
	gentity_t *ent;
	cast_state_t *cs;

	for ( i = 0, ent = g_entities, cs = caststates; i < level.maxclients; i++, ent++, cs++ ) {
		if ( !ent->inuse ) {
			continue;
		}
		if ( !cs->bs ) {
			continue;
		}
		AICast_ScriptRun( cs, qfalse );
	}
}

/*
==================
AICast_CheckLoadGame

  at the start of a level, the game is either saved, or loaded

  we must wait for all AI to spawn themselves, and a real client to connect
==================
*/
void AICast_CheckLoadGame( void ) {
	char loading[4];
	gentity_t *ent;
	qboolean ready;

	// have we already done the save or load?
	if ( !saveGamePending ) {
		return;
	}

	// tell the cgame NOT to render the scene while we are waiting for things to settle
	trap_Cvar_Set( "cg_norender", "1" );

	trap_Cvar_VariableStringBuffer( "savegame_loading", loading, sizeof( loading ) );

	// screen should be black if we are at this stage
	trap_SetConfigstring( CS_SCREENFADE, va( "1 %i 1", level.time - 10 ) );
	reloading = qtrue;

	if ( strlen( loading ) > 0 && atoi( loading ) != 0 ) {
		if ( !reloading && atoi( loading ) == 2 ) {
			reloading = qtrue;  // this gets reset at the Map_Restart() since the server unloads the game dll
		}

		ready = qtrue;
		if ( numSpawningCast != numcast ) {
			ready = qfalse;
		} else if ( !( ent = AICast_FindEntityForName( "player" ) ) ) {
			ready = qfalse;
		} else if ( !ent->client || ent->client->pers.connected != CON_CONNECTED ) {
			ready = qfalse;
		}

		if ( ready ) {
			trap_Cvar_Set( "savegame_loading", "0" ); // in-case it aborts
			saveGamePending = qfalse;
//			G_LoadGame( NULL );		// always load the "current" savegame
			trap_Cvar_Set( "cg_norender", "0" );

			// wait for the clients to return from faded screen
//			trap_SetConfigstring( CS_SCREENFADE, va("0 %i 1500", level.time + 500) );
			trap_SetConfigstring( CS_SCREENFADE, va( "0 %i 750", level.time + 500 ) );
			level.reloadPauseTime = level.time + 1100;

			AICast_CastScriptThink();
		}
	} else {

		ready = qtrue;
		if ( numSpawningCast != numcast ) {
			ready = qfalse;
		} else if ( !( ent = AICast_FindEntityForName( "player" ) ) ) {
			ready = qfalse;
		} else if ( !ent->client || ent->client->pers.connected != CON_CONNECTED ) {
			ready = qfalse;
		}

		// not loading a game, we must be in a new level, so look for some persistant data to read in, then save the game
		if ( ready ) {
//			G_LoadPersistant();		// make sure we save the game after we have brought across the items

			trap_Cvar_Set( "cg_norender", "0" );
			saveGamePending = qfalse;

			// wait for the clients to return from faded screen
//			trap_SetConfigstring( CS_SCREENFADE, va( "0 %i 1500", level.time + 500 ) );
			trap_SetConfigstring( CS_SCREENFADE, va( "0 %i 750", level.time + 500 ) );
			level.reloadPauseTime = level.time + 1100;

			AICast_CastScriptThink();
		}
	}
}

/*
===============
AICast_SolidsInBBox
===============
*/
qboolean AICast_SolidsInBBox( vec3_t pos, vec3_t mins, vec3_t maxs, int entnum, int mask ) {
	trace_t tr;

	if ( g_entities[entnum].health <= 0 ) {
		return qfalse;
	}

	trap_Trace( &tr, pos, mins, maxs, pos, entnum, mask );
	if ( tr.startsolid || tr.allsolid ) {
		return qtrue;
	} else {
		return qfalse;
	}
}

/*
===============
AICast_Activate
===============
*/
void AICast_Activate( int activatorNum, int entNum ) {
	cast_state_t *cs;

	cs = AICast_GetCastState( entNum );
	if ( cs->activate ) {
		cs->activate( entNum, activatorNum );
	}

	AICast_Printf( AICAST_PRT_DEBUG, "activated entity # %i\n", entNum );
}

/*
================
AICast_NoFlameDamage
================
*/
qboolean AICast_NoFlameDamage( int entNum ) {
	cast_state_t *cs;

	if ( entNum >= MAX_CLIENTS ) {
		return qfalse;
	}

	// DHM - Nerve :: Not in multiplayer
	if ( g_gametype.integer != GT_SINGLE_PLAYER ) {
		return qfalse;
	}

	cs = AICast_GetCastState( entNum );
	return ( ( cs->aiFlags & AIFL_NO_FLAME_DAMAGE ) != 0 );
}

/*
===============
G_SetAASBlockingEntity

  Adjusts routing so AI knows it can't move through this entity
===============
*/
void G_SetAASBlockingEntity( gentity_t *ent, qboolean blocking ) {
	ent->AASblocking = blocking;
	trap_AAS_SetAASBlockingEntity( ent->r.absmin, ent->r.absmax, blocking );
}

/*
===============
AICast_AdjustIdealYawForMover
===============
*/
void AICast_AdjustIdealYawForMover( int entnum, float yaw ) {
	cast_state_t *cs = AICast_GetCastState( entnum );
	//
	cs->bs->ideal_viewangles[YAW] += yaw;
}

/*
===============
AICast_AgePlayTime
===============
*/
void AICast_AgePlayTime( int entnum ) {
	cast_state_t *cs = AICast_GetCastState( entnum );
	//
	if ( ( level.time - cs->lastLoadTime ) > 100 ) {
		if ( ( level.time - cs->lastLoadTime ) < 1000 ) {
			cs->totalPlayTime += level.time - cs->lastLoadTime;
		}
		//
		cs->lastLoadTime = level.time;
	}
}

/*
===============
AICast_NoReload
===============
*/
int AICast_NoReload( int entnum ) {
	cast_state_t *cs = AICast_GetCastState( entnum );
	//
	return ( ( cs->aiFlags & AIFL_NO_RELOAD ) != 0 );
}