-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaiplayer.cpp
executable file
·707 lines (565 loc) · 17.5 KB
/
aiplayer.cpp
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
#include "mastrix.hpp"
ServerConsoleVar<float> botInaccuracy("bot_inaccuracy", 30.0f);
ServerConsoleVar<float> botVisibleRange("bot_visible_range", 1500.0f);
ServerConsoleVar<float> botFiringRange("bot_firing_range", 1500.0f);
ServerConsoleVar<float> minWaypointDistance("min_waypoint_dist", 1500.0f);
ServerConsoleVar<bool> enableChase("enable_chase", true);
ServerConsoleVar<bool> botsFrozen("bots_frozen", false);
ServerConsoleVar<float> turretHitpointScale("turret_hitpoint_scale", 5.5f);
SERVER_CONSOLE_COMMAND(bot_destination)
{
if (argc < 3)
{
printfToClient(who, "Usage: bot_destination entID x y");
return;
}
int botID = atoi(argv[0]);
float x = atof(argv[1]);
float y = atof(argv[2]);
if(server->entities.find(botID) == server->entities.end()) return;
if(!server->entities[botID]->isPlayer() || server->entities[botID]->isHuman()) return;
AIPlayer *bot = (AIPlayer *)server->entities[botID];
if (!bot->isTurret())
{
((AIShip *)bot)->setNewGoal(Position(x, y));
bot->setState(state_roaming);
}
}
SERVER_CONSOLE_COMMAND(bot_on_finish)
{
if (argc < 2)
{
printfToClient(who, "Usage: bot_destination entID var");
return;
}
int botID = atoi(argv[0]);
if(server->entities.find(botID) == server->entities.end()) return;
if(!server->entities[botID]->isPlayer() || server->entities[botID]->isHuman()) return;
AIPlayer *bot = (AIPlayer *)server->entities[botID];
bot->nextCommand = argv[1];
}
SERVER_CONSOLE_COMMAND(bot_on_die)
{
if(argc < 2)
{
printfToClient(who, "Usage: bot_on_die entID var");
return;
}
int botID = atoi(argv[0]);
if(server->entities.find(botID) == server->entities.end()) return;
if(!server->entities[botID]->isPlayer() || server->entities[botID]->isHuman()) return;
AIPlayer *bot = (AIPlayer *)server->entities[botID];
bot->deathTrigger = argv[1];
}
SERVER_CONSOLE_COMMAND(bot_stop)
{
if (argc < 1)
{
printfToClient(who, "Usage: bot_stop entID");
return;
}
int botID = atoi(argv[0]);
if(server->entities.find(botID) == server->entities.end()) return;
if(!server->entities[botID]->isPlayer() || server->entities[botID]->isHuman()) return;
AIPlayer *bot = (AIPlayer *)server->entities[botID];
bot->setState(state_stopping);
}
//static initializers
const int AIPlayer::noTarget = -1;
const float AIPlayer::angleErrorRange = 0.045f;
AIPlayer::AIPlayer(
float x,
float y,
ShipType *type,
team_type newTeam)
: Player(type)
{
position.setX(x);
position.setY(y);
position.setR(0);
//for now, let's only deal with one type of ship - aggressive chasers
aiState = state_roaming;
aiRole = role_chaser;
aiSteeringState = steering_state_at_new_dest;
targetID = noTarget;
////this is the waypoint that the bot is nearest to upon spawning
//WaypointMarker *source = getNearestWaypoint();
//currentGoal = source->getPosition();
//oldGoal = getPosition();
//highlight the goal for testing
/*WaypointMarker *dest = server->getWaypointNearestTo(currentGoal);
server->highlightEntity(dest); */
//initialize the bot's steering system
steering = AISteering(this, &position);
targetPosition = Position(0, 0);
aimOffsetX = aimOffsetY = 0;
nextCommand = "";
//if this is a tanker, then ally with the human team
/*if (type->isOnHumanTeam())
{
setTeam(team_human);
canAttack = false;
}
else
{
setTeam(team_enemy);
canAttack = true;
}*/
setTeam(newTeam);
canAttack = type->hasWeapons();
//give human allied turrets extra hitpoints
/*if (canAttack && getTeam() == team_human && !type->isMobile())
health = type->getHitpoints() * turretHitpointScale;*/
shotInaccuracy = randFloat(-botInaccuracy, botInaccuracy);
bool isHumanAlly = getTeam() == team_human;
if (isHumanAlly)
entType = ent_ai_ally_ship;
else
entType = ent_ai_enemy_ship;
sendAdd();
if (isHumanAlly)
server->markAsAlly(this);
}
AIPlayer::~AIPlayer()
{}
int AIPlayer::getCollisionEffect(void)
{
return collide_damage | collide_no_gravity;
}
void AIPlayer::timepass()
{
Player::timepass();
if (shieldTime > 0.0) {
shieldTime -= getDt();
} else {
shielding = false;
shieldTime = 0.0;
}
Entity::timepass();
runAI();
}
//given the bot's position and shot velocity and the
//target's position and velocity, predict where the target will be so that
//the bot leads its shots.
Position AIPlayer::getPredictedTargetPosition()
{
Vector2D targetVelocity = targetPosition.velocityVector();
//assuming that shots don't get ship velocity, (this is true by default)
//we use the shot's velocity as the source velocity
float currentShotSpeed = weapons.primary()->getSpeed();
float shotVelX = currentShotSpeed * cos(getPosition().getR());
float shotVelY = -currentShotSpeed * sin(getPosition().getR());
Vector2D sourceVelocity = Vector2D(shotVelX, shotVelY);
//...here I was going to account for shots getting ship velocity, but
//I can't seem to find where that's being handled...
Vector2D relVelocity = targetVelocity - sourceVelocity;
Vector2D relPosition = targetPosition.positionVector() - getPosition().positionVector();
float closingTime = relPosition.getMagnitude() /
relVelocity.getMagnitude();
Vector2D predictedPos = targetPosition.positionVector() + (targetVelocity * closingTime);
float inaccuracyFactor = targetVelocity.getMagnitude() + 150;
//now add some inaccuracy
predictedPos.x += aimOffsetX*inaccuracyFactor;
predictedPos.y += aimOffsetY*inaccuracyFactor;
aimOffsetX += randFloat(-.03, .03);
aimOffsetY += randFloat(-.03, .03);
aimOffsetX *= 0.99;
aimOffsetY *= 0.99;
////...and now improve your aim
//if (shotInaccuracy > 0)
// shotInaccuracy -= 0.1f;
//else
// shotInaccuracy += 0.1f;
return Position(predictedPos);
}
//called each frame to keep track of the target's position (if it's alive)
//assumed that hasTarget() has been called just before this!
void AIPlayer::updateTargetPosition()
{
Entity *target = server->entities[targetID];
targetPosition = target->getPosition();
}
//returns true if it's time to start facing the target (in chase mode)
bool AIPlayer::shouldFaceTarget() const
{
float maxSpeed = getMaxSpeed();
return (getSpeedSquared() >= maxSpeed * maxSpeed);
}
bool AIPlayer::hasTarget()
{
if (server->entities.find(targetID) == server->entities.end())
{
targetID = noTarget;
return false;
}
else
{
Entity *target = server->entities[targetID];
return isEntityVisible(target);
}
}
float AIPlayer::distSquaredTo(const Position &destination) const
{
return distSquaredBetween(position, destination);
}
//search through the server entities and find a target
int AIPlayer::getBestTargetID() const
{
//if you already have a valid target, then keep it
if (targetID != noTarget)
return targetID;
Server::Entpool::iterator ii;
for (ii = server->entities.begin(); ii != server->entities.end(); ++ii)
{
if (isEntityValid(ii->second))
return ii->first;
}
return noTarget;
}
//returns true if ent is a valid target for the bot, false otherwise
//..."valid" conditions: (for now)
//...1) close enough (within botVisibleRange)
//...2) is a ship
//...3) not the bot itself
//...maybe more to come
bool AIPlayer::isEntityValid(Entity *ent) const
{
bool isCloseEnough = isEntityVisible(ent);
//TODO: add a virtual function, i.e. isShip().
//Only targeting human players for now
bool isPlayer = ent->isPlayer();
bool isNotSelf = ent != this;
bool isEnemy = false;
if (isPlayer)
{
Player *targetShip = (Player *)ent;
isEnemy = !(targetShip->getTeam() == getTeam());// &&
// targetShip->getTeam() == team_free);
}
return (isCloseEnough && isNotSelf && isPlayer && isEnemy);
}
bool AIPlayer::isEntityVisible(Entity *ent) const
{
float minDistSquared = botVisibleRange * botVisibleRange;
return (distSquaredBetween(
position,
ent->getPosition()) <= minDistSquared);
}
bool AIPlayer::isEntityInRange(Entity *ent) const
{
float minRangeSquared = botFiringRange * botFiringRange;
return (distSquaredBetween(
position,
ent->getPosition()) <= minRangeSquared);
}
void AIPlayer::attackTarget(Entity *target)
{
//shoot your target if it happens to cross your path
if (steering.isFacing(targetPosition) &&
isEntityVisible(target) &&
isEntityInRange(target))
fire1(true);
else
fire1(false);
}
void AIPlayer::die(int killer)
{
serverScripting.defineVariable(deathTrigger, retprintf("%i", killer), tag_map_temporary);
Player::die(killer);
}
//
// AIShip methods
//
AIShip::AIShip(
float x,
float y,
ShipType *type,
team_type newTeam
) : AIPlayer(x, y, type, newTeam)
{
//this is the waypoint that the bot is nearest to upon spawning
WaypointMarker *source = getNearestWaypoint();
currentGoal = source->getPosition();
oldGoal = getPosition();
WaypointMarker *dest = server->getWaypointNearestTo(currentGoal);
server->highlightEntity(dest);
shouldStopAtGoal = false;
oldTargetWaypoint = 0;
}
AIShip::~AIShip()
{}
void AIShip::runAI()
{
/* if (botsFrozen)
aiState = state_stopping;
else
aiState = state_chasing;*/
updateGoal();
switch(aiState)
{
case state_roaming:
roam();
break;
case state_chasing:
chase();
break;
case state_evading:
break;
case state_stopping:
stop();
break;
};
// pathfinding.printTraversalSequence();
}
void AIShip::updateGoal()
{
//you've approximately reached your goal, so roam to a new one
if (isCloseToGoal())
{
//refill the traversal stack if empty (if we're at the destination)
if (pathfinding.getNumRemainingWaypoints() == 0)
{
if(nextCommand != "") {
serverScripting.defineVariable(nextCommand, "", tag_map_temporary);
}
WaypointMarker *oldDest = getNearestWaypoint();
server->unhighlightEntity(oldDest);
WaypointMarker *newDest = getRandomGoalFrom(oldDest);
assert(newDest != oldDest);
setNewGoal(newDest);
server->highlightEntity(newDest);
}
else
{
currentGoal = pathfinding.getNextWaypoint()->getPosition();
updateOldGoal();
}
steering.faceNewGoal(currentGoal);
aiSteeringState = steering_state_at_new_dest;
}//if
}
//either pick a random neighbor, or randomly pick a destination and
//construct a path
void AIShip::roam()
{
steering.moveTo(currentGoal);
//make sure we're not shooting!
fire1(false);
//if this is a tanker (non-combat bot) then make sure we can only roam
if (!(canAttack && enableChase))
return;
//try to find a suitable target
targetID = getBestTargetID();
if (targetID != noTarget)
{
//this might act up if a path doesn't exist to the target waypoint
aiState = state_chasing;
}
}
void AIShip::chase()
{
if (!(hasTarget() && canAttack))
{
aiState = state_roaming;
return;
}
updateTargetPosition();
//chase the target (if you're close to the first intermediate goal,
//pop it off the stack and pick the next one)
Entity *target = server->entities[targetID];
if (isCloseToGoal())
{
Position oldPos = currentGoal;
WaypointMarker *newDest = server->getWaypointNearestTo(target->getPosition());
setNewGoal(newDest);
if (!pathfinding.doesPathExistTo(newDest))
setNewGoal(getNearestWaypoint()->getRandomNeighbor());
//keeps bots from stopping at one place
if (currentGoal == oldPos)
setNewGoal(server->getWaypointNearestTo(oldGoal)->getRandomNeighbor());
//pathfinding.getNextWaypoint();
}
//shoot your target if it happens to cross your path
attackTarget(target);
//server->unhighlightEntity(this);
switch(aiSteeringState)
{
//we just arrived at a new waypoint; now decide if the waypoint is far
//enough so that we can thrust, turn, and thrust again. If not, just
//thrust.
case steering_state_at_new_dest:
if (isNextWaypointFarEnough())
aiSteeringState = steering_state_thrust_to_dest;
else
aiSteeringState = steering_state_dest_too_close;
break;
case steering_state_thrust_to_dest:
steering.moveTo(currentGoal);
if (shouldFaceTarget())
aiSteeringState = steering_state_face_target;
break;
case steering_state_face_target:
thrust(false);
brake(false);
if (isNearNextWaypoint())
{
if(steering.isFacing(currentGoal))
thrust(true);
steering.turnTo(currentGoal);
fire1(false);
aiSteeringState = steering_state_return_to_dest;
}
else
{
//steering.turnTo(targetPosition);
steering.turnTo(getPredictedTargetPosition());
//fire1(true);
attackTarget(target);
}
break;
case steering_state_return_to_dest:
/*steering.turnTo(currentGoal);
if (steering.isFacing(currentGoal))
aiSteeringState = steering_state_thrust_to_dest;*/
steering.moveTo(currentGoal);
break;
case steering_state_dest_too_close:
steering.moveTo(currentGoal);
break;
};
}
void AIShip::stop()
{
brake(false);
thrust(false);
fire1(false);
getPosition().setX_vel(0);
getPosition().setY_vel(0);
}
//TODO: fix the vector projections so that the bot stops more accurately
bool AIShip::isCloseToGoal()
{
return (distSquaredTo(currentGoal) <= 9000.0f);
/*Position relPosBetweenGoals = currentGoal - oldGoal;
Position botRelPos = getPosition() - oldGoal;
return (fabs(botRelPos * relPosBetweenGoals) <= 12);*/
/*Position relPos = currentGoal - oldGoal;
float relPosMagnitude = relPos.getMagnitude();
Position posAlongDest = Position(
relPos.getY(),
-relPos.getX()) / relPosMagnitude;
Position projection = posAlongDest * (getPosition() * posAlongDest);
float distToDest = (getPosition() - projection - oldGoal).getMagnitude();
return (distToDest > relPosMagnitude);*/
}
bool AIShip::isNextWaypointFarEnough() const
{
float waypointDistSquared = distSquaredBetween(
position,
currentGoal);
return (waypointDistSquared >= minWaypointDistance);
}
bool AIShip::isNearNextWaypoint() const
{
return (distSquaredBetween(position, currentGoal) <= 15000.0f);
}
//find the map waypoint that is most nearly corresponds to your current position
WaypointMarker *AIShip::getNearestWaypoint() const
{
return (server->getWaypointNearestTo(position));
}
//find the a random goal waypoint starting from your current waypoint
//(i.e. pick a random waypoint that is not the one you are at right now)
WaypointMarker *AIShip::getRandomGoalFrom(WaypointMarker *source) const
{
assert(source != 0);
const Server::WaypointPool &serverWaypoints = server->waypoints;
const int maxWaypointIndex = serverWaypoints.size() - 1;
int randomWaypointIndex = randInt(0, maxWaypointIndex);
WaypointMarker *possibleWaypoint = serverWaypoints.at(randomWaypointIndex);
//found a collision; the random index happened to map to the source waypoint
//randomly select another index -around- that one
if (possibleWaypoint == source)
{
if (randomWaypointIndex == 0)
randomWaypointIndex = randInt(1, maxWaypointIndex);
else if (randomWaypointIndex == maxWaypointIndex)
randomWaypointIndex = randInt(0, maxWaypointIndex - 1);
else
{
//the general case, that a collision is found in the middle
//we split the waypoint vector at the collision; the side with more
//indices will have a higher chance of being picked. We then pick
//a random index from within that side.
const int numIndicesOnLeft = randomWaypointIndex;
const int numIndicesOnRight = maxWaypointIndex - randomWaypointIndex;
const float leftProbability = (float)numIndicesOnLeft /
(float)(numIndicesOnLeft + numIndicesOnRight);
if (randFloat(0, 1) <= leftProbability)
randomWaypointIndex = randInt(0, randomWaypointIndex - 1);
else
randomWaypointIndex = randInt(randomWaypointIndex + 1, maxWaypointIndex);
}
}
//some sanity checks
assert(randomWaypointIndex >= 0);
assert((unsigned)randomWaypointIndex < server->waypoints.size());
assert(server->waypoints.at(randomWaypointIndex) != 0);
return serverWaypoints.at(randomWaypointIndex);
}
//determine the strength/weakness of the target entity based on
//its hitpoints, mass, size, and proximity
float AIShip::rateEntity(Entity *ent)
{
return 0.0f;
}
//used to specify a waypoint that the bot should want to go to.
//useful for issuing bot movement commands via scripting.
void AIShip::setNewGoal(WaypointMarker *destination)
{
//discard all previous intermediate destinations...
pathfinding.clearTraversalSequence();
pathfinding.constructShortestPathTo(
getNearestWaypoint(),
destination);
currentGoal = pathfinding.getNextWaypoint()->getPosition();
updateOldGoal();
}
void AIShip::setNewGoal(const Position &destination)
{
setNewGoal(server->getWaypointNearestTo(destination));
}
void AIShip::updateOldGoal()
{
oldGoal = getPosition();
}
//
// AITurret methods
//
AITurret::AITurret(
float x,
float y,
ShipType *type,
team_type newTeam
):AIPlayer(x, y, type, newTeam)
{}
AITurret::~AITurret()
{}
void AITurret::runAI()
{
if (!canAttack)
return;
//try to find a suitable target
targetID = getBestTargetID();
if (hasTarget())
{
updateTargetPosition();
steering.turnTo(getPredictedTargetPosition());
Entity *target = server->entities[targetID];
attackTarget(target);
}
else
{
fire1(false);
}
}