[7297] Fixed profession spells sorting in trainer spell list at client.
[getmangos.git] / src / game / Group.cpp
blobd2fabecea556f8aabd9534a4aad0f563759ba29b
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();
207 // update quest related GO states (quest activity dependent from raid membership)
208 for(member_citerator citr = m_memberSlots.begin(); citr != m_memberSlots.end(); ++citr)
209 if(Player* player = objmgr.GetPlayer(citr->guid))
210 player->UpdateForQuestsGO();
213 bool Group::AddInvite(Player *player)
215 if(!player || player->GetGroupInvite() || player->GetGroup())
216 return false;
218 RemoveInvite(player);
220 m_invitees.insert(player);
222 player->SetGroupInvite(this);
224 return true;
227 bool Group::AddLeaderInvite(Player *player)
229 if(!AddInvite(player))
230 return false;
232 m_leaderGuid = player->GetGUID();
233 m_leaderName = player->GetName();
234 return true;
237 uint32 Group::RemoveInvite(Player *player)
239 m_invitees.erase(player);
241 player->SetGroupInvite(NULL);
242 return GetMembersCount();
245 void Group::RemoveAllInvites()
247 for(InvitesList::iterator itr=m_invitees.begin(); itr!=m_invitees.end(); ++itr)
248 (*itr)->SetGroupInvite(NULL);
250 m_invitees.clear();
253 Player* Group::GetInvited(const uint64& guid) const
255 for(InvitesList::const_iterator itr = m_invitees.begin(); itr != m_invitees.end(); ++itr)
257 if((*itr)->GetGUID() == guid)
258 return (*itr);
260 return NULL;
263 Player* Group::GetInvited(const std::string& name) const
265 for(InvitesList::const_iterator itr = m_invitees.begin(); itr != m_invitees.end(); ++itr)
267 if((*itr)->GetName() == name)
268 return (*itr);
270 return NULL;
273 bool Group::AddMember(const uint64 &guid, const char* name)
275 if(!_addMember(guid, name))
276 return false;
277 SendUpdate();
279 Player *player = objmgr.GetPlayer(guid);
280 if(player)
282 if(!IsLeader(player->GetGUID()) && !isBGGroup())
284 // reset the new member's instances, unless he is currently in one of them
285 // including raid/heroic instances that they are not permanently bound to!
286 player->ResetInstances(INSTANCE_RESET_GROUP_JOIN);
288 if(player->getLevel() >= LEVELREQUIREMENT_HEROIC && player->GetDifficulty() != GetDifficulty() )
290 player->SetDifficulty(m_difficulty);
291 player->SendDungeonDifficulty(true);
294 player->SetGroupUpdateFlag(GROUP_UPDATE_FULL);
295 UpdatePlayerOutOfRange(player);
297 // quest related GO state dependent from raid memebership
298 if(isRaidGroup())
299 player->UpdateForQuestsGO();
302 return true;
305 uint32 Group::RemoveMember(const uint64 &guid, const uint8 &method)
307 // remove member and change leader (if need) only if strong more 2 members _before_ member remove
308 if(GetMembersCount() > (isBGGroup() ? 1 : 2)) // in BG group case allow 1 members group
310 bool leaderChanged = _removeMember(guid);
312 if(Player *player = objmgr.GetPlayer( guid ))
314 // quest related GO state dependent from raid membership
315 if(isRaidGroup())
316 player->UpdateForQuestsGO();
318 WorldPacket data;
320 if(method == 1)
322 data.Initialize( SMSG_GROUP_UNINVITE, 0 );
323 player->GetSession()->SendPacket( &data );
326 data.Initialize(SMSG_GROUP_LIST, 24);
327 data << uint64(0) << uint64(0) << uint64(0);
328 player->GetSession()->SendPacket(&data);
330 _homebindIfInstance(player);
333 if(leaderChanged)
335 WorldPacket data(SMSG_GROUP_SET_LEADER, (m_memberSlots.front().name.size()+1));
336 data << m_memberSlots.front().name;
337 BroadcastPacket(&data);
340 SendUpdate();
342 // if group before remove <= 2 disband it
343 else
344 Disband(true);
346 return m_memberSlots.size();
349 void Group::ChangeLeader(const uint64 &guid)
351 member_citerator slot = _getMemberCSlot(guid);
353 if(slot==m_memberSlots.end())
354 return;
356 _setLeader(guid);
358 WorldPacket data(SMSG_GROUP_SET_LEADER, slot->name.size()+1);
359 data << slot->name;
360 BroadcastPacket(&data);
361 SendUpdate();
364 void Group::Disband(bool hideDestroy)
366 Player *player;
368 for(member_citerator citr = m_memberSlots.begin(); citr != m_memberSlots.end(); ++citr)
370 player = objmgr.GetPlayer(citr->guid);
371 if(!player)
372 continue;
374 player->SetGroup(NULL);
376 // quest related GO state dependent from raid membership
377 if(isRaidGroup())
378 player->UpdateForQuestsGO();
381 if(!player->GetSession())
382 continue;
384 WorldPacket data;
385 if(!hideDestroy)
387 data.Initialize(SMSG_GROUP_DESTROYED, 0);
388 player->GetSession()->SendPacket(&data);
391 data.Initialize(SMSG_GROUP_LIST, 24);
392 data << uint64(0) << uint64(0) << uint64(0);
393 player->GetSession()->SendPacket(&data);
395 _homebindIfInstance(player);
397 RollId.clear();
398 m_memberSlots.clear();
400 RemoveAllInvites();
402 if(!isBGGroup())
404 CharacterDatabase.BeginTransaction();
405 CharacterDatabase.PExecute("DELETE FROM groups WHERE leaderGuid='%u'", GUID_LOPART(m_leaderGuid));
406 CharacterDatabase.PExecute("DELETE FROM group_member WHERE leaderGuid='%u'", GUID_LOPART(m_leaderGuid));
407 CharacterDatabase.CommitTransaction();
408 ResetInstances(INSTANCE_RESET_GROUP_DISBAND, NULL);
411 m_leaderGuid = 0;
412 m_leaderName = "";
415 /*********************************************************/
416 /*** LOOT SYSTEM ***/
417 /*********************************************************/
419 void Group::SendLootStartRoll(uint32 CountDown, const Roll &r)
421 WorldPacket data(SMSG_LOOT_START_ROLL, (8+4+4+4+4+4));
422 data << uint64(r.itemGUID); // guid of rolled item
423 data << uint32(r.totalPlayersRolling); // maybe the number of players rolling for it???
424 data << uint32(r.itemid); // the itemEntryId for the item that shall be rolled for
425 data << uint32(r.itemRandomSuffix); // randomSuffix
426 data << uint32(r.itemRandomPropId); // item random property ID
427 data << uint32(CountDown); // the countdown time to choose "need" or "greed"
429 for (Roll::PlayerVote::const_iterator itr=r.playerVote.begin(); itr!=r.playerVote.end(); ++itr)
431 Player *p = objmgr.GetPlayer(itr->first);
432 if(!p || !p->GetSession())
433 continue;
435 if(itr->second != NOT_VALID)
436 p->GetSession()->SendPacket( &data );
440 void Group::SendLootRoll(const uint64& SourceGuid, const uint64& TargetGuid, uint8 RollNumber, uint8 RollType, const Roll &r)
442 WorldPacket data(SMSG_LOOT_ROLL, (8+4+8+4+4+4+1+1));
443 data << uint64(SourceGuid); // guid of the item rolled
444 data << uint32(0); // unknown, maybe amount of players
445 data << uint64(TargetGuid);
446 data << uint32(r.itemid); // the itemEntryId for the item that shall be rolled for
447 data << uint32(r.itemRandomSuffix); // randomSuffix
448 data << uint32(r.itemRandomPropId); // Item random property ID
449 data << uint8(RollNumber); // 0: "Need for: [item name]" > 127: "you passed on: [item name]" Roll number
450 data << uint8(RollType); // 0: "Need for: [item name]" 0: "You have selected need for [item name] 1: need roll 2: greed roll
451 data << uint8(0); // 2.4.0
453 for( Roll::PlayerVote::const_iterator itr=r.playerVote.begin(); itr!=r.playerVote.end(); ++itr)
455 Player *p = objmgr.GetPlayer(itr->first);
456 if(!p || !p->GetSession())
457 continue;
459 if(itr->second != NOT_VALID)
460 p->GetSession()->SendPacket( &data );
464 void Group::SendLootRollWon(const uint64& SourceGuid, const uint64& TargetGuid, uint8 RollNumber, uint8 RollType, const Roll &r)
466 WorldPacket data(SMSG_LOOT_ROLL_WON, (8+4+4+4+4+8+1+1));
467 data << uint64(SourceGuid); // guid of the item rolled
468 data << uint32(0); // unknown, maybe amount of players
469 data << uint32(r.itemid); // the itemEntryId for the item that shall be rolled for
470 data << uint32(r.itemRandomSuffix); // randomSuffix
471 data << uint32(r.itemRandomPropId); // Item random property
472 data << uint64(TargetGuid); // guid of the player who won.
473 data << uint8(RollNumber); // rollnumber realted to SMSG_LOOT_ROLL
474 data << uint8(RollType); // Rolltype related to SMSG_LOOT_ROLL
476 for( Roll::PlayerVote::const_iterator itr=r.playerVote.begin(); itr!=r.playerVote.end(); ++itr)
478 Player *p = objmgr.GetPlayer(itr->first);
479 if(!p || !p->GetSession())
480 continue;
482 if(itr->second != NOT_VALID)
483 p->GetSession()->SendPacket( &data );
487 void Group::SendLootAllPassed(uint32 NumberOfPlayers, const Roll &r)
489 WorldPacket data(SMSG_LOOT_ALL_PASSED, (8+4+4+4+4));
490 data << uint64(r.itemGUID); // Guid of the item rolled
491 data << uint32(NumberOfPlayers); // The number of players rolling for it???
492 data << uint32(r.itemid); // The itemEntryId for the item that shall be rolled for
493 data << uint32(r.itemRandomPropId); // Item random property ID
494 data << uint32(r.itemRandomSuffix); // Item random suffix ID
496 for( Roll::PlayerVote::const_iterator itr=r.playerVote.begin(); itr!=r.playerVote.end(); ++itr)
498 Player *p = objmgr.GetPlayer(itr->first);
499 if(!p || !p->GetSession())
500 continue;
502 if(itr->second != NOT_VALID)
503 p->GetSession()->SendPacket( &data );
507 void Group::GroupLoot(const uint64& playerGUID, Loot *loot, Creature *creature)
509 std::vector<LootItem>::iterator i;
510 ItemPrototype const *item;
511 uint8 itemSlot = 0;
512 Player *player = objmgr.GetPlayer(playerGUID);
513 Group *group = player->GetGroup();
515 for (i=loot->items.begin(); i != loot->items.end(); ++i, ++itemSlot)
517 item = objmgr.GetItemPrototype(i->itemid);
518 if (!item)
520 //sLog.outDebug("Group::GroupLoot: missing item prototype for item with id: %d", i->itemid);
521 continue;
524 //roll for over-threshold item if it's one-player loot
525 if (item->Quality >= uint32(m_lootThreshold) && !i->freeforall)
527 uint64 newitemGUID = MAKE_NEW_GUID(objmgr.GenerateLowGuid(HIGHGUID_ITEM),0,HIGHGUID_ITEM);
528 Roll* r=new Roll(newitemGUID,*i);
530 //a vector is filled with only near party members
531 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
533 Player *member = itr->getSource();
534 if(!member || !member->GetSession())
535 continue;
536 if ( i->AllowedForPlayer(member) )
538 if (member->GetDistance2d(creature) < sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
540 r->playerVote[member->GetGUID()] = NOT_EMITED_YET;
541 ++r->totalPlayersRolling;
546 r->setLoot(loot);
547 r->itemSlot = itemSlot;
549 group->SendLootStartRoll(60000, *r);
551 loot->items[itemSlot].is_blocked = true;
552 creature->m_groupLootTimer = 60000;
553 creature->lootingGroupLeaderGUID = GetLeaderGUID();
555 RollId.push_back(r);
557 else
558 i->is_underthreshold=1;
563 void Group::NeedBeforeGreed(const uint64& playerGUID, Loot *loot, Creature *creature)
565 ItemPrototype const *item;
566 Player *player = objmgr.GetPlayer(playerGUID);
567 Group *group = player->GetGroup();
569 uint8 itemSlot = 0;
570 for(std::vector<LootItem>::iterator i=loot->items.begin(); i != loot->items.end(); ++i, ++itemSlot)
572 item = objmgr.GetItemPrototype(i->itemid);
574 //only roll for one-player items, not for ones everyone can get
575 if (item->Quality >= uint32(m_lootThreshold) && !i->freeforall)
577 uint64 newitemGUID = MAKE_NEW_GUID(objmgr.GenerateLowGuid(HIGHGUID_ITEM),0,HIGHGUID_ITEM);
578 Roll* r=new Roll(newitemGUID,*i);
580 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
582 Player *playerToRoll = itr->getSource();
583 if(!playerToRoll || !playerToRoll->GetSession())
584 continue;
586 if (playerToRoll->CanUseItem(item) && i->AllowedForPlayer(playerToRoll) )
588 if (playerToRoll->GetDistance2d(creature) < sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
590 r->playerVote[playerToRoll->GetGUID()] = NOT_EMITED_YET;
591 ++r->totalPlayersRolling;
596 if (r->totalPlayersRolling > 0)
598 r->setLoot(loot);
599 r->itemSlot = itemSlot;
601 group->SendLootStartRoll(60000, *r);
603 loot->items[itemSlot].is_blocked = true;
605 RollId.push_back(r);
607 else
609 delete r;
612 else
613 i->is_underthreshold=1;
617 void Group::MasterLoot(const uint64& playerGUID, Loot* /*loot*/, Creature *creature)
619 Player *player = objmgr.GetPlayer(playerGUID);
620 if(!player)
621 return;
623 sLog.outDebug("Group::MasterLoot (SMSG_LOOT_MASTER_LIST, 330) player = [%s].", player->GetName());
625 uint32 real_count = 0;
627 WorldPacket data(SMSG_LOOT_MASTER_LIST, 330);
628 data << (uint8)GetMembersCount();
630 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
632 Player *looter = itr->getSource();
633 if (!looter->IsInWorld())
634 continue;
636 if (looter->GetDistance2d(creature) < sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
638 data << looter->GetGUID();
639 ++real_count;
643 data.put<uint8>(0,real_count);
645 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
647 Player *looter = itr->getSource();
648 if (looter->GetDistance2d(creature) < sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
649 looter->GetSession()->SendPacket(&data);
653 void Group::CountRollVote(const uint64& playerGUID, const uint64& Guid, uint32 NumberOfPlayers, uint8 Choise)
655 Rolls::iterator rollI = GetRoll(Guid);
656 if (rollI == RollId.end())
657 return;
658 Roll* roll = *rollI;
660 Roll::PlayerVote::iterator itr = roll->playerVote.find(playerGUID);
661 // this condition means that player joins to the party after roll begins
662 if (itr == roll->playerVote.end())
663 return;
665 if (roll->getLoot())
666 if (roll->getLoot()->items.empty())
667 return;
669 switch (Choise)
671 case 0: //Player choose pass
673 SendLootRoll(0, playerGUID, 128, 128, *roll);
674 ++roll->totalPass;
675 itr->second = PASS;
677 break;
678 case 1: //player choose Need
680 SendLootRoll(0, playerGUID, 0, 0, *roll);
681 ++roll->totalNeed;
682 itr->second = NEED;
684 break;
685 case 2: //player choose Greed
687 SendLootRoll(0, playerGUID, 128, 2, *roll);
688 ++roll->totalGreed;
689 itr->second = GREED;
691 break;
693 if (roll->totalPass + roll->totalGreed + roll->totalNeed >= roll->totalPlayersRolling)
695 CountTheRoll(rollI, NumberOfPlayers);
699 //called when roll timer expires
700 void Group::EndRoll()
702 Rolls::iterator itr;
703 while(!RollId.empty())
705 //need more testing here, if rolls disappear
706 itr = RollId.begin();
707 CountTheRoll(itr, GetMembersCount()); //i don't have to edit player votes, who didn't vote ... he will pass
711 void Group::CountTheRoll(Rolls::iterator rollI, uint32 NumberOfPlayers)
713 Roll* roll = *rollI;
714 if(!roll->isValid()) // is loot already deleted ?
716 RollId.erase(rollI);
717 delete roll;
718 return;
720 //end of the roll
721 if (roll->totalNeed > 0)
723 if(!roll->playerVote.empty())
725 uint8 maxresul = 0;
726 uint64 maxguid = (*roll->playerVote.begin()).first;
727 Player *player;
729 for( Roll::PlayerVote::const_iterator itr=roll->playerVote.begin(); itr!=roll->playerVote.end(); ++itr)
731 if (itr->second != NEED)
732 continue;
734 uint8 randomN = urand(1, 99);
735 SendLootRoll(0, itr->first, randomN, 1, *roll);
736 if (maxresul < randomN)
738 maxguid = itr->first;
739 maxresul = randomN;
742 SendLootRollWon(0, maxguid, maxresul, 1, *roll);
743 player = objmgr.GetPlayer(maxguid);
745 if(player && player->GetSession())
747 player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT, roll->itemid, maxresul);
749 ItemPosCountVec dest;
750 LootItem *item = &(roll->getLoot()->items[roll->itemSlot]);
751 uint8 msg = player->CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, roll->itemid, item->count );
752 if ( msg == EQUIP_ERR_OK )
754 item->is_looted = true;
755 roll->getLoot()->NotifyItemRemoved(roll->itemSlot);
756 --roll->getLoot()->unlootedCount;
757 player->StoreNewItem( dest, roll->itemid, true, item->randomPropertyId);
759 else
761 item->is_blocked = false;
762 player->SendEquipError( msg, NULL, NULL );
767 else if (roll->totalGreed > 0)
769 if(!roll->playerVote.empty())
771 uint8 maxresul = 0;
772 uint64 maxguid = (*roll->playerVote.begin()).first;
773 Player *player;
775 Roll::PlayerVote::iterator itr;
776 for (itr=roll->playerVote.begin(); itr!=roll->playerVote.end(); ++itr)
778 if (itr->second != GREED)
779 continue;
781 uint8 randomN = urand(1, 99);
782 SendLootRoll(0, itr->first, randomN, 2, *roll);
783 if (maxresul < randomN)
785 maxguid = itr->first;
786 maxresul = randomN;
789 SendLootRollWon(0, maxguid, maxresul, 2, *roll);
790 player = objmgr.GetPlayer(maxguid);
792 if(player && player->GetSession())
794 player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT, roll->itemid, maxresul);
796 ItemPosCountVec dest;
797 LootItem *item = &(roll->getLoot()->items[roll->itemSlot]);
798 uint8 msg = player->CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, roll->itemid, item->count );
799 if ( msg == EQUIP_ERR_OK )
801 item->is_looted = true;
802 roll->getLoot()->NotifyItemRemoved(roll->itemSlot);
803 --roll->getLoot()->unlootedCount;
804 player->StoreNewItem( dest, roll->itemid, true, item->randomPropertyId);
806 else
808 item->is_blocked = false;
809 player->SendEquipError( msg, NULL, NULL );
814 else
816 SendLootAllPassed(NumberOfPlayers, *roll);
817 LootItem *item = &(roll->getLoot()->items[roll->itemSlot]);
818 if(item) item->is_blocked = false;
820 RollId.erase(rollI);
821 delete roll;
824 void Group::SetTargetIcon(uint8 id, uint64 guid)
826 if(id >= TARGETICONCOUNT)
827 return;
829 // clean other icons
830 if( guid != 0 )
831 for(int i=0; i<TARGETICONCOUNT; i++)
832 if( m_targetIcons[i] == guid )
833 SetTargetIcon(i, 0);
835 m_targetIcons[id] = guid;
837 WorldPacket data(MSG_RAID_TARGET_UPDATE, (2+8));
838 data << (uint8)0;
839 data << id;
840 data << guid;
841 BroadcastPacket(&data);
844 void Group::GetDataForXPAtKill(Unit const* victim, uint32& count,uint32& sum_level, Player* & member_with_max_level, Player* & not_gray_member_with_max_level)
846 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
848 Player* member = itr->getSource();
849 if(!member || !member->isAlive()) // only for alive
850 continue;
852 if(!member->IsAtGroupRewardDistance(victim)) // at req. distance
853 continue;
855 ++count;
856 sum_level += member->getLevel();
857 if(!member_with_max_level || member_with_max_level->getLevel() < member->getLevel())
858 member_with_max_level = member;
860 uint32 gray_level = MaNGOS::XP::GetGrayLevel(member->getLevel());
861 if( victim->getLevel() > gray_level && (!not_gray_member_with_max_level
862 || not_gray_member_with_max_level->getLevel() < member->getLevel()))
863 not_gray_member_with_max_level = member;
867 void Group::SendTargetIconList(WorldSession *session)
869 if(!session)
870 return;
872 WorldPacket data(MSG_RAID_TARGET_UPDATE, (1+TARGETICONCOUNT*9));
873 data << (uint8)1;
875 for(int i=0; i<TARGETICONCOUNT; i++)
877 if(m_targetIcons[i] == 0)
878 continue;
880 data << (uint8)i;
881 data << m_targetIcons[i];
884 session->SendPacket(&data);
887 void Group::SendUpdate()
889 Player *player;
891 for(member_citerator citr = m_memberSlots.begin(); citr != m_memberSlots.end(); ++citr)
893 player = objmgr.GetPlayer(citr->guid);
894 if(!player || !player->GetSession())
895 continue;
896 // guess size
897 WorldPacket data(SMSG_GROUP_LIST, (1+1+1+1+8+4+GetMembersCount()*20));
898 data << (uint8)m_groupType; // group type
899 data << (uint8)(isBGGroup() ? 1 : 0); // 2.0.x, isBattleGroundGroup?
900 data << (uint8)(citr->group); // groupid
901 data << (uint8)(citr->assistant?0x01:0); // 0x2 main assist, 0x4 main tank
902 data << uint64(0x50000000FFFFFFFELL); // related to voice chat?
903 data << uint32(GetMembersCount()-1);
904 for(member_citerator citr2 = m_memberSlots.begin(); citr2 != m_memberSlots.end(); ++citr2)
906 if(citr->guid == citr2->guid)
907 continue;
909 data << citr2->name;
910 data << (uint64)citr2->guid;
911 // online-state
912 data << (uint8)(objmgr.GetPlayer(citr2->guid) ? 1 : 0);
913 data << (uint8)(citr2->group); // groupid
914 data << (uint8)(citr2->assistant?0x01:0); // 0x2 main assist, 0x4 main tank
917 data << uint64(m_leaderGuid); // leader guid
918 if(GetMembersCount()-1)
920 data << (uint8)m_lootMethod; // loot method
921 data << (uint64)m_looterGuid; // looter guid
922 data << (uint8)m_lootThreshold; // loot threshold
923 data << (uint8)m_difficulty; // Heroic Mod Group
925 player->GetSession()->SendPacket( &data );
929 void Group::UpdatePlayerOutOfRange(Player* pPlayer)
931 if(!pPlayer)
932 return;
934 Player *player;
935 WorldPacket data;
936 pPlayer->GetSession()->BuildPartyMemberStatsChangedPacket(pPlayer, &data);
938 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
940 player = itr->getSource();
941 if (player && player != pPlayer && !pPlayer->isVisibleFor(player))
942 player->GetSession()->SendPacket(&data);
946 void Group::BroadcastPacket(WorldPacket *packet, int group, uint64 ignore)
948 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
950 Player *pl = itr->getSource();
951 if(!pl || (ignore != 0 && pl->GetGUID() == ignore))
952 continue;
954 if (pl->GetSession() && (group==-1 || itr->getSubGroup()==group))
955 pl->GetSession()->SendPacket(packet);
959 void Group::BroadcastReadyCheck(WorldPacket *packet)
961 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
963 Player *pl = itr->getSource();
964 if(pl && pl->GetSession())
965 if(IsLeader(pl->GetGUID()) || IsAssistant(pl->GetGUID()))
966 pl->GetSession()->SendPacket(packet);
970 void Group::OfflineReadyCheck()
972 for(member_citerator citr = m_memberSlots.begin(); citr != m_memberSlots.end(); ++citr)
974 Player *pl = objmgr.GetPlayer(citr->guid);
975 if (!pl || !pl->GetSession())
977 WorldPacket data(MSG_RAID_READY_CHECK_CONFIRM, 9);
978 data << citr->guid;
979 data << (uint8)0;
980 BroadcastReadyCheck(&data);
985 bool Group::_addMember(const uint64 &guid, const char* name, bool isAssistant)
987 // get first not-full group
988 uint8 groupid = 0;
989 if (m_subGroupsCounts)
991 bool groupFound = false;
992 for (; groupid < MAXRAIDSIZE/MAXGROUPSIZE; ++groupid)
994 if (m_subGroupsCounts[groupid] < MAXGROUPSIZE)
996 groupFound = true;
997 break;
1000 // We are raid group and no one slot is free
1001 if (!groupFound)
1002 return false;
1005 return _addMember(guid, name, isAssistant, groupid);
1008 bool Group::_addMember(const uint64 &guid, const char* name, bool isAssistant, uint8 group)
1010 if(IsFull())
1011 return false;
1013 if(!guid)
1014 return false;
1016 Player *player = objmgr.GetPlayer(guid);
1018 MemberSlot member;
1019 member.guid = guid;
1020 member.name = name;
1021 member.group = group;
1022 member.assistant = isAssistant;
1023 m_memberSlots.push_back(member);
1025 SubGroupCounterIncrease(group);
1027 if(player)
1029 player->SetGroupInvite(NULL);
1030 player->SetGroup(this, group);
1031 // if the same group invites the player back, cancel the homebind timer
1032 InstanceGroupBind *bind = GetBoundInstance(player->GetMapId(), player->GetDifficulty());
1033 if(bind && bind->save->GetInstanceId() == player->GetInstanceId())
1034 player->m_InstanceValid = true;
1037 if(!isRaidGroup()) // reset targetIcons for non-raid-groups
1039 for(int i=0; i<TARGETICONCOUNT; i++)
1040 m_targetIcons[i] = 0;
1043 if(!isBGGroup())
1045 // insert into group table
1046 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);
1049 return true;
1052 bool Group::_removeMember(const uint64 &guid)
1054 Player *player = objmgr.GetPlayer(guid);
1055 if (player)
1057 player->SetGroup(NULL);
1060 _removeRolls(guid);
1062 member_witerator slot = _getMemberWSlot(guid);
1063 if (slot != m_memberSlots.end())
1065 SubGroupCounterDecrease(slot->group);
1067 m_memberSlots.erase(slot);
1070 if(!isBGGroup())
1071 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid='%u'", GUID_LOPART(guid));
1073 if(m_leaderGuid == guid) // leader was removed
1075 if(GetMembersCount() > 0)
1076 _setLeader(m_memberSlots.front().guid);
1077 return true;
1080 return false;
1083 void Group::_setLeader(const uint64 &guid)
1085 member_citerator slot = _getMemberCSlot(guid);
1086 if(slot==m_memberSlots.end())
1087 return;
1089 if(!isBGGroup())
1091 // TODO: set a time limit to have this function run rarely cause it can be slow
1092 CharacterDatabase.BeginTransaction();
1094 // update the group's bound instances when changing leaders
1096 // remove all permanent binds from the group
1097 // in the DB also remove solo binds that will be replaced with permbinds
1098 // from the new leader
1099 CharacterDatabase.PExecute(
1100 "DELETE FROM group_instance WHERE leaderguid='%u' AND (permanent = 1 OR "
1101 "instance IN (SELECT instance FROM character_instance WHERE guid = '%u')"
1102 ")", GUID_LOPART(m_leaderGuid), GUID_LOPART(slot->guid)
1105 Player *player = objmgr.GetPlayer(slot->guid);
1106 if(player)
1108 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
1110 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end();)
1112 if(itr->second.perm)
1114 itr->second.save->RemoveGroup(this);
1115 m_boundInstances[i].erase(itr++);
1117 else
1118 ++itr;
1123 // update the group's solo binds to the new leader
1124 CharacterDatabase.PExecute("UPDATE group_instance SET leaderGuid='%u' WHERE leaderGuid = '%u'", GUID_LOPART(slot->guid), GUID_LOPART(m_leaderGuid));
1126 // copy the permanent binds from the new leader to the group
1127 // overwriting the solo binds with permanent ones if necessary
1128 // in the DB those have been deleted already
1129 Player::ConvertInstancesToGroup(player, this, slot->guid);
1131 // update the group leader
1132 CharacterDatabase.PExecute("UPDATE groups SET leaderGuid='%u' WHERE leaderGuid='%u'", GUID_LOPART(slot->guid), GUID_LOPART(m_leaderGuid));
1133 CharacterDatabase.PExecute("UPDATE group_member SET leaderGuid='%u' WHERE leaderGuid='%u'", GUID_LOPART(slot->guid), GUID_LOPART(m_leaderGuid));
1134 CharacterDatabase.CommitTransaction();
1137 m_leaderGuid = slot->guid;
1138 m_leaderName = slot->name;
1141 void Group::_removeRolls(const uint64 &guid)
1143 for (Rolls::iterator it = RollId.begin(); it < RollId.end(); ++it)
1145 Roll* roll = *it;
1146 Roll::PlayerVote::iterator itr2 = roll->playerVote.find(guid);
1147 if(itr2 == roll->playerVote.end())
1148 continue;
1150 if (itr2->second == GREED) --roll->totalGreed;
1151 if (itr2->second == NEED) --roll->totalNeed;
1152 if (itr2->second == PASS) --roll->totalPass;
1153 if (itr2->second != NOT_VALID) --roll->totalPlayersRolling;
1155 roll->playerVote.erase(itr2);
1157 CountRollVote(guid, roll->itemGUID, GetMembersCount()-1, 3);
1161 bool Group::_setMembersGroup(const uint64 &guid, const uint8 &group)
1163 member_witerator slot = _getMemberWSlot(guid);
1164 if(slot==m_memberSlots.end())
1165 return false;
1167 slot->group = group;
1169 SubGroupCounterIncrease(group);
1171 if(!isBGGroup()) CharacterDatabase.PExecute("UPDATE group_member SET subgroup='%u' WHERE memberGuid='%u'", group, GUID_LOPART(guid));
1173 return true;
1176 bool Group::_setAssistantFlag(const uint64 &guid, const bool &state)
1178 member_witerator slot = _getMemberWSlot(guid);
1179 if(slot==m_memberSlots.end())
1180 return false;
1182 slot->assistant = state;
1183 if(!isBGGroup()) CharacterDatabase.PExecute("UPDATE group_member SET assistant='%u' WHERE memberGuid='%u'", (state==true)?1:0, GUID_LOPART(guid));
1184 return true;
1187 bool Group::_setMainTank(const uint64 &guid)
1189 member_citerator slot = _getMemberCSlot(guid);
1190 if(slot==m_memberSlots.end())
1191 return false;
1193 if(m_mainAssistant == guid)
1194 _setMainAssistant(0);
1195 m_mainTank = guid;
1196 if(!isBGGroup()) CharacterDatabase.PExecute("UPDATE groups SET mainTank='%u' WHERE leaderGuid='%u'", GUID_LOPART(m_mainTank), GUID_LOPART(m_leaderGuid));
1197 return true;
1200 bool Group::_setMainAssistant(const uint64 &guid)
1202 member_witerator slot = _getMemberWSlot(guid);
1203 if(slot==m_memberSlots.end())
1204 return false;
1206 if(m_mainTank == guid)
1207 _setMainTank(0);
1208 m_mainAssistant = guid;
1209 if(!isBGGroup()) CharacterDatabase.PExecute("UPDATE groups SET mainAssistant='%u' WHERE leaderGuid='%u'", GUID_LOPART(m_mainAssistant), GUID_LOPART(m_leaderGuid));
1210 return true;
1213 bool Group::SameSubGroup(Player const* member1, Player const* member2) const
1215 if(!member1 || !member2) return false;
1216 if (member1->GetGroup() != this || member2->GetGroup() != this) return false;
1217 else return member1->GetSubGroup() == member2->GetSubGroup();
1220 // allows setting subgroup for offline members
1221 void Group::ChangeMembersGroup(const uint64 &guid, const uint8 &group)
1223 if(!isRaidGroup())
1224 return;
1225 Player *player = objmgr.GetPlayer(guid);
1227 if (!player)
1229 uint8 prevSubGroup;
1230 prevSubGroup = GetMemberGroup(guid);
1232 SubGroupCounterDecrease(prevSubGroup);
1234 if(_setMembersGroup(guid, group))
1235 SendUpdate();
1237 else
1238 // This methods handles itself groupcounter decrease
1239 ChangeMembersGroup(player, group);
1242 // only for online members
1243 void Group::ChangeMembersGroup(Player *player, const uint8 &group)
1245 if(!player || !isRaidGroup())
1246 return;
1247 if(_setMembersGroup(player->GetGUID(), group))
1249 uint8 prevSubGroup;
1250 prevSubGroup = player->GetSubGroup();
1252 SubGroupCounterDecrease(prevSubGroup);
1254 player->GetGroupRef().setSubGroup(group);
1255 SendUpdate();
1259 void Group::UpdateLooterGuid( Creature* creature, bool ifneed )
1261 switch (GetLootMethod())
1263 case MASTER_LOOT:
1264 case FREE_FOR_ALL:
1265 return;
1266 default:
1267 // round robin style looting applies for all low
1268 // quality items in each loot method except free for all and master loot
1269 break;
1272 member_citerator guid_itr = _getMemberCSlot(GetLooterGuid());
1273 if(guid_itr != m_memberSlots.end())
1275 if(ifneed)
1277 // not update if only update if need and ok
1278 Player* looter = ObjectAccessor::FindPlayer(guid_itr->guid);
1279 if(looter && looter->GetDistance2d(creature) < sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
1280 return;
1282 ++guid_itr;
1285 // search next after current
1286 if(guid_itr != m_memberSlots.end())
1288 for(member_citerator itr = guid_itr; itr != m_memberSlots.end(); ++itr)
1290 if(Player* pl = ObjectAccessor::FindPlayer(itr->guid))
1292 if (pl->GetDistance2d(creature) < sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
1294 bool refresh = pl->GetLootGUID()==creature->GetGUID();
1296 //if(refresh) // update loot for new looter
1297 // pl->GetSession()->DoLootRelease(pl->GetLootGUID());
1298 SetLooterGuid(pl->GetGUID());
1299 SendUpdate();
1300 if(refresh) // update loot for new looter
1301 pl->SendLoot(creature->GetGUID(),LOOT_CORPSE);
1302 return;
1308 // search from start
1309 for(member_citerator itr = m_memberSlots.begin(); itr != guid_itr; ++itr)
1311 if(Player* pl = ObjectAccessor::FindPlayer(itr->guid))
1313 if (pl->GetDistance2d(creature) < sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
1315 bool refresh = pl->GetLootGUID()==creature->GetGUID();
1317 //if(refresh) // update loot for new looter
1318 // pl->GetSession()->DoLootRelease(pl->GetLootGUID());
1319 SetLooterGuid(pl->GetGUID());
1320 SendUpdate();
1321 if(refresh) // update loot for new looter
1322 pl->SendLoot(creature->GetGUID(),LOOT_CORPSE);
1323 return;
1328 SetLooterGuid(0);
1329 SendUpdate();
1332 uint32 Group::CanJoinBattleGroundQueue(BattleGroundTypeId bgTypeId, BattleGroundQueueTypeId bgQueueTypeId, uint32 MinPlayerCount, uint32 MaxPlayerCount, bool isRated, uint32 arenaSlot)
1334 // check for min / max count
1335 uint32 memberscount = GetMembersCount();
1336 if(memberscount < MinPlayerCount)
1337 return BG_JOIN_ERR_GROUP_NOT_ENOUGH;
1338 if(memberscount > MaxPlayerCount)
1339 return BG_JOIN_ERR_GROUP_TOO_MANY;
1341 // get a player as reference, to compare other players' stats to (arena team id, queue id based on level, etc.)
1342 Player * reference = GetFirstMember()->getSource();
1343 // no reference found, can't join this way
1344 if(!reference)
1345 return BG_JOIN_ERR_OFFLINE_MEMBER;
1347 uint32 queue_id = reference->GetBattleGroundQueueIdFromLevel(bgTypeId);
1348 uint32 arenaTeamId = reference->GetArenaTeamId(arenaSlot);
1349 uint32 team = reference->GetTeam();
1351 // check every member of the group to be able to join
1352 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
1354 Player *member = itr->getSource();
1355 // offline member? don't let join
1356 if(!member)
1357 return BG_JOIN_ERR_OFFLINE_MEMBER;
1358 // don't allow cross-faction join as group
1359 if(member->GetTeam() != team)
1360 return BG_JOIN_ERR_MIXED_FACTION;
1361 // not in the same battleground level braket, don't let join
1362 if(member->GetBattleGroundQueueIdFromLevel(bgTypeId) != queue_id)
1363 return BG_JOIN_ERR_MIXED_LEVELS;
1364 // don't let join rated matches if the arena team id doesn't match
1365 if(isRated && member->GetArenaTeamId(arenaSlot) != arenaTeamId)
1366 return BG_JOIN_ERR_MIXED_ARENATEAM;
1367 // don't let join if someone from the group is already in that bg queue
1368 if(member->InBattleGroundQueueForBattleGroundQueueType(bgQueueTypeId))
1369 return BG_JOIN_ERR_GROUP_MEMBER_ALREADY_IN_QUEUE;
1370 // check for deserter debuff in case not arena queue
1371 if(bgTypeId != BATTLEGROUND_AA && !member->CanJoinToBattleground())
1372 return BG_JOIN_ERR_GROUP_DESERTER;
1373 // check if member can join any more battleground queues
1374 if(!member->HasFreeBattleGroundQueueId())
1375 return BG_JOIN_ERR_ALL_QUEUES_USED;
1377 return BG_JOIN_ERR_OK;
1380 //===================================================
1381 //============== Roll ===============================
1382 //===================================================
1384 void Roll::targetObjectBuildLink()
1386 // called from link()
1387 getTarget()->addLootValidatorRef(this);
1390 void Group::SetDifficulty(uint8 difficulty)
1392 m_difficulty = difficulty;
1393 if(!isBGGroup()) CharacterDatabase.PExecute("UPDATE groups SET difficulty = %u WHERE leaderGuid ='%u'", m_difficulty, GUID_LOPART(m_leaderGuid));
1395 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
1397 Player *player = itr->getSource();
1398 if(!player->GetSession() || player->getLevel() < LEVELREQUIREMENT_HEROIC)
1399 continue;
1400 player->SetDifficulty(difficulty);
1401 player->SendDungeonDifficulty(true);
1405 bool Group::InCombatToInstance(uint32 instanceId)
1407 for(GroupReference *itr = GetFirstMember(); itr != NULL; itr = itr->next())
1409 Player *pPlayer = itr->getSource();
1410 if(pPlayer->getAttackers().size() && pPlayer->GetInstanceId() == instanceId)
1411 return true;
1413 return false;
1416 void Group::ResetInstances(uint8 method, Player* SendMsgTo)
1418 if(isBGGroup())
1419 return;
1421 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_DISBAND
1423 // we assume that when the difficulty changes, all instances that can be reset will be
1424 uint8 dif = GetDifficulty();
1426 for(BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
1428 InstanceSave *p = itr->second.save;
1429 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
1430 if(!entry || (!p->CanReset() && method != INSTANCE_RESET_GROUP_DISBAND))
1432 ++itr;
1433 continue;
1436 if(method == INSTANCE_RESET_ALL)
1438 // the "reset all instances" method can only reset normal maps
1439 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
1441 ++itr;
1442 continue;
1446 bool isEmpty = true;
1447 // if the map is loaded, reset it
1448 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
1449 if(map && map->IsDungeon())
1450 isEmpty = ((InstanceMap*)map)->Reset(method);
1452 if(SendMsgTo)
1454 if(isEmpty) SendMsgTo->SendResetInstanceSuccess(p->GetMapId());
1455 else SendMsgTo->SendResetInstanceFailed(0, p->GetMapId());
1458 if(isEmpty || method == INSTANCE_RESET_GROUP_DISBAND || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
1460 // do not reset the instance, just unbind if others are permanently bound to it
1461 if(p->CanReset()) p->DeleteFromDB();
1462 else CharacterDatabase.PExecute("DELETE FROM group_instance WHERE instance = '%u'", p->GetInstanceId());
1463 // i don't know for sure if hash_map iterators
1464 m_boundInstances[dif].erase(itr);
1465 itr = m_boundInstances[dif].begin();
1466 // this unloads the instance save unless online players are bound to it
1467 // (eg. permanent binds or GM solo binds)
1468 p->RemoveGroup(this);
1470 else
1471 ++itr;
1475 InstanceGroupBind* Group::GetBoundInstance(uint32 mapid, uint8 difficulty)
1477 // some instances only have one difficulty
1478 const MapEntry* entry = sMapStore.LookupEntry(mapid);
1479 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
1481 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
1482 if(itr != m_boundInstances[difficulty].end())
1483 return &itr->second;
1484 else
1485 return NULL;
1488 InstanceGroupBind* Group::BindToInstance(InstanceSave *save, bool permanent, bool load)
1490 if(save && !isBGGroup())
1492 InstanceGroupBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
1493 if(bind.save)
1495 // when a boss is killed or when copying the players's binds to the group
1496 if(permanent != bind.perm || save != bind.save)
1497 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());
1499 else
1500 if(!load) CharacterDatabase.PExecute("INSERT INTO group_instance (leaderGuid, instance, permanent) VALUES ('%u', '%u', '%u')", GUID_LOPART(GetLeaderGUID()), save->GetInstanceId(), permanent);
1502 if(bind.save != save)
1504 if(bind.save) bind.save->RemoveGroup(this);
1505 save->AddGroup(this);
1508 bind.save = save;
1509 bind.perm = permanent;
1510 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());
1511 return &bind;
1513 else
1514 return NULL;
1517 void Group::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
1519 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
1520 if(itr != m_boundInstances[difficulty].end())
1522 if(!unload) CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u' AND instance = '%u'", GUID_LOPART(GetLeaderGUID()), itr->second.save->GetInstanceId());
1523 itr->second.save->RemoveGroup(this); // save can become invalid
1524 m_boundInstances[difficulty].erase(itr);
1528 void Group::_homebindIfInstance(Player *player)
1530 if(player && !player->isGameMaster() && sMapStore.LookupEntry(player->GetMapId())->IsDungeon())
1532 // leaving the group in an instance, the homebind timer is started
1533 // unless the player is permanently saved to the instance
1534 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(player->GetInstanceId());
1535 InstancePlayerBind *playerBind = save ? player->GetBoundInstance(save->GetMapId(), save->GetDifficulty()) : NULL;
1536 if(!playerBind || !playerBind->perm)
1537 player->m_InstanceValid = false;