npc.cpp 53.8 KB
Newer Older
1 2 3

#include "npc.hpp"

4 5
#include <memory>

scrawl's avatar
scrawl committed
6
#include <components/misc/rng.hpp>
dteviot's avatar
dteviot committed
7

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"
26
#include "../mwmechanics/difficultyscaling.hpp"
27
#include "../mwmechanics/character.hpp"
Marc Zinnschlag's avatar
Marc Zinnschlag committed
28

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

38
#include "../mwrender/objects.hpp"
39
#include "../mwrender/renderinginterface.hpp"
40

41
#include "../mwgui/tooltips.hpp"
42

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

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

54
    MWWorld::CustomData *NpcCustomData::clone() const
55
    {
56
        return new NpcCustomData (*this);
57
    }
58

59 60 61 62 63 64 65 66 67 68
    int is_even(double d) {
        double int_part;
        modf(d / 2.0, &int_part);
        return 2.0 * int_part == d;
    }

    int round_ieee_754(double d) {
        double i = floor(d);
        d -= i;
        if(d < 0.5)
69
            return static_cast<int>(i);
70
        if(d > 0.5)
71
            return static_cast<int>(i) + 1;
72
        if(is_even(i))
73 74
            return static_cast<int>(i);
        return static_cast<int>(i) + 1;
75 76
    }

77 78 79 80 81 82 83 84 85 86 87 88
    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];
89
            creatureStats.setAttribute(i, male ? attribute.mMale : attribute.mFemale);
90 91 92 93 94 95 96 97 98 99 100
        }

        // 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)
            {
101
                creatureStats.setAttribute(attribute,
102 103 104 105 106
                    creatureStats.getAttribute(attribute).getBase() + 10);
            }
        }

        // skill bonus
107
        for (int attribute=0; attribute < ESM::Attribute::Length; ++attribute)
108 109 110 111 112 113 114 115 116 117 118
        {
            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?
119
                float add=0.2f;
120 121 122 123 124 125 126 127 128 129 130 131
                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;
            }
132 133 134
            creatureStats.setAttribute(attribute, std::min(
                                           round_ieee_754(creatureStats.getAttribute(attribute).getBase()
                + (level-1) * modifierSum), 100) );
135
        }
136

137
        // initial health
138 139
        int strength = creatureStats.getAttribute(ESM::Attribute::Strength).getBase();
        int endurance = creatureStats.getAttribute(ESM::Attribute::Endurance).getBase();
140 141 142 143 144 145 146 147 148 149 150 151

        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;

152
        creatureStats.setHealth(floor(0.5f * (strength + endurance)) + multiplier * (creatureStats.getLevel() - 1));
153
    }
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168

    /**
     * @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.
     */
169
    void autoCalculateSkills(const ESM::NPC* npc, MWMechanics::NpcStats& npcStats, const MWWorld::Ptr& ptr)
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
    {
        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)
            {
203 204 205 206 207
                if (race->mData.mBonus[raceSkillIndex].mSkill == skillIndex)
                {
                    raceBonus = race->mData.mBonus[raceSkillIndex].mBonus;
                    break;
                }
208 209 210 211
            }

            for (int k = 0; k < 5; ++k)
            {
212 213 214 215 216 217
                // is this a minor or major skill?
                if ((class_->mData.mSkills[k][0] == skillIndex) || (class_->mData.mSkills[k][1] == skillIndex))
                {
                    majorMultiplier = 1.0f;
                    break;
                }
218 219 220 221 222 223
            }

            // 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)
            {
224 225
                specMultiplier = 0.5f;
                specBonus = 5;
226 227 228 229
            }

            npcStats.getSkill(skillIndex).setBase(
                  std::min(
230 231
                    round_ieee_754(
                            npcStats.getSkill(skillIndex).getBase()
232 233 234
                    + 5
                    + raceBonus
                    + specBonus
scrawl's avatar
scrawl committed
235
                    +(int(level)-1) * (majorMultiplier + specMultiplier)), 100)); // Must gracefully handle level 0
236
        }
237 238 239 240 241 242 243 244 245

        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();

246 247
        std::vector<std::string> spells = MWMechanics::autoCalcNpcSpells(skills, attributes, race);
        for (std::vector<std::string>::iterator it = spells.begin(); it != spells.end(); ++it)
248
            npcStats.getSpells().add(*it);
249
    }
250 251
}

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

            inited = true;
        }
286 287 288 289 290
        return gmst;
    }

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

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

297
            // creature stats
298
            int gold=0;
299
            if(ref->mBase->mNpdtType != ESM::NPC::NPC_WITH_AUTOCALCULATED_STATS)
300
            {
301 302
                gold = ref->mBase->mNpdt52.mGold;

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

306 307 308 309 310 311 312 313 314
                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);

315 316 317 318 319
                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
320
                data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt52.mDisposition);
321
                data->mNpcStats.setReputation(ref->mBase->mNpdt52.mReputation);
322 323

                data->mNpcStats.setNeedRecalcDynamicStats(false);
324 325 326
            }
            else
            {
327 328
                gold = ref->mBase->mNpdt12.mGold;

329
                for (int i=0; i<3; ++i)
330
                    data->mNpcStats.setDynamic (i, 10);
331

332
                data->mNpcStats.setLevel(ref->mBase->mNpdt12.mLevel);
333 334
                data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt12.mDisposition);
                data->mNpcStats.setReputation(ref->mBase->mNpdt12.mReputation);
335

336
                autoCalculateAttributes(ref->mBase, data->mNpcStats);
337
                autoCalculateSkills(ref->mBase, data->mNpcStats, ptr);
338 339

                data->mNpcStats.setNeedRecalcDynamicStats(true);
340
            }
341

342 343 344 345 346
            // 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)
            {
scrawl's avatar
scrawl committed
347
                if (const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().get<ESM::Spell>().search(*iter))
348 349 350
                    data->mNpcStats.getSpells().add (spell);
                else
                    std::cerr << "Warning: ignoring nonexistent race power '" << *iter << "' on NPC '" << ref->mBase->mId << "'" << std::endl;
351 352
            }

scrawl's avatar
scrawl committed
353
            if (!ref->mBase->mFaction.empty())
354 355 356 357 358
            {
                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();
scrawl's avatar
scrawl committed
359
                int rank = ref->mBase->getFactionRank();
360 361 362 363

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

364
            data->mNpcStats.getAiSequence().fill(ref->mBase->mAiPackage);
365

366 367 368 369
            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);
370

371
            // spells
greye's avatar
greye committed
372 373
            for (std::vector<std::string>::const_iterator iter (ref->mBase->mSpells.mList.begin());
                iter!=ref->mBase->mSpells.mList.end(); ++iter)
374
            {
scrawl's avatar
scrawl committed
375
                if (const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().get<ESM::Spell>().search(*iter))
376 377 378 379 380 381 382
                    data->mNpcStats.getSpells().add (spell);
                else
                {
                    /// \todo add option to make this a fatal error message pop-up, but default to warning for vanilla compatibility
                    std::cerr << "Warning: ignoring nonexistent spell '" << *iter << "' on NPC '" << ref->mBase->mId << "'" << std::endl;
                }
            }
383

384
            // inventory
385 386
            // setting ownership is used to make the NPC auto-equip his initial equipment only, and not bartered items
            data->mInventoryStore.fill(ref->mBase->mInventory, getId(ptr));
387

jefhai's avatar
jefhai committed
388 389
            data->mNpcStats.setGoldPool(gold);

390
            // store
391
            ptr.getRefData().setCustomData (data.release());
392

393
            getInventoryStore(ptr).autoEquip(ptr); 
394 395 396
        }
    }

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

greye's avatar
greye committed
402
        return ref->mBase->mId;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
403 404
    }

405
    void Npc::adjustPosition(const MWWorld::Ptr& ptr, bool force) const
406
    {
407
        MWBase::Environment::get().getWorld()->adjustPosition(ptr, force);
408 409
    }

410
    void Npc::insertObjectRendering (const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
411
    {
412
        renderingInterface.getObjects().insertNPC(ptr);
Jason Hooks's avatar
Jason Hooks committed
413
    }
Jason Hooks's avatar
Jason Hooks committed
414

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

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

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

greye's avatar
greye committed
440
        return model;
441 442 443

    }

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

451
            return store.find("sWerewolfPopup")->getString();
452
        }
Marc Zinnschlag's avatar
Marc Zinnschlag committed
453

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

458
    MWMechanics::CreatureStats& Npc::getCreatureStats (const MWWorld::Ptr& ptr) const
459
    {
460
        ensureCustomData (ptr);
461

462
        return dynamic_cast<NpcCustomData&> (*ptr.getRefData().getCustomData()).mNpcStats;
463 464
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
465 466
    MWMechanics::NpcStats& Npc::getNpcStats (const MWWorld::Ptr& ptr) const
    {
467
        ensureCustomData (ptr);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
468

469
        return dynamic_cast<NpcCustomData&> (*ptr.getRefData().getCustomData()).mNpcStats;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
470 471
    }

Chris Robinson's avatar
Chris Robinson committed
472

473
    void Npc::hit(const MWWorld::Ptr& ptr, int type) const
Chris Robinson's avatar
Chris Robinson committed
474
    {
475
        MWBase::World *world = MWBase::Environment::get().getWorld();
476 477

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

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

scrawl's avatar
scrawl committed
486
        MWMechanics::applyFatigueLoss(ptr, weapon);
487

488
        const float fCombatDistance = store.find("fCombatDistance")->getFloat();
scrawl's avatar
scrawl committed
489
        float dist = fCombatDistance * (!weapon.isEmpty() ?
490
                               weapon.get<ESM::Weapon>()->mBase->mData.mReach :
491
                               store.find("fHandToHandReach")->getFloat());
scrawl's avatar
scrawl committed
492

scrawl's avatar
scrawl committed
493
        // TODO: Use second to work out the hit angle
scrawl's avatar
scrawl committed
494
        std::pair<MWWorld::Ptr, osg::Vec3f> result = world->getHitContact(ptr, dist);
scrawl's avatar
scrawl committed
495
        MWWorld::Ptr victim = result.first;
scrawl's avatar
scrawl committed
496
        Ogre::Vector3 hitPosition (result.second.x(), result.second.y(), result.second.z());
Chris Robinson's avatar
Chris Robinson committed
497 498 499
        if(victim.isEmpty()) // Didn't hit anything
            return;

500
        const MWWorld::Class &othercls = victim.getClass();
501 502
        if(!othercls.isActor()) // Can't hit non-actors
            return;
503
        MWMechanics::CreatureStats &otherstats = othercls.getCreatureStats(victim);
504
        if(otherstats.isDead()) // Can't hit dead actors
Chris Robinson's avatar
Chris Robinson committed
505 506
            return;

507
        if(ptr == MWBase::Environment::get().getWorld()->getPlayerPtr())
scrawl's avatar
scrawl committed
508
            MWBase::Environment::get().getWindowManager()->setEnemy(victim);
scrawl's avatar
scrawl committed
509

510
        int weapskill = ESM::Skill::HandToHand;
511
        if(!weapon.isEmpty())
512
            weapskill = weapon.getClass().getEquipmentSkill(weapon);
513

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

scrawl's avatar
scrawl committed
516
        if (Misc::Rng::rollProbability() >= hitchance / 100.0f)
517
        {
518
            othercls.onHit(victim, 0.0f, false, weapon, ptr, false);
519
            MWMechanics::reduceWeaponCondition(0.f, false, weapon, ptr);
520 521
            return;
        }
Chris Robinson's avatar
Chris Robinson committed
522

523
        bool healthdmg;
524
        float damage = 0.0f;
525
        MWMechanics::NpcStats &stats = getNpcStats(ptr);
526
        if(!weapon.isEmpty())
Chris Robinson's avatar
Chris Robinson committed
527
        {
528
            const unsigned char *attack = NULL;
mrcheko's avatar
mrcheko committed
529
            if(type == ESM::Weapon::AT_Chop)
530
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mChop;
mrcheko's avatar
mrcheko committed
531
            else if(type == ESM::Weapon::AT_Slash)
532
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mSlash;
mrcheko's avatar
mrcheko committed
533
            else if(type == ESM::Weapon::AT_Thrust)
534
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mThrust;
535
            if(attack)
536
            {
537
                damage  = attack[0] + ((attack[1]-attack[0])*stats.getAttackStrength());
538
            }
scrawl's avatar
scrawl committed
539
            MWMechanics::adjustWeaponDamage(damage, weapon, ptr);
540
            MWMechanics::reduceWeaponCondition(damage, true, weapon, ptr);
541 542 543 544
            healthdmg = true;
        }
        else
        {
545
            MWMechanics::getHandToHandDamage(ptr, victim, damage, healthdmg);
Chris Robinson's avatar
Chris Robinson committed
546
        }
547
        if(ptr == MWBase::Environment::get().getWorld()->getPlayerPtr())
scrawl's avatar
scrawl committed
548
        {
549
            skillUsageSucceeded(ptr, weapskill, 0);
550

scrawl's avatar
scrawl committed
551 552 553 554 555 556 557 558 559 560
            const MWMechanics::AiSequence& seq = victim.getClass().getCreatureStats(victim).getAiSequence();

            bool unaware = !seq.isInCombat()
                    && !MWBase::Environment::get().getMechanicsManager()->awarenessCheck(ptr, victim);
            if(unaware)
            {
                damage *= store.find("fCombatCriticalStrikeMult")->getFloat();
                MWBase::Environment::get().getWindowManager()->messageBox("#{sTargetCriticalStrike}");
                MWBase::Environment::get().getSoundManager()->playSound3D(victim, "critical damage", 1.0f, 1.0f);
            }
561
        }
scrawl's avatar
scrawl committed
562

563
        if (othercls.getCreatureStats(victim).getKnockedDown())
564
            damage *= store.find("fCombatKODamageMult")->getFloat();
565

566
        // Apply "On hit" enchanted weapons
567
        std::string enchantmentName = !weapon.isEmpty() ? weapon.getClass().getEnchantment(weapon) : "";
568 569 570 571 572 573
        if (!enchantmentName.empty())
        {
            const ESM::Enchantment* enchantment = MWBase::Environment::get().getWorld()->getStore().get<ESM::Enchantment>().find(
                        enchantmentName);
            if (enchantment->mData.mType == ESM::Enchantment::WhenStrikes)
            {
574 575
                MWMechanics::CastSpell cast(ptr, victim);
                cast.mHitPosition = hitPosition;
576
                cast.cast(weapon);
577 578 579
            }
        }

580 581
        MWMechanics::applyElementalShields(ptr, victim);

582
        if (MWMechanics::blockMeleeAttack(ptr, victim, weapon, damage))
583 584 585
            damage = 0;

        if (healthdmg && damage > 0)
scrawl's avatar
scrawl committed
586
            MWBase::Environment::get().getWorld()->spawnBloodEffect(victim, osg::Vec3f(hitPosition.x, hitPosition.y, hitPosition.z));
scrawl's avatar
scrawl committed
587

588 589
        MWMechanics::diseaseContact(victim, ptr);

590
        othercls.onHit(victim, damage, healthdmg, weapon, ptr, true);
Chris Robinson's avatar
Chris Robinson committed
591 592
    }

593
    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
594
    {
595 596
        MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();

597 598
        // NOTE: 'object' and/or 'attacker' may be empty.

599 600
        bool wasDead = getCreatureStats(ptr).isDead();

601 602
        // Note OnPcHitMe is not set for friendly hits.
        bool setOnPcHitMe = true;
603 604 605
        if (!attacker.isEmpty() && !ptr.getClass().getCreatureStats(ptr).getAiSequence().isInCombat(attacker))
        {
            getCreatureStats(ptr).setAttacked(true);
606

607
            setOnPcHitMe = MWBase::Environment::get().getMechanicsManager()->actorAttacked(ptr, attacker);
608
        }
609

610 611 612
        if(!object.isEmpty())
            getCreatureStats(ptr).setLastHitAttemptObject(object.getClass().getId(object));

613 614 615
        if(!successful)
        {
            // Missed
616
            sndMgr->playSound3D(ptr, "miss", 1.0f, 1.0f);
617 618
            return;
        }
Chris Robinson's avatar
Chris Robinson committed
619

620
        if(!object.isEmpty())
621
            getCreatureStats(ptr).setLastHitObject(object.getClass().getId(object));
622

623
        if(setOnPcHitMe && !attacker.isEmpty() && attacker == MWBase::Environment::get().getWorld()->getPlayerPtr())
624
        {
scrawl's avatar
scrawl committed
625
            const std::string &script = ptr.getClass().getScript(ptr);
626 627 628 629
            /* Set the OnPCHitMe script variable. The script is responsible for clearing it. */
            if(!script.empty())
                ptr.getRefData().getLocals().setVarByInt(script, "onpchitme", 1);
        }
630

631 632 633
        if (damage > 0.0f && !object.isEmpty())
            MWMechanics::resistNormalWeapon(ptr, attacker, object, damage);

634 635 636
        if (damage < 0.001f)
            damage = 0;

637
        if(damage > 0.0f && !attacker.isEmpty())
Chris Robinson's avatar
Chris Robinson committed
638 639 640
        {
            // 'ptr' is losing health. Play a 'hit' voiced dialog entry if not already saying
            // something, alert the character controller, scripts, etc.
641

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

scrawl's avatar
scrawl committed
645
            int chance = store.get<ESM::GameSetting>().find("iVoiceHitOdds")->getInt();
scrawl's avatar
scrawl committed
646
            if (Misc::Rng::roll0to99() < chance)
scrawl's avatar
scrawl committed
647 648 649
            {
                MWBase::Environment::get().getDialogueManager()->say(ptr, "hit");
            }
650 651

            // Check for knockdown
652
            float agilityTerm = getCreatureStats(ptr).getAttribute(ESM::Attribute::Agility).getModified() * gmst.fKnockDownMult->getFloat();
653
            float knockdownTerm = getCreatureStats(ptr).getAttribute(ESM::Attribute::Agility).getModified()
654
                    * gmst.iKnockDownOddsMult->getInt() * 0.01f + gmst.iKnockDownOddsBase->getInt();
scrawl's avatar
scrawl committed
655
            if (ishealth && agilityTerm <= damage && knockdownTerm <= Misc::Rng::roll0to99())
656 657 658 659 660 661
            {
                getCreatureStats(ptr).setKnockedDown(true);

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

663
            if(damage > 0 && ishealth)
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
                };
scrawl's avatar
scrawl committed
681
                int hitslot = hitslots[Misc::Rng::rollDice(20)];
682

683 684 685
                float unmitigatedDamage = damage;
                float x = damage / (damage + getArmorRating(ptr));
                damage *= std::max(gmst.fCombatArmorMinMult->getFloat(), x);
686
                int damageDiff = static_cast<int>(unmitigatedDamage - damage);
687 688
                if (damage < 1)
                    damage = 1;
689

690 691 692 693
                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())
694
                {
695
                    int armorhealth = armor.getClass().getItemHealth(armor);
696
                    armorhealth -= std::min(std::max(1, damageDiff),
697 698
                                                 armorhealth);
                    armor.getCellRef().setCharge(armorhealth);
699 700

                    // Armor broken? unequip it
701
                    if (armorhealth == 0)
702
                        armor = *inv.unequipItem(armor, ptr);
703

704
                    if (ptr == MWBase::Environment::get().getWorld()->getPlayerPtr())
705
                        skillUsageSucceeded(ptr, armor.getClass().getEquipmentSkill(armor), 0);
706

707
                    switch(armor.getClass().getEquipmentSkill(armor))
708 709 710 711 712 713 714 715 716 717 718
                    {
                        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;
                    }
719
                }
720
                else if(ptr == MWBase::Environment::get().getWorld()->getPlayerPtr())
721
                    skillUsageSucceeded(ptr, ESM::Skill::Unarmored, 0);
722
            }
Chris Robinson's avatar
Chris Robinson committed
723 724
        }

725 726
        if(ishealth)
        {
727 728 729
            if (!attacker.isEmpty())
                damage = scaleDamage(damage, attacker, ptr);

730
            if(damage > 0.0f)
731
            {
732
                sndMgr->playSound3D(ptr, "Health Damage", 1.0f, 1.0f);
733
                if (ptr == MWBase::Environment::get().getWorld()->getPlayerPtr())
734 735
                    MWBase::Environment::get().getWindowManager()->activateHitOverlay();
            }
736 737 738 739 740 741
            float health = getCreatureStats(ptr).getHealth().getCurrent() - damage;
            setActorHealth(ptr, health, attacker);
        }
        else
        {
            MWMechanics::DynamicStat<float> fatigue(getCreatureStats(ptr).getFatigue());
742
            fatigue.setCurrent(fatigue.getCurrent() - damage, true);
743 744
            getCreatureStats(ptr).setFatigue(fatigue);
        }