コード例 #1
0
ファイル: aicombat.cpp プロジェクト: devnexen/openmw
    bool AiCombat::attack(const MWWorld::Ptr& actor, const MWWorld::Ptr& target, AiCombatStorage& storage, CharacterController& characterController)
    {
        const MWWorld::CellStore*& currentCell = storage.mCell;
        bool cellChange = currentCell && (actor.getCell() != currentCell);
        if(!currentCell || cellChange)
        {
            currentCell = actor.getCell();
        }

        bool forceFlee = false;
        if (!canFight(actor, target))
        {
            storage.stopAttack();
            characterController.setAttackingOrSpell(false);
            storage.mActionCooldown = 0.f;
            // Continue combat if target is player or player follower/escorter and an attack has been attempted
            const std::list<MWWorld::Ptr>& playerFollowersAndEscorters = MWBase::Environment::get().getMechanicsManager()->getActorsSidingWith(MWMechanics::getPlayer());
            bool targetSidesWithPlayer = (std::find(playerFollowersAndEscorters.begin(), playerFollowersAndEscorters.end(), target) != playerFollowersAndEscorters.end());
            if ((target == MWMechanics::getPlayer() || targetSidesWithPlayer)
                && ((actor.getClass().getCreatureStats(actor).getHitAttemptActorId() == target.getClass().getCreatureStats(target).getActorId())
                || (target.getClass().getCreatureStats(target).getHitAttemptActorId() == actor.getClass().getCreatureStats(actor).getActorId())))
                forceFlee = true;
            else // Otherwise end combat
                return true;
        }

        const MWWorld::Class& actorClass = actor.getClass();
        actorClass.getCreatureStats(actor).setMovementFlag(CreatureStats::Flag_Run, true);

        float& actionCooldown = storage.mActionCooldown;
        std::shared_ptr<Action>& currentAction = storage.mCurrentAction;

        if (!forceFlee)
        {
            if (actionCooldown > 0)
                return false;

            if (characterController.readyToPrepareAttack())
            {
                currentAction = prepareNextAction(actor, target);
                actionCooldown = currentAction->getActionCooldown();
            }
        }
        else
        {
            currentAction.reset(new ActionFlee());
            actionCooldown = currentAction->getActionCooldown();
        }

        if (!currentAction)
            return false;

        if (storage.isFleeing() != currentAction->isFleeing())
        {
            if (currentAction->isFleeing())
            {
                storage.startFleeing();
                MWBase::Environment::get().getDialogueManager()->say(actor, "flee");
                return false;
            }
            else
                storage.stopFleeing();
        }

        bool isRangedCombat = false;
        float &rangeAttack = storage.mAttackRange;

        rangeAttack = currentAction->getCombatRange(isRangedCombat);

        // Get weapon characteristics
        const ESM::Weapon* weapon = currentAction->getWeapon();

        ESM::Position pos = actor.getRefData().getPosition();
        osg::Vec3f vActorPos(pos.asVec3());
        osg::Vec3f vTargetPos(target.getRefData().getPosition().asVec3());

        osg::Vec3f vAimDir = MWBase::Environment::get().getWorld()->aimToTarget(actor, target);
        float distToTarget = MWBase::Environment::get().getWorld()->getHitDistance(actor, target);

        storage.mReadyToAttack = (currentAction->isAttackingOrSpell() && distToTarget <= rangeAttack && storage.mLOS);

        if (storage.mReadyToAttack)
        {
            storage.startCombatMove(isRangedCombat, distToTarget, rangeAttack, actor, target);
            // start new attack
            storage.startAttackIfReady(actor, characterController, weapon, isRangedCombat);

            if (isRangedCombat)
            {
                // rotate actor taking into account target movement direction and projectile speed
                osg::Vec3f& lastTargetPos = storage.mLastTargetPos;
                vAimDir = AimDirToMovingTarget(actor, target, lastTargetPos, AI_REACTION_TIME, (weapon ? weapon->mData.mType : 0), storage.mStrength);
                lastTargetPos = vTargetPos;

                storage.mMovement.mRotation[0] = getXAngleToDir(vAimDir);
                storage.mMovement.mRotation[2] = getZAngleToDir(vAimDir);
            }
            else
            {
                storage.mMovement.mRotation[0] = getXAngleToDir(vAimDir);
                storage.mMovement.mRotation[2] = getZAngleToDir((vTargetPos-vActorPos)); // using vAimDir results in spastic movements since the head is animated
            }
        }
        return false;
    }
コード例 #2
0
ファイル: aicombat.cpp プロジェクト: Kleptoid/openmw
    /*
     * 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, the code detail is a little different
     * (but including those detail will just complicate the diagram w/o adding much)
     *
     *    +----------(same)-------------->attack---------(same)---------->follow
     *    |                                 |^^                            |||
     *    |                                 |||                            |||
     *    |       +--(same)-----------------+|+----------(same)------------+||
     *    |       |                          |                              ||
     *    |       |                          | (in range)                   ||
     *    |   <---+         (too far)        |                              ||
     *  pursue<-------------------------[door open]<-----+                  ||
     *    ^^^                                            |                  ||
     *    |||                                            |                  ||
     *    ||+----------evade-----+                       |                  ||
     *    ||                     |    [closed door]      |                  ||
     *    |+----> maybe stuck, check --------------> back up, check door    ||
     *    |         ^   |   ^                          |   ^                ||
     *    |         |   |   |                          |   |                ||
     *    |         |   +---+                          +---+                ||
     *    |         +-------------------------------------------------------+|
     *    |                                                                  |
     *    +---------------------------(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.
     */
    bool AiCombat::execute (const MWWorld::Ptr& actor, AiState& state, float duration)
    {
        // get or create temporary storage
        AiCombatStorage& storage = state.get<AiCombatStorage>();
        

        
        //General description
        if(actor.getClass().getCreatureStats(actor).isDead())
            return true;

        MWWorld::Ptr target = MWBase::Environment::get().getWorld()->searchPtrViaActorId(mTargetActorId);
        if (target.isEmpty())
            return false;

        if(!target.getRefData().getCount() || !target.getRefData().isEnabled()  // Really we should be checking whether the target is currently registered
                                                                                // with the MechanicsManager
                || target.getClass().getCreatureStats(target).isDead())
            return true;

        const MWWorld::Class& actorClass = actor.getClass();
        MWBase::World* world = MWBase::Environment::get().getWorld();


        //Update every frame
        bool& combatMove = storage.mCombatMove;
        float& timerCombatMove = storage.mTimerCombatMove; 
        MWMechanics::Movement& movement = storage.mMovement;
        if(combatMove)
        {
            timerCombatMove -= duration;
            if( timerCombatMove <= 0)
            {
                timerCombatMove = 0;
                movement.mPosition[1] = movement.mPosition[0] = 0;
                combatMove = false;
            }
        }

        actorClass.getMovementSettings(actor) = movement;
        actorClass.getMovementSettings(actor).mRotation[0] = 0;
        actorClass.getMovementSettings(actor).mRotation[2] = 0;

        if(movement.mRotation[2] != 0)
        {
            if(zTurn(actor, Ogre::Degree(movement.mRotation[2]))) movement.mRotation[2] = 0;
        }

        if(movement.mRotation[0] != 0)
        {
            if(smoothTurn(actor, Ogre::Degree(movement.mRotation[0]), 0)) movement.mRotation[0] = 0;
        }

        //TODO: Some skills affect period of strikes.For berserk-like style period ~ 0.25f
        float attacksPeriod = 1.0f;

        ESM::Weapon::AttackType attackType;


        
        
        bool& attack = storage.mAttack;
        bool& readyToAttack = storage.mReadyToAttack;
        float& timerAttack = storage.mTimerAttack;
        
        bool& minMaxAttackDurationInitialised = storage.mMinMaxAttackDurationInitialised;
        float (&minMaxAttackDuration)[3][2] = storage.mMinMaxAttackDuration;
        
        if(readyToAttack)
        {
            if (!minMaxAttackDurationInitialised)
            {
                // TODO: this must be updated when a different weapon is equipped
                getMinMaxAttackDuration(actor, minMaxAttackDuration);
                minMaxAttackDurationInitialised = true;
            }

            if (timerAttack < 0) attack = false;

            timerAttack -= duration;
        }
        else
        {
            timerAttack = -attacksPeriod;
            attack = false;
        }

        actorClass.getCreatureStats(actor).setAttackingOrSpell(attack);


        float& actionCooldown = storage.mActionCooldown;
        actionCooldown -= duration;
        
        float& timerReact = storage.mTimerReact;
        float tReaction = 0.25f;
        if(timerReact < tReaction)
        {
            timerReact += duration;
            return false;
        }

        //Update with period = tReaction

        // Stop attacking if target is not seen
        if (target.getClass().getCreatureStats(target).getMagicEffects().get(ESM::MagicEffect::Invisibility).getMagnitude() > 0
                || target.getClass().getCreatureStats(target).getMagicEffects().get(ESM::MagicEffect::Chameleon).getMagnitude() > 75)
        {
            movement.mPosition[1] = movement.mPosition[0] = 0;
            return false; // TODO: run away instead of doing nothing
        }

        timerReact = 0;
        const MWWorld::CellStore*& currentCell = storage.mCell;
        bool cellChange = currentCell && (actor.getCell() != currentCell);
        if(!currentCell || cellChange)
        {
            currentCell = actor.getCell();
        }

        MWRender::Animation* anim = MWBase::Environment::get().getWorld()->getAnimation(actor);
        if (!anim) // shouldn't happen
            return false;

        actorClass.getCreatureStats(actor).setMovementFlag(CreatureStats::Flag_Run, true);

        if (actionCooldown > 0)
            return false;

        float rangeAttack = 0;
        float rangeFollow = 0;
        boost::shared_ptr<Action>& currentAction = storage.mCurrentAction;
        if (anim->upperBodyReady())
        {
            currentAction = prepareNextAction(actor, target);
            actionCooldown = currentAction->getActionCooldown();
        }

        if (currentAction.get())
            currentAction->getCombatRange(rangeAttack, rangeFollow);

        // FIXME: consider moving this stuff to ActionWeapon::getCombatRange
        const ESM::Weapon *weapon = NULL;
        MWMechanics::WeaponType weaptype = WeapType_None;
        float weapRange = 1.0f;

        // Get weapon characteristics
        if (actorClass.hasInventoryStore(actor))
        {
            // TODO: Check equipped weapon and equip a different one if we can't attack with it
            // (e.g. no ammunition, or wrong type of ammunition equipped, etc. autoEquip is not very smart in this regard))

            //Get weapon speed and range
            MWWorld::ContainerStoreIterator weaponSlot =
                MWMechanics::getActiveWeapon(actorClass.getCreatureStats(actor), actorClass.getInventoryStore(actor), &weaptype);

            if (weaptype == WeapType_HandToHand)
            {
                static float fHandToHandReach =
                    world->getStore().get<ESM::GameSetting>().find("fHandToHandReach")->getFloat();
                weapRange = fHandToHandReach;
            }
            else if (weaptype != WeapType_PickProbe && weaptype != WeapType_Spell && weaptype != WeapType_None)
            {
                // All other WeapTypes are actually weapons, so get<ESM::Weapon> is safe.
                weapon = weaponSlot->get<ESM::Weapon>()->mBase;
                weapRange = weapon->mData.mReach;
            }
            weapRange *= 100.0f;
        }
        else //is creature
        {
            weaptype = actorClass.getCreatureStats(actor).getDrawState() == DrawState_Spell ? WeapType_Spell : WeapType_HandToHand;
            weapRange = 150.0f; //TODO: use true attack range (the same problem in Creature::hit)
        }

        bool distantCombat = false;
        if (weaptype != WeapType_Spell)
        {
            // TODO: move to ActionWeapon
            if (weaptype == WeapType_BowAndArrow || weaptype == WeapType_Crossbow || weaptype == WeapType_Thrown)
            {
                rangeAttack = 1000;
                rangeFollow = 0; // not needed in ranged combat
                distantCombat = true;
            }
            else
            {
                rangeAttack = weapRange;
                rangeFollow = 300;
            }
        }
        else
        {
            distantCombat = (rangeAttack > 500);
            weapRange = 150.f;
        }

        
        float& strength = storage.mStrength;      
        // start new attack
        if(readyToAttack)
        {
            if(timerAttack <= -attacksPeriod)
            {
                attack = true; // attack starts just now

                if (!distantCombat) attackType = chooseBestAttack(weapon, movement);
                else attackType = ESM::Weapon::AT_Chop; // cause it's =0

                strength = OEngine::Misc::Rng::rollClosedProbability();

                // Note: may be 0 for some animations
                timerAttack = minMaxAttackDuration[attackType][0] + 
                    (minMaxAttackDuration[attackType][1] - minMaxAttackDuration[attackType][0]) * strength;

                //say a provoking combat phrase
                if (actor.getClass().isNpc())
                {
                    const MWWorld::ESMStore &store = world->getStore();
                    int chance = store.get<ESM::GameSetting>().find("iVoiceAttackOdds")->getInt();
                    if (OEngine::Misc::Rng::roll0to99() < chance)
                    {
                        MWBase::Environment::get().getDialogueManager()->say(actor, "attack");
                    }
                }
            }
        }


        /*
         * Some notes on meanings of variables:
         *
         * rangeAttack:
         *
         *  - Distance where attack using the actor's weapon is possible:
         *    longer for ranged weapons (obviously?) vs. melee weapons
         *  - Determined by weapon's reach parameter; hardcoded value
         *    for ranged weapon and for creatures
         *  - Once within this distance mFollowTarget is triggered
         *
         * rangeFollow:
         *
         *  - Applies to melee weapons or hand to hand only (or creatures without
         *    weapons)
         *  - Distance a little further away than the actor's weapon reach
         *    i.e. rangeFollow > rangeAttack for melee weapons
         *  - Hardcoded value (0 for ranged weapons)
         *  - Once the target gets beyond this distance mFollowTarget is cleared
         *    and a path to the target needs to be found
         *
         * 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)
         */

        ESM::Position pos = actor.getRefData().getPosition();
        Ogre::Vector3 vActorPos(pos.pos);
        Ogre::Vector3 vTargetPos(target.getRefData().getPosition().pos);
        Ogre::Vector3 vDirToTarget = vTargetPos - vActorPos;
        float distToTarget = vDirToTarget.length();
        
        Ogre::Vector3& lastActorPos = storage.mLastActorPos;
        bool& followTarget = storage.mFollowTarget;

        bool isStuck = false;
        float speed = 0.0f;
        if(movement.mPosition[1] && (lastActorPos - vActorPos).length() < (speed = actorClass.getSpeed(actor)) * tReaction / 2)
            isStuck = true;

        lastActorPos = vActorPos;

        // check if actor can move along z-axis
        bool canMoveByZ = (actorClass.canSwim(actor) && world->isSwimming(actor))
            || world->isFlying(actor);

        // for distant combat we should know if target is in LOS even if distToTarget < rangeAttack 
        bool inLOS = distantCombat ? world->getLOS(actor, target) : true;

        // can't fight if attacker can't go where target is.  E.g. A fish can't attack person on land.
        if (distToTarget >= rangeAttack
                && !actorClass.isNpc() && !MWMechanics::isEnvironmentCompatible(actor, target))
        {
            // TODO: start fleeing?
            movement.mPosition[0] = 0;
            movement.mPosition[1] = 0;
            movement.mPosition[2] = 0;
            readyToAttack = false;
            actorClass.getCreatureStats(actor).setAttackingOrSpell(false);
            return false;
        }

        // (within attack dist) || (not quite attack dist while following)
        if(inLOS && (distToTarget < rangeAttack || (distToTarget <= rangeFollow && followTarget && !isStuck)))
        {
            //Melee and Close-up combat
            
            // getXAngleToDir determines vertical angle to target:
            // if actor can move along z-axis it will control movement dir
            // if can't - it will control correct aiming.
            // note: in getZAngleToDir if we preserve dir.z then horizontal angle can be inaccurate
            if (distantCombat)
            {
                Ogre::Vector3& lastTargetPos = storage.mLastTargetPos;
                Ogre::Vector3 vAimDir = AimDirToMovingTarget(actor, target, lastTargetPos, tReaction, weaptype, strength);
                lastTargetPos = vTargetPos;
                movement.mRotation[0] = getXAngleToDir(vAimDir);
                movement.mRotation[2] = getZAngleToDir(vAimDir);
            }
            else
            {
                movement.mRotation[0] = getXAngleToDir(vDirToTarget, distToTarget);
                movement.mRotation[2] = getZAngleToDir(vDirToTarget);
            }

            // (not quite attack dist while following)
            if (followTarget && distToTarget > rangeAttack)
            {
                //Close-up combat: just run up on target
                movement.mPosition[1] = 1;
            }
            else // (within attack dist)
            {
                if(movement.mPosition[0] || movement.mPosition[1])
                {
                    timerCombatMove = 0.1f + 0.1f * OEngine::Misc::Rng::rollClosedProbability();
                    combatMove = true;
                }
                // only NPCs are smart enough to use dodge movements
                else if(actorClass.isNpc() && (!distantCombat || (distantCombat && distToTarget < rangeAttack/2)))
                {
                    //apply sideway movement (kind of dodging) with some probability
                    if (OEngine::Misc::Rng::rollClosedProbability() < 0.25)
                    {
                        movement.mPosition[0] = OEngine::Misc::Rng::rollProbability() < 0.5 ? 1.0f : -1.0f;
                        timerCombatMove = 0.05f + 0.15f * OEngine::Misc::Rng::rollClosedProbability();
                        combatMove = true;
                    }
                }

                if(distantCombat && distToTarget < rangeAttack/4)
                {
                    movement.mPosition[1] = -1;
                }

                readyToAttack = true;
                //only once got in melee combat, actor is allowed to use close-up shortcutting
                followTarget = true;
            }
        }
        else // remote pathfinding
        {
            bool preferShortcut = false;
            if (!distantCombat) inLOS = world->getLOS(actor, target);

            // check if shortcut is available
            bool& forceNoShortcut = storage.mForceNoShortcut;
            ESM::Position& shortcutFailPos = storage.mShortcutFailPos;
            
            if(inLOS && (!isStuck || readyToAttack)
                && (!forceNoShortcut || (Ogre::Vector3(shortcutFailPos.pos) - vActorPos).length() >= PATHFIND_SHORTCUT_RETRY_DIST))
            {
                if(speed == 0.0f) speed = actorClass.getSpeed(actor);
                // maximum dist before pit/obstacle for actor to avoid them depending on his speed
                float maxAvoidDist = tReaction * speed + speed / MAX_VEL_ANGULAR.valueRadians() * 2; // *2 - for reliability
				preferShortcut = checkWayIsClear(vActorPos, vTargetPos, Ogre::Vector3(vDirToTarget.x, vDirToTarget.y, 0).length() > maxAvoidDist*1.5? maxAvoidDist : maxAvoidDist/2);
            }

            // don't use pathgrid when actor can move in 3 dimensions
            if(canMoveByZ) preferShortcut = true;

            if(preferShortcut)
            {
                if (canMoveByZ)
                    movement.mRotation[0] = getXAngleToDir(vDirToTarget, distToTarget);
                movement.mRotation[2] = getZAngleToDir(vDirToTarget);
                forceNoShortcut = false;
                shortcutFailPos.pos[0] = shortcutFailPos.pos[1] = shortcutFailPos.pos[2] = 0;
                mPathFinder.clearPath();
            }
            else // if shortcut failed stick to path grid
            {
                if(!isStuck && shortcutFailPos.pos[0] == 0.0f && shortcutFailPos.pos[1] == 0.0f && shortcutFailPos.pos[2] == 0.0f)
                {
                    forceNoShortcut = true;
                    shortcutFailPos = pos;
                }

                followTarget = false;

                buildNewPath(actor, target); //may fail to build a path, check before use

                //delete visited path node
                mPathFinder.checkPathCompleted(pos.pos[0],pos.pos[1]);

                // This works on the borders between the path grid and areas with no waypoints.
                if(inLOS && mPathFinder.getPath().size() > 1)
                {
                    // get point just before target
                    std::list<ESM::Pathgrid::Point>::const_iterator pntIter = --mPathFinder.getPath().end();
                    --pntIter;
                    Ogre::Vector3 vBeforeTarget(PathFinder::MakeOgreVector3(*pntIter));

                    // if current actor pos is closer to target then last point of path (excluding target itself) then go straight on target
                    if(distToTarget <= (vTargetPos - vBeforeTarget).length())
                    {
                        movement.mRotation[2] = getZAngleToDir(vDirToTarget);
                        preferShortcut = true;
                    }
                }

                // if there is no new path, then go straight on target
                if(!preferShortcut)
                {
                    if(!mPathFinder.getPath().empty())
                        movement.mRotation[2] = mPathFinder.getZAngleToNext(pos.pos[0], pos.pos[1]);
                    else
                        movement.mRotation[2] = getZAngleToDir(vDirToTarget);
                }
            }

            movement.mPosition[1] = 1;
            if (readyToAttack)
            {
                // to stop possible sideway moving after target moved out of attack range
                combatMove = true;
                timerCombatMove = 0;
            }
            readyToAttack = false;
        }

        if(!isStuck && distToTarget > rangeAttack && !distantCombat)
        {
            //special run attack; it shouldn't affect melee combat tactics
            if(actorClass.getMovementSettings(actor).mPosition[1] == 1)
            {
                /*  check if actor can overcome the distance = distToTarget - attackerWeapRange
                    less than in time of swinging with weapon (t_swing), then start attacking 
                */
                float speed1 = actorClass.getSpeed(actor);
                float speed2 = target.getClass().getSpeed(target);
                if(target.getClass().getMovementSettings(target).mPosition[0] == 0
                        && target.getClass().getMovementSettings(target).mPosition[1] == 0)
                    speed2 = 0;

                float s1 = distToTarget - weapRange;
                float t = s1/speed1;
                float s2 = speed2 * t;
                float t_swing = 
                    minMaxAttackDuration[ESM::Weapon::AT_Thrust][0] + 
                    (minMaxAttackDuration[ESM::Weapon::AT_Thrust][1] - minMaxAttackDuration[ESM::Weapon::AT_Thrust][0]) * OEngine::Misc::Rng::rollClosedProbability();

                if (t + s2/speed1 <= t_swing)
                {
                    readyToAttack = true;
                    if(timerAttack <= -attacksPeriod)
                    {
                        timerAttack = t_swing;
                        attack = true;
                    }
                }
            }
        }

        // NOTE: This section gets updated every tReaction, which is currently hard
        //       coded at 250ms or 1/4 second
        //
        // TODO: Add a parameter to vary DURATION_SAME_SPOT?
        if((distToTarget > rangeAttack || followTarget) &&
            mObstacleCheck.check(actor, tReaction)) // check if evasive action needed
        {
            // probably walking into another NPC TODO: untested in combat situation
            // 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(followTarget)
                followTarget = false;
            // FIXME: can fool actors to stay behind doors, etc.
            // Related to Bug#1102 and to some degree #1155 as well
        }

        return false;
    }
コード例 #3
0
void VsSimulationWindow::SetCameraPositionAndLookAt(CStdFPoint oCameraPos, CStdFPoint oTarget)
{
	osg::Vec3d vCameraPos(oCameraPos.x, oCameraPos.y, oCameraPos.z);
	osg::Vec3d vTargetPos(oTarget.x, oTarget.y, oTarget.z);
	SetCameraPositionAndLookAt(vCameraPos, vTargetPos);
}
コード例 #4
0
ファイル: clientfxmgr.cpp プロジェクト: bibendovsky/ltjs
void CClientFXMgr::OnSpecialEffectNotify(HOBJECT hObject, ILTMessage_Read *pMsg)
{
	uint32		dwServerID = 0;
	char		sName[256];
	uint32		dwFxFlags;
	LTVector	vPos;
	LTRotation	rRot;
	uint8		nId;
	bool		bUseTargetData;
	HOBJECT		hTargetObj = LTNULL;
	LTVector	vTargetPos(0.0f, 0.0f, 0.0f);
	bool		bStartInst = true;

	// Read in the type of client fx
	nId = pMsg->Readuint8();

	switch( nId )
	{
		case SFX_CLIENTFXGROUP :
		{
			if( !hObject )
				return;

			// Retrieve the ID of the object
			
			pMsg->ReadString(sName, sizeof(sName));
			dwFxFlags = pMsg->Readuint32();

			bUseTargetData = !!(pMsg->Readuint8());
			if( bUseTargetData )
			{
				hTargetObj	= pMsg->ReadObject();
				vTargetPos	= pMsg->ReadCompPos();
			}

			m_pClientDE->GetObjectPos(hObject, &vPos);
			m_pClientDE->GetObjectRotation(hObject, &rRot);

			uint32 nUserFlags;
			m_pClientDE->Common()->GetObjectFlags(hObject, OFT_User, nUserFlags);

			if(hObject && !(nUserFlags & USRFLG_SFX_ON))
			{
				bStartInst = false;
			}

		}
		break;

		case SFX_CLIENTFXGROUPINSTANT :
		{
			// Retrieve the ID of the object

			pMsg->ReadString(sName, sizeof(sName));
			dwFxFlags = pMsg->Readuint32();
			vPos = pMsg->ReadCompPos();
			rRot = pMsg->ReadCompLTRotation();
			hObject = pMsg->ReadObject();

			bUseTargetData = !!(pMsg->Readuint8());
			if( bUseTargetData )
			{
				hTargetObj = pMsg->ReadObject();
				vTargetPos = pMsg->ReadCompPos();
			}
		}
		break;

		default:
			return;
	}

	// If we got here we don't yet have this special FX so we have to start it running

	CLIENTFX_CREATESTRUCT fxcs(sName, dwFxFlags, vPos, rRot);
	fxcs.m_hParent			= hObject;
	fxcs.m_bUseTargetData	= bUseTargetData;
	fxcs.m_hTarget			= hTargetObj;
	fxcs.m_vTargetPos		= vTargetPos;

	CLIENTFX_INSTANCE *pNewInst = CreateClientFX(fxcs, bStartInst);
	if (!pNewInst) 
		return;
}
コード例 #5
0
ファイル: aicombat.cpp プロジェクト: ChairGraveyard/TES3MP
    bool AiCombat::reactionTimeActions(const MWWorld::Ptr& actor, CharacterController& characterController, 
        AiCombatStorage& storage, MWWorld::Ptr target)
    {
        MWMechanics::Movement& movement = storage.mMovement;

        if (isTargetMagicallyHidden(target))
        {
            storage.stopAttack();
            return false; // TODO: run away instead of doing nothing
        }

        const MWWorld::CellStore*& currentCell = storage.mCell;
        bool cellChange = currentCell && (actor.getCell() != currentCell);
        if(!currentCell || cellChange)
        {
            currentCell = actor.getCell();
        }

        const MWWorld::Class& actorClass = actor.getClass();
        actorClass.getCreatureStats(actor).setMovementFlag(CreatureStats::Flag_Run, true);

        float& actionCooldown = storage.mActionCooldown;
        if (actionCooldown > 0)
            return false;

        float rangeAttack = 0;
        float rangeFollow = 0;
        boost::shared_ptr<Action>& currentAction = storage.mCurrentAction;
        if (characterController.readyToPrepareAttack())
        {
            currentAction = prepareNextAction(actor, target);
            actionCooldown = currentAction->getActionCooldown();
        }

        if (currentAction.get())
            currentAction->getCombatRange(rangeAttack, rangeFollow);

        // FIXME: consider moving this stuff to ActionWeapon::getCombatRange
        const ESM::Weapon *weapon = NULL;
        MWMechanics::WeaponType weaptype = WeapType_None;
        float weapRange = 1.0f;

        // Get weapon characteristics
        MWBase::World* world = MWBase::Environment::get().getWorld();
        if (actorClass.hasInventoryStore(actor))
        {
            //Get weapon range
            MWWorld::ContainerStoreIterator weaponSlot =
                MWMechanics::getActiveWeapon(actorClass.getCreatureStats(actor), actorClass.getInventoryStore(actor), &weaptype);

            if (weaptype == WeapType_HandToHand)
            {
                static float fHandToHandReach =
                    world->getStore().get<ESM::GameSetting>().find("fHandToHandReach")->getFloat();
                weapRange = fHandToHandReach;
            }
            else if (weaptype != WeapType_PickProbe && weaptype != WeapType_Spell && weaptype != WeapType_None)
            {
                // All other WeapTypes are actually weapons, so get<ESM::Weapon> is safe.
                weapon = weaponSlot->get<ESM::Weapon>()->mBase;
                weapRange = weapon->mData.mReach;
            }
            weapRange *= 100.0f;
        }
        else //is creature
        {
            weaptype = actorClass.getCreatureStats(actor).getDrawState() == DrawState_Spell ? WeapType_Spell : WeapType_HandToHand;
            weapRange = 150.0f; //TODO: use true attack range (the same problem in Creature::hit)
        }

        bool distantCombat = false;
        if (weaptype != WeapType_Spell)
        {
            // TODO: move to ActionWeapon
            if (weaptype == WeapType_BowAndArrow || weaptype == WeapType_Crossbow || weaptype == WeapType_Thrown)
            {
                rangeAttack = 1000;
                rangeFollow = 0; // not needed in ranged combat
                distantCombat = true;
            }
            else
            {
                rangeAttack = weapRange;
                rangeFollow = 300;
            }
        }
        else
        {
            distantCombat = (rangeAttack > 500);
        }

        
        bool& readyToAttack = storage.mReadyToAttack;
        // start new attack
        storage.startAttackIfReady(actor, characterController, weapon, distantCombat);

        /*
         * Some notes on meanings of variables:
         *
         * rangeAttack:
         *
         *  - Distance where attack using the actor's weapon is possible:
         *    longer for ranged weapons (obviously?) vs. melee weapons
         *  - Determined by weapon's reach parameter; hardcoded value
         *    for ranged weapon and for creatures
         *  - Once within this distance mFollowTarget is triggered
         *
         * rangeFollow:
         *
         *  - Applies to melee weapons or hand to hand only (or creatures without
         *    weapons)
         *  - Distance a little further away than the actor's weapon reach
         *    i.e. rangeFollow > rangeAttack for melee weapons
         *  - Hardcoded value (0 for ranged weapons)
         *  - Once the target gets beyond this distance mFollowTarget is cleared
         *    and a path to the target needs to be found
         *
         * 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)
         */

        ESM::Position pos = actor.getRefData().getPosition();
        osg::Vec3f vActorPos(pos.asVec3());
        osg::Vec3f vTargetPos(target.getRefData().getPosition().asVec3());

        osg::Vec3f vAimDir = MWBase::Environment::get().getWorld()->aimToTarget(actor, target);
        float distToTarget = MWBase::Environment::get().getWorld()->getHitDistance(actor, target);
        
        osg::Vec3f& lastActorPos = storage.mLastActorPos;
        bool& followTarget = storage.mFollowTarget;

        bool isStuck = false;
        float speed = 0.0f;
        if(movement.mPosition[1] && (lastActorPos - vActorPos).length() < (speed = actorClass.getSpeed(actor)) * REACTION_INTERVAL / 2)
            isStuck = true;

        lastActorPos = vActorPos;

        // check if actor can move along z-axis
        bool canMoveByZ = (actorClass.canSwim(actor) && world->isSwimming(actor))
            || world->isFlying(actor);

        // can't fight if attacker can't go where target is.  E.g. A fish can't attack person on land.
        if (distToTarget >= rangeAttack
                && !actorClass.isNpc() && !MWMechanics::isEnvironmentCompatible(actor, target))
        {
            // TODO: start fleeing?
            storage.stopAttack();
            return false;
        }

        // for distant combat we should know if target is in LOS even if distToTarget < rangeAttack 
        bool inLOS = distantCombat ? world->getLOS(actor, target) : true;

        // (within attack dist) || (not quite attack dist while following)
        if(inLOS && (distToTarget < rangeAttack || (distToTarget <= rangeFollow && followTarget && !isStuck)))
        {
            mPathFinder.clearPath();
            //Melee and Close-up combat
            
            // getXAngleToDir determines vertical angle to target:
            // if actor can move along z-axis it will control movement dir
            // if can't - it will control correct aiming.
            // note: in getZAngleToDir if we preserve dir.z then horizontal angle can be inaccurate
            if (distantCombat)
            {
                osg::Vec3f& lastTargetPos = storage.mLastTargetPos;
                vAimDir = AimDirToMovingTarget(actor, target, lastTargetPos, REACTION_INTERVAL, weaptype,
                    storage.mStrength);
                lastTargetPos = vTargetPos;
                movement.mRotation[0] = getXAngleToDir(vAimDir);
                movement.mRotation[2] = getZAngleToDir(vAimDir);
            }
            else
            {
                movement.mRotation[0] = getXAngleToDir(vAimDir);
                movement.mRotation[2] = getZAngleToDir((vTargetPos-vActorPos)); // using vAimDir results in spastic movements since the head is animated
            }

            // (not quite attack dist while following)
            if (followTarget && distToTarget > rangeAttack)
            {
                //Close-up combat: just run up on target
                storage.stopCombatMove();
                movement.mPosition[1] = 1;
            }
            else // (within attack dist)
            {
                storage.startCombatMove(actorClass.isNpc(), distantCombat, distToTarget, rangeAttack);

                readyToAttack = true;
                //only once got in melee combat, actor is allowed to use close-up shortcutting
                followTarget = true;
            }
        }
        else // remote pathfinding
        {
            bool preferShortcut = false;
            if (!distantCombat) inLOS = world->getLOS(actor, target);

            // check if shortcut is available
            bool& forceNoShortcut = storage.mForceNoShortcut;
            ESM::Position& shortcutFailPos = storage.mShortcutFailPos;
            
            if(inLOS && (!isStuck || readyToAttack)
                && (!forceNoShortcut || (shortcutFailPos.asVec3() - vActorPos).length() >= PATHFIND_SHORTCUT_RETRY_DIST))
            {
                if(speed == 0.0f) speed = actorClass.getSpeed(actor);
                // maximum dist before pit/obstacle for actor to avoid them depending on his speed
                float maxAvoidDist = REACTION_INTERVAL * speed + speed / MAX_VEL_ANGULAR_RADIANS * 2; // *2 - for reliability
                preferShortcut = checkWayIsClear(vActorPos, vTargetPos, osg::Vec3f(vAimDir.x(), vAimDir.y(), 0).length() > maxAvoidDist*1.5? maxAvoidDist : maxAvoidDist/2);
            }

            // don't use pathgrid when actor can move in 3 dimensions
            if (canMoveByZ)
            {
                preferShortcut = true;
                movement.mRotation[0] = getXAngleToDir(vAimDir);
            }

            if(preferShortcut)
            {
                movement.mRotation[2] = getZAngleToDir((vTargetPos-vActorPos));
                forceNoShortcut = false;
                shortcutFailPos.pos[0] = shortcutFailPos.pos[1] = shortcutFailPos.pos[2] = 0;
                mPathFinder.clearPath();
            }
            else // if shortcut failed stick to path grid
            {
                if(!isStuck && shortcutFailPos.pos[0] == 0.0f && shortcutFailPos.pos[1] == 0.0f && shortcutFailPos.pos[2] == 0.0f)
                {
                    forceNoShortcut = true;
                    shortcutFailPos = pos;
                }

                followTarget = false;

                buildNewPath(actor, target);

                // should always return a path (even if it's just go straight on target.)
                assert(mPathFinder.isPathConstructed());
            }

            if (readyToAttack)
            {
                // to stop possible sideway moving after target moved out of attack range
                storage.stopCombatMove();
                readyToAttack = false;
            }
            movement.mPosition[1] = 1;
        }

        return false;
    }
コード例 #6
0
ファイル: aicombat.cpp プロジェクト: Bene81/openmw
    void AiCombat::attack(const MWWorld::Ptr& actor, const MWWorld::Ptr& target, AiCombatStorage& storage, CharacterController& characterController)
    {
        if (isTargetMagicallyHidden(target))
        {
            storage.stopAttack();
            return; // TODO: run away instead of doing nothing
        }

        const MWWorld::CellStore*& currentCell = storage.mCell;
        bool cellChange = currentCell && (actor.getCell() != currentCell);
        if(!currentCell || cellChange)
        {
            currentCell = actor.getCell();
        }

        const MWWorld::Class& actorClass = actor.getClass();
        actorClass.getCreatureStats(actor).setMovementFlag(CreatureStats::Flag_Run, true);

        float& actionCooldown = storage.mActionCooldown;
        if (actionCooldown > 0)
            return;

        float &rangeAttack = storage.mAttackRange;
        boost::shared_ptr<Action>& currentAction = storage.mCurrentAction;
        if (characterController.readyToPrepareAttack())
        {
            currentAction = prepareNextAction(actor, target);
            actionCooldown = currentAction->getActionCooldown();
        }

        const ESM::Weapon *weapon = NULL;
        bool isRangedCombat = false;
        if (currentAction.get())
        {
            rangeAttack = currentAction->getCombatRange(isRangedCombat);
            // Get weapon characteristics
            weapon = currentAction->getWeapon();
        }

        ESM::Position pos = actor.getRefData().getPosition();
        osg::Vec3f vActorPos(pos.asVec3());
        osg::Vec3f vTargetPos(target.getRefData().getPosition().asVec3());

        osg::Vec3f vAimDir = MWBase::Environment::get().getWorld()->aimToTarget(actor, target);
        float distToTarget = MWBase::Environment::get().getWorld()->getHitDistance(actor, target);

        storage.mReadyToAttack = (distToTarget <= rangeAttack);
        
        // can't fight if attacker can't go where target is.  E.g. A fish can't attack person on land.
        if (distToTarget > rangeAttack
                && !actorClass.isNpc() && !MWMechanics::isEnvironmentCompatible(actor, target))
        {
            // TODO: start fleeing?
            storage.stopAttack();
            return;
        }

        if (storage.mReadyToAttack)
        {
            storage.startCombatMove(actorClass.isNpc(), isRangedCombat, distToTarget, rangeAttack);
            // start new attack
            storage.startAttackIfReady(actor, characterController, weapon, isRangedCombat);

            if (isRangedCombat)
            {
                // rotate actor taking into account target movement direction and projectile speed
                osg::Vec3f& lastTargetPos = storage.mLastTargetPos;
                vAimDir = AimDirToMovingTarget(actor, target, lastTargetPos, AI_REACTION_TIME, (weapon ? weapon->mData.mType : 0), storage.mStrength);
                lastTargetPos = vTargetPos;

                storage.mMovement.mRotation[0] = getXAngleToDir(vAimDir);
                storage.mMovement.mRotation[2] = getZAngleToDir(vAimDir);
            }
            else
            {
                storage.mMovement.mRotation[0] = getXAngleToDir(vAimDir);
                storage.mMovement.mRotation[2] = getZAngleToDir((vTargetPos-vActorPos)); // using vAimDir results in spastic movements since the head is animated
            }
        }
    }