npc.cpp 45 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"
Marc Zinnschlag's avatar
Marc Zinnschlag committed
24

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

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

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

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

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

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

    MWWorld::CustomData *CustomData::clone() const
    {
        return new CustomData (*this);
    }
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

    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];
            creatureStats.getAttribute(i).setBase (male ? attribute.mMale : attribute.mFemale);
        }

        // 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)
            {
                creatureStats.getAttribute(attribute).setBase (
                    creatureStats.getAttribute(attribute).getBase() + 10);
            }
        }

        // skill bonus
        for (int attribute=0; attribute<ESM::Attribute::Length; ++attribute)
        {
            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;
            }
            creatureStats.getAttribute(attribute).setBase ( std::min(creatureStats.getAttribute(attribute).getBase()
                + 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
namespace MWClass
137
{
138 139
    void Npc::ensureCustomData (const MWWorld::Ptr& ptr) const
    {
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
        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");
156 157 158 159 160
            fJumpEncumbranceBase = gmst.find("fJumpEncumbranceBase");
            fJumpEncumbranceMultiplier = gmst.find("fJumpEncumbranceMultiplier");
            fJumpAcrobaticsBase = gmst.find("fJumpAcrobaticsBase");
            fJumpAcroMultiplier = gmst.find("fJumpAcroMultiplier");
            fJumpRunMultiplier = gmst.find("fJumpRunMultiplier");
161
            fWereWolfRunMult = gmst.find("fWereWolfRunMult");
162 163 164

            inited = true;
        }
165 166
        if (!ptr.getRefData().getCustomData())
        {
167
            std::auto_ptr<CustomData> data(new CustomData);
168

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

171
            // NPC stats
greye's avatar
greye committed
172
            if (!ref->mBase->mFaction.empty())
173
            {
greye's avatar
greye committed
174
                std::string faction = ref->mBase->mFaction;
eduard's avatar
eduard committed
175
                Misc::StringUtils::toLower(faction);
greye's avatar
greye committed
176
                if(ref->mBase->mNpdt52.mGold != -10)
177
                {
greye's avatar
greye committed
178
                    data->mNpcStats.getFactionRanks()[faction] = (int)ref->mBase->mNpdt52.mRank;
179 180 181
                }
                else
                {
greye's avatar
greye committed
182
                    data->mNpcStats.getFactionRanks()[faction] = (int)ref->mBase->mNpdt12.mRank;
183
                }
184 185
            }

186
            // creature stats
187
            int gold=0;
greye's avatar
greye committed
188
            if(ref->mBase->mNpdt52.mGold != -10)
189
            {
190 191
                gold = ref->mBase->mNpdt52.mGold;

192
                for (int i=0; i<27; ++i)
greye's avatar
greye committed
193 194
                    data->mNpcStats.getSkill (i).setBase (ref->mBase->mNpdt52.mSkills[i]);

195 196 197 198 199 200 201 202 203 204 205 206 207
                data->mNpcStats.getAttribute(0).set (ref->mBase->mNpdt52.mStrength);
                data->mNpcStats.getAttribute(1).set (ref->mBase->mNpdt52.mIntelligence);
                data->mNpcStats.getAttribute(2).set (ref->mBase->mNpdt52.mWillpower);
                data->mNpcStats.getAttribute(3).set (ref->mBase->mNpdt52.mAgility);
                data->mNpcStats.getAttribute(4).set (ref->mBase->mNpdt52.mSpeed);
                data->mNpcStats.getAttribute(5).set (ref->mBase->mNpdt52.mEndurance);
                data->mNpcStats.getAttribute(6).set (ref->mBase->mNpdt52.mPersonality);
                data->mNpcStats.getAttribute(7).set (ref->mBase->mNpdt52.mLuck);
                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
208
                data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt52.mDisposition);
209
                data->mNpcStats.setReputation(ref->mBase->mNpdt52.mReputation);
210 211 212
            }
            else
            {
213 214
                gold = ref->mBase->mNpdt12.mGold;

215
                for (int i=0; i<3; ++i)
216
                    data->mNpcStats.setDynamic (i, 10);
217

218
                data->mNpcStats.setLevel(ref->mBase->mNpdt12.mLevel);
219 220
                data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt12.mDisposition);
                data->mNpcStats.setReputation(ref->mBase->mNpdt12.mReputation);
221

222
                autoCalculateAttributes(ref->mBase, data->mNpcStats);
223
            }
224

225
            data->mNpcStats.getAiSequence().fill(ref->mBase->mAiPackage);
226

227 228 229 230
            data->mNpcStats.setAiSetting (0, ref->mBase->mAiData.mHello);
            data->mNpcStats.setAiSetting (1, ref->mBase->mAiData.mFight);
            data->mNpcStats.setAiSetting (2, ref->mBase->mAiData.mFlee);
            data->mNpcStats.setAiSetting (3, ref->mBase->mAiData.mAlarm);
231

232
            // spells
greye's avatar
greye committed
233 234
            for (std::vector<std::string>::const_iterator iter (ref->mBase->mSpells.mList.begin());
                iter!=ref->mBase->mSpells.mList.end(); ++iter)
235
                data->mNpcStats.getSpells().add (*iter);
236

237 238 239 240
            // inventory
            data->mInventoryStore.fill(ref->mBase->mInventory, getId(ptr),
                                       MWBase::Environment::get().getWorld()->getStore());

241
            // store
242
            ptr.getRefData().setCustomData (data.release());
243

244 245
            getContainerStore(ptr).add("gold_001", gold, ptr);

246
            getInventoryStore(ptr).autoEquip(ptr);
247 248 249
        }
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
250 251
    std::string Npc::getId (const MWWorld::Ptr& ptr) const
    {
252
        MWWorld::LiveCellRef<ESM::NPC> *ref =
Marc Zinnschlag's avatar
Marc Zinnschlag committed
253 254
            ptr.get<ESM::NPC>();

greye's avatar
greye committed
255
        return ref->mBase->mId;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
256 257
    }

258 259 260 261 262
    void Npc::adjustPosition(const MWWorld::Ptr& ptr) const
    {
        MWBase::Environment::get().getWorld()->adjustPosition(ptr);
    }

Jason Hooks's avatar
Jason Hooks committed
263
    void Npc::insertObjectRendering (const MWWorld::Ptr& ptr, MWRender::RenderingInterface& renderingInterface) const
264
    {
265
        renderingInterface.getActors().insertNPC(ptr);
Jason Hooks's avatar
Jason Hooks committed
266
    }
Jason Hooks's avatar
Jason Hooks committed
267

268
    void Npc::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const
Jason Hooks's avatar
Jason Hooks committed
269
    {
270
        physics.addActor(ptr);
271
        MWBase::Environment::get().getMechanicsManager()->add(ptr);
greye's avatar
greye committed
272
    }
Jason Hooks's avatar
Jason Hooks committed
273

scrawl's avatar
scrawl committed
274 275 276 277 278 279
    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
280 281
    std::string Npc::getModel(const MWWorld::Ptr &ptr) const
    {
282
        MWWorld::LiveCellRef<ESM::NPC> *ref =
Jason Hooks's avatar
Jason Hooks committed
283
            ptr.get<ESM::NPC>();
greye's avatar
greye committed
284
        assert(ref->mBase != NULL);
285

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

scrawl's avatar
scrawl committed
288 289
        //int end = headID.find_last_of("head_") - 4;
        //std::string bodyRaceID = headID.substr(0, end);
greye's avatar
greye committed
290 291

        std::string model = "meshes\\base_anim.nif";
292 293
        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
294
            model = "meshes\\base_animkna.nif";
295

greye's avatar
greye committed
296
        return model;
297 298 299

    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
300 301
    std::string Npc::getName (const MWWorld::Ptr& ptr) const
    {
302 303 304 305 306 307 308
        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
309

310
        MWWorld::LiveCellRef<ESM::NPC> *ref = ptr.get<ESM::NPC>();
greye's avatar
greye committed
311
        return ref->mBase->mName;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
312 313
    }

314
    MWMechanics::CreatureStats& Npc::getCreatureStats (const MWWorld::Ptr& ptr) const
315
    {
316
        ensureCustomData (ptr);
317

318
        return dynamic_cast<CustomData&> (*ptr.getRefData().getCustomData()).mNpcStats;
319 320
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
321 322
    MWMechanics::NpcStats& Npc::getNpcStats (const MWWorld::Ptr& ptr) const
    {
323
        ensureCustomData (ptr);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
324

325
        return dynamic_cast<CustomData&> (*ptr.getRefData().getCustomData()).mNpcStats;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
326 327
    }

Chris Robinson's avatar
Chris Robinson committed
328

329
    void Npc::hit(const MWWorld::Ptr& ptr, int type) const
Chris Robinson's avatar
Chris Robinson committed
330
    {
331 332 333
        MWBase::World *world = MWBase::Environment::get().getWorld();
        const MWWorld::Store<ESM::GameSetting> &gmst = world->getStore().get<ESM::GameSetting>();

334 335
        // Get the weapon used (if hand-to-hand, weapon = inv.end())
        MWWorld::InventoryStore &inv = getInventoryStore(ptr);
336 337 338 339
        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();
340

341 342
        float dist = 100.0f * (!weapon.isEmpty() ?
                               weapon.get<ESM::Weapon>()->mBase->mData.mReach :
343
                               gmst.find("fHandToHandReach")->getFloat());
344 345
        // 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
346 347 348 349
        if(victim.isEmpty()) // Didn't hit anything
            return;

        const MWWorld::Class &othercls = MWWorld::Class::get(victim);
350 351
        if(!othercls.isActor()) // Can't hit non-actors
            return;
352
        MWMechanics::CreatureStats &otherstats = victim.getClass().getCreatureStats(victim);
353
        if(otherstats.isDead()) // Can't hit dead actors
Chris Robinson's avatar
Chris Robinson committed
354 355
            return;

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

359
        int weapskill = ESM::Skill::HandToHand;
360
        if(!weapon.isEmpty())
361
            weapskill = get(weapon).getEquipmentSkill(weapon);
362

363 364 365 366 367 368
        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();
369 370
        hitchance += mageffects.get(MWMechanics::EffectKey(ESM::MagicEffect::FortifyAttack)).mMagnitude -
                     mageffects.get(MWMechanics::EffectKey(ESM::MagicEffect::Blind)).mMagnitude;
371
        hitchance -= otherstats.getEvasion();
372

Chris Robinson's avatar
Chris Robinson committed
373
        if((::rand()/(RAND_MAX+1.0)) > hitchance/100.0f)
374
        {
375
            othercls.onHit(victim, 0.0f, false, weapon, ptr, false);
376 377
            return;
        }
Chris Robinson's avatar
Chris Robinson committed
378

379
        bool healthdmg;
380 381
        float damage = 0.0f;
        if(!weapon.isEmpty())
Chris Robinson's avatar
Chris Robinson committed
382
        {
383
            const bool weaphashealth = get(weapon).hasItemHealth(weapon);
384
            const unsigned char *attack = NULL;
Chris Robinson's avatar
Chris Robinson committed
385
            if(type == MWMechanics::CreatureStats::AT_Chop)
386
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mChop;
Chris Robinson's avatar
Chris Robinson committed
387
            else if(type == MWMechanics::CreatureStats::AT_Slash)
388
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mSlash;
Chris Robinson's avatar
Chris Robinson committed
389
            else if(type == MWMechanics::CreatureStats::AT_Thrust)
390
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mThrust;
391
            if(attack)
392
            {
393 394
                damage  = attack[0] + ((attack[1]-attack[0])*stats.getAttackStrength());
                damage *= 0.5f + (stats.getAttribute(ESM::Attribute::Luck).getModified() / 100.0f);
395 396 397 398 399 400 401
                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;
                }
402 403 404 405
                if(!othercls.hasDetected(victim, ptr))
                {
                    damage *= gmst.find("fCombatCriticalStrikeMult")->getFloat();
                    MWBase::Environment::get().getWindowManager()->messageBox("#{sTargetCriticalStrike}");
406
                    MWBase::Environment::get().getSoundManager()->playSound3D(victim, "critical damage", 1.0f, 1.0f);
407
                }
408 409 410 411
                
                if (!MWBase::Environment::get().getWorld()->getGodModeState())
                    weapon.getCellRef().mCharge -= std::min(std::max(1,
                        (int)(damage * gmst.find("fWeaponDamageMult")->getFloat())), weapon.getCellRef().mCharge);
412
            }
413 414 415 416 417 418 419 420 421
            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();
422 423
            damage  = stats.getSkill(weapskill).getModified();
            damage *= minstrike + ((maxstrike-minstrike)*stats.getAttackStrength());
424 425 426 427 428 429 430
            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);
            }

431
            healthdmg = (otherstats.getFatigue().getCurrent() < 1.0f);
432
            if(stats.isWerewolf())
433 434 435 436 437 438
            {
                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();
            }
439
            if(healthdmg)
440
                damage *= gmst.find("fHandtoHandHealthPer")->getFloat();
441 442 443 444

            MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();
            if(stats.isWerewolf())
            {
445 446 447
                const ESM::Sound *sound = world->getStore().get<ESM::Sound>().searchRandom("WolfHit");
                if(sound)
                    sndMgr->playSound3D(victim, sound->mId, 1.0f, 1.0f);
448 449 450
            }
            else
                sndMgr->playSound3D(victim, "Hand To Hand Hit", 1.0f, 1.0f);
Chris Robinson's avatar
Chris Robinson committed
451
        }
452 453
        if(ptr.getRefData().getHandle() == "player")
            skillUsageSucceeded(ptr, weapskill, 0);
454

455
        // Apply "On hit" enchanted weapons
456
        std::string enchantmentName = !weapon.isEmpty() ? weapon.getClass().getEnchantment(weapon) : "";
457 458 459 460 461 462 463 464 465
        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();
466
                const int castCost = std::max(1.f, enchantCost - (enchantCost / 100) * (eSkill - 10));
467 468 469 470 471 472 473 474 475 476 477

                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;
478 479 480

                    MWMechanics::CastSpell cast(ptr, victim);
                    cast.cast(weapon);
481 482 483

                    if (ptr.getRefData().getHandle() == "player")
                        skillUsageSucceeded (ptr, ESM::Skill::Enchant, 3);
484 485 486 487
                }
            }
        }

488
        othercls.onHit(victim, damage, healthdmg, weapon, ptr, true);
Chris Robinson's avatar
Chris Robinson committed
489 490
    }

491
    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
492
    {
493 494
        MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();

495 496 497 498 499 500 501
        // NOTE: 'object' and/or 'attacker' may be empty.

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

            // Missed
502
            sndMgr->playSound3D(ptr, "miss", 1.0f, 1.0f);
503 504
            return;
        }
Chris Robinson's avatar
Chris Robinson committed
505

506
        if(!object.isEmpty())
507
            getCreatureStats(ptr).setLastHitObject(get(object).getId(object));
508 509 510 511 512 513 514 515

        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);
        }
516 517

        if(damage > 0.0f)
Chris Robinson's avatar
Chris Robinson committed
518 519 520
        {
            // 'ptr' is losing health. Play a 'hit' voiced dialog entry if not already saying
            // something, alert the character controller, scripts, etc.
521 522

            MWBase::Environment::get().getDialogueManager()->say(ptr, "hit");
523

524
            if(object.isEmpty())
525 526
            {
                if(ishealth)
527
                    damage /= std::min(1.0f + getArmorRating(ptr)/std::max(1.0f, damage), 4.0f);
528 529
            }
            else if(ishealth)
530
            {
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
                // 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)];

549 550 551 552
                float damagediff = damage;
                damage /= std::min(1.0f + getArmorRating(ptr)/std::max(1.0f, damage), 4.0f);
                damagediff -= damage;

553 554 555 556
                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())
557
                {
558 559 560 561 562
                    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);
563 564 565 566 567 568 569 570 571 572 573 574
                    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;
                    }
575 576
                }
            }
Chris Robinson's avatar
Chris Robinson committed
577 578
        }

579 580 581 582 583 584 585 586 587 588 589 590 591
        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());
            fatigue.setCurrent(fatigue.getCurrent() - damage);
            getCreatureStats(ptr).setFatigue(fatigue);
        }
592 593 594 595 596
    }

    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
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
        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
        }
    }


614
    boost::shared_ptr<MWWorld::Action> Npc::activate (const MWWorld::Ptr& ptr,
615
        const MWWorld::Ptr& actor) const
616
    {
617 618
        if(get(actor).isNpc() && get(actor).getNpcStats(actor).isWerewolf())
        {
619 620 621
            const MWWorld::ESMStore &store = MWBase::Environment::get().getWorld()->getStore();
            const ESM::Sound *sound = store.get<ESM::Sound>().searchRandom("WolfNPC");

622
            boost::shared_ptr<MWWorld::Action> action(new MWWorld::FailedAction("#{sWerewolfRefusal}"));
623 624
            if(sound) action->setSound(sound->mId);

625 626 627 628 629 630 631
            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
        return boost::shared_ptr<MWWorld::Action>(new MWWorld::ActionTalk(ptr));
632
    }
Marc Zinnschlag's avatar
Marc Zinnschlag committed
633

634
    MWWorld::ContainerStore& Npc::getContainerStore (const MWWorld::Ptr& ptr)
635
        const
Marc Zinnschlag's avatar
Marc Zinnschlag committed
636
    {
637
        ensureCustomData (ptr);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
638

639 640 641 642 643 644 645 646 647
        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
648 649
    }

650 651
    std::string Npc::getScript (const MWWorld::Ptr& ptr) const
    {
652
        MWWorld::LiveCellRef<ESM::NPC> *ref =
653 654
            ptr.get<ESM::NPC>();

greye's avatar
greye committed
655
        return ref->mBase->mScript;
656 657
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
658 659 660 661 662 663 664 665
    void Npc::setForceStance (const MWWorld::Ptr& ptr, Stance stance, bool force) const
    {
        MWMechanics::NpcStats& stats = getNpcStats (ptr);

        switch (stance)
        {
            case Run:

666
                stats.setMovementFlag (MWMechanics::NpcStats::Flag_ForceRun, force);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
667 668 669 670
                break;

            case Sneak:

671
                stats.setMovementFlag (MWMechanics::NpcStats::Flag_ForceSneak, force);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
                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:

688
                stats.setMovementFlag (MWMechanics::NpcStats::Flag_Run, set);
689
                break;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
690 691 692

            case Sneak:

693
                stats.setMovementFlag (MWMechanics::NpcStats::Flag_Sneak, set);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
694 695 696 697
                break;

            case Combat:

698 699
                // 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
700 701 702 703 704 705 706 707 708 709 710 711
                break;
        }
    }

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

        switch (stance)
        {
            case Run:

712
                if (!ignoreForce && stats.getMovementFlag (MWMechanics::NpcStats::Flag_ForceRun))
713 714
                    return true;

715
                return stats.getMovementFlag (MWMechanics::NpcStats::Flag_Run);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
716 717 718

            case Sneak:

719
                if (!ignoreForce && stats.getMovementFlag (MWMechanics::NpcStats::Flag_ForceSneak))
Marc Zinnschlag's avatar
Marc Zinnschlag committed
720 721
                    return true;

722
                return stats.getMovementFlag (MWMechanics::NpcStats::Flag_Sneak);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
723 724 725

            case Combat:

726
                return false;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
727 728 729 730 731
        }

        return false;
    }

732
    float Npc::getSpeed(const MWWorld::Ptr& ptr) const
Marc Zinnschlag's avatar
Marc Zinnschlag committed
733
    {
734 735
        const MWBase::World *world = MWBase::Environment::get().getWorld();
        const CustomData *npcdata = static_cast<const CustomData*>(ptr.getRefData().getCustomData());
736
        const MWMechanics::MagicEffects &mageffects = npcdata->mNpcStats.getMagicEffects();
737

738 739
        const float normalizedEncumbrance = Npc::getEncumbrance(ptr) / Npc::getCapacity(ptr);

740
        float walkSpeed = fMinWalkSpeed->getFloat() + 0.01f*npcdata->mNpcStats.getAttribute(ESM::Attribute::Speed).getModified()*
741 742 743 744 745
                                                      (fMaxWalkSpeed->getFloat() - fMinWalkSpeed->getFloat());
        walkSpeed *= 1.0f - fEncumberedMoveEffect->getFloat()*normalizedEncumbrance;
        walkSpeed = std::max(0.0f, walkSpeed);
        if(Npc::getStance(ptr, Sneak, false))
            walkSpeed *= fSneakSpeedMultiplier->getFloat();
746

747 748
        float runSpeed = walkSpeed*(0.01f * npcdata->mNpcStats.getSkill(ESM::Skill::Athletics).getModified() *
                                    fAthleticsRunBonus->getFloat() + fBaseRunMultiplier->getFloat());
749 750
        if(npcdata->mNpcStats.isWerewolf())
            runSpeed *= fWereWolfRunMult->getFloat();
751 752

        float moveSpeed;
753
        if(normalizedEncumbrance >= 1.0f)
754
            moveSpeed = 0.0f;
755
        else if(mageffects.get(MWMechanics::EffectKey(10/*levitate*/)).mMagnitude > 0)
756
        {
757
            float flySpeed = 0.01f*(npcdata->mNpcStats.getAttribute(ESM::Attribute::Speed).getModified() +
758
                                    mageffects.get(MWMechanics::EffectKey(10/*levitate*/)).mMagnitude);
759 760 761 762 763 764 765 766 767 768
            flySpeed = fMinFlySpeed->getFloat() + flySpeed*(fMaxFlySpeed->getFloat() - fMinFlySpeed->getFloat());
            flySpeed *= 1.0f - fEncumberedMoveEffect->getFloat() * normalizedEncumbrance;
            flySpeed = std::max(0.0f, flySpeed);
            moveSpeed = flySpeed;
        }
        else if(world->isSwimming(ptr))
        {
            float swimSpeed = walkSpeed;
            if(Npc::getStance(ptr, Run, false))
                swimSpeed = runSpeed;
769
            swimSpeed *= 1.0f + 0.01f * mageffects.get(MWMechanics::EffectKey(1/*swift swim*/)).mMagnitude;
770 771 772 773
            swimSpeed *= fSwimRunBase->getFloat() + 0.01f*npcdata->mNpcStats.getSkill(ESM::Skill::Athletics).getModified()*
                                                    fSwimRunAthleticsMult->getFloat();
            moveSpeed = swimSpeed;
        }
scrawl's avatar
scrawl committed
774
        else if(Npc::getStance(ptr, Run, false) && !Npc::getStance(ptr, Sneak, false))
775 776 777
            moveSpeed = runSpeed;
        else
            moveSpeed = walkSpeed;
778
        if(getMovementSettings(ptr).mPosition[0] != 0 && getMovementSettings(ptr).mPosition[1] == 0)
779 780 781
            moveSpeed *= 0.75f;

        return moveSpeed;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
782 783
    }

784 785 786
    float Npc::getJump(const MWWorld::Ptr &ptr) const
    {
        const CustomData *npcdata = static_cast<const CustomData*>(ptr.getRefData().getCustomData());
787
        const MWMechanics::MagicEffects &mageffects = npcdata->mNpcStats.getMagicEffects();
788 789
        const float encumbranceTerm = fJumpEncumbranceBase->getFloat() +
                                          fJumpEncumbranceMultiplier->getFloat() *
790
                                          (1.0f - Npc::getEncumbrance(ptr)/Npc::getCapacity(ptr));
791 792 793 794 795 796 797 798 799 800 801

        float a = npcdata->mNpcStats.getSkill(ESM::Skill::Acrobatics).getModified();
        float b = 0.0f;
        if(a > 50.0f)
        {
            b = a - 50.0f;
            a = 50.0f;
        }

        float x = fJumpAcrobaticsBase->getFloat() +
                  std::pow(a / 15.0f, fJumpAcroMultiplier->getFloat());
802 803
        x += 3.0f * b * fJumpAcroMultiplier->getFloat();
        x += mageffects.get(MWMechanics::EffectKey(ESM::MagicEffect::Jump)).mMagnitude * 64;
804 805 806 807
        x *= encumbranceTerm;

        if(Npc::getStance(ptr, Run, false))
            x *= fJumpRunMultiplier->getFloat();
808
        x *= npcdata->mNpcStats.getFatigueTerm();
809 810
        x -= -627.2f;/*gravity constant*/
        x /= 3.0f;
811 812 813 814

        return x;
    }

815 816
    float Npc::getFallDamage(const MWWorld::Ptr &ptr, float fallHeight) const
    {
Emanuel Guevel's avatar
Emanuel Guevel committed
817 818 819 820
        MWBase::World *world = MWBase::Environment::get().getWorld();
        const MWWorld::Store<ESM::GameSetting> &gmst = world->getStore().get<ESM::GameSetting>();

        const float fallDistanceMin = gmst.find("fFallDamageDistanceMin")->getFloat();
821

Emanuel Guevel's avatar
Emanuel Guevel committed
822
        if (fallHeight >= fallDistanceMin)
823 824 825
        {
            const float acrobaticsSkill = MWWorld::Class::get(ptr).getNpcStats (ptr).getSkill(ESM::Skill::Acrobatics).getModified();
            const CustomData *npcdata = static_cast<const CustomData*>(ptr.getRefData().getCustomData());
Emanuel Guevel's avatar
Emanuel Guevel committed
826 827 828 829 830
            const float jumpSpellBonus = npcdata->mNpcStats.getMagicEffects().get(MWMechanics::EffectKey(ESM::MagicEffect::Jump)).mMagnitude;
            const float fallAcroBase = gmst.find("fFallAcroBase")->getFloat();
            const float fallAcroMult = gmst.find("fFallAcroMult")->getFloat();
            const float fallDistanceBase = gmst.find("fFallDistanceBase")->getFloat();
            const float fallDistanceMult = gmst.find("fFallDistanceMult")->getFloat();
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845

            float x = fallHeight - fallDistanceMin;
            x -= (1.5 * acrobaticsSkill) + jumpSpellBonus;
            x = std::max(0.0f, x);

            float a = fallAcroBase + fallAcroMult * (100 - acrobaticsSkill);
            x = fallDistanceBase + fallDistanceMult * x;
            x *= a;

            return x;
        }

        return 0;
    }

846 847
    MWMechanics::Movement& Npc::getMovementSettings (const MWWorld::Ptr& ptr) const
    {
848
        ensureCustomData (ptr);
849

850
        return dynamic_cast<CustomData&> (*ptr.getRefData().getCustomData()).mMovement;
851 852 853 854
    }

    Ogre::Vector3 Npc::getMovementVector (const MWWorld::Ptr& ptr) const
    {
855 856 857 858 859 860
        MWMechanics::Movement &movement = getMovementSettings(ptr);
        Ogre::Vector3 vec(movement.mPosition);