npc.cpp 43.5 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>

10 11
#include <components/esm/loadnpc.hpp>

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"
Marc Zinnschlag's avatar
Marc Zinnschlag committed
22

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

31
#include "../mwrender/actors.hpp"
32
#include "../mwrender/renderinginterface.hpp"
33

34
#include "../mwgui/tooltips.hpp"
35

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

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

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

    MWWorld::CustomData *CustomData::clone() const
    {
        return new CustomData (*this);
    }
54 55 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

    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) );
        }
114

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

        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));
131
    }
132 133
}

134
namespace MWClass
135
{
136 137
    void Npc::ensureCustomData (const MWWorld::Ptr& ptr) const
    {
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
        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");
154 155 156 157 158
            fJumpEncumbranceBase = gmst.find("fJumpEncumbranceBase");
            fJumpEncumbranceMultiplier = gmst.find("fJumpEncumbranceMultiplier");
            fJumpAcrobaticsBase = gmst.find("fJumpAcrobaticsBase");
            fJumpAcroMultiplier = gmst.find("fJumpAcroMultiplier");
            fJumpRunMultiplier = gmst.find("fJumpRunMultiplier");
159
            fWereWolfRunMult = gmst.find("fWereWolfRunMult");
160 161 162

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

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

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

184
            // creature stats
greye's avatar
greye committed
185
            if(ref->mBase->mNpdt52.mGold != -10)
186 187
            {
                for (int i=0; i<27; ++i)
greye's avatar
greye committed
188 189
                    data->mNpcStats.getSkill (i).setBase (ref->mBase->mNpdt52.mSkills[i]);

190 191 192 193 194 195 196 197 198 199 200 201 202
                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
203
                data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt52.mDisposition);
204
                data->mNpcStats.setReputation(ref->mBase->mNpdt52.mReputation);
205 206 207
            }
            else
            {
208
                for (int i=0; i<3; ++i)
209
                    data->mNpcStats.setDynamic (i, 10);
210

211
                data->mNpcStats.setLevel(ref->mBase->mNpdt12.mLevel);
212 213
                data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt12.mDisposition);
                data->mNpcStats.setReputation(ref->mBase->mNpdt12.mReputation);
214

215
                autoCalculateAttributes(ref->mBase, data->mNpcStats);
216
            }
217

218
            data->mNpcStats.getAiSequence().fill(ref->mBase->mAiPackage);
219

220 221 222 223
            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);
224

225
            // spells
greye's avatar
greye committed
226 227
            for (std::vector<std::string>::const_iterator iter (ref->mBase->mSpells.mList.begin());
                iter!=ref->mBase->mSpells.mList.end(); ++iter)
228
                data->mNpcStats.getSpells().add (*iter);
229

230 231 232 233
            // inventory
            data->mInventoryStore.fill(ref->mBase->mInventory, getId(ptr),
                                       MWBase::Environment::get().getWorld()->getStore());

234
            // store
235
            ptr.getRefData().setCustomData (data.release());
236 237

            getInventoryStore(ptr).autoEquip(ptr);
238 239 240
        }
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
241 242
    std::string Npc::getId (const MWWorld::Ptr& ptr) const
    {
243
        MWWorld::LiveCellRef<ESM::NPC> *ref =
Marc Zinnschlag's avatar
Marc Zinnschlag committed
244 245
            ptr.get<ESM::NPC>();

greye's avatar
greye committed
246
        return ref->mBase->mId;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
247 248
    }

249 250 251 252 253
    void Npc::adjustPosition(const MWWorld::Ptr& ptr) const
    {
        MWBase::Environment::get().getWorld()->adjustPosition(ptr);
    }

Jason Hooks's avatar
Jason Hooks committed
254
    void Npc::insertObjectRendering (const MWWorld::Ptr& ptr, MWRender::RenderingInterface& renderingInterface) const
255
    {
Jason Hooks's avatar
Jason Hooks committed
256
        renderingInterface.getActors().insertNPC(ptr, getInventoryStore(ptr));
Jason Hooks's avatar
Jason Hooks committed
257
    }
Jason Hooks's avatar
Jason Hooks committed
258

259
    void Npc::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const
Jason Hooks's avatar
Jason Hooks committed
260
    {
261
        physics.addActor(ptr);
262
        MWBase::Environment::get().getMechanicsManager()->add(ptr);
greye's avatar
greye committed
263
    }
Jason Hooks's avatar
Jason Hooks committed
264

scrawl's avatar
scrawl committed
265 266 267 268 269 270
    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
271 272
    std::string Npc::getModel(const MWWorld::Ptr &ptr) const
    {
273
        MWWorld::LiveCellRef<ESM::NPC> *ref =
Jason Hooks's avatar
Jason Hooks committed
274
            ptr.get<ESM::NPC>();
greye's avatar
greye committed
275
        assert(ref->mBase != NULL);
276

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

scrawl's avatar
scrawl committed
279 280
        //int end = headID.find_last_of("head_") - 4;
        //std::string bodyRaceID = headID.substr(0, end);
greye's avatar
greye committed
281 282

        std::string model = "meshes\\base_anim.nif";
283 284
        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
285
            model = "meshes\\base_animkna.nif";
286

greye's avatar
greye committed
287
        return model;
288 289 290

    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
291 292
    std::string Npc::getName (const MWWorld::Ptr& ptr) const
    {
293 294 295 296 297 298 299
        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
300

301
        MWWorld::LiveCellRef<ESM::NPC> *ref = ptr.get<ESM::NPC>();
greye's avatar
greye committed
302
        return ref->mBase->mName;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
303 304
    }

305
    MWMechanics::CreatureStats& Npc::getCreatureStats (const MWWorld::Ptr& ptr) const
306
    {
307
        ensureCustomData (ptr);
308

309
        return dynamic_cast<CustomData&> (*ptr.getRefData().getCustomData()).mNpcStats;
310 311
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
312 313
    MWMechanics::NpcStats& Npc::getNpcStats (const MWWorld::Ptr& ptr) const
    {
314
        ensureCustomData (ptr);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
315

316
        return dynamic_cast<CustomData&> (*ptr.getRefData().getCustomData()).mNpcStats;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
317 318
    }

Chris Robinson's avatar
Chris Robinson committed
319

320
    void Npc::hit(const MWWorld::Ptr& ptr, int type) const
Chris Robinson's avatar
Chris Robinson committed
321
    {
322 323 324
        MWBase::World *world = MWBase::Environment::get().getWorld();
        const MWWorld::Store<ESM::GameSetting> &gmst = world->getStore().get<ESM::GameSetting>();

325 326
        // Get the weapon used (if hand-to-hand, weapon = inv.end())
        MWWorld::InventoryStore &inv = getInventoryStore(ptr);
327 328 329 330
        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();
331

332 333
        float dist = 100.0f * (!weapon.isEmpty() ?
                               weapon.get<ESM::Weapon>()->mBase->mData.mReach :
334
                               gmst.find("fHandToHandReach")->getFloat());
335 336
        // 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
337 338 339 340
        if(victim.isEmpty()) // Didn't hit anything
            return;

        const MWWorld::Class &othercls = MWWorld::Class::get(victim);
341 342
        if(!othercls.isActor()) // Can't hit non-actors
            return;
343
        MWMechanics::CreatureStats &otherstats = victim.getClass().getCreatureStats(victim);
344
        if(otherstats.isDead()) // Can't hit dead actors
Chris Robinson's avatar
Chris Robinson committed
345 346
            return;

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

350
        int weapskill = ESM::Skill::HandToHand;
351
        if(!weapon.isEmpty())
352
            weapskill = get(weapon).getEquipmentSkill(weapon);
353

354 355 356 357 358 359
        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();
360 361
        hitchance += mageffects.get(MWMechanics::EffectKey(ESM::MagicEffect::FortifyAttack)).mMagnitude -
                     mageffects.get(MWMechanics::EffectKey(ESM::MagicEffect::Blind)).mMagnitude;
362
        hitchance -= otherstats.getEvasion();
363

Chris Robinson's avatar
Chris Robinson committed
364
        if((::rand()/(RAND_MAX+1.0)) > hitchance/100.0f)
365
        {
366
            othercls.onHit(victim, 0.0f, false, weapon, ptr, false);
367 368
            return;
        }
Chris Robinson's avatar
Chris Robinson committed
369

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

421
            healthdmg = (otherstats.getFatigue().getCurrent() < 1.0f);
422
            if(stats.isWerewolf())
423 424 425 426 427 428
            {
                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();
            }
429
            if(healthdmg)
430
                damage *= gmst.find("fHandtoHandHealthPer")->getFloat();
431 432 433 434

            MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();
            if(stats.isWerewolf())
            {
435 436 437
                const ESM::Sound *sound = world->getStore().get<ESM::Sound>().searchRandom("WolfHit");
                if(sound)
                    sndMgr->playSound3D(victim, sound->mId, 1.0f, 1.0f);
438 439 440
            }
            else
                sndMgr->playSound3D(victim, "Hand To Hand Hit", 1.0f, 1.0f);
Chris Robinson's avatar
Chris Robinson committed
441
        }
442 443
        if(ptr.getRefData().getHandle() == "player")
            skillUsageSucceeded(ptr, weapskill, 0);
444

445
        othercls.onHit(victim, damage, healthdmg, weapon, ptr, true);
Chris Robinson's avatar
Chris Robinson committed
446 447
    }

448
    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
449
    {
450 451
        MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();

452 453 454 455 456 457 458
        // NOTE: 'object' and/or 'attacker' may be empty.

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

            // Missed
459
            sndMgr->playSound3D(ptr, "miss", 1.0f, 1.0f);
460 461
            return;
        }
Chris Robinson's avatar
Chris Robinson committed
462

463
        if(!object.isEmpty())
464
            getCreatureStats(ptr).setLastHitObject(get(object).getId(object));
465 466 467 468 469 470 471 472

        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);
        }
473 474

        if(damage > 0.0f)
Chris Robinson's avatar
Chris Robinson committed
475 476 477
        {
            // 'ptr' is losing health. Play a 'hit' voiced dialog entry if not already saying
            // something, alert the character controller, scripts, etc.
478 479

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

481
            if(object.isEmpty())
482 483
            {
                if(ishealth)
484
                    damage /= std::min(1.0f + getArmorRating(ptr)/std::max(1.0f, damage), 4.0f);
485 486
            }
            else if(ishealth)
487
            {
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
                // 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)];

506 507 508 509
                float damagediff = damage;
                damage /= std::min(1.0f + getArmorRating(ptr)/std::max(1.0f, damage), 4.0f);
                damagediff -= damage;

510 511 512 513
                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())
514
                {
515 516 517 518 519
                    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);
520 521 522 523 524 525 526 527 528 529 530 531
                    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;
                    }
532 533
                }
            }
Chris Robinson's avatar
Chris Robinson committed
534 535
        }

536 537 538 539 540 541 542 543 544 545 546 547 548
        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);
        }
549 550 551 552 553
    }

    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
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
        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
        }
    }


571
    boost::shared_ptr<MWWorld::Action> Npc::activate (const MWWorld::Ptr& ptr,
572
        const MWWorld::Ptr& actor) const
573
    {
574 575
        if(get(actor).isNpc() && get(actor).getNpcStats(actor).isWerewolf())
        {
576 577 578
            const MWWorld::ESMStore &store = MWBase::Environment::get().getWorld()->getStore();
            const ESM::Sound *sound = store.get<ESM::Sound>().searchRandom("WolfNPC");

579
            boost::shared_ptr<MWWorld::Action> action(new MWWorld::FailedAction("#{sWerewolfRefusal}"));
580 581
            if(sound) action->setSound(sound->mId);

582 583 584 585 586 587 588
            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));
589
    }
Marc Zinnschlag's avatar
Marc Zinnschlag committed
590

591
    MWWorld::ContainerStore& Npc::getContainerStore (const MWWorld::Ptr& ptr)
592
        const
Marc Zinnschlag's avatar
Marc Zinnschlag committed
593
    {
594
        ensureCustomData (ptr);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
595

596 597 598 599 600 601 602 603 604
        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
605 606
    }

607 608
    std::string Npc::getScript (const MWWorld::Ptr& ptr) const
    {
609
        MWWorld::LiveCellRef<ESM::NPC> *ref =
610 611
            ptr.get<ESM::NPC>();

greye's avatar
greye committed
612
        return ref->mBase->mScript;
613 614
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
615 616 617 618 619 620 621 622
    void Npc::setForceStance (const MWWorld::Ptr& ptr, Stance stance, bool force) const
    {
        MWMechanics::NpcStats& stats = getNpcStats (ptr);

        switch (stance)
        {
            case Run:

623
                stats.setMovementFlag (MWMechanics::NpcStats::Flag_ForceRun, force);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
624 625 626 627
                break;

            case Sneak:

628
                stats.setMovementFlag (MWMechanics::NpcStats::Flag_ForceSneak, force);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
                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:

645
                stats.setMovementFlag (MWMechanics::NpcStats::Flag_Run, set);
646
                break;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
647 648 649

            case Sneak:

650
                stats.setMovementFlag (MWMechanics::NpcStats::Flag_Sneak, set);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
651 652 653 654
                break;

            case Combat:

655 656
                // 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
657 658 659 660 661 662 663 664 665 666 667 668
                break;
        }
    }

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

        switch (stance)
        {
            case Run:

669
                if (!ignoreForce && stats.getMovementFlag (MWMechanics::NpcStats::Flag_ForceRun))
670 671
                    return true;

672
                return stats.getMovementFlag (MWMechanics::NpcStats::Flag_Run);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
673 674 675

            case Sneak:

676
                if (!ignoreForce && stats.getMovementFlag (MWMechanics::NpcStats::Flag_ForceSneak))
Marc Zinnschlag's avatar
Marc Zinnschlag committed
677 678
                    return true;

679
                return stats.getMovementFlag (MWMechanics::NpcStats::Flag_Sneak);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
680 681 682

            case Combat:

683
                return false;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
684 685 686 687 688
        }

        return false;
    }

689
    float Npc::getSpeed(const MWWorld::Ptr& ptr) const
Marc Zinnschlag's avatar
Marc Zinnschlag committed
690
    {
691 692
        const MWBase::World *world = MWBase::Environment::get().getWorld();
        const CustomData *npcdata = static_cast<const CustomData*>(ptr.getRefData().getCustomData());
693
        const MWMechanics::MagicEffects &mageffects = npcdata->mNpcStats.getMagicEffects();
694

695 696
        const float normalizedEncumbrance = Npc::getEncumbrance(ptr) / Npc::getCapacity(ptr);

697
        float walkSpeed = fMinWalkSpeed->getFloat() + 0.01f*npcdata->mNpcStats.getAttribute(ESM::Attribute::Speed).getModified()*
698 699 700 701 702
                                                      (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();
703

704 705
        float runSpeed = walkSpeed*(0.01f * npcdata->mNpcStats.getSkill(ESM::Skill::Athletics).getModified() *
                                    fAthleticsRunBonus->getFloat() + fBaseRunMultiplier->getFloat());
706 707
        if(npcdata->mNpcStats.isWerewolf())
            runSpeed *= fWereWolfRunMult->getFloat();
708 709

        float moveSpeed;
710
        if(normalizedEncumbrance >= 1.0f)
711
            moveSpeed = 0.0f;
712
        else if(mageffects.get(MWMechanics::EffectKey(10/*levitate*/)).mMagnitude > 0)
713
        {
714
            float flySpeed = 0.01f*(npcdata->mNpcStats.getAttribute(ESM::Attribute::Speed).getModified() +
715
                                    mageffects.get(MWMechanics::EffectKey(10/*levitate*/)).mMagnitude);
716 717 718 719 720 721 722 723 724 725
            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;
726
            swimSpeed *= 1.0f + 0.01f * mageffects.get(MWMechanics::EffectKey(1/*swift swim*/)).mMagnitude;
727 728 729 730
            swimSpeed *= fSwimRunBase->getFloat() + 0.01f*npcdata->mNpcStats.getSkill(ESM::Skill::Athletics).getModified()*
                                                    fSwimRunAthleticsMult->getFloat();
            moveSpeed = swimSpeed;
        }
scrawl's avatar
scrawl committed
731
        else if(Npc::getStance(ptr, Run, false) && !Npc::getStance(ptr, Sneak, false))
732 733 734
            moveSpeed = runSpeed;
        else
            moveSpeed = walkSpeed;
735
        if(getMovementSettings(ptr).mPosition[0] != 0 && getMovementSettings(ptr).mPosition[1] == 0)
736 737 738
            moveSpeed *= 0.75f;

        return moveSpeed;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
739 740
    }

741 742 743
    float Npc::getJump(const MWWorld::Ptr &ptr) const
    {
        const CustomData *npcdata = static_cast<const CustomData*>(ptr.getRefData().getCustomData());
744
        const MWMechanics::MagicEffects &mageffects = npcdata->mNpcStats.getMagicEffects();
745 746
        const float encumbranceTerm = fJumpEncumbranceBase->getFloat() +
                                          fJumpEncumbranceMultiplier->getFloat() *
747
                                          (1.0f - Npc::getEncumbrance(ptr)/Npc::getCapacity(ptr));
748 749 750 751 752 753 754 755 756 757 758

        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());
759 760
        x += 3.0f * b * fJumpAcroMultiplier->getFloat();
        x += mageffects.get(MWMechanics::EffectKey(ESM::MagicEffect::Jump)).mMagnitude * 64;
761 762 763 764
        x *= encumbranceTerm;

        if(Npc::getStance(ptr, Run, false))
            x *= fJumpRunMultiplier->getFloat();
765
        x *= npcdata->mNpcStats.getFatigueTerm();
766 767
        x -= -627.2f;/*gravity constant*/
        x /= 3.0f;
768 769 770 771

        return x;
    }

772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
    float Npc::getFallDamage(const MWWorld::Ptr &ptr, float fallHeight) const
    {
        const float fallDistanceMin = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>().find("fFallDamageDistanceMin")->getFloat();

        if (fallHeight>=fallDistanceMin)
        {
            const float acrobaticsSkill = MWWorld::Class::get(ptr).getNpcStats (ptr).getSkill(ESM::Skill::Acrobatics).getModified();
            const CustomData *npcdata = static_cast<const CustomData*>(ptr.getRefData().getCustomData());
            const float jumpSpellBonus = npcdata->mNpcStats.getMagicEffects().get(MWMechanics::EffectKey(9/*jump*/)).mMagnitude;
            const float fallAcroBase = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>().find("fFallAcroBase")->getFloat();
            const float fallAcroMult = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>().find("fFallAcroMult")->getFloat();
            const float fallDistanceBase = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>().find("fFallDistanceBase")->getFloat();
            const float fallDistanceMult = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>().find("fFallDistanceMult")->getFloat();

            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;
    }

800 801
    MWMechanics::Movement& Npc::getMovementSettings (const MWWorld::Ptr& ptr) const
    {
802
        ensureCustomData (ptr);
803

804
        return dynamic_cast<CustomData&> (*ptr.getRefData().getCustomData()).mMovement;
805 806 807 808
    }

    Ogre::Vector3 Npc::getMovementVector (const MWWorld::Ptr& ptr) const
    {
809 810 811 812 813 814
        MWMechanics::Movement &movement = getMovementSettings(ptr);
        Ogre::Vector3 vec(movement.mPosition);
        movement.mPosition[0] = 0.0f;
        movement.mPosition[1] = 0.0f;
        movement.mPosition[2] = 0.0f;
        return vec;
815
    }
816 817 818

    Ogre::Vector3 Npc::getRotationVector (const MWWorld::Ptr& ptr) const
    {
819 820 821 822 823 824
        MWMechanics::Movement &movement = getMovementSettings(ptr);
        Ogre::Vector3 vec(movement.mRotation);
        movement.mRotation[0] = 0.0f;
        movement.mRotation[1] = 0.0f;
        movement.mRotation[2] = 0.0f;
        return vec;
825 826
    }

827 828 829 830
    bool Npc::isEssential (const MWWorld::Ptr& ptr) const
    {
        MWWorld::LiveCellRef<ESM::NPC> *ref =
            ptr.get<ESM::NPC>();
831

greye's avatar
greye committed
832
        return ref->mBase->mFlags & ESM::NPC::Essential;
833 834
    }
    
835 836 837 838 839
    void Npc::registerSelf()
    {
        boost::shared_ptr<Class> instance (new Npc);
        registerClass (typeid (ESM::NPC).name(), instance);
    }
840 841 842 843 844 845 846 847

    bool Npc::hasToolTip (const MWWorld::Ptr& ptr) const
    {
        /// \todo We don't want tooltips for NPCs in combat mode.

        return true;
    }

848
    MWGui::ToolTipInfo Npc::getToolTipInfo (const MWWorld::Ptr& ptr) const
849
    {
850
        MWWorld::LiveCellRef<ESM::NPC> *ref = ptr.get<ESM::NPC>();
851

852
        bool fullHelp = MWBase::Environment::get().getWindowManager()->getFullHelp();
853 854
        MWGui::ToolTipInfo info;

855 856 857 858 859 860 861 862 863 864
        info.caption = getName(ptr);
        if(fullHelp && getNpcStats(ptr).isWerewolf())
        {
            info.caption += " (";
            info.caption += ref->mBase->mName;
            info.caption += ")";
        }

        if(fullHelp)
            info.text = MWGui::ToolTips::getMiscString(ref->mBase->mScript, "Script");
865 866 867

        return info;
    }
Marc Zinnschlag's avatar
Marc Zinnschlag committed
868

scrawl's avatar
scrawl committed