You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
openmw-tes3mp/apps/openmw/mwmechanics/aicombat.cpp

627 lines
25 KiB
C++

11 years ago
#include "aicombat.hpp"
#include <OgreMath.h>
#include <OgreVector3.h>
11 years ago
#include "../mwworld/class.hpp"
#include "../mwworld/timestamp.hpp"
#include "../mwworld/inventorystore.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/dialoguemanager.hpp"
11 years ago
#include "creaturestats.hpp"
#include "steering.hpp"
#include "movement.hpp"
#include "character.hpp" // fixme: for getActiveWeapon
namespace
{
static float sgn(Ogre::Radian a)
{
if(a.valueDegrees() > 0)
return 1.0;
return -1.0;
}
//chooses an attack depending on probability to avoid uniformity
void chooseBestAttack(const ESM::Weapon* weapon, MWMechanics::Movement &movement);
}
11 years ago
namespace MWMechanics
{
static const float DOOR_CHECK_INTERVAL = 1.5f;
// NOTE: MIN_DIST_TO_DOOR_SQUARED is defined in obstacle.hpp
AiCombat::AiCombat(const MWWorld::Ptr& actor) :
mTarget(actor),
mTimerAttack(0),
mTimerReact(0),
mTimerCombatMove(0),
mFollowTarget(false),
mReadyToAttack(false),
mStrike(false),
mCombatMove(false),
mBackOffDoor(false),
mRotate(false),
mMovement(),
mDoorIter(actor.getCell()->get<ESM::Door>().mList.end()),
mDoors(actor.getCell()->get<ESM::Door>().mList),
mDoorCheckDuration(0),
mTargetAngle(0)
11 years ago
{
}
/*
* The 'pursuit' part of AiCombat now has some memory to allow backtracking.
* The intention is to allow actors to detect being 'stuck' somewhere, whether
* in a river or facing a door, to go back to a known 'good' position.
*
* Each actor goes through these states of movement once alerted and an AiCombat
* package is queued (FIXME: below is a DRAFT proposal only):
*
* - Maybe remember the starting position so that the actor can return if
* lose sight of the target? Last Known Target Location Tracking - keep track
* of target positions every sec, paired with actor's location at the time
*
* - Get to the target if far away (need path finding), how close depends on
* the current best (selected?) weapon. As the actor moves, some breadcrumb
* is left (e.g. every second store a position in a FIFO) so that the actor
* can back track if necessary.
*
* - If the actor gets stuck (need a way of detecting this) then decide what
* to do next. For example, if next to a door then maybe back track one or
* two positions and check LOS of the target every x frames (reaction time?).
* Or maybe back track then look for a new path.
*
* - Once in weapon range, may need a strategy to get to the target for a
* strike (maybe there are others nearby attacking the same target).
*
*
* Current AiCombat movement states (as of 0.29.0), ignoring the details of the
* attack states such as CombatMove, Strike and ReadyToAttack:
*
* +-----(within strike range)----->attack--(beyond strike range)-->follow
* | | ^ | |
* | | | | |
* pursue<----(beyond follow range)-----+ +----(within strike range)---+ |
* ^ |
* | |
* +--------------------------(beyond follow range)--------------------+
*
*
* Below diagram is high level only, FIXME: code detail may be different:
*
* +-----------(same)-------------->attack---------(same)---------->follow
* | |^^ | |
* | ||| | |
* | +--(same)-----------------+|+----------(same)------------+ |
* | | | in range |
* | | too far | |
* | | +---------------got hit or LOS<---+ |
* | <----+ | | |
* pursue<---------+ door | |
* ^^ <--> maybe stuck, check --------------> back up and wait |
* || | ^ | | ^ | |
* || | | | stuck | | | waited |
* || +---+ | +---+ | too long |
* || backtrack | | |
* |+----------------------+ go back? <-----------+ |
* | |
* +----------------------------(same)---------------------------------+
*
* FIXME:
*
* The new scheme is way too complicated, should really be implemented as a
* proper state machine.
*
* TODO:
*
* Use the Observer Pattern to co-ordinate attacks, provide intelligence on
* whether the target was hit, etc.
*
* TODO:
*
* Auto-generate large cubes or squares as a poor-man's navmesh? Many
* external cells do not have any pathgrids, and certainly none for flying
* or swimming.
*
*
* Called from: (check Doxygen as this comment could be out of date)
*
* OMW::Engine::go() |
* Ogre::Root::renderOneFrame() |
* Ogre::Root::... | ... detail omitted
* Ogre::Root::fireFrameRenderingQueued() |
* OMW::Engine::frameRenderingQueued() | virtual Ogre::FrameListener
* MWMechanics::MechanicsManager::update() |
* MWMechanics::Actors::update() |
* MWMechanics::Actors::updateActor() |
* MWMechanics::AiSequence::execute() | from priority queue mPackages
* MWMechanics::AiCombat::execute() | virtual MWMechanics::AiPackage
*/
11 years ago
bool AiCombat::execute (const MWWorld::Ptr& actor,float duration)
11 years ago
{
//General description
11 years ago
if(!actor.getClass().getCreatureStats(actor).isHostile()
|| actor.getClass().getCreatureStats(actor).getHealth().getCurrent() <= 0)
return true;
11 years ago
11 years ago
if(mTarget.getClass().getCreatureStats(mTarget).isDead())
return true;
//Update every frame
if(mCombatMove)
{
mTimerCombatMove -= duration;
if( mTimerCombatMove <= 0)
{
mTimerCombatMove = 0;
mMovement.mPosition[1] = mMovement.mPosition[0] = 0;
mCombatMove = false;
}
}
actor.getClass().getMovementSettings(actor) = mMovement;
if (mRotate)
{
if (zTurn(actor, Ogre::Degree(mTargetAngle)))
mRotate = false;
}
mTimerAttack -= duration;
actor.getClass().getCreatureStats(actor).setAttackingOrSpell(mStrike);
float tReaction = 0.25f;
if(mTimerReact < tReaction)
{
mTimerReact += duration;
return false;
}
11 years ago
//Update with period = tReaction
11 years ago
mTimerReact = 0;
//actual attacking logic
//TODO: Some skills affect period of strikes.For berserk-like style period ~ 0.25f
float attackPeriod = 1.0f;
if(mReadyToAttack)
{
if(mTimerAttack <= -attackPeriod)
{
//TODO: should depend on time between 'start' to 'min attack'
//for better controlling of NPCs' attack strength.
//Also it seems that this time is different for slash/thrust/chop
mTimerAttack = 0.35f * static_cast<float>(rand())/RAND_MAX;
mStrike = true;
//say a provoking combat phrase
if (actor.getClass().isNpc())
{
const MWWorld::ESMStore &store = MWBase::Environment::get().getWorld()->getStore();
int chance = store.get<ESM::GameSetting>().find("iVoiceAttackOdds")->getInt();
int roll = std::rand()/ (static_cast<double> (RAND_MAX) + 1) * 100; // [0, 99]
if (roll < chance)
{
MWBase::Environment::get().getDialogueManager()->say(actor, "attack");
}
}
}
else if (mTimerAttack <= 0)
mStrike = false;
}
else
{
mTimerAttack = -attackPeriod;
mStrike = false;
}
const MWWorld::Class &cls = actor.getClass();
const ESM::Weapon *weapon = NULL;
MWMechanics::WeaponType weaptype;
float weapRange, weapSpeed = 1.0f;
actor.getClass().getCreatureStats(actor).setMovementFlag(CreatureStats::Flag_Run, true);
if (actor.getClass().hasInventoryStore(actor))
11 years ago
{
MWMechanics::DrawState_ state = actor.getClass().getCreatureStats(actor).getDrawState();
11 years ago
if (state == MWMechanics::DrawState_Spell || state == MWMechanics::DrawState_Nothing)
actor.getClass().getCreatureStats(actor).setDrawState(MWMechanics::DrawState_Weapon);
//Get weapon speed and range
MWWorld::ContainerStoreIterator weaponSlot =
MWMechanics::getActiveWeapon(cls.getCreatureStats(actor), cls.getInventoryStore(actor), &weaptype);
if (weaptype == WeapType_HandToHand)
{
const MWWorld::Store<ESM::GameSetting> &gmst =
MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>();
weapRange = gmst.find("fHandToHandReach")->getFloat();
}
else
{
weapon = weaponSlot->get<ESM::Weapon>()->mBase;
weapRange = weapon->mData.mReach;
weapSpeed = weapon->mData.mSpeed;
}
weapRange *= 100.0f;
}
else //is creature
{
weaptype = WeapType_HandToHand; //doesn't matter, should only reflect if it is melee or distant weapon
weapRange = 150; //TODO: use true attack range (the same problem in Creature::hit)
}
ESM::Position pos = actor.getRefData().getPosition();
11 years ago
/*
* Some notes on meanings of variables:
*
* rangeMelee:
*
* - Distance where attack using the actor's weapon is possible
* - longer for ranged weapons (obviously?) vs. melee weapons
* - Once within this distance mFollowTarget is triggered
* (TODO: check whether the follow logic still works for ranged
* weapons, since rangeCloseup is set to zero)
* - TODO: The variable name is confusing. It was ok when AiCombat only
* had melee weapons but now that ranged weapons are supported that is
* no longer the case. It should really be renamed to something
* like rangeStrike - alternatively, keep this name for melee
* weapons and use a different variable for tracking ranged weapon
* distance (rangeRanged maybe?)
*
* rangeCloseup:
*
* - Applies to melee weapons or hand to hand only (or creatures without
* weapons)
* - Distance a little further away from the actor's weapon strike
* i.e. rangeCloseup > rangeMelee for melee weapons
* (the variable names make this simple concept counter-intuitive,
* something like rangeMelee > rangeStrike may be better)
* - Once the target gets beyond this distance mFollowTarget is cleared
* and a path to the target needs to be found
* - TODO: Possibly rename this variable to rangeMelee or even rangeFollow
*
* mFollowTarget:
*
* - Once triggered, the actor follows the target with LOS shortcut
* (the shortcut really only applies to cells where pathgrids are
* available, since the default path without pathgrids is direct to
* target even if LOS is not achieved)
*
*/
float rangeMelee;
float rangeCloseUp;
bool distantCombat = false;
11 years ago
if (weaptype==WeapType_BowAndArrow || weaptype==WeapType_Crossbow || weaptype==WeapType_Thrown)
{
rangeMelee = 1000; // TODO: should depend on archer skill
rangeCloseUp = 0; //doesn't needed when attacking from distance
distantCombat = true;
}
else
{
rangeMelee = weapRange;
rangeCloseUp = 300;
}
11 years ago
Ogre::Vector3 vStart(pos.pos[0], pos.pos[1], pos.pos[2]);
ESM::Position targetPos = mTarget.getRefData().getPosition();
Ogre::Vector3 vDest(targetPos.pos[0], targetPos.pos[1], targetPos.pos[2]);
Ogre::Vector3 vDir = vDest - vStart;
float distBetween = vDir.length();
// (within strike dist) || (not quite strike dist while following)
if(distBetween < rangeMelee || (distBetween <= rangeCloseUp && mFollowTarget) )
{
//Melee and Close-up combat
vDir.z = 0;
float dirLen = vDir.length();
mTargetAngle = Ogre::Radian( Ogre::Math::ACos(vDir.y / dirLen) * sgn(Ogre::Math::ASin(vDir.x / dirLen)) ).valueDegrees();
mRotate = true;
11 years ago
//bool LOS = MWBase::Environment::get().getWorld()->getLOS(actor, mTarget);
// (not quite strike dist while following)
if (mFollowTarget && distBetween > rangeMelee)
{
//Close-up combat: just run up on target
mMovement.mPosition[1] = 1;
}
else // (within strike dist)
{
//Melee: stop running and attack
mMovement.mPosition[1] = 0;
// When attacking with a weapon, choose between slash, thrust or chop
if (actor.getClass().hasInventoryStore(actor))
chooseBestAttack(weapon, mMovement);
if(mMovement.mPosition[0] || mMovement.mPosition[1])
{
mTimerCombatMove = 0.1f + 0.1f * static_cast<float>(rand())/RAND_MAX;
mCombatMove = true;
}
else if(actor.getClass().isNpc() && (!distantCombat || (distantCombat && rangeMelee/5)))
{
//apply sideway movement (kind of dodging) with some probability
if(static_cast<float>(rand())/RAND_MAX < 0.25)
{
mMovement.mPosition[0] = static_cast<float>(rand())/RAND_MAX < 0.5? 1: -1;
mTimerCombatMove = 0.05f + 0.15f * static_cast<float>(rand())/RAND_MAX;
mCombatMove = true;
}
}
11 years ago
if(distantCombat && distBetween < rangeMelee/4)
{
mMovement.mPosition[1] = -1;
}
mReadyToAttack = true;
//only once got in melee combat, actor is allowed to use close-up shortcutting
mFollowTarget = true;
}
}
else
{
//target is at far distance: build path to target
mFollowTarget = false;
buildNewPath(actor); //may fail to build a path, check before use
//delete visited path node
mPathFinder.checkPathCompleted(pos.pos[0],pos.pos[1],pos.pos[2]);
//if no new path leave mTargetAngle unchanged
if(!mPathFinder.getPath().empty())
{
//try shortcut
if(vDir.length() < mPathFinder.getDistToNext(pos.pos[0],pos.pos[1],pos.pos[2]) && MWBase::Environment::get().getWorld()->getLOS(actor, mTarget))
mTargetAngle = Ogre::Radian( Ogre::Math::ACos(vDir.y / vDir.length()) * sgn(Ogre::Math::ASin(vDir.x / vDir.length())) ).valueDegrees();
else
mTargetAngle = mPathFinder.getZAngleToNext(pos.pos[0], pos.pos[1]);
mRotate = true;
}
mMovement.mPosition[1] = 1;
mReadyToAttack = false;
// remember that this section gets updated every tReaction, which is
// currently hard coded at 250ms or 1/4 second
if(mObstacleCheck.check(actor, tReaction)) // true if evasive action needed
{
std::cout<<"found obstacle"<<std::endl;
// first check if we're walking into a door
bool foundClosedDoor = false;
MWWorld::CellStore *cell = actor.getCell();
if(!cell->getCell()->isExterior())
{
// Check all the doors in this cell
mDoors = cell->get<ESM::Door>().mList; // update list member
mDoorIter = mDoors.begin();
Ogre::Vector3 actorPos(actor.getRefData().getPosition().pos);
for (; mDoorIter != mDoors.end(); ++mDoorIter)
{
MWWorld::LiveCellRef<ESM::Door>& ref = *mDoorIter;
if(actorPos.squaredDistance(Ogre::Vector3(ref.mRef.mPos.pos)) < 1.3*1.3*MIN_DIST_TO_DOOR_SQUARED &&
ref.mData.getLocalRotation().rot[2] == 0)
{
std::cout<<"closed door id \""<<ref.mRef.mRefID<<"\""<<std::endl;
foundClosedDoor = true;
break;
}
}
}
if(foundClosedDoor)
{
mBackOffDoor = true;
mObstacleCheck.clear();
if(mFollowTarget) // FIXME: probably not needed
{
std::cout<<"follow door"<<std::endl;
mFollowTarget = false;
}
}
else // probably walking into another NPC
{
// TODO: diagonal should have same animation as walk forward
// but doesn't seem to do that?
actor.getClass().getMovementSettings(actor).mPosition[0] = 1;
actor.getClass().getMovementSettings(actor).mPosition[1] = 0.1f;
// change the angle a bit, too
if(mPathFinder.isPathConstructed())
zTurn(actor, Ogre::Degree(mPathFinder.getZAngleToNext(pos.pos[0] + 1, pos.pos[1])));
}
}
}
if(distBetween > rangeMelee)
{
//special run attack; it shouldn't affect melee combat tactics
if(actor.getClass().getMovementSettings(actor).mPosition[1] == 1)
11 years ago
{
//check if actor can overcome the distance = distToTarget - attackerWeapRange
//less than in time of playing weapon anim from 'start' to 'hit' tags (t_swing)
//then start attacking
float speed1 = cls.getSpeed(actor);
float speed2 = mTarget.getClass().getSpeed(mTarget);
if(mTarget.getClass().getMovementSettings(mTarget).mPosition[0] == 0
&& mTarget.getClass().getMovementSettings(mTarget).mPosition[1] == 0)
speed2 = 0;
float s1 = distBetween - weapRange;
float t = s1/speed1;
float s2 = speed2 * t;
float t_swing = 0.17f/weapSpeed;//instead of 0.17 should be the time of playing weapon anim from 'start' to 'hit' tags
if (t + s2/speed1 <= t_swing)
{
mReadyToAttack = true;
if(mTimerAttack <= -attackPeriod)
{
mTimerAttack = 0.3f*static_cast<float>(rand())/RAND_MAX;
mStrike = true;
}
}
11 years ago
}
}
11 years ago
MWWorld::LiveCellRef<ESM::Door>& ref = *mDoorIter;
Ogre::Vector3 actorPos(actor.getRefData().getPosition().pos);
if(mBackOffDoor &&
actorPos.squaredDistance(Ogre::Vector3(ref.mRef.mPos.pos)) < 1.5*1.5*MIN_DIST_TO_DOOR_SQUARED)
{
mMovement.mPosition[1] = -0.2; // back off, but slowly
if(mDoorIter != mDoors.end() && ref.mData.getLocalRotation().rot[2] >= 1) // open
{
mDoorIter = mDoors.end();
mBackOffDoor = false;
std::cout<<"open door id \""<<ref.mRef.mRefID<<"\""<<std::endl;
}
}
else
{
if(mReadyToAttack && !mBackOffDoor)
{
std::cout<<"ready to attack, move forward"<<std::endl;
mMovement.mPosition[1] = 1; // FIXME: oscillates?
}
}
actor.getClass().getMovementSettings(actor) = mMovement;
return false;
}
11 years ago
void AiCombat::buildNewPath(const MWWorld::Ptr& actor)
{
//Construct path to target
ESM::Pathgrid::Point dest;
dest.mX = mTarget.getRefData().getPosition().pos[0];
dest.mY = mTarget.getRefData().getPosition().pos[1];
dest.mZ = mTarget.getRefData().getPosition().pos[2];
Ogre::Vector3 newPathTarget = Ogre::Vector3(dest.mX, dest.mY, dest.mZ);
float dist = -1; //hack to indicate first time, to construct a new path
if(!mPathFinder.getPath().empty())
{
ESM::Pathgrid::Point lastPt = mPathFinder.getPath().back();
Ogre::Vector3 currPathTarget(lastPt.mX, lastPt.mY, lastPt.mZ);
dist = Ogre::Math::Abs((newPathTarget - currPathTarget).length());
}
11 years ago
float targetPosThreshold;
bool isOutside = actor.getCell()->getCell()->isExterior();
if (isOutside)
targetPosThreshold = 300;
else
targetPosThreshold = 100;
if((dist < 0) || (dist > targetPosThreshold))
{
//construct new path only if target has moved away more than on <targetPosThreshold>
ESM::Position pos = actor.getRefData().getPosition();
11 years ago
ESM::Pathgrid::Point start;
start.mX = pos.pos[0];
start.mY = pos.pos[1];
start.mZ = pos.pos[2];
if(!mPathFinder.isPathConstructed())
mPathFinder.buildPath(start, dest, actor.getCell(), isOutside);
else
{
PathFinder newPathFinder;
newPathFinder.buildPath(start, dest, actor.getCell(), isOutside);
//TO EXPLORE:
//maybe here is a mistake (?): PathFinder::getPathSize() returns number of grid points in the path,
//not the actual path length. Here we should know if the new path is actually more effective.
//if(pathFinder2.getPathSize() < mPathFinder.getPathSize())
if(!mPathFinder.getPath().empty())
{
newPathFinder.syncStart(mPathFinder.getPath());
mPathFinder = newPathFinder;
}
}
11 years ago
}
}
int AiCombat::getTypeId() const
{
return TypeIdCombat;
}
unsigned int AiCombat::getPriority() const
{
return 1;
11 years ago
}
const std::string &AiCombat::getTargetId() const
{
return mTarget.getRefData().getHandle();
}
11 years ago
AiCombat *MWMechanics::AiCombat::clone() const
{
return new AiCombat(*this);
}
}
11 years ago
namespace
{
void chooseBestAttack(const ESM::Weapon* weapon, MWMechanics::Movement &movement)
{
if (weapon == NULL)
{
//hand-to-hand deal equal damage for each type
float roll = static_cast<float>(rand())/RAND_MAX;
if(roll <= 0.333f) //side punch
{
movement.mPosition[0] = (static_cast<float>(rand())/RAND_MAX < 0.5f)? 1: -1;
movement.mPosition[1] = 0;
}
else if(roll <= 0.666f) //forward punch
movement.mPosition[1] = 1;
else
{
movement.mPosition[1] = movement.mPosition[0] = 0;
}
return;
}
//the more damage attackType deals the more probability it has
int slash = (weapon->mData.mSlash[0] + weapon->mData.mSlash[1])/2;
int chop = (weapon->mData.mChop[0] + weapon->mData.mChop[1])/2;
int thrust = (weapon->mData.mThrust[0] + weapon->mData.mThrust[1])/2;
float total = slash + chop + thrust;
float roll = static_cast<float>(rand())/RAND_MAX;
if(roll <= static_cast<float>(slash)/total)
{
movement.mPosition[0] = (static_cast<float>(rand())/RAND_MAX < 0.5f)? 1: -1;
movement.mPosition[1] = 0;
}
else if(roll <= (static_cast<float>(slash) + static_cast<float>(thrust))/total)
movement.mPosition[1] = 1;
else
movement.mPosition[1] = movement.mPosition[0] = 0;
11 years ago
}
}