npc.cpp 51.6 KB
Newer Older
1 2 3

#include "npc.hpp"

4 5
#include <memory>

scrawl's avatar
scrawl committed
6 7
#include <boost/algorithm/string.hpp>

8 9
#include <OgreSceneNode.h>

Emanuel Guevel's avatar
Emanuel Guevel committed
10
#include <components/esm/loadmgef.hpp>
11 12
#include <components/esm/loadnpc.hpp>

13 14
#include "../mwbase/environment.hpp"
#include "../mwbase/world.hpp"
15
#include "../mwbase/mechanicsmanager.hpp"
16
#include "../mwbase/windowmanager.hpp"
17
#include "../mwbase/dialoguemanager.hpp"
18
#include "../mwbase/soundmanager.hpp"
19

Marc Zinnschlag's avatar
Marc Zinnschlag committed
20
#include "../mwmechanics/creaturestats.hpp"
Marc Zinnschlag's avatar
Marc Zinnschlag committed
21
#include "../mwmechanics/npcstats.hpp"
22
#include "../mwmechanics/movement.hpp"
23
#include "../mwmechanics/spellcasting.hpp"
24
#include "../mwmechanics/disease.hpp"
Marc Zinnschlag's avatar
Marc Zinnschlag committed
25

26
#include "../mwworld/ptr.hpp"
27
#include "../mwworld/actiontalk.hpp"
scrawl's avatar
scrawl committed
28
#include "../mwworld/actionopen.hpp"
29
#include "../mwworld/failedaction.hpp"
30
#include "../mwworld/inventorystore.hpp"
Marc Zinnschlag's avatar
Marc Zinnschlag committed
31
#include "../mwworld/customdata.hpp"
32
#include "../mwworld/physicssystem.hpp"
33

34
#include "../mwrender/actors.hpp"
35
#include "../mwrender/renderinginterface.hpp"
36

37
#include "../mwgui/tooltips.hpp"
38

Marc Zinnschlag's avatar
Marc Zinnschlag committed
39
namespace
40 41 42
{
    const Ogre::Radian kOgrePi (Ogre::Math::PI);
    const Ogre::Radian kOgrePiOverTwo (Ogre::Math::PI / Ogre::Real(2.0));
43 44 45 46

    struct CustomData : public MWWorld::CustomData
    {
        MWMechanics::NpcStats mNpcStats;
47
        MWMechanics::Movement mMovement;
48
        MWWorld::InventoryStore mInventoryStore;
49 50 51 52 53 54 55 56

        virtual MWWorld::CustomData *clone() const;
    };

    MWWorld::CustomData *CustomData::clone() const
    {
        return new CustomData (*this);
    }
57 58 59 60 61 62 63 64 65 66 67 68 69

    void autoCalculateAttributes (const ESM::NPC* npc, MWMechanics::CreatureStats& creatureStats)
    {
        // race bonus
        const ESM::Race *race =
            MWBase::Environment::get().getWorld()->getStore().get<ESM::Race>().find(npc->mRace);

        bool male = (npc->mFlags & ESM::NPC::Female) == 0;

        int level = creatureStats.getLevel();
        for (int i=0; i<ESM::Attribute::Length; ++i)
        {
            const ESM::Race::MaleFemale& attribute = race->mData.mAttributeValues[i];
70
            creatureStats.setAttribute(i, male ? attribute.mMale : attribute.mFemale);
71 72 73 74 75 76 77 78 79 80 81
        }

        // class bonus
        const ESM::Class *class_ =
            MWBase::Environment::get().getWorld()->getStore().get<ESM::Class>().find(npc->mClass);

        for (int i=0; i<2; ++i)
        {
            int attribute = class_->mData.mAttribute[i];
            if (attribute>=0 && attribute<8)
            {
82
                creatureStats.setAttribute(attribute,
83 84 85 86 87
                    creatureStats.getAttribute(attribute).getBase() + 10);
            }
        }

        // skill bonus
88
        for (int attribute=0; attribute < ESM::Attribute::Length; ++attribute)
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
        {
            float modifierSum = 0;

            for (int j=0; j<ESM::Skill::Length; ++j)
            {
                const ESM::Skill* skill = MWBase::Environment::get().getWorld()->getStore().get<ESM::Skill>().find(j);

                if (skill->mData.mAttribute != attribute)
                    continue;

                // is this a minor or major skill?
                float add=0.2;
                for (int k=0; k<5; ++k)
                {
                    if (class_->mData.mSkills[k][0] == j)
                        add=0.5;
                }
                for (int k=0; k<5; ++k)
                {
                    if (class_->mData.mSkills[k][1] == j)
                        add=1.0;
                }
                modifierSum += add;
            }
113
            creatureStats.setAttribute(attribute, std::min(creatureStats.getAttribute(attribute).getBase()
114 115
                + static_cast<int>((level-1) * modifierSum+0.5), 100) );
        }
116

117
        // initial health
118 119
        int strength = creatureStats.getAttribute(ESM::Attribute::Strength).getBase();
        int endurance = creatureStats.getAttribute(ESM::Attribute::Endurance).getBase();
120 121 122 123 124 125 126 127 128 129 130 131 132

        int multiplier = 3;

        if (class_->mData.mSpecialization == ESM::Class::Combat)
            multiplier += 2;
        else if (class_->mData.mSpecialization == ESM::Class::Stealth)
            multiplier += 1;

        if (class_->mData.mAttribute[0] == ESM::Attribute::Endurance
            || class_->mData.mAttribute[1] == ESM::Attribute::Endurance)
            multiplier += 1;

        creatureStats.setHealth(static_cast<int> (0.5 * (strength + endurance)) + multiplier * (creatureStats.getLevel() - 1));
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

    /**
     * @brief autoCalculateSkills
     *
     * Skills are calculated with following formulae ( http://www.uesp.net/wiki/Morrowind:NPCs#Skills ):
     *
     * Skills: (Level - 1) × (Majority Multiplier + Specialization Multiplier)
     *
     *         The Majority Multiplier is 1.0 for a Major or Minor Skill, or 0.1 for a Miscellaneous Skill.
     *
     *         The Specialization Multiplier is 0.5 for a Skill in the same Specialization as the class,
     *         zero for other Skills.
     *
     * and by adding class, race, specialization bonus.
     */
    void autoCalculateSkills(const ESM::NPC* npc, MWMechanics::NpcStats& npcStats)
    {
        const ESM::Class *class_ =
            MWBase::Environment::get().getWorld()->getStore().get<ESM::Class>().find(npc->mClass);

        unsigned int level = npcStats.getLevel();

        const ESM::Race *race = MWBase::Environment::get().getWorld()->getStore().get<ESM::Race>().find(npc->mRace);


        for (int i = 0; i < 2; ++i)
        {
            int bonus = (i==0) ? 10 : 25;

            for (int i2 = 0; i2 < 5; ++i2)
            {
                int index = class_->mData.mSkills[i2][i];
                if (index >= 0 && index < ESM::Skill::Length)
                {
                    npcStats.getSkill(index).setBase (npcStats.getSkill(index).getBase() + bonus);
                }
            }
        }

        for (int skillIndex = 0; skillIndex < ESM::Skill::Length; ++skillIndex)
        {
            float majorMultiplier = 0.1f;
            float specMultiplier = 0.0f;

            int raceBonus = 0;
            int specBonus = 0;

            for (int raceSkillIndex = 0; raceSkillIndex < 7; ++raceSkillIndex)
            {
183 184 185 186 187
                if (race->mData.mBonus[raceSkillIndex].mSkill == skillIndex)
                {
                    raceBonus = race->mData.mBonus[raceSkillIndex].mBonus;
                    break;
                }
188 189 190 191
            }

            for (int k = 0; k < 5; ++k)
            {
192 193 194 195 196 197
                // is this a minor or major skill?
                if ((class_->mData.mSkills[k][0] == skillIndex) || (class_->mData.mSkills[k][1] == skillIndex))
                {
                    majorMultiplier = 1.0f;
                    break;
                }
198 199 200 201 202 203
            }

            // is this skill in the same Specialization as the class?
            const ESM::Skill* skill = MWBase::Environment::get().getWorld()->getStore().get<ESM::Skill>().find(skillIndex);
            if (skill->mData.mSpecialization == class_->mData.mSpecialization)
            {
204 205
                specMultiplier = 0.5f;
                specBonus = 5;
206 207 208 209 210 211 212 213
            }

            npcStats.getSkill(skillIndex).setBase(
                  std::min(
                    npcStats.getSkill(skillIndex).getBase()
                    + 5
                    + raceBonus
                    + specBonus
214
                    + static_cast<int>((level-1) * (majorMultiplier + specMultiplier)), 100));
215 216
        }
    }
217 218
}

219
namespace MWClass
220
{
221 222
    void Npc::ensureCustomData (const MWWorld::Ptr& ptr) const
    {
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
        static bool inited = false;
        if(!inited)
        {
            const MWBase::World *world = MWBase::Environment::get().getWorld();
            const MWWorld::Store<ESM::GameSetting> &gmst = world->getStore().get<ESM::GameSetting>();

            fMinWalkSpeed = gmst.find("fMinWalkSpeed");
            fMaxWalkSpeed = gmst.find("fMaxWalkSpeed");
            fEncumberedMoveEffect = gmst.find("fEncumberedMoveEffect");
            fSneakSpeedMultiplier = gmst.find("fSneakSpeedMultiplier");
            fAthleticsRunBonus = gmst.find("fAthleticsRunBonus");
            fBaseRunMultiplier = gmst.find("fBaseRunMultiplier");
            fMinFlySpeed = gmst.find("fMinFlySpeed");
            fMaxFlySpeed = gmst.find("fMaxFlySpeed");
            fSwimRunBase = gmst.find("fSwimRunBase");
            fSwimRunAthleticsMult = gmst.find("fSwimRunAthleticsMult");
239 240 241 242 243
            fJumpEncumbranceBase = gmst.find("fJumpEncumbranceBase");
            fJumpEncumbranceMultiplier = gmst.find("fJumpEncumbranceMultiplier");
            fJumpAcrobaticsBase = gmst.find("fJumpAcrobaticsBase");
            fJumpAcroMultiplier = gmst.find("fJumpAcroMultiplier");
            fJumpRunMultiplier = gmst.find("fJumpRunMultiplier");
244
            fWereWolfRunMult = gmst.find("fWereWolfRunMult");
245 246 247

            inited = true;
        }
248 249
        if (!ptr.getRefData().getCustomData())
        {
250
            std::auto_ptr<CustomData> data(new CustomData);
251

252
            MWWorld::LiveCellRef<ESM::NPC> *ref = ptr.get<ESM::NPC>();
253

254
            // NPC stats
greye's avatar
greye committed
255
            if (!ref->mBase->mFaction.empty())
256
            {
greye's avatar
greye committed
257
                std::string faction = ref->mBase->mFaction;
eduard's avatar
eduard committed
258
                Misc::StringUtils::toLower(faction);
259
                if(ref->mBase->mNpdtType != ESM::NPC::NPC_WITH_AUTOCALCULATED_STATS)
260
                {
greye's avatar
greye committed
261
                    data->mNpcStats.getFactionRanks()[faction] = (int)ref->mBase->mNpdt52.mRank;
262 263 264
                }
                else
                {
greye's avatar
greye committed
265
                    data->mNpcStats.getFactionRanks()[faction] = (int)ref->mBase->mNpdt12.mRank;
266
                }
267 268
            }

269
            // creature stats
270
            int gold=0;
271
            if(ref->mBase->mNpdtType != ESM::NPC::NPC_WITH_AUTOCALCULATED_STATS)
272
            {
273 274
                gold = ref->mBase->mNpdt52.mGold;

275
                for (unsigned int i=0; i< ESM::Skill::Length; ++i)
greye's avatar
greye committed
276 277
                    data->mNpcStats.getSkill (i).setBase (ref->mBase->mNpdt52.mSkills[i]);

278 279 280 281 282 283 284 285 286
                data->mNpcStats.setAttribute(ESM::Attribute::Strength, ref->mBase->mNpdt52.mStrength);
                data->mNpcStats.setAttribute(ESM::Attribute::Intelligence, ref->mBase->mNpdt52.mIntelligence);
                data->mNpcStats.setAttribute(ESM::Attribute::Willpower, ref->mBase->mNpdt52.mWillpower);
                data->mNpcStats.setAttribute(ESM::Attribute::Agility, ref->mBase->mNpdt52.mAgility);
                data->mNpcStats.setAttribute(ESM::Attribute::Speed, ref->mBase->mNpdt52.mSpeed);
                data->mNpcStats.setAttribute(ESM::Attribute::Endurance, ref->mBase->mNpdt52.mEndurance);
                data->mNpcStats.setAttribute(ESM::Attribute::Personality, ref->mBase->mNpdt52.mPersonality);
                data->mNpcStats.setAttribute(ESM::Attribute::Luck, ref->mBase->mNpdt52.mLuck);

287 288 289 290 291
                data->mNpcStats.setHealth (ref->mBase->mNpdt52.mHealth);
                data->mNpcStats.setMagicka (ref->mBase->mNpdt52.mMana);
                data->mNpcStats.setFatigue (ref->mBase->mNpdt52.mFatigue);

                data->mNpcStats.setLevel(ref->mBase->mNpdt52.mLevel);
scrawl's avatar
scrawl committed
292
                data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt52.mDisposition);
293
                data->mNpcStats.setReputation(ref->mBase->mNpdt52.mReputation);
294 295 296
            }
            else
            {
297 298
                gold = ref->mBase->mNpdt12.mGold;

299
                for (int i=0; i<3; ++i)
300
                    data->mNpcStats.setDynamic (i, 10);
301

302
                data->mNpcStats.setLevel(ref->mBase->mNpdt12.mLevel);
303 304
                data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt12.mDisposition);
                data->mNpcStats.setReputation(ref->mBase->mNpdt12.mReputation);
305

306
                autoCalculateAttributes(ref->mBase, data->mNpcStats);
307
                autoCalculateSkills(ref->mBase, data->mNpcStats);
308
            }
309

310 311 312 313 314 315 316 317 318 319 320
            if (data->mNpcStats.getFactionRanks().size())
            {
                static const int iAutoRepFacMod = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>()
                        .find("iAutoRepFacMod")->getInt();
                static const int iAutoRepLevMod = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>()
                        .find("iAutoRepLevMod")->getInt();
                int rank = data->mNpcStats.getFactionRanks().begin()->second;

                data->mNpcStats.setReputation(iAutoRepFacMod * (rank+1) + iAutoRepLevMod * (data->mNpcStats.getLevel()-1));
            }

321
            data->mNpcStats.getAiSequence().fill(ref->mBase->mAiPackage);
322

323 324 325 326
            data->mNpcStats.setAiSetting (MWMechanics::CreatureStats::AI_Hello, ref->mBase->mAiData.mHello);
            data->mNpcStats.setAiSetting (MWMechanics::CreatureStats::AI_Fight, ref->mBase->mAiData.mFight);
            data->mNpcStats.setAiSetting (MWMechanics::CreatureStats::AI_Flee, ref->mBase->mAiData.mFlee);
            data->mNpcStats.setAiSetting (MWMechanics::CreatureStats::AI_Alarm, ref->mBase->mAiData.mAlarm);
327

328
            // spells
greye's avatar
greye committed
329 330
            for (std::vector<std::string>::const_iterator iter (ref->mBase->mSpells.mList.begin());
                iter!=ref->mBase->mSpells.mList.end(); ++iter)
331
                data->mNpcStats.getSpells().add (*iter);
332

333
            // inventory
scrawl's avatar
scrawl committed
334
            data->mInventoryStore.fill(ref->mBase->mInventory, getId(ptr), "",
335 336
                                       MWBase::Environment::get().getWorld()->getStore());

337
            // store
338
            ptr.getRefData().setCustomData (data.release());
339

scrawl's avatar
scrawl committed
340 341
            // TODO: this is not quite correct, in vanilla the merchant's gold pool is not available in his inventory.
            // (except for gold you gave him)
342
            getContainerStore(ptr).add(MWWorld::ContainerStore::sGoldId, gold, ptr);
343

344
            getInventoryStore(ptr).autoEquip(ptr);
345 346 347
        }
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
348 349
    std::string Npc::getId (const MWWorld::Ptr& ptr) const
    {
350
        MWWorld::LiveCellRef<ESM::NPC> *ref =
Marc Zinnschlag's avatar
Marc Zinnschlag committed
351 352
            ptr.get<ESM::NPC>();

greye's avatar
greye committed
353
        return ref->mBase->mId;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
354 355
    }

356 357 358 359 360
    void Npc::adjustPosition(const MWWorld::Ptr& ptr) const
    {
        MWBase::Environment::get().getWorld()->adjustPosition(ptr);
    }

Jason Hooks's avatar
Jason Hooks committed
361
    void Npc::insertObjectRendering (const MWWorld::Ptr& ptr, MWRender::RenderingInterface& renderingInterface) const
362
    {
363
        renderingInterface.getActors().insertNPC(ptr);
Jason Hooks's avatar
Jason Hooks committed
364
    }
Jason Hooks's avatar
Jason Hooks committed
365

366
    void Npc::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const
Jason Hooks's avatar
Jason Hooks committed
367
    {
368
        physics.addActor(ptr);
369
        MWBase::Environment::get().getMechanicsManager()->add(ptr);
greye's avatar
greye committed
370
    }
Jason Hooks's avatar
Jason Hooks committed
371

scrawl's avatar
scrawl committed
372 373 374 375 376 377
    bool Npc::isPersistent(const MWWorld::Ptr &actor) const
    {
        MWWorld::LiveCellRef<ESM::NPC>* ref = actor.get<ESM::NPC>();
        return ref->mBase->mPersistent;
    }

greye's avatar
greye committed
378 379
    std::string Npc::getModel(const MWWorld::Ptr &ptr) const
    {
380
        MWWorld::LiveCellRef<ESM::NPC> *ref =
Jason Hooks's avatar
Jason Hooks committed
381
            ptr.get<ESM::NPC>();
greye's avatar
greye committed
382
        assert(ref->mBase != NULL);
383

scrawl's avatar
scrawl committed
384
        //std::string headID = ref->mBase->mHead;
385

scrawl's avatar
scrawl committed
386 387
        //int end = headID.find_last_of("head_") - 4;
        //std::string bodyRaceID = headID.substr(0, end);
greye's avatar
greye committed
388 389

        std::string model = "meshes\\base_anim.nif";
390 391
        const ESM::Race* race = MWBase::Environment::get().getWorld()->getStore().get<ESM::Race>().find(ref->mBase->mRace);
        if(race->mData.mFlags & ESM::Race::Beast)
greye's avatar
greye committed
392
            model = "meshes\\base_animkna.nif";
393

greye's avatar
greye committed
394
        return model;
395 396 397

    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
398 399
    std::string Npc::getName (const MWWorld::Ptr& ptr) const
    {
400 401 402 403 404 405 406
        if(getNpcStats(ptr).isWerewolf())
        {
            const MWBase::World *world = MWBase::Environment::get().getWorld();
            const MWWorld::Store<ESM::GameSetting> &gmst = world->getStore().get<ESM::GameSetting>();

            return gmst.find("sWerewolfPopup")->getString();
        }
Marc Zinnschlag's avatar
Marc Zinnschlag committed
407

408
        MWWorld::LiveCellRef<ESM::NPC> *ref = ptr.get<ESM::NPC>();
greye's avatar
greye committed
409
        return ref->mBase->mName;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
410 411
    }

412
    MWMechanics::CreatureStats& Npc::getCreatureStats (const MWWorld::Ptr& ptr) const
413
    {
414
        ensureCustomData (ptr);
415

416
        return dynamic_cast<CustomData&> (*ptr.getRefData().getCustomData()).mNpcStats;
417 418
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
419 420
    MWMechanics::NpcStats& Npc::getNpcStats (const MWWorld::Ptr& ptr) const
    {
421
        ensureCustomData (ptr);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
422

423
        return dynamic_cast<CustomData&> (*ptr.getRefData().getCustomData()).mNpcStats;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
424 425
    }

Chris Robinson's avatar
Chris Robinson committed
426

427
    void Npc::hit(const MWWorld::Ptr& ptr, int type) const
Chris Robinson's avatar
Chris Robinson committed
428
    {
429 430 431
        MWBase::World *world = MWBase::Environment::get().getWorld();
        const MWWorld::Store<ESM::GameSetting> &gmst = world->getStore().get<ESM::GameSetting>();

432 433
        // Get the weapon used (if hand-to-hand, weapon = inv.end())
        MWWorld::InventoryStore &inv = getInventoryStore(ptr);
434 435 436 437
        MWWorld::ContainerStoreIterator weaponslot = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight);
        MWWorld::Ptr weapon = ((weaponslot != inv.end()) ? *weaponslot : MWWorld::Ptr());
        if(!weapon.isEmpty() && weapon.getTypeName() != typeid(ESM::Weapon).name())
            weapon = MWWorld::Ptr();
438

439 440 441 442 443 444 445 446 447 448 449 450 451 452
        // Reduce fatigue
        // somewhat of a guess, but using the weapon weight makes sense
        const float fFatigueAttackBase = gmst.find("fFatigueAttackBase")->getFloat();
        const float fFatigueAttackMult = gmst.find("fFatigueAttackMult")->getFloat();
        const float fWeaponFatigueMult = gmst.find("fWeaponFatigueMult")->getFloat();
        MWMechanics::DynamicStat<float> fatigue = getCreatureStats(ptr).getFatigue();
        const float normalizedEncumbrance = getEncumbrance(ptr) / getCapacity(ptr);
        float fatigueLoss = fFatigueAttackBase + normalizedEncumbrance * fFatigueAttackMult;
        if (!weapon.isEmpty())
            fatigueLoss += weapon.getClass().getWeight(weapon) * getNpcStats(ptr).getAttackStrength() * fWeaponFatigueMult;
        fatigue.setCurrent(fatigue.getCurrent() - fatigueLoss);
        getCreatureStats(ptr).setFatigue(fatigue);


453 454
        float dist = 100.0f * (!weapon.isEmpty() ?
                               weapon.get<ESM::Weapon>()->mBase->mData.mReach :
455
                               gmst.find("fHandToHandReach")->getFloat());
456 457
        // TODO: Use second to work out the hit angle and where to spawn the blood effect
        MWWorld::Ptr victim = world->getHitContact(ptr, dist).first;
Chris Robinson's avatar
Chris Robinson committed
458 459 460 461
        if(victim.isEmpty()) // Didn't hit anything
            return;

        const MWWorld::Class &othercls = MWWorld::Class::get(victim);
462 463
        if(!othercls.isActor()) // Can't hit non-actors
            return;
464
        MWMechanics::CreatureStats &otherstats = victim.getClass().getCreatureStats(victim);
465
        if(otherstats.isDead()) // Can't hit dead actors
Chris Robinson's avatar
Chris Robinson committed
466 467
            return;

scrawl's avatar
scrawl committed
468
        if(ptr.getRefData().getHandle() == "player")
scrawl's avatar
scrawl committed
469
            MWBase::Environment::get().getWindowManager()->setEnemy(victim);
scrawl's avatar
scrawl committed
470

471 472 473 474
        // Attacking peaceful NPCs is a crime
        if (victim.getClass().isNpc() && victim.getClass().getCreatureStats(victim).getAiSetting(MWMechanics::CreatureStats::AI_Fight).getModified() <= 30)
            MWBase::Environment::get().getMechanicsManager()->commitCrime(ptr, victim, MWBase::MechanicsManager::OT_Assault);

475
        int weapskill = ESM::Skill::HandToHand;
476
        if(!weapon.isEmpty())
477
            weapskill = get(weapon).getEquipmentSkill(weapon);
478

479 480 481 482 483 484
        MWMechanics::NpcStats &stats = getNpcStats(ptr);
        const MWMechanics::MagicEffects &mageffects = stats.getMagicEffects();
        float hitchance = stats.getSkill(weapskill).getModified() +
                          (stats.getAttribute(ESM::Attribute::Agility).getModified() / 5.0f) +
                          (stats.getAttribute(ESM::Attribute::Luck).getModified() / 10.0f);
        hitchance *= stats.getFatigueTerm();
scrawl's avatar
scrawl committed
485 486
        hitchance += mageffects.get(ESM::MagicEffect::FortifyAttack).mMagnitude -
                     mageffects.get(ESM::MagicEffect::Blind).mMagnitude;
487
        hitchance -= otherstats.getEvasion();
488

Chris Robinson's avatar
Chris Robinson committed
489
        if((::rand()/(RAND_MAX+1.0)) > hitchance/100.0f)
490
        {
491
            othercls.onHit(victim, 0.0f, false, weapon, ptr, false);
492 493
            return;
        }
Chris Robinson's avatar
Chris Robinson committed
494

495
        bool healthdmg;
496 497
        float damage = 0.0f;
        if(!weapon.isEmpty())
Chris Robinson's avatar
Chris Robinson committed
498
        {
499
            const bool weaphashealth = get(weapon).hasItemHealth(weapon);
500
            const unsigned char *attack = NULL;
Chris Robinson's avatar
Chris Robinson committed
501
            if(type == MWMechanics::CreatureStats::AT_Chop)
502
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mChop;
Chris Robinson's avatar
Chris Robinson committed
503
            else if(type == MWMechanics::CreatureStats::AT_Slash)
504
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mSlash;
Chris Robinson's avatar
Chris Robinson committed
505
            else if(type == MWMechanics::CreatureStats::AT_Thrust)
506
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mThrust;
507
            if(attack)
508
            {
509 510
                damage  = attack[0] + ((attack[1]-attack[0])*stats.getAttackStrength());
                damage *= 0.5f + (stats.getAttribute(ESM::Attribute::Luck).getModified() / 100.0f);
511 512 513 514 515 516 517
                if(weaphashealth)
                {
                    int weapmaxhealth = weapon.get<ESM::Weapon>()->mBase->mData.mHealth;
                    if(weapon.getCellRef().mCharge == -1)
                        weapon.getCellRef().mCharge = weapmaxhealth;
                    damage *= float(weapon.getCellRef().mCharge) / weapmaxhealth;
                }
518 519 520 521
                if(!othercls.hasDetected(victim, ptr))
                {
                    damage *= gmst.find("fCombatCriticalStrikeMult")->getFloat();
                    MWBase::Environment::get().getWindowManager()->messageBox("#{sTargetCriticalStrike}");
522
                    MWBase::Environment::get().getSoundManager()->playSound3D(victim, "critical damage", 1.0f, 1.0f);
523
                }
524 525 526 527
                
                if (!MWBase::Environment::get().getWorld()->getGodModeState())
                    weapon.getCellRef().mCharge -= std::min(std::max(1,
                        (int)(damage * gmst.find("fWeaponDamageMult")->getFloat())), weapon.getCellRef().mCharge);
528 529 530 531 532

                // Weapon broken? unequip it
                if (weapon.getCellRef().mCharge == 0)
                    weapon = *inv.unequipItem(weapon, ptr);

533
            }
534 535 536 537 538 539 540 541 542
            healthdmg = true;
        }
        else
        {
            // Note: MCP contains an option to include Strength in hand-to-hand damage
            // calculations. Some mods recommend using it, so we may want to include am
            // option for it.
            float minstrike = gmst.find("fMinHandToHandMult")->getFloat();
            float maxstrike = gmst.find("fMaxHandToHandMult")->getFloat();
543 544
            damage  = stats.getSkill(weapskill).getModified();
            damage *= minstrike + ((maxstrike-minstrike)*stats.getAttackStrength());
545 546 547 548 549 550 551
            if(!othercls.hasDetected(victim, ptr))
            {
                damage *= gmst.find("fCombatCriticalStrikeMult")->getFloat();
                MWBase::Environment::get().getWindowManager()->messageBox("#{sTargetCriticalStrike}");
                MWBase::Environment::get().getSoundManager()->playSound3D(victim, "critical damage", 1.0f, 1.0f);
            }

scrawl's avatar
scrawl committed
552 553
            healthdmg = (otherstats.getFatigue().getCurrent() < 1.0f)
                    || (otherstats.getMagicEffects().get(ESM::MagicEffect::Paralyze).mMagnitude > 0);
554
            if(stats.isWerewolf())
555 556 557 558 559 560
            {
                healthdmg = true;
                // GLOB instead of GMST because it gets updated during a quest
                const MWWorld::Store<ESM::Global> &glob = world->getStore().get<ESM::Global>();
                damage *= glob.find("WerewolfClawMult")->mValue.getFloat();
            }
561
            if(healthdmg)
562
                damage *= gmst.find("fHandtoHandHealthPer")->getFloat();
563 564 565 566

            MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();
            if(stats.isWerewolf())
            {
567 568 569
                const ESM::Sound *sound = world->getStore().get<ESM::Sound>().searchRandom("WolfHit");
                if(sound)
                    sndMgr->playSound3D(victim, sound->mId, 1.0f, 1.0f);
570 571 572
            }
            else
                sndMgr->playSound3D(victim, "Hand To Hand Hit", 1.0f, 1.0f);
Chris Robinson's avatar
Chris Robinson committed
573
        }
574 575
        if(ptr.getRefData().getHandle() == "player")
            skillUsageSucceeded(ptr, weapskill, 0);
576

577
        // Apply "On hit" enchanted weapons
578
        std::string enchantmentName = !weapon.isEmpty() ? weapon.getClass().getEnchantment(weapon) : "";
579 580 581 582 583 584 585 586 587
        if (!enchantmentName.empty())
        {
            const ESM::Enchantment* enchantment = MWBase::Environment::get().getWorld()->getStore().get<ESM::Enchantment>().find(
                        enchantmentName);
            if (enchantment->mData.mType == ESM::Enchantment::WhenStrikes)
            {
                // Check if we have enough charges
                const float enchantCost = enchantment->mData.mCost;
                int eSkill = stats.getSkill(ESM::Skill::Enchant).getModified();
588
                const int castCost = std::max(1.f, enchantCost - (enchantCost / 100) * (eSkill - 10));
589 590 591 592 593 594 595 596 597 598 599

                if (weapon.getCellRef().mEnchantmentCharge == -1)
                    weapon.getCellRef().mEnchantmentCharge = enchantment->mData.mCharge;
                if (weapon.getCellRef().mEnchantmentCharge < castCost)
                {
                    if (ptr.getRefData().getHandle() == "player")
                        MWBase::Environment::get().getWindowManager()->messageBox("#{sMagicInsufficientCharge}");
                }
                else
                {
                    weapon.getCellRef().mEnchantmentCharge -= castCost;
600 601 602

                    MWMechanics::CastSpell cast(ptr, victim);
                    cast.cast(weapon);
603 604 605

                    if (ptr.getRefData().getHandle() == "player")
                        skillUsageSucceeded (ptr, ESM::Skill::Enchant, 3);
606 607 608 609
                }
            }
        }

610
        othercls.onHit(victim, damage, healthdmg, weapon, ptr, true);
Chris Robinson's avatar
Chris Robinson committed
611 612
    }

613
    void Npc::onHit(const MWWorld::Ptr &ptr, float damage, bool ishealth, const MWWorld::Ptr &object, const MWWorld::Ptr &attacker, bool successful) const
Chris Robinson's avatar
Chris Robinson committed
614
    {
615 616
        MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();

617 618 619 620 621 622 623
        // NOTE: 'object' and/or 'attacker' may be empty.

        if(!successful)
        {
            // TODO: Handle HitAttemptOnMe script function

            // Missed
624
            sndMgr->playSound3D(ptr, "miss", 1.0f, 1.0f);
625 626
            return;
        }
Chris Robinson's avatar
Chris Robinson committed
627

628
        if(!object.isEmpty())
629
            getCreatureStats(ptr).setLastHitObject(get(object).getId(object));
630 631 632 633 634 635 636 637

        if(!attacker.isEmpty() && attacker.getRefData().getHandle() == "player")
        {
            const std::string &script = ptr.get<ESM::NPC>()->mBase->mScript;
            /* Set the OnPCHitMe script variable. The script is responsible for clearing it. */
            if(!script.empty())
                ptr.getRefData().getLocals().setVarByInt(script, "onpchitme", 1);
        }
638

639 640 641
        if (!attacker.isEmpty())
            MWMechanics::diseaseContact(ptr, attacker);

642
        if(damage > 0.0f)
Chris Robinson's avatar
Chris Robinson committed
643 644 645
        {
            // 'ptr' is losing health. Play a 'hit' voiced dialog entry if not already saying
            // something, alert the character controller, scripts, etc.
646

scrawl's avatar
scrawl committed
647 648 649 650 651 652 653
            const MWWorld::ESMStore &store = MWBase::Environment::get().getWorld()->getStore();
            int chance = store.get<ESM::GameSetting>().find("iVoiceHitOdds")->getInt();
            int roll = std::rand()/ (static_cast<double> (RAND_MAX) + 1) * 100; // [0, 99]
            if (roll < chance)
            {
                MWBase::Environment::get().getDialogueManager()->say(ptr, "hit");
            }
mrcheko's avatar
mrcheko committed
654
            getCreatureStats(ptr).setAttacked(true);//used in CharacterController
655

656
            if(object.isEmpty())
657 658
            {
                if(ishealth)
659
                    damage /= std::min(1.0f + getArmorRating(ptr)/std::max(1.0f, damage), 4.0f);
660 661
            }
            else if(ishealth)
662
            {
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
                // Hit percentages:
                // cuirass = 30%
                // shield, helmet, greaves, boots, pauldrons = 10% each
                // guantlets = 5% each
                static const int hitslots[20] = {
                    MWWorld::InventoryStore::Slot_Cuirass, MWWorld::InventoryStore::Slot_Cuirass,
                    MWWorld::InventoryStore::Slot_Cuirass, MWWorld::InventoryStore::Slot_Cuirass,
                    MWWorld::InventoryStore::Slot_Cuirass, MWWorld::InventoryStore::Slot_Cuirass,
                    MWWorld::InventoryStore::Slot_CarriedLeft, MWWorld::InventoryStore::Slot_CarriedLeft,
                    MWWorld::InventoryStore::Slot_Helmet, MWWorld::InventoryStore::Slot_Helmet,
                    MWWorld::InventoryStore::Slot_Greaves, MWWorld::InventoryStore::Slot_Greaves,
                    MWWorld::InventoryStore::Slot_Boots, MWWorld::InventoryStore::Slot_Boots,
                    MWWorld::InventoryStore::Slot_LeftPauldron, MWWorld::InventoryStore::Slot_LeftPauldron,
                    MWWorld::InventoryStore::Slot_RightPauldron, MWWorld::InventoryStore::Slot_RightPauldron,
                    MWWorld::InventoryStore::Slot_LeftGauntlet, MWWorld::InventoryStore::Slot_RightGauntlet
                };
                int hitslot = hitslots[(int)(::rand()/(RAND_MAX+1.0)*20.0)];

681 682 683 684
                float damagediff = damage;
                damage /= std::min(1.0f + getArmorRating(ptr)/std::max(1.0f, damage), 4.0f);
                damagediff -= damage;

685 686 687 688
                MWWorld::InventoryStore &inv = getInventoryStore(ptr);
                MWWorld::ContainerStoreIterator armorslot = inv.getSlot(hitslot);
                MWWorld::Ptr armor = ((armorslot != inv.end()) ? *armorslot : MWWorld::Ptr());
                if(!armor.isEmpty() && armor.getTypeName() == typeid(ESM::Armor).name())
689
                {
690 691 692 693 694
                    ESM::CellRef &armorref = armor.getCellRef();
                    if(armorref.mCharge == -1)
                        armorref.mCharge = armor.get<ESM::Armor>()->mBase->mData.mHealth;
                    armorref.mCharge -= std::min(std::max(1, (int)damagediff),
                                                 armorref.mCharge);
695 696 697 698 699

                    // Armor broken? unequip it
                    if (armorref.mCharge == 0)
                        inv.unequipItem(armor, ptr);

700 701 702 703 704 705 706 707 708 709 710 711
                    switch(get(armor).getEquipmentSkill(armor))
                    {
                        case ESM::Skill::LightArmor:
                            sndMgr->playSound3D(ptr, "Light Armor Hit", 1.0f, 1.0f);
                            break;
                        case ESM::Skill::MediumArmor:
                            sndMgr->playSound3D(ptr, "Medium Armor Hit", 1.0f, 1.0f);
                            break;
                        case ESM::Skill::HeavyArmor:
                            sndMgr->playSound3D(ptr, "Heavy Armor Hit", 1.0f, 1.0f);
                            break;
                    }
712 713
                }
            }
Chris Robinson's avatar
Chris Robinson committed
714 715
        }

716 717 718 719 720 721 722 723 724 725
        if(ishealth)
        {
            if(damage > 0.0f)
                sndMgr->playSound3D(ptr, "Health Damage", 1.0f, 1.0f);
            float health = getCreatureStats(ptr).getHealth().getCurrent() - damage;
            setActorHealth(ptr, health, attacker);
        }
        else
        {
            MWMechanics::DynamicStat<float> fatigue(getCreatureStats(ptr).getFatigue());
726
            fatigue.setCurrent(fatigue.getCurrent() - damage, true);
727 728
            getCreatureStats(ptr).setFatigue(fatigue);
        }
729 730 731 732 733
    }

    void Npc::setActorHealth(const MWWorld::Ptr& ptr, float health, const MWWorld::Ptr& attacker) const
    {
        MWMechanics::CreatureStats &crstats = getCreatureStats(ptr);
Chris Robinson's avatar
Chris Robinson committed
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
        bool wasDead = crstats.isDead();

        MWMechanics::DynamicStat<float> stat(crstats.getHealth());
        stat.setCurrent(health);
        crstats.setHealth(stat);

        if(!wasDead && crstats.isDead())
        {
            // actor was just killed
        }
        else if(wasDead && !crstats.isDead())
        {
            // actor was just resurrected
        }
    }


751
    boost::shared_ptr<MWWorld::Action> Npc::activate (const MWWorld::Ptr& ptr,
752
        const MWWorld::Ptr& actor) const
753
    {
754 755
        if(get(actor).isNpc() && get(actor).getNpcStats(actor).isWerewolf())
        {
756 757 758
            const MWWorld::ESMStore &store = MWBase::Environment::get().getWorld()->getStore();
            const ESM::Sound *sound = store.get<ESM::Sound>().searchRandom("WolfNPC");

759
            boost::shared_ptr<MWWorld::Action> action(new MWWorld::FailedAction("#{sWerewolfRefusal}"));
760 761
            if(sound) action->setSound(sound->mId);

762 763 764 765 766 767
            return action;
        }
        if(getCreatureStats(ptr).isDead())
            return boost::shared_ptr<MWWorld::Action>(new MWWorld::ActionOpen(ptr, true));
        if(get(actor).getStance(actor, MWWorld::Class::Sneak))
            return boost::shared_ptr<MWWorld::Action>(new MWWorld::ActionOpen(ptr)); // stealing
768 769
        if(get(ptr).getCreatureStats(ptr).isHostile())
            return boost::shared_ptr<MWWorld::Action>(new MWWorld::FailedAction("#{sActorInCombat}"));
770
        return boost::shared_ptr<MWWorld::Action>(new MWWorld::ActionTalk(ptr));
771
    }
Marc Zinnschlag's avatar
Marc Zinnschlag committed
772

773
    MWWorld::ContainerStore& Npc::getContainerStore (const MWWorld::Ptr& ptr)
774
        const
Marc Zinnschlag's avatar
Marc Zinnschlag committed
775
    {
776
        ensureCustomData (ptr);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
777

778 779 780 781 782 783 784 785 786
        return dynamic_cast<CustomData&> (*ptr.getRefData().getCustomData()).mInventoryStore;
    }

    MWWorld::InventoryStore& Npc::getInventoryStore (const MWWorld::Ptr& ptr)
        const
    {
        ensureCustomData (ptr);

        return dynamic_cast<CustomData&> (*ptr.getRefData().getCustomData()).mInventoryStore;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
787 788
    }

789 790
    std::string Npc::getScript (const MWWorld::Ptr& ptr) const
    {
791
        MWWorld::LiveCellRef<ESM::NPC> *ref =
792 793
            ptr.get<ESM::NPC>();

greye's avatar
greye committed
794
        return ref->mBase->mScript;
795 796
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
797 798 799 800 801 802 803 804
    void Npc::setForceStance (const MWWorld::Ptr& ptr, Stance stance, bool force) const
    {
        MWMechanics::NpcStats& stats = getNpcStats (ptr);

        switch (stance)
        {
            case Run:

805
                stats.setMovementFlag (MWMechanics::NpcStats::Flag_ForceRun, force);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
806 807 808 809
                break;

            case Sneak:

810
                stats.setMovementFlag (MWMechanics::NpcStats::Flag_ForceSneak, force);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
                break;

            case Combat:

                throw std::runtime_error ("combat stance not enforcable for NPCs");
        }
    }

    void Npc::setStance (const MWWorld::Ptr& ptr, Stance stance, bool set) const
    {
        MWMechanics::NpcStats& stats = getNpcStats (ptr);

        switch (stance)
        {
            case Run:

827
                stats.setMovementFlag (MWMechanics::NpcStats::Flag_Run, set);
828
                break;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
829 830 831

            case Sneak:

832
                stats.setMovementFlag (MWMechanics::NpcStats::Flag_Sneak, set);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
833 834 835 836
                break;

            case Combat:

837 838
                // Combat stance ignored for now; need to be determined based on draw state instead of
                // being maunally set.
Marc Zinnschlag's avatar
Marc Zinnschlag committed
839 840 841 842 843 844 845 846 847 848 849 850
                break;
        }
    }

    bool Npc::getStance (const MWWorld::Ptr& ptr, Stance stance, bool ignoreForce) const
    {
        MWMechanics::NpcStats& stats = getNpcStats (ptr);

        switch (stance)
        {
            case Run:

851
                if (!ignoreForce && stats.getMovementFlag (MWMechanics::NpcStats::Flag_ForceRun))
852 853
                    return true;

854
                return stats.getMovementFlag (MWMechanics::NpcStats::Flag_Run);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
855 856 857

            case Sneak:

858
                if (!ignoreForce && stats.getMovementFlag (MWMechanics::NpcStats::Flag_ForceSneak))
Marc Zinnschlag's avatar
Marc Zinnschlag committed
859 860
                    return true;

861
                return stats.getMovementFlag (MWMechanics::NpcStats::Flag_Sneak);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
862 863 864

            case Combat:

865
                return false;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
866 867 868 869 870
        }

        return false;
    }

871
    float Npc::getSpeed(const MWWorld::Ptr& ptr) const
Marc Zinnschlag's avatar
Marc Zinnschlag committed
872
    {
873 874
        const MWBase::World *world = MWBase::Environment::get().getWorld();
        const CustomData *npcdata = static_cast<const CustomData*>(ptr.getRefData().getCustomData());
875
        const MWMechanics::MagicEffects &mageffects = npcdata->mNpcStats.getMagicEffects();
876

877 878