Пример #1
0
 void HandleScript(SpellEffIndex /*effIndex*/)
 {
     Unit* caster = GetCaster();
     if (Unit* owner = caster->GetOwner())
         if (!caster->HasAura(SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_DEBUFF))
         {
             owner->CastCustomSpell(SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_TRIGGERED, SPELLVALUE_BASE_POINT0, 100, caster, true);
             caster->CastSpell(caster, SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_DEBUFF, true);
         }
 }
Пример #2
0
 void HandleScript(SpellEffIndex /*effIndex*/)
 {
     Unit* caster = GetCaster();
     if (Unit* owner = caster->GetOwner())
     {
         if (!caster->HasAura(SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_DEBUFF))
         {
             int32 bp0 = 100;
             owner->CastCustomSpell(caster, SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_TRIGGERED, &bp0, NULL, NULL, true);
             caster->CastSpell(caster, SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_DEBUFF, true);
         }
     }
 }
Пример #3
0
 void Entrapment(SpellEffIndex /*effIndex*/)
 {
     Unit* caster = GetCaster();
     if (Unit* target = GetHitUnit())
     {
         if (Unit* owner = caster->GetOwner())
         {
             if (owner->HasAura(TALENT_ENTRAPMENT_RANK_3))
                 caster->CastSpell(target, SPELL_ENTRAPMENT_TRIGGER_3, true);
             else if (owner->HasAura(TALENT_ENTRAPMENT_RANK_2))
                 caster->CastSpell(target, SPELL_ENTRAPMENT_TRIGGER_2, true);
             else if (owner->HasAura(TALENT_ENTRAPMENT_RANK_1))
                 caster->CastSpell(target, SPELL_ENTRAPMENT_TRIGGER_1, true);
         }
     }
 }
Пример #4
0
        void LockAndLoad(SpellEffIndex /*effIndex*/)
        {
            Unit* caster = GetCaster();
            if (Unit* owner = caster->GetOwner())
            {
                uint32 chanceProc = 0;
                if (owner->HasAura(TALENT_LOCK_AND_LOAD_RANK_1))
                    chanceProc = 33;
                else if (owner->HasAura(TALENT_LOCK_AND_LOAD_RANK_2))
                    chanceProc = 66;
                else if (owner->HasAura(TALENT_LOCK_AND_LOAD_RANK_3))
                    chanceProc = 100;

                if (chanceProc != 0 && urand(0,99) < chanceProc)
                    owner->CastSpell(owner,SPELL_LOCK_AND_LOAD_TRIGGER,true);
            }
        }
Пример #5
0
            void MoveInLineOfSight(Unit * who)
            {
                if (!who || me->getVictim())
                    return;

                Unit * pTarget = who;
                // Keine NPCs angreifen, die nicht zu einem Spieler gehören!
                if (pTarget->GetTypeId() == TYPEID_UNIT && !pTarget->GetOwner())
                    return;

                if (pTarget->GetTypeId() == TYPEID_PLAYER)
                    if (!AccountMgr::IsPlayerAccount(pTarget->ToPlayer()->GetSession()->GetSecurity())) // Nur Spieler angreifen, die keine GMs sind!
                        return;

                if (me->canStartAttack(pTarget, true))
                    AttackStart(pTarget);
            }
Пример #6
0
 void HandleDummy(SpellEffIndex /*effIndex*/)
 {
     Unit* caster = GetCaster();
     if (Unit* unitTarget = GetHitUnit())
     {
         if (unitTarget->getPowerType() == POWER_MANA)
         {
             int32 effValue = GetEffectValue();
             // Glyph of Mana Tide
             if (Unit* owner = caster->GetOwner())
                 if (AuraEffect* dummy = owner->GetAuraEffect(SHAMAN_SPELL_GLYPH_OF_MANA_TIDE, 0))
                     effValue += dummy->GetAmount();
             // Regenerate 6% of Total Mana Every 3 secs
             int32 effBasePoints0 = int32(CalculatePctN(unitTarget->GetMaxPower(POWER_MANA), effValue));
             caster->CastCustomSpell(unitTarget, SHAMAN_SPELL_MANA_TIDE_TOTEM, &effBasePoints0, NULL, NULL, true, NULL, NULL, GetOriginalCaster()->GetGUID());
         }
     }
 }
Пример #7
0
    //Edit Player TP
    static bool HandleModifyTalentCommand (ChatHandler* handler, const char* args)
    {
        if (!*args)
            return false;

        int tp = atoi((char*)args);
        if (tp < 0)
            return false;

        Unit* target = handler->getSelectedUnit();
        if (!target)
        {
            handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
            handler->SetSentErrorMessage(true);
            return false;
        }

        if (target->GetTypeId() == TYPEID_PLAYER)
        {
            // check online security
            if (handler->HasLowerSecurity(target->ToPlayer(), 0))
                return false;
            target->ToPlayer()->SetFreeTalentPoints(tp);
            target->ToPlayer()->SendTalentsInfoData(false);
            return true;
        }
        else if (target->ToCreature()->isPet())
        {
            Unit* owner = target->GetOwner();
            if (owner && owner->GetTypeId() == TYPEID_PLAYER && ((Pet *)target)->IsPermanentPetFor(owner->ToPlayer()))
            {
                // check online security
                if (handler->HasLowerSecurity(owner->ToPlayer(), 0))
                    return false;
                ((Pet *)target)->SetFreeTalentPoints(tp);
                owner->ToPlayer()->SendTalentsInfoData(true);
                return true;
            }
        }

        handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
        handler->SetSentErrorMessage(true);
        return false;
    }
Пример #8
0
            void HandleEffectPeriodic(AuraEffect const* /*aurEff*/)
            {
                Unit* target = GetTarget();
                Unit* owner = target->GetOwner();

                if (!owner)
                    return;

                if (owner->IsMounted() && !target->IsMounted())
                {
                    if (VolunteerAI* volunteerAI = CAST_AI(VolunteerAI, target->GetAI()))
                        target->Mount(volunteerAI->GetMountId());
                }
                else if (!owner->IsMounted() && target->IsMounted())
                    target->Dismount();

                target->SetSpeed(MOVE_RUN, owner->GetSpeedRate(MOVE_RUN));
                target->SetSpeed(MOVE_WALK, owner->GetSpeedRate(MOVE_WALK));
            }
Пример #9
0
double MapAnalysis::CityAtRiskRatio(const Unit city, const PLAYER_INDEX opponentId) const
{
    Assert(city.IsValid());
    PLAYER_INDEX playerId = city.GetOwner();

    Player * player_ptr = g_player[playerId];
    if (player_ptr == NULL)
        return 0.0;

    if (opponentId != PLAYER_UNASSIGNED && g_player[opponentId] == NULL)
        return 0.0;

    MapPoint pos;
    city.GetPos(pos);


    sint32  player_threat   = m_threatGrid[playerId].GetGridValue(pos);
    sint32  opponent_threat = (PLAYER_UNASSIGNED == opponentId) // In that case no opponent there, so it is the right way to calculate it?
                              ? GetThreat(playerId, pos)
                              : m_threatGrid[opponentId].GetGridValue(pos);

    double ratio;
    if (player_threat > 0)
	{
		ratio = ((double) opponent_threat / (double) player_threat) * 0.2;
        if (ratio > 1.0)
            ratio = 1.0;
        else if (ratio < 0.0)
            ratio = 0.0;
	}
	else if (opponent_threat <= 0)
	{
		ratio  = 0.0;
	}
	else 
	{
		ratio = 1.0;
	}

	return ratio;
}
Пример #10
0
void MapAnalysis::UpdateBoundingRectangle(const Unit & city)
{
    const PLAYER_INDEX player = city.GetOwner();

    MapPoint xy_center(0, 0);
    xy_center.rc2xy(city.RetPos(), * g_theWorld->GetSize());

    MapPoint xy_map_size(g_theWorld->GetWidth() * 2, g_theWorld->GetHeight());

    if (!m_empireBoundingRect[player].IsValid())
    {
        m_empireBoundingRect[player].Initialize
			(xy_center, 0, xy_map_size, g_theWorld->IsXwrap(), g_theWorld->IsYwrap());
    }

    sint32 city_size = city->GetCityData()->GetSizeIndex();
    if (city_size >= g_theCitySizeDB->NumRecords())
	{
		city_size = g_theCitySizeDB->NumRecords() - 1;
	}
    sint16 xy_radius = (sint16)g_theCitySizeDB->Get(city_size)->GetIntRadius();

    if ((xy_radius % 2) != 0)
        xy_radius++;

    BoundingRect cityRect(xy_center, xy_radius, xy_map_size,
						  g_theWorld->IsXwrap(), g_theWorld->IsYwrap()
						 );

    bool added = m_empireBoundingRect[player].Add(cityRect);
    Assert(added);

	m_empireCenter[player].xy2rc(m_empireBoundingRect[player].GetCenter(), * g_theWorld->GetSize());
	DPRINTF(k_DBG_SCHEDULER, ("Empire Center for player %d :  rc(%3d,%3d)   \n",
		player,
		m_empireCenter[player].x,
		m_empireCenter[player].y));
}
Пример #11
0
            void MoveInLineOfSight(Unit * who)
            {
                if (!who || me->getVictim())
                    return;

                Unit * pTarget = who;

                if (!introDone && pTarget->GetDistance(me) <= 100)
                {
                    DoAction(ACTION_INTRO_BALTHARUS);
                    return;
                }
                // Keine NPCs angreifen, die nicht zu einem Spieler gehören!
                if (pTarget->GetTypeId() == TYPEID_UNIT && !pTarget->GetOwner())
                    return;
                // Nur Spieler angreifen, die keine GMs sind!
                if (pTarget->GetTypeId() == TYPEID_PLAYER)
                    if (!AccountMgr::IsPlayerAccount(pTarget->ToPlayer()->GetSession()->GetSecurity()))
                        return;

                if (me->canStartAttack(pTarget, true))
                    AttackStart(pTarget);
            }
Пример #12
0
/// Update the settle target information when a city grows
/// \param city The city
void SettleMap::HandleCityGrowth(const Unit & city)
{
	Assert(city.IsValid());
	MapPoint        cityPos     = city.RetPos();
	CityData *      citydata    = city.GetCityData();
	PLAYER_INDEX    playerId    = city.GetOwner();
	sint32          radius      = g_theCitySizeDB->Get(citydata->GetSizeIndex())->GetIntRadius();
	/// @todo Check functionality. Using "2 * current radius + 1" looks arbitrary.
	/// This does not account for future growth (city spacing may become too tight), but it also
	/// prevents any overlap.
	radius += radius + 1;
	
	// Mark tiles near to the grown city as not worth to settle at all
	RadiusIterator it(cityPos, radius);
	for (it.Start(); !it.End(); it.Next()) 
	{
		MapPoint    clearPos = it.Pos();
		m_invalidCells.Set(clearPos.x, clearPos.y, TRUE);
	}

	
	const StrategyRecord & strategy = Diplomat::GetDiplomat(playerId).GetCurrentStrategy();
	sint32                  min_settle_distance = 0;
	strategy.GetMinSettleDistance(min_settle_distance);

	// Mark tiles further away as having only half the usual value
	/// \todo Optimise using CircleIterator, to skip computing values for the already invalidated tiles.
	RadiusIterator settleIt(cityPos, min_settle_distance);
	for (settleIt.Start(); !settleIt.End(); settleIt.Next()) 
	{
		MapPoint        claimPos    = settleIt.Pos();
		double const    new_value   = ComputeSettleValue(claimPos) * 0.5;
		m_settleValues.SetGridValue(claimPos, new_value);
	}
	
	MapAnalysis::GetMapAnalysis().UpdateBoundingRectangle(city);
}
Пример #13
0
void CreatureEventAI::ProcessAction(CreatureEventAI_Action const& action, uint32 rnd, uint32 eventId, Unit* actionInvoker)
{
    switch (action.type)
    {
    case ACTION_T_TEXT:
    {
        if (!action.text.TextId1)
            return;

        int32 temp = action.text.TextId1;

        if (action.text.TextId2 && action.text.TextId3)
            temp = RAND(action.text.TextId1, action.text.TextId2, action.text.TextId3);
        else if (action.text.TextId2 && urand(0, 1))
            temp = action.text.TextId2;

        if (temp)
        {
            Unit* target = NULL;

            if (actionInvoker)
            {
                if (actionInvoker->GetTypeId() == TYPEID_PLAYER)
                    target = actionInvoker;
                else if (Unit* owner = actionInvoker->GetOwner())
                {
                    if (owner->GetTypeId() == TYPEID_PLAYER)
                        target = owner;
                }
            }
            else
            {
                target = me->getVictim();
                if (target && target->GetTypeId() != TYPEID_PLAYER)
                    if (Unit* owner = target->GetOwner())
                        if (owner->GetTypeId() == TYPEID_PLAYER)
                            target = owner;
            }

            DoScriptText(temp, me, target);
        }
        break;
    }
    case ACTION_T_SET_FACTION:
    {
        if (action.set_faction.factionId)
            me->setFaction(action.set_faction.factionId);
        else
        {
            if (CreatureTemplate const* ci = sObjectMgr->GetCreatureTemplate(me->GetEntry()))
            {
                //if no id provided, assume reset and then use default
                if (me->getFaction() != ci->faction_A)
                    me->setFaction(ci->faction_A);
            }
        }
        break;
    }
    case ACTION_T_MORPH_TO_ENTRY_OR_MODEL:
    {
        if (action.morph.creatureId || action.morph.modelId)
        {
            //set model based on entry from creature_template
            if (action.morph.creatureId)
            {
                if (CreatureTemplate const* ci = sObjectMgr->GetCreatureTemplate(action.morph.creatureId))
                {
                    uint32 display_id = sObjectMgr->ChooseDisplayId(0, ci);
                    me->SetDisplayId(display_id);
                }
            }
            //if no param1, then use value from param2 (modelId)
            else
                me->SetDisplayId(action.morph.modelId);
        }
        else
            me->DeMorph();
        break;
    }
    case ACTION_T_SOUND:
        me->PlayDirectSound(action.sound.soundId);
        break;
    case ACTION_T_EMOTE:
        me->HandleEmoteCommand(action.emote.emoteId);
        break;
    case ACTION_T_RANDOM_SOUND:
    {
        int32 temp = GetRandActionParam(rnd, action.random_sound.soundId1, action.random_sound.soundId2, action.random_sound.soundId3);
        if (temp >= 0)
            me->PlayDirectSound(temp);
        break;
    }
    case ACTION_T_RANDOM_EMOTE:
    {
        int32 temp = GetRandActionParam(rnd, action.random_emote.emoteId1, action.random_emote.emoteId2, action.random_emote.emoteId3);
        if (temp >= 0)
            me->HandleEmoteCommand(temp);
        break;
    }
    case ACTION_T_CAST:
    {
        Unit* target = GetTargetByType(action.cast.target, actionInvoker);
        Unit* caster = me;

        if (!target)
            return;

        if (action.cast.castFlags & CAST_FORCE_TARGET_SELF)
            caster = target;

        //Allowed to cast only if not casting (unless we interrupt ourself) or if spell is triggered
        bool canCast = !caster->IsNonMeleeSpellCasted(false) || (action.cast.castFlags & (CAST_TRIGGERED | CAST_INTERRUPT_PREVIOUS));

        // If cast flag CAST_AURA_NOT_PRESENT is active, check if target already has aura on them
        if (action.cast.castFlags & CAST_AURA_NOT_PRESENT)
        {
            if (target->HasAura(action.cast.spellId))
                return;
        }

        if (canCast)
        {
            const SpellInfo* tSpell = sSpellMgr->GetSpellInfo(action.cast.spellId);

            //Verify that spell exists
            if (tSpell)
            {
                //Check if cannot cast spell
                if (!(action.cast.castFlags & (CAST_FORCE_TARGET_SELF | CAST_FORCE_CAST)) &&
                        !CanCast(target, tSpell, (action.cast.castFlags & CAST_TRIGGERED)))
                {
                    //Melee current victim if flag not set
                    if (!(action.cast.castFlags & CAST_NO_MELEE_IF_OOM))
                    {
                        if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == CHASE_MOTION_TYPE)
                        {
                            m_AttackDistance = 0.0f;
                            m_AttackAngle = 0.0f;

                            me->GetMotionMaster()->MoveChase(me->getVictim(), m_AttackDistance, m_AttackAngle);
                        }
                    }
                }
                else
                {
                    //Interrupt any previous spell
                    if (caster->IsNonMeleeSpellCasted(false) && action.cast.castFlags & CAST_INTERRUPT_PREVIOUS)
                        caster->InterruptNonMeleeSpells(false);

                    caster->CastSpell(target, action.cast.spellId, (action.cast.castFlags & CAST_TRIGGERED));
                }

            }
            else
                sLog->outErrorDb("CreatureEventAI: event %d creature %d attempt to cast spell that doesn't exist %d", eventId, me->GetEntry(), action.cast.spellId);
        }
        break;
    }
    case ACTION_T_SUMMON:
    {
        Unit* target = GetTargetByType(action.summon.target, actionInvoker);

        Creature* creature = NULL;

        if (action.summon.duration)
            creature = me->SummonCreature(action.summon.creatureId, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, action.summon.duration);
        else
            creature = me->SummonCreature(action.summon.creatureId, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 0);

        if (!creature)
            sLog->outErrorDb("CreatureEventAI: failed to spawn creature %u. Spawn event %d is on creature %d", action.summon.creatureId, eventId, me->GetEntry());
        else if (action.summon.target != TARGET_T_SELF && target)
            creature->AI()->AttackStart(target);
        break;
    }
    case ACTION_T_THREAT_SINGLE_PCT:
        if (Unit* target = GetTargetByType(action.threat_single_pct.target, actionInvoker))
            me->getThreatManager().modifyThreatPercent(target, action.threat_single_pct.percent);
        break;
    case ACTION_T_THREAT_ALL_PCT:
    {
        std::list<HostileReference*>& threatList = me->getThreatManager().getThreatList();
        for (std::list<HostileReference*>::iterator i = threatList.begin(); i != threatList.end(); ++i)
            if (Unit* Temp = Unit::GetUnit(*me, (*i)->getUnitGuid()))
                me->getThreatManager().modifyThreatPercent(Temp, action.threat_all_pct.percent);
        break;
    }
    case ACTION_T_QUEST_EVENT:
        if (Unit* target = GetTargetByType(action.quest_event.target, actionInvoker))
            if (target->GetTypeId() == TYPEID_PLAYER)
                target->ToPlayer()->AreaExploredOrEventHappens(action.quest_event.questId);
        break;
    case ACTION_T_CAST_EVENT:
        if (Unit* target = GetTargetByType(action.cast_event.target, actionInvoker))
            if (target->GetTypeId() == TYPEID_PLAYER)
                target->ToPlayer()->CastedCreatureOrGO(action.cast_event.creatureId, me->GetGUID(), action.cast_event.spellId);
        break;
    case ACTION_T_SET_UNIT_FIELD:
    {
        Unit* target = GetTargetByType(action.set_unit_field.target, actionInvoker);

        // not allow modify important for integrity object fields
        if (action.set_unit_field.field < OBJECT_END || action.set_unit_field.field >= UNIT_END)
            return;

        if (target)
            target->SetUInt32Value(action.set_unit_field.field, action.set_unit_field.value);

        break;
    }
    case ACTION_T_SET_UNIT_FLAG:
        if (Unit* target = GetTargetByType(action.unit_flag.target, actionInvoker))
            target->SetFlag(UNIT_FIELD_FLAGS, action.unit_flag.value);
        break;
    case ACTION_T_REMOVE_UNIT_FLAG:
        if (Unit* target = GetTargetByType(action.unit_flag.target, actionInvoker))
            target->RemoveFlag(UNIT_FIELD_FLAGS, action.unit_flag.value);
        break;
    case ACTION_T_AUTO_ATTACK:
        m_MeleeEnabled = action.auto_attack.state != 0;
        break;
    case ACTION_T_COMBAT_MOVEMENT:
        // ignore no affect case
        if (m_CombatMovementEnabled == (action.combat_movement.state != 0))
            return;

        m_CombatMovementEnabled = action.combat_movement.state != 0;

        //Allow movement (create new targeted movement gen only if idle)
        if (m_CombatMovementEnabled)
        {
            Unit* victim = me->getVictim();
            if (me->isInCombat() && victim)
            {
                if (action.combat_movement.melee)
                {
                    me->AddUnitState(UNIT_STATE_MELEE_ATTACKING);
                    me->SendMeleeAttackStart(victim);
                }
                if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == IDLE_MOTION_TYPE)
                    me->GetMotionMaster()->MoveChase(victim, m_AttackDistance, m_AttackAngle); // Targeted movement generator will start melee automatically, no need to send it explicitly
            }
        }
        else
        {
            if (me->isInCombat())
            {
                Unit* victim = me->getVictim();
                if (action.combat_movement.melee && victim)
                {
                    me->ClearUnitState(UNIT_STATE_MELEE_ATTACKING);
                    me->SendMeleeAttackStop(victim);
                }
                if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == CHASE_MOTION_TYPE)
                    me->GetMotionMaster()->MoveIdle();
            }
        }
        break;
    case ACTION_T_SET_PHASE:
        m_Phase = action.set_phase.phase;
        break;
    case ACTION_T_INC_PHASE:
    {
        int32 new_phase = int32(m_Phase)+action.set_inc_phase.step;
        if (new_phase < 0)
        {
            sLog->outErrorDb("CreatureEventAI: Event %d decrease m_Phase under 0. CreatureEntry = %d", eventId, me->GetEntry());
            m_Phase = 0;
        }
        else if (new_phase >= MAX_PHASE)
        {
            sLog->outErrorDb("CreatureEventAI: Event %d incremented m_Phase above %u. m_Phase mask cannot be used with phases past %u. CreatureEntry = %d", eventId, MAX_PHASE-1, MAX_PHASE-1, me->GetEntry());
            m_Phase = MAX_PHASE-1;
        }
        else
            m_Phase = new_phase;

        break;
    }
    case ACTION_T_EVADE:
        EnterEvadeMode();
        break;
    case ACTION_T_FLEE_FOR_ASSIST:
        me->DoFleeToGetAssistance();
        break;
    case ACTION_T_QUEST_EVENT_ALL:
        if (actionInvoker && actionInvoker->GetTypeId() == TYPEID_PLAYER)
        {
            if (Unit* Temp = Unit::GetUnit(*me, actionInvoker->GetGUID()))
                if (Temp->GetTypeId() == TYPEID_PLAYER)
                    Temp->ToPlayer()->GroupEventHappens(action.quest_event_all.questId, me);
        }
        break;
    case ACTION_T_CAST_EVENT_ALL:
    {
        std::list<HostileReference*>& threatList = me->getThreatManager().getThreatList();
        for (std::list<HostileReference*>::iterator i = threatList.begin(); i != threatList.end(); ++i)
            if (Unit* Temp = Unit::GetUnit(*me, (*i)->getUnitGuid()))
                if (Temp->GetTypeId() == TYPEID_PLAYER)
                    Temp->ToPlayer()->CastedCreatureOrGO(action.cast_event_all.creatureId, me->GetGUID(), action.cast_event_all.spellId);
        break;
    }
    case ACTION_T_REMOVEAURASFROMSPELL:
        if (Unit* target = GetTargetByType(action.remove_aura.target, actionInvoker))
            target->RemoveAurasDueToSpell(action.remove_aura.spellId);
        break;
    case ACTION_T_RANGED_MOVEMENT:
        m_AttackDistance = (float)action.ranged_movement.distance;
        m_AttackAngle = action.ranged_movement.angle/180.0f*M_PI;

        if (m_CombatMovementEnabled)
        {
            me->GetMotionMaster()->MoveChase(me->getVictim(), m_AttackDistance, m_AttackAngle);
        }
        break;
    case ACTION_T_RANDOM_PHASE:
        m_Phase = GetRandActionParam(rnd, action.random_phase.phase1, action.random_phase.phase2, action.random_phase.phase3);
        break;
    case ACTION_T_RANDOM_PHASE_RANGE:
        if (action.random_phase_range.phaseMin <= action.random_phase_range.phaseMax)
            m_Phase = urand(action.random_phase_range.phaseMin, action.random_phase_range.phaseMax);
        else
            sLog->outErrorDb("CreatureEventAI: ACTION_T_RANDOM_PHASE_RANGE cannot have Param2 < Param1. Event = %d. CreatureEntry = %d", eventId, me->GetEntry());
        break;
    case ACTION_T_SUMMON_ID:
    {
        Unit* target = GetTargetByType(action.summon_id.target, actionInvoker);

        CreatureEventAI_Summon_Map::const_iterator i = sEventAIMgr->GetCreatureEventAISummonMap().find(action.summon_id.spawnId);
        if (i == sEventAIMgr->GetCreatureEventAISummonMap().end())
        {
            sLog->outErrorDb("CreatureEventAI: failed to spawn creature %u. Summon map index %u does not exist. EventID %d. CreatureID %d", action.summon_id.creatureId, action.summon_id.spawnId, eventId, me->GetEntry());
            return;
        }

        Creature* creature = NULL;
        if ((*i).second.SpawnTimeSecs)
            creature = me->SummonCreature(action.summon_id.creatureId, (*i).second.position_x, (*i).second.position_y, (*i).second.position_z, (*i).second.orientation, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, (*i).second.SpawnTimeSecs);
        else
            creature = me->SummonCreature(action.summon_id.creatureId, (*i).second.position_x, (*i).second.position_y, (*i).second.position_z, (*i).second.orientation, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 0);

        if (!creature)
            sLog->outErrorDb("CreatureEventAI: failed to spawn creature %u. EventId %d.Creature %d", action.summon_id.creatureId, eventId, me->GetEntry());
        else if (action.summon_id.target != TARGET_T_SELF && target)
            creature->AI()->AttackStart(target);

        break;
    }
    case ACTION_T_KILLED_MONSTER:
        //first attempt player who tapped creature
        if (Player* player = me->GetLootRecipient())
            player->RewardPlayerAndGroupAtEvent(action.killed_monster.creatureId, player);    // player as param is a hacky solution not to use GUID
        else
        {
            //if not available, use actionInvoker
            if (Unit* target = GetTargetByType(action.killed_monster.target, actionInvoker))
                if (Player* player2 = target->GetCharmerOrOwnerPlayerOrPlayerItself())
                    player2->RewardPlayerAndGroupAtEvent(action.killed_monster.creatureId, player2);
        }
        break;
    case ACTION_T_SET_INST_DATA:
    {
        InstanceScript* instance = (InstanceScript*)me->GetInstanceScript();
        if (!instance)
        {
            sLog->outErrorDb("CreatureEventAI: Event %d attempt to set instance data without instance script. Creature %d", eventId, me->GetEntry());
            return;
        }

        instance->SetData(action.set_inst_data.field, action.set_inst_data.value);
        break;
    }
    case ACTION_T_SET_INST_DATA64:
    {
        Unit* target = GetTargetByType(action.set_inst_data64.target, actionInvoker);
        if (!target)
        {
            sLog->outErrorDb("CreatureEventAI: Event %d attempt to set instance data64 but Target == NULL. Creature %d", eventId, me->GetEntry());
            return;
        }

        InstanceScript* instance = (InstanceScript*)me->GetInstanceScript();
        if (!instance)
        {
            sLog->outErrorDb("CreatureEventAI: Event %d attempt to set instance data64 without instance script. Creature %d", eventId, me->GetEntry());
            return;
        }

        instance->SetData64(action.set_inst_data64.field, target->GetGUID());
        break;
    }
    case ACTION_T_UPDATE_TEMPLATE:
        if (me->GetEntry() == action.update_template.creatureId)
        {

            sLog->outErrorDb("CreatureEventAI: Event %d ACTION_T_UPDATE_TEMPLATE call with param1 == current entry. Creature %d", eventId, me->GetEntry());
            return;
        }

        me->UpdateEntry(action.update_template.creatureId, action.update_template.team ? HORDE : ALLIANCE);
        break;
    case ACTION_T_DIE:
        if (me->isDead())
        {

            sLog->outErrorDb("CreatureEventAI: Event %d ACTION_T_DIE on dead creature. Creature %d", eventId, me->GetEntry());
            return;
        }
        me->Kill(me);
        break;
    case ACTION_T_ZONE_COMBAT_PULSE:
    {
        me->SetInCombatWithZone();
        break;
    }
    case ACTION_T_CALL_FOR_HELP:
    {
        me->CallForHelp((float)action.call_for_help.radius);
        break;
    }
    break;

    // TRINITY ONLY
    case ACTION_T_MOVE_RANDOM_POINT: //dosen't work in combat
    {
        float x, y, z;
        me->GetClosePoint(x, y, z, me->GetObjectSize() / 3, (float)action.raw.param1);
        me->GetMotionMaster()->MovePoint(0, x, y, z);
        break;
    }
    case ACTION_T_SET_STAND_STATE:
        me->SetStandState(UnitStandStateType(action.raw.param1));
        break;
    case ACTION_T_SET_PHASE_MASK:
        me->SetPhaseMask(action.raw.param1, true);
        break;
    case ACTION_T_SET_VISIBILITY:
        me->SetVisible(bool(action.raw.param1));
        break;
    case ACTION_T_SET_ACTIVE:
        me->setActive(action.raw.param1 ? true : false);
        break;
    case ACTION_T_SET_AGGRESSIVE:
        me->SetReactState(ReactStates(action.raw.param1));
        break;
    case ACTION_T_ATTACK_START_PULSE:
        AttackStart(me->SelectNearestTarget((float)action.raw.param1));
        break;
    case ACTION_T_SUMMON_GO:
    {
        GameObject* object = NULL;

        float x, y, z;
        me->GetPosition(x, y, z);
        object = me->SummonGameObject(action.raw.param1, x, y, z, 0, 0, 0, 0, 0, action.raw.param2);
        if (!object)
        {
            sLog->outErrorDb("TSCR: EventAI failed to spawn object %u. Spawn event %d is on creature %d", action.raw.param1, eventId, me->GetEntry());
        }
        break;
    }

    case ACTION_T_SET_SHEATH:
    {
        me->SetSheath(SheathState(action.set_sheath.sheath));
        break;
    }
    case ACTION_T_FORCE_DESPAWN:
    {
        me->DespawnOrUnsummon(action.forced_despawn.msDelay);
        break;
    }
    case ACTION_T_SET_INVINCIBILITY_HP_LEVEL:
    {
        if (action.invincibility_hp_level.is_percent)
            m_InvincibilityHpLevel = me->CountPctFromMaxHealth(action.invincibility_hp_level.hp_level);
        else
            m_InvincibilityHpLevel = action.invincibility_hp_level.hp_level;
        break;
    }
    case ACTION_T_MOUNT_TO_ENTRY_OR_MODEL:
    {
        if (action.mount.creatureId || action.mount.modelId)
        {
            // set model based on entry from creature_template
            if (action.mount.creatureId)
            {
                if (CreatureTemplate const* cInfo = sObjectMgr->GetCreatureTemplate(action.mount.creatureId))
                {
                    uint32 display_id = sObjectMgr->ChooseDisplayId(0, cInfo);
                    me->Mount(display_id);
                }
            }
            //if no param1, then use value from param2 (modelId)
            else
                me->Mount(action.mount.modelId);
        }
        else
            me->Dismount();

        break;
    }
    }
}
Пример #14
0
/// Display espionage intelligence of a city
/// \param  a_City  The city that has been investigated
void CityEspionage::DisplayWindow(Unit a_City)
{
	if (m_window)
	{
		AUI_ERRCODE err = g_c3ui->AddWindow(m_window);
		Assert(err == AUI_ERRCODE_OK);

		if (err == AUI_ERRCODE_OK) 
		{
			err = m_window->Show();
		}

		if (!a_City.IsValid())
		{
			return;
		}

		SlicObject so;
		so.AddPlayer(a_City.GetOwner());
		so.AddCity(a_City);

		SetLabelText("DialogBackground.CityLabel",          "str_ldl_Espionage_City_Label",         so);
		SetLabelText("DialogBackground.PopulationLabel",    "str_ldl_Espionage_Population_Label",   so);
		SetLabelText("DialogBackground.HapinessLabel",      "str_ldl_Espionage_Happiness_Label",    so);
		SetLabelText("DialogBackground.Building",           "str_ldl_Espionage_Building_Label",     so);
		SetLabelText("DialogBackground.CompleteIn",         "str_ldl_Espionage_CompleteIn_Label",   so);
		SetLabelText("DialogBackground.CityIncome",         "str_ldl_Espionage_CityIncome_Label",   so);
		SetLabelText("DialogBackground.GoldFromTrade",      "str_ldl_Espionage_GoldInTrade_Label",  so);

		Assert(m_inventoryList);
		if (m_inventoryList) 
		{
			m_inventoryList->ClearUserData CALL_TEMPLATE_FUNCTION_WITHOUT_ARGUMENT(InventoryItemInfo);
			m_inventoryList->Clear();
			m_inventoryList->BuildListStart();

			CityData const *    cityData    = a_City.GetCityData();

			for (sint32 buildIndex = 0; buildIndex < g_theBuildingDB->NumRecords(); ++buildIndex)
			{
				if (cityData->HasBuilding(buildIndex)) 
				{
					ctp2_ListItem * item = static_cast<ctp2_ListItem *>
					    (aui_Ldl::BuildHierarchyFromRoot("ce_InventoryListItem"));

					if (item) 
					{
						item->SetText(g_theBuildingDB->Get(buildIndex)->GetNameText());
						item->SetUserData(new InventoryItemInfo(true, buildIndex));
					}

					m_inventoryList->AddItem(item);
				}
			}

			
			for (sint32 wonderIndex = 0; wonderIndex < g_theWonderDB->NumRecords(); ++wonderIndex) 
			{
				if (cityData->GetBuiltWonders() & ((uint64) 1 << (uint64) wonderIndex)) 
				{
					ctp2_ListItem * item = static_cast<ctp2_ListItem *>
					    (aui_Ldl::BuildHierarchyFromRoot("ce_InventoryListItem"));

					if (item) 
					{
						item->SetText(g_theWonderDB->Get(wonderIndex)->GetNameText());
						item->SetUserData(new InventoryItemInfo(false, wonderIndex));
					}
					
					m_inventoryList->AddItem(item);
				}
			}

			m_inventoryList->BuildListEnd();

			MapPoint pos;
			a_City.GetPos(pos);
			Cell * cell = g_theWorld->GetCell(pos);

			CellUnitList cellUnitList;
			cell->GetArmy(cellUnitList);

			
			sint32 unitIndex = 0;

			
			for (sint32 multiIndex = 0; multiIndex < k_MAX_ARMY_SIZE; ++multiIndex) 
			{
				MBCHAR interp[k_MAX_NAME_LEN];
				sprintf(interp, "DialogBackground.FortifiedUnitsBox.Unit%i", multiIndex);
				ctp2_Static * st = (ctp2_Static *) aui_Ldl::GetObject(LDL_BLOCK, interp);
				
				if (st)
				{
					if (unitIndex < cellUnitList.Num()) 
					{
						Unit &  unit = cellUnitList[unitIndex++];
						
						if (st->IsDisabled())
						{
							st->Enable(true);
						}

						st->ExchangeImage(0, 0,	unit.GetDBRec()->GetDefaultIcon()->GetIcon());
					}
					else
					{
						if (!st->IsDisabled())
						{
							st->Enable(false);
						}

						st->ExchangeImage(0, 0, NULL);
					}
				}
			}
		}
	}
}
Пример #15
0
void WonderTab::AddWonderItem(sint32 wonder, sint32 player, sint32 turn)
{
	Unit curCity;
	if(!g_theWonderTracker->GetCityWithWonder(wonder, curCity))
		curCity.m_id = 0;

	const WonderRecord *rec = wonderutil_Get(wonder, player);
	ctp2_ListItem *item = (ctp2_ListItem *)aui_Ldl::BuildHierarchyFromRoot("WonderTabListItem");
	Assert(item);
	if(item) {
		ctp2_Static *box = (ctp2_Static *)item->GetChildByIndex(0);

		Assert(box);
		if(box) {
			ctp2_Static *st = (ctp2_Static *)box->GetChildByIndex(0);
			Assert(st);
			if(st) {
				st->SetImage((char *)rec->GetDefaultIcon()->GetFirstFrame());
			}

			st = (ctp2_Static *)box->GetChildByIndex(1);
			Assert(st);
			if(st) {
				st->SetText(rec->GetNameText());
			}

			st = (ctp2_Static *)box->GetChildByIndex(2);
			Assert(st);
			if(st) {
				const char *year = diffutil_GetYearStringFromTurn(g_theGameSettings->GetDifficulty(), turn);
				if(year) {
					st->SetText(year);
				} else {
					st->SetText("error");
				}
				
				item->SetUserData((void*)turn);
			}

			st = (ctp2_Static *)box->GetChildByIndex(3);
			Assert(st);
			if(st) {
				if(curCity.IsValid()) {
					st->SetText(curCity.CD()->GetName());
					st->SetTextColor(g_colorSet->GetColorRef(g_colorSet->ComputePlayerColor(curCity.GetOwner())));
				} else {
					st->SetText("---");
				}
			}

			st = (ctp2_Static *)box->GetChildByIndex(4);
			Assert(st);
			if(st) {
				Player *p = g_player[player];
				if(!p) {
					PointerList<Player>::Walker walk(g_deadPlayer);
					for(; walk.IsValid(); walk.Next()) {
						if(walk.GetObj()->m_owner == player) {
							p = walk.GetObj();
							break;
						}
					}
				}
				if(!p) {
					st->SetText("---");
				} else {					
					MBCHAR buf[k_MAX_NAME_LEN];
					p->m_civilisation->GetCountryName(buf);
					st->SetText(buf);
				}
			}
		}

		item->SetCompareCallback(CompareWonderItems);

		m_list->AddItem(item);
	}
}
Пример #16
0
/// %Log the player out
void WorldSession::LogoutPlayer(bool Save)
{
    // finish pending transfers before starting the logout
    while(_player && _player->IsBeingTeleportedFar())
        HandleMoveWorldportAckOpcode();

    m_playerLogout = true;
    m_playerSave = Save;

    if (_player)
    {
        // Playerbot mod: log out all player bots owned by this toon
        if (GetPlayer()->GetPlayerbotMgr())
            GetPlayer()->GetPlayerbotMgr()->LogoutAllBots();

        sLog.outChar("Account: %d (IP: %s) Logout Character:[%s] (guid: %u)", GetAccountId(), GetRemoteAddress().c_str(), _player->GetName() ,_player->GetGUIDLow());

        if (ObjectGuid lootGuid = GetPlayer()->GetLootGuid())
            DoLootRelease(lootGuid);

        ///- If the player just died before logging out, make him appear as a ghost
        //FIXME: logout must be delayed in case lost connection with client in time of combat
        if (GetPlayer()->GetDeathTimer())
        {
            GetPlayer()->getHostileRefManager().deleteReferences();
            GetPlayer()->BuildPlayerRepop();
            GetPlayer()->RepopAtGraveyard();
        }
        else if (GetPlayer()->IsInCombat() && GetPlayer()->GetMap())
        {
            GetPlayer()->CombatStop();
            GetPlayer()->getHostileRefManager().setOnlineOfflineState(false);
            GetPlayer()->RemoveAllAurasOnDeath();

            // build set of player who attack _player or who have pet attacking of _player
            std::set<Player*> aset;
            GuidSet& attackers = GetPlayer()->GetMap()->GetAttackersFor(GetPlayer()->GetObjectGuid());

            for (GuidSet::const_iterator itr = attackers.begin(); itr != attackers.end();)
            {
                Unit* attacker = GetPlayer()->GetMap()->GetUnit(*itr++);
                if (!attacker)
                    continue;

                Unit* owner = attacker->GetOwner();           // including player controlled case
                if(owner)
                {
                    if(owner->GetTypeId() == TYPEID_PLAYER)
                        aset.insert((Player*)owner);
                }
                else
                    if(attacker->GetTypeId() == TYPEID_PLAYER)
                        aset.insert((Player*)(attacker));
            }

            GetPlayer()->SetPvPDeath(!aset.empty());
            GetPlayer()->KillPlayer();
            GetPlayer()->BuildPlayerRepop();
            GetPlayer()->RepopAtGraveyard();

            // give honor to all attackers from set like group case
            for(std::set<Player*>::const_iterator itr = aset.begin(); itr != aset.end(); ++itr)
                (*itr)->RewardHonor(GetPlayer(),aset.size());

            // give bg rewards and update counters like kill by first from attackers
            // this can't be called for all attackers.
            if(!aset.empty())
                if(BattleGround *bg = GetPlayer()->GetBattleGround())
                    bg->HandleKillPlayer(GetPlayer(),*aset.begin());
        }
        else if(GetPlayer()->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION))
        {
            // this will kill character by SPELL_AURA_SPIRIT_OF_REDEMPTION
            GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT);
            //GetPlayer()->SetDeathPvP(*); set at SPELL_AURA_SPIRIT_OF_REDEMPTION apply time
            GetPlayer()->KillPlayer();
            GetPlayer()->BuildPlayerRepop();
            GetPlayer()->RepopAtGraveyard();
        }
        else if (GetPlayer()->HasPendingBind())
        {
            GetPlayer()->RepopAtGraveyard();
            GetPlayer()->SetPendingBind(NULL, 0);
        }

        //drop a flag if player is carrying it
        if(BattleGround *bg = GetPlayer()->GetBattleGround())
            bg->EventPlayerLoggedOut(GetPlayer());

        ///- Teleport to home if the player is in an invalid instance
        if(!GetPlayer()->m_InstanceValid && !GetPlayer()->isGameMaster())
        {
            GetPlayer()->TeleportToHomebind();
            //this is a bad place to call for far teleport because we need player to be in world for successful logout
            //maybe we should implement delayed far teleport logout?
        }

        // FG: finish pending transfers after starting the logout
        // this should fix players beeing able to logout and login back with full hp at death position
        while(GetPlayer()->IsBeingTeleportedFar())
            HandleMoveWorldportAckOpcode();

        for (int i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
        {
            if(BattleGroundQueueTypeId bgQueueTypeId = GetPlayer()->GetBattleGroundQueueTypeId(i))
            {
                GetPlayer()->RemoveBattleGroundQueueId(bgQueueTypeId);
                sBattleGroundMgr.m_BattleGroundQueues[ bgQueueTypeId ].RemovePlayer(GetPlayer()->GetObjectGuid(), true);
            }
        }

        ///- Reset the online field in the account table
        // no point resetting online in character table here as Player::SaveToDB() will set it to 1 since player has not been removed from world at this stage
        // No SQL injection as AccountID is uint32
        if (!GetPlayer()->GetPlayerbotAI())
        {
            static SqlStatementID id;

            SqlStatement stmt = LoginDatabase.CreateStatement(id, "UPDATE account SET active_realm_id = ? WHERE id = ?");
            stmt.PExecute(uint32(0), GetAccountId());
        }

        ///- If the player is in a guild, update the guild roster and broadcast a logout message to other guild members
        Guild* guild = sGuildMgr.GetGuildById(GetPlayer()->GetGuildId());
        if (guild)
        {
            if (MemberSlot* slot = guild->GetMemberSlot(GetPlayer()->GetObjectGuid()))
            {
                slot->SetMemberStats(GetPlayer());
                slot->UpdateLogoutTime();
            }

            guild->BroadcastEvent(GE_SIGNED_OFF, GetPlayer()->GetObjectGuid(), GetPlayer()->GetName());
        }

        ///- Remove pet
        GetPlayer()->RemovePet(PET_SAVE_AS_CURRENT);

        GetPlayer()->InterruptNonMeleeSpells(true);

        if (VehicleKitPtr vehicle = GetPlayer()->GetVehicle())
            GetPlayer()->ExitVehicle();

        ///- empty buyback items and save the player in the database
        // some save parts only correctly work in case player present in map/player_lists (pets, etc)
        if(Save)
            GetPlayer()->SaveToDB();

        ///- Leave all channels before player delete...
        GetPlayer()->CleanupChannels();

        // LFG cleanup
        sLFGMgr.Leave(GetPlayer());

        ///- If the player is in a group (or invited), remove him. If the group if then only 1 person, disband the group.
        GetPlayer()->UninviteFromGroup();

        // remove player from the group if he is:
        // a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected)
        if(GetPlayer()->GetGroup() && !GetPlayer()->GetGroup()->isRaidGroup() && m_Socket)
            GetPlayer()->RemoveFromGroup();

        ///- Send update to group
        if(GetPlayer()->GetGroup())
            GetPlayer()->GetGroup()->SendUpdate();

        ///- Broadcast a logout message to the player's friends
        sSocialMgr.SendFriendStatus(GetPlayer(), FRIEND_OFFLINE, GetPlayer()->GetObjectGuid(), true);
        sSocialMgr.RemovePlayerSocial (GetPlayer()->GetGUIDLow ());

        // Playerbot - remember player GUID for update SQL below
        uint32 guid = GetPlayer()->GetGUIDLow();

        ///- Remove the player from the world
        // the player may not be in the world when logging out
        // e.g if he got disconnected during a transfer to another map
        // calls to GetMap in this case may cause crashes
        if (GetPlayer()->IsInWorld())
        {
            Map* _map = GetPlayer()->GetMap();
            _map->Remove(GetPlayer(), true);
        }
        else
        {
            GetPlayer()->CleanupsBeforeDelete();
            if (GetPlayer()->GetMap())
                GetPlayer()->GetMap()->DeleteFromWorld(GetPlayer());
            else
            {
                sObjectAccessor.RemoveObject(GetPlayer());
                delete GetPlayer();
            }
        }

        SetPlayer(NULL);                                    // deleted in Remove/DeleteFromWorld call

        ///- Send the 'logout complete' packet to the client
        WorldPacket data( SMSG_LOGOUT_COMPLETE, 0 );
        SendPacket( &data );

        static SqlStatementID updChars;

        // Playerbot mod: commented out above and do this one instead
        SqlStatement stmt = CharacterDatabase.CreateStatement(updChars, "UPDATE characters SET online = 0 WHERE guid = ?");
        stmt.PExecute(guid);

        DEBUG_LOG( "SESSION: Sent SMSG_LOGOUT_COMPLETE Message" );
    }

    m_playerLogout = false;
    m_playerSave = false;
    m_playerRecentlyLogout = true;
    LogoutRequest(0);
}
Пример #17
0
//----------------------------------------------------------------------------
//
// Name       : UnseenCell::UnseenCell
//
// Description: Constructor
//
// Parameters : point			: The point (RC coordinate)
//
// Globals    : g_theWorld		: World information
//
// Returns    : -
//
// Remark(s)  : The constructor to use normally.
//
//----------------------------------------------------------------------------
UnseenCell::UnseenCell(const MapPoint & point)
:
	m_env                           (0),
	m_terrain_type                  (TERRAIN_UNKNOWN),
	m_move_cost                     (MOVECOST_UNKNOWN),
	m_flags                         (0x0000),
	m_bioInfectedOwner              (0x00), /// @todo Check PLAYER_UNASSIGNED?
	m_nanoInfectedOwner             (0x00),
	m_convertedOwner                (0x00),
	m_franchiseOwner                (0x00),
	m_injoinedOwner                 (0x00),
	m_happinessAttackOwner          (0x00),
	m_citySize                      (0),
	m_cityOwner                     (0),
	m_citySpriteIndex               (-1),
	m_cell_owner                    (PLAYER_UNASSIGNED),
	m_slaveBits                     (0x0000),
#ifdef BATTLE_FLAGS
	m_battleFlags                   (0),
#endif
	m_tileInfo                      (NULL),
	m_point                         (point),
	m_installations                 (new PointerList<UnseenInstallationInfo>),
	m_improvements                  (new PointerList<UnseenImprovementInfo>),
	m_cityName                      (NULL),
	m_actor                         (NULL),
	m_poolIndex                     (-1),
	m_visibleCityOwner              (0)
{
	if (g_theWorld->GetTileInfo(point))
	{
		m_tileInfo = new TileInfo(g_theWorld->GetTileInfo(point));
	}

	Cell * cell = g_theWorld->GetCell(point);
	if (cell)
	{
		m_env = cell->GetEnv();
		m_move_cost = sint16(cell->GetMoveCost());
		m_terrain_type = (sint8)TERRAIN_TYPES(cell->GetTerrain());
#ifdef BATTLE_FLAGS
		m_battleFlags = cell->GetBattleFlags();
#endif

		sint32 i;

		// Same as well information about existing
		// tile improvments, except roadlike ones,
		// so that this information is available
		// later as well.
		// And in order not to break anythink use the existing
		// list for unfinished tile improvements.
		for(i = 0; i < cell->GetNumDBImprovements(); i++) {
			sint32 imp = cell->GetDBImprovement(i);
			m_improvements->AddTail(new UnseenImprovementInfo(imp, 100));
		}
		for(i = 0; i < cell->GetNumImprovements(); i++) {
			TerrainImprovement imp = cell->AccessImprovement(i);
			if (imp.IsValid())
			{
				m_improvements->AddTail(new UnseenImprovementInfo(imp.GetType(),
															      imp.PercentComplete()));
			}
		}

		DynamicArray<Installation> instArray;
		g_theInstallationTree->GetAt(point, instArray);
		for(i = 0; i < instArray.Num(); i++) {
			m_installations->AddTail(new UnseenInstallationInfo(instArray[i].GetType(),
														       instArray[i].GetVisibility()));
		}

		m_cell_owner = (sint8) cell->GetOwner();

		// Store the city that controlls this tile.
		m_visibleCityOwner = cell->GetCityOwner().m_id;

		Unit    city = cell->GetCity();

		if (city.IsValid())
		{
			m_citySize = (sint16)city.PopCount();
			m_citySpriteIndex = (sint16)city.CD()->GetDesiredSpriteIndex();
			const MBCHAR *name = city.GetName();
			m_cityName = new MBCHAR[strlen(name) + 1];
			strcpy(m_cityName, name);

			m_cityOwner = static_cast<sint16>(city.GetCityData()->GetOwner());

			CityData *cityData = city.GetData()->GetCityData();

			UnitActor *actor = city.GetActor();

			if (actor) {

				SpriteState *newSS = new SpriteState(city.GetSpriteState()->GetIndex());

				UnitActor *newActor = new UnitActor(newSS,
												    city,
												    city.GetType(),
												    point,
												    city.GetOwner(),
												    TRUE,
												    city.GetVisionRange(),
												    city.CD()->GetDesiredSpriteIndex());

				newActor->SetUnitVisibility((1 << g_selected_item->GetVisiblePlayer())
										    | actor->GetUnitVisibility());
				newActor->SetPos(point);

				newActor->SetIsFortified(actor->IsFortified());
				newActor->SetIsFortifying(actor->IsFortifying());
				newActor->SetHasCityWalls(actor->HasCityWalls());
				newActor->SetHasForceField(actor->HasForceField());

				newActor->SetSize(m_citySize);

				newActor->ChangeImage(newSS, city.GetType(), city);

				newActor->AddIdle();
				newActor->GetNextAction();

				m_actor = newActor;
			} // actor

			SetIsBioInfected(cityData->IsBioInfected());
			SetIsNanoInfected(cityData->IsNanoInfected());
			SetIsConverted(cityData->IsConverted());
			SetIsFranchised(cityData->IsFranchised());
			SetIsInjoined(cityData->IsInjoined());
			SetWasHappinessAttacked(cityData->WasHappinessAttacked());
			SetIsRioting(cityData->GetIsRioting());
			SetHasAirport(cityData->HasAirport());
			SetHasSleepingUnits(cityData->HasSleepingUnits());
			SetIsWatchful(cityData->IsWatchful());
			SetIsCapitol(cityData->IsCapitol()); //emod
			SetIsReligionIcon(cityData->HasReligionIcon()); //emod
			m_bioInfectedOwner = (sint8)cityData->GetBioInfectedBy();
			m_nanoInfectedOwner = (sint8)cityData->GetNanoInfectedBy();
			m_convertedOwner = (sint8)cityData->IsConvertedTo();
			m_franchiseOwner = (sint8)cityData->GetFranchiseOwner();
			m_injoinedOwner = (sint8)cityData->InjoinedBy();
			m_happinessAttackOwner = (sint8)cityData->GetHappinessAttackedBy();
			m_slaveBits = cityData->GetSlaveBits();
			SetIsSpecialIcon(cityData->HasSpecialIcon()); //emod

		    sint32 pollution = cityData->GetPollution();
			SetIsPollutionRisk(pollution > g_theConstDB->Get(0)->GetLocalPollutionLevel());

		} // city.IsValid
	} // cell

	SetHasHut(NULL != g_theWorld->GetGoodyHut(point));
}
Пример #18
0
 bool CheckProc(ProcEventInfo& eventInfo)
 {
     Unit* actionTarget = eventInfo.GetActionTarget();
     return actionTarget && actionTarget->GetCreatureType() == CREATURE_TYPE_UNDEAD && actionTarget->GetOwner();
 }
Пример #19
0
int RebuildFrontList (int do_barcaps, int incremental)
{
	MissionRequestClass	mis;
	Objective			o,n;
	ulong				fseed;
	//static CampaignTime	lastRequest=0;
	//CampaignTime testLast;
	int					i,front,isolated,bok=0,dirty=0;

	// HACK to allow furball to work
	if (FalconLocalGame && FalconLocalGame->GetGameType() == game_Dogfight){
		return 0;
	}

	//TJL 11/14/03 Barcap timer and request interval were severely broken
	//lastRequest is now subtracted from CurrentTime.
	//Barcap Request also needed to be converted to milliseconds.  
	//if (do_barcaps && lastRequest - Camp_GetCurrentTime() > (unsigned int)BARCAP_REQUEST_INTERVAL)
	if (
		do_barcaps && 
		(Camp_GetCurrentTime() - lastRequest > ((unsigned int)BARCAP_REQUEST_INTERVAL * CampaignMinutes))
	){
		lastRequest = Camp_GetCurrentTime();
		bok = 1;
	}

	if (!incremental){
		FrontList->Purge();
	}

	{
		VuListIterator		myit(AllObjList);
		o = GetFirstObjective(&myit);
		while (o){
			front = 0;
			fseed = 0;
			isolated = 1;
			for (i=0,n=o; i<o->static_data.links && n && (!front || isolated); i++){
				n = o->GetNeighbor(i);
				if (n){
					if (GetTTRelations(o->GetTeam(),n->GetTeam()) > Neutral){
						front = n->GetOwner();
					}
					else if (isolated && !GetRoE(n->GetTeam(),o->GetTeam(),ROE_GROUND_CAPTURE)){
						isolated = 0;
					}
					if (bok && front && GetRoE(o->GetTeam(), n->GetTeam(), ROE_AIR_ENGAGE)){
						fseed = o->Id() + n->Id();
						mis.vs = n->GetTeam();
					}
				}
			}

			if (front && isolated && !o->IsSecondary()){
				// This objective has been cut off
				Unit		u;
				GridIndex	x,y;
				o->GetLocation(&x,&y);
				u = FindNearestRealUnit(x, y, NULL, 5);
				if (u && GetRoE(u->GetTeam(), o->GetTeam(), ROE_GROUND_CAPTURE)){
					front = u->GetOwner();
				}
				if (!u || (u && u->GetTeam() != o->GetTeam())){
					// Enemy units are in control, send a captured message
					CaptureObjective(o, (Control)front, NULL);
				}
			}

			if (!front){
				if (o->IsFrontline()){
					dirty = 1;
					if (incremental){
						FrontList->Remove(o);
					}
					o->ClearObjFlags (O_FRONTLINE | O_SECONDLINE | O_THIRDLINE);
				}
				o->SetAbandoned(0);
				fseed = 0;
			}
			else if (front){
				if (!o->IsFrontline()){
					dirty = 1;
					o->SetObjFlags (O_FRONTLINE);
					o->ClearObjFlags (O_SECONDLINE | O_THIRDLINE);
				}

				if (!incremental || !o->IsFrontline()){
					FrontList->ForcedInsert(o);
				}
			}

			//TJL 11/14/03 This is the BARCAP generator for the campaign. 
			if (fseed && do_barcaps){
				int barsweep = rand()%3;
				// Request a low priority BARCAP mission (each side should take care of their own)
				mis.requesterID = o->Id();
				o->GetLocation(&mis.tx,&mis.ty);
				mis.who = o->GetTeam();
				mis.vs = 0;
				// Try to base TOT on the combined ID of the two frontline objectives - 
				// to try and get both teams here at same time
				mis.tot = Camp_GetCurrentTime() + (60+fseed%60)*CampaignMinutes;
				mis.tot_type = TYPE_EQ;
				//Cobra This allows a variety of CAP missions
				if (barsweep == 1){
					mis.mission = AMIS_SWEEP;
				}
				else if (barsweep == 2){
					mis.mission = AMIS_BARCAP;
				}
				else {
					mis.mission = AMIS_BARCAP2;
				}
				mis.context = hostileAircraftPresent;
				mis.roe_check = ROE_AIR_ENGAGE;
				mis.flags = 0;
				mis.priority = 0;
				mis.RequestMission();
			}
			o = GetNextObjective(&myit);
		}
	}

	if (dirty){
		MarkObjectives();
		RebuildParentsList();
	}
	return dirty;
}