npc.cpp 57.7 KB
Newer Older
1 2 3

#include "npc.hpp"

4 5
#include <memory>

6 7
#include <OgreSceneNode.h>

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

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

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

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

36
#include "../mwrender/actors.hpp"
37
#include "../mwrender/renderinginterface.hpp"
38

39
#include "../mwgui/tooltips.hpp"
40

Marc Zinnschlag's avatar
Marc Zinnschlag committed
41
namespace
42
{
43
    struct NpcCustomData : public MWWorld::CustomData
44 45
    {
        MWMechanics::NpcStats mNpcStats;
46
        MWMechanics::Movement mMovement;
47
        MWWorld::InventoryStore mInventoryStore;
48 49 50 51

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

52
    MWWorld::CustomData *NpcCustomData::clone() const
53
    {
54
        return new NpcCustomData (*this);
55
    }
56 57 58 59 60 61 62 63 64 65 66 67 68

    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];
69
            creatureStats.setAttribute(i, male ? attribute.mMale : attribute.mFemale);
70 71 72 73 74 75 76 77 78 79 80
        }

        // 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)
            {
81
                creatureStats.setAttribute(attribute,
82 83 84 85 86
                    creatureStats.getAttribute(attribute).getBase() + 10);
            }
        }

        // skill bonus
87
        for (int attribute=0; attribute < ESM::Attribute::Length; ++attribute)
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
        {
            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;
            }
112
            creatureStats.setAttribute(attribute, std::min(creatureStats.getAttribute(attribute).getBase()
113 114
                + static_cast<int>((level-1) * modifierSum+0.5), 100) );
        }
115

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

        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));
132
    }
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147

    /**
     * @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.
     */
148
    void autoCalculateSkills(const ESM::NPC* npc, MWMechanics::NpcStats& npcStats, const MWWorld::Ptr& ptr)
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
    {
        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)
            {
182 183 184 185 186
                if (race->mData.mBonus[raceSkillIndex].mSkill == skillIndex)
                {
                    raceBonus = race->mData.mBonus[raceSkillIndex].mBonus;
                    break;
                }
187 188 189 190
            }

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

            // 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)
            {
203 204
                specMultiplier = 0.5f;
                specBonus = 5;
205 206 207 208 209 210 211 212
            }

            npcStats.getSkill(skillIndex).setBase(
                  std::min(
                    npcStats.getSkill(skillIndex).getBase()
                    + 5
                    + raceBonus
                    + specBonus
213
                    + static_cast<int>((level-1) * (majorMultiplier + specMultiplier)), 100));
214
        }
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250

        int skills[ESM::Skill::Length];
        for (int i=0; i<ESM::Skill::Length; ++i)
            skills[i] = npcStats.getSkill(i).getBase();

        int attributes[ESM::Attribute::Length];
        for (int i=0; i<ESM::Attribute::Length; ++i)
            attributes[i] = npcStats.getAttribute(i).getBase();

        std::cout << npc->mId << std::endl;
        std::cout << "Skills: " << std::endl;
        for (int i=0; i<ESM::Skill::Length; ++i)
            std::cout << skills[i] << std::endl;
        std::cout << "Attributes: " << std::endl;
        for (int i=0; i<ESM::Attribute::Length; ++i)
            std::cout << attributes[i] << std::endl;
        std::set<std::string> spells = MWMechanics::autoCalcNpcSpells(skills, attributes, race);
        std::cout << "Spells: " << spells.size() << std::endl;
        for (std::set<std::string>::iterator it = spells.begin(); it != spells.end(); ++it)
        {
            std::cout << *it << ", ";
            npcStats.getSpells().add(*it);
        }
        std::cout << std::endl;

        const char* compare[] = { "weary","dire noise","reflect","weak spelldrinker","absorb endurance","absorb personality","absorb speed","absorb strength","absorb willpower","fortify alteration skill","fortify illusion skill","fortify unarmored skill","fortify mysticism skill","fortify restoration skill","assured sublime wisdom","surpassing sublime wisdom","surpassing golden wisdom","blood gift","surpassing silver wisdom","surpassing unseen wisdom","surpassing green wisdom","powerwell","orc's strength","surpassing fluid evasion","poet's whim","rapid regenerate","dispel","shadow weave" };
        int n = sizeof(compare) / sizeof(compare[0]);
        std::set<std::string> compareSet;
        for (int i=0; i<n; ++i)
            compareSet.insert(compare[i]);
        std::cout << "Compare: " << n << std::endl;
        for (std::set<std::string>::iterator it = compareSet.begin(); it != compareSet.end(); ++it)
        {
            std::cout << *it << ", ";
        }
        std::cout << std::endl;
251
    }
252 253
}

254
namespace MWClass
255
{
256
    const Npc::GMST& Npc::getGmst()
257
    {
258
        static GMST gmst;
259 260 261 262
        static bool inited = false;
        if(!inited)
        {
            const MWBase::World *world = MWBase::Environment::get().getWorld();
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
            const MWWorld::Store<ESM::GameSetting> &store = world->getStore().get<ESM::GameSetting>();

            gmst.fMinWalkSpeed = store.find("fMinWalkSpeed");
            gmst.fMaxWalkSpeed = store.find("fMaxWalkSpeed");
            gmst.fEncumberedMoveEffect = store.find("fEncumberedMoveEffect");
            gmst.fSneakSpeedMultiplier = store.find("fSneakSpeedMultiplier");
            gmst.fAthleticsRunBonus = store.find("fAthleticsRunBonus");
            gmst.fBaseRunMultiplier = store.find("fBaseRunMultiplier");
            gmst.fMinFlySpeed = store.find("fMinFlySpeed");
            gmst.fMaxFlySpeed = store.find("fMaxFlySpeed");
            gmst.fSwimRunBase = store.find("fSwimRunBase");
            gmst.fSwimRunAthleticsMult = store.find("fSwimRunAthleticsMult");
            gmst.fJumpEncumbranceBase = store.find("fJumpEncumbranceBase");
            gmst.fJumpEncumbranceMultiplier = store.find("fJumpEncumbranceMultiplier");
            gmst.fJumpAcrobaticsBase = store.find("fJumpAcrobaticsBase");
            gmst.fJumpAcroMultiplier = store.find("fJumpAcroMultiplier");
            gmst.fJumpRunMultiplier = store.find("fJumpRunMultiplier");
            gmst.fWereWolfRunMult = store.find("fWereWolfRunMult");
            gmst.fKnockDownMult = store.find("fKnockDownMult");
            gmst.iKnockDownOddsMult = store.find("iKnockDownOddsMult");
            gmst.iKnockDownOddsBase = store.find("iKnockDownOddsBase");
            gmst.fDamageStrengthBase = store.find("fDamageStrengthBase");
            gmst.fDamageStrengthMult = store.find("fDamageStrengthMult");
286 287 288

            inited = true;
        }
289 290 291 292 293
        return gmst;
    }

    void Npc::ensureCustomData (const MWWorld::Ptr& ptr) const
    {
294 295
        if (!ptr.getRefData().getCustomData())
        {
296
            std::auto_ptr<NpcCustomData> data(new NpcCustomData);
297

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

300
            // NPC stats
greye's avatar
greye committed
301
            if (!ref->mBase->mFaction.empty())
302
            {
greye's avatar
greye committed
303
                std::string faction = ref->mBase->mFaction;
eduard's avatar
eduard committed
304
                Misc::StringUtils::toLower(faction);
305
                if(ref->mBase->mNpdtType != ESM::NPC::NPC_WITH_AUTOCALCULATED_STATS)
306
                {
greye's avatar
greye committed
307
                    data->mNpcStats.getFactionRanks()[faction] = (int)ref->mBase->mNpdt52.mRank;
308 309 310
                }
                else
                {
greye's avatar
greye committed
311
                    data->mNpcStats.getFactionRanks()[faction] = (int)ref->mBase->mNpdt12.mRank;
312
                }
313 314
            }

315
            // creature stats
316
            int gold=0;
317
            if(ref->mBase->mNpdtType != ESM::NPC::NPC_WITH_AUTOCALCULATED_STATS)
318
            {
319 320
                gold = ref->mBase->mNpdt52.mGold;

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

324 325 326 327 328 329 330 331 332
                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);

333 334 335 336 337
                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
338
                data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt52.mDisposition);
339
                data->mNpcStats.setReputation(ref->mBase->mNpdt52.mReputation);
340 341 342
            }
            else
            {
343 344
                gold = ref->mBase->mNpdt12.mGold;

345
                for (int i=0; i<3; ++i)
346
                    data->mNpcStats.setDynamic (i, 10);
347

348
                data->mNpcStats.setLevel(ref->mBase->mNpdt12.mLevel);
349 350
                data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt12.mDisposition);
                data->mNpcStats.setReputation(ref->mBase->mNpdt12.mReputation);
351

352
                autoCalculateAttributes(ref->mBase, data->mNpcStats);
353
                autoCalculateSkills(ref->mBase, data->mNpcStats, ptr);
354
            }
355

356 357 358 359 360 361 362 363
            // race powers
            const ESM::Race *race = MWBase::Environment::get().getWorld()->getStore().get<ESM::Race>().find(ref->mBase->mRace);
            for (std::vector<std::string>::const_iterator iter (race->mPowers.mList.begin());
                iter!=race->mPowers.mList.end(); ++iter)
            {
                data->mNpcStats.getSpells().add (*iter);
            }

364 365 366 367 368 369 370 371 372 373 374
            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));
            }

375
            data->mNpcStats.getAiSequence().fill(ref->mBase->mAiPackage);
376

377 378 379 380
            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);
381

382
            // spells
greye's avatar
greye committed
383 384
            for (std::vector<std::string>::const_iterator iter (ref->mBase->mSpells.mList.begin());
                iter!=ref->mBase->mSpells.mList.end(); ++iter)
385
                data->mNpcStats.getSpells().add (*iter);
386

387
            // inventory
scrawl's avatar
scrawl committed
388
            data->mInventoryStore.fill(ref->mBase->mInventory, getId(ptr), "",
389 390
                                       MWBase::Environment::get().getWorld()->getStore());

jefhai's avatar
jefhai committed
391 392
            data->mNpcStats.setGoldPool(gold);

393
            // store
394
            ptr.getRefData().setCustomData (data.release());
395

396
            getInventoryStore(ptr).autoEquip(ptr); 
397 398 399
        }
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
400 401
    std::string Npc::getId (const MWWorld::Ptr& ptr) const
    {
402
        MWWorld::LiveCellRef<ESM::NPC> *ref =
Marc Zinnschlag's avatar
Marc Zinnschlag committed
403 404
            ptr.get<ESM::NPC>();

greye's avatar
greye committed
405
        return ref->mBase->mId;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
406 407
    }

408 409 410 411 412
    void Npc::adjustPosition(const MWWorld::Ptr& ptr) const
    {
        MWBase::Environment::get().getWorld()->adjustPosition(ptr);
    }

Jason Hooks's avatar
Jason Hooks committed
413
    void Npc::insertObjectRendering (const MWWorld::Ptr& ptr, MWRender::RenderingInterface& renderingInterface) const
414
    {
415
        renderingInterface.getActors().insertNPC(ptr);
Jason Hooks's avatar
Jason Hooks committed
416
    }
Jason Hooks's avatar
Jason Hooks committed
417

418
    void Npc::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const
Jason Hooks's avatar
Jason Hooks committed
419
    {
420
        physics.addActor(ptr);
421
        MWBase::Environment::get().getMechanicsManager()->add(ptr);
422 423
        if (getCreatureStats(ptr).isDead())
            MWBase::Environment::get().getWorld()->enableActorCollision(ptr, false);
greye's avatar
greye committed
424
    }
Jason Hooks's avatar
Jason Hooks committed
425

scrawl's avatar
scrawl committed
426 427 428 429 430 431
    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
432 433
    std::string Npc::getModel(const MWWorld::Ptr &ptr) const
    {
434
        MWWorld::LiveCellRef<ESM::NPC> *ref =
Jason Hooks's avatar
Jason Hooks committed
435
            ptr.get<ESM::NPC>();
greye's avatar
greye committed
436
        assert(ref->mBase != NULL);
437

greye's avatar
greye committed
438
        std::string model = "meshes\\base_anim.nif";
439 440
        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
441
            model = "meshes\\base_animkna.nif";
442

greye's avatar
greye committed
443
        return model;
444 445 446

    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
447 448
    std::string Npc::getName (const MWWorld::Ptr& ptr) const
    {
449 450 451
        if(getNpcStats(ptr).isWerewolf())
        {
            const MWBase::World *world = MWBase::Environment::get().getWorld();
452
            const MWWorld::Store<ESM::GameSetting> &store = world->getStore().get<ESM::GameSetting>();
453

454
            return store.find("sWerewolfPopup")->getString();
455
        }
Marc Zinnschlag's avatar
Marc Zinnschlag committed
456

457
        MWWorld::LiveCellRef<ESM::NPC> *ref = ptr.get<ESM::NPC>();
greye's avatar
greye committed
458
        return ref->mBase->mName;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
459 460
    }

461
    MWMechanics::CreatureStats& Npc::getCreatureStats (const MWWorld::Ptr& ptr) const
462
    {
463
        ensureCustomData (ptr);
464

465
        return dynamic_cast<NpcCustomData&> (*ptr.getRefData().getCustomData()).mNpcStats;
466 467
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
468 469
    MWMechanics::NpcStats& Npc::getNpcStats (const MWWorld::Ptr& ptr) const
    {
470
        ensureCustomData (ptr);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
471

472
        return dynamic_cast<NpcCustomData&> (*ptr.getRefData().getCustomData()).mNpcStats;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
473 474
    }

Chris Robinson's avatar
Chris Robinson committed
475

476
    void Npc::hit(const MWWorld::Ptr& ptr, int type) const
Chris Robinson's avatar
Chris Robinson committed
477
    {
478
        MWBase::World *world = MWBase::Environment::get().getWorld();
479 480 481
        const GMST& gmst = getGmst();

        const MWWorld::Store<ESM::GameSetting> &store = world->getStore().get<ESM::GameSetting>();
482

483 484
        // Get the weapon used (if hand-to-hand, weapon = inv.end())
        MWWorld::InventoryStore &inv = getInventoryStore(ptr);
485 486 487 488
        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();
489

490 491
        // Reduce fatigue
        // somewhat of a guess, but using the weapon weight makes sense
492 493 494
        const float fFatigueAttackBase = store.find("fFatigueAttackBase")->getFloat();
        const float fFatigueAttackMult = store.find("fFatigueAttackMult")->getFloat();
        const float fWeaponFatigueMult = store.find("fWeaponFatigueMult")->getFloat();
495 496 497 498 499 500 501 502
        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);

503
        const float fCombatDistance = store.find("fCombatDistance")->getFloat();
scrawl's avatar
scrawl committed
504
        float dist = fCombatDistance * (!weapon.isEmpty() ?
505
                               weapon.get<ESM::Weapon>()->mBase->mData.mReach :
506
                               store.find("fHandToHandReach")->getFloat());
scrawl's avatar
scrawl committed
507

scrawl's avatar
scrawl committed
508
        // TODO: Use second to work out the hit angle
scrawl's avatar
scrawl committed
509 510 511
        std::pair<MWWorld::Ptr, Ogre::Vector3> result = world->getHitContact(ptr, dist);
        MWWorld::Ptr victim = result.first;
        Ogre::Vector3 hitPosition = result.second;
Chris Robinson's avatar
Chris Robinson committed
512 513 514
        if(victim.isEmpty()) // Didn't hit anything
            return;

515
        const MWWorld::Class &othercls = victim.getClass();
516 517
        if(!othercls.isActor()) // Can't hit non-actors
            return;
518
        MWMechanics::CreatureStats &otherstats = othercls.getCreatureStats(victim);
519
        if(otherstats.isDead()) // Can't hit dead actors
Chris Robinson's avatar
Chris Robinson committed
520 521
            return;

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

525
        int weapskill = ESM::Skill::HandToHand;
526
        if(!weapon.isEmpty())
527
            weapskill = weapon.getClass().getEquipmentSkill(weapon);
528

529
        float hitchance = MWMechanics::getHitChance(ptr, victim, ptr.getClass().getSkill(ptr, weapskill));
530

Chris Robinson's avatar
Chris Robinson committed
531
        if((::rand()/(RAND_MAX+1.0)) > hitchance/100.0f)
532
        {
533
            othercls.onHit(victim, 0.0f, false, weapon, ptr, false);
534 535
            return;
        }
Chris Robinson's avatar
Chris Robinson committed
536

537
        bool healthdmg;
538
        float damage = 0.0f;
539
        MWMechanics::NpcStats &stats = getNpcStats(ptr);
540
        if(!weapon.isEmpty())
Chris Robinson's avatar
Chris Robinson committed
541
        {
542
            const bool weaphashealth = weapon.getClass().hasItemHealth(weapon);
543
            const unsigned char *attack = NULL;
mrcheko's avatar
mrcheko committed
544
            if(type == ESM::Weapon::AT_Chop)
545
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mChop;
mrcheko's avatar
mrcheko committed
546
            else if(type == ESM::Weapon::AT_Slash)
547
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mSlash;
mrcheko's avatar
mrcheko committed
548
            else if(type == ESM::Weapon::AT_Thrust)
549
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mThrust;
550
            if(attack)
551
            {
552
                damage  = attack[0] + ((attack[1]-attack[0])*stats.getAttackStrength());
553 554
                damage *= gmst.fDamageStrengthBase->getFloat() +
                        (stats.getAttribute(ESM::Attribute::Strength).getModified() * gmst.fDamageStrengthMult->getFloat() * 0.1);
555 556
                if(weaphashealth)
                {
557 558
                    int weapmaxhealth = weapon.getClass().getItemMaxHealth(weapon);
                    int weaphealth = weapon.getClass().getItemHealth(weapon);
559

560
                    damage *= float(weaphealth) / weapmaxhealth;
561

562 563 564 565
                    if (!MWBase::Environment::get().getWorld()->getGodModeState())
                    {
                        // Reduce weapon charge by at least one, but cap at 0
                        weaphealth -= std::min(std::max(1,
566
                                    (int)(damage * store.find("fWeaponDamageMult")->getFloat())), weaphealth);
567

568 569 570 571 572 573 574
                        weapon.getCellRef().setCharge(weaphealth);
                    }

                    // Weapon broken? unequip it
                    if (weaphealth == 0)
                        weapon = *inv.unequipItem(weapon, ptr);
                }
575
            }
576 577 578 579 580 581 582
            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.
583 584
            float minstrike = store.find("fMinHandToHandMult")->getFloat();
            float maxstrike = store.find("fMaxHandToHandMult")->getFloat();
585 586
            damage  = stats.getSkill(weapskill).getModified();
            damage *= minstrike + ((maxstrike-minstrike)*stats.getAttackStrength());
587

scrawl's avatar
scrawl committed
588 589
            healthdmg = (otherstats.getFatigue().getCurrent() < 1.0f)
                    || (otherstats.getMagicEffects().get(ESM::MagicEffect::Paralyze).mMagnitude > 0);
590
            if(stats.isWerewolf())
591 592 593 594 595 596
            {
                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();
            }
597
            if(healthdmg)
598
                damage *= store.find("fHandtoHandHealthPer")->getFloat();
599 600 601 602

            MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();
            if(stats.isWerewolf())
            {
603 604 605
                const ESM::Sound *sound = world->getStore().get<ESM::Sound>().searchRandom("WolfHit");
                if(sound)
                    sndMgr->playSound3D(victim, sound->mId, 1.0f, 1.0f);
606 607 608
            }
            else
                sndMgr->playSound3D(victim, "Hand To Hand Hit", 1.0f, 1.0f);
Chris Robinson's avatar
Chris Robinson committed
609
        }
610 611
        if(ptr.getRefData().getHandle() == "player")
            skillUsageSucceeded(ptr, weapskill, 0);
612

613 614 615
        bool detected = MWBase::Environment::get().getMechanicsManager()->awarenessCheck(ptr, victim);
        if(!detected)
        {
616
            damage *= store.find("fCombatCriticalStrikeMult")->getFloat();
617 618 619 620
            MWBase::Environment::get().getWindowManager()->messageBox("#{sTargetCriticalStrike}");
            MWBase::Environment::get().getSoundManager()->playSound3D(victim, "critical damage", 1.0f, 1.0f);
        }
        if (othercls.getCreatureStats(victim).getKnockedDown())
621
            damage *= store.find("fCombatKODamageMult")->getFloat();
622

623
        // Apply "On hit" enchanted weapons
624
        std::string enchantmentName = !weapon.isEmpty() ? weapon.getClass().getEnchantment(weapon) : "";
625 626 627 628 629 630
        if (!enchantmentName.empty())
        {
            const ESM::Enchantment* enchantment = MWBase::Environment::get().getWorld()->getStore().get<ESM::Enchantment>().find(
                        enchantmentName);
            if (enchantment->mData.mType == ESM::Enchantment::WhenStrikes)
            {
631 632
                MWMechanics::CastSpell cast(ptr, victim);
                cast.mHitPosition = hitPosition;
633
                cast.cast(weapon);
634 635 636
            }
        }

637 638 639 640
        if (!weapon.isEmpty() && MWMechanics::blockMeleeAttack(ptr, victim, weapon, damage))
            damage = 0;

        if (healthdmg && damage > 0)
641
            MWBase::Environment::get().getWorld()->spawnBloodEffect(victim, hitPosition);
scrawl's avatar
scrawl committed
642

643 644
        MWMechanics::diseaseContact(victim, ptr);

645
        othercls.onHit(victim, damage, healthdmg, weapon, ptr, true);
Chris Robinson's avatar
Chris Robinson committed
646 647
    }

648
    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
649
    {
650 651
        MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();

652 653
        // NOTE: 'object' and/or 'attacker' may be empty.

scrawl's avatar
scrawl committed
654
        // Attacking peaceful NPCs is a crime
655
        if (!attacker.isEmpty() && !ptr.getClass().getCreatureStats(ptr).isHostile() &&
656
                !MWBase::Environment::get().getMechanicsManager()->isAggressive(ptr, attacker))
scrawl's avatar
scrawl committed
657 658
            MWBase::Environment::get().getMechanicsManager()->commitCrime(attacker, ptr, MWBase::MechanicsManager::OT_Assault);

659 660
        bool wasDead = getCreatureStats(ptr).isDead();

661 662
        getCreatureStats(ptr).setAttacked(true);

663 664 665 666 667
        if(!successful)
        {
            // TODO: Handle HitAttemptOnMe script function

            // Missed
668
            sndMgr->playSound3D(ptr, "miss", 1.0f, 1.0f);
669 670
            return;
        }
Chris Robinson's avatar
Chris Robinson committed
671

672
        if(!object.isEmpty())
673
            getCreatureStats(ptr).setLastHitObject(object.getClass().getId(object));
674 675 676

        if(!attacker.isEmpty() && attacker.getRefData().getHandle() == "player")
        {
scrawl's avatar
scrawl committed
677
            const std::string &script = ptr.getClass().getScript(ptr);
678 679 680 681
            /* Set the OnPCHitMe script variable. The script is responsible for clearing it. */
            if(!script.empty())
                ptr.getRefData().getLocals().setVarByInt(script, "onpchitme", 1);
        }
682

683 684 685
        if (damage > 0.0f && !object.isEmpty())
            MWMechanics::resistNormalWeapon(ptr, attacker, object, damage);

686
        if(damage > 0.0f)
Chris Robinson's avatar
Chris Robinson committed
687 688 689
        {
            // 'ptr' is losing health. Play a 'hit' voiced dialog entry if not already saying
            // something, alert the character controller, scripts, etc.
690

scrawl's avatar
scrawl committed
691
            const MWWorld::ESMStore &store = MWBase::Environment::get().getWorld()->getStore();
692 693
            const GMST& gmst = getGmst();

scrawl's avatar
scrawl committed
694 695 696 697 698 699
            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");
            }
700 701

            // Check for knockdown
702
            float agilityTerm = getCreatureStats(ptr).getAttribute(ESM::Attribute::Agility).getModified() * gmst.fKnockDownMult->getFloat();
703
            float knockdownTerm = getCreatureStats(ptr).getAttribute(ESM::Attribute::Agility).getModified()
704
                    * gmst.iKnockDownOddsMult->getInt() * 0.01 + gmst.iKnockDownOddsBase->getInt();
705 706 707 708 709 710 711 712
            roll = std::rand()/ (static_cast<double> (RAND_MAX) + 1) * 100; // [0, 99]
            if (ishealth && agilityTerm <= damage && knockdownTerm <= roll)
            {
                getCreatureStats(ptr).setKnockedDown(true);

            }
            else
                getCreatureStats(ptr).setHitRecovery(true); // Is this supposed to always occur?
713

714
            if(ishealth && !attacker.isEmpty()) // Don't use armor mitigation for fall damage
715
            {
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
                // 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)];

734 735 736 737
                float damagediff = damage;
                damage /= std::min(1.0f + getArmorRating(ptr)/std::max(1.0f, damage), 4.0f);
                damagediff -= damage;

738 739 740 741
                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())
742
                {
743 744 745 746
                    int armorhealth = armor.getClass().getItemHealth(armor);
                    armorhealth -= std::min(std::max(1, (int)damagediff),
                                                 armorhealth);
                    armor.getCellRef().setCharge(armorhealth);
747 748

                    // Armor broken? unequip it
749
                    if (armorhealth == 0)
750 751
                        inv.unequipItem(armor, ptr);

752
                    if (ptr.getRefData().getHandle() == "player")
753
                        skillUsageSucceeded(ptr, armor.getClass().getEquipmentSkill(armor), 0);
754

755
                    switch(armor.getClass().getEquipmentSkill(armor))
756 757 758 759 760 761 762 763 764 765 766
                    {
                        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;
                    }
767
                }
768 769
                else if(ptr.getRefData().getHandle() == "player")
                    skillUsageSucceeded(ptr, ESM::Skill::Unarmored, 0);
770
            }
Chris Robinson's avatar
Chris Robinson committed
771 772
        }

773 774 775 776 777 778 779 780 781 782
        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());
783
            fatigue.setCurrent(fatigue.getCurrent() - damage, true);
784 785
            getCreatureStats(ptr).setFatigue(fatigue);
        }
786 787 788 789

        if (!wasDead && getCreatureStats(ptr).isDead())
        {
            // NPC was killed
scrawl's avatar
scrawl committed
790 791 792 793 794
            if (!attacker.isEmpty() && attacker.getClass().isNpc() && attacker.getClass().getNpcStats(attacker).isWerewolf())
            {
                attacker.getClass().getNpcStats(attacker).addWerewolfKill();
            }

795 796 797 798
            // Simple check for who attacked first: if the player attacked first, a crimeId should be set
            // Doesn't handle possible edge case where no one reported the assault, but in such a case,
            // for bystanders it is not possible to tell who attacked first, anyway.
            MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayerPtr();
scrawl's avatar
scrawl committed
799
            if (attacker == player && ptr.getClass().getNpcStats(ptr).getCrimeId() != -1 && ptr != player)
800 801
                MWBase::Environment::get().getMechanicsManager()->commitCrime(player, ptr, MWBase::MechanicsManager::OT_Murder);
        }
802 803
    }

804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825