Implemented gameobjects and creatures grouping (pools of them)
[getmangos.git] / src / game / GameObject.cpp
blob5f7cf6c4be77447109e12eabf719b8684f81b982
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 "QuestDef.h"
21 #include "GameObject.h"
22 #include "ObjectMgr.h"
23 #include "PoolHandler.h"
24 #include "SpellMgr.h"
25 #include "Spell.h"
26 #include "UpdateMask.h"
27 #include "Opcodes.h"
28 #include "WorldPacket.h"
29 #include "WorldSession.h"
30 #include "World.h"
31 #include "Database/DatabaseEnv.h"
32 #include "MapManager.h"
33 #include "LootMgr.h"
34 #include "GridNotifiers.h"
35 #include "GridNotifiersImpl.h"
36 #include "CellImpl.h"
37 #include "InstanceData.h"
38 #include "BattleGround.h"
39 #include "Util.h"
41 GameObject::GameObject() : WorldObject()
43 m_objectType |= TYPEMASK_GAMEOBJECT;
44 m_objectTypeId = TYPEID_GAMEOBJECT;
45 // 2.3.2 - 0x58
46 m_updateFlag = (UPDATEFLAG_LOWGUID | UPDATEFLAG_HIGHGUID | UPDATEFLAG_HAS_POSITION);
48 m_valuesCount = GAMEOBJECT_END;
49 m_respawnTime = 0;
50 m_respawnDelayTime = 25;
51 m_lootState = GO_NOT_READY;
52 m_spawnedByDefault = true;
53 m_usetimes = 0;
54 m_spellId = 0;
55 m_charges = 5;
56 m_cooldownTime = 0;
57 m_goInfo = NULL;
59 m_DBTableGuid = 0;
62 GameObject::~GameObject()
64 if(m_uint32Values) // field array can be not exist if GameOBject not loaded
66 // Possible crash at access to deleted GO in Unit::m_gameobj
67 uint64 owner_guid = GetOwnerGUID();
68 if(owner_guid)
70 Unit* owner = ObjectAccessor::GetUnit(*this,owner_guid);
71 if(owner)
72 owner->RemoveGameObject(this,false);
73 else if(!IS_PLAYER_GUID(owner_guid))
74 sLog.outError("Delete GameObject (GUID: %u Entry: %u ) that have references in not found creature %u GO list. Crash possible later.",GetGUIDLow(),GetGOInfo()->id,GUID_LOPART(owner_guid));
79 void GameObject::AddToWorld()
81 ///- Register the gameobject for guid lookup
82 if(!IsInWorld()) ObjectAccessor::Instance().AddObject(this);
83 Object::AddToWorld();
86 void GameObject::RemoveFromWorld()
88 ///- Remove the gameobject from the accessor
89 if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
90 Object::RemoveFromWorld();
93 bool GameObject::Create(uint32 guidlow, uint32 name_id, Map *map, uint32 phaseMask, float x, float y, float z, float ang, float rotation0, float rotation1, float rotation2, float rotation3, uint32 animprogress, uint32 go_state)
95 Relocate(x,y,z,ang);
96 SetMapId(map->GetId());
97 SetInstanceId(map->GetInstanceId());
98 SetPhaseMask(phaseMask,false);
100 if(!IsPositionValid())
102 sLog.outError("ERROR: Gameobject (GUID: %u Entry: %u ) not created. Suggested coordinates isn't valid (X: %f Y: %f)",guidlow,name_id,x,y);
103 return false;
106 GameObjectInfo const* goinfo = objmgr.GetGameObjectInfo(name_id);
107 if (!goinfo)
109 sLog.outErrorDb("Gameobject (GUID: %u Entry: %u) not created: it have not exist entry in `gameobject_template`. Map: %u (X: %f Y: %f Z: %f) ang: %f rotation0: %f rotation1: %f rotation2: %f rotation3: %f",guidlow, name_id, map->GetId(), x, y, z, ang, rotation0, rotation1, rotation2, rotation3);
110 return false;
113 Object::_Create(guidlow, goinfo->id, HIGHGUID_GAMEOBJECT);
115 m_goInfo = goinfo;
117 if (goinfo->type >= MAX_GAMEOBJECT_TYPE)
119 sLog.outErrorDb("Gameobject (GUID: %u Entry: %u) not created: it have not exist GO type '%u' in `gameobject_template`. It's will crash client if created.",guidlow,name_id,goinfo->type);
120 return false;
123 SetFloatValue(GAMEOBJECT_POS_X, x);
124 SetFloatValue(GAMEOBJECT_POS_Y, y);
125 SetFloatValue(GAMEOBJECT_POS_Z, z);
126 SetFloatValue(GAMEOBJECT_FACING, ang); //this is not facing angle
128 int64 rotation = 0;
130 float f_rot1 = sin(ang / 2.0f);
131 int64 i_rot1 = f_rot1 / atan(pow(2.0f, -20.0f));
132 rotation |= (i_rot1 << 43 >> 43) & 0x00000000001FFFFF;
134 //float f_rot2 = sin(0.0f / 2.0f);
135 //int64 i_rot2 = f_rot2 / atan(pow(2.0f, -20.0f));
136 //rotation |= (((i_rot2 << 22) >> 32) >> 11) & 0x000003FFFFE00000;
138 //float f_rot3 = sin(0.0f / 2.0f);
139 //int64 i_rot3 = f_rot3 / atan(pow(2.0f, -21.0f));
140 //rotation |= (i_rot3 >> 42) & 0x7FFFFC0000000000;
142 SetUInt64Value(GAMEOBJECT_ROTATION, rotation);
144 SetFloatValue(GAMEOBJECT_PARENTROTATION+0, rotation0);
145 SetFloatValue(GAMEOBJECT_PARENTROTATION+1, rotation1);
146 SetFloatValue(GAMEOBJECT_PARENTROTATION+2, rotation2);
147 SetFloatValue(GAMEOBJECT_PARENTROTATION+3, rotation3);
149 SetFloatValue(OBJECT_FIELD_SCALE_X, goinfo->size);
151 SetUInt32Value(GAMEOBJECT_FACTION, goinfo->faction);
152 SetUInt32Value(GAMEOBJECT_FLAGS, goinfo->flags);
154 SetEntry(goinfo->id);
156 SetUInt32Value(GAMEOBJECT_DISPLAYID, goinfo->displayId);
158 SetGoState(go_state);
159 SetGoType(GameobjectTypes(goinfo->type));
161 SetGoAnimProgress(animprogress);
163 // Spell charges for GAMEOBJECT_TYPE_SPELLCASTER (22)
164 if (goinfo->type == GAMEOBJECT_TYPE_SPELLCASTER)
165 m_charges = goinfo->spellcaster.charges;
167 //Notify the map's instance data.
168 //Only works if you create the object in it, not if it is moves to that map.
169 //Normally non-players do not teleport to other maps.
170 if(map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
172 ((InstanceMap*)map)->GetInstanceData()->OnObjectCreate(this);
175 return true;
178 void GameObject::Update(uint32 /*p_time*/)
180 if (IS_MO_TRANSPORT(GetGUID()))
182 //((Transport*)this)->Update(p_time);
183 return;
186 switch (m_lootState)
188 case GO_NOT_READY:
190 switch(GetGoType())
192 case GAMEOBJECT_TYPE_TRAP:
194 // Arming Time for GAMEOBJECT_TYPE_TRAP (6)
195 Unit* owner = GetOwner();
196 if (owner && ((Player*)owner)->isInCombat())
197 m_cooldownTime = time(NULL) + GetGOInfo()->trap.startDelay;
198 m_lootState = GO_READY;
199 break;
201 case GAMEOBJECT_TYPE_FISHINGNODE:
203 // fishing code (bobber ready)
204 if( time(NULL) > m_respawnTime - FISHING_BOBBER_READY_TIME )
206 // splash bobber (bobber ready now)
207 Unit* caster = GetOwner();
208 if(caster && caster->GetTypeId()==TYPEID_PLAYER)
210 SetGoState(0);
211 SetUInt32Value(GAMEOBJECT_FLAGS, GO_FLAG_NODESPAWN);
213 UpdateData udata;
214 WorldPacket packet;
215 BuildValuesUpdateBlockForPlayer(&udata,((Player*)caster));
216 udata.BuildPacket(&packet);
217 ((Player*)caster)->GetSession()->SendPacket(&packet);
219 WorldPacket data(SMSG_GAMEOBJECT_CUSTOM_ANIM,8+4);
220 data << GetGUID();
221 data << (uint32)(0);
222 ((Player*)caster)->SendMessageToSet(&data,true);
225 m_lootState = GO_READY; // can be successfully open with some chance
227 return;
229 default:
230 m_lootState = GO_READY; // for other GOis same switched without delay to GO_READY
231 break;
233 // NO BREAK for switch (m_lootState)
235 case GO_READY:
237 if (m_respawnTime > 0) // timer on
239 if (m_respawnTime <= time(NULL)) // timer expired
241 m_respawnTime = 0;
242 m_SkillupList.clear();
243 m_usetimes = 0;
245 switch (GetGoType())
247 case GAMEOBJECT_TYPE_FISHINGNODE: // can't fish now
249 Unit* caster = GetOwner();
250 if(caster && caster->GetTypeId()==TYPEID_PLAYER)
252 if(caster->m_currentSpells[CURRENT_CHANNELED_SPELL])
254 caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->SendChannelUpdate(0);
255 caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->finish(false);
258 WorldPacket data(SMSG_FISH_NOT_HOOKED,0);
259 ((Player*)caster)->GetSession()->SendPacket(&data);
261 // can be delete
262 m_lootState = GO_JUST_DEACTIVATED;
263 return;
265 case GAMEOBJECT_TYPE_DOOR:
266 case GAMEOBJECT_TYPE_BUTTON:
267 //we need to open doors if they are closed (add there another condition if this code breaks some usage, but it need to be here for battlegrounds)
268 if( !GetGoState() )
269 SwitchDoorOrButton(false);
270 //flags in AB are type_button and we need to add them here so no break!
271 default:
272 if(!m_spawnedByDefault) // despawn timer
274 // can be despawned or destroyed
275 SetLootState(GO_JUST_DEACTIVATED);
276 return;
278 // respawn timer
279 uint16 poolid = poolhandler.IsPartOfAPool(GetGUIDLow(), TYPEID_GAMEOBJECT);
280 if (poolid)
281 poolhandler.UpdatePool(poolid, GetGUIDLow(), TYPEID_GAMEOBJECT);
282 else
283 GetMap()->Add(this);
284 break;
289 // traps can have time and can not have
290 GameObjectInfo const* goInfo = GetGOInfo();
291 if(goInfo->type == GAMEOBJECT_TYPE_TRAP)
293 // traps
294 Unit* owner = GetOwner();
295 Unit* ok = NULL; // pointer to appropriate target if found any
297 if(m_cooldownTime >= time(NULL))
298 return;
300 bool IsBattleGroundTrap = false;
301 //FIXME: this is activation radius (in different casting radius that must be selected from spell data)
302 //TODO: move activated state code (cast itself) to GO_ACTIVATED, in this place only check activating and set state
303 float radius = goInfo->trap.radius;
304 if(!radius)
306 if(goInfo->trap.cooldown != 3) // cast in other case (at some triggering/linked go/etc explicit call)
307 return;
308 else
310 if(m_respawnTime > 0)
311 break;
313 radius = goInfo->trap.cooldown; // battlegrounds gameobjects has data2 == 0 && data5 == 3
314 IsBattleGroundTrap = true;
318 bool NeedDespawn = (goInfo->trap.charges != 0);
320 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
321 Cell cell(p);
322 cell.data.Part.reserved = ALL_DISTRICT;
324 // Note: this hack with search required until GO casting not implemented
325 // search unfriendly creature
326 if(owner && NeedDespawn) // hunter trap
328 MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, owner, radius);
329 MaNGOS::UnitSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> checker(this,ok, u_check);
331 CellLock<GridReadGuard> cell_lock(cell, p);
333 TypeContainerVisitor<MaNGOS::UnitSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_object_checker(checker);
334 cell_lock->Visit(cell_lock, grid_object_checker, *GetMap());
336 // or unfriendly player/pet
337 if(!ok)
339 TypeContainerVisitor<MaNGOS::UnitSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_object_checker(checker);
340 cell_lock->Visit(cell_lock, world_object_checker, *GetMap());
343 else // environmental trap
345 // environmental damage spells already have around enemies targeting but this not help in case not existed GO casting support
347 // affect only players
348 Player* p_ok = NULL;
349 MaNGOS::AnyPlayerInObjectRangeCheck p_check(this, radius);
350 MaNGOS::PlayerSearcher<MaNGOS::AnyPlayerInObjectRangeCheck> checker(this,p_ok, p_check);
352 CellLock<GridReadGuard> cell_lock(cell, p);
354 TypeContainerVisitor<MaNGOS::PlayerSearcher<MaNGOS::AnyPlayerInObjectRangeCheck>, WorldTypeMapContainer > world_object_checker(checker);
355 cell_lock->Visit(cell_lock, world_object_checker, *GetMap());
356 ok = p_ok;
359 if (ok)
361 Unit *caster = owner ? owner : ok;
363 caster->CastSpell(ok, goInfo->trap.spellId, true, 0, 0, GetGUID());
364 m_cooldownTime = time(NULL) + 4; // 4 seconds
366 if(NeedDespawn)
367 SetLootState(GO_JUST_DEACTIVATED); // can be despawned or destroyed
369 if(IsBattleGroundTrap && ok->GetTypeId() == TYPEID_PLAYER)
371 //BattleGround gameobjects case
372 if(((Player*)ok)->InBattleGround())
373 if(BattleGround *bg = ((Player*)ok)->GetBattleGround())
374 bg->HandleTriggerBuff(GetGUID());
379 if (m_charges && m_usetimes >= m_charges)
380 SetLootState(GO_JUST_DEACTIVATED); // can be despawned or destroyed
382 break;
384 case GO_ACTIVATED:
386 switch(GetGoType())
388 case GAMEOBJECT_TYPE_DOOR:
389 case GAMEOBJECT_TYPE_BUTTON:
390 if(GetAutoCloseTime() && (m_cooldownTime < time(NULL)))
392 SwitchDoorOrButton(false);
393 SetLootState(GO_JUST_DEACTIVATED);
395 break;
397 break;
399 case GO_JUST_DEACTIVATED:
401 //if Gameobject should cast spell, then this, but some GOs (type = 10) should be destroyed
402 if (GetGoType() == GAMEOBJECT_TYPE_GOOBER)
404 uint32 spellId = GetGOInfo()->goober.spellId;
406 if(spellId)
408 std::set<uint32>::iterator it = m_unique_users.begin();
409 std::set<uint32>::iterator end = m_unique_users.end();
410 for (; it != end; it++)
412 Unit* owner = Unit::GetUnit(*this, uint64(*it));
413 if (owner) owner->CastSpell(owner, spellId, false, 0, 0, GetGUID());
416 m_unique_users.clear();
417 m_usetimes = 0;
419 //any return here in case battleground traps
422 if(GetOwnerGUID())
424 m_respawnTime = 0;
425 Delete();
426 return;
429 //burning flags in some battlegrounds, if you find better condition, just add it
430 if (GetGoAnimProgress() > 0)
432 SendObjectDeSpawnAnim(GetGUID());
433 //reset flags
434 SetUInt32Value(GAMEOBJECT_FLAGS, GetGOInfo()->flags);
437 loot.clear();
438 SetLootState(GO_READY);
440 if(!m_respawnDelayTime)
441 return;
443 if(!m_spawnedByDefault)
445 m_respawnTime = 0;
446 return;
449 m_respawnTime = time(NULL) + m_respawnDelayTime;
451 // if option not set then object will be saved at grid unload
452 if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY))
453 SaveRespawnTime();
455 ObjectAccessor::UpdateObjectVisibility(this);
457 break;
462 void GameObject::Refresh()
464 // not refresh despawned not casted GO (despawned casted GO destroyed in all cases anyway)
465 if(m_respawnTime > 0 && m_spawnedByDefault)
466 return;
468 if(isSpawned())
469 GetMap()->Add(this);
472 void GameObject::AddUniqueUse(Player* player)
474 AddUse();
475 m_unique_users.insert(player->GetGUIDLow());
478 void GameObject::Delete()
480 SendObjectDeSpawnAnim(GetGUID());
482 SetGoState(1);
483 SetUInt32Value(GAMEOBJECT_FLAGS, GetGOInfo()->flags);
485 uint16 poolid = poolhandler.IsPartOfAPool(GetGUIDLow(), TYPEID_GAMEOBJECT);
486 if (poolid)
487 poolhandler.UpdatePool(poolid, GetGUIDLow(), TYPEID_GAMEOBJECT);
488 else
489 AddObjectToRemoveList();
492 void GameObject::getFishLoot(Loot *fishloot, Player* loot_owner)
494 fishloot->clear();
496 uint32 subzone = GetAreaId();
498 // if subzone loot exist use it
499 if(LootTemplates_Fishing.HaveLootFor(subzone))
500 fishloot->FillLoot(subzone, LootTemplates_Fishing, loot_owner,true);
501 // else use zone loot
502 else
503 fishloot->FillLoot(GetZoneId(), LootTemplates_Fishing, loot_owner,true);
506 void GameObject::SaveToDB()
508 // this should only be used when the gameobject has already been loaded
509 // preferably after adding to map, because mapid may not be valid otherwise
510 GameObjectData const *data = objmgr.GetGOData(m_DBTableGuid);
511 if(!data)
513 sLog.outError("GameObject::SaveToDB failed, cannot get gameobject data!");
514 return;
517 SaveToDB(GetMapId(), data->spawnMask, data->phaseMask);
520 void GameObject::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask)
522 const GameObjectInfo *goI = GetGOInfo();
524 if (!goI)
525 return;
527 if (!m_DBTableGuid)
528 m_DBTableGuid = GetGUIDLow();
529 // update in loaded data (changing data only in this place)
530 GameObjectData& data = objmgr.NewGOData(m_DBTableGuid);
532 // data->guid = guid don't must be update at save
533 data.id = GetEntry();
534 data.mapid = mapid;
535 data.phaseMask = phaseMask;
536 data.posX = GetFloatValue(GAMEOBJECT_POS_X);
537 data.posY = GetFloatValue(GAMEOBJECT_POS_Y);
538 data.posZ = GetFloatValue(GAMEOBJECT_POS_Z);
539 data.orientation = GetFloatValue(GAMEOBJECT_FACING);
540 data.rotation0 = GetFloatValue(GAMEOBJECT_PARENTROTATION+0);
541 data.rotation1 = GetFloatValue(GAMEOBJECT_PARENTROTATION+1);
542 data.rotation2 = GetFloatValue(GAMEOBJECT_PARENTROTATION+2);
543 data.rotation3 = GetFloatValue(GAMEOBJECT_PARENTROTATION+3);
544 data.spawntimesecs = m_spawnedByDefault ? m_respawnDelayTime : -(int32)m_respawnDelayTime;
545 data.animprogress = GetGoAnimProgress();
546 data.go_state = GetGoState();
547 data.spawnMask = spawnMask;
549 // updated in DB
550 std::ostringstream ss;
551 ss << "INSERT INTO gameobject VALUES ( "
552 << m_DBTableGuid << ", "
553 << GetEntry() << ", "
554 << mapid << ", "
555 << (uint32)spawnMask << ", "
556 << (uint32)GetPhaseMask() << ","
557 << GetFloatValue(GAMEOBJECT_POS_X) << ", "
558 << GetFloatValue(GAMEOBJECT_POS_Y) << ", "
559 << GetFloatValue(GAMEOBJECT_POS_Z) << ", "
560 << GetFloatValue(GAMEOBJECT_FACING) << ", "
561 << GetFloatValue(GAMEOBJECT_PARENTROTATION) << ", "
562 << GetFloatValue(GAMEOBJECT_PARENTROTATION+1) << ", "
563 << GetFloatValue(GAMEOBJECT_PARENTROTATION+2) << ", "
564 << GetFloatValue(GAMEOBJECT_PARENTROTATION+3) << ", "
565 << m_respawnDelayTime << ", "
566 << (uint32)GetGoAnimProgress() << ", "
567 << (uint32)GetGoState() << ")";
569 WorldDatabase.BeginTransaction();
570 WorldDatabase.PExecuteLog("DELETE FROM gameobject WHERE guid = '%u'", m_DBTableGuid);
571 WorldDatabase.PExecuteLog( ss.str( ).c_str( ) );
572 WorldDatabase.CommitTransaction();
575 bool GameObject::LoadFromDB(uint32 guid, Map *map)
577 GameObjectData const* data = objmgr.GetGOData(guid);
579 if( !data )
581 sLog.outErrorDb("ERROR: Gameobject (GUID: %u) not found in table `gameobject`, can't load. ",guid);
582 return false;
585 uint32 entry = data->id;
586 //uint32 map_id = data->mapid; // already used before call
587 uint32 phaseMask = data->phaseMask;
588 float x = data->posX;
589 float y = data->posY;
590 float z = data->posZ;
591 float ang = data->orientation;
593 float rotation0 = data->rotation0;
594 float rotation1 = data->rotation1;
595 float rotation2 = data->rotation2;
596 float rotation3 = data->rotation3;
598 uint32 animprogress = data->animprogress;
599 uint32 go_state = data->go_state;
601 m_DBTableGuid = guid;
602 if (map->GetInstanceId() != 0) guid = objmgr.GenerateLowGuid(HIGHGUID_GAMEOBJECT);
604 if (!Create(guid,entry, map, phaseMask, x, y, z, ang, rotation0, rotation1, rotation2, rotation3, animprogress, go_state) )
605 return false;
607 switch(GetGOInfo()->type)
609 case GAMEOBJECT_TYPE_DOOR:
610 case GAMEOBJECT_TYPE_BUTTON:
611 /* this code (in comment) isn't correct because in battlegrounds we need despawnable doors and buttons, pls remove
612 SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NODESPAWN);
613 m_spawnedByDefault = true;
614 m_respawnDelayTime = 0;
615 m_respawnTime = 0;
616 break;*/
617 default:
618 if(data->spawntimesecs >= 0)
620 m_spawnedByDefault = true;
621 m_respawnDelayTime = data->spawntimesecs;
622 m_respawnTime = objmgr.GetGORespawnTime(m_DBTableGuid, map->GetInstanceId());
624 // ready to respawn
625 if(m_respawnTime && m_respawnTime <= time(NULL))
627 m_respawnTime = 0;
628 objmgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),0);
631 else
633 m_spawnedByDefault = false;
634 m_respawnDelayTime = -data->spawntimesecs;
635 m_respawnTime = 0;
637 break;
640 return true;
643 void GameObject::DeleteFromDB()
645 objmgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),0);
646 objmgr.DeleteGOData(m_DBTableGuid);
647 WorldDatabase.PExecuteLog("DELETE FROM gameobject WHERE guid = '%u'", m_DBTableGuid);
648 WorldDatabase.PExecuteLog("DELETE FROM game_event_gameobject WHERE guid = '%u'", m_DBTableGuid);
651 GameObject* GameObject::GetGameObject(WorldObject& object, uint64 guid)
653 return ObjectAccessor::GetGameObject(object,guid);
656 GameObjectInfo const *GameObject::GetGOInfo() const
658 return m_goInfo;
661 uint32 GameObject::GetLootId(GameObjectInfo const* ginfo)
663 if (!ginfo)
664 return 0;
666 switch(ginfo->type)
668 case GAMEOBJECT_TYPE_CHEST:
669 return ginfo->chest.lootId;
670 case GAMEOBJECT_TYPE_FISHINGHOLE:
671 return ginfo->fishinghole.lootId;
672 case GAMEOBJECT_TYPE_FISHINGNODE:
673 return ginfo->fishnode.lootId;
674 default:
675 return 0;
679 /*********************************************************/
680 /*** QUEST SYSTEM ***/
681 /*********************************************************/
682 bool GameObject::hasQuest(uint32 quest_id) const
684 QuestRelations const& qr = objmgr.mGOQuestRelations;
685 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
687 if(itr->second==quest_id)
688 return true;
690 return false;
693 bool GameObject::hasInvolvedQuest(uint32 quest_id) const
695 QuestRelations const& qr = objmgr.mGOQuestInvolvedRelations;
696 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
698 if(itr->second==quest_id)
699 return true;
701 return false;
704 bool GameObject::IsTransport() const
706 // If something is marked as a transport, don't transmit an out of range packet for it.
707 GameObjectInfo const * gInfo = GetGOInfo();
708 if(!gInfo) return false;
709 return gInfo->type == GAMEOBJECT_TYPE_TRANSPORT || gInfo->type == GAMEOBJECT_TYPE_MO_TRANSPORT;
712 Unit* GameObject::GetOwner() const
714 return ObjectAccessor::GetUnit(*this, GetOwnerGUID());
717 void GameObject::SaveRespawnTime()
719 if(m_respawnTime > time(NULL) && m_spawnedByDefault)
720 objmgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
723 bool GameObject::isVisibleForInState(Player const* u, bool inVisibleList) const
725 // Not in world
726 if(!IsInWorld() || !u->IsInWorld())
727 return false;
729 // Transport always visible at this step implementation
730 if(IsTransport() && IsInMap(u))
731 return true;
733 // quick check visibility false cases for non-GM-mode
734 if(!u->isGameMaster())
736 // despawned and then not visible for non-GM in GM-mode
737 if(!isSpawned())
738 return false;
740 // special invisibility cases
741 /* TODO: implement trap stealth, take look at spell 2836
742 if(GetGOInfo()->type == GAMEOBJECT_TYPE_TRAP && GetGOInfo()->trap.stealthed && u->IsHostileTo(GetOwner()))
744 if(check stuff here)
745 return false;
749 // check distance
750 return IsWithinDistInMap(u,World::GetMaxVisibleDistanceForObject() +
751 (inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), false);
754 void GameObject::Respawn()
756 if(m_spawnedByDefault && m_respawnTime > 0)
758 m_respawnTime = time(NULL);
759 objmgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),0);
763 bool GameObject::ActivateToQuest( Player *pTarget)const
765 if(!objmgr.IsGameObjectForQuests(GetEntry()))
766 return false;
768 switch(GetGoType())
770 // scan GO chest with loot including quest items
771 case GAMEOBJECT_TYPE_CHEST:
773 if(LootTemplates_Gameobject.HaveQuestLootForPlayer(GetLootId(), pTarget))
774 return true;
775 break;
777 case GAMEOBJECT_TYPE_GOOBER:
779 if(pTarget->GetQuestStatus(GetGOInfo()->goober.questId) == QUEST_STATUS_INCOMPLETE)
780 return true;
781 break;
783 default:
784 break;
787 return false;
790 void GameObject::TriggeringLinkedGameObject( uint32 trapEntry, Unit* target)
792 GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(trapEntry);
793 if(!trapInfo || trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
794 return;
796 SpellEntry const* trapSpell = sSpellStore.LookupEntry(trapInfo->trap.spellId);
797 if(!trapSpell) // checked at load already
798 return;
800 float range = GetSpellMaxRange(sSpellRangeStore.LookupEntry(trapSpell->rangeIndex));
802 // search nearest linked GO
803 GameObject* trapGO = NULL;
805 // using original GO distance
806 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
807 Cell cell(p);
808 cell.data.Part.reserved = ALL_DISTRICT;
810 MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*target,trapEntry,range);
811 MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(this, trapGO,go_check);
813 TypeContainerVisitor<MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
814 CellLock<GridReadGuard> cell_lock(cell, p);
815 cell_lock->Visit(cell_lock, object_checker, *GetMap());
818 // found correct GO
819 // FIXME: when GO casting will be implemented trap must cast spell to target
820 if(trapGO)
821 target->CastSpell(target,trapSpell,true, 0, 0, GetGUID());
824 GameObject* GameObject::LookupFishingHoleAround(float range)
826 GameObject* ok = NULL;
828 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
829 Cell cell(p);
830 cell.data.Part.reserved = ALL_DISTRICT;
831 MaNGOS::NearestGameObjectFishingHole u_check(*this, range);
832 MaNGOS::GameObjectSearcher<MaNGOS::NearestGameObjectFishingHole> checker(this, ok, u_check);
834 CellLock<GridReadGuard> cell_lock(cell, p);
836 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::NearestGameObjectFishingHole>, GridTypeMapContainer > grid_object_checker(checker);
837 cell_lock->Visit(cell_lock, grid_object_checker, *GetMap());
839 return ok;
842 void GameObject::UseDoorOrButton(uint32 time_to_restore)
844 if(m_lootState != GO_READY)
845 return;
847 if(!time_to_restore)
848 time_to_restore = GetAutoCloseTime();
850 SwitchDoorOrButton(true);
851 SetLootState(GO_ACTIVATED);
853 m_cooldownTime = time(NULL) + time_to_restore;
857 void GameObject::SwitchDoorOrButton(bool activate)
859 if(activate)
860 SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
861 else
862 RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
864 if(GetGoState()) //if closed -> open
865 SetGoState(0);
866 else //if open -> close
867 SetGoState(1);
870 void GameObject::Use(Unit* user)
872 // by default spell caster is user
873 Unit* spellCaster = user;
874 uint32 spellId = 0;
876 switch(GetGoType())
878 case GAMEOBJECT_TYPE_DOOR: //0
879 case GAMEOBJECT_TYPE_BUTTON: //1
880 //doors/buttons never really despawn, only reset to default state/flags
881 UseDoorOrButton();
883 // activate script
884 sWorld.ScriptsStart(sGameObjectScripts, GetDBTableGUIDLow(), spellCaster, this);
885 return;
887 case GAMEOBJECT_TYPE_QUESTGIVER: //2
889 if(user->GetTypeId()!=TYPEID_PLAYER)
890 return;
892 Player* player = (Player*)user;
894 player->PrepareQuestMenu( GetGUID() );
895 player->SendPreparedQuest( GetGUID() );
896 return;
898 //Sitting: Wooden bench, chairs enzz
899 case GAMEOBJECT_TYPE_CHAIR: //7
901 GameObjectInfo const* info = GetGOInfo();
902 if(!info)
903 return;
905 if(user->GetTypeId()!=TYPEID_PLAYER)
906 return;
908 Player* player = (Player*)user;
910 // a chair may have n slots. we have to calculate their positions and teleport the player to the nearest one
912 // check if the db is sane
913 if(info->chair.slots > 0)
915 float lowestDist = DEFAULT_VISIBILITY_DISTANCE;
917 float x_lowest = GetPositionX();
918 float y_lowest = GetPositionY();
920 // the object orientation + 1/2 pi
921 // every slot will be on that straight line
922 float orthogonalOrientation = GetOrientation()+M_PI*0.5f;
923 // find nearest slot
924 for(uint32 i=0; i<info->chair.slots; i++)
926 // the distance between this slot and the center of the go - imagine a 1D space
927 float relativeDistance = (info->size*i)-(info->size*(info->chair.slots-1)/2.0f);
929 float x_i = GetPositionX() + relativeDistance * cos(orthogonalOrientation);
930 float y_i = GetPositionY() + relativeDistance * sin(orthogonalOrientation);
932 // calculate the distance between the player and this slot
933 float thisDistance = player->GetDistance2d(x_i, y_i);
935 /* debug code. It will spawn a npc on each slot to visualize them.
936 Creature* helper = player->SummonCreature(14496, x_i, y_i, GetPositionZ(), GetOrientation(), TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 10000);
937 std::ostringstream output;
938 output << i << ": thisDist: " << thisDistance;
939 helper->MonsterSay(output.str().c_str(), LANG_UNIVERSAL, 0);
942 if(thisDistance <= lowestDist)
944 lowestDist = thisDistance;
945 x_lowest = x_i;
946 y_lowest = y_i;
949 player->TeleportTo(GetMapId(), x_lowest, y_lowest, GetPositionZ(), GetOrientation(),TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET);
951 else
953 // fallback, will always work
954 player->TeleportTo(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation(),TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET);
956 player->SetStandState(UNIT_STAND_STATE_SIT_LOW_CHAIR+info->chair.height);
957 return;
959 //big gun, its a spell/aura
960 case GAMEOBJECT_TYPE_GOOBER: //10
962 GameObjectInfo const* info = GetGOInfo();
964 if(user->GetTypeId()==TYPEID_PLAYER)
966 Player* player = (Player*)user;
968 // show page
969 if(info->goober.pageId)
971 WorldPacket data(SMSG_GAMEOBJECT_PAGETEXT, 8);
972 data << GetGUID();
973 player->GetSession()->SendPacket(&data);
976 // possible quest objective for active quests
977 player->CastedCreatureOrGO(info->id, GetGUID(), 0);
980 // cast this spell later if provided
981 spellId = info->goober.spellId;
983 break;
985 case GAMEOBJECT_TYPE_CAMERA: //13
987 GameObjectInfo const* info = GetGOInfo();
988 if(!info)
989 return;
991 if(user->GetTypeId()!=TYPEID_PLAYER)
992 return;
994 Player* player = (Player*)user;
996 if(info->camera.cinematicId)
998 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
999 data << info->camera.cinematicId;
1000 player->GetSession()->SendPacket(&data);
1002 return;
1004 //fishing bobber
1005 case GAMEOBJECT_TYPE_FISHINGNODE: //17
1007 if(user->GetTypeId()!=TYPEID_PLAYER)
1008 return;
1010 Player* player = (Player*)user;
1012 if(player->GetGUID() != GetOwnerGUID())
1013 return;
1015 switch(getLootState())
1017 case GO_READY: // ready for loot
1019 // 1) skill must be >= base_zone_skill
1020 // 2) if skill == base_zone_skill => 5% chance
1021 // 3) chance is linear dependence from (base_zone_skill-skill)
1023 uint32 subzone = GetAreaId();
1025 int32 zone_skill = objmgr.GetFishingBaseSkillLevel( subzone );
1026 if(!zone_skill)
1027 zone_skill = objmgr.GetFishingBaseSkillLevel( GetZoneId() );
1029 //provide error, no fishable zone or area should be 0
1030 if(!zone_skill)
1031 sLog.outErrorDb("Fishable areaId %u are not properly defined in `skill_fishing_base_level`.",subzone);
1033 int32 skill = player->GetSkillValue(SKILL_FISHING);
1034 int32 chance = skill - zone_skill + 5;
1035 int32 roll = irand(1,100);
1037 DEBUG_LOG("Fishing check (skill: %i zone min skill: %i chance %i roll: %i",skill,zone_skill,chance,roll);
1039 if(skill >= zone_skill && chance >= roll)
1041 // prevent removing GO at spell cancel
1042 player->RemoveGameObject(this,false);
1043 SetOwnerGUID(player->GetGUID());
1045 //fish catched
1046 player->UpdateFishingSkill();
1048 GameObject* ok = LookupFishingHoleAround(DEFAULT_VISIBILITY_DISTANCE);
1049 if (ok)
1051 player->SendLoot(ok->GetGUID(),LOOT_FISHINGHOLE);
1052 SetLootState(GO_JUST_DEACTIVATED);
1054 else
1055 player->SendLoot(GetGUID(),LOOT_FISHING);
1057 else
1059 // fish escaped, can be deleted now
1060 SetLootState(GO_JUST_DEACTIVATED);
1062 WorldPacket data(SMSG_FISH_ESCAPED, 0);
1063 player->GetSession()->SendPacket(&data);
1065 break;
1067 case GO_JUST_DEACTIVATED: // nothing to do, will be deleted at next update
1068 break;
1069 default:
1071 SetLootState(GO_JUST_DEACTIVATED);
1073 WorldPacket data(SMSG_FISH_NOT_HOOKED, 0);
1074 player->GetSession()->SendPacket(&data);
1075 break;
1079 if(player->m_currentSpells[CURRENT_CHANNELED_SPELL])
1081 player->m_currentSpells[CURRENT_CHANNELED_SPELL]->SendChannelUpdate(0);
1082 player->m_currentSpells[CURRENT_CHANNELED_SPELL]->finish();
1084 return;
1087 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
1089 if(user->GetTypeId()!=TYPEID_PLAYER)
1090 return;
1092 Player* player = (Player*)user;
1094 Unit* caster = GetOwner();
1096 GameObjectInfo const* info = GetGOInfo();
1098 if( !caster || caster->GetTypeId()!=TYPEID_PLAYER )
1099 return;
1101 // accept only use by player from same group for caster except caster itself
1102 if(((Player*)caster)==player || !((Player*)caster)->IsInSameRaidWith(player))
1103 return;
1105 AddUniqueUse(player);
1107 // full amount unique participants including original summoner
1108 if(GetUniqueUseCount() < info->summoningRitual.reqParticipants)
1109 return;
1111 // in case summoning ritual caster is GO creator
1112 spellCaster = caster;
1114 if(!caster->m_currentSpells[CURRENT_CHANNELED_SPELL])
1115 return;
1117 spellId = info->summoningRitual.spellId;
1119 // finish spell
1120 caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->SendChannelUpdate(0);
1121 caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->finish();
1123 // can be deleted now
1124 SetLootState(GO_JUST_DEACTIVATED);
1126 // go to end function to spell casting
1127 break;
1129 case GAMEOBJECT_TYPE_SPELLCASTER: //22
1131 SetUInt32Value(GAMEOBJECT_FLAGS,2);
1133 GameObjectInfo const* info = GetGOInfo();
1134 if(!info)
1135 return;
1137 if(info->spellcaster.partyOnly)
1139 Unit* caster = GetOwner();
1140 if( !caster || caster->GetTypeId()!=TYPEID_PLAYER )
1141 return;
1143 if(user->GetTypeId()!=TYPEID_PLAYER || !((Player*)user)->IsInSameRaidWith((Player*)caster))
1144 return;
1147 spellId = info->spellcaster.spellId;
1149 AddUse();
1150 break;
1152 case GAMEOBJECT_TYPE_MEETINGSTONE: //23
1154 GameObjectInfo const* info = GetGOInfo();
1156 if(user->GetTypeId()!=TYPEID_PLAYER)
1157 return;
1159 Player* player = (Player*)user;
1161 Player* targetPlayer = ObjectAccessor::FindPlayer(player->GetSelection());
1163 // accept only use by player from same group for caster except caster itself
1164 if(!targetPlayer || targetPlayer == player || !targetPlayer->IsInSameGroupWith(player))
1165 return;
1167 //required lvl checks!
1168 uint8 level = player->getLevel();
1169 if (level < info->meetingstone.minLevel || level > info->meetingstone.maxLevel)
1170 return;
1171 level = targetPlayer->getLevel();
1172 if (level < info->meetingstone.minLevel || level > info->meetingstone.maxLevel)
1173 return;
1175 spellId = 23598;
1177 break;
1180 case GAMEOBJECT_TYPE_FLAGSTAND: // 24
1182 if(user->GetTypeId()!=TYPEID_PLAYER)
1183 return;
1185 Player* player = (Player*)user;
1187 if( player->isAllowUseBattleGroundObject() )
1189 // in battleground check
1190 BattleGround *bg = player->GetBattleGround();
1191 if(!bg)
1192 return;
1193 // BG flag click
1194 // AB:
1195 // 15001
1196 // 15002
1197 // 15003
1198 // 15004
1199 // 15005
1200 bg->EventPlayerClickedOnFlag(player, this);
1201 return; //we don;t need to delete flag ... it is despawned!
1203 break;
1205 case GAMEOBJECT_TYPE_FLAGDROP: // 26
1207 if(user->GetTypeId()!=TYPEID_PLAYER)
1208 return;
1210 Player* player = (Player*)user;
1212 if( player->isAllowUseBattleGroundObject() )
1214 // in battleground check
1215 BattleGround *bg = player->GetBattleGround();
1216 if(!bg)
1217 return;
1218 // BG flag dropped
1219 // WS:
1220 // 179785 - Silverwing Flag
1221 // 179786 - Warsong Flag
1222 // EotS:
1223 // 184142 - Netherstorm Flag
1224 GameObjectInfo const* info = GetGOInfo();
1225 if(info)
1227 switch(info->id)
1229 case 179785: // Silverwing Flag
1230 // check if it's correct bg
1231 if(bg->GetTypeID() == BATTLEGROUND_WS)
1232 bg->EventPlayerClickedOnFlag(player, this);
1233 break;
1234 case 179786: // Warsong Flag
1235 if(bg->GetTypeID() == BATTLEGROUND_WS)
1236 bg->EventPlayerClickedOnFlag(player, this);
1237 break;
1238 case 184142: // Netherstorm Flag
1239 if(bg->GetTypeID() == BATTLEGROUND_EY)
1240 bg->EventPlayerClickedOnFlag(player, this);
1241 break;
1244 //this cause to call return, all flags must be deleted here!!
1245 spellId = 0;
1246 Delete();
1248 break;
1250 case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
1252 GameObjectInfo const* info = GetGOInfo();
1253 if(!info)
1254 return;
1256 if(user->GetTypeId()!=TYPEID_PLAYER)
1257 return;
1259 Player* player = (Player*)user;
1261 // fallback, will always work
1262 player->TeleportTo(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation(),TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET);
1264 WorldPacket data(SMSG_ENABLE_BARBER_SHOP, 0);
1265 player->GetSession()->SendPacket(&data);
1267 player->SetStandState(UNIT_STAND_STATE_SIT_LOW_CHAIR+info->barberChair.chairheight);
1268 return;
1270 default:
1271 sLog.outDebug("Unknown Object Type %u", GetGoType());
1272 break;
1275 if(!spellId)
1276 return;
1278 SpellEntry const *spellInfo = sSpellStore.LookupEntry( spellId );
1279 if(!spellInfo)
1281 sLog.outError("WORLD: unknown spell id %u at use action for gameobject (Entry: %u GoType: %u )", spellId,GetEntry(),GetGoType());
1282 return;
1285 Spell *spell = new Spell(spellCaster, spellInfo, false);
1287 // spell target is user of GO
1288 SpellCastTargets targets;
1289 targets.setUnitTarget( user );
1291 spell->prepare(&targets);
1294 // overwrite WorldObject function for proper name localization
1295 const char* GameObject::GetNameForLocaleIdx(int32 loc_idx) const
1297 if (loc_idx >= 0)
1299 GameObjectLocale const *cl = objmgr.GetGameObjectLocale(GetEntry());
1300 if (cl)
1302 if (cl->Name.size() > loc_idx && !cl->Name[loc_idx].empty())
1303 return cl->Name[loc_idx].c_str();
1307 return GetName();