[7123] Cleanup in using STD's containers erase method.
[getmangos.git] / src / game / Group.cpp
blob3b411227d8e52ed564aad91e6aa2592157049d02
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Opcodes.h"
21 #include "WorldPacket.h"
22 #include "WorldSession.h"
23 #include "Player.h"
24 #include "World.h"
25 #include "ObjectMgr.h"
26 #include "Group.h"
27 #include "Formulas.h"
28 #include "ObjectAccessor.h"
29 #include "BattleGround.h"
30 #include "MapManager.h"
31 #include "InstanceSaveMgr.h"
32 #include "MapInstanced.h"
33 #include "Util.h"
35 Group::Group()
37 m_leaderGuid = 0;
38 m_mainTank = 0;
39 m_mainAssistant = 0;
40 m_groupType = (GroupType)0;
41 m_bgGroup = NULL;
42 m_lootMethod = (LootMethod)0;
43 m_looterGuid = 0;
44 m_lootThreshold = ITEM_QUALITY_UNCOMMON;
45 m_subGroupsCounts = NULL;
47 for(int i=0; i<TARGETICONCOUNT; i++)
48 m_targetIcons[i] = 0;
51 Group::~Group()
53 if(m_bgGroup)
55 sLog.outDebug("Group::~Group: battleground group being deleted.");
56 if(m_bgGroup->GetBgRaid(ALLIANCE) == this) m_bgGroup->SetBgRaid(ALLIANCE, NULL);
57 else if(m_bgGroup->GetBgRaid(HORDE) == this) m_bgGroup->SetBgRaid(HORDE, NULL);
58 else sLog.outError("Group::~Group: battleground group is not linked to the correct battleground.");
60 Rolls::iterator itr;
61 while(!RollId.empty())
63 itr = RollId.begin();
64 Roll *r = *itr;
65 RollId.erase(itr);
66 delete(r);
69 // it is undefined whether objectmgr (which stores the groups) or instancesavemgr
70 // will be unloaded first so we must be prepared for both cases
71 // this may unload some instance saves
72 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
73 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
74 itr->second.save->RemoveGroup(this);
76 // Sub group counters clean up
77 if (m_subGroupsCounts)
78 delete[] m_subGroupsCounts;
81 bool Group::Create(const uint64 &guid, const char * name)
83 m_leaderGuid = guid;
84 m_leaderName = name;
86 m_groupType = isBGGroup() ? GROUPTYPE_RAID : GROUPTYPE_NORMAL;
88 if (m_groupType == GROUPTYPE_RAID)
89 _initRaidSubGroupsCounter();
91 m_lootMethod = GROUP_LOOT;
92 m_lootThreshold = ITEM_QUALITY_UNCOMMON;
93 m_looterGuid = guid;
95 m_difficulty = DIFFICULTY_NORMAL;
96 if(!isBGGroup())
98 Player *leader = objmgr.GetPlayer(guid);
99 if(leader) m_difficulty = leader->GetDifficulty();
101 Player::ConvertInstancesToGroup(leader, this, guid);
103 // store group in database
104 CharacterDatabase.BeginTransaction();
105 CharacterDatabase.PExecute("DELETE FROM groups WHERE leaderGuid ='%u'", GUID_LOPART(m_leaderGuid));
106 CharacterDatabase.PExecute("DELETE FROM group_member WHERE leaderGuid ='%u'", GUID_LOPART(m_leaderGuid));
107 CharacterDatabase.PExecute("INSERT INTO groups(leaderGuid,mainTank,mainAssistant,lootMethod,looterGuid,lootThreshold,icon1,icon2,icon3,icon4,icon5,icon6,icon7,icon8,isRaid,difficulty) "
108 "VALUES('%u','%u','%u','%u','%u','%u','" I64FMTD "','" I64FMTD "','" I64FMTD "','" I64FMTD "','" I64FMTD "','" I64FMTD "','" I64FMTD "','" I64FMTD "','%u','%u')",
109 GUID_LOPART(m_leaderGuid), GUID_LOPART(m_mainTank), GUID_LOPART(m_mainAssistant), uint32(m_lootMethod),
110 GUID_LOPART(m_looterGuid), uint32(m_lootThreshold), m_targetIcons[0], m_targetIcons[1], m_targetIcons[2], m_targetIcons[3], m_targetIcons[4], m_targetIcons[5], m_targetIcons[6], m_targetIcons[7], isRaidGroup(), m_difficulty);
113 if(!AddMember(guid, name))
114 return false;
116 if(!isBGGroup()) CharacterDatabase.CommitTransaction();
118 return true;
121 bool Group::LoadGroupFromDB(const uint64 &leaderGuid, QueryResult *result, bool loadMembers)
123 if(isBGGroup())
124 return false;
126 bool external = true;
127 if(!result)
129 external = false;
130 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
131 result = CharacterDatabase.PQuery("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty FROM groups WHERE leaderGuid ='%u'", GUID_LOPART(leaderGuid));
132 if(!result)
133 return false;
136 m_leaderGuid = leaderGuid;
138 // group leader not exist
139 if(!objmgr.GetPlayerNameByGUID(m_leaderGuid, m_leaderName))
141 if(!external) delete result;
142 return false;
145 m_groupType = (*result)[13].GetBool() ? GROUPTYPE_RAID : GROUPTYPE_NORMAL;
147 if (m_groupType == GROUPTYPE_RAID)
148 _initRaidSubGroupsCounter();
150 m_difficulty = (*result)[14].GetUInt8();
151 m_mainTank = (*result)[0].GetUInt64();
152 m_mainAssistant = (*result)[1].GetUInt64();
153 m_lootMethod = (LootMethod)(*result)[2].GetUInt8();
154 m_looterGuid = MAKE_NEW_GUID((*result)[3].GetUInt32(), 0, HIGHGUID_PLAYER);
155 m_lootThreshold = (ItemQualities)(*result)[4].GetUInt16();
157 for(int i=0; i<TARGETICONCOUNT; i++)
158 m_targetIcons[i] = (*result)[5+i].GetUInt64();
159 if(!external) delete result;
161 if(loadMembers)
163 result = CharacterDatabase.PQuery("SELECT memberGuid, assistant, subgroup FROM group_member WHERE leaderGuid ='%u'", GUID_LOPART(leaderGuid));
164 if(!result)
165 return false;
169 LoadMemberFromDB((*result)[0].GetUInt32(), (*result)[2].GetUInt8(), (*result)[1].GetBool());
170 } while( result->NextRow() );
171 delete result;
172 // group too small
173 if(GetMembersCount() < 2)
174 return false;
177 return true;
180 bool Group::LoadMemberFromDB(uint32 guidLow, uint8 subgroup, bool assistant)
182 MemberSlot member;
183 member.guid = MAKE_NEW_GUID(guidLow, 0, HIGHGUID_PLAYER);
185 // skip non-existed member
186 if(!objmgr.GetPlayerNameByGUID(member.guid, member.name))
187 return false;
189 member.group = subgroup;
190 member.assistant = assistant;
191 m_memberSlots.push_back(member);
193 SubGroupCounterIncrease(subgroup);
195 return true;
198 void Group::ConvertToRaid()
200 m_groupType = GROUPTYPE_RAID;
202 _initRaidSubGroupsCounter();
204 if(!isBGGroup()) CharacterDatabase.PExecute("UPDATE groups SET isRaid = 1 WHERE leaderGuid='%u'", GUID_LOPART(m_leaderGuid));
205 SendUpdate();
208 bool Group::AddInvite(Player *player)
210 if(!player || player->GetGroupInvite() || player->GetGroup())
211 return false;
213 RemoveInvite(player);
215 m_invitees.insert(player);
217 player->SetGroupInvite(this);
219 return true;
222 bool Group::AddLeaderInvite(Player *player)
224 if(!AddInvite(player))
225 return false;
227 m_leaderGuid = player->GetGUID();
228 m_leaderName = player->GetName();
229 return true;
232 uint32 Group::RemoveInvite(Player *player)
234 m_invitees.erase(player);
236 player->SetGroupInvite(NULL);
237 return GetMembersCount();
240 void Group::RemoveAllInvites()
242 for(InvitesList::iterator itr=m_invitees.begin(); itr!=m_invitees.end(); ++itr)
243 (*itr)->SetGroupInvite(NULL);
245 m_invitees.clear();
248 Player* Group::GetInvited(const uint64& guid) const
250 for(InvitesList::const_iterator itr = m_invitees.begin(); itr != m_invitees.end(); ++itr)
252 if((*itr)->GetGUID() == guid)
253 return (*itr);
255 return NULL;
258 Player* Group::GetInvited(const std::string& name) const
260 for(InvitesList::const_iterator itr = m_invitees.begin(); itr != m_invitees.end(); ++itr)
262 if((*itr)->GetName() == name)
263 return (*itr);
265 return NULL;
268 bool Group::AddMember(const uint64 &guid, const char* name)
270 if(!_addMember(guid, name))
271 return false;
272 SendUpdate();
274 Player *player = objmgr.GetPlayer(guid);
275 if(player)
277 if(!IsLeader(player->GetGUID()) && !isBGGroup())
279 // reset the new member's instances, unless he is currently in one of them
280 // including raid/heroic instances that they are not permanently bound to!
281 player->ResetInstances(INSTANCE_RESET_GROUP_JOIN);
283 if(player->getLevel() >= LEVELREQUIREMENT_HEROIC && player->GetDifficulty() != GetDifficulty() )
285 player->SetDifficulty(m_difficulty);
286 player->SendDungeonDifficulty(true);
289 player->SetGroupUpdateFlag(GROUP_UPDATE_FULL);
290 UpdatePlayerOutOfRange(player);
293 return true;
296 uint32 Group::RemoveMember(const uint64 &guid, const uint8 &method)
298 // remove member and change leader (if need) only if strong more 2 members _before_ member remove
299 if(GetMembersCount() > (isBGGroup() ? 1 : 2)) // in BG group case allow 1 members group
301 bool leaderChanged = _removeMember(guid);
303 Player *player = objmgr.GetPlayer( guid );
304 if (player)
306 WorldPacket data;
308 if(method == 1)
310 data.Initialize( SMSG_GROUP_UNINVITE, 0 );
311 player->GetSession()->SendPacket( &data );
314 data.Initialize(SMSG_GROUP_LIST, 24);
315 data << uint64(0) << uint64(0) << uint64(0);
316 player->GetSession()->SendPacket(&data);
318 _homebindIfInstance(player);
321 if(leaderChanged)
323 WorldPacket data(SMSG_GROUP_SET_LEADER, (m_memberSlots.front().name.size()+1));
324 data << m_memberSlots.front().name;
325 BroadcastPacket(&data);
328 SendUpdate();
330 // if group before remove <= 2 disband it
331 else
332 Disband(true);
334 return m_memberSlots.size();
337 void Group::ChangeLeader(const uint64 &guid)
339 member_citerator slot = _getMemberCSlot(guid);
341 if(slot==m_memberSlots.end())
342 return;
344 _setLeader(guid);
346 WorldPacket data(SMSG_GROUP_SET_LEADER, slot->name.size()+1);
347 data << slot->name;
348 BroadcastPacket(&data);
349 SendUpdate();
352 void Group::Disband(bool hideDestroy)
354 Player *player;
356 for(member_citerator citr = m_memberSlots.begin(); citr != m_memberSlots.end(); ++citr)
358 player = objmgr.GetPlayer(citr->guid);
359 if(!player)
360 continue;
362 player->SetGroup(NULL);
364 if(!player->GetSession())
365 continue;
367 WorldPacket data;
368 if(!hideDestroy)
370 data.Initialize(SMSG_GROUP_DESTROYED, 0);
371 player->GetSession()->SendPacket(&data);
374 data.Initialize(SMSG_GROUP_LIST, 24);
375 data << uint64(0) << uint64(0) << uint64(0);
376 player->GetSession()->SendPacket(&data);
378 _homebindIfInstance(player);
380 RollId.clear();
381 m_memberSlots.clear();
383 RemoveAllInvites();
385 if(!isBGGroup())
387 CharacterDatabase.BeginTransaction();
388 CharacterDatabase.PExecute("DELETE FROM groups WHERE leaderGuid='%u'", GUID_LOPART(m_leaderGuid));
389 CharacterDatabase.PExecute("DELETE FROM group_member WHERE leaderGuid='%u'", GUID_LOPART(m_leaderGuid));
390 CharacterDatabase.CommitTransaction();
391 ResetInstances(INSTANCE_RESET_GROUP_DISBAND, NULL);
394 m_leaderGuid = 0;
395 m_leaderName = "";
398 /*********************************************************/
399 /*** LOOT SYSTEM ***/
400 /*********************************************************/
402 void Group::SendLootStartRoll(uint32 CountDown, const Roll &r)
404 WorldPacket data(SMSG_LOOT_START_ROLL, (8+4+4+4+4+4));
405 data << uint64(r.itemGUID); // guid of rolled item
406 data << uint32(r.totalPlayersRolling); // maybe the number of players rolling for it???
407 data << uint32(r.itemid); // the itemEntryId for the item that shall be rolled for
408 data << uint32(r.itemRandomSuffix); // randomSuffix
409 data << uint32(r.itemRandomPropId); // item random property ID
410 data << uint32(CountDown); // the countdown time to choose "need" or "greed"
412 for (Roll::PlayerVote::const_iterator itr=r.playerVote.begin(); itr!=r.playerVote.end(); ++itr)
414 Player *p = objmgr.GetPlayer(itr->first);
415 if(!p || !p->GetSession())
416 continue;
418 if(itr->second != NOT_VALID)
419 p->GetSession()->SendPacket( &data );
423 void Group::SendLootRoll(const uint64& SourceGuid, const uint64& TargetGuid, uint8 RollNumber, uint8 RollType, const Roll &r)
425 WorldPacket data(SMSG_LOOT_ROLL, (8+4+8+4+4+4+1+1));
426 data << uint64(SourceGuid); // guid of the item rolled
427 data << uint32(0); // unknown, maybe amount of players
428 data << uint64(TargetGuid);
429 data << uint32(r.itemid); // the itemEntryId for the item that shall be rolled for
430 data << uint32(r.itemRandomSuffix); // randomSuffix
431 data << uint32(r.itemRandomPropId); // Item random property ID
432 data << uint8(RollNumber); // 0: "Need for: [item name]" > 127: "you passed on: [item name]" Roll number
433 data << uint8(RollType); // 0: "Need for: [item name]" 0: "You have selected need for [item name] 1: need roll 2: greed roll
434 data << uint8(0); // 2.4.0
436 for( Roll::PlayerVote::const_iterator itr=r.playerVote.begin(); itr!=r.playerVote.end(); ++itr)
438 Player *p = objmgr.GetPlayer(itr->first);
439 if(!p || !p->GetSession())
440 continue;
442 if(itr->second != NOT_VALID)
443 p->GetSession()->SendPacket( &data );
447 void Group::SendLootRollWon(const uint64& SourceGuid, const uint64& TargetGuid, uint8 RollNumber, uint8 RollType, const Roll &r)
449 WorldPacket data(SMSG_LOOT_ROLL_WON, (8+4+4+4+4+8+1+1));
450 data << uint64(SourceGuid); // guid of the item rolled
451 data << uint32(0); // unknown, maybe amount of players
452 data << uint32(r.itemid); // the itemEntryId for the item that shall be rolled for
453 data << uint32(r.itemRandomSuffix); // randomSuffix
454 data << uint32(r.itemRandomPropId); // Item random property
455 data << uint64(TargetGuid); // guid of the player who won.
456 data << uint8(RollNumber); // rollnumber realted to SMSG_LOOT_ROLL
457 data << uint8(RollType); // Rolltype related to SMSG_LOOT_ROLL
459 for( Roll::PlayerVote::const_iterator itr=r.playerVote.begin(); itr!=r.playerVote.end(); ++itr)
461 Player *p = objmgr.GetPlayer(itr->first);
462 if(!p || !p->GetSession())
463 continue;
465 if(itr->second != NOT_VALID)
466 p->GetSession()->SendPacket( &data );
470 void Group::SendLootAllPassed(uint32 NumberOfPlayers, const Roll &r)
472 WorldPacket data(SMSG_LOOT_ALL_PASSED, (8+4+4+4+4));
473 data << uint64(r.itemGUID); // Guid of the item rolled
474 data << uint32(NumberOfPlayers); // The number of players rolling for it???
475 data << uint32(r.itemid); // The itemEntryId for the item that shall be rolled for
476 data << uint32(r.itemRandomPropId); // Item random property ID
477 data << uint32(r.itemRandomSuffix); // Item random suffix ID
479 for( Roll::PlayerVote::const_iterator itr=r.playerVote.begin(); itr!=r.playerVote.end(); ++itr)
481 Player *p = objmgr.GetPlayer(itr->first);
482 if(!p || !p->GetSession())
483 continue;
485 if(itr->second != NOT_VALID)
486 p->GetSession()->SendPacket( &data );
490 void Group::GroupLoot(const uint64& playerGUID, Loot *loot, Creature *creature)
492 std::vector<LootItem>::iterator i;
493 ItemPrototype const *item;
494 uint8 itemSlot = 0;
495 Player *player = objmgr.GetPlayer(playerGUID);
496 Group *group = player->GetGroup();
498 for (i=loot->items.begin(); i != loot->items.end(); ++i, ++itemSlot)
500 item = objmgr.GetItemPrototype(i->itemid);
501 if (!item)
503 //sLog.outDebug("Group::GroupLoot: missing item prototype for item with id: %d", i->itemid);
504 continue;
507 //roll for over-threshold item if it's one-player loot
508 if (item->Quality >= uint32(m_lootThreshold) && !i->freeforall)
510 uint64 newitemGUID = MAKE_NEW_GUID(objmgr.GenerateLowGuid(HIGHGUID_ITEM),0,HIGHGUID_ITEM);
511 Roll* r=new Roll(newitemGUID,*i);
513 //a vector is filled with only near party members
514 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
516 Player *member = itr->getSource();
517 if(!member || !member->GetSession())
518 continue;
519 if ( i->AllowedForPlayer(member) )
521 if (member->GetDistance2d(creature) < sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
523 r->playerVote[member->GetGUID()] = NOT_EMITED_YET;
524 ++r->totalPlayersRolling;
529 r->setLoot(loot);
530 r->itemSlot = itemSlot;
532 group->SendLootStartRoll(60000, *r);
534 loot->items[itemSlot].is_blocked = true;
535 creature->m_groupLootTimer = 60000;
536 creature->lootingGroupLeaderGUID = GetLeaderGUID();
538 RollId.push_back(r);
540 else
541 i->is_underthreshold=1;
546 void Group::NeedBeforeGreed(const uint64& playerGUID, Loot *loot, Creature *creature)
548 ItemPrototype const *item;
549 Player *player = objmgr.GetPlayer(playerGUID);
550 Group *group = player->GetGroup();
552 uint8 itemSlot = 0;
553 for(std::vector<LootItem>::iterator i=loot->items.begin(); i != loot->items.end(); ++i, ++itemSlot)
555 item = objmgr.GetItemPrototype(i->itemid);
557 //only roll for one-player items, not for ones everyone can get
558 if (item->Quality >= uint32(m_lootThreshold) && !i->freeforall)
560 uint64 newitemGUID = MAKE_NEW_GUID(objmgr.GenerateLowGuid(HIGHGUID_ITEM),0,HIGHGUID_ITEM);
561 Roll* r=new Roll(newitemGUID,*i);
563 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
565 Player *playerToRoll = itr->getSource();
566 if(!playerToRoll || !playerToRoll->GetSession())
567 continue;
569 if (playerToRoll->CanUseItem(item) && i->AllowedForPlayer(playerToRoll) )
571 if (playerToRoll->GetDistance2d(creature) < sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
573 r->playerVote[playerToRoll->GetGUID()] = NOT_EMITED_YET;
574 ++r->totalPlayersRolling;
579 if (r->totalPlayersRolling > 0)
581 r->setLoot(loot);
582 r->itemSlot = itemSlot;
584 group->SendLootStartRoll(60000, *r);
586 loot->items[itemSlot].is_blocked = true;
588 RollId.push_back(r);
590 else
592 delete r;
595 else
596 i->is_underthreshold=1;
600 void Group::MasterLoot(const uint64& playerGUID, Loot* /*loot*/, Creature *creature)
602 Player *player = objmgr.GetPlayer(playerGUID);
603 if(!player)
604 return;
606 sLog.outDebug("Group::MasterLoot (SMSG_LOOT_MASTER_LIST, 330) player = [%s].", player->GetName());
608 uint32 real_count = 0;
610 WorldPacket data(SMSG_LOOT_MASTER_LIST, 330);
611 data << (uint8)GetMembersCount();
613 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
615 Player *looter = itr->getSource();
616 if (!looter->IsInWorld())
617 continue;
619 if (looter->GetDistance2d(creature) < sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
621 data << looter->GetGUID();
622 ++real_count;
626 data.put<uint8>(0,real_count);
628 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
630 Player *looter = itr->getSource();
631 if (looter->GetDistance2d(creature) < sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
632 looter->GetSession()->SendPacket(&data);
636 void Group::CountRollVote(const uint64& playerGUID, const uint64& Guid, uint32 NumberOfPlayers, uint8 Choise)
638 Rolls::iterator rollI = GetRoll(Guid);
639 if (rollI == RollId.end())
640 return;
641 Roll* roll = *rollI;
643 Roll::PlayerVote::iterator itr = roll->playerVote.find(playerGUID);
644 // this condition means that player joins to the party after roll begins
645 if (itr == roll->playerVote.end())
646 return;
648 if (roll->getLoot())
649 if (roll->getLoot()->items.empty())
650 return;
652 switch (Choise)
654 case 0: //Player choose pass
656 SendLootRoll(0, playerGUID, 128, 128, *roll);
657 ++roll->totalPass;
658 itr->second = PASS;
660 break;
661 case 1: //player choose Need
663 SendLootRoll(0, playerGUID, 0, 0, *roll);
664 ++roll->totalNeed;
665 itr->second = NEED;
667 break;
668 case 2: //player choose Greed
670 SendLootRoll(0, playerGUID, 128, 2, *roll);
671 ++roll->totalGreed;
672 itr->second = GREED;
674 break;
676 if (roll->totalPass + roll->totalGreed + roll->totalNeed >= roll->totalPlayersRolling)
678 CountTheRoll(rollI, NumberOfPlayers);
682 //called when roll timer expires
683 void Group::EndRoll()
685 Rolls::iterator itr;
686 while(!RollId.empty())
688 //need more testing here, if rolls disappear
689 itr = RollId.begin();
690 CountTheRoll(itr, GetMembersCount()); //i don't have to edit player votes, who didn't vote ... he will pass
694 void Group::CountTheRoll(Rolls::iterator rollI, uint32 NumberOfPlayers)
696 Roll* roll = *rollI;
697 if(!roll->isValid()) // is loot already deleted ?
699 RollId.erase(rollI);
700 delete roll;
701 return;
703 //end of the roll
704 if (roll->totalNeed > 0)
706 if(!roll->playerVote.empty())
708 uint8 maxresul = 0;
709 uint64 maxguid = (*roll->playerVote.begin()).first;
710 Player *player;
712 for( Roll::PlayerVote::const_iterator itr=roll->playerVote.begin(); itr!=roll->playerVote.end(); ++itr)
714 if (itr->second != NEED)
715 continue;
717 uint8 randomN = urand(1, 99);
718 SendLootRoll(0, itr->first, randomN, 1, *roll);
719 if (maxresul < randomN)
721 maxguid = itr->first;
722 maxresul = randomN;
725 SendLootRollWon(0, maxguid, maxresul, 1, *roll);
726 player = objmgr.GetPlayer(maxguid);
728 if(player && player->GetSession())
730 player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT, roll->itemid, maxresul);
732 ItemPosCountVec dest;
733 LootItem *item = &(roll->getLoot()->items[roll->itemSlot]);
734 uint8 msg = player->CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, roll->itemid, item->count );
735 if ( msg == EQUIP_ERR_OK )
737 item->is_looted = true;
738 roll->getLoot()->NotifyItemRemoved(roll->itemSlot);
739 --roll->getLoot()->unlootedCount;
740 player->StoreNewItem( dest, roll->itemid, true, item->randomPropertyId);
742 else
744 item->is_blocked = false;
745 player->SendEquipError( msg, NULL, NULL );
750 else if (roll->totalGreed > 0)
752 if(!roll->playerVote.empty())
754 uint8 maxresul = 0;
755 uint64 maxguid = (*roll->playerVote.begin()).first;
756 Player *player;
758 Roll::PlayerVote::iterator itr;
759 for (itr=roll->playerVote.begin(); itr!=roll->playerVote.end(); ++itr)
761 if (itr->second != GREED)
762 continue;
764 uint8 randomN = urand(1, 99);
765 SendLootRoll(0, itr->first, randomN, 2, *roll);
766 if (maxresul < randomN)
768 maxguid = itr->first;
769 maxresul = randomN;
772 SendLootRollWon(0, maxguid, maxresul, 2, *roll);
773 player = objmgr.GetPlayer(maxguid);
775 if(player && player->GetSession())
777 player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT, roll->itemid, maxresul);
779 ItemPosCountVec dest;
780 LootItem *item = &(roll->getLoot()->items[roll->itemSlot]);
781 uint8 msg = player->CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, roll->itemid, item->count );
782 if ( msg == EQUIP_ERR_OK )
784 item->is_looted = true;
785 roll->getLoot()->NotifyItemRemoved(roll->itemSlot);
786 --roll->getLoot()->unlootedCount;
787 player->StoreNewItem( dest, roll->itemid, true, item->randomPropertyId);
789 else
791 item->is_blocked = false;
792 player->SendEquipError( msg, NULL, NULL );
797 else
799 SendLootAllPassed(NumberOfPlayers, *roll);
800 LootItem *item = &(roll->getLoot()->items[roll->itemSlot]);
801 if(item) item->is_blocked = false;
803 RollId.erase(rollI);
804 delete roll;
807 void Group::SetTargetIcon(uint8 id, uint64 guid)
809 if(id >= TARGETICONCOUNT)
810 return;
812 // clean other icons
813 if( guid != 0 )
814 for(int i=0; i<TARGETICONCOUNT; i++)
815 if( m_targetIcons[i] == guid )
816 SetTargetIcon(i, 0);
818 m_targetIcons[id] = guid;
820 WorldPacket data(MSG_RAID_TARGET_UPDATE, (2+8));
821 data << (uint8)0;
822 data << id;
823 data << guid;
824 BroadcastPacket(&data);
827 void Group::GetDataForXPAtKill(Unit const* victim, uint32& count,uint32& sum_level, Player* & member_with_max_level, Player* & not_gray_member_with_max_level)
829 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
831 Player* member = itr->getSource();
832 if(!member || !member->isAlive()) // only for alive
833 continue;
835 if(!member->IsAtGroupRewardDistance(victim)) // at req. distance
836 continue;
838 ++count;
839 sum_level += member->getLevel();
840 if(!member_with_max_level || member_with_max_level->getLevel() < member->getLevel())
841 member_with_max_level = member;
843 uint32 gray_level = MaNGOS::XP::GetGrayLevel(member->getLevel());
844 if( victim->getLevel() > gray_level && (!not_gray_member_with_max_level
845 || not_gray_member_with_max_level->getLevel() < member->getLevel()))
846 not_gray_member_with_max_level = member;
850 void Group::SendTargetIconList(WorldSession *session)
852 if(!session)
853 return;
855 WorldPacket data(MSG_RAID_TARGET_UPDATE, (1+TARGETICONCOUNT*9));
856 data << (uint8)1;
858 for(int i=0; i<TARGETICONCOUNT; i++)
860 if(m_targetIcons[i] == 0)
861 continue;
863 data << (uint8)i;
864 data << m_targetIcons[i];
867 session->SendPacket(&data);
870 void Group::SendUpdate()
872 Player *player;
874 for(member_citerator citr = m_memberSlots.begin(); citr != m_memberSlots.end(); ++citr)
876 player = objmgr.GetPlayer(citr->guid);
877 if(!player || !player->GetSession())
878 continue;
879 // guess size
880 WorldPacket data(SMSG_GROUP_LIST, (1+1+1+1+8+4+GetMembersCount()*20));
881 data << (uint8)m_groupType; // group type
882 data << (uint8)(isBGGroup() ? 1 : 0); // 2.0.x, isBattleGroundGroup?
883 data << (uint8)(citr->group); // groupid
884 data << (uint8)(citr->assistant?0x01:0); // 0x2 main assist, 0x4 main tank
885 data << uint64(0x50000000FFFFFFFELL); // related to voice chat?
886 data << uint32(GetMembersCount()-1);
887 for(member_citerator citr2 = m_memberSlots.begin(); citr2 != m_memberSlots.end(); ++citr2)
889 if(citr->guid == citr2->guid)
890 continue;
892 data << citr2->name;
893 data << (uint64)citr2->guid;
894 // online-state
895 data << (uint8)(objmgr.GetPlayer(citr2->guid) ? 1 : 0);
896 data << (uint8)(citr2->group); // groupid
897 data << (uint8)(citr2->assistant?0x01:0); // 0x2 main assist, 0x4 main tank
900 data << uint64(m_leaderGuid); // leader guid
901 if(GetMembersCount()-1)
903 data << (uint8)m_lootMethod; // loot method
904 data << (uint64)m_looterGuid; // looter guid
905 data << (uint8)m_lootThreshold; // loot threshold
906 data << (uint8)m_difficulty; // Heroic Mod Group
908 player->GetSession()->SendPacket( &data );
912 void Group::UpdatePlayerOutOfRange(Player* pPlayer)
914 if(!pPlayer)
915 return;
917 Player *player;
918 WorldPacket data;
919 pPlayer->GetSession()->BuildPartyMemberStatsChangedPacket(pPlayer, &data);
921 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
923 player = itr->getSource();
924 if (player && player != pPlayer && !pPlayer->isVisibleFor(player))
925 player->GetSession()->SendPacket(&data);
929 void Group::BroadcastPacket(WorldPacket *packet, int group, uint64 ignore)
931 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
933 Player *pl = itr->getSource();
934 if(!pl || (ignore != 0 && pl->GetGUID() == ignore))
935 continue;
937 if (pl->GetSession() && (group==-1 || itr->getSubGroup()==group))
938 pl->GetSession()->SendPacket(packet);
942 void Group::BroadcastReadyCheck(WorldPacket *packet)
944 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
946 Player *pl = itr->getSource();
947 if(pl && pl->GetSession())
948 if(IsLeader(pl->GetGUID()) || IsAssistant(pl->GetGUID()))
949 pl->GetSession()->SendPacket(packet);
953 void Group::OfflineReadyCheck()
955 for(member_citerator citr = m_memberSlots.begin(); citr != m_memberSlots.end(); ++citr)
957 Player *pl = objmgr.GetPlayer(citr->guid);
958 if (!pl || !pl->GetSession())
960 WorldPacket data(MSG_RAID_READY_CHECK_CONFIRM, 9);
961 data << citr->guid;
962 data << (uint8)0;
963 BroadcastReadyCheck(&data);
968 bool Group::_addMember(const uint64 &guid, const char* name, bool isAssistant)
970 // get first not-full group
971 uint8 groupid = 0;
972 if (m_subGroupsCounts)
974 bool groupFound = false;
975 for (; groupid < MAXRAIDSIZE/MAXGROUPSIZE; ++groupid)
977 if (m_subGroupsCounts[groupid] < MAXGROUPSIZE)
979 groupFound = true;
980 break;
983 // We are raid group and no one slot is free
984 if (!groupFound)
985 return false;
988 return _addMember(guid, name, isAssistant, groupid);
991 bool Group::_addMember(const uint64 &guid, const char* name, bool isAssistant, uint8 group)
993 if(IsFull())
994 return false;
996 if(!guid)
997 return false;
999 Player *player = objmgr.GetPlayer(guid);
1001 MemberSlot member;
1002 member.guid = guid;
1003 member.name = name;
1004 member.group = group;
1005 member.assistant = isAssistant;
1006 m_memberSlots.push_back(member);
1008 SubGroupCounterIncrease(group);
1010 if(player)
1012 player->SetGroupInvite(NULL);
1013 player->SetGroup(this, group);
1014 // if the same group invites the player back, cancel the homebind timer
1015 InstanceGroupBind *bind = GetBoundInstance(player->GetMapId(), player->GetDifficulty());
1016 if(bind && bind->save->GetInstanceId() == player->GetInstanceId())
1017 player->m_InstanceValid = true;
1020 if(!isRaidGroup()) // reset targetIcons for non-raid-groups
1022 for(int i=0; i<TARGETICONCOUNT; i++)
1023 m_targetIcons[i] = 0;
1026 if(!isBGGroup())
1028 // insert into group table
1029 CharacterDatabase.PExecute("INSERT INTO group_member(leaderGuid,memberGuid,assistant,subgroup) VALUES('%u','%u','%u','%u')", GUID_LOPART(m_leaderGuid), GUID_LOPART(member.guid), ((member.assistant==1)?1:0), member.group);
1032 return true;
1035 bool Group::_removeMember(const uint64 &guid)
1037 Player *player = objmgr.GetPlayer(guid);
1038 if (player)
1040 player->SetGroup(NULL);
1043 _removeRolls(guid);
1045 member_witerator slot = _getMemberWSlot(guid);
1046 if (slot != m_memberSlots.end())
1048 SubGroupCounterDecrease(slot->group);
1050 m_memberSlots.erase(slot);
1053 if(!isBGGroup())
1054 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid='%u'", GUID_LOPART(guid));
1056 if(m_leaderGuid == guid) // leader was removed
1058 if(GetMembersCount() > 0)
1059 _setLeader(m_memberSlots.front().guid);
1060 return true;
1063 return false;
1066 void Group::_setLeader(const uint64 &guid)
1068 member_citerator slot = _getMemberCSlot(guid);
1069 if(slot==m_memberSlots.end())
1070 return;
1072 if(!isBGGroup())
1074 // TODO: set a time limit to have this function run rarely cause it can be slow
1075 CharacterDatabase.BeginTransaction();
1077 // update the group's bound instances when changing leaders
1079 // remove all permanent binds from the group
1080 // in the DB also remove solo binds that will be replaced with permbinds
1081 // from the new leader
1082 CharacterDatabase.PExecute(
1083 "DELETE FROM group_instance WHERE leaderguid='%u' AND (permanent = 1 OR "
1084 "instance IN (SELECT instance FROM character_instance WHERE guid = '%u')"
1085 ")", GUID_LOPART(m_leaderGuid), GUID_LOPART(slot->guid)
1088 Player *player = objmgr.GetPlayer(slot->guid);
1089 if(player)
1091 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
1093 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end();)
1095 if(itr->second.perm)
1097 itr->second.save->RemoveGroup(this);
1098 m_boundInstances[i].erase(itr++);
1100 else
1101 ++itr;
1106 // update the group's solo binds to the new leader
1107 CharacterDatabase.PExecute("UPDATE group_instance SET leaderGuid='%u' WHERE leaderGuid = '%u'", GUID_LOPART(slot->guid), GUID_LOPART(m_leaderGuid));
1109 // copy the permanent binds from the new leader to the group
1110 // overwriting the solo binds with permanent ones if necessary
1111 // in the DB those have been deleted already
1112 Player::ConvertInstancesToGroup(player, this, slot->guid);
1114 // update the group leader
1115 CharacterDatabase.PExecute("UPDATE groups SET leaderGuid='%u' WHERE leaderGuid='%u'", GUID_LOPART(slot->guid), GUID_LOPART(m_leaderGuid));
1116 CharacterDatabase.PExecute("UPDATE group_member SET leaderGuid='%u' WHERE leaderGuid='%u'", GUID_LOPART(slot->guid), GUID_LOPART(m_leaderGuid));
1117 CharacterDatabase.CommitTransaction();
1120 m_leaderGuid = slot->guid;
1121 m_leaderName = slot->name;
1124 void Group::_removeRolls(const uint64 &guid)
1126 for (Rolls::iterator it = RollId.begin(); it < RollId.end(); ++it)
1128 Roll* roll = *it;
1129 Roll::PlayerVote::iterator itr2 = roll->playerVote.find(guid);
1130 if(itr2 == roll->playerVote.end())
1131 continue;
1133 if (itr2->second == GREED) --roll->totalGreed;
1134 if (itr2->second == NEED) --roll->totalNeed;
1135 if (itr2->second == PASS) --roll->totalPass;
1136 if (itr2->second != NOT_VALID) --roll->totalPlayersRolling;
1138 roll->playerVote.erase(itr2);
1140 CountRollVote(guid, roll->itemGUID, GetMembersCount()-1, 3);
1144 bool Group::_setMembersGroup(const uint64 &guid, const uint8 &group)
1146 member_witerator slot = _getMemberWSlot(guid);
1147 if(slot==m_memberSlots.end())
1148 return false;
1150 slot->group = group;
1152 SubGroupCounterIncrease(group);
1154 if(!isBGGroup()) CharacterDatabase.PExecute("UPDATE group_member SET subgroup='%u' WHERE memberGuid='%u'", group, GUID_LOPART(guid));
1156 return true;
1159 bool Group::_setAssistantFlag(const uint64 &guid, const bool &state)
1161 member_witerator slot = _getMemberWSlot(guid);
1162 if(slot==m_memberSlots.end())
1163 return false;
1165 slot->assistant = state;
1166 if(!isBGGroup()) CharacterDatabase.PExecute("UPDATE group_member SET assistant='%u' WHERE memberGuid='%u'", (state==true)?1:0, GUID_LOPART(guid));
1167 return true;
1170 bool Group::_setMainTank(const uint64 &guid)
1172 member_citerator slot = _getMemberCSlot(guid);
1173 if(slot==m_memberSlots.end())
1174 return false;
1176 if(m_mainAssistant == guid)
1177 _setMainAssistant(0);
1178 m_mainTank = guid;
1179 if(!isBGGroup()) CharacterDatabase.PExecute("UPDATE groups SET mainTank='%u' WHERE leaderGuid='%u'", GUID_LOPART(m_mainTank), GUID_LOPART(m_leaderGuid));
1180 return true;
1183 bool Group::_setMainAssistant(const uint64 &guid)
1185 member_witerator slot = _getMemberWSlot(guid);
1186 if(slot==m_memberSlots.end())
1187 return false;
1189 if(m_mainTank == guid)
1190 _setMainTank(0);
1191 m_mainAssistant = guid;
1192 if(!isBGGroup()) CharacterDatabase.PExecute("UPDATE groups SET mainAssistant='%u' WHERE leaderGuid='%u'", GUID_LOPART(m_mainAssistant), GUID_LOPART(m_leaderGuid));
1193 return true;
1196 bool Group::SameSubGroup(Player const* member1, Player const* member2) const
1198 if(!member1 || !member2) return false;
1199 if (member1->GetGroup() != this || member2->GetGroup() != this) return false;
1200 else return member1->GetSubGroup() == member2->GetSubGroup();
1203 // allows setting subgroup for offline members
1204 void Group::ChangeMembersGroup(const uint64 &guid, const uint8 &group)
1206 if(!isRaidGroup())
1207 return;
1208 Player *player = objmgr.GetPlayer(guid);
1210 if (!player)
1212 uint8 prevSubGroup;
1213 prevSubGroup = GetMemberGroup(guid);
1215 SubGroupCounterDecrease(prevSubGroup);
1217 if(_setMembersGroup(guid, group))
1218 SendUpdate();
1220 else
1221 // This methods handles itself groupcounter decrease
1222 ChangeMembersGroup(player, group);
1225 // only for online members
1226 void Group::ChangeMembersGroup(Player *player, const uint8 &group)
1228 if(!player || !isRaidGroup())
1229 return;
1230 if(_setMembersGroup(player->GetGUID(), group))
1232 uint8 prevSubGroup;
1233 prevSubGroup = player->GetSubGroup();
1235 SubGroupCounterDecrease(prevSubGroup);
1237 player->GetGroupRef().setSubGroup(group);
1238 SendUpdate();
1242 void Group::UpdateLooterGuid( Creature* creature, bool ifneed )
1244 switch (GetLootMethod())
1246 case MASTER_LOOT:
1247 case FREE_FOR_ALL:
1248 return;
1249 default:
1250 // round robin style looting applies for all low
1251 // quality items in each loot method except free for all and master loot
1252 break;
1255 member_citerator guid_itr = _getMemberCSlot(GetLooterGuid());
1256 if(guid_itr != m_memberSlots.end())
1258 if(ifneed)
1260 // not update if only update if need and ok
1261 Player* looter = ObjectAccessor::FindPlayer(guid_itr->guid);
1262 if(looter && looter->GetDistance2d(creature) < sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
1263 return;
1265 ++guid_itr;
1268 // search next after current
1269 if(guid_itr != m_memberSlots.end())
1271 for(member_citerator itr = guid_itr; itr != m_memberSlots.end(); ++itr)
1273 if(Player* pl = ObjectAccessor::FindPlayer(itr->guid))
1275 if (pl->GetDistance2d(creature) < sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
1277 bool refresh = pl->GetLootGUID()==creature->GetGUID();
1279 //if(refresh) // update loot for new looter
1280 // pl->GetSession()->DoLootRelease(pl->GetLootGUID());
1281 SetLooterGuid(pl->GetGUID());
1282 SendUpdate();
1283 if(refresh) // update loot for new looter
1284 pl->SendLoot(creature->GetGUID(),LOOT_CORPSE);
1285 return;
1291 // search from start
1292 for(member_citerator itr = m_memberSlots.begin(); itr != guid_itr; ++itr)
1294 if(Player* pl = ObjectAccessor::FindPlayer(itr->guid))
1296 if (pl->GetDistance2d(creature) < sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
1298 bool refresh = pl->GetLootGUID()==creature->GetGUID();
1300 //if(refresh) // update loot for new looter
1301 // pl->GetSession()->DoLootRelease(pl->GetLootGUID());
1302 SetLooterGuid(pl->GetGUID());
1303 SendUpdate();
1304 if(refresh) // update loot for new looter
1305 pl->SendLoot(creature->GetGUID(),LOOT_CORPSE);
1306 return;
1311 SetLooterGuid(0);
1312 SendUpdate();
1315 uint32 Group::CanJoinBattleGroundQueue(uint32 bgTypeId, uint32 bgQueueType, uint32 MinPlayerCount, uint32 MaxPlayerCount, bool isRated, uint32 arenaSlot)
1317 // check for min / max count
1318 uint32 memberscount = GetMembersCount();
1319 if(memberscount < MinPlayerCount)
1320 return BG_JOIN_ERR_GROUP_NOT_ENOUGH;
1321 if(memberscount > MaxPlayerCount)
1322 return BG_JOIN_ERR_GROUP_TOO_MANY;
1324 // get a player as reference, to compare other players' stats to (arena team id, queue id based on level, etc.)
1325 Player * reference = GetFirstMember()->getSource();
1326 // no reference found, can't join this way
1327 if(!reference)
1328 return BG_JOIN_ERR_OFFLINE_MEMBER;
1330 uint32 bgQueueId = reference->GetBattleGroundQueueIdFromLevel();
1331 uint32 arenaTeamId = reference->GetArenaTeamId(arenaSlot);
1332 uint32 team = reference->GetTeam();
1334 // check every member of the group to be able to join
1335 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
1337 Player *member = itr->getSource();
1338 // offline member? don't let join
1339 if(!member)
1340 return BG_JOIN_ERR_OFFLINE_MEMBER;
1341 // don't allow cross-faction join as group
1342 if(member->GetTeam() != team)
1343 return BG_JOIN_ERR_MIXED_FACTION;
1344 // not in the same battleground level braket, don't let join
1345 if(member->GetBattleGroundQueueIdFromLevel() != bgQueueId)
1346 return BG_JOIN_ERR_MIXED_LEVELS;
1347 // don't let join rated matches if the arena team id doesn't match
1348 if(isRated && member->GetArenaTeamId(arenaSlot) != arenaTeamId)
1349 return BG_JOIN_ERR_MIXED_ARENATEAM;
1350 // don't let join if someone from the group is already in that bg queue
1351 if(member->InBattleGroundQueueForBattleGroundQueueType(bgQueueType))
1352 return BG_JOIN_ERR_GROUP_MEMBER_ALREADY_IN_QUEUE;
1353 // check for deserter debuff in case not arena queue
1354 if(bgTypeId != BATTLEGROUND_AA && !member->CanJoinToBattleground())
1355 return BG_JOIN_ERR_GROUP_DESERTER;
1356 // check if member can join any more battleground queues
1357 if(!member->HasFreeBattleGroundQueueId())
1358 return BG_JOIN_ERR_ALL_QUEUES_USED;
1360 return BG_JOIN_ERR_OK;
1363 //===================================================
1364 //============== Roll ===============================
1365 //===================================================
1367 void Roll::targetObjectBuildLink()
1369 // called from link()
1370 getTarget()->addLootValidatorRef(this);
1373 void Group::SetDifficulty(uint8 difficulty)
1375 m_difficulty = difficulty;
1376 if(!isBGGroup()) CharacterDatabase.PExecute("UPDATE groups SET difficulty = %u WHERE leaderGuid ='%u'", m_difficulty, GUID_LOPART(m_leaderGuid));
1378 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
1380 Player *player = itr->getSource();
1381 if(!player->GetSession() || player->getLevel() < LEVELREQUIREMENT_HEROIC)
1382 continue;
1383 player->SetDifficulty(difficulty);
1384 player->SendDungeonDifficulty(true);
1388 bool Group::InCombatToInstance(uint32 instanceId)
1390 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
1392 Player *pPlayer = itr->getSource();
1393 if(pPlayer->getAttackers().size() && pPlayer->GetInstanceId() == instanceId)
1394 return true;
1396 return false;
1399 void Group::ResetInstances(uint8 method, Player* SendMsgTo)
1401 if(isBGGroup())
1402 return;
1404 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_DISBAND
1406 // we assume that when the difficulty changes, all instances that can be reset will be
1407 uint8 dif = GetDifficulty();
1409 for(BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
1411 InstanceSave *p = itr->second.save;
1412 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
1413 if(!entry || (!p->CanReset() && method != INSTANCE_RESET_GROUP_DISBAND))
1415 ++itr;
1416 continue;
1419 if(method == INSTANCE_RESET_ALL)
1421 // the "reset all instances" method can only reset normal maps
1422 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
1424 ++itr;
1425 continue;
1429 bool isEmpty = true;
1430 // if the map is loaded, reset it
1431 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
1432 if(map && map->IsDungeon())
1433 isEmpty = ((InstanceMap*)map)->Reset(method);
1435 if(SendMsgTo)
1437 if(isEmpty) SendMsgTo->SendResetInstanceSuccess(p->GetMapId());
1438 else SendMsgTo->SendResetInstanceFailed(0, p->GetMapId());
1441 if(isEmpty || method == INSTANCE_RESET_GROUP_DISBAND || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
1443 // do not reset the instance, just unbind if others are permanently bound to it
1444 if(p->CanReset()) p->DeleteFromDB();
1445 else CharacterDatabase.PExecute("DELETE FROM group_instance WHERE instance = '%u'", p->GetInstanceId());
1446 // i don't know for sure if hash_map iterators
1447 m_boundInstances[dif].erase(itr);
1448 itr = m_boundInstances[dif].begin();
1449 // this unloads the instance save unless online players are bound to it
1450 // (eg. permanent binds or GM solo binds)
1451 p->RemoveGroup(this);
1453 else
1454 ++itr;
1458 InstanceGroupBind* Group::GetBoundInstance(uint32 mapid, uint8 difficulty)
1460 // some instances only have one difficulty
1461 const MapEntry* entry = sMapStore.LookupEntry(mapid);
1462 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
1464 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
1465 if(itr != m_boundInstances[difficulty].end())
1466 return &itr->second;
1467 else
1468 return NULL;
1471 InstanceGroupBind* Group::BindToInstance(InstanceSave *save, bool permanent, bool load)
1473 if(save && !isBGGroup())
1475 InstanceGroupBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
1476 if(bind.save)
1478 // when a boss is killed or when copying the players's binds to the group
1479 if(permanent != bind.perm || save != bind.save)
1480 if(!load) CharacterDatabase.PExecute("UPDATE group_instance SET instance = '%u', permanent = '%u' WHERE leaderGuid = '%u' AND instance = '%u'", save->GetInstanceId(), permanent, GUID_LOPART(GetLeaderGUID()), bind.save->GetInstanceId());
1482 else
1483 if(!load) CharacterDatabase.PExecute("INSERT INTO group_instance (leaderGuid, instance, permanent) VALUES ('%u', '%u', '%u')", GUID_LOPART(GetLeaderGUID()), save->GetInstanceId(), permanent);
1485 if(bind.save != save)
1487 if(bind.save) bind.save->RemoveGroup(this);
1488 save->AddGroup(this);
1491 bind.save = save;
1492 bind.perm = permanent;
1493 if(!load) sLog.outDebug("Group::BindToInstance: %d is now bound to map %d, instance %d, difficulty %d", GUID_LOPART(GetLeaderGUID()), save->GetMapId(), save->GetInstanceId(), save->GetDifficulty());
1494 return &bind;
1496 else
1497 return NULL;
1500 void Group::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
1502 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
1503 if(itr != m_boundInstances[difficulty].end())
1505 if(!unload) CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u' AND instance = '%u'", GUID_LOPART(GetLeaderGUID()), itr->second.save->GetInstanceId());
1506 itr->second.save->RemoveGroup(this); // save can become invalid
1507 m_boundInstances[difficulty].erase(itr);
1511 void Group::_homebindIfInstance(Player *player)
1513 if(player && !player->isGameMaster() && sMapStore.LookupEntry(player->GetMapId())->IsDungeon())
1515 // leaving the group in an instance, the homebind timer is started
1516 // unless the player is permanently saved to the instance
1517 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(player->GetInstanceId());
1518 InstancePlayerBind *playerBind = save ? player->GetBoundInstance(save->GetMapId(), save->GetDifficulty()) : NULL;
1519 if(!playerBind || !playerBind->perm)
1520 player->m_InstanceValid = false;