repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
leoloso/PoP | layers/Legacy/Schema/packages/migrate-everythingelse/migrate/plugins/pop-locationposts-processors/library/processor-hooks/submenu-hooks.php | 975 | <?php
class PoP_CommonPages_EM_SubmenuHooks
{
public function __construct()
{
// Execute before the Events, so it can add the page right next to "All Content" button
\PoP\Root\App::addFilter(
'PoP_Module_Processor_CustomSubMenus:author:routes',
array($this, 'addRoutes'),
2
);
\PoP\Root\App::addFilter(
'PoP_Module_Processor_CustomSubMenus:tag:routes',
array($this, 'addRoutes'),
2
);
}
public function addRoutes($routes)
{
// If the values for the constants were kept in false (eg: Projects not needed for TPP Debate) then don't add them
if (defined('POP_LOCATIONPOSTS_ROUTE_LOCATIONPOSTS') && POP_LOCATIONPOSTS_ROUTE_LOCATIONPOSTS) {
$routes[POP_LOCATIONPOSTS_ROUTE_LOCATIONPOSTS] = array();
}
return $routes;
}
}
/**
* Initialization
*/
new PoP_CommonPages_EM_SubmenuHooks();
| gpl-2.0 |
dlitz/resin | modules/resin/src/com/caucho/boot/ResultStatus.java | 1852 | /*
* Copyright (c) 1998-2011 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.boot;
import java.io.Serializable;
/**
* General result status for watchdog queries
*/
@SuppressWarnings("serial")
public class ResultStatus implements Serializable {
private final boolean _isSuccess;
private final String _message;
@SuppressWarnings("unused")
private ResultStatus()
{
_isSuccess = false;
_message = null;
}
public ResultStatus(boolean isSuccess, String message)
{
_isSuccess = isSuccess;
_message = message;
}
public boolean isSuccess()
{
return _isSuccess;
}
public String getMessage()
{
return _message;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append("[");
sb.append(_isSuccess);
sb.append(", ");
sb.append(_message);
sb.append("]");
return sb.toString();
}
}
| gpl-2.0 |
TeaJizzle/AntiTeaJizzle | src/cx/gg/antiteajizzle/AntiTeaJizzle.java | 997 | package cx.gg.antiteajizzle;
import org.bukkit.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import cx.gg.antiteajizzle.AsyncCheckChunkBedrock;
public class AntiTeaJizzle extends JavaPlugin implements Listener {
//Check chunks for dodgy bedrock
@EventHandler
public void onChunkLoad (ChunkLoadEvent event) {
//check if it's overworld
if (!event.getWorld().getEnvironment().equals(World.Environment.NORMAL)) {
return;
}
if (event.isNewChunk()) {
return;
}
//run task to check for dodgy bedrock
ChunkSnapshot chunk = event.getChunk().getChunkSnapshot();
Bukkit.getServer().getScheduler().runTask((Plugin) this, new AsyncCheckChunkBedrock(chunk, this));
}
public void onEnable() {
Bukkit.getPluginManager().registerEvents(this, this);
}
}
| gpl-2.0 |
georgejhunt/HaitiDictionary.activity | data/words/kalite_kalte_.js | 251 | showWord(["n. "," 1. Tip, varyete. Ki kalite twal sa a. 2. Jan, espès. Sa se yon kalite plant ki ra. 3. Karaktè pozitif. Jera gen anpil kalite, li prèske pa gen defo. 4. Siperyè, ki gen valè, ki pa bon mache. Wonm Babankou se wonm bon kalite."
]) | gpl-2.0 |
atibbs/mysite2015 | wp-content/themes/andrewtibbs2015/content-none.php | 1245 | <?php
/**
* The template part for displaying a message that posts cannot be found
*
* Learn more: {@link https://codex.wordpress.org/Template_Hierarchy}
*
* @package WordPress
* @subpackage Twenty_Fifteen
* @since Twenty Fifteen 1.0
*/
?>
<section class="no-results not-found">
<div class="row">
<div class="medium-12 columns">
<header class="page-header">
<h1 class="page-title"><?php _e( 'Nothing Found', 'twentyfifteen' ); ?></h1>
</header><!-- .page-header -->
<div class="page-content">
<?php if ( is_home() && current_user_can( 'publish_posts' ) ) : ?>
<p><?php printf( __( 'Ready to publish your first post? <a href="%1$s">Get started here</a>.', 'twentyfifteen' ), esc_url( admin_url( 'post-new.php' ) ) ); ?></p>
<?php elseif ( is_search() ) : ?>
<p><?php _e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'twentyfifteen' ); ?></p>
<?php // get_search_form(); ?>
<?php else : ?>
<p><?php _e( 'It seems we can’t find what you’re looking for.', 'twentyfifteen' ); ?></p>
<?php // get_search_form(); ?>
<?php endif; ?>
</div><!-- .page-content -->
</div>
</div>
</section><!-- .no-results -->
| gpl-2.0 |
LordPsyan/WoWSource434_V10 | src/server/shared/Database/Implementation/CharacterDatabase.cpp | 86261 | /*
* Copyright (C) 2013-2015 DeathCore <http://www.noffearrdeathproject.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "CharacterDatabase.h"
void CharacterDatabaseConnection::DoPrepareStatements()
{
if (!m_reconnecting)
m_stmts.resize(MAX_CHARACTERDATABASE_STATEMENTS);
PrepareStatement(CHAR_DEL_QUEST_POOL_SAVE, "DELETE FROM pool_quest_save WHERE pool_id = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_QUEST_POOL_SAVE, "INSERT INTO pool_quest_save (pool_id, quest_id) VALUES (?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_NONEXISTENT_GUILD_BANK_ITEM, "DELETE FROM guild_bank_item WHERE guildid = ? AND TabId = ? AND SlotId = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_EXPIRED_BANS, "UPDATE character_banned SET active = 0 WHERE unbandate <= UNIX_TIMESTAMP() AND unbandate <> bandate", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_GUID_BY_NAME, "SELECT guid FROM characters WHERE name = ?", CONNECTION_BOTH);
PrepareStatement(CHAR_SEL_CHECK_NAME, "SELECT 1 FROM characters WHERE name = ?", CONNECTION_BOTH);
PrepareStatement(CHAR_SEL_CHECK_GUID, "SELECT 1 FROM characters WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_SUM_CHARS, "SELECT COUNT(guid) FROM characters WHERE account = ?", CONNECTION_BOTH);
PrepareStatement(CHAR_SEL_CHAR_CREATE_INFO, "SELECT level, race, class FROM characters WHERE account = ? LIMIT 0, ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHARACTER_BAN, "INSERT INTO character_banned VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, ?, ?, 1)", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHARACTER_BAN, "UPDATE character_banned SET active = 0 WHERE guid = ? AND active != 0", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHARACTER_BAN, "DELETE cb FROM character_banned cb INNER JOIN characters c ON c.guid = cb.guid WHERE c.account = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_BANINFO, "SELECT FROM_UNIXTIME(bandate), unbandate-bandate, active, unbandate, banreason, bannedby FROM character_banned WHERE guid = ? ORDER BY bandate ASC", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_GUID_BY_NAME_FILTER, "SELECT guid, name FROM characters WHERE name LIKE CONCAT('%%', ?, '%%')", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_BANINFO_LIST, "SELECT bandate, unbandate, bannedby, banreason FROM character_banned WHERE guid = ? ORDER BY unbandate", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_BANNED_NAME, "SELECT characters.name FROM characters, character_banned WHERE character_banned.guid = ? AND character_banned.guid = characters.guid", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_ENUM, "SELECT c.guid, c.name, c.race, c.class, c.gender, c.playerBytes, c.playerBytes2, c.level, c.zone, c.map, c.position_x, c.position_y, c.position_z, "
"gm.guildid, c.playerFlags, c.at_login, cp.entry, cp.modelid, cp.level, c.equipmentCache, cb.guid, c.slot "
"FROM characters AS c LEFT JOIN character_pet AS cp ON c.guid = cp.owner AND cp.slot = ? LEFT JOIN guild_member AS gm ON c.guid = gm.guid "
"LEFT JOIN character_banned AS cb ON c.guid = cb.guid AND cb.active = 1 WHERE c.account = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_ENUM_DECLINED_NAME, "SELECT c.guid, c.name, c.race, c.class, c.gender, c.playerBytes, c.playerBytes2, c.level, c.zone, c.map, "
"c.position_x, c.position_y, c.position_z, gm.guildid, c.playerFlags, c.at_login, cp.entry, cp.modelid, cp.level, c.equipmentCache, "
"cb.guid, c.slot, cd.genitive FROM characters AS c LEFT JOIN character_pet AS cp ON c.guid = cp.owner AND cp.slot = ? "
"LEFT JOIN character_declinedname AS cd ON c.guid = cd.guid LEFT JOIN guild_member AS gm ON c.guid = gm.guid "
"LEFT JOIN character_banned AS cb ON c.guid = cb.guid AND cb.active = 1 WHERE c.account = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_FREE_NAME, "SELECT guid, name FROM characters WHERE guid = ? AND account = ? AND (at_login & ?) = ? AND NOT EXISTS (SELECT NULL FROM characters WHERE name = ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_GUID_RACE_ACC_BY_NAME, "SELECT guid, race, account FROM characters WHERE name = ?", CONNECTION_BOTH);
PrepareStatement(CHAR_SEL_CHAR_RACE, "SELECT race FROM characters WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_LEVEL, "SELECT level FROM characters WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_ZONE, "SELECT zone FROM characters WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHARACTER_NAME_DATA, "SELECT race, class, gender, level FROM characters WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_POSITION_XYZ, "SELECT map, position_x, position_y, position_z FROM characters WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_POSITION, "SELECT position_x, position_y, position_z, orientation, map, taxi_path FROM characters WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_DEL_QUEST_STATUS_DAILY, "DELETE FROM character_queststatus_daily", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_QUEST_STATUS_WEEKLY, "DELETE FROM character_queststatus_weekly", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_QUEST_STATUS_MONTHLY, "DELETE FROM character_queststatus_monthly", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_QUEST_STATUS_SEASONAL, "DELETE FROM character_queststatus_seasonal WHERE event = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_QUEST_STATUS_DAILY_CHAR, "DELETE FROM character_queststatus_daily WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_QUEST_STATUS_WEEKLY_CHAR, "DELETE FROM character_queststatus_weekly WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_QUEST_STATUS_MONTHLY_CHAR, "DELETE FROM character_queststatus_monthly WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_QUEST_STATUS_SEASONAL_CHAR, "DELETE FROM character_queststatus_seasonal WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_BATTLEGROUND_RANDOM, "DELETE FROM character_battleground_random", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_BATTLEGROUND_RANDOM, "INSERT INTO character_battleground_random (guid) VALUES (?)", CONNECTION_ASYNC);
// Start LoginQueryHolder content
PrepareStatement(CHAR_SEL_CHARACTER, "SELECT guid, account, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags, "
"position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, "
"resettalents_time, talentTree, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, instance_mode_mask, "
"totalKills, todayKills, yesterdayKills, chosenTitle, watchedFaction, drunk, "
"health, power1, power2, power3, power4, power5, instance_id, speccount, activespec, exploredZones, equipmentCache, knownTitles, actionBars, grantableLevels, currentPetSlot "
"FROM characters WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_GROUP_MEMBER, "SELECT guid FROM group_member WHERE memberGuid = ?", CONNECTION_BOTH);
PrepareStatement(CHAR_SEL_CHARACTER_INSTANCE, "SELECT id, permanent, map, difficulty, resettime FROM character_instance LEFT JOIN instance ON instance = id WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_AURAS, "SELECT caster_guid, spell, effect_mask, recalculate_mask, stackcount, amount0, amount1, amount2, "
"base_amount0, base_amount1, base_amount2, maxduration, remaintime, remaincharges FROM character_aura WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_SPELL, "SELECT spell, active, disabled FROM character_spell WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_QUESTSTATUS, "SELECT quest, status, explored, timer, mobcount1, mobcount2, mobcount3, mobcount4, "
"itemcount1, itemcount2, itemcount3, itemcount4, playercount FROM character_queststatus WHERE guid = ? AND status <> 0", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_DAILYQUESTSTATUS, "SELECT quest, time FROM character_queststatus_daily WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_WEEKLYQUESTSTATUS, "SELECT quest FROM character_queststatus_weekly WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_MONTHLYQUESTSTATUS, "SELECT quest FROM character_queststatus_monthly WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_SEASONALQUESTSTATUS, "SELECT quest, event FROM character_queststatus_seasonal WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHARACTER_DAILYQUESTSTATUS, "INSERT INTO character_queststatus_daily (guid, quest, time) VALUES (?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHARACTER_WEEKLYQUESTSTATUS, "INSERT INTO character_queststatus_weekly (guid, quest) VALUES (?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHARACTER_MONTHLYQUESTSTATUS, "INSERT INTO character_queststatus_monthly (guid, quest) VALUES (?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHARACTER_SEASONALQUESTSTATUS, "INSERT INTO character_queststatus_seasonal (guid, quest, event) VALUES (?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_REPUTATION, "SELECT faction, standing, flags FROM character_reputation WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_INVENTORY, "SELECT creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text, bag, slot, "
"item, itemEntry FROM character_inventory ci JOIN item_instance ii ON ci.item = ii.guid WHERE ci.guid = ? ORDER BY bag, slot", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_ACTIONS, "SELECT a.button, a.action, a.type FROM character_action as a, characters as c WHERE a.guid = c.guid AND a.spec = c.activespec AND a.guid = ? ORDER BY button", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_MAILCOUNT, "SELECT COUNT(id) FROM mail WHERE receiver = ? AND (checked & 1) = 0 AND deliver_time <= ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_MAILDATE, "SELECT MIN(deliver_time) FROM mail WHERE receiver = ? AND (checked & 1) = 0", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_MAIL_COUNT, "SELECT COUNT(*) FROM mail WHERE receiver = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHARACTER_SOCIALLIST, "SELECT friend, flags, note FROM character_social JOIN characters ON characters.guid = character_social.friend WHERE character_social.guid = ? AND deleteinfos_name IS NULL LIMIT 255", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_HOMEBIND, "SELECT mapId, zoneId, posX, posY, posZ FROM character_homebind WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_SPELLCOOLDOWNS, "SELECT spell, item, time FROM character_spell_cooldown WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_DECLINEDNAMES, "SELECT genitive, dative, accusative, instrumental, prepositional FROM character_declinedname WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_GUILD_MEMBER, "SELECT guildid, rank FROM guild_member WHERE guid = ?", CONNECTION_BOTH);
PrepareStatement(CHAR_SEL_GUILD_MEMBER_EXTENDED, "SELECT g.guildid, g.name, gm.rank, gr.rname, gm.pnote, gm.offnote FROM guild g JOIN guild_member gm ON g.guildid = gm.guildid JOIN guild_rank gr ON g.guildid = gr.guildid AND rid = gm.rank WHERE gm.guid = ?", CONNECTION_BOTH);
PrepareStatement(CHAR_SEL_CHARACTER_ACHIEVEMENTS, "SELECT achievement, date FROM character_achievement WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_CRITERIAPROGRESS, "SELECT criteria, counter, date FROM character_achievement_progress WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_EQUIPMENTSETS, "SELECT setguid, setindex, name, iconname, ignore_mask, item0, item1, item2, item3, item4, item5, item6, item7, item8, "
"item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = ? ORDER BY setindex", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_BGDATA, "SELECT instanceId, team, joinX, joinY, joinZ, joinO, joinMapId, taxiStart, taxiEnd, mountSpell FROM character_battleground_data WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_GLYPHS, "SELECT spec, glyph1, glyph2, glyph3, glyph4, glyph5, glyph6, glyph7, glyph8, glyph9 FROM character_glyphs WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_TALENTS, "SELECT spell, spec FROM character_talent WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_SKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_RANDOMBG, "SELECT guid FROM character_battleground_random WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_BANNED, "SELECT guid FROM character_banned WHERE guid = ? AND active = 1", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_QUESTSTATUSREW, "SELECT quest FROM character_queststatus_rewarded WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_ACCOUNT_INSTANCELOCKTIMES, "SELECT instanceId, releaseTime FROM account_instance_times WHERE accountId = ?", CONNECTION_ASYNC);
// End LoginQueryHolder content
PrepareStatement(CHAR_SEL_CHARACTER_ACTIONS_SPEC, "SELECT button, action, type FROM character_action WHERE guid = ? AND spec = ? ORDER BY button", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_MAILITEMS, "SELECT creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text, item_guid, itemEntry, owner_guid FROM mail_items mi JOIN item_instance ii ON mi.item_guid = ii.guid WHERE mail_id = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_AUCTION_ITEMS, "SELECT creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text, itemguid, itemEntry FROM auctionhouse ah JOIN item_instance ii ON ah.itemguid = ii.guid", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_AUCTIONS, "SELECT id, auctioneerguid, itemguid, itemEntry, count, itemowner, buyoutprice, time, buyguid, lastbid, startbid, deposit FROM auctionhouse ah INNER JOIN item_instance ii ON ii.guid = ah.itemguid", CONNECTION_SYNCH);
PrepareStatement(CHAR_INS_AUCTION, "INSERT INTO auctionhouse (id, auctioneerguid, itemguid, itemowner, buyoutprice, time, buyguid, lastbid, startbid, deposit) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_AUCTION, "DELETE FROM auctionhouse WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_AUCTION_BY_TIME, "SELECT id FROM auctionhouse WHERE time <= ? ORDER BY TIME ASC", CONNECTION_SYNCH);
PrepareStatement(CHAR_UPD_AUCTION_BID, "UPDATE auctionhouse SET buyguid = ?, lastbid = ? WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_MAIL, "INSERT INTO mail(id, messageType, stationery, mailTemplateId, sender, receiver, subject, body, has_items, expire_time, deliver_time, money, cod, checked) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_MAIL_BY_ID, "DELETE FROM mail WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_MAIL_ITEM, "INSERT INTO mail_items(mail_id, item_guid, receiver) VALUES (?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_MAIL_ITEM, "DELETE FROM mail_items WHERE item_guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_INVALID_MAIL_ITEM, "DELETE FROM mail_items WHERE item_guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_EMPTY_EXPIRED_MAIL, "DELETE FROM mail WHERE expire_time < ? AND has_items = 0 AND body = ''", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_EXPIRED_MAIL, "SELECT id, messageType, sender, receiver, has_items, expire_time, cod, checked, mailTemplateId FROM mail WHERE expire_time < ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_EXPIRED_MAIL_ITEMS, "SELECT item_guid, itemEntry, mail_id FROM mail_items mi INNER JOIN item_instance ii ON ii.guid = mi.item_guid LEFT JOIN mail mm ON mi.mail_id = mm.id WHERE mm.id IS NOT NULL AND mm.expire_time < ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_UPD_MAIL_RETURNED, "UPDATE mail SET sender = ?, receiver = ?, expire_time = ?, deliver_time = ?, cod = 0, checked = ? WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_MAIL_ITEM_RECEIVER, "UPDATE mail_items SET receiver = ? WHERE item_guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_ITEM_OWNER, "UPDATE item_instance SET owner_guid = ? WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_ITEM_REFUNDS, "SELECT player_guid, paidMoney, paidExtendedCost FROM item_refund_instance WHERE item_guid = ? AND player_guid = ? LIMIT 1", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_ITEM_BOP_TRADE, "SELECT allowedPlayers FROM item_soulbound_trade_data WHERE itemGuid = ? LIMIT 1", CONNECTION_SYNCH);
PrepareStatement(CHAR_DEL_ITEM_BOP_TRADE, "DELETE FROM item_soulbound_trade_data WHERE itemGuid = ? LIMIT 1", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_ITEM_BOP_TRADE, "INSERT INTO item_soulbound_trade_data VALUES (?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_REP_INVENTORY_ITEM, "REPLACE INTO character_inventory (guid, bag, slot, item) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_REP_ITEM_INSTANCE, "REPLACE INTO item_instance (itemEntry, owner_guid, creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text, guid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_ITEM_INSTANCE, "UPDATE item_instance SET itemEntry = ?, owner_guid = ?, creatorGuid = ?, giftCreatorGuid = ?, count = ?, duration = ?, charges = ?, flags = ?, enchantments = ?, randomPropertyId = ?, durability = ?, playedTime = ?, text = ? WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_ITEM_INSTANCE_ON_LOAD, "UPDATE item_instance SET duration = ?, flags = ?, durability = ? WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_ITEM_INSTANCE, "DELETE FROM item_instance WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_ITEM_INSTANCE_BY_OWNER, "DELETE FROM item_instance WHERE owner_guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_GIFT_OWNER, "UPDATE character_gifts SET guid = ? WHERE item_guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GIFT, "DELETE FROM character_gifts WHERE item_guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_GIFT_BY_ITEM, "SELECT entry, flags FROM character_gifts WHERE item_guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_ACCOUNT_BY_NAME, "SELECT account FROM characters WHERE name = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_ACCOUNT_BY_GUID, "SELECT account FROM characters WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_ACCOUNT_NAME_BY_GUID, "SELECT account, name FROM characters WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHARACTER_DATA_BY_GUID, "SELECT account, name, level FROM characters WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_DEL_ACCOUNT_INSTANCE_LOCK_TIMES, "DELETE FROM account_instance_times WHERE accountId = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_ACCOUNT_INSTANCE_LOCK_TIMES, "INSERT INTO account_instance_times (accountId, instanceId, releaseTime) VALUES (?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_NAME_CLASS, "SELECT name, class FROM characters WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHARACTER_NAME, "SELECT name FROM characters WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_MATCH_MAKER_RATING, "SELECT matchMakerRating FROM character_arena_stats WHERE guid = ? AND slot = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHARACTER_COUNT, "SELECT account, COUNT(guid) FROM characters WHERE account = ? GROUP BY account", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_NAME, "UPDATE characters set name = ?, at_login = at_login & ~ ? WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_DECLINED_NAME, "DELETE FROM character_declinedname WHERE guid = ?", CONNECTION_ASYNC);
// Guild handling
// 0: uint32, 1: string, 2: uint32, 3: string, 4: string, 5: uint64, 6-10: uint32, 11: uint64
PrepareStatement(CHAR_INS_GUILD, "INSERT INTO guild (guildid, name, leaderguid, info, motd, createdate, EmblemStyle, EmblemColor, BorderStyle, BorderColor, BackgroundColor, BankMoney) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GUILD, "DELETE FROM guild WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint32
// 0: uint32, 1: uint32, 2: uint8, 4: string, 5: string
PrepareStatement(CHAR_INS_GUILD_MEMBER, "INSERT INTO guild_member (guildid, guid, rank, pnote, offnote, activity, weekActivity, weekReputation) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GUILD_MEMBER, "DELETE FROM guild_member WHERE guid = ?", CONNECTION_ASYNC); // 0: uint32
PrepareStatement(CHAR_DEL_GUILD_MEMBERS, "DELETE FROM guild_member WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint32
// 0: uint32, 1: uint8, 3: string, 4: uint32
PrepareStatement(CHAR_INS_GUILD_RANK, "INSERT INTO guild_rank (guildid, rid, rname, rights) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GUILD_RANKS, "DELETE FROM guild_rank WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint32
PrepareStatement(CHAR_DEL_GUILD_RANK, "DELETE FROM guild_rank WHERE guildid = ? AND rid = ?", CONNECTION_ASYNC); // 0: uint32, 1: uint8
PrepareStatement(CHAR_INS_GUILD_BANK_TAB, "INSERT INTO guild_bank_tab (guildid, TabId) VALUES (?, ?)", CONNECTION_ASYNC); // 0: uint32, 1: uint8
PrepareStatement(CHAR_DEL_GUILD_BANK_TAB, "DELETE FROM guild_bank_tab WHERE guildid = ? AND TabId = ?", CONNECTION_ASYNC); // 0: uint32, 1: uint8
PrepareStatement(CHAR_DEL_GUILD_BANK_TABS, "DELETE FROM guild_bank_tab WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint32
// 0: uint32, 1: uint8, 2: uint8, 3: uint32, 4: uint32
PrepareStatement(CHAR_INS_GUILD_BANK_ITEM, "INSERT INTO guild_bank_item (guildid, TabId, SlotId, item_guid) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GUILD_BANK_ITEM, "DELETE FROM guild_bank_item WHERE guildid = ? AND TabId = ? AND SlotId = ?", CONNECTION_ASYNC); // 0: uint32, 1: uint8, 2: uint8
PrepareStatement(CHAR_DEL_GUILD_BANK_ITEMS, "DELETE FROM guild_bank_item WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint32
// 0: uint32, 1: uint8, 2: uint8, 3: uint8, 4: uint32
PrepareStatement(CHAR_INS_GUILD_BANK_RIGHT, "INSERT INTO guild_bank_right (guildid, TabId, rid, gbright, SlotPerDay) VALUES (?, ?, ?, ?, ?) "
"ON DUPLICATE KEY UPDATE gbright = VALUES(gbright), SlotPerDay = VALUES(SlotPerDay)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GUILD_BANK_RIGHTS, "DELETE FROM guild_bank_right WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint32
PrepareStatement(CHAR_DEL_GUILD_BANK_RIGHTS_FOR_RANK, "DELETE FROM guild_bank_right WHERE guildid = ? AND rid = ?", CONNECTION_ASYNC); // 0: uint32, 1: uint8
// 0-1: uint32, 2-3: uint8, 4-5: uint32, 6: uint16, 7: uint8, 8: uint64
PrepareStatement(CHAR_INS_GUILD_BANK_EVENTLOG, "INSERT INTO guild_bank_eventlog (guildid, LogGuid, TabId, EventType, PlayerGuid, ItemOrMoney, ItemStackCount, DestTabId, TimeStamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GUILD_BANK_EVENTLOG, "DELETE FROM guild_bank_eventlog WHERE guildid = ? AND LogGuid = ? AND TabId = ?", CONNECTION_ASYNC); // 0: uint32, 1: uint32, 2: uint8
PrepareStatement(CHAR_DEL_GUILD_BANK_EVENTLOGS, "DELETE FROM guild_bank_eventlog WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint32
// 0-1: uint32, 2: uint8, 3-4: uint32, 5: uint8, 6: uint64
PrepareStatement(CHAR_INS_GUILD_EVENTLOG, "INSERT INTO guild_eventlog (guildid, LogGuid, EventType, PlayerGuid1, PlayerGuid2, NewRank, TimeStamp) VALUES (?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GUILD_EVENTLOG, "DELETE FROM guild_eventlog WHERE guildid = ? AND LogGuid = ?", CONNECTION_ASYNC); // 0: uint32, 1: uint32
PrepareStatement(CHAR_DEL_GUILD_EVENTLOGS, "DELETE FROM guild_eventlog WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint32
PrepareStatement(CHAR_UPD_GUILD_MEMBER_PNOTE, "UPDATE guild_member SET pnote = ? WHERE guid = ?", CONNECTION_ASYNC); // 0: string, 1: uint32
PrepareStatement(CHAR_UPD_GUILD_MEMBER_OFFNOTE, "UPDATE guild_member SET offnote = ? WHERE guid = ?", CONNECTION_ASYNC); // 0: string, 1: uint32
PrepareStatement(CHAR_UPD_GUILD_MEMBER_RANK, "UPDATE guild_member SET rank = ? WHERE guid = ?", CONNECTION_ASYNC); // 0: uint8, 1: uint32
PrepareStatement(CHAR_UPD_GUILD_MEMBER_ACTIVITY, "UPDATE guild_member SET activity = ?, weekActivity = ? WHERE guid = ?", CONNECTION_ASYNC); // 0: uint64, 1: uint64, 2: uint32
PrepareStatement(CHAR_UPD_GUILD_MEMBER_PROFESSION, "UPDATE guild_member SET profession1_level=?, profession1_skillID=?, profession1_rank=?, "
"profession2_level=?, profession2_skillID=?, profession2_rank=? WHERE guid=?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_GUILD_MEMBER_WEEK_REPUTATION, "UPDATE guild_member SET weekReputation = ? WHERE guid = ?", CONNECTION_ASYNC); // 0: uint32, 1: uint32
PrepareStatement(CHAR_RESET_GUILD_MEMBER_WEEK_ACTIVITY, "UPDATE guild_member SET weekActivity = 0 WHERE guid = ?", CONNECTION_ASYNC); // 0: uint32
PrepareStatement(CHAR_RESET_GUILD_MEMBER_WEEK_REPUTATION, "UPDATE guild_member SET weekReputation = 0 WHERE guid = ?", CONNECTION_ASYNC); // 0: uint32
PrepareStatement(CHAR_UPD_GUILD_MOTD, "UPDATE guild SET motd = ? WHERE guildid = ?", CONNECTION_ASYNC); // 0: string, 1: uint32
PrepareStatement(CHAR_UPD_GUILD_INFO, "UPDATE guild SET info = ? WHERE guildid = ?", CONNECTION_ASYNC); // 0: string, 1: uint32
PrepareStatement(CHAR_UPD_GUILD_LEADER, "UPDATE guild SET leaderguid = ? WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint32, 1: uint32
PrepareStatement(CHAR_UPD_GUILD_RANK_NAME, "UPDATE guild_rank SET rname = ? WHERE rid = ? AND guildid = ?", CONNECTION_ASYNC); // 0: string, 1: uint8, 2: uint32
PrepareStatement(CHAR_UPD_GUILD_RANK_RIGHTS, "UPDATE guild_rank SET rights = ? WHERE rid = ? AND guildid = ?", CONNECTION_ASYNC); // 0: uint32, 1: uint8, 2: uint32
// 0-5: uint32
PrepareStatement(CHAR_UPD_GUILD_EMBLEM_INFO, "UPDATE guild SET EmblemStyle = ?, EmblemColor = ?, BorderStyle = ?, BorderColor = ?, BackgroundColor = ? WHERE guildid = ?", CONNECTION_ASYNC);
// 0: string, 1: string, 2: uint32, 3: uint8
PrepareStatement(CHAR_UPD_GUILD_BANK_TAB_INFO, "UPDATE guild_bank_tab SET TabName = ?, TabIcon = ? WHERE guildid = ? AND TabId = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_GUILD_BANK_MONEY, "UPDATE guild SET BankMoney = ? WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint64, 1: uint32
// 0: uint8, 1: uint32, 2: uint8, 3: uint32
PrepareStatement(CHAR_UPD_GUILD_BANK_EVENTLOG_TAB, "UPDATE guild_bank_eventlog SET TabId = ? WHERE guildid = ? AND TabId = ? AND LogGuid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_GUILD_RANK_BANK_MONEY, "UPDATE guild_rank SET BankMoneyPerDay = ? WHERE rid = ? AND guildid = ?", CONNECTION_ASYNC); // 0: uint32, 1: uint8, 2: uint32
PrepareStatement(CHAR_UPD_GUILD_BANK_TAB_TEXT, "UPDATE guild_bank_tab SET TabText = ? WHERE guildid = ? AND TabId = ?", CONNECTION_ASYNC); // 0: string, 1: uint32, 2: uint8
PrepareStatement(CHAR_INS_GUILD_MEMBER_WITHDRAW,
"INSERT INTO guild_member_withdraw (guid, tab0, tab1, tab2, tab3, tab4, tab5, tab6, tab7, money) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "
"ON DUPLICATE KEY UPDATE tab0 = VALUES (tab0), tab1 = VALUES (tab1), tab2 = VALUES (tab2), tab3 = VALUES (tab3), tab4 = VALUES (tab4), tab5 = VALUES (tab5), tab6 = VALUES (tab6), tab7 = VALUES (tab7), money = VALUES (money)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GUILD_MEMBER_WITHDRAW, "TRUNCATE guild_member_withdraw", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_GUILD_NAME, "UPDATE guild SET name = ? WHERE guildid = ?", CONNECTION_ASYNC); // 0: string, 1: uint32
PrepareStatement(CHAR_SEL_GUILD_CHALLENGES_COMPLETED, "SELECT challengeId FROM guild_challenges_completed WHERE guildId = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_FIRST_GUILD_CHALLENGE_COMPLETED_DATE, "SELECT dateCompleted FROM guild_challenges_completed WHERE guildId = ? ORDER BY dateCompleted ASC", CONNECTION_SYNCH);
PrepareStatement(CHAR_INS_GUILD_CHALLENGE_DONE, "INSERT INTO guild_challenges_completed (guildId, challengeId, dateCompleted) VALUES (?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GUILD_CHALLENGE_EXPIERED, "DELETE FROM guild_challenges_completed WHERE guildId = ?", CONNECTION_ASYNC);
// Guild Reputation
PrepareStatement(CHAR_ADD_GUILD_REP, "INSERT INTO character_guild_reputation (guid, guildid) VALUES (?, ?)", CONNECTION_ASYNC); // 0,1: uint32
PrepareStatement(CHAR_GET_GUILD_REP, "SELECT guildid FROM character_guild_reputation WHERE guid = ?", CONNECTION_SYNCH); // 0: uint32
PrepareStatement(CHAR_SET_GUILD_REP, "UPDATE character_guild_reputation SET guildid = ? WHERE guid = ?", CONNECTION_ASYNC); // 0,1: uint32
PrepareStatement(CHAR_SET_GUILD_REP_TIME, "UPDATE character_guild_reputation SET disband_time = UNIX_TIMESTAMP(NOW()) WHERE guid = ?", CONNECTION_ASYNC); // 0: uint32
PrepareStatement(CHAR_SET_GUILD_REP_RESET_TIME, "UPDATE character_guild_reputation SET disband_time = '0' WHERE guid = ?", CONNECTION_ASYNC); // 0: uint32
PrepareStatement(CHAR_GET_GUILD_REP_TIME, "SELECT disband_time FROM character_guild_reputation WHERE guid = ?", CONNECTION_SYNCH); // 0: uint32
PrepareStatement(CHAR_GET_GUILD_REP_VAL, "SELECT weekly_rep FROM character_guild_reputation WHERE guid = ?", CONNECTION_SYNCH); // 0: uint32
PrepareStatement(CHAR_SET_GUILD_REP_VAL, "UPDATE character_guild_reputation SET weekly_rep = ? WHERE guid = ?", CONNECTION_ASYNC); // 0,1: uint32
PrepareStatement(CHAR_GET_GUILD_TOTAL_REP_VAL, "SELECT total_rep FROM character_guild_reputation WHERE guid = ?", CONNECTION_SYNCH); // 0: uint32
PrepareStatement(CHAR_SET_GUILD_TOTAL_REP_VAL, "UPDATE character_guild_reputation SET total_rep = ? WHERE guid = ?", CONNECTION_ASYNC); // 0,1: uint32
// 0: uint32, 1: uint32, 2: uint32
PrepareStatement(CHAR_SEL_CHAR_DATA_FOR_GUILD, "SELECT c.name, c.level, c.class, c.zone, c.account, c.achievementPoint, r.standing FROM characters c LEFT JOIN character_reputation r ON c.guid = r.guid AND r.faction = 1168 WHERE c.guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_OLD_GUILD_DATA, "SELECT guildId, weekReputation FROM guild_old_member WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_DEL_OLD_GUILD_DATA, "DELETE FROM guild_old_member WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_RESET_OLD_GUILD_WEEK_REPUTATION, "UPDATE guild_old_member SET weekReputation = 0", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_OLD_OLD_GUILD_MEMBER, "DELETE FROM guild_old_member WHERE leaveDate < ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_LEAVE_GUILD_DATA, "INSERT INTO guild_old_member (guid, guildId, weekReputation, leaveDate) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GUILD_ACHIEVEMENT, "DELETE FROM guild_achievement WHERE guildId = ? AND achievement = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_GUILD_ACHIEVEMENT, "INSERT INTO guild_achievement (guildId, achievement, date, guids) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GUILD_ACHIEVEMENT_CRITERIA, "DELETE FROM guild_achievement_progress WHERE guildId = ? AND criteria = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_GUILD_ACHIEVEMENT_CRITERIA, "INSERT INTO guild_achievement_progress (guildId, criteria, counter, date, completedGuid) VALUES (?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_ALL_GUILD_ACHIEVEMENTS, "DELETE FROM guild_achievement WHERE guildId = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_ALL_GUILD_ACHIEVEMENT_CRITERIA, "DELETE FROM guild_achievement_progress WHERE guildId = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_GUILD_ACHIEVEMENT, "SELECT achievement, date, guids FROM guild_achievement WHERE guildId = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_GUILD_ACHIEVEMENT_CRITERIA, "SELECT criteria, counter, date, completedGuid FROM guild_achievement_progress WHERE guildId = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_UPD_GUILD_EXPERIENCE, "UPDATE guild SET level = ?, experience = ?, todayExperience = ? WHERE guildId = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_GUILD_CHALLENGE, "UPDATE guild SET DungeonChallenge = ?, RaidChallenge = ?, RatedBGChallenge = ? WHERE guildId = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_GUILD_RESET_CHALLENGE, "UPDATE guild SET DungeonChallenge = 0, RaidChallenge = 0, RatedBGChallenge = 0 WHERE guildId = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_GUILD_RESET_TODAY_EXPERIENCE, "UPDATE guild SET todayExperience = 0", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_GUILD_NEWS, "INSERT INTO guild_newslog (guildid, LogGuid, EventType, PlayerGuid, Flags, Value, Timestamp) VALUES (?, ?, ?, ?, ?, ?, ?)"
" ON DUPLICATE KEY UPDATE LogGuid = VALUES (LogGuid), EventType = VALUES (EventType), PlayerGuid = VALUES (PlayerGuid), Flags = VALUES (Flags), Value = VALUES (Value), Timestamp = VALUES (Timestamp)", CONNECTION_ASYNC);
// Chat channel handling
PrepareStatement(CHAR_SEL_CHANNEL, "SELECT announce, ownership, password, bannedList FROM channels WHERE name = ? AND team = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_INS_CHANNEL, "INSERT INTO channels(name, team, lastUsed) VALUES (?, ?, UNIX_TIMESTAMP())", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHANNEL, "UPDATE channels SET announce = ?, ownership = ?, password = ?, bannedList = ?, lastUsed = UNIX_TIMESTAMP() WHERE name = ? AND team = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHANNEL_USAGE, "UPDATE channels SET lastUsed = UNIX_TIMESTAMP() WHERE name = ? AND team = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHANNEL_OWNERSHIP, "UPDATE channels SET ownership = ? WHERE name LIKE ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_OLD_CHANNELS, "DELETE FROM channels WHERE ownership = 1 AND lastUsed + ? < UNIX_TIMESTAMP()", CONNECTION_ASYNC);
// Equipmentsets
PrepareStatement(CHAR_UPD_EQUIP_SET, "UPDATE character_equipmentsets SET name=?, iconname=?, ignore_mask=?, item0=?, item1=?, item2=?, item3=?, "
"item4=?, item5=?, item6=?, item7=?, item8=?, item9=?, item10=?, item11=?, item12=?, item13=?, item14=?, item15=?, item16=?, "
"item17=?, item18=? WHERE guid=? AND setguid=? AND setindex=?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_EQUIP_SET, "INSERT INTO character_equipmentsets (guid, setguid, setindex, name, iconname, ignore_mask, item0, item1, item2, item3, "
"item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_EQUIP_SET, "DELETE FROM character_equipmentsets WHERE setguid=?", CONNECTION_ASYNC);
// Auras
PrepareStatement(CHAR_INS_AURA, "INSERT INTO character_aura (guid, caster_guid, item_guid, spell, effect_mask, recalculate_mask, stackcount, amount0, amount1, amount2, base_amount0, base_amount1, base_amount2, maxduration, remaintime, remaincharges) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
// Currency
PrepareStatement(CHAR_SEL_PLAYER_CURRENCY, "SELECT currency, week_count, total_count, season_count FROM character_currency WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_PLAYER_CURRENCY, "UPDATE character_currency SET week_count = ?, total_count = ?, season_count = ? WHERE guid = ? AND currency = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_REP_PLAYER_CURRENCY, "REPLACE INTO character_currency (guid, currency, week_count, total_count, season_count) VALUES (?, ?, ?, ?, ?)", CONNECTION_ASYNC);
// Currency Cap
PrepareStatement(CHAR_SEL_PLAYER_CURRENCY_WEEK_CAP, "SELECT source, max_week_rating, week_cap FROM character_currency_weekcap WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_REP_PLAYER_CURRENCY_WEEK_CAP, "REPLACE INTO character_currency_weekcap (guid, source, max_week_rating, week_cap) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC);
// Account data
PrepareStatement(CHAR_SEL_ACCOUNT_DATA, "SELECT type, time, data FROM account_data WHERE accountId = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_REP_ACCOUNT_DATA, "REPLACE INTO account_data (accountId, type, time, data) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_ACCOUNT_DATA, "DELETE FROM account_data WHERE accountId = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_PLAYER_ACCOUNT_DATA, "SELECT type, time, data FROM character_account_data WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_REP_PLAYER_ACCOUNT_DATA, "REPLACE INTO character_account_data(guid, type, time, data) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_PLAYER_ACCOUNT_DATA, "DELETE FROM character_account_data WHERE guid = ?", CONNECTION_ASYNC);
// Tutorials
PrepareStatement(CHAR_SEL_TUTORIALS, "SELECT tut0, tut1, tut2, tut3, tut4, tut5, tut6, tut7 FROM account_tutorial WHERE accountId = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_HAS_TUTORIALS, "SELECT 1 FROM account_tutorial WHERE accountId = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_INS_TUTORIALS, "INSERT INTO account_tutorial(tut0, tut1, tut2, tut3, tut4, tut5, tut6, tut7, accountId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_TUTORIALS, "UPDATE account_tutorial SET tut0 = ?, tut1 = ?, tut2 = ?, tut3 = ?, tut4 = ?, tut5 = ?, tut6 = ?, tut7 = ? WHERE accountId = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_TUTORIALS, "DELETE FROM account_tutorial WHERE accountId = ?", CONNECTION_ASYNC);
// Instance saves
PrepareStatement(CHAR_INS_INSTANCE_SAVE, "INSERT INTO instance (id, map, resettime, difficulty, completedEncounters, data) VALUES (?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_INSTANCE_DATA, "UPDATE instance SET completedEncounters=?, data=? WHERE id=?", CONNECTION_ASYNC);
// Game event saves
PrepareStatement(CHAR_DEL_GAME_EVENT_SAVE, "DELETE FROM game_event_save WHERE eventEntry = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_GAME_EVENT_SAVE, "INSERT INTO game_event_save (eventEntry, state, next_start) VALUES (?, ?, ?)", CONNECTION_ASYNC);
// Game event condition saves
PrepareStatement(CHAR_DEL_ALL_GAME_EVENT_CONDITION_SAVE, "DELETE FROM game_event_condition_save WHERE eventEntry = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GAME_EVENT_CONDITION_SAVE, "DELETE FROM game_event_condition_save WHERE eventEntry = ? AND condition_id = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_GAME_EVENT_CONDITION_SAVE, "INSERT INTO game_event_condition_save (eventEntry, condition_id, done) VALUES (?, ?, ?)", CONNECTION_ASYNC);
// Petitions
PrepareStatement(CHAR_SEL_PETITION, "SELECT ownerguid, name, type FROM petition WHERE petitionguid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_PETITION_SIGNATURE, "SELECT playerguid FROM petition_sign WHERE petitionguid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_DEL_ALL_PETITION_SIGNATURES, "DELETE FROM petition_sign WHERE playerguid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_PETITION_SIGNATURE, "DELETE FROM petition_sign WHERE playerguid = ? AND type = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_PETITION_BY_OWNER, "SELECT petitionguid FROM petition WHERE ownerguid = ? AND type = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_PETITION_TYPE, "SELECT type FROM petition WHERE petitionguid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_PETITION_SIGNATURES, "SELECT ownerguid, (SELECT COUNT(playerguid) FROM petition_sign WHERE petition_sign.petitionguid = ?) AS signs, type FROM petition WHERE petitionguid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_PETITION_SIG_BY_ACCOUNT, "SELECT playerguid FROM petition_sign WHERE player_account = ? AND petitionguid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_PETITION_OWNER_BY_GUID, "SELECT ownerguid FROM petition WHERE petitionguid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_PETITION_SIG_BY_GUID, "SELECT ownerguid, petitionguid FROM petition_sign WHERE playerguid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_PETITION_SIG_BY_GUID_TYPE, "SELECT ownerguid, petitionguid FROM petition_sign WHERE playerguid = ? AND type = ?", CONNECTION_SYNCH);
// Arena teams
PrepareStatement(CHAR_SEL_CHARACTER_ARENAINFO, "SELECT arenaTeamId, weekGames, seasonGames, seasonWins, personalRating FROM arena_team_member WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_ARENA_TEAM, "INSERT INTO arena_team (arenaTeamId, name, captainGuid, type, rating, backgroundColor, emblemStyle, emblemColor, borderStyle, borderColor) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_ARENA_TEAM_MEMBER, "INSERT INTO arena_team_member (arenaTeamId, guid) VALUES (?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_ARENA_TEAM, "DELETE FROM arena_team where arenaTeamId = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_ARENA_TEAM_MEMBERS, "DELETE FROM arena_team_member WHERE arenaTeamId = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_ARENA_TEAM_CAPTAIN, "UPDATE arena_team SET captainGuid = ? WHERE arenaTeamId = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_ARENA_TEAM_MEMBER, "DELETE FROM arena_team_member WHERE arenaTeamId = ? AND guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_ARENA_TEAM_STATS, "UPDATE arena_team SET rating = ?, weekGames = ?, weekWins = ?, seasonGames = ?, seasonWins = ?, rank = ? WHERE arenaTeamId = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_ARENA_TEAM_MEMBER, "UPDATE arena_team_member SET personalRating = ?, weekGames = ?, weekWins = ?, seasonGames = ?, seasonWins = ? WHERE arenaTeamId = ? AND guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_REP_CHARACTER_ARENA_STATS, "REPLACE INTO character_arena_stats (guid, slot, matchMakerRating) VALUES (?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_PLAYER_ARENA_TEAMS, "SELECT arena_team_member.arenaTeamId FROM arena_team_member JOIN arena_team ON arena_team_member.arenaTeamId = arena_team.arenaTeamId WHERE guid = ?", CONNECTION_SYNCH);
// Character battleground data
PrepareStatement(CHAR_INS_PLAYER_BGDATA, "INSERT INTO character_battleground_data (guid, instanceId, team, joinX, joinY, joinZ, joinO, joinMapId, taxiStart, taxiEnd, mountSpell) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_PLAYER_BGDATA, "DELETE FROM character_battleground_data WHERE guid = ?", CONNECTION_ASYNC);
// Character homebind
PrepareStatement(CHAR_INS_PLAYER_HOMEBIND, "INSERT INTO character_homebind (guid, mapId, zoneId, posX, posY, posZ) VALUES (?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_PLAYER_HOMEBIND, "UPDATE character_homebind SET mapId = ?, zoneId = ?, posX = ?, posY = ?, posZ = ? WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_PLAYER_HOMEBIND, "DELETE FROM character_homebind WHERE guid = ?", CONNECTION_ASYNC);
// Corpse
PrepareStatement(CHAR_SEL_CORPSES, "SELECT posX, posY, posZ, orientation, mapId, displayId, itemCache, bytes1, bytes2, flags, dynFlags, time, corpseType, instanceId, phaseMask, corpseGuid, guid FROM corpse WHERE corpseType <> 0", CONNECTION_SYNCH);
PrepareStatement(CHAR_INS_CORPSE, "INSERT INTO corpse (corpseGuid, guid, posX, posY, posZ, orientation, mapId, displayId, itemCache, bytes1, bytes2, flags, dynFlags, time, corpseType, instanceId, phaseMask) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CORPSE, "DELETE FROM corpse WHERE corpseGuid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_PLAYER_CORPSES, "DELETE FROM corpse WHERE guid = ? AND corpseType <> 0", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_OLD_CORPSES, "DELETE FROM corpse WHERE corpseType = 0 OR time < (UNIX_TIMESTAMP(NOW()) - ?)", CONNECTION_ASYNC);
// Creature respawn
PrepareStatement(CHAR_SEL_CREATURE_RESPAWNS, "SELECT guid, respawnTime FROM creature_respawn WHERE mapId = ? AND instanceId = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_REP_CREATURE_RESPAWN, "REPLACE INTO creature_respawn (guid, respawnTime, mapId, instanceId) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CREATURE_RESPAWN, "DELETE FROM creature_respawn WHERE guid = ? AND mapId = ? AND instanceId = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CREATURE_RESPAWN_BY_INSTANCE, "DELETE FROM creature_respawn WHERE mapId = ? AND instanceId = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_MAX_CREATURE_RESPAWNS, "SELECT MAX(respawnTime), instanceId FROM creature_respawn WHERE instanceId > 0 GROUP BY instanceId", CONNECTION_SYNCH);
// Gameobject respawn
PrepareStatement(CHAR_SEL_GO_RESPAWNS, "SELECT guid, respawnTime FROM gameobject_respawn WHERE mapId = ? AND instanceId = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_REP_GO_RESPAWN, "REPLACE INTO gameobject_respawn (guid, respawnTime, mapId, instanceId) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GO_RESPAWN, "DELETE FROM gameobject_respawn WHERE guid = ? AND mapId = ? AND instanceId = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GO_RESPAWN_BY_INSTANCE, "DELETE FROM gameobject_respawn WHERE mapId = ? AND instanceId = ?", CONNECTION_ASYNC);
// GM Tickets
PrepareStatement(CHAR_SEL_GM_TICKETS, "SELECT ticketId, guid, name, message, createTime, mapId, posX, posY, posZ, lastModifiedTime, closedBy, assignedTo, comment, response, completed, escalated, viewed, haveTicket FROM gm_tickets", CONNECTION_SYNCH);
PrepareStatement(CHAR_REP_GM_TICKET, "REPLACE INTO gm_tickets (ticketId, guid, name, message, createTime, mapId, posX, posY, posZ, lastModifiedTime, closedBy, assignedTo, comment, response, completed, escalated, viewed, haveTicket) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GM_TICKET, "DELETE FROM gm_tickets WHERE ticketId = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_PLAYER_GM_TICKETS, "DELETE FROM gm_tickets WHERE guid = ?", CONNECTION_ASYNC);
// GM Survey/subsurvey/lag report
PrepareStatement(CHAR_INS_GM_SURVEY, "INSERT INTO gm_surveys (guid, surveyId, mainSurvey, overallComment, createTime) VALUES (?, ?, ?, ?, UNIX_TIMESTAMP(NOW()))", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_GM_SUBSURVEY, "INSERT INTO gm_subsurveys (surveyId, subsurveyId, rank, comment) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_LAG_REPORT, "INSERT INTO lag_reports (guid, lagType, mapId, posX, posY, posZ, latency, createTime) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
// For loading and deleting expired auctions at startup
PrepareStatement(CHAR_SEL_EXPIRED_AUCTIONS, "SELECT id, auctioneerguid, itemguid, itemEntry, count, itemowner, buyoutprice, time, buyguid, lastbid, startbid, deposit FROM auctionhouse ah INNER JOIN item_instance ii ON ii.guid = ah.itemguid WHERE ah.time <= ?", CONNECTION_SYNCH);
// LFG Data
PrepareStatement(CHAR_INS_LFG_DATA, "INSERT INTO lfg_data (guid, dungeon, state) VALUES (?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_LFG_DATA, "DELETE FROM lfg_data WHERE guid = ?", CONNECTION_ASYNC);
// Player saving
PrepareStatement(CHAR_INS_CHARACTER, "INSERT INTO characters (guid, account, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags, "
"map, instance_id, instance_mode_mask, position_x, position_y, position_z, orientation, "
"taximask, cinematic, "
"totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, talentTree, "
"extra_flags, stable_slots, at_login, zone, "
"death_expire_time, taxi_path, totalKills, "
"todayKills, yesterdayKills, chosenTitle, watchedFaction, drunk, health, power1, power2, power3, "
"power4, power5, latency, speccount, activespec, exploredZones, equipmentCache, knownTitles, actionBars, grantableLevels, achievementPoint, currentPetSlot) VALUES "
"(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHARACTER, "UPDATE characters SET name=?,race=?,class=?,gender=?,level=?,xp=?,money=?,playerBytes=?,playerBytes2=?,playerFlags=?,"
"map=?,instance_id=?,instance_mode_mask=?,position_x=?,position_y=?,position_z=?,orientation=?,taximask=?,cinematic=?,totaltime=?,leveltime=?,rest_bonus=?,"
"logout_time=?,is_logout_resting=?,resettalents_cost=?,resettalents_time=?,talentTree=?,extra_flags=?,stable_slots=?,at_login=?,zone=?,death_expire_time=?,taxi_path=?,"
"totalKills=?,todayKills=?,yesterdayKills=?,chosenTitle=?,"
"watchedFaction=?,drunk=?,health=?,power1=?,power2=?,power3=?,power4=?,power5=?,latency=?,speccount=?,activespec=?,exploredZones=?,"
"equipmentCache=?,knownTitles=?,actionBars=?,grantableLevels=?,achievementPoint=?,online=?,currentPetSlot=? WHERE guid=?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG, "UPDATE characters SET at_login = at_login | ? WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_REM_AT_LOGIN_FLAG, "UPDATE characters set at_login = at_login & ~ ? WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_ALL_AT_LOGIN_FLAGS, "UPDATE characters SET at_login = at_login | ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_BUG_REPORT, "INSERT INTO bugreport (type, content) VALUES(?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_PETITION_NAME, "UPDATE petition SET name = ? WHERE petitionguid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_PETITION_SIGNATURE, "INSERT INTO petition_sign (ownerguid, petitionguid, playerguid, player_account) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_ACCOUNT_ONLINE, "UPDATE characters SET online = 0 WHERE account = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_GROUP, "INSERT INTO groups (guid, leaderGuid, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, groupType, difficulty, raiddifficulty) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_GROUP_MEMBER, "INSERT INTO group_member (guid, memberGuid, memberFlags, subgroup, roles) VALUES(?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GROUP_MEMBER, "DELETE FROM group_member WHERE memberGuid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GROUP_INSTANCE_PERM_BINDING, "DELETE FROM group_instance WHERE guid = ? AND (permanent = 1 OR instance IN (SELECT instance FROM character_instance WHERE guid = ?))", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_GROUP_LEADER, "UPDATE groups SET leaderGuid = ? WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_GROUP_TYPE, "UPDATE groups SET groupType = ? WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_GROUP_MEMBER_SUBGROUP, "UPDATE group_member SET subgroup = ? WHERE memberGuid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_GROUP_MEMBER_FLAG, "UPDATE group_member SET memberFlags = ? WHERE memberGuid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_GROUP_DIFFICULTY, "UPDATE groups SET difficulty = ? WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_GROUP_RAID_DIFFICULTY, "UPDATE groups SET raiddifficulty = ? WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_ALL_GM_TICKETS, "TRUNCATE TABLE gm_tickets", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_INVALID_SPELL_TALENTS, "DELETE FROM character_talent WHERE spell = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_INVALID_SPELL_SPELLS, "DELETE FROM character_spell WHERE spell = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_DELETE_INFO, "UPDATE characters SET deleteInfos_Name = name, deleteInfos_Account = account, deleteDate = UNIX_TIMESTAMP(), name = '', account = 0 WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UDP_RESTORE_DELETE_INFO, "UPDATE characters SET name = ?, account = ?, deleteDate = NULL, deleteInfos_Name = NULL, deleteInfos_Account = NULL WHERE deleteDate IS NOT NULL AND guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_ZONE, "UPDATE characters SET zone = ? WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_LEVEL, "UPDATE characters SET level = ?, xp = 0 WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_INVALID_ACHIEV_PROGRESS_CRITERIA, "DELETE FROM character_achievement_progress WHERE criteria = ? and guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_INVALID_ACHIEV_PROGRESS_CRITERIA_GUILD, "DELETE FROM guild_achievement_progress WHERE criteria = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_INVALID_ACHIEVMENT, "DELETE FROM character_achievement WHERE achievement = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_ADDON, "INSERT INTO addons (name, crc) VALUES (?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_INVALID_PET_SPELL, "DELETE FROM pet_spell WHERE spell = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GROUP_INSTANCE_BY_INSTANCE, "DELETE FROM group_instance WHERE instance = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GROUP_INSTANCE_BY_GUID, "DELETE FROM group_instance WHERE guid = ? AND instance = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_REP_GROUP_INSTANCE, "REPLACE INTO group_instance (guid, instance, permanent) VALUES (?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_INSTANCE_RESETTIME, "UPDATE instance SET resettime = ? WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_GLOBAL_INSTANCE_RESETTIME, "UPDATE instance_reset SET resettime = ? WHERE mapid = ? AND difficulty = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHAR_ONLINE, "UPDATE characters SET online = 1 WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHAR_NAME_AT_LOGIN, "UPDATE characters set name = ?, at_login = at_login & ~ ? WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_WORLDSTATE, "UPDATE worldstates SET value = ? WHERE entry = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_WORLDSTATE, "INSERT INTO worldstates (entry, value) VALUES (?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID, "DELETE FROM character_instance WHERE guid = ? AND instance = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHAR_INSTANCE, "UPDATE character_instance SET instance = ?, permanent = ? WHERE guid = ? AND instance = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHAR_INSTANCE, "INSERT INTO character_instance (guid, instance, permanent) VALUES (?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_GENDER_PLAYERBYTES, "UPDATE characters SET gender = ?, playerBytes = ?, playerBytes2 = ? WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHARACTER_SKILL, "DELETE FROM character_skills WHERE guid = ? AND skill = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_ADD_CHARACTER_SOCIAL_FLAGS, "UPDATE character_social SET flags = flags | ? WHERE guid = ? AND friend = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_REM_CHARACTER_SOCIAL_FLAGS, "UPDATE character_social SET flags = flags & ~ ? WHERE guid = ? AND friend = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHARACTER_SOCIAL, "INSERT INTO character_social (guid, friend, flags) VALUES (?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHARACTER_SOCIAL, "DELETE FROM character_social WHERE guid = ? AND friend = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHARACTER_SOCIAL_NOTE, "UPDATE character_social SET note = ? WHERE guid = ? AND friend = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHARACTER_POSITION, "UPDATE characters SET position_x = ?, position_y = ?, position_z = ?, orientation = ?, map = ?, zone = ?, trans_x = 0, trans_y = 0, trans_z = 0, transguid = 0, taxi_path = '' WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHARACTER_AURA_FROZEN, "SELECT characters.name FROM characters LEFT JOIN character_aura ON (characters.guid = character_aura.guid) WHERE character_aura.spell = 9454", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHARACTER_ONLINE, "SELECT name, account, map, zone FROM characters WHERE online > 0", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_DEL_INFO_BY_GUID, "SELECT guid, deleteInfos_Name, deleteInfos_Account, deleteDate FROM characters WHERE deleteDate IS NOT NULL AND guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_DEL_INFO_BY_NAME, "SELECT guid, deleteInfos_Name, deleteInfos_Account, deleteDate FROM characters WHERE deleteDate IS NOT NULL AND deleteInfos_Name LIKE CONCAT('%%', ?, '%%')", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_DEL_INFO, "SELECT guid, deleteInfos_Name, deleteInfos_Account, deleteDate FROM characters WHERE deleteDate IS NOT NULL", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHARS_BY_ACCOUNT_ID, "SELECT guid FROM characters WHERE account = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_PINFO, "SELECT totaltime, level, money, account, race, class, map, zone FROM characters WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_PINFO_BANS, "SELECT unbandate, bandate = unbandate, bannedby, banreason FROM character_banned WHERE guid = ? AND active ORDER BY bandate ASC LIMIT 1", CONNECTION_SYNCH);
//0: lowGUID
PrepareStatement(CHAR_SEL_PINFO_MAILS, "SELECT SUM(CASE WHEN (checked & 1) THEN 1 ELSE 0 END) AS 'readmail', COUNT(*) AS 'totalmail' FROM mail WHERE `receiver` = ?", CONNECTION_SYNCH);
//0: lowGUID
PrepareStatement(CHAR_SEL_PINFO_XP, "SELECT a.xp, b.guid FROM characters a LEFT JOIN guild_member b ON a.guid = b.guid WHERE a.guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_HOMEBIND, "SELECT mapId, zoneId, posX, posY, posZ FROM character_homebind WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_GUID_NAME_BY_ACC, "SELECT guid, name FROM characters WHERE account = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_POOL_QUEST_SAVE, "SELECT quest_id FROM pool_quest_save WHERE pool_id = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHARACTER_AT_LOGIN, "SELECT at_login FROM characters WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_CLASS_LVL_AT_LOGIN, "SELECT class, level, at_login, knownTitles FROM characters WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_AT_LOGIN_TITLES, "SELECT at_login, knownTitles FROM characters WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_INSTANCE, "SELECT data, completedEncounters FROM instance WHERE map = ? AND id = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_COD_ITEM_MAIL, "SELECT id, messageType, mailTemplateId, sender, subject, body, money, has_items FROM mail WHERE receiver = ? AND has_items <> 0 AND cod <> 0", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_SOCIAL, "SELECT DISTINCT guid FROM character_social WHERE friend = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_OLD_CHARS, "SELECT guid, deleteInfos_Account FROM characters WHERE deleteDate IS NOT NULL AND deleteDate < ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_ARENA_TEAM_ID_BY_PLAYER_GUID, "SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid = ? AND type = ? LIMIT 1", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_MAIL, "SELECT id, messageType, sender, receiver, subject, body, has_items, expire_time, deliver_time, money, cod, checked, stationery, mailTemplateId FROM mail WHERE receiver = ? ORDER BY id DESC", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_PLAYERBYTES2, "SELECT playerBytes2 FROM characters WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_GUID_BY_NAME, "SELECT guid FROM characters WHERE name = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_DEL_CHAR_AURA_FROZEN, "DELETE FROM character_aura WHERE spell = 9454 AND guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHAR_INVENTORY_COUNT_ITEM, "SELECT COUNT(itemEntry) FROM character_inventory ci INNER JOIN item_instance ii ON ii.guid = ci.item WHERE itemEntry = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_MAIL_COUNT_ITEM, "SELECT COUNT(itemEntry) FROM mail_items mi INNER JOIN item_instance ii ON ii.guid = mi.item_guid WHERE itemEntry = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_AUCTIONHOUSE_COUNT_ITEM,"SELECT COUNT(itemEntry) FROM auctionhouse ah INNER JOIN item_instance ii ON ii.guid = ah.itemguid WHERE itemEntry = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_GUILD_BANK_COUNT_ITEM, "SELECT COUNT(itemEntry) FROM guild_bank_item gbi INNER JOIN item_instance ii ON ii.guid = gbi.item_guid WHERE itemEntry = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_INVENTORY_ITEM_BY_ENTRY, "SELECT ci.item, cb.slot AS bag, ci.slot, ci.guid, c.account, c.name FROM characters c "
"INNER JOIN character_inventory ci ON ci.guid = c.guid "
"INNER JOIN item_instance ii ON ii.guid = ci.item "
"LEFT JOIN character_inventory cb ON cb.item = ci.bag WHERE ii.itemEntry = ? LIMIT ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_MAIL_ITEMS_BY_ENTRY, "SELECT mi.item_guid, m.sender, m.receiver, cs.account, cs.name, cr.account, cr.name "
"FROM mail m INNER JOIN mail_items mi ON mi.mail_id = m.id INNER JOIN item_instance ii ON ii.guid = mi.item_guid "
"INNER JOIN characters cs ON cs.guid = m.sender INNER JOIN characters cr ON cr.guid = m.receiver WHERE ii.itemEntry = ? LIMIT ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_AUCTIONHOUSE_ITEM_BY_ENTRY, "SELECT ah.itemguid, ah.itemowner, c.account, c.name FROM auctionhouse ah INNER JOIN characters c ON c.guid = ah.itemowner INNER JOIN item_instance ii ON ii.guid = ah.itemguid WHERE ii.itemEntry = ? LIMIT ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_GUILD_BANK_ITEM_BY_ENTRY, "SELECT gi.item_guid, gi.guildid, g.name FROM guild_bank_item gi INNER JOIN guild g ON g.guildid = gi.guildid INNER JOIN item_instance ii ON ii.guid = gi.item_guid WHERE ii.itemEntry = ? LIMIT ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_DEL_CHAR_ACHIEVEMENT, "DELETE FROM character_achievement WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_ACHIEVEMENT_PROGRESS, "DELETE FROM character_achievement_progress WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_REPUTATION_BY_FACTION, "DELETE FROM character_reputation WHERE guid = ? AND faction = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHAR_REPUTATION_BY_FACTION, "INSERT INTO character_reputation (guid, faction, standing, flags) VALUES (?, ?, ? , ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_ITEM_REFUND_INSTANCE, "DELETE FROM item_refund_instance WHERE item_guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_ITEM_REFUND_INSTANCE, "INSERT INTO item_refund_instance (item_guid, player_guid, paidMoney, paidExtendedCost) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GROUP, "DELETE FROM groups WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GROUP_MEMBER_ALL, "DELETE FROM group_member WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHAR_GIFT, "INSERT INTO character_gifts (guid, item_guid, entry, flags) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_INSTANCE_BY_INSTANCE, "DELETE FROM instance WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE, "DELETE FROM character_instance WHERE instance = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_INSTANCE_BY_MAP_DIFF, "DELETE FROM character_instance USING character_instance LEFT JOIN instance ON character_instance.instance = id WHERE map = ? and difficulty = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GROUP_INSTANCE_BY_MAP_DIFF, "DELETE FROM group_instance USING group_instance LEFT JOIN instance ON group_instance.instance = id WHERE map = ? and difficulty = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_INSTANCE_BY_MAP_DIFF, "DELETE FROM instance WHERE map = ? and difficulty = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_MAIL_ITEM_BY_ID, "DELETE FROM mail_items WHERE mail_id = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_PETITION, "INSERT INTO petition (ownerguid, petitionguid, name, type) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_PETITION_BY_GUID, "DELETE FROM petition WHERE petitionguid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_PETITION_SIGNATURE_BY_GUID, "DELETE FROM petition_sign WHERE petitionguid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_DECLINED_NAME, "DELETE FROM character_declinedname WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHAR_DECLINED_NAME, "INSERT INTO character_declinedname (guid, genitive, dative, accusative, instrumental, prepositional) VALUES (?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_FACTION_OR_RACE, "UPDATE characters SET name = ?, race = ?, at_login = at_login & ~ ? WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_SKILL_LANGUAGES, "DELETE FROM character_skills WHERE skill IN (98, 113, 759, 111, 313, 109, 115, 315, 673, 137) AND guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHAR_SKILL_LANGUAGE, "INSERT INTO `character_skills` (guid, skill, value, max) VALUES (?, ?, 300, 300)", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHAR_TAXI_PATH, "UPDATE characters SET taxi_path = '' WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHAR_TAXIMASK, "UPDATE characters SET taximask = ? WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_QUESTSTATUS, "DELETE FROM character_queststatus WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_SOCIAL_BY_GUID, "DELETE FROM character_social WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_SOCIAL_BY_FRIEND, "DELETE FROM character_social WHERE friend = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_ACHIEVEMENT_BY_ACHIEVEMENT, "DELETE FROM character_achievement WHERE achievement = ? AND guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHAR_ACHIEVEMENT, "UPDATE character_achievement SET achievement = ? where achievement = ? AND guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHAR_INVENTORY_FACTION_CHANGE, "UPDATE item_instance ii, character_inventory ci SET ii.itemEntry = ? WHERE ii.itemEntry = ? AND ci.guid = ? AND ci.item = ii.guid", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_SPELL_BY_SPELL, "DELETE FROM character_spell WHERE spell = ? AND guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHAR_SPELL_FACTION_CHANGE, "UPDATE character_spell SET spell = ? where spell = ? AND guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHAR_REP_BY_FACTION, "SELECT standing FROM character_reputation WHERE faction = ? AND guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_DEL_CHAR_REP_BY_FACTION, "DELETE FROM character_reputation WHERE faction = ? AND guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHAR_REP_FACTION_CHANGE, "UPDATE character_reputation SET faction = ?, standing = ? WHERE faction = ? AND guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHAR_TITLES_FACTION_CHANGE, "UPDATE characters SET knownTitles = ? WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_RES_CHAR_TITLES_FACTION_CHANGE, "UPDATE characters SET chosenTitle = 0 WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_SPELL_COOLDOWN, "DELETE FROM character_spell_cooldown WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHARACTER, "DELETE FROM characters WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_ACTION, "DELETE FROM character_action WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_AURA, "DELETE FROM character_aura WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_GIFT, "DELETE FROM character_gifts WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_INSTANCE, "DELETE FROM character_instance WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_INVENTORY, "DELETE FROM character_inventory WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED, "DELETE FROM character_queststatus_rewarded WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_REPUTATION, "DELETE FROM character_reputation WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_SPELL, "DELETE FROM character_spell WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_MAIL, "DELETE FROM mail WHERE receiver = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_MAIL_ITEMS, "DELETE FROM mail_items WHERE receiver = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_ACHIEVEMENTS, "DELETE FROM character_achievement WHERE guid = ? AND achievement NOT BETWEEN '456' AND '467' AND achievement NOT BETWEEN '1400' AND '1427' AND achievement NOT IN(1463, 3117, 3259)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_EQUIPMENTSETS, "DELETE FROM character_equipmentsets WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GUILD_EVENTLOG_BY_PLAYER, "DELETE FROM guild_eventlog WHERE PlayerGuid1 = ? OR PlayerGuid2 = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GUILD_BANK_EVENTLOG_BY_PLAYER, "DELETE FROM guild_bank_eventlog WHERE PlayerGuid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_GLYPHS, "DELETE FROM character_glyphs WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_QUESTSTATUS_DAILY, "DELETE FROM character_queststatus_daily WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_TALENT, "DELETE FROM character_talent WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_SKILLS, "DELETE FROM character_skills WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UDP_CHAR_MONEY, "UPDATE characters SET money = ? WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHAR_ACTION, "INSERT INTO character_action (guid, spec, button, action, type) VALUES (?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHAR_ACTION, "UPDATE character_action SET action = ?, type = ? WHERE guid = ? AND button = ? AND spec = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_ACTION_BY_BUTTON_SPEC, "DELETE FROM character_action WHERE guid = ? and button = ? and spec = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_INVENTORY_BY_ITEM, "DELETE FROM character_inventory WHERE item = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_INVENTORY_BY_BAG_SLOT, "DELETE FROM character_inventory WHERE bag = ? AND slot = ? AND guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_MAIL, "UPDATE mail SET has_items = ?, expire_time = ?, deliver_time = ?, money = ?, cod = ?, checked = ? WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_REP_CHAR_QUESTSTATUS, "REPLACE INTO character_queststatus (guid, quest, status, explored, timer, mobcount1, mobcount2, mobcount3, mobcount4, itemcount1, itemcount2, itemcount3, itemcount4, playercount) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_QUESTSTATUS_BY_QUEST, "DELETE FROM character_queststatus WHERE guid = ? AND quest = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHAR_QUESTSTATUS, "INSERT IGNORE INTO character_queststatus_rewarded (guid, quest) VALUES (?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED_BY_QUEST, "DELETE FROM character_queststatus_rewarded WHERE guid = ? AND quest = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_SKILL_BY_SKILL, "DELETE FROM character_skills WHERE guid = ? AND skill = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHAR_SKILLS, "INSERT INTO character_skills (guid, skill, value, max) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_UDP_CHAR_SKILLS, "UPDATE character_skills SET value = ?, max = ? WHERE guid = ? AND skill = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHAR_SPELL, "INSERT INTO character_spell (guid, spell, active, disabled) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_STATS, "DELETE FROM character_stats WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHAR_STATS, "INSERT INTO character_stats (guid, maxhealth, maxpower1, maxpower2, maxpower3, maxpower4, maxpower5, strength, agility, stamina, intellect, spirit, "
"armor, resHoly, resFire, resNature, resFrost, resShadow, resArcane, blockPct, dodgePct, parryPct, critPct, rangedCritPct, spellCritPct, attackPower, rangedAttackPower, "
"spellPower, resilience) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_PETITION_BY_OWNER, "DELETE FROM petition WHERE ownerguid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_PETITION_SIGNATURE_BY_OWNER, "DELETE FROM petition_sign WHERE ownerguid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_PETITION_BY_OWNER_AND_TYPE, "DELETE FROM petition WHERE ownerguid = ? AND type = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_PETITION_SIGNATURE_BY_OWNER_AND_TYPE, "DELETE FROM petition_sign WHERE ownerguid = ? AND type = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHAR_GLYPHS, "INSERT INTO character_glyphs (guid, spec, glyph1, glyph2, glyph3, glyph4, glyph5, glyph6, glyph7, glyph8, glyph9) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_TALENT_BY_SPELL_SPEC, "DELETE FROM character_talent WHERE guid = ? and spell = ? and spec = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHAR_TALENT, "INSERT INTO character_talent (guid, spell, spec) VALUES (?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_ACTION_EXCEPT_SPEC, "DELETE FROM character_action WHERE spec<>? AND guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_CHAR_LIST_SLOT, "UPDATE characters SET slot = ? WHERE guid = ?", CONNECTION_ASYNC);
// Void Storage
PrepareStatement(CHAR_SEL_CHAR_VOID_STORAGE, "SELECT itemId, itemEntry, slot, creatorGuid, randomProperty, suffixFactor FROM character_void_storage WHERE playerGuid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_REP_CHAR_VOID_STORAGE_ITEM, "REPLACE INTO character_void_storage (itemId, playerGuid, itemEntry, slot, creatorGuid, randomProperty, suffixFactor) VALUES (?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_VOID_STORAGE_ITEM_BY_SLOT, "DELETE FROM character_void_storage WHERE slot = ? AND playerGuid = ?", CONNECTION_ASYNC);
// CompactUnitFrame profiles
PrepareStatement(CHAR_SEL_CHAR_CUF_PROFILES, "SELECT id, name, frameHeight, frameWidth, sortBy, healthText, boolOptions, unk146, unk147, unk148, unk150, unk152, unk154 FROM character_cuf_profiles WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_REP_CHAR_CUF_PROFILES, "REPLACE INTO character_cuf_profiles (guid, id, name, frameHeight, frameWidth, sortBy, healthText, boolOptions, unk146, unk147, unk148, unk150, unk152, unk154) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_CUF_PROFILES, "DELETE FROM character_cuf_profiles WHERE guid = ? and id = ?", CONNECTION_ASYNC);
// Guild Finder
PrepareStatement(CHAR_REP_GUILD_FINDER_APPLICANT, "REPLACE INTO guild_finder_applicant (guildId, playerGuid, availability, classRole, interests, comment, submitTime) VALUES(?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GUILD_FINDER_APPLICANT, "DELETE FROM guild_finder_applicant WHERE guildId = ? AND playerGuid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_REP_GUILD_FINDER_GUILD_SETTINGS, "REPLACE INTO guild_finder_guild_settings (guildId, availability, classRoles, interests, level, listed, comment) VALUES(?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_GUILD_FINDER_GUILD_SETTINGS, "DELETE FROM guild_finder_guild_settings WHERE guildId = ?", CONNECTION_ASYNC);
// Items that hold loot or money
PrepareStatement(CHAR_SEL_ITEMCONTAINER_ITEMS, "SELECT item_id, item_count, follow_rules, ffa, blocked, counted, under_threshold, needs_quest, rnd_prop, rnd_suffix FROM item_loot_items WHERE container_id = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_DEL_ITEMCONTAINER_ITEMS, "DELETE FROM item_loot_items WHERE container_id = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_ITEMCONTAINER_ITEM, "DELETE FROM item_loot_items WHERE container_id = ? AND item_id = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_ITEMCONTAINER_ITEMS, "INSERT INTO item_loot_items (container_id, item_id, item_count, follow_rules, ffa, blocked, counted, under_threshold, needs_quest, rnd_prop, rnd_suffix) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_ITEMCONTAINER_MONEY, "SELECT money FROM item_loot_money WHERE container_id = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_DEL_ITEMCONTAINER_MONEY, "DELETE FROM item_loot_money WHERE container_id = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_ITEMCONTAINER_MONEY, "INSERT INTO item_loot_money (container_id, money) VALUES (?, ?)", CONNECTION_ASYNC);
// Calendar
PrepareStatement(CHAR_REP_CALENDAR_EVENT, "REPLACE INTO calendar_events (id, creator, title, description, type, dungeon, eventtime, flags, time2) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CALENDAR_EVENT, "DELETE FROM calendar_events WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_REP_CALENDAR_INVITE, "REPLACE INTO calendar_invites (id, event, invitee, sender, status, statustime, rank, text) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CALENDAR_INVITE, "DELETE FROM calendar_invites WHERE id = ?", CONNECTION_ASYNC);
// Pet
//Select Part
PrepareStatement(CHAR_SEL_CHAR_PET, "SELECT id FROM character_pet WHERE owner = ? AND id <> ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_CHAR_PETS, "SELECT id FROM character_pet WHERE owner = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_PET_SLOTS, "SELECT id, entry, owner, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, abdata, savetime, CreatedBySpell, PetType FROM character_pet WHERE owner = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_PET_SPELL_LIST, "SELECT guid, spell, active FROM pet_spell,character_pet WHERE pet_spell.guid = character_pet.id and character_pet.owner = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_PET_SPELL_COOLDOWN, "SELECT guid, spell, time FROM pet_spell_cooldown,character_pet WHERE pet_spell_cooldown.guid = character_pet.id and character_pet.owner = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_PET_AURA, "SELECT guid,caster_guid, spell, effect_mask, recalculate_mask, stackcount, amount0, amount1, amount2, base_amount0, base_amount1, base_amount2, maxduration, remaintime, remaincharges FROM pet_aura,character_pet WHERE pet_aura.guid = character_pet.id and character_pet.owner = ?", CONNECTION_ASYNC);
//Remove Part
PrepareStatement(CHAR_DEL_CHAR_PET_BY_ID, "DELETE FROM character_pet WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_PET_AURAS, "DELETE FROM pet_aura WHERE guid = ?", CONNECTION_BOTH);
PrepareStatement(CHAR_DEL_PET_SPELLS, "DELETE FROM pet_spell WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_PET_SPELL_COOLDOWNS, "DELETE FROM pet_spell_cooldown WHERE guid = ?", CONNECTION_BOTH);
//Insert
PrepareStatement(CHAR_INS_PET_BASE, "INSERT INTO character_pet (id, entry, owner, modelid, CreatedBySpell, PetType, level, exp, Reactstate, name, renamed, slot, curhealth, curmana, savetime, abdata) VALUES (?, ?, ?, ?,?, ?, ?, ?,?, ?, ?, ?,?, ?, ?, ?)", CONNECTION_BOTH);
PrepareStatement(CHAR_INS_PET_SPELL, "INSERT INTO pet_spell (guid, spell, active) VALUES (?, ?, ?)", CONNECTION_BOTH);
PrepareStatement(CHAR_INS_PET_SPELL_COOLDOWN, "INSERT INTO pet_spell_cooldown (guid, spell, time) VALUES (?, ?, ?)", CONNECTION_BOTH);
PrepareStatement(CHAR_INS_PET_AURA, "INSERT INTO pet_aura (guid, caster_guid, spell, effect_mask, recalculate_mask, stackcount, amount0, amount1, amount2, "
"base_amount0, base_amount1, base_amount2, maxduration, remaintime, remaincharges) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_BOTH);
PrepareStatement(CHAR_DEL_CHAR_PET_DECLINEDNAME_BY_OWNER, "DELETE FROM character_pet_declinedname WHERE owner = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_PET_DECLINEDNAME, "DELETE FROM character_pet_declinedname WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_ADD_CHAR_PET_DECLINEDNAME, "INSERT INTO character_pet_declinedname (id, owner, genitive, dative, accusative, instrumental, prepositional) VALUES (?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_PET_DECLINED_NAME, "SELECT genitive, dative, accusative, instrumental, prepositional FROM character_pet_declinedname WHERE owner = ? AND id = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_DEL_CHAR_PET_BY_OWNER, "DELETE FROM character_pet WHERE owner = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_DEL_CHAR_DIGSITES, "DELETE FROM character_digsites WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHAR_DIGSITES, "INSERT INTO character_digsites VALUES (?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHAR_DIGSITES, "SELECT entry FROM character_digsites WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_DEL_CHAR_CURRENT_ARTEFACTS, "DELETE FROM character_current_artifacts WHERE guid = ?", CONNECTION_ASYNC);
PrepareStatement(CHAR_INS_CHAR_CURRENT_ARTEFACTS, "INSERT INTO character_current_artifacts VALUES(?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_CHAR_CURRENT_ARTEFACTS, "SELECT entry, branchId FROM character_current_artifacts WHERE guid = ?", CONNECTION_SYNCH);
PrepareStatement(CHAR_SEL_MAILS, "SELECT id, messageType, sender, receiver, subject, body, has_items, expire_time, deliver_time, money, cod, checked, stationery, mailTemplateId FROM mail WHERE receiver = ? ORDER BY id DESC", CONNECTION_ASYNC);
PrepareStatement(CHAR_SEL_MAILS_ITEMS, "SELECT creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text, item_guid, itemEntry, owner_guid, mail_id FROM mail INNER JOIN mail_items ON (mail.id = mail_items.mail_id) INNER JOIN item_instance ON (mail_items.item_guid = item_instance.guid) WHERE mail.has_items = 1 AND mail.receiver = ? ORDER BY id DESC", CONNECTION_ASYNC);
// QuestTracker
PrepareStatement(CHAR_INS_QUEST_TRACK, "INSERT INTO quest_tracker (id, character_guid, quest_accept_time, core_hash, core_revision) VALUES (?, ?, NOW(), ?, ?)", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_QUEST_TRACK_GM_COMPLETE, "UPDATE quest_tracker SET completed_by_gm = 1 WHERE id = ? AND character_guid = ? ORDER BY quest_accept_time DESC LIMIT 1", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_QUEST_TRACK_COMPLETE_TIME, "UPDATE quest_tracker SET quest_complete_time = NOW() WHERE id = ? AND character_guid = ? ORDER BY quest_accept_time DESC LIMIT 1", CONNECTION_ASYNC);
PrepareStatement(CHAR_UPD_QUEST_TRACK_ABANDON_TIME, "UPDATE quest_tracker SET quest_abandon_time = NOW() WHERE id = ? AND character_guid = ? ORDER BY quest_accept_time DESC LIMIT 1", CONNECTION_ASYNC);
}
| gpl-2.0 |
otmarjr/jtreg-fork | make/netbeans/lib/testng-6.8/testng-6.8/src/main/java/org/testng/internal/SuiteRunnerMap.java | 526 | package org.testng.internal;
import org.testng.ISuite;
import org.testng.collections.Maps;
import org.testng.xml.XmlSuite;
import java.util.Collection;
import java.util.Map;
public class SuiteRunnerMap {
private Map<String, ISuite> m_map = Maps.newHashMap();
public void put(XmlSuite xmlSuite, ISuite suite) {
m_map.put(xmlSuite.getName(), suite);
}
public ISuite get(XmlSuite xmlSuite) {
return m_map.get(xmlSuite.getName());
}
public Collection<ISuite> values() {
return m_map.values();
}
}
| gpl-2.0 |
wenshao/oceanbase | src/rootserver/ob_root_meta2.cpp | 6210 | /*
* (C) 2007-2010 Taobao Inc.
*
*
*
* Version: 0.1
*
* Authors:
* daoan <daoan@taobao.com>
*
*/
#include <algorithm>
#include <tbsys.h>
#include "rootserver/ob_root_meta2.h"
#include "rootserver/ob_tablet_info_manager.h"
namespace oceanbase
{
using namespace common;
namespace rootserver
{
ObRootMeta2::ObRootMeta2():tablet_info_index_(OB_INVALID_INDEX), last_dead_server_time_(0), last_migrate_time_(0)
{
for (int i = 0; i < OB_SAFE_COPY_COUNT; ++i)
{
server_info_indexes_[i] = OB_INVALID_INDEX;
tablet_version_[i] = 0;
}
}
void ObRootMeta2::dump() const
{
for (int32_t i = 0; i < common::OB_SAFE_COPY_COUNT; i++)
{
TBSYS_LOG(INFO, "server_info_index = %d, tablet_version = %ld",
server_info_indexes_[i], tablet_version_[i]);
}
TBSYS_LOG(INFO, "last_dead_server_time = %ld last_migrate_time = %ld",
last_dead_server_time_, last_migrate_time_);
}
void ObRootMeta2::dump(const int server_index, int64_t &tablet_num) const
{
for (int32_t i = 0; i < common::OB_SAFE_COPY_COUNT; i++)
{
if (server_index == server_info_indexes_[i])
{
tablet_num ++;
TBSYS_LOG(INFO, "tablet_number = %ld, server_info_index = %d, tablet_version = %ld",
tablet_num, server_info_indexes_[i], tablet_version_[i]);
}
}
}
void ObRootMeta2::dump_as_hex(FILE* stream) const
{
if (stream != NULL)
{
fprintf(stream, "tablet_info_index %d ", tablet_info_index_);
}
for (int32_t i = 0; i < common::OB_SAFE_COPY_COUNT; i++)
{
fprintf(stream, "server_info_index %d tablet_version %ld ",
server_info_indexes_[i], tablet_version_[i]);
}
fprintf(stream, "last_dead_server_time %ld\n", last_dead_server_time_);
return;
}
void ObRootMeta2::read_from_hex(FILE* stream)
{
if (stream != NULL)
{
fscanf(stream, "tablet_info_index %d ", &tablet_info_index_);
}
for (int32_t i = 0; i < common::OB_SAFE_COPY_COUNT; i++)
{
fscanf(stream, "server_info_index %d tablet_version %ld ",
&server_info_indexes_[i], &tablet_version_[i]);
}
fscanf(stream, "last_dead_server_time %ld\n", &last_dead_server_time_);
return;
}
DEFINE_SERIALIZE(ObRootMeta2)
{
int ret = OB_SUCCESS;
int64_t tmp_pos = pos;
if (OB_SUCCESS == ret)
{
ret = serialization::encode_vi32(buf, buf_len, tmp_pos, tablet_info_index_);
}
if (OB_SUCCESS == ret)
{
ret = serialization::encode_vi64(buf, buf_len, tmp_pos, last_dead_server_time_);
}
for (int32_t i = 0; i < OB_SAFE_COPY_COUNT; ++i)
{
if (OB_SUCCESS == ret)
{
ret = serialization::encode_vi32(buf, buf_len, tmp_pos, server_info_indexes_[i]);
}
if (OB_SUCCESS == ret)
{
ret = serialization::encode_vi64(buf, buf_len, tmp_pos, tablet_version_[i]);
}
}
if (OB_SUCCESS == ret)
{
pos = tmp_pos;
}
return ret;
}
DEFINE_DESERIALIZE(ObRootMeta2)
{
int ret = OB_SUCCESS;
int64_t tmp_pos = pos;
if (OB_SUCCESS == ret)
{
ret = serialization::decode_vi32(buf, data_len, tmp_pos, &tablet_info_index_);
}
if (OB_SUCCESS == ret)
{
ret = serialization::decode_vi64(buf, data_len, tmp_pos, &last_dead_server_time_);
}
for (int32_t i = 0; i < OB_SAFE_COPY_COUNT; ++i)
{
if (OB_SUCCESS == ret)
{
ret = serialization::decode_vi32(buf, data_len, tmp_pos, &(server_info_indexes_[i]));
}
if (OB_SUCCESS == ret)
{
ret = serialization::decode_vi64(buf, data_len, tmp_pos, &(tablet_version_[i]));
}
}
if (OB_SUCCESS == ret)
{
pos = tmp_pos;
}
return ret;
}
DEFINE_GET_SERIALIZE_SIZE(ObRootMeta2)
{
int64_t len = serialization::encoded_length_vi32(tablet_info_index_);
len += serialization::encoded_length_vi64(last_dead_server_time_);
for (int32_t i = 0; i < OB_SAFE_COPY_COUNT; i++)
{
len += serialization::encoded_length_vi32(server_info_indexes_[i]);
len += serialization::encoded_length_vi64(tablet_version_[i]);
}
return len;
}
void ObRootMeta2::has_been_migrated()
{
last_migrate_time_ = tbsys::CTimeUtil::getTime();
}
bool ObRootMeta2::can_be_migrated_now(int64_t disabling_period_us) const
{
bool ret = false;
if (0 >= last_migrate_time_)
{
ret = true;
}
else
{
int64_t now = tbsys::CTimeUtil::getTime();
ret = (now > last_migrate_time_ + disabling_period_us);
}
return ret;
}
ObRootMeta2CompareHelper::ObRootMeta2CompareHelper(ObTabletInfoManager* otim):tablet_info_manager_(otim)
{
}
int ObRootMeta2CompareHelper::compare(const int32_t r1, const int32_t r2) const
{
int ret = 0;
if (tablet_info_manager_ != NULL)
{
const ObTabletInfo* p_r1 = NULL;
const ObTabletInfo* p_r2 = NULL;
p_r1 = tablet_info_manager_->get_tablet_info(r1);
p_r2 = tablet_info_manager_->get_tablet_info(r2);
if (p_r1 != p_r2)
{
if (p_r1 == NULL)
{
ret = -1;
}
else if (p_r2 == NULL)
{
ret = 1;
}
else
{
ret = p_r1->range_.compare_with_endkey(p_r2->range_);
}
}
}
else
{
TBSYS_LOG(WARN, "NULL info manager");
}
return ret;
}
bool ObRootMeta2CompareHelper::operator () (const ObRootMeta2& r1, const ObRootMeta2& r2) const
{
int res = compare(r1.tablet_info_index_, r2.tablet_info_index_);
if (0 == res)
{
//res = static_cast<int> (&r1 - &r2);
res = static_cast<int> (r1.tablet_info_index_ - r2.tablet_info_index_);
}
return res < 0;
}
} // end namespace rootserver
} // end namespace oceanbase
| gpl-2.0 |
tommythorn/yari | shared/cacao-related/phoneme_feature/jsr239/src/share/classes/javax/microedition/khronos/opengles/GL11ExtensionPack.java | 112860 | /*
* Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package javax.microedition.khronos.opengles;
import java.nio.*;
/**
* The <code>GL11ExtensionPack</code> interface contains the Java(TM)
* programming language bindings for the OpenGL ES 1.1 Extension Pack.
* The runtime OpenGL ES engine may or may not implement any
* particular extensions defined in the extension pack. Functions
* that require a particular extension will throw an
* <code>UnsupportedOperationException</code> if the extension is not
* available at runtime.
*
* <p> The OpenGL ES 1.1 Extension Pack consists of the following extensions:
*
* <ul>
* <li>OES_texture_env_crossbar</li>
* <li>OES_texture_mirrored_repeat</li>
* <li>OES_texture_cube_map</li>
* <li>OES_blend_subtract</li>
* <li>OES_blend_func_separate</li>
* <li>OES_blend_equation_separate</li>
* <li>OES_stencil_wrap</li>
* <li>OES_extended_matrix_palette</li>
* <li>OES_framebuffer_object</li>
* </ul>
*
* <p> The specification for the OpenGL ES 1.1 Extension Pack may be
* found at <a
* href="http://www.khronos.org/cgi-bin/fetch/fetch.cgi?opengles_spec_1_1_extension_pack">http://www.khronos.org/cgi-bin/fetch/fetch.cgi?opengles_spec_1_1_extension_pack</a>.
*
* <p> The documentation in this class is normative with respect to
* instance variable names and values, method names and signatures,
* and exception behavior. The remaining documentation is placed here
* for convenience and does not replace the normative documentation
* found in the OpenGL ES 1.1 Extension Pack specification, OpenGL ES
* specification, relevant extension specifications, and the OpenGL
* specification versions referenced by any of the preceding
* specifications.
*/
public interface GL11ExtensionPack extends GL {
// /**
// * Flag indicating the presence of the "texture env crossbar"
// * extension. <code>OES_texture_env_crossbar</code> is an optional
// * profile extension in OpenGL ES 1.1, and is part of the OpenGL ES
// * 1.1 Extension Pack.
// *
// * <p> The value of this flag does not imply the presence of the
// * extension in the runtime enviroment.
// */
// int GL_OES_texture_env_crossbar = 1;
/**
* (<code>OES_texture_env_crossbar</code> extension)
* Set texture environment parameters.
*
* <p> The <code>OES_texture_env_crossbar</code> extension adds the
* capability to use the texture color from other texture units as
* sources to the <code>COMBINE</code> texture function. OpenGL ES
* 1.1 defined texture combine functions which could use the color
* from the current texture unit as a source. This extension adds
* the ability to use the color from any texture unit as a source.
*
* <p> The tables that define arguments for <code>COMBINE_RGB</code>
* and <code>COMBINE_ALPHA</code> functions are extended to include
* <code>TEXTURE</code><i>n</i>:
*
* <pre>
* SRCn_RGB OPERANDn_RGB Argument
*
* TEXTURE SRC_COLOR Cs
* ONE_MINUS_SRC_COLOR 1 - Cs
* SRC_ALPHA As
* ONE_MINUS_SRC_ALPHA 1 - As
*
* TEXTUREn SRC_COLOR Cs^n
* ONE_MINUS_SRC_COLOR 1 - Cs^n
* SRC_ALPHA As^n
* ONE_MINUS_SRC_ALPHA 1 - As^n
*
* CONSTANT SRC_COLOR Cc
* ONE_MINUS_SRC_COLOR 1 - Cc
* SRC_ALPHA Ac
* ONE_MINUS_SRC_ALPHA 1 - Ac
*
* PRIMARY_COLOR SRC_COLOR Cf
* ONE_MINUS_SRC_COLOR 1 - Cf
* SRC_ALPHA Af
* ONE_MINUS_SRC_ALPHA 1 - Af
*
* PREVIOUS SRC_COLOR Cp
* ONE_MINUS_SRC_COLOR 1 - Cp
* SRC_ALPHA Ap
* ONE_MINUS_SRC_ALPHA 1 - Ap
* </pre>
*
* @param param additionally accept <code>TEXTURE</code><i>n</i>,
* where <i>n</i> is a number between 0 and 31, inclusive.
*
* @see GL11#glTexEnvf(int target, int pname, float param)
*/
void glTexEnvf(int target, int pname, float param);
/**
* (<code>OES_texture_env_crossbar</code> extension)
* Floating-point array version of <code>glTexEnv</code>.
*
* @see #glTexEnvf(int target, int pname, float param)
*
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>offset</code> is
* less than 0.
* @exception IllegalArgumentException if <code>params.length -
* offset</code> is smaller than the number of values required by
* the parameter.
*/
void glTexEnvfv(int target, int pname, float[] params, int offset);
/**
* (<code>OES_texture_env_crossbar</code> extension)
* Floating-point <code>Buffer</code> version of
* <code>glTexEnv</code>.
*
* @see #glTexEnvf(int target, int pname, float param)
*
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if
* <code>params.remaining()</code> is smaller than the number of
* values required by the parameter.
*/
void glTexEnvfv(int target, int pname, FloatBuffer params);
/**
* (<code>OES_texture_env_crossbar</code> extension)
* Integer version of <code>glTexEnv</code>.
*
* @see #glTexEnvf(int target, int pname, float param)
*/
void glTexEnvx(int target, int pname, int param);
/**
* (<code>OES_texture_env_crossbar</code> extension)
* Fixed-point array version of <code>glTexEnv</code>.
*
* @see #glTexEnvf(int target, int pname, float param)
*
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>offset</code> is
* less than 0.
* @exception IllegalArgumentException if <code>params.length -
* offset</code> is smaller than the number of values required by
* the parameter.
*/
void glTexEnvxv(int target, int pname, int[] params, int offset);
/**
* (<code>OES_texture_env_crossbar</code> extension)
* Fixed-point <code>Buffer</code> version of <code>glTexEnv</code>.
*
* @see #glTexEnvf(int target, int pname, float param)
*
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if
* <code>params.remaining()</code> is smaller than the number of
* values required by the parameter.
*/
void glTexEnvxv(int target, int pname, IntBuffer params);
// /**
// * Flag indicating the presence of the "texture mirrored repeat"
// * extension. <code>OES_texture_mirrored_repeat</code> is an optional
// * profile extension in OpenGL ES 1.1, and is part of the OpenGL ES
// * 1.1 Extension Pack.
// *
// * <p> The value of this flag does not imply the presence of the
// * extension in the runtime enviroment.
// */
// int GL_OES_texture_mirrored_repeat = 1;
/**
* Constant for use with <code>glTexParameter</code> and
* <code>glGetTexParameter</code>
* (<code>OES_texture_mirrored_repeat</code> extension).
*/
int GL_MIRRORED_REPEAT = 0x8370;
/**
* (<code>OES_texture_mirrored_repeat</code> extension)
* Set texture parameters.
*
* <p> An additional option is accepted for
* <code>GL_TEXTURE_WRAP_S</code> and
* <code>GL_TEXTURE_WRAP_T</code></li> parameters.
* <code>GL_MIRRORED_REPEAT</code> effectively uses a texture map
* twice as large as the original image im which the additional
* half, for each coordinate, of the new image is a mirror image of
* the original image.
*
* @see GL11#glTexParameterf(int target, int pname, float param)
*/
void glTexParameterf(int target, int pname, float param);
// /**
// * Flag indicating the presence of the "texture cube map" extension.
// * <code>OES_texture_cube_map</code> is an optional profile
// * extension in OpenGL ES 1.1, and is part of the OpenGL ES 1.1
// * Extension Pack.
// *
// * <p> The value of this flag does not imply the presence of the
// * extension in the runtime enviroment.
// */
// int GL_OES_texture_cube_map = 1;
/**
* Constant for use with <code>glTexGen</code>
* (<code>OES_texture_cube_map</code> extension).
*/
int GL_NORMAL_MAP = 0x8511;
/**
* Constant for use with <code>glTexGen</code>
* (<code>OES_texture_cube_map</code> extension).
*/
int GL_REFLECTION_MAP = 0x8512;
/**
* Constant for use with <code>glBindTexture</code>,
* <code>glTexParameter</code>, <code>glEnable</code>,
* <code>glDisable</code>, and <code>glIsEnabled</code>
* (<code>OES_texture_cube_map</code> extension).
*/
int GL_TEXTURE_CUBE_MAP = 0x8513;
/**
* Constant for use with <code>glGetInteger</code>
* (<code>OES_texture_cube_map</code> extension).
*/
int GL_TEXTURE_BINDING_CUBE_MAP = 0x8514;
// Need revisit - value
/**
* Constant for use with <code>glTexGen</code> for the
* <code>OES_texture_cube_map</code> extension.
*/
int GL_STR = -1;
/**
* Constant for use with <code>glTexGen</code>
* (<code>OES_texture_cube_map</code> extension).
*/
int GL_TEXTURE_GEN_MODE = 0x2500;
/**
* Constant for use with <code>glEnable</code> and
* <code>glDisable</code> (<code>OES_texture_cube_map</code>
* extension).
*/
int GL_TEXTURE_GEN_STR = 0x8D60;
/**
* Constant for use with <code>glTexImage2D</code> and
* <code>glCompressedTexImage2D</code>
* (<code>OES_texture_cube_map</code> extension).
*/
int GL_TEXTURE_CUBE_MAP_POSITIVE_X = 0x207D;
/**
* Constant for use with <code>glTexImage2D</code> and
* <code>glCompressedTexImage2D</code>
* (<code>OES_texture_cube_map</code> extension).
*/
int GL_TEXTURE_CUBE_MAP_NEGATIVE_X = 0x207E;
/**
* Constant for use with <code>glTexImage2D</code> and
* <code>glCompressedTexImage2D</code>
* (<code>OES_texture_cube_map</code> extension).
*/
int GL_TEXTURE_CUBE_MAP_POSITIVE_Y = 0x207F;
/**
* Constant for use with <code>glTexImage2D</code> and
* <code>glCompressedTexImage2D</code>
* (<code>OES_texture_cube_map</code> extension).
*/
int GL_TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x2080;
/**
* Constant for use with <code>glTexImage2D</code> and
* <code>glCompressedTexImage2D</code>
* (<code>OES_texture_cube_map</code> extension).
*/
int GL_TEXTURE_CUBE_MAP_POSITIVE_Z = 0x2081;
/**
* Constant for use with <code>glTexImage2D</code> and
* <code>glCompressedTexImage2D</code>
* (<code>OES_texture_cube_map</code> extension).
*/
int GL_TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x2082;
/**
* Constant for use with <code>glGetIntegerv</code>
* (<code>OES_texture_cube_map</code> extension).
*/
int GL_MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C;
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Bind a named texture to a texturing target.
*
* <p> The <code>OES_texture_cube_map</code> extension allows the
* value <code>GL_TEXTURE_CUBE_MAP</code> to be passed to the
* <code>target</code> parameter.
*
* @param target additionally accepts
* <code>GL_TEXTURE_CUBE_MAP</code>.
*
* @see GL11#glBindTexture(int target, int texture)
*/
void glBindTexture(int target, int texture);
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Specify a two-dimensional compressed texture image.
*
* <p> The <code>OES_texture_cube_map</code> extension allows the
* values
* <code>GL_TEXTURE_CUBE_MAP_{POSITIVE,NEGATIVE}_{X,Y,Z}</code> to
* be passed to the <code>target</code> parameter.
*
* @param target additionally accepts the constants
* <code>GL_TEXTURE_CUBE_MAP_POSITIVE_X</code>,
* <code>GL_TEXTURE_CUBE_MAP_POSITIVE_Y</code>,
* <code>GL_TEXTURE_CUBE_MAP_POSITIVE_Z</code>,
* <code>GL_TEXTURE_CUBE_MAP_NEGATIVE_X</code>,
* <code>GL_TEXTURE_CUBE_MAP_NEGATIVE_Y</code>, and
* <code>GL_TEXTURE_CUBE_MAP_NEGATIVE_Z</code>.
*
* @see GL11#glCompressedTexImage2D
*
* @exception IllegalArgumentException if <code>data</code> is
* <code>null</code>.
* @exception IllegalArgumentException if
* <code>data.remaining()</code> is less than
* <code>imageSize</code>.
*/
void glCompressedTexImage2D(int target, int level,
int internalformat,
int width, int height,
int border, int imageSize,
Buffer data);
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Specify a two-dimensional texture image with pixels from the
* color buffer.
*
* <p> The <code>OES_texture_cube_map</code> extension allows the
* values
* <code>GL_TEXTURE_CUBE_MAP_{POSITIVE,NEGATIVE}_{X,Y,Z}</code> to
* be passed to the <code>target</code> parameter.
*
* @param target additionally accepts the constants
* <code>GL_TEXTURE_CUBE_MAP_POSITIVE_X</code>,
* <code>GL_TEXTURE_CUBE_MAP_POSITIVE_Y</code>,
* <code>GL_TEXTURE_CUBE_MAP_POSITIVE_Z</code>,
* <code>GL_TEXTURE_CUBE_MAP_NEGATIVE_X</code>,
* <code>GL_TEXTURE_CUBE_MAP_NEGATIVE_Y</code>, and
* <code>GL_TEXTURE_CUBE_MAP_NEGATIVE_Z</code>.
*
* @see GL11#glCompressedTexImage2D
*/
void glCopyTexImage2D(int target, int level,
int internalformat,
int x, int y,
int width, int height,
int border);
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Enable server-side GL capabilities.
*
* <p>Cube-map texturing is enabled if <code>cap</code> assumes the
* value <code>GL_TEXTURE_CUBE_MAP</code>.
*
* <p>If enabled, cube-map texturing is performed for the active
* texture unit. See <code>GL.glActiveTexture</code>,
* <code>GL.glTexImage2D</code>, <code>glCompressedTexImage2D</code>,
* and <code>glCopyTexImage2D</code>.
*
* <p>Texture coordinates with be generated if <code>cap</code> is
* equal to <code>GL_TEXTURE_GEN_STR</code>.
*
* @see GL11#glEnable(int cap)
*/
void glEnable(int cap);
/**
* (1.1 + <code>OES_texture_cube_map</code>,
* <code>OES_blend_subtract</code>,
* <code>OES_blend_func_separate</code>, and
* <code>OES_blend_equation_separate</code> extensions) Return the
* value or values of a selected parameter.
*
* <p> The extensions in the GL 1.1 Extension Pack add the following
* constants as possible values for <code>pname</code>:
*
* <ul>
*
* <li><code>GL_BLEND_DST_ALPHA</code> (1.1 +
* <code>OES_blend_func_separate</code> extension)</li>
*
* <p><code>params</code> returns one value, the symbolic constant
* identifying the destination blend function set by
* <code>glBlendFunc</code>, or the destination alpha blend function
* set by <code>glBlendFuncSeparate</code>. See
* <code>glBlendFunc</code> and <code>glBlendFuncSeparate</code>.
*
* <li><code>GL_BLEND_DST_RGB</code> (1.1 +
* <code>OES_blend_func_separate</code> extension)</li>
*
* <p><code>params</code> returns one value, the symbolic constant
* identifying the destination blend function set by
* <code>glBlendFunc</code>, or the destination RGB blend function
* set by <code>glBlendFuncSeparate</code>. See
* <code>glBlendFunc</code> and <code>glBlendFuncSeparate</code>.
*
* <li><code>GL_BLEND_EQUATION</code> (1.1 +
* <code>OES_blend_subtract</code> and
* <code>OES_blend_equation_separate</code> extensions)</li>
*
* <p><code>params</code> returns one value, the symbolic constant
* identifying the blend equation set by
* <code>glBlendEquation</code>, or the RGB blend equation set by
* <code>glBlendEquationSeparate</code>. See
* <code>glBlendEquation</code> and
* <code>glBlendEquationSeparate</code>.
*
* <li><code>GL_BLEND_EQUATION_ALPHA</code> (1.1 +
* <code>OES_blend_equation_separate</code> extension)</li>
*
* <p><code>params</code> returns one value, the symbolic constant
* identifying the blend equation set by
* <code>glBlendEquation</code>, or the alpha blend equation set by
* <code>glBlendEquationSeparate</code>. See
* <code>glBlendEquation</code> and
* <code>glBlendEquationSeparate</code>.
*
* <li><code>GL_BLEND_EQUATION_RGB</code> (1.1 +
* <code>OES_blend_subtract</code> and
* <code>OES_blend_equation_separate</code> extensions)</li>
*
* <p><code>params</code> returns one value, the symbolic constant
* identifying the blend equation set by
* <code>glBlendEquation</code>, or the RGB blend equation set by
* <code>glBlendEquationSeparate</code>. See
* <code>glBlendEquation</code> and
* <code>glBlendEquationSeparate</code>.
*
* <li><code>GL_BLEND_SRC</code> (1.1 only)</li>
*
* <p><code>params</code> returns one value, the symbolic constant
* identifying the source blend function set by <code>glBlendFunc</code>,
* or the source RGB blend function set by
* <code>glBlendFuncSeparate</code>. See <code>glBlendFunc</code> and
* <code>glBlendFuncSeparate</code>.
*
* <li><code>GL_BLEND_SRC_ALPHA</code> (1.1 +
* <code>OES_blend_func_separate</code> extension)</li>
*
* <p><code>params</code> returns one value, the symbolic constant
* identifying the source blend function set by <code>glBlendFunc</code>,
* or the source alpha blend function set by
* <code>glBlendFuncSeparate</code>. See <code>glBlendFunc</code> and
* <code>glBlendFuncSeparate</code>.
*
* <li><code>GL_BLEND_SRC_RGB</code> (1.1 +
* <code>OES_blend_func_separate</code> extension)</li>
*
* <p><code>params</code> returns one value, the symbolic constant
* identifying the source blend function set by <code>glBlendFunc</code>,
* or the source RGB blend function set by
* <code>glBlendFuncSeparate</code>. See <code>glBlendFunc</code> and
* <code>glBlendFuncSeparate</code>.
*
* <li><code>GL_MAX_CUBE_MAP_TEXTURE_SIZE</code> (1.1 +
* <code>OES_texture_cube_map</code> extension)</li>
*
* <p><code>params</code> returns one value, the maximum dimension
* of any face in a cube map texture. The value must be at least
* 64. See <code>glTexImage2D</code>,
* <code>glCompressedTexImage2D</code>, and
* <code>glCopyTexImage2D</code>.
*
* <li><code>GL_MAX_PALETTE_MATRICES_OES</code>
* (<code>OES_matrix_palette</code> extension)</li>
*
* <p><code>params</code> returns the size of the matrix
* palette. The initial value is 32 if the
* <code>OES_extended_matrix_palette</code> extension is present.
*
* <li><code>GL_MAX_VERTEX_UNITS_OES</code>
* (<code>OES_matrix_palette</code> extension)</li>
*
* <p><code>params</code> returns the number of matrices per
* vertex. The initial value is 4 if the
* <code>OES_extended_matrix_palette</code> extension is present.
*
* </ul>
*
* @see GL11#glGetIntegerv(int pname, int[] params, int offset)
*
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>offset</code> is
* less than 0.
* @exception IllegalArgumentException if <code>params.length -
* offset</code> is smaller than the number of values required by
* the parameter.
*/
void glGetIntegerv(int pname, int[] params, int offset);
/**
* (1.1 + <code>OES_texture_cube_map</code>,
* <code>OES_blend_subtract</code>,
* <code>OES_blend_func_separate</code>, and
* <code>OES_blend_equation_separate</code> extensions)
* Integer <code>Buffer</code> version of
* <code>getGetIntegerv</code>.
*
* @see #glGetIntegerv(int pname, int[] params, int offset)
*
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if
* <code>params.remaining()</code> is smaller than the number of
* values required by the parameter.
*/
void glGetIntegerv(int pname, IntBuffer params);
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Specify texture coordinate generation function.
*
* <p>The <code>OES_texture_cube_map</code> extension provides a new
* texture generation scheme for cube map textures. Instead of the
* current texture providing a 2D lookup into a 2D texture image,
* the texture is a set of six 2D images representing the faces of a
* cube. The <code>(s,t,r)</code> texture coordinates are treated as
* a direction vector emanating from the center of a cube. At
* texture generation time, the interpolated per-fragment
* <code>(s,t,r)</code> selects one cube face 2D image based on the
* largest magnitude coordinate (the major axis). A new 2D
* <code>(s,t)</code> is calculated by dividing the two other
* coordinates (the minor axes values) by the major axis value. Then
* the new <code>(s,t)</code> is used to lookup into the selected 2D
* texture image face of the cube map.
*
* <p>Unlike a standard 2D texture that have just one target, a cube
* map texture has six targets, one for each of its six 2D texture
* image cube faces. All these targets must be consistent, complete,
* and have equal width and height.
*
* <p>This extension also provides two new texture coordinate
* generation modes for use in conjunction with cube map
* texturing. The reflection map mode generates texture coordinates
* <code>(s,t,r)</code> matching the vertex?s eyespace reflection
* vector. The reflection map mode is useful for environment mapping
* without the singularity inherent in sphere mapping. The normal
* map mode generates texture coordinates <code>(s,t,r)</code>
* matching the vertex?s transformed eyespace normal. The normal map
* mode is useful for sophisticated cube map texturing-based diffuse
* lighting models.
*
* <p>The intent of the new texgen functionality is that an
* application using cube map texturing can use the new texgen modes
* to automatically generate the reflection or normal vectors used
* to look up into the cube map texture.
*
* <p>The following texgen modes are supported: <code>GL_REFLECTION
* MAP</code> and <code>GL_NORMAL MAP</code>. The
* <code>GL_SPHERE_MAP</code>, <code>GL_OBJECT LINEAR</code>, and
* <code>GL_EYE LINEAR</code> texgen modes are not supported. Texgen
* supports a new coord value <code>GL_STR</code>. This allows the
* application to specify the texgen mode for the appropriate
* coordinates in a single call. Texgen with coord values of
* <code>GL_S</code>, <code>GL_T</code>, <code>GL_R</code> and
* <code>GL_Q</code> are not supported.
*
* <h4>Errors</h4>
*
* <p><code>GL_INVALID_ENUM</code> is generated if
* <code>param</code> or <code>pname</code> is not an accepted
* value, or if <code>pname</code> is
* <code>GL_TEXTURE_GEN_MODE</code> and <code>params</code> is not
* <code>GL_REFLECTION_MAP</code> or <code>GL_NORMAL_MAP</code>.
*
* <h4>Associated Gets</h4>
*
* <p><code>glGetTexGen</code>, <code>glIsEnabled</code> with
* argument <code>GL_TEXTURE_GEN_STR</code>.
*
* @param coord Specifies the texture coordinate or coordinates for
* which a generation function is being specified. At present, only
* <code>GL_STR</code> is accepted.
* @param pname Specifies a single-valued integer texture coordinate
* generation parameter. At present, only
* <code>GL_TEXTURE_GEN_MODE</code> is accepted.
* @param param Specifies the value that <code>pname</code> will be
* set to. If <code>pname</code> is <code>GL_TEXTURE_GEN_MODE</code>, then
* <code>GL_REFLECTION_MAP</code> and <code>GL_NORMAL_MAP</code> are
* accepted.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_texture_cube_map</code> extension.
*/
void glTexGeni(int coord, int pname, int param);
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Floating-point version of <code>glTexGen</code>.
*
* @see #glTexGeni(int coord, int pname, int param)
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_texture_cube_map</code> extension.
*/
void glTexGenf(int coord, int pname, float param);
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Fixed-point version of <code>glTexGen</code>.
*
* @see #glTexGeni(int coord, int pname, int param)
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_texture_cube_map</code> extension.
*/
void glTexGenx(int coord, int pname, int param);
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Floating-point array version of <code>glTexGen</code>.
*
* @see #glTexGeni(int coord, int pname, int param)
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_texture_cube_map</code> extension.
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>offset</code> is
* less than 0.
* @exception IllegalArgumentException if <code>params.length -
* offset</code> is smaller than the number of values required by
* the parameter.
*/
void glTexGenfv(int coord, int pname, float[] params, int offset);
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Floating-point <code>Buffer</code> version of
* <code>glTexGen</code>.
*
* @see #glTexGeni(int coord, int pname, int param)
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_texture_cube_map</code> extension.
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if
* <code>params.remaining()</code> is smaller than the number of
* values required by the parameter.
*/
void glTexGenfv(int coord, int pname, FloatBuffer params);
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Integer array version of <code>glTexGen</code>.
*
* @see #glTexGeni(int coord, int pname, int param)
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_texture_cube_map</code> extension.
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>offset</code> is
* less than 0.
* @exception IllegalArgumentException if <code>params.length -
* offset</code> is smaller than the number of values required by
* the parameter.
*/
void glTexGeniv(int coord, int pname, int[] params, int offset);
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Integer <code>Buffer</code> version of <code>glTexGen</code>.
*
* @see #glTexGeni(int coord, int pname, int param)
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_texture_cube_map</code> extension.
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if
* <code>params.remaining()</code> is smaller than the number of
* values required by the parameter.
*/
void glTexGeniv(int coord, int pname, IntBuffer params);
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Fixed-point array version of <code>glTexGen</code>.
*
* @see #glTexGeni(int coord, int pname, int param)
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_texture_cube_map</code> extension.
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>offset</code> is
* less than 0.
* @exception IllegalArgumentException if <code>params.length -
* offset</code> is smaller than the number of values required by
* the parameter.
*/
void glTexGenxv(int coord, int pname, int[] params, int offset);
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Fixed-point <code>Buffer</code> version of <code>glTexGen</code>.
*
* @see #glTexGeni(int coord, int pname, int param)
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_texture_cube_map</code> extension.
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if
* <code>params.remaining()</code> is smaller than the number of
* values required by the parameter.
*/
void glTexGenxv(int coord, int pname, IntBuffer params);
// GetTexGen
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Get texture coordinate generation parameters.
*
* This method queries texture coordinate generation parameters set
* using <code>glTexGen</code>.
*
* <h4>Errors</h4>
*
* <p><code>GL_INVALID_ENUM</code> is generated if
* <code>param</code> or <code>pname</code> is not an accepted
* value, or if <code>pname</code> is
* <code>GL_TEXTURE_GEN_MODE</code> and <code>params</code> is not
* <code>GL_REFLECTION_MAP</code> or <code>GL_NORMAL_MAP</code>.
*
* @param coord Specifies the texture coordinate or coordinates for
* which a generation parameter is being requested. At present, only
* <code>GL_STR</code> is accepted.
* @param pname Specifies a single-valued integer texture coordinate
* generation parameter. At present, only
* <code>GL_TEXTURE_GEN_MODE</code> is accepted.
* @param params Returns the value or values of the specified
* parameter.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_texture_cube_map</code> extension.
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>offset</code> is
* less than 0.
* @exception IllegalArgumentException if <code>params.length -
* offset</code> is smaller than the number of values required by
* the parameter.
*/
void glGetTexGeniv(int coord, int pname, int[] params, int offset);
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Integer <code>Buffer</code> version of <code>glGetTexGen</code>.
*
* @see #glGetTexGeniv(int coord, int pname, int[] params, int offset)
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_texture_cube_map</code> extension.
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if
* <code>params.remaining()</code> is smaller than the number of
* values required by the parameter.
*/
void glGetTexGeniv(int coord, int pname, IntBuffer params);
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Floating-point array version of <code>glGetTexGen</code>.
*
* @see #glGetTexGeniv(int coord, int pname, int[] params, int offset)
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_texture_cube_map</code> extension.
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>offset</code> is
* less than 0.
* @exception IllegalArgumentException if <code>params.length -
* offset</code> is smaller than the number of values required by
* the parameter.
*/
void glGetTexGenfv(int coord, int pname, float[] params, int offset);
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Fixed-point array version of <code>glGetTexGen</code>.
*
* @see #glGetTexGeniv(int coord, int pname, int[] params, int offset)
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_texture_cube_map</code> extension.
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>offset</code> is
* less than 0.
* @exception IllegalArgumentException if <code>params.length -
* offset</code> is smaller than the number of values required by
* the parameter.
*/
void glGetTexGenxv(int coord, int pname, int[] params, int offset);
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Fixed-point <code>Buffer</code> version of <code>glGetTexGen</code>.
*
* @see #glGetTexGeniv(int coord, int pname, int[] params, int offset)
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_texture_cube_map</code> extension.
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if
* <code>params.remaining()</code> is smaller than the number of
* values required by the parameter.
*/
void glGetTexGenxv(int coord, int pname, IntBuffer params);
/**
* (1.1 + <code>OES_texture_cube_map</code> extension)
* Floating-point <code>Buffer</code> version of <code>glGetTexGen</code>.
*
* @see #glGetTexGeniv(int coord, int pname, int[] params, int offset)
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_texture_cube_map</code> extension.
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if
* <code>params.remaining()</code> is smaller than the number of
* values required by the parameter.
*/
void glGetTexGenfv(int coord, int pname, FloatBuffer params);
// /**
// * Flag indicating the presence of the "blend subtract" extension.
// * <code>OES_blend_subtract</code> is an optional profile extension
// * in OpenGL ES 1.1, and is part of the OpenGL ES 1.1 Extension
// * Pack.
// *
// * <p> The value of this flag does not imply the presence of the
// * extension in the runtime enviroment.
// */
// int GL_OES_blend_subtract = 1;
/**
* Constant for use with <code>glBlendEquation</code>
* (<code>OES_blend_subtract</code> extension).
*/
int GL_FUNC_ADD = 0x8006;
/**
* Constant for use with <code>glBlendEquation</code>
* (<code>OES_blend_subtract</code> extension).
*/
int GL_FUNC_SUBTRACT = 0x800A;
/**
* Constant for use with <code>glBlendEquation</code>
* (<code>OES_blend_subtract</code> extension).
*/
int GL_FUNC_REVERSE_SUBTRACT = 0x800B;
/**
* (1.1 + <code>OES_blend_subtract</code> extension) Specify the
* blending equation.
*
* <p>Blending is controlled by <code>glBlendEquation</code>.
*
* <p><code>glBlendEquation</code> <code>mode</code>
* <code>GL_FUNC_ADD</code> defines the blend equation as
*
* <pre>C = Cs * S + Cd * D,</pre>
*
* where <code>Cs</code> and <code>Cd</code> are the source and
* destination colors, <code>S</code> and <code>D</code> are the
* quadruplets of weighting factors determined by the blend
* functions <code>glBlendFunc</code> and
* <code>glBlendFuncSeparate</code>, and C is the new color
* resulting from blending.
*
* <p>If <code>mode</code> is <code>GL_FUNC_SUBTRACT</code>, the
* blending equation is defined as
*
* <pre>C = Cs * S - Cd * D.</pre>
*
* <p>If <code>mode</code> is <code>GL_FUNC_REVERSE_SUBTRACT</code>,
* the blend equation is defined as
*
* <pre>C = Cd * D - Cs * S.</pre>
*
* <h4>Errors</h4>
*
* <p><code>GL_INVALID_ENUM</code> is generated if <code>mode</code>
* is not an accepted value.
*
* <h4>Associated Gets</h4>
*
* <p><code>glGetIntegerv</code> with argument
* <code>GL_BLEND_EQUATION</code> returns the blend equation.
*
* @param mode Specifies the blend
* equation. <code>GL_FUNC_ADD</code>,
* <code>GL_FUNC_SUBTRACT</code>, and
* <code>GL_FUNC_REVERSE_SUBTRACT</code> are accepted.
*
* @see GL11#glBlendFunc
* @see #glBlendFuncSeparate
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_blend_subtract</code> extension.
*/
void glBlendEquation(int mode);
// /**
// * Flag indicating the presence of the "blend func separate"
// * extension. <code>OES_blend_func_separate</code> is an optional
// * profile extension in OpenGL ES 1.1, and is part of the OpenGL ES
// * 1.1 Extension Pack.
// *
// * <p> The value of this flag does not imply the presence
// * of the extension in the runtime enviroment.
// */
// int GL_OES_blend_func_separate = 1;
/**
* Constant for use with <code>glBlendFuncSeparate</code>
* (<code>OES_blend_func_separate</code> extension).
*/
int GL_BLEND_DST_RGB = 0x80C8;
/**
* Constant for use with <code>glBlendFuncSeparate</code>
* (<code>OES_blend_func_separate</code> extension).
*/
int GL_BLEND_SRC_RGB = 0x80C9;
/**
* Constant for use with <code>glBlendFuncSeparate</code>
* (<code>OES_blend_func_separate</code> extension).
*/
int GL_BLEND_DST_ALPHA = 0x80CA;
/**
* Constant for use with <code>glBlendFuncSeparate</code>
* (<code>OES_blend_func_separate</code> extension).
*/
int GL_BLEND_SRC_ALPHA = 0x80CB;
/**
* (1.1 + <code>GL_OES_blend_func_separate</code> extension)
* Apply different blend factors to RGB and alpha.
*
* <p><code>glBlendFuncSeparate</code> allows different blend factors to be
* applied to RGB and alpha. The blend factors are those defined for
* <code>glBlendFunc</code>.
*
* <h4>Errors</h4>
*
* <p><code>GL_INVALID_ENUM</code> is generated if
* <code>srcRGB</code>, <code>dstRGB</code>, <code>srcAlpha</code>,
* or <code>dstAlpha</code> is not an accepted value.
*
* <h4>Associated Gets</h4>
*
* <p><code>glGetIntegerv</code> with argument
* <code>GL_BLEND_SRC_RGB</code> or <code>GL_BLEND_SRC</code>
* returns the source RGB blend function.
*
* <p><code>glGetIntegerv</code> with argument
* <code>GL_BLEND_DST_RGB</code> or <code>GL_BLEND_DST</code>
* returns the destination RGB blend function.
*
* <p><code>glGetIntegerv</code> with argument
* <code>GL_BLEND_SRC_ALPHA</code> returns the source alpha blend
* function.
*
* <p><code>glGetIntegerv</code> with argument
* <code>GL_BLEND_DST_ALPHA</code> returns the destination alpha
* blend function.
*
* @param srcRGB Source RGB blend function. Must be one of the blend
* functions accepted by <code>glBlendFunc</code>.
* @param dstRGB Destination RGB blend function. Must be one of the blend
* functions accepted by <code>glBlendFunc</code>.
* @param srcAlpha Source alpha blend function. Must be one of the
* blend functions accepted by <code>glBlendFunc</code>.
* @param dstAlpha Destination alpha blend function. Must be one of
* the blend functions accepted by <code>glBlendFunc</code>.
*
* @see GL11#glBlendFunc
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_blend_func_separate</code> extension.
*/
void glBlendFuncSeparate(int srcRGB, int dstRGB,
int srcAlpha, int dstAlpha);
// /**
// * Flag indicating the presence of the "blend equation separate"
// * extension. <code>OES_blend_equation_separate</code> is an
// * optional profile extension in OpenGL ES 1.1, and is part of the
// * OpenGL ES 1.1 Extension Pack.
// *
// * <p> The value of this flag does not imply the presence
// * of the extension in the runtime enviroment.
// */
// int GL_OES_blend_equation_separate = 1;
/**
* Constant for use with <code>glBlendEquationSeparate</code> and
* <code>glGetInteger</code>
* (<code>OES_blend_equation_separate</code> extension).
*/
int GL_BLEND_EQUATION = 0x8009;
/**
* Constant for use with <code>glBlendEquationSeparate</code> and
* <code>glGetInteger</code>
* (<code>OES_blend_equation_separate</code> extension). Synonym
* for <code>GL_BLEND_EQUATION</code>.
*/
int GL_BLEND_EQUATION_RGB = 0x8009;
/**
* Constant for use with <code>glBlendEquationSeparate</code> and
* <code>glGetInteger</code>
* (<code>OES_blend_equation_separate</code> extension).
*/
int GL_BLEND_EQUATION_ALPHA = 0x883D;
/**
* (1.1 + <code>OES_blend_equation_separate</code> extension)
* Provide different blend equations for RGB and alpha.
*
* <p><code>glBlendEquationSeparate</code> allows different blend
* equations to be provideded for RGB and alpha. The blend equations
* are those defined for <code>glBlendEquation</code>.
*
* <h4>Errors</h4>
*
* <p><code>GL_INVALID_ENUM</code> is generated if
* <code>modeRGB</code>, or <code>modeAlpha</code> is not an
* accepted value.
*
* <h4>Associated Gets</h4>
*
* <p><code>glGetIntegerv</code> with argument
* <code>GL_BLEND_EQUATION_RGB</code> or
* <code>GL_BLEND_EQUATION</code> returns the RGB blend equation.
*
* <p><code>glGetIntegerv</code> with argument
* <code>GL_BLEND_EQUATION_ALPHA</code> returns the alpha blend
* equation.
*
* @param modeRGB RGB blend equation. Must be one of the blend
* equations accepted by <code>glBlendEquation</code>.
* @param modeAlpha Alpha blend equation. Must be one of the blend
* equations accepted by <code>glBlendEquation</code>.
*
* @see #glBlendEquation
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_blend_equation_separate</code> extension.
*/
void glBlendEquationSeparate(int modeRGB, int modeAlpha);
// /**
// * Flag indicating the presence of the "stencil wrap" extension.
// * <code>OES_stencil_wrap</code> is an optional profile extension in
// * OpenGL ES 1.1, and is part of the OpenGL ES 1.1 Extension Pack.
// *
// * <p> The value of this flag does not imply the presence of the
// * extension in the runtime enviroment.
// */
// int GL_OES_stencil_wrap = 1;
/**
* Constant for use with <code>glStencilOp</code>
* (<code>OES_stencil_wrap</code> extension).
*/
int GL_INCR_WRAP = 0x8507;
/**
* Constant for use with <code>glStencilOp</code>
* (<code>OES_stencil_wrap</code> extension).
*/
int GL_DECR_WRAP = 0x8508;
/**
* (<code>OES_stencil_wrap</code> extension)
* Set stencil test actions.
*
* <p> Two additional actions are defined by the
* <code>OES_stencil_wrap</code> extension:
*
* <ul>
*
* <li>(<code>OES_stencil_wrap</code> extension)
* <code>GL_DECR_WRAP</code></li>
*
* <p>Decrements the current stencil buffer value, wrapping around
* to the maximum representable unsigned value if less than 0.
*
* <li>(<code>OES_stencil_wrap</code> extension)
* <code>GL_INCR</code></li>
*
* <p>Increments the current stencil buffer value, wrapping around
* to 0 if greater than the maximum representable unsigned value.
*
* </ul>
*
* @see GL11#glStencilOp(int fail, int zfail, int zpass)
*/
void glStencilOp(int fail, int zfail, int zpass);
// /**
// * Flag indicating the presence of the "extended matrix palette"
// * extension. <code>OES_extended_matrix_palette</code> is an
// * optional profile extension in OpenGL ES 1.1, and is part of the
// * OpenGL ES 1.1 Extension Pack.
// *
// * <p> The value of this flag does not imply the presence of the
// * extension in the runtime enviroment.
// */
// int GL_OES_extended_matrix_palette = 1;
// /**
// * Flag indicating the presence of the "framebuffer object"
// * extension. <code>OES_framebuffer_object</code> is an optional
// * profile extension in OpenGL ES 1.1, and is part of the OpenGL ES
// * 1.1 Extension Pack.
// *
// * <p> The value of this flag does not imply the presence of the
// * extension in the runtime enviroment.
// */
// int GL_OES_framebuffer_object = 1;
/**
* Constant accepted by the <code>target</code> parameter of
* <code>glBindFramebufferOES</code>,
* <code>glCheckFramebufferStatusOES</code>,
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_FRAMEBUFFER_OES = 0x8D40;
/**
* Constant accepted by the <code>target</code> parameter of
* <code>glBindRenderbufferOES</code>,
* <code>glRenderbufferStorageOES</code>, and
* <code>glGetRenderbufferParameterivOES</code>, and returned by
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_RENDERBUFFER_OES = 0x8D41;
/**
* Constant accepted by the <code>pname</code> parameter of
* <code>glGetRenderbufferParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_RENDERBUFFER_WIDTH_OES = 0x8D42;
/**
* Constant accepted by the <code>pname</code> parameter of
* <code>glGetRenderbufferParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_RENDERBUFFER_HEIGHT_OES = 0x8D43;
/**
* Constant accepted by the <code>pname</code> parameter of
* <code>glGetRenderbufferParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_RENDERBUFFER_INTERNAL_FORMAT_OES = 0x8D44;
/**
* Constant accepted by the <code>pname</code> parameter of
* <code>glGetRenderbufferParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_RENDERBUFFER_RED_SIZE_OES = 0x8D50;
/**
* Constant accepted by the <code>pname</code> parameter of
* <code>glGetRenderbufferParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_RENDERBUFFER_GREEN_SIZE_OES = 0x8D51;
/**
* Constant accepted by the <code>pname</code> parameter of
* <code>glGetRenderbufferParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_RENDERBUFFER_BLUE_SIZE_OES = 0x8D52;
/**
* Constant accepted by the <code>pname</code> parameter of
* <code>glGetRenderbufferParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_RENDERBUFFER_ALPHA_SIZE_OES = 0x8D53;
/**
* Constant accepted by the <code>pname</code> parameter of
* <code>glGetRenderbufferParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_RENDERBUFFER_DEPTH_SIZE_OES = 0x8D54;
/**
* Constant accepted by the <code>pname</code> parameter of
* <code>glGetRenderbufferParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_RENDERBUFFER_STENCIL_SIZE_OES = 0x8D55;
/**
* Constant accepted by the <code>pname</code> parameter of
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_OES = 0x8CD0;
/**
* Constant accepted by the <code>pname</code> parameter of
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_OES = 0x8CD1;
/**
* Constant accepted by the <code>pname</code> parameter of
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_OES = 0x8CD2;
/**
* Constant accepted by the <code>pname</code> parameter of
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_OES = 0x8CD3;
/**
* Constant accepted by the <code>attachment</code> parameter of
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_COLOR_ATTACHMENT0_OES = 0x8CE0;
/**
* Constant accepted by the <code>attachment</code> parameter of
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_COLOR_ATTACHMENT1_OES = 0x8CE1;
/**
* Constant accepted by the <code>attachment</code> parameter of
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_COLOR_ATTACHMENT2_OES = 0x8CE2;
/**
* Constant accepted by the <code>attachment</code> parameter of
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_COLOR_ATTACHMENT3_OES = 0x8CE3;
/**
* Constant accepted by the <code>attachment</code> parameter of
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_COLOR_ATTACHMENT4_OES = 0x8CE4;
/**
* Constant accepted by the <code>attachment</code> parameter of
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_COLOR_ATTACHMENT5_OES = 0x8CE5;
/**
* Constant accepted by the <code>attachment</code> parameter of
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_COLOR_ATTACHMENT6_OES = 0x8CE6;
/**
* Constant accepted by the <code>attachment</code> parameter of
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_COLOR_ATTACHMENT7_OES = 0x8CE7;
/**
* Constant accepted by the <code>attachment</code> parameter of
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_COLOR_ATTACHMENT8_OES = 0x8CE8;
/**
* Constant accepted by the <code>attachment</code> parameter of
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_COLOR_ATTACHMENT9_OES = 0x8CE9;
/**
* Constant accepted by the <code>attachment</code> parameter of
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_COLOR_ATTACHMENT10_OES = 0x8CEA;
/**
* Constant accepted by the <code>attachment</code> parameter of
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_COLOR_ATTACHMENT11_OES = 0x8CEB;
/**
* Constant accepted by the <code>attachment</code> parameter of
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_COLOR_ATTACHMENT12_OES = 0x8CEC;
/**
* Constant accepted by the <code>attachment</code> parameter of
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_COLOR_ATTACHMENT13_OES = 0x8CED;
/**
* Constant accepted by the <code>attachment</code> parameter of
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_COLOR_ATTACHMENT14_OES = 0x8CEE;
/**
* Constant accepted by the <code>attachment</code> parameter of
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_COLOR_ATTACHMENT15_OES = 0x8CEF;
/**
* Constant accepted by the <code>attachment</code> parameter of
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_DEPTH_ATTACHMENT_OES = 0x8D00;
/**
* Constant accepted by the <code>attachment</code> parameter of
* <code>glFramebufferTexture2DOES</code>,
* <code>glFramebufferRenderbufferOES</code>, and
* <code>glGetFramebufferAttachmentParameterivOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_STENCIL_ATTACHMENT_OES = 0x8D20;
/**
* Constant returned by <code>glCheckFramebufferStatusOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_FRAMEBUFFER_COMPLETE_OES = 0x8CD5;
/**
* Constant returned by <code>glCheckFramebufferStatusOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_OES = 0x8CD6;
/**
* Constant returned by <code>glCheckFramebufferStatusOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_OES = 0x8CD7;
/**
* Constant returned by <code>glCheckFramebufferStatusOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_OES = 0x8CD9;
/**
* Constant returned by <code>glCheckFramebufferStatusOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_FRAMEBUFFER_INCOMPLETE_FORMATS_OES = 0x8CDA;
/**
* Constant returned by <code>glCheckFramebufferStatusOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_OES = 0x8CDB;
/**
* Constant returned by <code>glCheckFramebufferStatusOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_OES = 0x8CDC;
/**
* Constant returned by <code>glCheckFramebufferStatusOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_FRAMEBUFFER_UNSUPPORTED_OES = 0x8CDD;
/**
* Constant accepted by <code>glGetIntegerv</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_FRAMEBUFFER_BINDING_OES = 0x8CA6;
/**
* Constant accepted by <code>glGetIntegerv</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_RENDERBUFFER_BINDING_OES = 0x8CA7;
/**
* Constant accepted by <code>glGetIntegerv</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_MAX_COLOR_ATTACHMENTS_OES = 0x8CDF;
/**
* Constant accepted by <code>glGetIntegerv</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_MAX_RENDERBUFFER_SIZE_OES = 0x84E8;
/**
* Constant returned by <code>glGetError</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_INVALID_FRAMEBUFFER_OPERATION_OES = 0x0506;
/**
* Constant accepted by the <code>internalformat</code> parameter of
* <code>glRenderbufferStorageOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_RGB565_OES = 0x8D62;
/**
* Constant accepted by the <code>internalformat</code> parameter of
* <code>glRenderbufferStorageOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_RGBA4 = 0x8056;
/**
* Constant accepted by the <code>internalformat</code> parameter of
* <code>glRenderbufferStorageOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_RGB5_A1 = 0x8057;
/**
* Constant accepted by the <code>internalformat</code> parameter of
* <code>glRenderbufferStorageOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_DEPTH_COMPONENT16 = 0x81A5;
/**
* Constant optionally accepted by the <code>internalformat</code>
* parameter of <code>glRenderbufferStorageOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_RGBA8 = 0x8058;
/**
* Constant optionally accepted by the <code>internalformat</code>
* parameter of <code>glRenderbufferStorageOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_RGB8 = 0x8051;
/**
* Constant optionally accepted by the <code>internalformat</code>
* parameter of <code>glRenderbufferStorageOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_DEPTH_COMPONENT24 = 0x81A6;
/**
* Constant optionally accepted by the <code>internalformat</code>
* parameter of <code>glRenderbufferStorageOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_DEPTH_COMPONENT32 = 0x81A7;
/**
* Constant optionally accepted by the <code>internalformat</code>
* parameter of <code>glRenderbufferStorageOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_STENCIL_INDEX1_OES = 0x8D46;
/**
* Constant optionally accepted by the <code>internalformat</code>
* parameter of <code>glRenderbufferStorageOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_STENCIL_INDEX4_OES = 0x8D47;
/**
* Constant optionally accepted by the <code>internalformat</code>
* parameter of <code>glRenderbufferStorageOES</code>
* (<code>OES_framebuffer_object</code> extension).
*/
int GL_STENCIL_INDEX8_OES = 0x8D48;
/*
int GL_STENCIL_INDEX16_OES = 0x8D49;
*/
/**
* Constant (<code>OES_framebuffer_object</code> extension).
*/
int GL_STENCIL_INDEX = 0x1901;
/**
* Constant (<code>OES_framebuffer_object</code> extension).
*/
int GL_DEPTH_COMPONENT = 0x1902;
/**
* (<code>OES_framebuffer_object</code> extension) Determine whether a
* token represents a renderbuffer.
*
* <p> Returns <code>true</code> if <code>renderbuffer</code> is the
* name of a renderbuffer object. If <code>renderbuffer</code> is
* zero, or if <code>renderbuffer</code> is a non-zero value that is
* not the name of a renderbuffer object,
* <code>glIsRenderbufferOES</code> returns <code>false</code>.
*
* @param renderbuffer an integer.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
*/
boolean glIsRenderbufferOES(int renderbuffer);
/**
* (<code>OES_framebuffer_object</code> extension)
* Bind a renderbuffer.
*
* <p> A renderbuffer is a data storage object containing a single
* image of a renderable internal format. GL provides the methods
* described below to allocate and delete a renderbuffer's image,
* and to attach a renderbuffer's image to a framebuffer object.
*
* <p> The name space for renderbuffer objects is the unsigned
* integers, with zero reserved for the GL. A renderbuffer object
* is created by binding an unused name to
* <code>GL_RENDERBUFFER_OES</code>. The binding is effected by
* setting <code>target</code> to <code>GL_RENDERBUFFER_OES</code>
* and <code>renderbuffer</code> set to the unused name. If
* <code>renderbuffer</code> is not zero, then the resulting
* renderbuffer object is a new state vector, initialized with a
* zero-sized memory buffer, and comprising the state values listed
* in Table 8.nnn of the <code>EXT_framebuffer_object</code>
* specification. Any previous binding to <code>target</code> is
* broken.
*
* <p> <code>glBindRenderbufferOES</code> may also be used to bind an
* existing renderbuffer object. If the bind is successful, no
* change is made to the state of the newly bound renderbuffer
* object, and any previous binding to <code>target</code> is
* broken.
*
* <p> While a renderbuffer object is bound, GL operations on the target
* to which it is bound affect the bound renderbuffer object, and
* queries of the target to which a renderbuffer object is bound
* return state from the bound object.
*
* <p> The name zero is reserved. A renderbuffer object cannot be
* created with the name zero. If <code>renderbuffer</code> is
* zero, then any previous binding to <code>target</code> is broken
* and the <code>target</code> binding is restored to the initial
* state.
*
* <p> In the initial state, the reserved name zero is bound to
* <code>GL_RENDERBUFFER_OES</code>. There is no renderbuffer
* object corresponding to the name zero, so client attempts to
* modify or query renderbuffer state for the target
* <code>GL_RENDERBUFFER_OES</code> while zero is bound will
* generate GL errors.
*
* <p> Using <code>glGetIntegerv</code>, the current
* <code>GL_RENDERBUFFER_OES</code> binding can be queried as
* <code>GL_RENDERBUFFER_BINDING_OES</code>.
*
* @param target the value <code>GL_RENDERBUFFER_OES</code>.
* @param renderbuffer Specifies the name of a renderbuffer.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
*/
void glBindRenderbufferOES(int target, int renderbuffer);
/**
* (<code>OES_framebuffer_object</code> extension)
* Delete a renderbuffer.
*
* <p> Renderbuffer objects are deleted by calling
* glDeleteRenderbuffersOES where <code>renderbuffers</code>
* contains <code>n</code> names of renderbuffer objects to be
* deleted. After a renderbuffer object is deleted, it has no
* contents, and its name is again unused. If a renderbuffer that
* is currently bound to <code>GL_RENDERBUFFER_OES</code> is
* deleted, it is as though <code>glBindRenderbufferOES</code> had
* been executed with the <code>target</code>
* <code>GL_RENDERBUFFER_OES</code> and <code>name</code> of zero.
* Additionally, special care must be taken when deleting a
* renderbuffer if the image of the renderbuffer is attached to a
* framebuffer object. Unused names in
* <code>renderbuffers</code> are silently ignored, as is the value
* zero.
*
* @param n the number of renderbuffers to be deleted.
* @param renderbuffers an array of <code>n</code> renderbuffer names.
* @param offset the starting offset within the
* <code>renderbuffers</code> array.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
* @exception IllegalArgumentException if <code>renderbuffers</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>offset</code> is
* less than 0.
* @exception IllegalArgumentException if <code>renderbuffers.length
* - offset</code> is less than <code>n</code>.
*/
void glDeleteRenderbuffersOES(int n, int[] renderbuffers, int offset);
/**
* (<code>OES_framebuffer_object</code> extension)
* Integer <code>Buffer</code> version of
* <code>glDeleteRenderbuffersOES</code>.
*
* @see #glDeleteRenderbuffersOES(int n, int[] renderbuffers, int offset)
*
* @param n the number of renderbuffers to be deleted.
* @param renderbuffers an <code>IntBuffer</code> containing
* renderbuffer names.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
* @exception IllegalArgumentException if <code>renderbuffers</code> is
* <code>null</code>.
* @exception IllegalArgumentException if
* <code>renderbuffers.limit() - renderbuffers.position()</code> is
* less than <code>n</code>.
*/
void glDeleteRenderbuffersOES(int n, IntBuffer renderbuffers);
/**
* (<code>OES_framebuffer_object</code> extension)
* Generate renderbuffer names.
*
* <p> The command <code>glGenRenderbuffersOES</code> returns
* <code>n</code> previously unused renderbuffer object names in
* <code>renderbuffers</code>. These names are marked as used, for
* the purposes of <code>glGenRenderbuffersOES</code> only, but they
* acquire renderbuffer state only when they are first bound, just
* as if they were unused.
*
* @param n the number of renderbuffer names to be generated.
* @param renderbuffers an array to be filled in with <code>n</code>
* renderbuffer names.
* @param offset the starting offset within the
* <code>renderbuffers</code> array.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
* @exception IllegalArgumentException if <code>renderbuffers</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>offset</code> is
* less than 0.
* @exception IllegalArgumentException if <code>renderbuffers.length
* - offset</code> is less than <code>n</code>.
*/
void glGenRenderbuffersOES(int n, int[] renderbuffers, int offset);
/**
* (<code>OES_framebuffer_object</code> extension)
* Integer <code>Buffer</code> version of
* <code>glGenRenderbuffersOES</code>.
*
* @see #glGenRenderbuffersOES(int n, int[] renderbuffers, int offset)
*
* @param n the number of renderbuffer names to be generated.
* @param renderbuffers an <code>IntBuffer</code> to be filled in
* with <code>n</code> renderbuffer names.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
* @exception IllegalArgumentException if <code>renderbuffers</code> is
* <code>null</code>.
* @exception IllegalArgumentException if
* <code>renderbuffers.limit() - renderbuffers.position()</code> is
* less than <code>n</code>.
*/
void glGenRenderbuffersOES(int n, IntBuffer renderbuffers);
/**
* (<code>OES_framebuffer_object</code> extension)
* Establish the layout of a renderbuffer object's image.
*
* <p> The command <code>glRenderbufferStorageOES</code> establishes
* the data storage, format, and dimensions of a renderbuffer
* object's image. <code>target</code> must be
* <code>GL_RENDERBUFFER_OES</code>. <code>internalformat</code>
* must be one of the sized internal formats from the following
* tables which has a base internal format of <code>GL_RGB</code>,
* <code>GL_RGBA</code>, <code>GL_DEPTH_COMPONENT</code>, or
* <code>GL_STENCIL_INDEX</code>.
*
* <p> The following formats are required:
*
* <pre>
* Sized Base Size in
* Internal Format Internal format Bits
* --------------- --------------- ----
* RGB565_OES RGB 16
* RGBA4 RGBA 16
* RGB5_A1 RGBA 16
* DEPTH_COMPONENT_16 DEPTH_COMPONENT 16
* </pre>
*
* <p> The following formats are optional:
*
* <pre>
* Sized Base Size in
* Internal Format Internal format Bits
* --------------- --------------- ----
* RGBA8 RGBA 32
* RGB8 RGB 24
* DEPTH_COMPONENT_24 DEPTH_COMPONENT 24
* DEPTH_COMPONENT_32 DEPTH_COMPONENT 32
* STENCIL_INDEX1_OES STENCIL_INDEX 1
* STENCIL_INDEX4_OES STENCIL_INDEX 4
* STENCIL_INDEX8_OES STENCIL_INDEX 8
* </pre>
*
* <p> The optional formats are described by the
* <code>OES_rgb8_rgba8</code>, <code>OES_depth24</code>,
* <code>OES_depth32</code>, <code>OES_stencil1</code>,
* <code>OES_stencil4</code>, and <code>OES_stencil8</code>
* extensions.
*
* <p> If <code>glRenderbufferStorageOES</code> is called with an
* <code>internalformat</code> value that is not supported by the
* OpenGL ES implementation, a <code>GL_INVALID_ENUM</code> error
* will be generated.
*
* <p> <code>width</code> and
* <code>height</code> are the dimensions in pixels of the
* renderbuffer. If either <code>width</code> or
* <code>height</code> is greater than
* <code>GL_MAX_RENDERBUFFER_SIZE_OES</code>, then the error
* <code>GL_INVALID_VALUE</code> is generated. If the GL is unable
* to create a data store of the requested size, the error
* <code>GL_OUT_OF_MEMORY</code> is
* generated. <code>glRenderbufferStorageOES</code> deletes any
* existing data store for the renderbuffer and the contents of the
* data store after calling <code>glRenderbufferStorageOES</code>
* are undefined.
*
* @param target the value <code>GL_RENDERBUFFER_OES</code>.
* @param internalformat one of <code>GL_RGB</code>,
* <code>GL_RGBA</code>, <code>GL_DEPTH_COMPONENT</code>,
* <code>GL_STENCIL_INDEX</code>, or an internal format that has one
* of those as a base format.
* @param width the width of the image.
* @param height the height of the image.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
*/
void glRenderbufferStorageOES(int target, int internalformat,
int width, int height);
/**
* (<code>OES_framebuffer_object</code> extension)
* Query a renderbuffer parameter.
*
* <p> <code>target</code> must be <code>GL_RENDERBUFFER_OES</code>.
* <code>pname</code> must be one of the symbolic values in the
* table below.
*
* <p> If the renderbuffer currently bound to <code>target</code> is
* zero, then <code>GL_INVALID_OPERATION</code> is generated.
*
* <p> Upon successful return from
* <code>glGetRenderbufferParameterivOES</code>, if
* <code>pname</code> is <code>GL_RENDERBUFFER_WIDTH_OES</code>,
* <code>GL_RENDERBUFFER_HEIGHT_OES</code>, or
* <code>GL_RENDERBUFFER_INTERNAL_FORMAT_OES</code>, then
* <code>params</code> will contain the width in pixels, height in
* pixels, or internal format, respectively, of the image of the
* renderbuffer currently bound to <code>target</code>.
*
* <p> Upon successful return from
* <code>glGetRenderbufferParameterivOES</code>, if
* <code>pname</code> is <code>GL_RENDERBUFFER_RED_SIZE_OES</code>,
* <code>GL_RENDERBUFFER_GREEN_SIZE_OES</code>,
* <code>GL_RENDERBUFFER_BLUE_SIZE_OES</code>,
* <code>GL_RENDERBUFFER_ALPHA_SIZE_OES</code>,
* <code>GK_RENDERBUFFER_DEPTH_SIZE_OES</code>, or
* <code>GL_RENDERBUFFER_STENCIL_SIZE_OES</code>, then
* <code>params</code> will contain the actual resolutions, (not the
* resolutions specified when the image array was defined), for the
* red, green, blue, alpha depth, or stencil components,
* respectively, of the image of the renderbuffer currently bound to
* <code>target</code>.
*
* <p> Otherwise, <code>GL_INVALID_ENUM</code> is generated.
*
* <p> The values in the first column of the table below should be
* prefixed with <code>GL_RENDERBUFFER_</code> and suffixed with
* <code>OES</code>. The get command for all values is
* <code>glGetRenderbufferParameterivOES</code>. All take on
* positive integral values.
*
* <pre>
* Get Initial
* Value Value Description
* --------------- ------- ----------------------
* WIDTH 0 width of renderbuffer
*
* HEIGHT 0 height of renderbuffer
*
* INTERNAL_FORMAT GL_RGBA internal format
* of renderbuffer
*
* RED_SIZE 0 size in bits of
* renderbuffer image's
* red component
*
* GREEN_SIZE 0 size in bits of
* renderbuffer image's
* green component
*
* BLUE_SIZE 0 size in bits of
* renderbuffer image's
* blue component
*
* ALPHA_SIZE 0 size in bits of
* renderbuffer image's
* alpha component
*
* DEPTH_SIZE 0 size in bits of
* renderbuffer image's
* depth component
*
* STENCIL_SIZE 0 size in bits of
* renderbuffer image's
* stencil component
* </pre>
*
* @param target the value <code>GL_RENDERBUFFER_OES</code>.
* @param pname one of <code>GL_RENDERBUFFER_WIDTH_OES</code>,
* <code>GL_RENDERBUFFER_HEIGHT_OES</code>,
* <code>GL_RENDERBUFFER_INTERNAL_FORMAT_OES</code>,
* <code>GL_RENDERBUFFER_RED_SIZE_OES</code>,
* <code>GL_RENDERBUFFER_GREEN_SIZE_OES</code>,
* <code>GL_RENDERBUFFER_BLUE_SIZE_OES</code>,
* <code>GL_RENDERBUFFER_ALPHA_SIZE_OES</code>,
* <code>GL_RENDERBUFFER_DEPTH_SIZE_OES</code>, or
* <code>GL_RENDERBUFFER_STENCIL_SIZE_OES</code>.
* @param params an array into which renderbuffer parameters will be
* written.
* @param offset the starting offset within the
* <code>params</code> array.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>offset</code> is
* less than 0.
* @exception IllegalArgumentException if <code>params.length -
* offset</code> is smaller than the number of values required by
* the parameter.
*/
void glGetRenderbufferParameterivOES(int target, int pname,
int[] params, int offset);
/**
* (<code>OES_framebuffer_object</code> extension)
* Integer <code>Buffer</code> version of
* <code>glGetRenderbufferParameterivOES</code>.
*
* @see #glGetRenderbufferParameterivOES(int target, int pname,
* int[] params, int offset)
*
* @param target the value <code>GL_RENDERBUFFER_OES</code>.
* @param pname one of <code>GL_RENDERBUFFER_WIDTH_OES</code>,
* <code>GL_RENDERBUFFER_HEIGHT_OES</code>,
* <code>GL_RENDERBUFFER_INTERNAL_FORMAT_OES</code>,
* <code>GL_RENDERBUFFER_RED_SIZE_OES</code>,
* <code>GL_RENDERBUFFER_GREEN_SIZE_OES</code>,
* <code>GL_RENDERBUFFER_BLUE_SIZE_OES</code>,
* <code>GL_RENDERBUFFER_ALPHA_SIZE_OES</code>,
* <code>GL_RENDERBUFFER_DEPTH_SIZE_OES</code>, or
* <code>GL_RENDERBUFFER_STENCIL_SIZE_OES</code>.
* @param params an <code>IntBuffer</code> into which renderbuffer
* parameters will be written.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if
* <code>params.remaining()</code> is smaller than the number of
* values required by the parameter.
*/
void glGetRenderbufferParameterivOES(int target, int pname,
IntBuffer params);
/**
* (<code>OES_framebuffer_object</code> extension) Determine whether a
* token represents a framebuffer.
*
* <p> Returns <code>true</code> if <code>framebuffer</code> is the
* name of a framebuffer object. If <code>framebuffer</code> is
* zero, or if <code>framebuffer</code> is a non-zero value that is
* not the name of a framebuffer object,
* <code>glIsFrambufferOES</code> returns <code>false</code>.
*
* @param framebuffer an integer.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
*/
boolean glIsFramebufferOES(int framebuffer);
/**
* (<code>OES_framebuffer_object</code> extension)
* Bind a framebuffer.
* <p> The operations described in chapter 4 of the OpenGL 1.5
* specification affect the images attached to the framebuffer
* object bound to the target GL_FRAMEBUFFER_OES. By default,
* framebuffer bound to the target GL_FRAMEBUFFER_OES is zero,
* specifying the default implementation dependent framebuffer
* provided by the windowing system. When the framebuffer bound to
* target GL_FRAMEBUFFER_OES is not zero, but instead names a
* application-created framebuffer object, then operations
* affect the application-created framebuffer object
* rather than the default framebuffer.
*
* <p> The namespace for framebuffer objects is the unsigned
* integers, with zero reserved by the GL to refer to the default
* framebuffer. A framebuffer object is created by binding an
* unused name to the target <code>GL_FRAMEBUFFER_OES</code>. The
* binding is effected by calling <code>glBindFramebufferOES</code>
* with <code>target</code> set to <code>GL_FRAMEBUFFER_OES</code>
* and <code>framebuffer</code> set to the unused name. The
* resulting framebuffer object is a new state vector, comprising
* all the state values listed in the table below. There are
* <code>GL_MAX_COLOR_ATTACHMENTS_OES</code> color attachment
* points, plus one each for the depth and stencil attachment
* points.
*
* <code>glBindFramebufferOES</code> may also be used to bind an
* existing framebuffer object to <code>target</code>. If the bind
* is successful no change is made to the state of the bound
* framebuffer object and any previous binding to
* <code>target</code> is broken. The current
* <code>GL_FRAMEBUFFER_OES</code> binding can be queried using
* <code>glGetIntegerv(GL_FRAMEBUFFER_BINDING_OES)</code>.
*
* <p> While a framebuffer object is bound to the target
* <code>GL_FRAMEBUFFER_OES</code>, GL operations on the target to
* which it is bound affect the images attached to the bound
* framebuffer object, and queries of the target to which it is
* bound return state from the bound object. The framebuffer object
* bound to the target <code>GL_FRAMEBUFFER_OES</code> is used as
* the destination of fragment operations and as the source of pixel
* reads such as <code>glReadPixels</code>.
*
* In the initial state, the reserved name zero is bound to the
* target <code>GL_FRAMEBUFFER_OES</code>. There is no
* application-created framebuffer object corresponding to the name
* zero. Instead, the name zero refers to the
* window-system-provided framebuffer. All queries and operations
* on the framebuffer while the name zero is bound to the target
* <code>GL_FRAMEBUFFER_OES</code> operate on this default
* framebuffer. On some implementations, the properties of the
* default window-system-provided framebuffer can change over time
* (e.g., in response to window-system events such as attaching the
* context to a new window-system drawable.)
*
* <p> Application-created framebuffer objects (i.e., those with a
* non-zero name) differ from the default window-system-provided
* framebuffer in a few important ways. First and foremost, unlike
* the window-system-provided framebuffer,
* application-created-framebuffers have modifiable attachment
* points for each logical buffer in the framebuffer.
* Framebuffer-attachable images can be attached to and detached
* from these attachment points. Also, the size and format of the
* images attached to application-created framebuffers are
* controlled entirely within the GL interface, and are not affected
* by window-system events, such as pixel format selection, window
* resizes, and display mode changes.
*
* <p> Additionally, when rendering to or reading from an
* application created-framebuffer object:
*
* <ul>
*
* <li>The pixel ownership test always succeeds. In other words,
* application-created framebuffer objects own all of their
* pixels.</li>
*
* <li>There are no visible color buffer bitplanes. This means
* there is no color buffer corresponding to the back, front, left,
* or right color bitplanes.</li>
*
* <li>The only color buffer bitplanes are the ones defined by the
* framebuffer attachment points named
* <code>COLOR_ATTACHMENT0_OES</code> through
* <code>COLOR_ATTACHMENT</code><i>n</i><code>_OES</code>.</li>
*
* <li>The only depth buffer bitplanes are the ones defined by the
* framebuffer attachment point
* <code>DEPTH_ATTACHMENT_OES</code>.</li>
*
* <li>The only stencil buffer bitplanes are the ones defined by the
* framebuffer attachment point
* <code>STENCIL_ATTACHMENT_OES</code>.</li>
*
* </ul>
*
* @param target the value <code>GL_FRAMEBUFFER_OES</code>.
* @param framebuffer the framebuffer to be bound.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
*/
void glBindFramebufferOES(int target, int framebuffer);
/**
* (<code>OES_framebuffer_object</code> extension)
* Delete framebuffer objects.
*
* <p> Framebuffer objects are deleted by calling
* <code>glDeleteFramebuffersOES</code>. <code>framebuffers</code>
* contains <code>n</code> names of framebuffer objects to be
* deleted. After a framebuffer object is deleted, it has no
* attachments, and its name is again unused. If a framebuffer that
* is currently bound to the target <code>GL_FRAMEBUFFER_OES</code>
* is deleted, it is as though <code>glBindFramebufferOES</code> had
* been executed with the <code>target</code> of
* <code>GL_FRAMEBUFFER_OES</code> and <code>framebuffer</code> of
* zero. Unused names in <code>framebuffers</code> are silently
* ignored, as is the value zero.
*
* @param n the number of framebuffers to be deleted.
* @param framebuffers a list of framebuffers.
* @param offset the starting offset within the
* <code>framebuffers</code> array.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
* @exception IllegalArgumentException if <code>framebuffers</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>offset</code> is
* less than 0.
* @exception IllegalArgumentException if <code>framebuffers.length
* - offset</code> is less than <code>n</code>.
*/
void glDeleteFramebuffersOES(int n, int[] framebuffers, int offset);
/**
* (<code>OES_framebuffer_object</code> extension)
* Integer <code>Buffer</code> version of
* <code>glDeleteFramebuffersOES</code>.
*
* @see #glDeleteFramebuffersOES(int n, int[] framebuffers, int offset)
*
* @param n
* @param framebuffers
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
* @exception IllegalArgumentException if <code>framebuffers</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>framebuffers.limit()
* - framebuffers.position()</code> is less than <code>n</code>.
*/
void glDeleteFramebuffersOES(int n, IntBuffer framebuffers);
/**
* (<code>OES_framebuffer_object</code> extension)
* Generate framebuffer names.
*
* <p> The command <code>glGenFramebuffersOES</code> returns
* <code>n</code> previously unused framebuffer object names in
* <code>ids</code>. These names are marked as used, for the
* purposes of <code>glGenFramebuffersOES</code> only, but they
* acquire state and type only when they are first bound, just as if
* they were unused.
*
* @param n the number of framebuffer names to be generated.
* @param framebuffers an array to be filled in with <code>n</code>
* framebuffer names.
* @param offset the starting offset within the
* <code>framebuffers</code> array.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
* @exception IllegalArgumentException if <code>framebuffers</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>offset</code> is
* less than 0.
* @exception IllegalArgumentException if <code>framebuffers.length
* - offset</code> is less than <code>n</code>.
*/
void glGenFramebuffersOES(int n, int[] framebuffers, int offset);
/**
* (<code>OES_framebuffer_object</code> extension)
* Integer <code>Buffer</code> version of
* <code>glGenFramebuffersOES</code>.
*
* @see #glGenFramebuffersOES(int n, int[] framebuffers, int offset)
*
* @param n the number of framebuffer names to be generated.
* @param framebuffers an <code>IntBuffer</code> to be filled in
* with <code>n</code> framebuffer names.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
* @exception IllegalArgumentException if <code>framebuffers</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>framebuffers.limit()
* - framebuffers.position()</code> is less than <code>n</code>.
*/
void glGenFramebuffersOES(int n, IntBuffer framebuffers);
/**
* (<code>OES_framebuffer_object</code> extension)
* Check the status of a framebuffer.
*
* <p> Returns one of <code>GL_FRAMEBUFFER_COMPLETE_OES</code>,
* <code>GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_OES</code>,
* <code>GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_OES</code>,
* <code>GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_OES</code>,
* <code>GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_OES</code>,
* <code>GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_OES</code>, or
* <code>GL_FRAMEBUFFER_UNSUPPORTED_OES</code>.
*
* @param target a framebuffer.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
*/
int glCheckFramebufferStatusOES(int target);
/**
* (<code>OES_framebuffer_object</code> extension)
* Attach an image from a texture object to a framebuffer.
*
* <p> To render directly into a texture image, a specified image from a
* texture object can be attached as one of the logical buffers of the
* currently bound framebuffer object by calling this method.
*
* <p> GL_INVALID_OPERATION is generated if the current value of
* <code>GL_FRAMEBUFFER_BINDING_OES</code> is zero when
* <code>glFramebufferTexture2DOES</code> is called.
* <code>attachment</code> must be one of the attachment points of
* the framebuffer, either
* <code>GL_COLOR_ATTACHMENT</code><i>n</i><code>_OES</code> (where
* <i>n</i> is from 0 to <code>GL_MAX_COLOR_ATTACHMENTS_OES</code> -
* 1), <code>GL_DEPTH_ATTACHMENT_OES</code>, or
* <code>GL_STENCIL_ATTACHMENT_OES</code>.
*
* <p> If <code>texture</code> is zero, then <code>textarget</code>
* and <code>level</code> are ignored. If <code>texture</code> is
* not zero, then <code>texture</code> must either name an existing
* texture object with an target of <code>textarget</code>, or
* <code>texture</code> must name an existing cube map texture and
* <code>textarget</code> must be one of:
* <code>GL_TEXTURE_CUBE_MAP_POSITIVE_X</code>,
* <code>GL_TEXTURE_CUBE_MAP_POSITIVE_Y</code>,
* <code>GL_TEXTURE_CUBE_MAP_POSITIVE_Z</code>,
* <code>GL_TEXTURE_CUBE_MAP_NEGATIVE_X</code>,
* <code>GL_TEXTURE_CUBE_MAP_NEGATIVE_Y</code>, or
* <code>GL_TEXTURE_CUBE_MAP_NEGATIVE_Z</code>. Otherwise,
* <code>GL_INVALID_OPERATION</code> is generated.
*
* <p> <code>level</code> specifies the mipmap level of the texture
* image to be attached to the framebuffer and must be 0 (indicating
* the base MIPmap level).
*
* <p> If <code>textarget</code> is one of
* <code>GL_TEXTURE_CUBE_MAP_POSITIVE_X</code>,
* <code>GL_TEXTURE_CUBE_MAP_POSITIVE_Y</code>,
* <code>GL_TEXTURE_CUBE_MAP_POSITIVE_Z</code>,
* <code>GL_TEXTURE_CUBE_MAP_NEGATIVE_X</code>,
* <code>GL_TEXTURE_CUBE_MAP_NEGATIVE_Y</code>, or
* <code>GL_TEXTURE_CUBE_MAP_NEGATIVE_Z</code>, then
* <code>level</code> must be greater than or equal to zero and less
* than or equal to log base 2 of
* <code>GL_MAX_CUBE_MAP_TEXTURE_SIZE</code>. For all other values of
* <code>textarget</code>, <code>level</code> must be greater than or
* equal to zero and no larger than log base 2 of
* <code>GL_MAX_TEXTURE_SIZE</code>. Otherwise,
* <code>GL_INVALID_VALUE</code> is generated.
*
* <p> If <code>texture</code> is not zero, then
* <code>textarget</code> must be one of:
* <code>GL_TEXTURE_2D</code>,
* <code>GL_TEXTURE_CUBE_MAP_POSITIVE_X</code>,
* <code>GL_TEXTURE_CUBE_MAP_POSITIVE_Y</code>,
* <code>GL_TEXTURE_CUBE_MAP_POSITIVE_Z</code>,
* <code>GL_TEXTURE_CUBE_MAP_NEGATIVE_X</code>,
* <code>GL_TEXTURE_CUBE_MAP_NEGATIVE_Y</code>, or
* <code>GL_TEXTURE_CUBE_MAP_NEGATIVE_Z</code>.
*
* <p> If <code>texture</code> is not zero, and if
* <code>glFramebufferTexture2DOES</code> is successful, then the
* specified texture image will be used as the logical buffer
* identified by <code>attachment</code> of the framebuffer currently
* bound to <code>target</code>. The value of
* <code>GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_OES</code> for the
* specified attachment point is set to <code>GL_TEXTURE</code> and
* the value of
* <code>GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_OES</code> is set to
* <texture>. Additionally, the value of
* <code>GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_OES</code> for the
* named attachment point is set to <code>level</code>. If
* <code>texture</code> is a cubemap texture then, the value of
* <code>GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_OES</code>
* the named attachment point is set to <code>textarget</code>. All
* other state values of the attachment point specified by
* <code>attachment</code> are set to their default values listed in
* the table below. No change is made to the state of the texture
* object, and any previous attachment to the <code>attachment</code>
* logical buffer of the framebuffer object bound to framebuffer
* <code>target</code> is broken. If, on the other hand, the
* attachment is not successful, then no change is made to the state
* of either the texture object or the framebuffer object.
*
* <p> Calling <code>glFramebufferTexture2DOES</code> with
* <code>texture</code> name zero will detach the image identified by
* <code>attachment</code>, if any, in the framebuffer currently
* bound to <code>target</code>. All state values of the attachment
* point specified by <code>attachment</code> are set to their
* default values listed in the table below.
*
* <p> If a texture object is deleted while its image is attached to
* one or more attachment points in the currently bound framebuffer,
* then it is as if <code>glFramebufferTexture2DOES</code> had been
* called, with a <code>texture</code> of 0, for each attachment
* point to which this image was attached in the currently bound
* framebuffer. In other words, this texture image is first detached
* from all attachment points in the currently bound framebuffer.
* Note that the texture image is specifically <b>not</b> detached from
* any other framebuffer objects. Detaching the texture image from
* any other framebuffer objects is the responsibility of the
* application.
*
* <p> The entire texture image, including border texels, if any, can be
* addressed with window-coordinates in the following range:
*
* <pre>
* 0 <= window_x < (texture_width + (2 * border)),
* </pre>
* and
* <pre>
* 0 <= window_y < (texture_height + (2 * border))
* </pre>
*
* <p> The values in the first column of the table below should be
* prefixed with <code>GL_RENDERBUFFER_</code> and suffixed with
* <code>OES</code>. The get command for all values is
* <code>glGetRenderbufferParameterivOES</code>. All take on
* positive integral values.
*
* <pre>
* Get Initial
* Value Value Description
* --------------- ------- ----------------------
* ATTACHMENT_OBJECT_TYPE GL_NONE type of
* image attached to
* framebuffer attachment
* point
*
* ATTACHMENT_OBJECT_NAME 0 name of object
* attached to
* framebuffer attachment
* point
*
* ATTACHMENT_TEXTURE_LEVEL 0 mipmap level of
* texture image
* attached, if object
* attached is texture.
*
* ATTACHMENT_TEXTURE_ GL_TEXTURE_ cubemap face of
* CUBE_MAP_FACE CUBE_MAP_ texture image
* POSITIVE_X attached, if object
* attached is cubemap
* texture.
* </pre>
*
* @param target the value <code>GL_FRAMEBUFFER_OES</code>.
* @param attachment the framebuffer attachment, one of
* <code>GL_COLOR_ATTACHMENT_</code><i>n</i><code>_OES</code> (where
* <i>n</i> is from 0 to <code>GL_MAX_COLOR_ATTACHMENTS_OES</code> -
* 1), <code>GL_DEPTH_ATTACHMENT_OES</code>, or
* <code>GL_STENCIL_ATTACHMENT_OES</code>.
* @param textarget one of <code>GL_TEXTURE_2D</code>,
* <code>GL_TEXTURE_CUBE_MAP_POSITIVE_X</code>,
* <code>GL_TEXTURE_CUBE_MAP_POSITIVE_Y</code>,
* <code>GL_TEXTURE_CUBE_MAP_POSITIVE_Z</code>,
* <code>GL_TEXTURE_CUBE_MAP_NEGATIVE_X</code>,
* <code>GL_TEXTURE_CUBE_MAP_NEGATIVE_Y</code>, or
* <code>GL_TEXTURE_CUBE_MAP_NEGATIVE_Z</code>.
* @param texture the texture, or zero.
* @param level the texture MIPmap level, which must be 0.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
*/
void glFramebufferTexture2DOES(int target, int attachment,
int textarget, int texture,
int level);
/**
* (<code>OES_framebuffer_object</code> extension)
* Attach a renderbuffer to a framebuffer.
*
* <p> A renderbuffer can be attached as one of the logical buffers
* of the currently bound framebuffer object by calling
* <code>glFramebufferRenderbufferOES</code>. <code>target</code>
* must be <code>GL_FRAMEBUFFER_OES</code>.
* <code>GL_INVALID_OPERATION</code> is generated if the current
* value of <code>GL_FRAMEBUFFER_BINDING_OES</code> is zero when
* <code>glFramebufferRenderbufferOES</code> is called.
* <code>attachment</code> should be set to one of the attachment
* points of the framebuffer, one of
* <code>GL_COLOR_ATTACHMENT</code><i>n</i><code>_OES</code> (where
* <i>n</i> is from 0 to <code>GL_MAX_COLOR_ATTACHMENTS_OES</code> -
* 1), <code>GL_DEPTH_ATTACHMENT_OES</code>, or
* <code>GL_STENCIL_ATTACHMENT_OES</code>.
* <code>renderbuffertarget</code> must be
* <code>GL_RENDERBUFFER_OES</code> and <code>renderbuffer</code>
* should be set to the name of the renderbuffer object to be
* attached to the framebuffer. <code>renderbuffer</code> must be
* either zero or the name of an existing renderbuffer object of
* type <code>renderbuffertarget</code>, otherwise
* <code>GL_INVALID_OPERATION</code> is generated. If
* <code>renderbuffer</code> is zero, then the value of
* <code>renderbuffertarget</code> is ignored.
*
* <p> If <code>renderbuffer</code> is not zero and if
* <code>glFramebufferRenderbufferOES</code> is successful, then the
* renderbuffer named <code>renderbuffer</code> will be used as the
* logical buffer identified by <code>attachment</code> of the
* framebuffer currently bound to <code>target</code>. The value of
* <code>GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_OES</code> for the
* specified attachment point is set to
* <code>GL_RENDERBUFFER_OES</code> and the value of
* <code>GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_OES</code> is set to
* <code>renderbuffer</code>. All other state values of the
* attachment point specified by <code>attachment</code> are set to
* their default values listed in the table below. No change is made
* to the state of the renderbuffer object and any previous
* attachment to the <code>attachment</code> logical buffer of the
* framebuffer object bound to framebuffer <code>target</code> is
* broken. If, on the other hand, the attachment is not successful,
* then no change is made to the state of either the renderbuffer
* object or the framebuffer object.
*
* <p> Calling <code>glFramebufferRenderbufferOES</code> with the
* <code>renderbuffer</code> name zero will detach the image, if
* any, identified by <code>attachment</code>, in the framebuffer
* currently bound to <code>target</code>. All state values of the
* attachment point specified by <code>attachment</code> in the
* object bound to <code>target</code> are set to their default
* values listed in the table below.
*
* <p> If a renderbuffer object is deleted while its image is
* attached to one or more attachment points in the currently bound
* framebuffer, then it is as if
* <code>glFramebufferRenderbufferOES</code> had been called, with a
* <code>renderbuffer</code> of 0, for each attachment point to
* which this image was attached in the currently bound framebuffer.
* In other words, this renderbuffer image is first detached from
* all attachment points in the currently bound framebuffer. Note
* that the renderbuffer image is specifically *not* detached from
* any non-bound framebuffers. Detaching the image from any
* non-bound framebuffers is the responsibility of the application.
*
* <p> The values in the first column of the table below should be
* prefixed with <code>GL_RENDERBUFFER_</code> and suffixed with
* <code>OES</code>. The get command for all values is
* <code>glGetRenderbufferParameterivOES</code>. All take on
* positive integral values.
*
* <pre>
* Get Initial
* Value Value Description
* --------------- ------- ----------------------
* ATTACHMENT_OBJECT_TYPE GL_NONE type of
* image attached to
* framebuffer attachment
* point
*
* ATTACHMENT_OBJECT_NAME 0 name of object
* attached to
* framebuffer attachment
* point
*
* ATTACHMENT_TEXTURE_LEVEL 0 mipmap level of
* texture image
* attached, if object
* attached is texture.
*
* ATTACHMENT_TEXTURE_ GL_TEXTURE_ cubemap face of
* CUBE_MAP_FACE CUBE_MAP_ texture image
* POSITIVE_X attached, if object
* attached is cubemap
* texture.
* </pre>
*
* @param target the value <code>GL_FRAMEBUFFER_OES</code>.
* @param attachment one of
* <code>GL_COLOR_ATTACHMENT</code><i>n</i><code>_OES</code> (where
* <i>n</i> is from 0 to <code>GL_MAX_COLOR_ATTACHMENTS_OES</code> -
* 1), <code>GL_DEPTH_ATTACHMENT_OES</code>, or
* <code>GL_STENCIL_ATTACHMENT_OES</code>.
* @param renderbuffertarget the value
* <code>GL_RENDERBUFFER_OES</code>.
* @param renderbuffer the renderbuffer to be attached to the framebuffer.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
*/
void glFramebufferRenderbufferOES(int target, int attachment,
int renderbuffertarget,
int renderbuffer);
/**
* (<code>OES_framebuffer_object</code> extension)
* Query the value of a framebuffer attachment parameter.
*
* <p> <code>target</code> must be <code>GL_FRAMEBUFFER_OES</code>.
* <code>attachment</code> must be one of the attachment points of
* the framebuffer, either <code>GL_COLOR_ATTACHMENT</code><i>n</i><code>_OES</code> (where
* <i>n</i> is from 0 to <code>GL_MAX_COLOR_ATTACHMENTS_OES</code> -
* 1), <code>GL_DEPTH_ATTACHMENT_OES</code>, or
* <code>GL_STENCIL_ATTACHMENT_OES</code>.
* <code>pname</code> must be one of the following:
* <code>GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_OES</code>,
* <code>GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_OES</code>,
* <code>GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_OES</code>, or
* <code>GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_OES</code>.
*
* <p> If the framebuffer currently bound to <code>target</code> is
* zero, then <code>GL_INVALID_OPERATION</code> is generated.
*
* <p> Upon successful return from
* <code>glGetFramebufferAttachmentParameterivOES</code>, if
* <code>pname</code> is
* <code>GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_OES</code>, then
* <code>param</code> will contain one of <code>GL_NONE</code>,
* <code>GL_TEXTURE</code>, or <code>GL_RENDERBUFFER_OES</code>,
* identifying the type of object which contains the attached image.
*
* <p> If the value of GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_OES is
* <code>GL_RENDERBUFFER_OES</code>, then:
*
* <ul> <li>If <code>pname</code> is
* <code>GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_OES</code>,
* <code>params</code> will contain the name of the renderbuffer
* object which contains the attached image.</li>
*
* <li>Otherwise, <code>GL_INVALID_ENUM</code> is generated.</li>
* </ul>
*
* <p> If the value of
* <code>GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_OES</code> is
* <code>GL_TEXTURE</code>, then:
*
* <ul>
*
* <li>If <pname> is
* <code>GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_OES</code>, then
* <params> will contain the name of the texture object which
* contains the attached image.</li>
*
* <li>If <pname> is
* <code>GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_OES</code>, then
* <params> will contain the mipmap level of the texture object
* which contains the attached image.</li>
*
* <li>If <pname> is
* <code>GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_OES</code>
* and the texture object named
* <code>FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_OES</code> is a cube map
* texture, then <params> will contain the cube map face of the
* cubemap texture object which contains the attached image.
* Otherwise <params> will contain the value zero.</li>
*
* <li>Otherwise, <code>GL_INVALID_ENUM</code> is generated.</li>
*
* </ul>
*
* @param target the value <code>GL_FRAMEBUFFER_OES</code>.
* @param attachment one of
* <code>GL_COLOR_ATTACHMENT</code><i>n</i><code>_OES</code> (where
* <i>n</i> is from 0 to <code>GL_MAX_COLOR_ATTACHMENTS_OES</code> -
* 1), <code>GL_DEPTH_ATTACHMENT_OES</code>, or
* <code>GL_STENCIL_ATTACHMENT_OES</code>.
* @param pname one of
* <code>GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_OES</code>,
* <code>GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_OES</code>,
* <code>GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_OES</code>, or
* <code>GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_OES</code>.
* @param params an array to which the query results will be written.
* @param offset the starting offset within the
* <code>params</code> array.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>offset</code> is
* less than 0.
* @exception IllegalArgumentException if <code>params.length -
* offset</code> is smaller than the number of values required by
* the parameter.
*/
void glGetFramebufferAttachmentParameterivOES(int target,
int attachment,
int pname,
int[] params, int offset);
/**
* (<code>OES_framebuffer_object</code> extension)
* Integer <code>Buffer</code> version of
* <code>glGetFramebufferAttachmentParameterivOES</code>.
*
* @see #glGetFramebufferAttachmentParameterivOES(int target, int
* attachment, int pname, int[] params, int offset)
*
* @param target the value <code>GL_FRAMEBUFFER_OES</code>.
* @param attachment one of
* <code>GL_COLOR_ATTACHMENT</code><i>n</i><code>_OES</code> (where
* <i>n</i> is from 0 to <code>GL_MAX_COLOR_ATTACHMENTS_OES</code> -
* 1), <code>GL_DEPTH_ATTACHMENT_OES</code>, or
* <code>GL_STENCIL_ATTACHMENT_OES</code>.
* @param pname one of
* <code>GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_OES</code>,
* <code>GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_OES</code>,
* <code>GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_OES</code>, or
* <code>GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_OES</code>.
* @param params an <code>IntBuffer</code> to which the query
* results will be written.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
* @exception IllegalArgumentException if <code>params</code> is
* <code>null</code>.
* @exception IllegalArgumentException if
* <code>params.remaining()</code> is smaller than the number of
* values required by the parameter.
*/
void glGetFramebufferAttachmentParameterivOES(int target,
int attachment,
int pname,
IntBuffer params);
/**
* (<code>OES_framebuffer_object</code> extension) Generate mipmaps
* manually.
*
* <p> <code>target</code> is one of <code>TEXTURE_2D</code> or
* <code>TEXTURE_CUBE_MAP</code>. Mipmap generation affects the
* texture image attached to <code>target</code>. For cube map
* textures, <code>INVALID_OPERATION</code> is generated if the
* texture bound to <code>target</code> is not cube complete.
*
* @param target one of <code>TEXTURE_2D</code> or
* <code>TEXTURE_CUBE_MAP</code>.
*
* @exception UnsupportedOperationException if the underlying
* runtime engine does not support the
* <code>OES_framebuffer_object</code> extension.
*/
void glGenerateMipmapOES(int target);
}
| gpl-2.0 |
AlanGuerraQuispe/SisAtuxPerfumeria | atux-jrcp/src/main/java/com/aw/swing/mvp/ui/painter/ColorInfoProvider.java | 2848 | /*
* Copyright (c) 2007 Agile-Works
* All rights reserved.
*
* This software is the confidential and proprietary information of
* Agile-Works. ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with Agile-Works.
*/
package com.aw.swing.mvp.ui.painter;
import java.awt.*;
/**
* User: gmc
* Date: 01-oct-2007
*/
public class ColorInfoProvider {
public static final Color COLOR_DEFAULT = new Color(255, 255, 255);
public static final Color COLOR_TITLE_DEFAULT = new Color(0, 0, 0);
// public static final Color COLOR_ERROR = new Color(255, 215, 215);
public static final Color COLOR_ERROR = new Color(254, 204, 205);
public static final Color COLOR_BORDER_ERROR = new Color(255, 0, 0);
public static final Color PANEL_ERROR_BACKGROUND = Color.WHITE;
public static final String PANEL_ERROR = "pnlError";
public static final String LABEL_ERROR = "lblError";
public static final String LABEL_OPTIONS = "lblOptions";
public static final Color LABEL_OPTIONS_FOREGROUND = Color.GREEN;
public static final String PANEL_TITULO_GRID = "pnlTitGrid";
public static final Color PANEL_TITULO_GRID_BACKGROUND = Color.RED;
public static final String CHECKBOX_SEL = "chkSel";
public static final Color CHECKBOX_SEL_BACKGROUND = Color.RED;
public static final Color CHECKBOX_SEL_FOREGROUND = Color.GREEN;
public static final String LABEL_TITULO_GRID = "lblTitGrid";
public static final Color LABEL_TITULO_GRID_FOREGROUND = Color.WHITE;
// public static final Color TEXT_BOX_READ_ONLY = Color.lightGray;
// public static final Color TEXT_BOX_READ_ONLY = new Color(214,217,223);
public static final Color TEXT_BOX_READ_ONLY = new Color(219, 216,222);
public static final Color CALENDAR_TODAY_FOREGROUND = new Color(20,56,110);
public static final Color CALENDAR_TODAY_FOREGROUND_OVER = new Color(1,130,184);
public static Color getBackGroundFor(String componentName) {
if (componentName.equals(PANEL_ERROR)) {
return PANEL_ERROR_BACKGROUND;
} else if (componentName.equals(PANEL_TITULO_GRID)) {
return PANEL_TITULO_GRID_BACKGROUND;
} else if (componentName.equals(CHECKBOX_SEL)) {
return CHECKBOX_SEL_BACKGROUND;
}
return null;
}
public static Color getForeGround(String componentName) {
if (componentName.equals(LABEL_OPTIONS)) {
return LABEL_OPTIONS_FOREGROUND;
} else if (componentName.equals(LABEL_TITULO_GRID)) {
return LABEL_TITULO_GRID_FOREGROUND;
} else if (componentName.equals(CHECKBOX_SEL)) {
return CHECKBOX_SEL_FOREGROUND;
}
return null;
}
}
| gpl-2.0 |
hoaibang07/Webscrap | transcripture/sources/checkcomplete.py | 1294 | import io
import os.path
def check_numline(filename):
urlsach_list = []
urlsach_file = open(filename, 'r')
for line in urlsach_file:
urlsach_list.append(line.strip())
_len = len(urlsach_list)
return _len
def main():
f = io.open('check_output.txt', 'w', encoding = 'utf-8')
for x in xrange(1,67):
ok = True
#kiem tra xem file nam co ton tai hay khong
fname = 'urlsach/data/complete/sach' + str(x) + '.txt'
if os.path.isfile(fname):
print('ton tai sach %d'%x)
urlsach = 'urlsach/sach' + str(x) + '.txt'
#kiem tra so dong cua url sach, tuong ung voi so chuong
numline = check_numline(urlsach)
print numline
#doc data tu file sach data
data = open(fname).read()
#kiem tra xem moi dong trong file sach data da co chuong cac so nay chua
for i in xrange(1,numline + 1):
key = str(i)
# print ('da chay den day')
if key not in data:
ok = False
break
if ok:
out = u'Sach ' + str(x) + ' ok\n'
print out
f.write(out)
f.close()
if __name__ == '__main__':
main() | gpl-2.0 |
kuul-dev/Kuul-Dev-Booking | themes/default/views/pages/search.php | 2320 | <?php defined('SYSPATH') or die('No direct script access.');?>
<div class="well clearfix">
<?= FORM::open(Route::url('search'), array('class'=>'form-search', 'method'=>'GET', 'action'=>''))?>
<div class="">
<div class="col-md-3">
<label><?=__('Name')?></label>
<input type="text" id="search" name="search" class="form-control" value="<?=core::get('search')?>" placeholder="<?=__('Search')?>">
</div>
</div>
<div class="">
<div class="col-md-3">
<label><?=__('Category')?></label>
<select name="category" id="category" class="form-control remove_chzn" >
<option></option>
<?function lili($item, $key,$cats){?>
<option value="<?=$cats[$key]['seoname']?>" <?=(core::get('category')==$cats[$key]['seoname']?'selected':'')?> >
<?=$cats[$key]['name']?></option>
<?if (count($item)>0):?>
<optgroup label="<?=$cats[$key]['name']?>">
<? if (is_array($item)) array_walk($item, 'lili', $cats);?>
<?endif?>
<?}array_walk($order_categories, 'lili',$categories);?>
</select>
</div>
</div>
<div class="">
<div class="col-md-2">
<label><?=__('Price from')?></label>
<input type="text" id="price-min" name="price-min" class="form-control" value="<?=core::get('price-min')?>" placeholder="0">
</div>
</div>
<div class="">
<div class="col-md-2">
<label><?=__('to')?></label>
<input type="text" id="price-max" name="price-max" class="form-control" value="<?=core::get('price-max')?>" placeholder="100">
</div>
</div>
<div class="adv-btn">
<?= FORM::button('submit', __('Search'), array('type'=>'submit', 'class'=>'btn btn-primary pull-right', 'action'=>Route::url('search')))?>
</div>
<?= FORM::close()?>
</div>
<?if (count($products)>0):?>
<h3><?=__('Search results')?></h3>
<?=View::factory('pages/product/listing',array('pagination'=>$pagination,'products'=>$products,'category'=>NULL))?>
<?endif?> | gpl-2.0 |
GMDSP-Linked-Data/PhaseTwo | Visualisations/Expenditure/chartVis.js | 801 | function visChart(data, canvas) {
var chartData = [];
var pieOptions = {
segmentShowStroke: false,
animateScale: true
};
var results = data.results.bindings;
for (i = 0; i < results.length; i++) {
var unit = results[i].label.value;
var amount = parseFloat(results[i].count.value);
var col = getRandomColor();
chartData.push({value: amount, label: unit, color: col});
}
new Chart(canvas).Doughnut(chartData, pieOptions);
}
function getCanvas(canvasId) {
return $("#" + canvasId).get(0).getContext("2d");
}
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
} | gpl-2.0 |
vlabatut/totalboumboum | resources/ai/org/totalboumboum/ai/v201112/ais/_simplet/v1/UtilityHandler.java | 12948 | package org.totalboumboum.ai.v201112.ais._simplet.v1;
/*
* Total Boum Boum
* Copyright 2008-2014 Vincent Labatut
*
* This file is part of Total Boum Boum.
*
* Total Boum Boum is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* Total Boum Boum is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Total Boum Boum. If not, see <http://www.gnu.org/licenses/>.
*
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.totalboumboum.ai.v201112.ais._simplet.v1.criterion.CriterionDestruction;
import org.totalboumboum.ai.v201112.ais._simplet.v1.criterion.CriterionLocality;
import org.totalboumboum.ai.v201112.ais._simplet.v1.criterion.CriterionThreat;
import org.totalboumboum.ai.v201112.adapter.agent.AiMode;
import org.totalboumboum.ai.v201112.adapter.agent.AiUtilityCase;
import org.totalboumboum.ai.v201112.adapter.agent.AiUtilityCombination;
import org.totalboumboum.ai.v201112.adapter.agent.AiUtilityCriterion;
import org.totalboumboum.ai.v201112.adapter.agent.AiUtilityHandler;
import org.totalboumboum.ai.v201112.adapter.communication.StopRequestException;
import org.totalboumboum.ai.v201112.adapter.data.AiHero;
import org.totalboumboum.ai.v201112.adapter.data.AiItem;
import org.totalboumboum.ai.v201112.adapter.data.AiTile;
import org.totalboumboum.ai.v201112.adapter.data.AiZone;
import org.totalboumboum.ai.v201112.adapter.path.AiLocation;
import org.totalboumboum.ai.v201112.adapter.path.AiSearchNode;
import org.totalboumboum.ai.v201112.adapter.path.LimitReachedException;
import org.totalboumboum.ai.v201112.adapter.path.cost.CostCalculator;
import org.totalboumboum.ai.v201112.adapter.path.cost.TileCostCalculator;
import org.totalboumboum.ai.v201112.adapter.path.search.Dijkstra;
import org.totalboumboum.ai.v201112.adapter.path.successor.BasicSuccessorCalculator;
import org.totalboumboum.ai.v201112.adapter.path.successor.SuccessorCalculator;
/**
* Classe gérant le calcul des valeurs d'utilité de l'agent.
* Pour cet exemple, on ne distingue qu'un petit nombre
* de critères et de cas.
*
* @author Vincent Labatut
*/
@SuppressWarnings("deprecation")
public class UtilityHandler extends AiUtilityHandler<Simplet>
{
/**
* Construit un gestionnaire pour l'agent passé en paramètre.
*
* @param ai
* l'agent que cette classe doit gérer.
*
* @throws StopRequestException
* Au cas où le moteur demande la terminaison de l'agent.
*/
protected UtilityHandler(Simplet ai) throws StopRequestException
{ super(ai);
ai.checkInterruption();
// on initialise certains objets une fois pour toutes
initData();
}
/////////////////////////////////////////////////////////////////
// DATA /////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
/** La zone de jeu */
private AiZone zone = null;
/** Le personnage contrôlé par cet agent */
private AiHero ownHero = null;
/** Un objet dijkstra utilisé pour identifier le voisinage de l'agent */
private Dijkstra dijkstra = null;
/** Les méthodes communes */
private CommonTools commonTools;
/** Indique pour chaque case traitée si on veut y poser une bombe ou pas */
protected HashMap<AiTile,Boolean> bombTiles = new HashMap<AiTile,Boolean>();
/**
* Permet d'initialiser certains objets une fois pour toutes.
*
* @throws StopRequestException
* Au cas où le moteur demande la terminaison de l'agent.
*/
private void initData() throws StopRequestException
{ ai.checkInterruption();
zone = ai.getZone();
ownHero = zone.getOwnHero();
commonTools = ai.commonTools;
// on a besoin d'un objet dijkstra pour le traitement,
CostCalculator costCalculator = new TileCostCalculator(ai);
SuccessorCalculator successorCalculator = new BasicSuccessorCalculator(ai);
dijkstra = new Dijkstra(ai,ownHero,costCalculator,successorCalculator);
dijkstra.setMaxHeight(5); // on se met une limite raisonnable
}
@Override
protected void resetData() throws StopRequestException
{ ai.checkInterruption();
super.resetData();
bombTiles.clear();
}
/////////////////////////////////////////////////////////////////
// CRITERIA /////////////////////////////////////
/////////////////////////////////////////////////////////////////
/** Cas de collecte correspondant à une case contenant un item visible */
private final String CASE_COLLECT_VISIBLE_ITEM = "VISIBLE_ITEM";
/** Cas de collecte correspondant à une case voisine d'un mur destructible */
private final String CASE_COLLECT_WALL_NEIGHBOR = "WALL_NEIGHBOR";
/** Cas d'attaque correspondant à une case suffisamment proche de la cible */
private final String CASE_ATTACK = "ATTACK";
@Override
protected Set<AiTile> selectTiles() throws StopRequestException
{ ai.checkInterruption();
Set<AiTile> result = new TreeSet<AiTile>();
HashMap<AiTile,AiSearchNode> map = null;
// ici, la sélection des cases dont on veut l'utilité dépend du mode
AiMode mode = ai.modeHandler.getMode();
// pour le mode attaque, l'agent considère les cases à portée de sa cible
if(mode==AiMode.ATTACKING)
{ // on récupère la cible
AiHero target = ai.targetHandler.target;
if(target!=null)
{ // on récupère les cases permettant de la menacer directement
Set<AiTile> dangerous = commonTools.getTilesForRadius(target.getTile(),ownHero);
// on les ajoute aux cases à traiter
result.addAll(dangerous);
}
}
// pour le mode collecte, l'agent considère les items ainsi
// que les cases situées dans son voisinage
else
{ // on récupère les items visibles
List<AiItem> items = zone.getItems();
// s'il y en a, on considère uniquement leurs cases (grosse simplification !)
if(!items.isEmpty())
{ for(AiItem item: items)
{ ai.checkInterruption();
AiTile tile = item.getTile();
result.add(tile);
}
}
// sinon on on considère le voisinage de l'agent
else
{ // on utilise une version simple de dijkstra pour identifier le voisinage
AiLocation startLocation = new AiLocation(ownHero);
try
{ map = dijkstra.startProcess(startLocation);
result.addAll(map.keySet());
}
catch (LimitReachedException e)
{ //e.printStackTrace();
}
}
}
// on veut toujours avoir au moins une case
if(result.isEmpty())
{ AiTile tile = null;
// si on n'en a pas, on en prend une au hasard
final AiTile currentTile = ownHero.getTile();
// on utilise une version simple de dijkstra pour identifier le voisinage
AiLocation startLocation = new AiLocation(ownHero);
try
{ if(map==null)
map = dijkstra.startProcess(startLocation);
List<AiTile> tiles = new ArrayList<AiTile>(map.keySet());
Collections.shuffle(tiles);
Collections.sort(tiles,new Comparator<AiTile>()
{ @Override
public int compare(AiTile t1, AiTile t2)
{ int d1 = zone.getTileDistance(t1,currentTile);
int d2 = zone.getTileDistance(t2,currentTile);
int result = d2 - d1; // ordre inverse
return result;
}
});
if(!tiles.isEmpty())
{ tile = tiles.get(0);
result.add(tile);
}
}
catch (LimitReachedException e)
{ //e.printStackTrace();
}
// on prend un voisin direct
// List<AiTile> neighbors = new ArrayList<AiTile>(currentTile.getNeighbors());
// Collections.shuffle(neighbors);
// Iterator<AiTile> it = neighbors.iterator();
// while(result.isEmpty() && it.hasNext())
// { ai.checkInterruption();
//
// AiTile neighbor = it.next();
// if(neighbor.isCrossableBy(ownHero))
// { result.add(neighbor);
// tile = neighbor;
// }
// }
// si aucune case n'est accessible (!?) on prend la case courante
if(result.isEmpty())
{ result.add(currentTile);
tile = currentTile;
}
bombTiles.put(tile,false);
}
return result;
}
@Override
protected void initCriteria() throws StopRequestException
{ ai.checkInterruption();
// on définit les critères
CriterionLocality criterionLocality = new CriterionLocality(ai);
CriterionDestruction criterionDestruction = new CriterionDestruction(ai);
CriterionThreat criterionThreat = new CriterionThreat(ai);
// on définit les cas
AiUtilityCase caseCollectVisibleItem;
AiUtilityCase caseCollectWallNeighbor;
AiUtilityCase caseAttack;
// cas de collecte
{ // cas de l'item visible
Set<AiUtilityCriterion<?>> criteria = new TreeSet<AiUtilityCriterion<?>>();
criteria.add(criterionLocality);
caseCollectVisibleItem = new AiUtilityCase(CASE_COLLECT_VISIBLE_ITEM,criteria);
cases.put(CASE_COLLECT_VISIBLE_ITEM,caseCollectVisibleItem);
}
{ // cas des autres cases
Set<AiUtilityCriterion<?>> criteria = new TreeSet<AiUtilityCriterion<?>>();
criteria.add(criterionLocality);
criteria.add(criterionDestruction);
caseCollectWallNeighbor = new AiUtilityCase(CASE_COLLECT_WALL_NEIGHBOR,criteria);
cases.put(CASE_COLLECT_WALL_NEIGHBOR,caseCollectVisibleItem);
}
// cas d'attaque
{ // un seul cas
Set<AiUtilityCriterion<?>> criteria = new TreeSet<AiUtilityCriterion<?>>();
criteria.add(criterionLocality);
criteria.add(criterionThreat);
caseAttack = new AiUtilityCase(CASE_ATTACK,criteria);
cases.put(CASE_ATTACK,caseAttack);
}
// on affecte les valeurs d'utilité
int utility = 1;
AiUtilityCombination combi;
// cas de collecte
for(int locality=0;locality<=CriterionLocality.LOCALITY_LIMIT;locality++)
{ ai.checkInterruption();
for(int destruction=0;destruction<=CriterionDestruction.DESTRUCTION_LIMIT;destruction++)
{ ai.checkInterruption();
combi = new AiUtilityCombination(caseCollectWallNeighbor);
combi.setCriterionValue(criterionLocality,locality);
combi.setCriterionValue(criterionDestruction,destruction);
referenceUtilities.put(combi,utility);
utility++;
}
}
for(int locality=0;locality<=CriterionLocality.LOCALITY_LIMIT;locality++)
{ ai.checkInterruption();
combi = new AiUtilityCombination(caseCollectVisibleItem);
combi.setCriterionValue(criterionLocality,locality);
referenceUtilities.put(combi,utility);
utility++;
}
// on màj la valeur d'utilité maximale pour la collecte
maxUtilities.put(AiMode.COLLECTING,utility-1);
// cas d'attaque
utility = 1;
for(int threat=1;threat<=CriterionThreat.THREAT_LIMIT;threat++)
{ ai.checkInterruption();
for(int locality=0;locality<=CriterionLocality.LOCALITY_LIMIT;locality++)
{ ai.checkInterruption();
combi = new AiUtilityCombination(caseAttack);
combi.setCriterionValue(criterionLocality,locality);
combi.setCriterionValue(criterionThreat,threat);
referenceUtilities.put(combi,utility);
utility++;
}
}
// on màj la valeur d'utilité maximale pour l'attaque
maxUtilities.put(AiMode.ATTACKING,utility-1);
}
@Override
protected AiUtilityCase identifyCase(AiTile tile) throws StopRequestException
{ ai.checkInterruption();
AiUtilityCase result = null;
// le cas dépend du mode
AiMode mode = ai.modeHandler.getMode();
// pour l'attaque, on n'a définit qu'un seul cas
if(mode.equals(AiMode.ATTACKING))
{ result = cases.get(CASE_ATTACK);
if(!bombTiles.containsKey(tile))
bombTiles.put(tile,true);
}
// pour la collecte, on teste simplement la présence d'un item
else
{ List<AiItem> items = tile.getItems();
if(items.isEmpty())
{ result = cases.get(CASE_COLLECT_VISIBLE_ITEM);
bombTiles.put(tile,false);
}
else
{ result = cases.get(CASE_COLLECT_WALL_NEIGHBOR);
bombTiles.put(tile,true);
}
}
return result;
}
/////////////////////////////////////////////////////////////////
// OUTPUT /////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
@Override
public void updateOutput() throws StopRequestException
{ ai.checkInterruption();
// ici on se contente de faire le traitement par défaut
super.updateOutput();
}
}
| gpl-2.0 |
frrisus/dnd5e | app/assets/javascripts/characters/index.js | 3666 | function characters_open_edit_form(ev) {
var $modal = $( '#editchar-modal' ).modal( 'show' );
var $form = $( 'form', $modal );
var $me = $( ev.currentTarget );
var $this_row = $me.parents( 'tr' );
var char_id = $this_row.attr( 'data-char-id' );
var $these_data = $this_row.children( 'td' );
$form.attr( 'action', '/characters/' + char_id );
var fields = [ "name", "str", "dex", "con", "int", "wis", "chr",
"perception", "initiative", "speed", "ac" ];
for (var i = 0; i < fields.length; i++) {
objname = 'input[name="character[' + fields[i] + ']"]';
$( objname, $form ).val( $these_data.eq(i+1).text() );
}
var $notes_row = $this_row.next();
if ( $notes_row.attr( 'data-notes-id' ) == char_id ) {
$( 'input[name="character[notes]"]', $form ).val( $notes_row.find( 'td' ).eq(0).text() );
}
$( 'input[name="character[highlight]"]', $form ).prop( 'checked', ( $this_row.attr( 'data-char-highlight' ) == "true" ) );
}
function characters_fetch() {
$.ajax({
url: '/ajax/characters/index.html',
method: 'GET',
success: function(data) {
$( '#char-results' ).html( data );
$( '.glyphicon-pencil', '#character-table' ).on( 'click', characters_open_edit_form );
}
})
}
$( function () {
character_auth_token = $( 'form input[name="authenticity_token"]', '#editchar-form' ).val();
if ( $('#char-results').length > 0 ) { characters_fetch(); }
// --------------------------------------------
var $editchar_form = $( '#editchar-form' );
var $editchar_inputs = $( 'input.form-control', $editchar_form );
$( '#editchar-modal' ).on( 'shown.bs.modal', function () {
$editchar_form.bootstrapValidator( 'validate' );
$editchar_inputs.eq(0).focus();
} );
$editchar_form.bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh',
},
fields: {
'character[name]': {
message: 'Not valid',
validators: {
notEmpty: { message: 'Required' }
}
}
}
}).on( 'success.form.bv', function (ev) {
ev.preventDefault();
$( '#editchar-ok' ).removeAttr( 'disabled' );
});
$editchar_form.on( 'submit', function (ev) {
submit_form_via_ajax( $editchar_form,
function () {
characters_fetch();
$( '#editchar-modal' ).modal( 'hide' );
},
function () {
alert( "Error: Couldn't submit form" );
}
);
});
// --------------------------------------------
var $newchar_form = $( '#newchar-modal form' );
var $newchar_inputs = $( 'input.form-control', $newchar_form );
$( '#newchar-modal' ).on( 'show.bs.modal', function () {
$newchar_inputs.val( '' );
} );
$( '#newchar-modal' ).on( 'shown.bs.modal', function () {
$newchar_form.bootstrapValidator( 'resetForm' );
$newchar_inputs.eq(0).focus();
} );
$newchar_form.bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh',
},
fields: {
'chars[name]': {
message: 'Not valid',
validators: {
notEmpty: {
message: 'Required'
}
}
}
}
}).on( 'success.form.bv', function (ev) {
ev.preventDefault();
submit_form_via_ajax( $newchar_form,
function () {
$( '#newchar-modal' ).modal( 'hide' );
$( '#char-results' ).load( '/ajax/characters/index.html');
},
function () {
alert( "Error: Couldn't submit form" );
}
);
});
});
| gpl-2.0 |
maddy2101/TYPO3.CMS | typo3/sysext/core/Tests/Unit/Context/UserAspectTest.php | 6012 | <?php
declare(strict_types=1);
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
namespace TYPO3\CMS\Core\Tests\Unit\Context;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
use TYPO3\CMS\Core\Context\Exception\AspectPropertyNotFoundException;
use TYPO3\CMS\Core\Context\UserAspect;
use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
use TYPO3\TestingFramework\Core\Unit\UnitTestCase;
class UserAspectTest extends UnitTestCase
{
/**
* @test
*/
public function getterReturnsProperDefaultValues()
{
$subject = new UserAspect(null, null);
self::assertEquals(0, $subject->get('id'));
self::assertEquals('', $subject->get('username'));
self::assertFalse($subject->get('isLoggedIn'));
self::assertEquals([], $subject->get('groupIds'));
self::assertEquals([], $subject->get('groupNames'));
}
/**
* @test
*/
public function alternativeGroupsAreAlwaysReturned()
{
$subject = new UserAspect(null, []);
self::assertEquals([], $subject->get('groupIds'));
$subject = new UserAspect(null, [567]);
self::assertEquals([567], $subject->get('groupIds'));
}
/**
* @test
*/
public function getterReturnsValidUserId()
{
$user = new FrontendUserAuthentication();
$user->user = [
'uid' => 13
];
$subject = new UserAspect($user);
self::assertEquals(13, $subject->get('id'));
}
/**
* @test
*/
public function getterReturnsValidUsername()
{
$user = new FrontendUserAuthentication();
$user->user = [
'uid' => 13,
'username' => 'Teddy'
];
$subject = new UserAspect($user);
self::assertEquals('Teddy', $subject->get('username'));
}
/**
* @test
*/
public function isLoggedInReturnsTrueOnFrontendUserWithoutUserGroup()
{
$user = new FrontendUserAuthentication();
$user->user = [
'uid' => 13
];
$subject = new UserAspect($user);
self::assertTrue($subject->isLoggedIn());
}
/**
* @test
*/
public function isLoggedInReturnsTrueOnFrontendUserWithUserGroup()
{
$user = new FrontendUserAuthentication();
$user->user = [
'uid' => 13
];
$user->groupData['uid'] = [1, 5, 7];
$subject = new UserAspect($user);
self::assertTrue($subject->isLoggedIn());
}
/**
* @test
*/
public function isLoggedInReturnsTrueOnBackendUserWithId()
{
$user = new BackendUserAuthentication();
$user->user = [
'uid' => 13
];
$subject = new UserAspect($user);
self::assertTrue($subject->isLoggedIn());
}
/**
* @test
*/
public function getGroupIdsReturnsFrontendUserGroups()
{
$user = new FrontendUserAuthentication();
$user->user = [
'uid' => 13
];
$user->groupData['uid'] = [23, 54];
$subject = new UserAspect($user);
self::assertEquals([0, -2, 23, 54], $subject->getGroupIds());
}
/**
* @test
*/
public function getGroupIdsReturnsOverriddenGroups()
{
$user = new FrontendUserAuthentication();
// Not used, because overridden with 33
$user->groupData['uid'] = [23, 54];
$subject = new UserAspect($user, [33]);
self::assertEquals([33], $subject->getGroupIds());
}
public function isUserOrGroupSetDataProvider()
{
return [
'Not logged in: no id or group set' => [
0,
null,
null,
false
],
'only valid user id' => [
13,
null,
null,
true
],
'valid user and overridden group' => [
13,
null,
[33],
true
],
'no user and overridden group' => [
0,
null,
[33],
true
],
'valid user, default groups and overridden group' => [
13,
[23],
[33],
true
],
'no user, default groups and overridden group' => [
0,
[23],
[33],
true
],
'Not logged in: no user, and classic group structure' => [
0,
null,
[0, -1],
false
],
];
}
/**
* @test
* @dataProvider isUserOrGroupSetDataProvider
* @param $userId
* @param $userGroups
* @param $overriddenGroups
* @param bool $expectedResult
*/
public function isUserOrGroupSetChecksForValidUser($userId, $userGroups, $overriddenGroups, $expectedResult)
{
$user = new FrontendUserAuthentication();
if ($userId) {
$user->user['uid'] = $userId;
}
$user->groupData['uid'] = $userGroups;
$subject = new UserAspect($user, $overriddenGroups);
self::assertEquals($expectedResult, $subject->isUserOrGroupSet());
}
/**
* @test
*/
public function getThrowsExceptionOnInvalidArgument()
{
$this->expectException(AspectPropertyNotFoundException::class);
$this->expectExceptionCode(1529996567);
$subject = new UserAspect();
$subject->get('football');
}
}
| gpl-2.0 |
wellyyang/NovelTool | src/com/welly/noveltool/dao/po/package-info.java | 99 | /**
* ºÍÊý¾Ý¿â±í¶ÔÓ¦µÄʵÌåÀà
* @author welly-yang
*
*/
package com.welly.noveltool.dao.po; | gpl-2.0 |
V1rd/ReanEmu | src/server/game/Entities/Unit/Unit.cpp | 670339 | /*
* Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "AnticheatMgr.h"
#include "Common.h"
#include "CreatureAIImpl.h"
#include "Log.h"
#include "Opcodes.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "World.h"
#include "ObjectMgr.h"
#include "SpellMgr.h"
#include "Unit.h"
#include "QuestDef.h"
#include "Player.h"
#include "Creature.h"
#include "Spell.h"
#include "Group.h"
#include "SpellAuras.h"
#include "SpellAuraEffects.h"
#include "MapManager.h"
#include "ObjectAccessor.h"
#include "CreatureAI.h"
#include "Formulas.h"
#include "Pet.h"
#include "Util.h"
#include "Totem.h"
#include "Battleground.h"
#include "OutdoorPvP.h"
#include "InstanceSaveMgr.h"
#include "GridNotifiersImpl.h"
#include "CellImpl.h"
#include "Path.h"
#include "CreatureGroups.h"
#include "PetAI.h"
#include "PassiveAI.h"
#include "Traveller.h"
#include "TemporarySummon.h"
#include "Vehicle.h"
#include "Transport.h"
#include "InstanceScript.h"
#include "SpellInfo.h"
#include <math.h>
float baseMoveSpeed[MAX_MOVE_TYPE] =
{
2.5f, // MOVE_WALK
7.0f, // MOVE_RUN
2.5f, // MOVE_RUN_BACK
4.722222f, // MOVE_SWIM
4.5f, // MOVE_SWIM_BACK
3.141594f, // MOVE_TURN_RATE
7.0f, // MOVE_FLIGHT
4.5f, // MOVE_FLIGHT_BACK
3.14f // MOVE_PITCH_RATE
};
float playerBaseMoveSpeed[MAX_MOVE_TYPE] = {
2.5f, // MOVE_WALK
7.0f, // MOVE_RUN
2.5f, // MOVE_RUN_BACK
4.722222f, // MOVE_SWIM
4.5f, // MOVE_SWIM_BACK
3.141594f, // MOVE_TURN_RATE
7.0f, // MOVE_FLIGHT
4.5f, // MOVE_FLIGHT_BACK
3.14f // MOVE_PITCH_RATE
};
// Used for prepare can/can`t triggr aura
static bool InitTriggerAuraData();
// Define can trigger auras
static bool isTriggerAura[TOTAL_AURAS];
// Define can't trigger auras (need for disable second trigger)
static bool isNonTriggerAura[TOTAL_AURAS];
// Triggered always, even from triggered spells
static bool isAlwaysTriggeredAura[TOTAL_AURAS];
// Prepare lists
static bool procPrepared = InitTriggerAuraData();
DamageInfo::DamageInfo(Unit* _attacker, Unit* _victim, uint32 _damage, SpellInfo const* _spellInfo, SpellSchoolMask _schoolMask, DamageEffectType _damageType)
: m_attacker(_attacker), m_victim(_victim), m_damage(_damage), m_spellInfo(_spellInfo), m_schoolMask(_schoolMask),
m_damageType(_damageType), m_attackType(BASE_ATTACK)
{
m_absorb = 0;
m_resist = 0;
m_block = 0;
}
DamageInfo::DamageInfo(CalcDamageInfo& dmgInfo)
: m_attacker(dmgInfo.attacker), m_victim(dmgInfo.target), m_damage(dmgInfo.damage), m_spellInfo(NULL), m_schoolMask(SpellSchoolMask(dmgInfo.damageSchoolMask)),
m_damageType(DIRECT_DAMAGE), m_attackType(dmgInfo.attackType)
{
m_absorb = 0;
m_resist = 0;
m_block = 0;
}
void DamageInfo::ModifyDamage(int32 amount)
{
amount = std::min(amount, int32(GetDamage()));
m_damage += amount;
}
void DamageInfo::AbsorbDamage(uint32 amount)
{
amount = std::min(amount, GetDamage());
m_absorb += amount;
m_damage -= amount;
}
void DamageInfo::ResistDamage(uint32 amount)
{
amount = std::min(amount, GetDamage());
m_resist += amount;
m_damage -= amount;
}
void DamageInfo::BlockDamage(uint32 amount)
{
amount = std::min(amount, GetDamage());
m_block += amount;
m_damage -= amount;
}
ProcEventInfo::ProcEventInfo(Unit* actor, Unit* actionTarget, Unit* procTarget, uint32 typeMask, uint32 spellTypeMask, uint32 spellPhaseMask, uint32 hitMask, Spell* spell, DamageInfo* damageInfo, HealInfo* healInfo)
:_actor(actor), _actionTarget(actionTarget), _procTarget(procTarget), _typeMask(typeMask), _spellTypeMask(spellTypeMask), _spellPhaseMask(spellPhaseMask),
_hitMask(hitMask), _spell(spell), _damageInfo(damageInfo), _healInfo(healInfo)
{
}
// we can disable this warning for this since it only
// causes undefined behavior when passed to the base class constructor
#ifdef _MSC_VER
#pragma warning(disable:4355)
#endif
Unit::Unit(): WorldObject(),
m_movedPlayer(NULL), m_lastSanctuaryTime(0), IsAIEnabled(false), NeedChangeAI(false),
m_ControlledByPlayer(false), i_AI(NULL), i_disabledAI(NULL), m_procDeep(0),
m_removedAurasCount(0), i_motionMaster(this), m_ThreatManager(this), m_vehicle(NULL),
m_vehicleKit(NULL), m_unitTypeMask(UNIT_MASK_NONE), m_HostileRefManager(this)
{
#ifdef _MSC_VER
#pragma warning(default:4355)
#endif
m_objectType |= TYPEMASK_UNIT;
m_objectTypeId = TYPEID_UNIT;
m_updateFlag = (UPDATEFLAG_HIGHGUID | UPDATEFLAG_LIVING | UPDATEFLAG_HAS_POSITION);
m_attackTimer[BASE_ATTACK] = 0;
m_attackTimer[OFF_ATTACK] = 0;
m_attackTimer[RANGED_ATTACK] = 0;
m_modAttackSpeedPct[BASE_ATTACK] = 1.0f;
m_modAttackSpeedPct[OFF_ATTACK] = 1.0f;
m_modAttackSpeedPct[RANGED_ATTACK] = 1.0f;
m_extraAttacks = 0;
m_canDualWield = false;
m_rootTimes = 0;
m_state = 0;
m_deathState = ALIVE;
for (uint8 i = 0; i < CURRENT_MAX_SPELL; ++i)
m_currentSpells[i] = NULL;
m_addDmgOnce = 0;
for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i)
m_SummonSlot[i] = 0;
for (uint8 i = 0; i < MAX_GAMEOBJECT_SLOT; ++i)
m_ObjectSlot[i] = 0;
m_auraUpdateIterator = m_ownedAuras.end();
m_interruptMask = 0;
m_transform = 0;
m_canModifyStats = false;
for (uint8 i = 0; i < MAX_SPELL_IMMUNITY; ++i)
m_spellImmune[i].clear();
for (uint8 i = 0; i < UNIT_MOD_END; ++i)
{
m_auraModifiersGroup[i][BASE_VALUE] = 0.0f;
m_auraModifiersGroup[i][BASE_PCT] = 1.0f;
m_auraModifiersGroup[i][TOTAL_VALUE] = 0.0f;
m_auraModifiersGroup[i][TOTAL_PCT] = 1.0f;
}
// implement 50% base damage from offhand
m_auraModifiersGroup[UNIT_MOD_DAMAGE_OFFHAND][TOTAL_PCT] = 0.5f;
for (uint8 i = 0; i < MAX_ATTACK; ++i)
{
m_weaponDamage[i][MINDAMAGE] = BASE_MINDAMAGE;
m_weaponDamage[i][MAXDAMAGE] = BASE_MAXDAMAGE;
}
for (uint8 i = 0; i < MAX_STATS; ++i)
m_createStats[i] = 0.0f;
m_attacking = NULL;
m_modMeleeHitChance = 0.0f;
m_modRangedHitChance = 0.0f;
m_modSpellHitChance = 0.0f;
m_baseSpellCritChance = 5;
m_CombatTimer = 0;
m_lastManaUse = 0;
for (uint8 i = 0; i < MAX_SPELL_SCHOOL; ++i)
m_threatModifier[i] = 1.0f;
m_isSorted = true;
for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i)
m_speed_rate[i] = 1.0f;
m_charmInfo = NULL;
m_reducedThreatPercent = 0;
m_misdirectionTargetGUID = 0;
// remove aurastates allowing special moves
for (uint8 i = 0; i < MAX_REACTIVE; ++i)
m_reactiveTimer[i] = 0;
m_cleanupDone = false;
m_duringRemoveFromWorld = false;
m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_ALIVE);
_focusSpell = NULL;
_targetLocked = false;
}
////////////////////////////////////////////////////////////
// Methods of class GlobalCooldownMgr
bool GlobalCooldownMgr::HasGlobalCooldown(SpellInfo const* spellInfo) const
{
GlobalCooldownList::const_iterator itr = m_GlobalCooldowns.find(spellInfo->StartRecoveryCategory);
return itr != m_GlobalCooldowns.end() && itr->second.duration && getMSTimeDiff(itr->second.cast_time, getMSTime()) < itr->second.duration;
}
void GlobalCooldownMgr::AddGlobalCooldown(SpellInfo const* spellInfo, uint32 gcd)
{
m_GlobalCooldowns[spellInfo->StartRecoveryCategory] = GlobalCooldown(gcd, getMSTime());
}
void GlobalCooldownMgr::CancelGlobalCooldown(SpellInfo const* spellInfo)
{
m_GlobalCooldowns[spellInfo->StartRecoveryCategory].duration = 0;
}
////////////////////////////////////////////////////////////
// Methods of class Unit
Unit::~Unit()
{
// set current spells as deletable
for (uint8 i = 0; i < CURRENT_MAX_SPELL; ++i)
if (m_currentSpells[i])
{
m_currentSpells[i]->SetReferencedFromCurrent(false);
m_currentSpells[i] = NULL;
}
_DeleteRemovedAuras();
delete m_charmInfo;
delete m_vehicleKit;
ASSERT(!m_duringRemoveFromWorld);
ASSERT(!m_attacking);
ASSERT(m_attackers.empty());
ASSERT(m_sharedVision.empty());
ASSERT(m_Controlled.empty());
ASSERT(m_appliedAuras.empty());
ASSERT(m_ownedAuras.empty());
ASSERT(m_removedAuras.empty());
ASSERT(m_gameObj.empty());
ASSERT(m_dynObj.empty());
}
void Unit::Update(uint32 p_time)
{
// WARNING! Order of execution here is important, do not change.
// Spells must be processed with event system BEFORE they go to _UpdateSpells.
// Or else we may have some SPELL_STATE_FINISHED spells stalled in pointers, that is bad.
m_Events.Update(p_time);
if (!IsInWorld())
return;
_UpdateSpells(p_time);
// If this is set during update SetCantProc(false) call is missing somewhere in the code
// Having this would prevent spells from being proced, so let's crash
ASSERT(!m_procDeep);
if (CanHaveThreatList() && getThreatManager().isNeedUpdateToClient(p_time))
SendThreatListUpdate();
// update combat timer only for players and pets (only pets with PetAI)
if (isInCombat() && (GetTypeId() == TYPEID_PLAYER || (ToCreature()->isPet() && IsControlledByPlayer())))
{
// Check UNIT_STAT_MELEE_ATTACKING or UNIT_STAT_CHASE (without UNIT_STAT_FOLLOW in this case) so pets can reach far away
// targets without stopping half way there and running off.
// These flags are reset after target dies or another command is given.
if (m_HostileRefManager.isEmpty())
{
// m_CombatTimer set at aura start and it will be freeze until aura removing
if (m_CombatTimer <= p_time)
ClearInCombat();
else
m_CombatTimer -= p_time;
}
}
// not implemented before 3.0.2
if (uint32 base_att = getAttackTimer(BASE_ATTACK))
setAttackTimer(BASE_ATTACK, (p_time >= base_att ? 0 : base_att - p_time));
if (uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time));
if (uint32 off_att = getAttackTimer(OFF_ATTACK))
setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time));
// update abilities available only for fraction of time
UpdateReactives(p_time);
if (isAlive())
{
ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, HealthBelowPct(20));
ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, HealthBelowPct(35));
ModifyAuraState(AURA_STATE_HEALTH_ABOVE_75_PERCENT, HealthAbovePct(75));
}
i_motionMaster.UpdateMotion(p_time);
}
bool Unit::haveOffhandWeapon() const
{
if (GetTypeId() == TYPEID_PLAYER)
return ToPlayer()->GetWeaponForAttack(OFF_ATTACK, true);
else
return m_canDualWield;
}
void Unit::SendMonsterMoveWithSpeedToCurrentDestination(Player* player)
{
float x, y, z;
if (GetMotionMaster()->GetDestination(x, y, z))
SendMonsterMoveWithSpeed(x, y, z, 0, player);
}
void Unit::SendMonsterMoveWithSpeed(float x, float y, float z, uint32 transitTime, Player* player)
{
if (!transitTime)
{
if (GetTypeId() == TYPEID_PLAYER)
{
Traveller<Player> traveller(*(Player*)this);
transitTime = traveller.GetTotalTrevelTimeTo(x, y, z);
}
else
{
Traveller<Creature> traveller(*ToCreature());
transitTime = traveller.GetTotalTrevelTimeTo(x, y, z);
}
}
//float orientation = (float)atan2((double)dy, (double)dx);
SendMonsterMove(x, y, z, transitTime, player);
}
void Unit::SetFacing(float ori, WorldObject* obj)
{
SetOrientation(obj ? GetAngle(obj) : ori);
WorldPacket data(SMSG_MONSTER_MOVE, (1+12+4+1+(obj ? 8 : 4)+4+4+4+12+GetPackGUID().size()));
data.append(GetPackGUID());
data << uint8(0); // unk
data << GetPositionX() << GetPositionY() << GetPositionZ();
data << getMSTime();
if (obj)
{
data << uint8(SPLINETYPE_FACING_TARGET);
data << uint64(obj->GetGUID());
}
else
{
data << uint8(SPLINETYPE_FACING_ANGLE);
data << ori;
}
data << uint32(SPLINEFLAG_NONE);
data << uint32(0); // move time 0
data << uint32(1); // one point
data << GetPositionX() << GetPositionY() << GetPositionZ();
SendMessageToSet(&data, true);
}
void Unit::SendMonsterStop(bool on_death)
{
WorldPacket data(SMSG_MONSTER_MOVE, (17 + GetPackGUID().size()));
data.append(GetPackGUID());
data << uint8(0); // new in 3.1
data << GetPositionX() << GetPositionY() << GetPositionZ();
data << getMSTime();
if (on_death == true)
{
data << uint8(0);
data << uint32((GetUnitMovementFlags() & MOVEMENTFLAG_LEVITATING) ? SPLINEFLAG_FLYING : SPLINEFLAG_WALKING);
data << uint32(0); // Time in between points
data << uint32(1); // 1 single waypoint
data << GetPositionX() << GetPositionY() << GetPositionZ();
}
else
data << uint8(1);
SendMessageToSet(&data, true);
ClearUnitState(UNIT_STAT_MOVE);
}
void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint32 Time, Player* player)
{
WorldPacket data(SMSG_MONSTER_MOVE, 1+12+4+1+4+4+4+12+GetPackGUID().size());
data.append(GetPackGUID());
data << uint8(0); // new in 3.1
data << GetPositionX() << GetPositionY() << GetPositionZ();
data << getMSTime();
data << uint8(0);
data << uint32((GetUnitMovementFlags() & MOVEMENTFLAG_LEVITATING) ? SPLINEFLAG_FLYING : SPLINEFLAG_WALKING);
data << Time; // Time in between points
data << uint32(1); // 1 single waypoint
data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
if (player)
player->GetSession()->SendPacket(&data);
else
SendMessageToSet(&data, true);
AddUnitState(UNIT_STAT_MOVE);
}
void Unit::SendMonsterMove(MonsterMoveData const& moveData, Player* player)
{
WorldPacket data(SMSG_MONSTER_MOVE, GetPackGUID().size() + 1 + 12 + 4 + 1 + 4 + 8 + 4 + 4 + 12);
data.append(GetPackGUID());
data << uint8(0); // new in 3.1
data << GetPositionX() << GetPositionY() << GetPositionZ();
data << getMSTime();
data << uint8(0);
data << moveData.SplineFlag;
if (moveData.SplineFlag & SPLINEFLAG_ANIMATIONTIER)
{
data << uint8(moveData.AnimationState);
data << uint32(0);
}
data << moveData.Time;
if (moveData.SplineFlag & SPLINEFLAG_TRAJECTORY)
{
data << moveData.SpeedZ;
data << uint32(0); // walk time after jump
}
data << uint32(1); // waypoint count
data << moveData.DestLocation.GetPositionX();
data << moveData.DestLocation.GetPositionY();
data << moveData.DestLocation.GetPositionZ();
if (player)
player->GetSession()->SendPacket(&data);
else
SendMessageToSet(&data, true);
}
void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint32 MoveFlags, uint32 time, float speedZ, Player* player)
{
MonsterMoveData data;
data.DestLocation.Relocate(NewPosX, NewPosY, NewPosZ);
data.SplineFlag = MoveFlags;
data.Time = time;
data.SpeedZ = speedZ;
SendMonsterMove(data, player);
}
void Unit::SendMonsterMoveExitVehicle(Position const* newPos)
{
WorldPacket data(SMSG_MONSTER_MOVE, 1+12+4+1+4+4+4+12+GetPackGUID().size());
data.append(GetPackGUID());
data << uint8(GetTypeId() == TYPEID_PLAYER ? 1 : 0); // new in 3.1, bool
data << GetPositionX() << GetPositionY() << GetPositionZ();
data << getMSTime();
data << uint8(SPLINETYPE_FACING_ANGLE);
data << float(GetOrientation()); // guess
data << uint32(SPLINEFLAG_EXIT_VEHICLE);
data << uint32(0); // Time in between points
data << uint32(1); // 1 single waypoint
data << newPos->GetPositionX();
data << newPos->GetPositionY();
data << newPos->GetPositionZ();
SendMessageToSet(&data, true);
}
void Unit::SendMonsterMoveTransport(Unit* vehicleOwner)
{
// TODO: Turn into BuildMonsterMoveTransport packet and allow certain variables (for npc movement aboard vehicles)
WorldPacket data(SMSG_MONSTER_MOVE_TRANSPORT, GetPackGUID().size()+vehicleOwner->GetPackGUID().size() + 47);
data.append(GetPackGUID());
data.append(vehicleOwner->GetPackGUID());
data << int8(GetTransSeat());
data << uint8(GetTypeId() == TYPEID_PLAYER ? 1 : 0); // boolean
data << GetPositionX() - vehicleOwner->GetPositionX();
data << GetPositionY() - vehicleOwner->GetPositionY();
data << GetPositionZ() - vehicleOwner->GetPositionZ();
data << uint32(getMSTime()); // should be an increasing constant that indicates movement packet count
data << uint8(SPLINETYPE_FACING_ANGLE);
data << GetTransOffsetO(); // facing angle?
data << uint32(SPLINEFLAG_TRANSPORT);
data << uint32(GetTransTime()); // move time
data << uint32(1); // amount of waypoints
data << uint32(0); // waypoint X
data << uint32(0); // waypoint Y
data << uint32(0); // waypoint Z
SendMessageToSet(&data, true);
}
void Unit::resetAttackTimer(WeaponAttackType type)
{
m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]);
}
bool Unit::IsWithinCombatRange(const Unit* obj, float dist2compare) const
{
if (!obj || !IsInMap(obj)) return false;
float dx = GetPositionX() - obj->GetPositionX();
float dy = GetPositionY() - obj->GetPositionY();
float dz = GetPositionZ() - obj->GetPositionZ();
float distsq = dx * dx + dy * dy + dz * dz;
float sizefactor = GetCombatReach() + obj->GetCombatReach();
float maxdist = dist2compare + sizefactor;
return distsq < maxdist * maxdist;
}
bool Unit::IsWithinMeleeRange(const Unit* obj, float dist) const
{
if (!obj || !IsInMap(obj)) return false;
float dx = GetPositionX() - obj->GetPositionX();
float dy = GetPositionY() - obj->GetPositionY();
float dz = GetPositionZ() - obj->GetPositionZ();
float distsq = dx*dx + dy*dy + dz*dz;
float sizefactor = GetMeleeReach() + obj->GetMeleeReach();
float maxdist = dist + sizefactor;
return distsq < maxdist * maxdist;
}
void Unit::GetRandomContactPoint(const Unit* obj, float &x, float &y, float &z, float distance2dMin, float distance2dMax) const
{
float combat_reach = GetCombatReach();
if (combat_reach < 0.1f) // sometimes bugged for players
combat_reach = DEFAULT_COMBAT_REACH;
uint32 attacker_number = getAttackers().size();
if (attacker_number > 0)
--attacker_number;
GetNearPoint(obj, x, y, z, obj->GetCombatReach(), distance2dMin+(distance2dMax-distance2dMin) * (float)rand_norm()
, GetAngle(obj) + (attacker_number ? (static_cast<float>(M_PI/2) - static_cast<float>(M_PI) * (float)rand_norm()) * float(attacker_number) / combat_reach * 0.3f : 0));
}
void Unit::UpdateInterruptMask()
{
m_interruptMask = 0;
for (AuraApplicationList::const_iterator i = m_interruptableAuras.begin(); i != m_interruptableAuras.end(); ++i)
m_interruptMask |= (*i)->GetBase()->GetSpellInfo()->AuraInterruptFlags;
if (Spell* spell = m_currentSpells[CURRENT_CHANNELED_SPELL])
if (spell->getState() == SPELL_STATE_CASTING)
m_interruptMask |= spell->m_spellInfo->ChannelInterruptFlags;
}
bool Unit::HasAuraTypeWithFamilyFlags(AuraType auraType, uint32 familyName, uint32 familyFlags) const
{
if (!HasAuraType(auraType))
return false;
AuraEffectList const& auras = GetAuraEffectsByType(auraType);
for (AuraEffectList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
if (SpellInfo const* iterSpellProto = (*itr)->GetSpellInfo())
if (iterSpellProto->SpellFamilyName == familyName && iterSpellProto->SpellFamilyFlags[0] & familyFlags)
return true;
return false;
}
void Unit::DealDamageMods(Unit* victim, uint32 &damage, uint32* absorb)
{
if (!victim || !victim->isAlive() || victim->HasUnitState(UNIT_STAT_IN_FLIGHT) || (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsInEvadeMode()))
{
if (absorb)
*absorb += damage;
damage = 0;
return;
}
uint32 originalDamage = damage;
if (absorb && originalDamage > damage)
*absorb += (originalDamage - damage);
}
uint32 Unit::DealDamage(Unit* victim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellInfo const* spellProto, bool durabilityLoss)
{
if (victim->IsAIEnabled)
victim->GetAI()->DamageTaken(this, damage);
if (IsAIEnabled)
GetAI()->DamageDealt(victim, damage, damagetype);
if (damagetype != NODAMAGE)
{
// interrupting auras with AURA_INTERRUPT_FLAG_DAMAGE before checking !damage (absorbed damage breaks that type of auras)
if (spellProto)
{
if (!(spellProto->AttributesEx4 & SPELL_ATTR4_DAMAGE_DOESNT_BREAK_AURAS))
victim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TAKE_DAMAGE, spellProto->Id);
}
else
victim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TAKE_DAMAGE, 0);
// We're going to call functions which can modify content of the list during iteration over it's elements
// Let's copy the list so we can prevent iterator invalidation
AuraEffectList vCopyDamageCopy(victim->GetAuraEffectsByType(SPELL_AURA_SHARE_DAMAGE_PCT));
// copy damage to casters of this aura
for (AuraEffectList::iterator i = vCopyDamageCopy.begin(); i != vCopyDamageCopy.end(); ++i)
{
// Check if aura was removed during iteration - we don't need to work on such auras
if (!((*i)->GetBase()->IsAppliedOnTarget(victim->GetGUID())))
continue;
// check damage school mask
if (((*i)->GetMiscValue() & damageSchoolMask) == 0)
continue;
Unit* shareDamageTarget = (*i)->GetCaster();
if (!shareDamageTarget)
continue;
SpellInfo const* spell = (*i)->GetSpellInfo();
uint32 share = CalculatePctN(damage, (*i)->GetAmount());
// TODO: check packets if damage is done by victim, or by attacker of victim
DealDamageMods(shareDamageTarget, share, NULL);
DealDamage(shareDamageTarget, share, NULL, NODAMAGE, spell->GetSchoolMask(), spell, false);
}
}
// Rage from Damage made (only from direct weapon damage)
if (cleanDamage && damagetype == DIRECT_DAMAGE && this != victim && getPowerType() == POWER_RAGE)
{
uint32 weaponSpeedHitFactor;
uint32 rage_damage = damage + cleanDamage->absorbed_damage;
switch (cleanDamage->attackType)
{
case BASE_ATTACK:
{
weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType) / 1000.0f * 3.5f);
if (cleanDamage->hitOutCome == MELEE_HIT_CRIT)
weaponSpeedHitFactor *= 2;
RewardRage(rage_damage, weaponSpeedHitFactor, true);
break;
}
case OFF_ATTACK:
{
weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType) / 1000.0f * 1.75f);
if (cleanDamage->hitOutCome == MELEE_HIT_CRIT)
weaponSpeedHitFactor *= 2;
RewardRage(rage_damage, weaponSpeedHitFactor, true);
break;
}
case RANGED_ATTACK:
break;
default:
break;
}
}
if (!damage)
{
// Rage from absorbed damage
if (cleanDamage && cleanDamage->absorbed_damage && victim->getPowerType() == POWER_RAGE)
victim->RewardRage(cleanDamage->absorbed_damage, 0, false);
return 0;
}
sLog->outStaticDebug("DealDamageStart");
uint32 health = victim->GetHealth();
sLog->outDetail("deal dmg:%d to health:%d ", damage, health);
// duel ends when player has 1 or less hp
bool duel_hasEnded = false;
if (victim->GetTypeId() == TYPEID_PLAYER && victim->ToPlayer()->duel && damage >= (health-1))
{
// prevent kill only if killed in duel and killed by opponent or opponent controlled creature
if (victim->ToPlayer()->duel->opponent == this || victim->ToPlayer()->duel->opponent->GetGUID() == GetOwnerGUID())
damage = health - 1;
duel_hasEnded = true;
}
if (GetTypeId() == TYPEID_PLAYER && this != victim)
{
Player* killer = ToPlayer();
// in bg, count dmg if victim is also a player
if (victim->GetTypeId() == TYPEID_PLAYER)
{
if (Battleground* bg = killer->GetBattleground())
{
bg->UpdatePlayerScore(killer, SCORE_DAMAGE_DONE, damage);
/** World of Warcraft Armory **/
if (Battleground *bgV = ((Player*)victim)->GetBattleground())
bgV->UpdatePlayerScore(((Player*)victim), SCORE_DAMAGE_TAKEN, damage);
/** World of Warcraft Armory **/
}
}
killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE, damage, 0, victim);
killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT, damage);
}
if (victim->GetTypeId() == TYPEID_PLAYER)
victim->ToPlayer()->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED, damage);
else if (!victim->IsControlledByPlayer() || victim->IsVehicle())
{
if (!victim->ToCreature()->hasLootRecipient())
victim->ToCreature()->SetLootRecipient(this);
if (IsControlledByPlayer())
victim->ToCreature()->LowerPlayerDamageReq(health < damage ? health : damage);
}
if (health <= damage)
{
sLog->outStaticDebug("DealDamage: victim just died");
if (victim->GetTypeId() == TYPEID_PLAYER && victim != this)
{
victim->ToPlayer()->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, health);
// call before auras are removed
if (Player* killer = GetCharmerOrOwnerPlayerOrPlayerItself())
killer->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL, 1, 0, victim);
}
Kill(victim, durabilityLoss);
}
else
{
sLog->outStaticDebug("DealDamageAlive");
if (victim->GetTypeId() == TYPEID_PLAYER)
victim->ToPlayer()->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, damage);
victim->ModifyHealth(- (int32)damage);
if (damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE)
victim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DIRECT_DAMAGE, spellProto ? spellProto->Id : 0);
if (victim->GetTypeId() != TYPEID_PLAYER)
victim->AddThreat(this, float(damage), damageSchoolMask, spellProto);
else // victim is a player
{
// random durability for items (HIT TAKEN)
if (roll_chance_f(sWorld->getRate(RATE_DURABILITY_LOSS_DAMAGE)))
{
EquipmentSlots slot = EquipmentSlots(urand(0, EQUIPMENT_SLOT_END-1));
victim->ToPlayer()->DurabilityPointLossForEquipSlot(slot);
}
}
// Rage from damage received
if (this != victim && victim->getPowerType() == POWER_RAGE)
{
uint32 rage_damage = damage + (cleanDamage ? cleanDamage->absorbed_damage : 0);
victim->RewardRage(rage_damage, 0, false);
}
if (GetTypeId() == TYPEID_PLAYER)
{
// random durability for items (HIT DONE)
if (roll_chance_f(sWorld->getRate(RATE_DURABILITY_LOSS_DAMAGE)))
{
EquipmentSlots slot = EquipmentSlots(urand(0, EQUIPMENT_SLOT_END-1));
ToPlayer()->DurabilityPointLossForEquipSlot(slot);
}
}
if (damagetype != NODAMAGE && damage)
{
if (victim != this && victim->GetTypeId() == TYPEID_PLAYER) // does not support creature push_back
{
if (damagetype != DOT)
if (Spell* spell = victim->m_currentSpells[CURRENT_GENERIC_SPELL])
if (spell->getState() == SPELL_STATE_PREPARING)
{
uint32 interruptFlags = spell->m_spellInfo->InterruptFlags;
if (interruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG)
victim->InterruptNonMeleeSpells(false);
else if (interruptFlags & SPELL_INTERRUPT_FLAG_PUSH_BACK)
spell->Delayed();
}
if (Spell* spell = victim->m_currentSpells[CURRENT_CHANNELED_SPELL])
if (spell->getState() == SPELL_STATE_CASTING)
{
uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags;
if (((channelInterruptFlags & CHANNEL_FLAG_DELAY) != 0) && (damagetype != DOT))
spell->DelayedChannel();
}
}
}
// last damage from duel opponent
if (duel_hasEnded)
{
ASSERT(victim->GetTypeId() == TYPEID_PLAYER);
Player* he = victim->ToPlayer();
ASSERT(he->duel);
he->SetHealth(1);
he->duel->opponent->CombatStopWithPets(true);
he->CombatStopWithPets(true);
he->CastSpell(he, 7267, true); // beg
he->DuelComplete(DUEL_WON);
}
}
sLog->outStaticDebug("DealDamageEnd returned %d damage", damage);
return damage;
}
void Unit::CastStop(uint32 except_spellid)
{
for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id != except_spellid)
InterruptSpell(CurrentSpellTypes(i), false);
}
void Unit::CastSpell(SpellCastTargets const& targets, SpellInfo const* spellInfo, CustomSpellValues const* value, TriggerCastFlags triggerFlags, Item* castItem, AuraEffect const* triggeredByAura, uint64 originalCaster)
{
if (!spellInfo)
{
sLog->outError("CastSpell: unknown spell by caster: %s %u)", (GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"), (GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
return;
}
// TODO: this is a workaround and needs removal
if (!originalCaster && GetTypeId() == TYPEID_UNIT && ToCreature()->isTotem() && IsControlledByPlayer())
if (Unit* owner = GetOwner())
originalCaster=owner->GetGUID();
// TODO: this is a workaround - not needed anymore, but required for some scripts :(
if (!originalCaster && triggeredByAura)
originalCaster = triggeredByAura->GetCasterGUID();
Spell* spell = new Spell(this, spellInfo, triggerFlags, originalCaster);
if (value)
for (CustomSpellValues::const_iterator itr = value->begin(); itr != value->end(); ++itr)
spell->SetSpellValue(itr->first, itr->second);
spell->m_CastItem = castItem;
spell->prepare(&targets, triggeredByAura);
}
void Unit::CastSpell(Unit* victim, uint32 spellId, bool triggered, Item* castItem, AuraEffect const* triggeredByAura, uint64 originalCaster)
{
CastSpell(victim, spellId, triggered ? TRIGGERED_FULL_MASK : TRIGGERED_NONE, castItem, triggeredByAura, originalCaster);
}
void Unit::CastSpell(Unit* victim, uint32 spellId, TriggerCastFlags triggerFlags /*= TRIGGER_NONE*/, Item* castItem /*= NULL*/, AuraEffect const* triggeredByAura /*= NULL*/, uint64 originalCaster /*= 0*/)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo)
{
sLog->outError("CastSpell: unknown spell id %u by caster: %s %u)", spellId, (GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"), (GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
return;
}
CastSpell(victim, spellInfo, triggerFlags, castItem, triggeredByAura, originalCaster);
}
void Unit::CastSpell(Unit* victim, SpellInfo const* spellInfo, bool triggered, Item* castItem/*= NULL*/, AuraEffect const* triggeredByAura /*= NULL*/, uint64 originalCaster /*= 0*/)
{
CastSpell(victim, spellInfo, triggered ? TRIGGERED_FULL_MASK : TRIGGERED_NONE, castItem, triggeredByAura, originalCaster);
}
void Unit::CastSpell(Unit* victim, SpellInfo const* spellInfo, TriggerCastFlags triggerFlags, Item* castItem, AuraEffect const* triggeredByAura, uint64 originalCaster)
{
SpellCastTargets targets;
targets.SetUnitTarget(victim);
CastSpell(targets, spellInfo, NULL, triggerFlags, castItem, triggeredByAura, originalCaster);
}
void Unit::CastCustomSpell(Unit* target, uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item* castItem, AuraEffect const* triggeredByAura, uint64 originalCaster)
{
CustomSpellValues values;
if (bp0)
values.AddSpellMod(SPELLVALUE_BASE_POINT0, *bp0);
if (bp1)
values.AddSpellMod(SPELLVALUE_BASE_POINT1, *bp1);
if (bp2)
values.AddSpellMod(SPELLVALUE_BASE_POINT2, *bp2);
CastCustomSpell(spellId, values, target, triggered, castItem, triggeredByAura, originalCaster);
}
void Unit::CastCustomSpell(uint32 spellId, SpellValueMod mod, int32 value, Unit* target, bool triggered, Item* castItem, AuraEffect const* triggeredByAura, uint64 originalCaster)
{
CustomSpellValues values;
values.AddSpellMod(mod, value);
CastCustomSpell(spellId, values, target, triggered, castItem, triggeredByAura, originalCaster);
}
void Unit::CastCustomSpell(uint32 spellId, CustomSpellValues const& value, Unit* victim, bool triggered, Item* castItem, AuraEffect const* triggeredByAura, uint64 originalCaster)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo)
{
sLog->outError("CastSpell: unknown spell id %u by caster: %s %u)", spellId, (GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"), (GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
return;
}
SpellCastTargets targets;
targets.SetUnitTarget(victim);
CastSpell(targets, spellInfo, &value, triggered ? TRIGGERED_FULL_MASK : TRIGGERED_NONE, castItem, triggeredByAura, originalCaster);
}
void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item* castItem, AuraEffect const* triggeredByAura, uint64 originalCaster)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo)
{
sLog->outError("CastSpell: unknown spell id %u by caster: %s %u)", spellId, (GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"), (GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
return;
}
SpellCastTargets targets;
targets.SetDst(x, y, z, GetOrientation());
CastSpell(targets, spellInfo, NULL, triggered ? TRIGGERED_FULL_MASK : TRIGGERED_NONE, castItem, triggeredByAura, originalCaster);
}
void Unit::CastSpell(GameObject* go, uint32 spellId, bool triggered, Item* castItem, AuraEffect* triggeredByAura, uint64 originalCaster)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo)
{
sLog->outError("CastSpell: unknown spell id %u by caster: %s %u)", spellId, (GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"), (GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
return;
}
SpellCastTargets targets;
targets.SetGOTarget(go);
CastSpell(targets, spellInfo, NULL, triggered ? TRIGGERED_FULL_MASK : TRIGGERED_NONE, castItem, triggeredByAura, originalCaster);
}
// Obsolete func need remove, here only for comotability vs another patches
uint32 Unit::SpellNonMeleeDamageLog(Unit* victim, uint32 spellID, uint32 damage)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellID);
SpellNonMeleeDamage damageInfo(this, victim, spellInfo->Id, spellInfo->SchoolMask);
damage = SpellDamageBonus(victim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
CalculateSpellDamageTaken(&damageInfo, damage, spellInfo);
DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb);
SendSpellNonMeleeDamageLog(&damageInfo);
DealSpellDamage(&damageInfo, true);
return damageInfo.damage;
}
void Unit::CalculateSpellDamageTaken(SpellNonMeleeDamage* damageInfo, int32 damage, SpellInfo const* spellInfo, WeaponAttackType attackType, bool crit)
{
if (damage < 0)
return;
Unit* victim = damageInfo->target;
if (!victim || !victim->isAlive())
return;
SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask);
uint32 crTypeMask = victim->GetCreatureTypeMask();
if (IsDamageReducedByArmor(damageSchoolMask, spellInfo))
damage = CalcArmorReducedDamage(victim, damage, spellInfo, attackType);
bool blocked = false;
// Per-school calc
switch (spellInfo->DmgClass)
{
// Melee and Ranged Spells
case SPELL_DAMAGE_CLASS_RANGED:
case SPELL_DAMAGE_CLASS_MELEE:
{
// Physical Damage
if (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL)
{
// Get blocked status
blocked = isSpellBlocked(victim, spellInfo, attackType);
}
if (crit)
{
damageInfo->HitInfo |= SPELL_HIT_TYPE_CRIT;
// Calculate crit bonus
uint32 crit_bonus = damage;
// Apply crit_damage bonus for melee spells
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
damage += crit_bonus;
// Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
float critPctDamageMod = 0.0f;
if (attackType == RANGED_ATTACK)
critPctDamageMod += victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
else
critPctDamageMod += victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
// Increase crit damage from SPELL_AURA_MOD_CRIT_DAMAGE_BONUS
critPctDamageMod += (GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS, spellInfo->GetSchoolMask()) - 1.0f) * 100;
// Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
if (critPctDamageMod != 0)
AddPctF(damage, critPctDamageMod);
}
// Spell weapon based damage CAN BE crit & blocked at same time
if (blocked)
{
damageInfo->blocked = victim->GetShieldBlockValue();
// double blocked amount if block is critical
if (victim->isBlockCritical())
damageInfo->blocked += damageInfo->blocked;
if (damage < int32(damageInfo->blocked))
damageInfo->blocked = uint32(damage);
damage -= damageInfo->blocked;
}
if (attackType != RANGED_ATTACK)
ApplyResilience(victim, NULL, &damage, crit, CR_CRIT_TAKEN_MELEE);
else
ApplyResilience(victim, NULL, &damage, crit, CR_CRIT_TAKEN_RANGED);
break;
}
// Magical Attacks
case SPELL_DAMAGE_CLASS_NONE:
case SPELL_DAMAGE_CLASS_MAGIC:
{
// If crit add critical bonus
if (crit)
{
damageInfo->HitInfo |= SPELL_HIT_TYPE_CRIT;
damage = SpellCriticalDamageBonus(spellInfo, damage, victim);
}
ApplyResilience(victim, NULL, &damage, crit, CR_CRIT_TAKEN_SPELL);
break;
}
default:
break;
}
// Calculate absorb resist
if (damage > 0)
{
CalcAbsorbResist(victim, damageSchoolMask, SPELL_DIRECT_DAMAGE, damage, &damageInfo->absorb, &damageInfo->resist, spellInfo);
damage -= damageInfo->absorb + damageInfo->resist;
}
else
damage = 0;
damageInfo->damage = damage;
}
void Unit::DealSpellDamage(SpellNonMeleeDamage* damageInfo, bool durabilityLoss)
{
if (damageInfo == 0)
return;
Unit* victim = damageInfo->target;
if (!victim)
return;
if (!victim->isAlive() || victim->HasUnitState(UNIT_STAT_IN_FLIGHT) || (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsInEvadeMode()))
return;
SpellInfo const* spellProto = sSpellMgr->GetSpellInfo(damageInfo->SpellID);
if (spellProto == NULL)
{
sLog->outDebug(LOG_FILTER_UNITS, "Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID);
return;
}
// Call default DealDamage
CleanDamage cleanDamage(damageInfo->cleanDamage, damageInfo->absorb, BASE_ATTACK, MELEE_HIT_NORMAL);
DealDamage(victim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss);
}
// TODO for melee need create structure as in
void Unit::CalculateMeleeDamage(Unit* victim, uint32 damage, CalcDamageInfo* damageInfo, WeaponAttackType attackType)
{
damageInfo->attacker = this;
damageInfo->target = victim;
damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask();
damageInfo->attackType = attackType;
damageInfo->damage = 0;
damageInfo->cleanDamage = 0;
damageInfo->absorb = 0;
damageInfo->resist = 0;
damageInfo->blocked_amount = 0;
damageInfo->TargetState = 0;
damageInfo->HitInfo = 0;
damageInfo->procAttacker = PROC_FLAG_NONE;
damageInfo->procVictim = PROC_FLAG_NONE;
damageInfo->procEx = PROC_EX_NONE;
damageInfo->hitOutCome = MELEE_HIT_EVADE;
if (!victim)
return;
if (!isAlive() || !victim->isAlive())
return;
// Select HitInfo/procAttacker/procVictim flag based on attack type
switch (attackType)
{
case BASE_ATTACK:
damageInfo->procAttacker = PROC_FLAG_DONE_MELEE_AUTO_ATTACK | PROC_FLAG_DONE_MAINHAND_ATTACK;
damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_AUTO_ATTACK;
damageInfo->HitInfo = HITINFO_NORMALSWING2;
break;
case OFF_ATTACK:
damageInfo->procAttacker = PROC_FLAG_DONE_MELEE_AUTO_ATTACK | PROC_FLAG_DONE_OFFHAND_ATTACK;
damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_AUTO_ATTACK;
damageInfo->HitInfo = HITINFO_LEFTSWING;
break;
default:
return;
}
// Physical Immune check
if (damageInfo->target->IsImmunedToDamage(SpellSchoolMask(damageInfo->damageSchoolMask)))
{
damageInfo->HitInfo |= HITINFO_NORMALSWING;
damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE;
damageInfo->procEx |= PROC_EX_IMMUNE;
damageInfo->damage = 0;
damageInfo->cleanDamage = 0;
return;
}
damage += CalculateDamage(damageInfo->attackType, false, true);
// Add melee damage bonus
MeleeDamageBonus(damageInfo->target, &damage, damageInfo->attackType);
// Calculate armor reduction
if (IsDamageReducedByArmor((SpellSchoolMask)(damageInfo->damageSchoolMask)))
{
damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage, NULL, damageInfo->attackType);
damageInfo->cleanDamage += damage - damageInfo->damage;
}
else
damageInfo->damage = damage;
damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType);
switch (damageInfo->hitOutCome)
{
case MELEE_HIT_EVADE:
damageInfo->HitInfo |= HITINFO_MISS|HITINFO_SWINGNOHITSOUND;
damageInfo->TargetState = VICTIMSTATE_EVADES;
damageInfo->procEx|=PROC_EX_EVADE;
damageInfo->damage = 0;
damageInfo->cleanDamage = 0;
return;
case MELEE_HIT_MISS:
damageInfo->HitInfo |= HITINFO_MISS;
damageInfo->TargetState = VICTIMSTATE_INTACT;
damageInfo->procEx |= PROC_EX_MISS;
damageInfo->damage = 0;
damageInfo->cleanDamage = 0;
break;
case MELEE_HIT_NORMAL:
damageInfo->TargetState = VICTIMSTATE_HIT;
damageInfo->procEx|=PROC_EX_NORMAL_HIT;
break;
case MELEE_HIT_CRIT:
{
damageInfo->HitInfo |= HITINFO_CRITICALHIT;
damageInfo->TargetState = VICTIMSTATE_HIT;
damageInfo->procEx |= PROC_EX_CRITICAL_HIT;
// Crit bonus calc
damageInfo->damage += damageInfo->damage;
float mod = 0.0f;
// Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
if (damageInfo->attackType == RANGED_ATTACK)
mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
else
mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
// Increase crit damage from SPELL_AURA_MOD_CRIT_DAMAGE_BONUS
mod += (GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS, damageInfo->damageSchoolMask) - 1.0f) * 100;
uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask();
// Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
if (mod != 0)
AddPctF(damageInfo->damage, mod);
break;
}
case MELEE_HIT_PARRY:
damageInfo->TargetState = VICTIMSTATE_PARRY;
damageInfo->procEx |= PROC_EX_PARRY;
damageInfo->cleanDamage += damageInfo->damage;
damageInfo->damage = 0;
break;
case MELEE_HIT_DODGE:
damageInfo->TargetState = VICTIMSTATE_DODGE;
damageInfo->procEx |= PROC_EX_DODGE;
damageInfo->cleanDamage += damageInfo->damage;
damageInfo->damage = 0;
break;
case MELEE_HIT_BLOCK:
damageInfo->TargetState = VICTIMSTATE_HIT;
damageInfo->HitInfo |= HITINFO_BLOCK;
damageInfo->procEx |= PROC_EX_BLOCK;
damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue();
// double blocked amount if block is critical
if (damageInfo->target->isBlockCritical())
damageInfo->blocked_amount+=damageInfo->blocked_amount;
if (damageInfo->blocked_amount >= damageInfo->damage)
{
damageInfo->TargetState = VICTIMSTATE_BLOCKS;
damageInfo->blocked_amount = damageInfo->damage;
damageInfo->procEx |= PROC_EX_FULL_BLOCK;
}
else
damageInfo->procEx |= PROC_EX_NORMAL_HIT;
damageInfo->damage -= damageInfo->blocked_amount;
damageInfo->cleanDamage += damageInfo->blocked_amount;
break;
case MELEE_HIT_GLANCING:
{
damageInfo->HitInfo |= HITINFO_GLANCING;
damageInfo->TargetState = VICTIMSTATE_HIT;
damageInfo->procEx |= PROC_EX_NORMAL_HIT;
int32 leveldif = int32(victim->getLevel()) - int32(getLevel());
if (leveldif > 3)
leveldif = 3;
float reducePercent = 1 - leveldif * 0.1f;
damageInfo->cleanDamage += damageInfo->damage-uint32(reducePercent * damageInfo->damage);
damageInfo->damage = uint32(reducePercent * damageInfo->damage);
break;
}
case MELEE_HIT_CRUSHING:
damageInfo->HitInfo |= HITINFO_CRUSHING;
damageInfo->TargetState = VICTIMSTATE_HIT;
damageInfo->procEx |= PROC_EX_NORMAL_HIT;
// 150% normal damage
damageInfo->damage += (damageInfo->damage / 2);
break;
default:
break;
}
int32 resilienceReduction = damageInfo->damage;
if (attackType != RANGED_ATTACK)
ApplyResilience(victim, NULL, &resilienceReduction, (damageInfo->hitOutCome == MELEE_HIT_CRIT), CR_CRIT_TAKEN_MELEE);
else
ApplyResilience(victim, NULL, &resilienceReduction, (damageInfo->hitOutCome == MELEE_HIT_CRIT), CR_CRIT_TAKEN_RANGED);
resilienceReduction = damageInfo->damage - resilienceReduction;
damageInfo->damage -= resilienceReduction;
damageInfo->cleanDamage += resilienceReduction;
// Calculate absorb resist
if (int32(damageInfo->damage) > 0)
{
damageInfo->procVictim |= PROC_FLAG_TAKEN_DAMAGE;
// Calculate absorb & resists
CalcAbsorbResist(damageInfo->target, SpellSchoolMask(damageInfo->damageSchoolMask), DIRECT_DAMAGE, damageInfo->damage, &damageInfo->absorb, &damageInfo->resist);
damageInfo->damage -= damageInfo->absorb + damageInfo->resist;
if (damageInfo->absorb)
{
damageInfo->HitInfo |= HITINFO_ABSORB;
damageInfo->procEx |= PROC_EX_ABSORB;
}
if (damageInfo->resist)
damageInfo->HitInfo |= HITINFO_RESIST;
}
else // Impossible get negative result but....
damageInfo->damage = 0;
}
void Unit::DealMeleeDamage(CalcDamageInfo* damageInfo, bool durabilityLoss)
{
Unit* victim = damageInfo->target;
if (!victim->isAlive() || victim->HasUnitState(UNIT_STAT_IN_FLIGHT) || (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsInEvadeMode()))
return;
// Hmmmm dont like this emotes client must by self do all animations
if (damageInfo->HitInfo & HITINFO_CRITICALHIT)
victim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL);
if (damageInfo->blocked_amount && damageInfo->TargetState != VICTIMSTATE_BLOCKS)
victim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD);
if (damageInfo->TargetState == VICTIMSTATE_PARRY)
{
// Get attack timers
float offtime = float(victim->getAttackTimer(OFF_ATTACK));
float basetime = float(victim->getAttackTimer(BASE_ATTACK));
// Reduce attack time
if (victim->haveOffhandWeapon() && offtime < basetime)
{
float percent20 = victim->GetAttackTime(OFF_ATTACK) * 0.20f;
float percent60 = 3.0f * percent20;
if (offtime > percent20 && offtime <= percent60)
victim->setAttackTimer(OFF_ATTACK, uint32(percent20));
else if (offtime > percent60)
{
offtime -= 2.0f * percent20;
victim->setAttackTimer(OFF_ATTACK, uint32(offtime));
}
}
else
{
float percent20 = victim->GetAttackTime(BASE_ATTACK) * 0.20f;
float percent60 = 3.0f * percent20;
if (basetime > percent20 && basetime <= percent60)
victim->setAttackTimer(BASE_ATTACK, uint32(percent20));
else if (basetime > percent60)
{
basetime -= 2.0f * percent20;
victim->setAttackTimer(BASE_ATTACK, uint32(basetime));
}
}
}
// Call default DealDamage
CleanDamage cleanDamage(damageInfo->cleanDamage, damageInfo->absorb, damageInfo->attackType, damageInfo->hitOutCome);
DealDamage(victim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), NULL, durabilityLoss);
// If this is a creature and it attacks from behind it has a probability to daze it's victim
if ((damageInfo->hitOutCome == MELEE_HIT_CRIT || damageInfo->hitOutCome == MELEE_HIT_CRUSHING || damageInfo->hitOutCome == MELEE_HIT_NORMAL || damageInfo->hitOutCome == MELEE_HIT_GLANCING) &&
GetTypeId() != TYPEID_PLAYER && !ToCreature()->IsControlledByPlayer() && !victim->HasInArc(M_PI, this)
&& (victim->GetTypeId() == TYPEID_PLAYER || !victim->ToCreature()->isWorldBoss()))
{
// -probability is between 0% and 40%
// 20% base chance
float Probability = 20.0f;
// there is a newbie protection, at level 10 just 7% base chance; assuming linear function
if (victim->getLevel() < 30)
Probability = 0.65f * victim->getLevel() + 0.5f;
uint32 VictimDefense=victim->GetDefenseSkillValue();
uint32 AttackerMeleeSkill=GetUnitMeleeSkill();
Probability *= AttackerMeleeSkill/(float)VictimDefense;
if (Probability > 40.0f)
Probability = 40.0f;
if (roll_chance_f(Probability))
CastSpell(victim, 1604, true);
}
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->CastItemCombatSpell(victim, damageInfo->attackType, damageInfo->procVictim, damageInfo->procEx);
// Do effect if any damage done to target
if (damageInfo->damage)
{
// We're going to call functions which can modify content of the list during iteration over it's elements
// Let's copy the list so we can prevent iterator invalidation
AuraEffectList vDamageShieldsCopy(victim->GetAuraEffectsByType(SPELL_AURA_DAMAGE_SHIELD));
for (AuraEffectList::const_iterator dmgShieldItr = vDamageShieldsCopy.begin(); dmgShieldItr != vDamageShieldsCopy.end(); ++dmgShieldItr)
{
SpellInfo const* i_spellProto = (*dmgShieldItr)->GetSpellInfo();
// Damage shield can be resisted...
if (SpellMissInfo missInfo = victim->SpellHitResult(this, i_spellProto, false))
{
victim->SendSpellMiss(this, i_spellProto->Id, missInfo);
continue;
}
// ...or immuned
if (IsImmunedToDamage(i_spellProto))
{
victim->SendSpellDamageImmune(this, i_spellProto->Id);
continue;
}
uint32 damage = (*dmgShieldItr)->GetAmount();
if (Unit* caster = (*dmgShieldItr)->GetCaster())
damage = caster->SpellDamageBonus(this, i_spellProto, damage, SPELL_DIRECT_DAMAGE);
// No Unit::CalcAbsorbResist here - opcode doesn't send that data - this damage is probably not affected by that
victim->DealDamageMods(this, damage, NULL);
// TODO: Move this to a packet handler
WorldPacket data(SMSG_SPELLDAMAGESHIELD, (8+8+4+4+4+4));
data << uint64(victim->GetGUID());
data << uint64(GetGUID());
data << uint32(i_spellProto->Id);
data << uint32(damage); // Damage
int32 overkill = int32(damage) - int32(GetHealth());
data << uint32(overkill > 0 ? overkill : 0); // Overkill
data << uint32(i_spellProto->SchoolMask);
victim->SendMessageToSet(&data, true);
victim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, i_spellProto->GetSchoolMask(), i_spellProto, true);
}
}
}
void Unit::HandleEmoteCommand(uint32 anim_id)
{
WorldPacket data(SMSG_EMOTE, 4 + 8);
data << uint32(anim_id);
data << uint64(GetGUID());
SendMessageToSet(&data, true);
}
bool Unit::IsDamageReducedByArmor(SpellSchoolMask schoolMask, SpellInfo const* spellInfo, uint8 effIndex)
{
// only physical spells damage gets reduced by armor
if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL) == 0)
return false;
if (spellInfo)
{
// there are spells with no specific attribute but they have "ignores armor" in tooltip
if (spellInfo->AttributesCu & SPELL_ATTR0_CU_IGNORE_ARMOR)
return false;
// bleeding effects are not reduced by armor
if (effIndex != MAX_SPELL_EFFECTS && spellInfo->Effects[effIndex].ApplyAuraName == SPELL_AURA_PERIODIC_DAMAGE)
if (spellInfo->GetEffectMechanicMask(effIndex) & (1<<MECHANIC_BLEED))
return false;
}
return true;
}
uint32 Unit::CalcArmorReducedDamage(Unit* victim, const uint32 damage, SpellInfo const* spellInfo, WeaponAttackType /*attackType*/)
{
uint32 newdamage = 0;
float armor = float(victim->GetArmor());
// Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura
armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL);
if (spellInfo)
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_IGNORE_ARMOR, armor);
AuraEffectList const& ResIgnoreAurasAb = GetAuraEffectsByType(SPELL_AURA_MOD_ABILITY_IGNORE_TARGET_RESIST);
for (AuraEffectList::const_iterator j = ResIgnoreAurasAb.begin(); j != ResIgnoreAurasAb.end(); ++j)
{
if ((*j)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL
&& (*j)->IsAffectedOnSpell(spellInfo))
armor = floor(AddPctN(armor, -(*j)->GetAmount()));
}
AuraEffectList const& ResIgnoreAuras = GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_TARGET_RESIST);
for (AuraEffectList::const_iterator j = ResIgnoreAuras.begin(); j != ResIgnoreAuras.end(); ++j)
{
if ((*j)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL)
armor = floor(AddPctN(armor, -(*j)->GetAmount()));
}
// Apply Player CR_ARMOR_PENETRATION rating and buffs from stances\specializations etc.
if (GetTypeId() == TYPEID_PLAYER)
{
float bonusPct = 0;
AuraEffectList const& ResIgnoreAuras = GetAuraEffectsByType(SPELL_AURA_MOD_ARMOR_PENETRATION_PCT);
for (AuraEffectList::const_iterator itr = ResIgnoreAuras.begin(); itr != ResIgnoreAuras.end(); ++itr)
{
if ((*itr)->GetSpellInfo()->EquippedItemClass == -1)
{
if (!spellInfo || (*itr)->IsAffectedOnSpell(spellInfo) || (*itr)->GetMiscValue() & spellInfo->GetSchoolMask())
bonusPct += (*itr)->GetAmount();
else if (!(*itr)->GetMiscValue() && !(*itr)->HasSpellClassMask())
bonusPct += (*itr)->GetAmount();
}
else
{
if (ToPlayer() && ToPlayer()->HasItemFitToSpellRequirements((*itr)->GetSpellInfo()))
bonusPct += (*itr)->GetAmount();
}
}
float maxArmorPen = 0;
if (victim->getLevel() < 60)
maxArmorPen = float(400 + 85 * victim->getLevel());
else
maxArmorPen = 400 + 85 * victim->getLevel() + 4.5f * 85 * (victim->getLevel() - 59);
// Cap armor penetration to this number
maxArmorPen = std::min((armor + maxArmorPen) / 3, armor);
// Figure out how much armor do we ignore
float armorPen = CalculatePctF(maxArmorPen, bonusPct + ToPlayer()->GetRatingBonusValue(CR_ARMOR_PENETRATION));
// Got the value, apply it
armor -= std::min(armorPen, maxArmorPen);
}
armor *= 1.0f - GetTotalAuraModifier(SPELL_AURA_MOD_ARMOR_PENETRATION_PCT) / 100.0f;
if (armor < 0.0f)
armor = 0.0f;
float levelModifier = getLevel();
if (levelModifier > 59)
levelModifier = levelModifier + (4.5f * (levelModifier - 59));
float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40);
tmpvalue = tmpvalue / (1.0f + tmpvalue);
if (tmpvalue < 0.0f)
tmpvalue = 0.0f;
if (tmpvalue > 0.75f)
tmpvalue = 0.75f;
newdamage = uint32(damage - (damage * tmpvalue));
return (newdamage > 1) ? newdamage : 1;
}
void Unit::CalcAbsorbResist(Unit* victim, SpellSchoolMask schoolMask, DamageEffectType damagetype, uint32 const damage, uint32 *absorb, uint32 *resist, SpellInfo const* spellInfo)
{
if (!victim || !victim->isAlive() || !damage)
return;
DamageInfo dmgInfo = DamageInfo(this, victim, damage, spellInfo, schoolMask, damagetype);
// Magic damage, check for resists
if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL) == 0)
{
float victimResistance = float(victim->GetResistance(schoolMask));
victimResistance += float(GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask));
if (Player* player = ToPlayer())
victimResistance -= float(player->GetSpellPenetrationItemMod());
// Resistance can't be lower then 0.
if (victimResistance < 0.0f)
victimResistance = 0.0f;
static uint32 const BOSS_LEVEL = 83;
static float const BOSS_RESISTANCE_CONSTANT = 510.0f;
uint32 level = victim->getLevel();
float resistanceConstant = 0.0f;
if (level == BOSS_LEVEL)
resistanceConstant = BOSS_RESISTANCE_CONSTANT;
else
resistanceConstant = level * 5.0f;
float averageResist = victimResistance / (victimResistance + resistanceConstant);
float discreteResistProbability[11];
for (uint32 i = 0; i < 11; ++i)
{
discreteResistProbability[i] = 0.5f - 2.5f * fabs(0.1f * i - averageResist);
if (discreteResistProbability[i] < 0.0f)
discreteResistProbability[i] = 0.0f;
}
if (averageResist <= 0.1f)
{
discreteResistProbability[0] = 1.0f - 7.5f * averageResist;
discreteResistProbability[1] = 5.0f * averageResist;
discreteResistProbability[2] = 2.5f * averageResist;
}
float r = float(rand_norm());
uint32 i = 0;
float probabilitySum = discreteResistProbability[0];
while (r >= probabilitySum && i < 10)
probabilitySum += discreteResistProbability[++i];
float damageResisted = float(damage * i / 10);
AuraEffectList const& ResIgnoreAurasAb = GetAuraEffectsByType(SPELL_AURA_MOD_ABILITY_IGNORE_TARGET_RESIST);
for (AuraEffectList::const_iterator j = ResIgnoreAurasAb.begin(); j != ResIgnoreAurasAb.end(); ++j)
if (((*j)->GetMiscValue() & schoolMask) && (*j)->IsAffectedOnSpell(spellInfo))
AddPctN(damageResisted, -(*j)->GetAmount());
AuraEffectList const& ResIgnoreAuras = GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_TARGET_RESIST);
for (AuraEffectList::const_iterator j = ResIgnoreAuras.begin(); j != ResIgnoreAuras.end(); ++j)
if ((*j)->GetMiscValue() & schoolMask)
AddPctN(damageResisted, -(*j)->GetAmount());
dmgInfo.ResistDamage(uint32(damageResisted));
}
// Ignore Absorption Auras
float auraAbsorbMod = 0;
AuraEffectList const& AbsIgnoreAurasA = GetAuraEffectsByType(SPELL_AURA_MOD_TARGET_ABSORB_SCHOOL);
for (AuraEffectList::const_iterator itr = AbsIgnoreAurasA.begin(); itr != AbsIgnoreAurasA.end(); ++itr)
{
if (!((*itr)->GetMiscValue() & schoolMask))
continue;
if ((*itr)->GetAmount() > auraAbsorbMod)
auraAbsorbMod = float((*itr)->GetAmount());
}
AuraEffectList const& AbsIgnoreAurasB = GetAuraEffectsByType(SPELL_AURA_MOD_TARGET_ABILITY_ABSORB_SCHOOL);
for (AuraEffectList::const_iterator itr = AbsIgnoreAurasB.begin(); itr != AbsIgnoreAurasB.end(); ++itr)
{
if (!((*itr)->GetMiscValue() & schoolMask))
continue;
if (((*itr)->GetAmount() > auraAbsorbMod) && (*itr)->IsAffectedOnSpell(spellInfo))
auraAbsorbMod = float((*itr)->GetAmount());
}
RoundToInterval(auraAbsorbMod, 0.0f, 100.0f);
// We're going to call functions which can modify content of the list during iteration over it's elements
// Let's copy the list so we can prevent iterator invalidation
AuraEffectList vSchoolAbsorbCopy(victim->GetAuraEffectsByType(SPELL_AURA_SCHOOL_ABSORB));
vSchoolAbsorbCopy.sort(Trinity::AbsorbAuraOrderPred());
// absorb without mana cost
for (AuraEffectList::iterator itr = vSchoolAbsorbCopy.begin(); (itr != vSchoolAbsorbCopy.end()) && (dmgInfo.GetDamage() > 0); ++itr)
{
AuraEffect* absorbAurEff = *itr;
// Check if aura was removed during iteration - we don't need to work on such auras
AuraApplication const* aurApp = absorbAurEff->GetBase()->GetApplicationOfTarget(victim->GetGUID());
if (!aurApp)
continue;
if (!(absorbAurEff->GetMiscValue() & schoolMask))
continue;
// get amount which can be still absorbed by the aura
int32 currentAbsorb = absorbAurEff->GetAmount();
// aura with infinite absorb amount - let the scripts handle absorbtion amount, set here to 0 for safety
if (currentAbsorb < 0)
currentAbsorb = 0;
uint32 tempAbsorb = uint32(currentAbsorb);
bool defaultPrevented = false;
absorbAurEff->GetBase()->CallScriptEffectAbsorbHandlers(absorbAurEff, aurApp, dmgInfo, tempAbsorb, defaultPrevented);
currentAbsorb = tempAbsorb;
if (defaultPrevented)
continue;
// Apply absorb mod auras
AddPctF(currentAbsorb, -auraAbsorbMod);
// absorb must be smaller than the damage itself
currentAbsorb = RoundToInterval(currentAbsorb, 0, int32(dmgInfo.GetDamage()));
dmgInfo.AbsorbDamage(currentAbsorb);
tempAbsorb = currentAbsorb;
absorbAurEff->GetBase()->CallScriptEffectAfterAbsorbHandlers(absorbAurEff, aurApp, dmgInfo, tempAbsorb);
// Check if our aura is using amount to count damage
if (absorbAurEff->GetAmount() >= 0)
{
// Reduce shield amount
absorbAurEff->SetAmount(absorbAurEff->GetAmount() - currentAbsorb);
// Aura cannot absorb anything more - remove it
if (absorbAurEff->GetAmount() <= 0)
absorbAurEff->GetBase()->Remove(AURA_REMOVE_BY_ENEMY_SPELL);
}
}
// absorb by mana cost
AuraEffectList vManaShieldCopy(victim->GetAuraEffectsByType(SPELL_AURA_MANA_SHIELD));
for (AuraEffectList::const_iterator itr = vManaShieldCopy.begin(); (itr != vManaShieldCopy.end()) && (dmgInfo.GetDamage() > 0); ++itr)
{
AuraEffect* absorbAurEff = *itr;
// Check if aura was removed during iteration - we don't need to work on such auras
AuraApplication const* aurApp = absorbAurEff->GetBase()->GetApplicationOfTarget(victim->GetGUID());
if (!aurApp)
continue;
// check damage school mask
if (!(absorbAurEff->GetMiscValue() & schoolMask))
continue;
// get amount which can be still absorbed by the aura
int32 currentAbsorb = absorbAurEff->GetAmount();
// aura with infinite absorb amount - let the scripts handle absorbtion amount, set here to 0 for safety
if (currentAbsorb < 0)
currentAbsorb = 0;
uint32 tempAbsorb = currentAbsorb;
bool defaultPrevented = false;
absorbAurEff->GetBase()->CallScriptEffectManaShieldHandlers(absorbAurEff, aurApp, dmgInfo, tempAbsorb, defaultPrevented);
currentAbsorb = tempAbsorb;
if (defaultPrevented)
continue;
AddPctF(currentAbsorb, -auraAbsorbMod);
// absorb must be smaller than the damage itself
currentAbsorb = RoundToInterval(currentAbsorb, 0, int32(dmgInfo.GetDamage()));
int32 manaReduction = currentAbsorb;
// lower absorb amount by talents
if (float manaMultiplier = absorbAurEff->GetSpellInfo()->Effects[absorbAurEff->GetEffIndex()].CalcValueMultiplier(absorbAurEff->GetCaster()))
manaReduction = int32(float(manaReduction) * manaMultiplier);
int32 manaTaken = -victim->ModifyPower(POWER_MANA, -manaReduction);
// take case when mana has ended up into account
currentAbsorb = currentAbsorb ? int32(float(currentAbsorb) * (float(manaTaken) / float(manaReduction))) : 0;
dmgInfo.AbsorbDamage(currentAbsorb);
tempAbsorb = currentAbsorb;
absorbAurEff->GetBase()->CallScriptEffectAfterManaShieldHandlers(absorbAurEff, aurApp, dmgInfo, tempAbsorb);
// Check if our aura is using amount to count damage
if (absorbAurEff->GetAmount() >= 0)
{
absorbAurEff->SetAmount(absorbAurEff->GetAmount() - currentAbsorb);
if ((absorbAurEff->GetAmount() <= 0))
absorbAurEff->GetBase()->Remove(AURA_REMOVE_BY_ENEMY_SPELL);
}
}
// split damage auras - only when not damaging self
if (victim != this)
{
// We're going to call functions which can modify content of the list during iteration over it's elements
// Let's copy the list so we can prevent iterator invalidation
AuraEffectList vSplitDamageFlatCopy(victim->GetAuraEffectsByType(SPELL_AURA_SPLIT_DAMAGE_FLAT));
for (AuraEffectList::iterator itr = vSplitDamageFlatCopy.begin(); (itr != vSplitDamageFlatCopy.end()) && (dmgInfo.GetDamage() > 0); ++itr)
{
// Check if aura was removed during iteration - we don't need to work on such auras
if (!((*itr)->GetBase()->IsAppliedOnTarget(victim->GetGUID())))
continue;
// check damage school mask
if (!((*itr)->GetMiscValue() & schoolMask))
continue;
// Damage can be splitted only if aura has an alive caster
Unit* caster = (*itr)->GetCaster();
if (!caster || (caster == victim) || !caster->IsInWorld() || !caster->isAlive())
continue;
int32 splitDamage = (*itr)->GetAmount();
// absorb must be smaller than the damage itself
splitDamage = RoundToInterval(splitDamage, 0, int32(dmgInfo.GetDamage()));
dmgInfo.AbsorbDamage(splitDamage);
uint32 splitted = splitDamage;
uint32 splitted_absorb = 0;
DealDamageMods(caster, splitted, &splitted_absorb);
SendSpellNonMeleeDamageLog(caster, (*itr)->GetSpellInfo()->Id, splitted, schoolMask, splitted_absorb, 0, false, 0, false);
CleanDamage cleanDamage = CleanDamage(splitted, 0, BASE_ATTACK, MELEE_HIT_NORMAL);
DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*itr)->GetSpellInfo(), false);
}
// We're going to call functions which can modify content of the list during iteration over it's elements
// Let's copy the list so we can prevent iterator invalidation
AuraEffectList vSplitDamagePctCopy(victim->GetAuraEffectsByType(SPELL_AURA_SPLIT_DAMAGE_PCT));
for (AuraEffectList::iterator itr = vSplitDamagePctCopy.begin(), next; (itr != vSplitDamagePctCopy.end()) && (dmgInfo.GetDamage() > 0); ++itr)
{
// Check if aura was removed during iteration - we don't need to work on such auras
if (!((*itr)->GetBase()->IsAppliedOnTarget(victim->GetGUID())))
continue;
// check damage school mask
if (!((*itr)->GetMiscValue() & schoolMask))
continue;
// Damage can be splitted only if aura has an alive caster
Unit* caster = (*itr)->GetCaster();
if (!caster || (caster == victim) || !caster->IsInWorld() || !caster->isAlive())
continue;
int32 splitDamage = CalculatePctN(dmgInfo.GetDamage(), (*itr)->GetAmount());
// absorb must be smaller than the damage itself
splitDamage = RoundToInterval(splitDamage, 0, int32(dmgInfo.GetDamage()));
dmgInfo.AbsorbDamage(splitDamage);
uint32 splitted = splitDamage;
uint32 split_absorb = 0;
DealDamageMods(caster, splitted, &split_absorb);
SendSpellNonMeleeDamageLog(caster, (*itr)->GetSpellInfo()->Id, splitted, schoolMask, split_absorb, 0, false, 0, false);
CleanDamage cleanDamage = CleanDamage(splitted, 0, BASE_ATTACK, MELEE_HIT_NORMAL);
DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*itr)->GetSpellInfo(), false);
}
}
*resist = dmgInfo.GetResist();
*absorb = dmgInfo.GetAbsorb();
}
void Unit::CalcHealAbsorb(Unit* victim, const SpellInfo* healSpell, uint32 &healAmount, uint32 &absorb)
{
if (!healAmount)
return;
int32 RemainingHeal = healAmount;
// Need remove expired auras after
bool existExpired = false;
// absorb without mana cost
AuraEffectList const& vHealAbsorb = victim->GetAuraEffectsByType(SPELL_AURA_SCHOOL_HEAL_ABSORB);
for (AuraEffectList::const_iterator i = vHealAbsorb.begin(); i != vHealAbsorb.end() && RemainingHeal > 0; ++i)
{
if (!((*i)->GetMiscValue() & healSpell->SchoolMask))
continue;
// Max Amount can be absorbed by this aura
int32 currentAbsorb = (*i)->GetAmount();
// Found empty aura (impossible but..)
if (currentAbsorb <= 0)
{
existExpired = true;
continue;
}
// currentAbsorb - damage can be absorbed by shield
// If need absorb less damage
if (RemainingHeal < currentAbsorb)
currentAbsorb = RemainingHeal;
RemainingHeal -= currentAbsorb;
// Reduce shield amount
(*i)->SetAmount((*i)->GetAmount() - currentAbsorb);
// Need remove it later
if ((*i)->GetAmount() <= 0)
existExpired = true;
}
// Remove all expired absorb auras
if (existExpired)
{
for (AuraEffectList::const_iterator i = vHealAbsorb.begin(); i != vHealAbsorb.end();)
{
AuraEffect* auraEff = *i;
++i;
if (auraEff->GetAmount() <= 0)
{
uint32 removedAuras = victim->m_removedAurasCount;
auraEff->GetBase()->Remove(AURA_REMOVE_BY_ENEMY_SPELL);
if (removedAuras+1 < victim->m_removedAurasCount)
i = vHealAbsorb.begin();
}
}
}
absorb = RemainingHeal > 0 ? (healAmount - RemainingHeal) : healAmount;
healAmount = RemainingHeal;
}
void Unit::AttackerStateUpdate (Unit* victim, WeaponAttackType attType, bool extra)
{
if (HasUnitState(UNIT_STAT_CANNOT_AUTOATTACK) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
return;
if (!victim->isAlive())
return;
if ((attType == BASE_ATTACK || attType == OFF_ATTACK) && !IsWithinLOSInMap(victim))
return;
CombatStart(victim);
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MELEE_ATTACK);
uint32 hitInfo;
if (attType == BASE_ATTACK)
hitInfo = HITINFO_NORMALSWING2;
else if (attType == OFF_ATTACK)
hitInfo = HITINFO_LEFTSWING;
else
return; // ignore ranged case
// melee attack spell casted at main hand attack only - no normal melee dmg dealt
if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL] && !extra)
m_currentSpells[CURRENT_MELEE_SPELL]->cast();
else
{
// attack can be redirected to another target
victim = SelectMagnetTarget(victim);
CalcDamageInfo damageInfo;
CalculateMeleeDamage(victim, 0, &damageInfo, attType);
// Send log damage message to client
DealDamageMods(victim, damageInfo.damage, &damageInfo.absorb);
SendAttackStateUpdate(&damageInfo);
//TriggerAurasProcOnEvent(damageInfo);
ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType);
DealMeleeDamage(&damageInfo, true);
if (GetTypeId() == TYPEID_PLAYER)
sLog->outStaticDebug("AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
GetGUIDLow(), victim->GetGUIDLow(), victim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
else
sLog->outStaticDebug("AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
GetGUIDLow(), victim->GetGUIDLow(), victim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
}
}
void Unit::HandleProcExtraAttackFor(Unit* victim)
{
while (m_extraAttacks)
{
AttackerStateUpdate(victim, BASE_ATTACK, true);
--m_extraAttacks;
}
}
bool isInEvasiveManeuvers(const Unit* victim)
{
if(victim->HasAura(50240))
{
// we also drop 1 charge of Evasive charges
if(Aura* evasiveCharges = victim->GetAura(50241))
if(evasiveCharges->GetStackAmount() > 1)
evasiveCharges->SetStackAmount(evasiveCharges->GetStackAmount() - 1);
else
evasiveCharges->Remove();
return true;
}
return false;
}
MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit* victim, WeaponAttackType attType) const
{
// This is only wrapper
// Miss chance based on melee
//float miss_chance = MeleeMissChanceCalc(victim, attType);
float miss_chance = MeleeSpellMissChance(victim, attType, int32(GetWeaponSkillValue(attType, victim)) - int32(GetMaxSkillValueForLevel(this)), 0);
// Critical hit chance
float crit_chance = GetUnitCriticalChance(attType, victim);
// stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case)
float dodge_chance = victim->GetUnitDodgeChance();
float block_chance = victim->GetUnitBlockChance();
float parry_chance = victim->GetUnitParryChance();
// Useful if want to specify crit & miss chances for melee, else it could be removed
sLog->outStaticDebug("MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance, crit_chance, dodge_chance, parry_chance, block_chance);
return RollMeleeOutcomeAgainst(victim, attType, int32(crit_chance*100), int32(miss_chance*100), int32(dodge_chance*100), int32(parry_chance*100), int32(block_chance*100));
}
MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit* victim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const
{
if (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsInEvadeMode())
return MELEE_HIT_EVADE;
int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(victim);
int32 victimMaxSkillValueForLevel = victim->GetMaxSkillValueForLevel(this);
int32 attackerWeaponSkill = GetWeaponSkillValue(attType, victim);
int32 victimDefenseSkill = victim->GetDefenseSkillValue(this);
// bonus from skills is 0.04%
int32 skillBonus = 4 * (attackerWeaponSkill - victimMaxSkillValueForLevel);
int32 sum = 0, tmp = 0;
int32 roll = urand (0, 10000);
sLog->outStaticDebug ("RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus);
sLog->outStaticDebug ("RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d",
roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance);
tmp = miss_chance;
if (tmp > 0 && roll < (sum += tmp))
{
sLog->outStaticDebug ("RollMeleeOutcomeAgainst: MISS");
return MELEE_HIT_MISS;
}
// always crit against a sitting target (except 0 crit chance)
if (victim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !victim->IsStandState())
{
sLog->outStaticDebug ("RollMeleeOutcomeAgainst: CRIT (sitting victim)");
return MELEE_HIT_CRIT;
}
// Dodge chance
// only players can't dodge if attacker is behind
if (victim->GetTypeId() == TYPEID_PLAYER && !victim->HasInArc(M_PI, this) && !victim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
{
sLog->outStaticDebug ("RollMeleeOutcomeAgainst: attack came from behind and victim was a player.");
}
else
{
// Reduce dodge chance by attacker expertise rating
if (GetTypeId() == TYPEID_PLAYER)
dodge_chance -= int32(ToPlayer()->GetExpertiseDodgeOrParryReduction(attType) * 100);
else
dodge_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE) * 25;
// Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE) * 100;
dodge_chance = int32 (float (dodge_chance) * GetTotalAuraMultiplier(SPELL_AURA_MOD_ENEMY_DODGE));
// If target has evasive maneuvers result should always be dodge
if(isInEvasiveManeuvers(victim))
return MELEE_HIT_DODGE;
tmp = dodge_chance;
if ((tmp > 0) // check if unit _can_ dodge
&& ((tmp -= skillBonus) > 0)
&& roll < (sum += tmp))
{
sLog->outStaticDebug ("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum);
return MELEE_HIT_DODGE;
}
}
// parry & block chances
// check if attack comes from behind, nobody can parry or block if attacker is behind
if (!victim->HasInArc(M_PI, this) && !victim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
sLog->outStaticDebug ("RollMeleeOutcomeAgainst: attack came from behind.");
else
{
// Reduce parry chance by attacker expertise rating
if (GetTypeId() == TYPEID_PLAYER)
parry_chance -= int32(ToPlayer()->GetExpertiseDodgeOrParryReduction(attType) * 100);
else
parry_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE) * 25;
if (victim->GetTypeId() == TYPEID_PLAYER || !(victim->ToCreature()->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY))
{
int32 tmp2 = int32(parry_chance);
if (tmp2 > 0 // check if unit _can_ parry
&& (tmp2 -= skillBonus) > 0
&& roll < (sum += tmp2))
{
sLog->outStaticDebug ("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp2, sum);
return MELEE_HIT_PARRY;
}
}
if (victim->GetTypeId() == TYPEID_PLAYER || !(victim->ToCreature()->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK))
{
tmp = block_chance;
if (tmp > 0 // check if unit _can_ block
&& (tmp -= skillBonus) > 0
&& roll < (sum += tmp))
{
sLog->outStaticDebug ("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum);
return MELEE_HIT_BLOCK;
}
}
}
// Critical chance
tmp = crit_chance;
if (tmp > 0 && roll < (sum += tmp))
{
sLog->outStaticDebug ("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum);
if (GetTypeId() == TYPEID_UNIT && (ToCreature()->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRIT))
sLog->outStaticDebug ("RollMeleeOutcomeAgainst: CRIT DISABLED)");
else
return MELEE_HIT_CRIT;
}
// Max 40% chance to score a glancing blow against mobs that are higher level (can do only players and pets and not with ranged weapon)
if (attType != RANGED_ATTACK &&
(GetTypeId() == TYPEID_PLAYER || ToCreature()->isPet()) &&
victim->GetTypeId() != TYPEID_PLAYER && !victim->ToCreature()->isPet() &&
getLevel() < victim->getLevelForTarget(this))
{
// cap possible value (with bonuses > max skill)
int32 skill = attackerWeaponSkill;
int32 maxskill = attackerMaxSkillValueForLevel;
skill = (skill > maxskill) ? maxskill : skill;
tmp = (10 + (victimDefenseSkill - skill)) * 100;
tmp = tmp > 4000 ? 4000 : tmp;
if (roll < (sum += tmp))
{
sLog->outStaticDebug ("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum);
return MELEE_HIT_GLANCING;
}
}
// mobs can score crushing blows if they're 4 or more levels above victim
if (getLevelForTarget(victim) >= victim->getLevelForTarget(this) + 4 &&
// can be from by creature (if can) or from controlled player that considered as creature
!IsControlledByPlayer() &&
!(GetTypeId() == TYPEID_UNIT && ToCreature()->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH))
{
// when their weapon skill is 15 or more above victim's defense skill
tmp = victimDefenseSkill;
int32 tmpmax = victimMaxSkillValueForLevel;
// having defense above your maximum (from items, talents etc.) has no effect
tmp = tmp > tmpmax ? tmpmax : tmp;
// tmp = mob's level * 5 - player's current defense skill
tmp = attackerMaxSkillValueForLevel - tmp;
if (tmp >= 15)
{
// add 2% chance per lacking skill point, min. is 15%
tmp = tmp * 200 - 1500;
if (roll < (sum += tmp))
{
sLog->outStaticDebug ("RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum);
return MELEE_HIT_CRUSHING;
}
}
}
sLog->outStaticDebug ("RollMeleeOutcomeAgainst: NORMAL");
return MELEE_HIT_NORMAL;
}
uint32 Unit::CalculateDamage(WeaponAttackType attType, bool normalized, bool addTotalPct)
{
float min_damage, max_damage;
if (GetTypeId() == TYPEID_PLAYER && (normalized || !addTotalPct))
ToPlayer()->CalculateMinMaxDamage(attType, normalized, addTotalPct, min_damage, max_damage);
else
{
switch (attType)
{
case RANGED_ATTACK:
min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE);
max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE);
break;
case BASE_ATTACK:
min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE);
max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE);
break;
case OFF_ATTACK:
min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE);
max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE);
break;
// Just for good manner
default:
min_damage = 0.0f;
max_damage = 0.0f;
break;
}
}
if (min_damage > max_damage)
std::swap(min_damage, max_damage);
if (max_damage == 0.0f)
max_damage = 5.0f;
return urand((uint32)min_damage, (uint32)max_damage);
}
float Unit::CalculateLevelPenalty(SpellInfo const* spellProto) const
{
if (spellProto->SpellLevel <= 0 || spellProto->SpellLevel >= spellProto->MaxLevel)
return 1.0f;
float LvlPenalty = 0.0f;
if (spellProto->SpellLevel < 20)
LvlPenalty = 20.0f - spellProto->SpellLevel * 3.75f;
float LvlFactor = (float(spellProto->SpellLevel) + 6.0f) / float(getLevel());
if (LvlFactor > 1.0f)
LvlFactor = 1.0f;
return AddPctF(LvlFactor, -LvlPenalty);
}
void Unit::SendMeleeAttackStart(Unit* victim)
{
WorldPacket data(SMSG_ATTACKSTART, 8 + 8);
data << uint64(GetGUID());
data << uint64(victim->GetGUID());
SendMessageToSet(&data, true);
sLog->outStaticDebug("WORLD: Sent SMSG_ATTACKSTART");
}
void Unit::SendMeleeAttackStop(Unit* victim)
{
WorldPacket data(SMSG_ATTACKSTOP, (8+8+4)); // we guess size
data.append(GetPackGUID());
data.append(victim ? victim->GetPackGUID() : 0); // can be 0x00...
data << uint32(0); // can be 0x1
SendMessageToSet(&data, true);
sLog->outStaticDebug("WORLD: Sent SMSG_ATTACKSTART");
if (victim)
sLog->outDetail("%s %u stopped attacking %s %u", (GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature"), GetGUIDLow(), (victim->GetTypeId() == TYPEID_PLAYER ? "player" : "creature"), victim->GetGUIDLow());
else
sLog->outDetail("%s %u stopped attacking", (GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature"), GetGUIDLow());
}
bool Unit::isSpellBlocked(Unit* victim, SpellInfo const* spellProto, WeaponAttackType attackType)
{
// These spells can't be blocked
if (spellProto && spellProto->Attributes & SPELL_ATTR0_IMPOSSIBLE_DODGE_PARRY_BLOCK)
return false;
if (victim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION) || victim->HasInArc(M_PI, this))
{
// Check creatures flags_extra for disable block
if (victim->GetTypeId() == TYPEID_UNIT &&
victim->ToCreature()->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK)
return false;
float blockChance = victim->GetUnitBlockChance();
blockChance += (int32(GetWeaponSkillValue(attackType)) - int32(victim->GetMaxSkillValueForLevel())) * 0.04f;
if (roll_chance_f(blockChance))
return true;
}
return false;
}
bool Unit::isBlockCritical()
{
if (roll_chance_i(GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_CRIT_CHANCE)))
return true;
return false;
}
int32 Unit::GetMechanicResistChance(const SpellInfo* spell)
{
if (!spell)
return 0;
int32 resist_mech = 0;
for (uint8 eff = 0; eff < MAX_SPELL_EFFECTS; ++eff)
{
if (!spell->Effects[eff].IsEffect())
break;
int32 effect_mech = spell->GetEffectMechanic(eff);
if (effect_mech)
{
int32 temp = GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
if (resist_mech < temp)
resist_mech = temp;
}
}
return resist_mech;
}
// Melee based spells hit result calculations
SpellMissInfo Unit::MeleeSpellHitResult(Unit* victim, SpellInfo const* spell)
{
// Spells with SPELL_ATTR3_IGNORE_HIT_RESULT will additionally fully ignore
// resist and deflect chances
if (spell->AttributesEx3 & SPELL_ATTR3_IGNORE_HIT_RESULT)
return SPELL_MISS_NONE;
WeaponAttackType attType = BASE_ATTACK;
// Check damage class instead of attack type to correctly handle judgements
// - they are meele, but can't be dodged/parried/deflected because of ranged dmg class
if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED)
attType = RANGED_ATTACK;
int32 attackerWeaponSkill;
// skill value for these spells (for example judgements) is 5* level
if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED && !spell->IsRangedWeaponSpell())
attackerWeaponSkill = getLevel() * 5;
// bonus from skills is 0.04% per skill Diff
else
attackerWeaponSkill = int32(GetWeaponSkillValue(attType, victim));
int32 skillDiff = attackerWeaponSkill - int32(victim->GetMaxSkillValueForLevel(this));
uint32 roll = urand (0, 10000);
uint32 missChance = uint32(MeleeSpellMissChance(victim, attType, skillDiff, spell->Id) * 100.0f);
// Roll miss
uint32 tmp = missChance;
if (roll < tmp)
return SPELL_MISS_MISS;
// Chance resist mechanic (select max value from every mechanic spell effect)
int32 resist_mech = 0;
// Get effects mechanic and chance
for (uint8 eff = 0; eff < MAX_SPELL_EFFECTS; ++eff)
{
int32 effect_mech = spell->GetEffectMechanic(eff);
if (effect_mech)
{
int32 temp = victim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
if (resist_mech < temp*100)
resist_mech = temp*100;
}
}
// Roll chance
tmp += resist_mech;
if (roll < tmp)
return SPELL_MISS_RESIST;
bool canDodge = true;
bool canParry = true;
bool canBlock = spell->AttributesEx3 & SPELL_ATTR3_BLOCKABLE_SPELL;
// Same spells cannot be parry/dodge
if (spell->Attributes & SPELL_ATTR0_IMPOSSIBLE_DODGE_PARRY_BLOCK)
return SPELL_MISS_NONE;
// Chance resist mechanic
int32 resist_chance = victim->GetMechanicResistChance(spell) * 100;
tmp += resist_chance;
if (roll < tmp)
return SPELL_MISS_RESIST;
// Ranged attacks can only miss, resist and deflect
if (attType == RANGED_ATTACK)
{
// only if in front
if (victim->HasInArc(M_PI, this) || victim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
{
int32 deflect_chance = victim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS) * 100;
tmp+=deflect_chance;
if (roll < tmp)
return SPELL_MISS_DEFLECT;
}
return SPELL_MISS_NONE;
}
// Check for attack from behind
if (!victim->HasInArc(M_PI, this))
{
if (!victim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
{
// Can`t dodge from behind in PvP (but its possible in PvE)
if (victim->GetTypeId() == TYPEID_PLAYER)
canDodge = false;
// Can`t parry or block
canParry = false;
canBlock = false;
}
else // Only deterrence as of 3.3.5
{
if (spell->AttributesCu & SPELL_ATTR0_CU_REQ_CASTER_BEHIND_TARGET)
canParry = false;
}
}
// Check creatures flags_extra for disable parry
if (victim->GetTypeId() == TYPEID_UNIT)
{
uint32 flagEx = victim->ToCreature()->GetCreatureInfo()->flags_extra;
if (flagEx & CREATURE_FLAG_EXTRA_NO_PARRY)
canParry = false;
// Check creatures flags_extra for disable block
if (flagEx & CREATURE_FLAG_EXTRA_NO_BLOCK)
canBlock = false;
}
// Ignore combat result aura
AuraEffectList const& ignore = GetAuraEffectsByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
for (AuraEffectList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
{
if (!(*i)->IsAffectedOnSpell(spell))
continue;
switch ((*i)->GetMiscValue())
{
case MELEE_HIT_DODGE: canDodge = false; break;
case MELEE_HIT_BLOCK: canBlock = false; break;
case MELEE_HIT_PARRY: canParry = false; break;
default:
sLog->outStaticDebug("Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT have unhandled state %d", (*i)->GetId(), (*i)->GetMiscValue());
break;
}
}
if (canDodge)
{
// Roll dodge
int32 dodgeChance = int32(victim->GetUnitDodgeChance() * 100.0f) - skillDiff * 4;
// Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
dodgeChance += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE) * 100;
dodgeChance = int32(float(dodgeChance) * GetTotalAuraMultiplier(SPELL_AURA_MOD_ENEMY_DODGE));
// Reduce dodge chance by attacker expertise rating
if (GetTypeId() == TYPEID_PLAYER)
dodgeChance -= int32(ToPlayer()->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
else
dodgeChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE) * 25;
if (dodgeChance < 0)
dodgeChance = 0;
if (roll < (tmp += dodgeChance))
return SPELL_MISS_DODGE;
}
if (canParry)
{
// Roll parry
int32 parryChance = int32(victim->GetUnitParryChance() * 100.0f) - skillDiff * 4;
// Reduce parry chance by attacker expertise rating
if (GetTypeId() == TYPEID_PLAYER)
parryChance -= int32(ToPlayer()->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
else
parryChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE) * 25;
if (parryChance < 0)
parryChance = 0;
tmp += parryChance;
if (roll < tmp)
return SPELL_MISS_PARRY;
}
if (canBlock)
{
int32 blockChance = int32(victim->GetUnitBlockChance() * 100.0f) - skillDiff * 4;
if (blockChance < 0)
blockChance = 0;
tmp += blockChance;
if (roll < tmp)
return SPELL_MISS_BLOCK;
}
return SPELL_MISS_NONE;
}
// TODO need use unit spell resistances in calculations
SpellMissInfo Unit::MagicSpellHitResult(Unit* victim, SpellInfo const* spell)
{
// Can`t miss on dead target (on skinning for example)
if (!victim->isAlive() && victim->GetTypeId() != TYPEID_PLAYER)
return SPELL_MISS_NONE;
SpellSchoolMask schoolMask = spell->GetSchoolMask();
// PvP - PvE spell misschances per leveldif > 2
int32 lchance = victim->GetTypeId() == TYPEID_PLAYER ? 7 : 11;
int32 thisLevel = getLevelForTarget(victim);
if (GetTypeId() == TYPEID_UNIT && ToCreature()->isTrigger())
thisLevel = std::max<int32>(thisLevel, spell->SpellLevel);
int32 leveldif = int32(victim->getLevelForTarget(this)) - thisLevel;
// Base hit chance from attacker and victim levels
int32 modHitChance;
if (leveldif < 3)
modHitChance = 96 - leveldif;
else
modHitChance = 94 - (leveldif - 2) * lchance;
// Spellmod from SPELLMOD_RESIST_MISS_CHANCE
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance);
// Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras
modHitChance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask);
// Spells with SPELL_ATTR3_IGNORE_HIT_RESULT will ignore target's avoidance effects
if (!(spell->AttributesEx3 & SPELL_ATTR3_IGNORE_HIT_RESULT))
{
// Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras
modHitChance += victim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask);
// Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura
if (spell->IsAOE())
modHitChance -= victim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE);
// Decrease hit chance from victim rating bonus
if (victim->GetTypeId() == TYPEID_PLAYER)
modHitChance -= int32(victim->ToPlayer()->GetRatingBonusValue(CR_HIT_TAKEN_SPELL));
}
// If target has evasive maneuvers result should always be dodge
if(isInEvasiveManeuvers(victim))
return SPELL_MISS_DODGE;
int32 HitChance = modHitChance * 100;
// Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings
HitChance += int32(m_modSpellHitChance * 100.0f);
if (HitChance < 100)
HitChance = 100;
else if (HitChance > 10000)
HitChance = 10000;
int32 tmp = 10000 - HitChance;
int32 rand = irand(0, 10000);
if (rand < tmp)
return SPELL_MISS_MISS;
// Spells with SPELL_ATTR3_IGNORE_HIT_RESULT will additionally fully ignore
// resist and deflect chances
if (spell->AttributesEx3 & SPELL_ATTR3_IGNORE_HIT_RESULT)
return SPELL_MISS_NONE;
// Chance resist mechanic (select max value from every mechanic spell effect)
int32 resist_chance = victim->GetMechanicResistChance(spell) * 100;
tmp += resist_chance;
// Chance resist debuff
if (!spell->IsPositive())
{
bool bNegativeAura = false;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (spell->Effects[i].ApplyAuraName != 0)
{
bNegativeAura = true;
break;
}
}
if (bNegativeAura)
{
tmp += victim->GetMaxPositiveAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel)) * 100;
tmp += victim->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel)) * 100;
}
}
// Roll chance
if (rand < tmp)
return SPELL_MISS_RESIST;
// cast by caster in front of victim
if (victim->HasInArc(M_PI, this) || victim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
{
int32 deflect_chance = victim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS) * 100;
tmp += deflect_chance;
if (rand < tmp)
return SPELL_MISS_DEFLECT;
}
return SPELL_MISS_NONE;
}
// Calculate spell hit result can be:
// Every spell can: Evade/Immune/Reflect/Sucesful hit
// For melee based spells:
// Miss
// Dodge
// Parry
// For spells
// Resist
SpellMissInfo Unit::SpellHitResult(Unit* victim, SpellInfo const* spell, bool CanReflect)
{
// Check for immune
if (victim->IsImmunedToSpell(spell))
return SPELL_MISS_IMMUNE;
// All positive spells can`t miss
// TODO: client not show miss log for this spells - so need find info for this in dbc and use it!
if (spell->IsPositive()
&&(!IsHostileTo(victim))) // prevent from affecting enemy by "positive" spell
return SPELL_MISS_NONE;
// Check for immune
if (victim->IsImmunedToDamage(spell))
return SPELL_MISS_IMMUNE;
if (this == victim)
return SPELL_MISS_NONE;
// Return evade for units in evade mode
if (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsInEvadeMode())
return SPELL_MISS_EVADE;
// If target has evasive maneuvers result should always be dodge
if(isInEvasiveManeuvers(victim))
return SPELL_MISS_RESIST;
// Try victim reflect spell
if (CanReflect)
{
int32 reflectchance = victim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS);
Unit::AuraEffectList const& mReflectSpellsSchool = victim->GetAuraEffectsByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL);
for (Unit::AuraEffectList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i)
if ((*i)->GetMiscValue() & spell->GetSchoolMask())
reflectchance += (*i)->GetAmount();
if (reflectchance > 0 && roll_chance_i(reflectchance))
{
return SPELL_MISS_REFLECT;
}
}
switch (spell->DmgClass)
{
case SPELL_DAMAGE_CLASS_RANGED:
case SPELL_DAMAGE_CLASS_MELEE:
return MeleeSpellHitResult(victim, spell);
case SPELL_DAMAGE_CLASS_NONE:
return SPELL_MISS_NONE;
case SPELL_DAMAGE_CLASS_MAGIC:
return MagicSpellHitResult(victim, spell);
}
return SPELL_MISS_NONE;
}
uint32 Unit::GetDefenseSkillValue(Unit const* target) const
{
if (GetTypeId() == TYPEID_PLAYER)
{
// in PvP use full skill instead current skill value
uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER)
? ToPlayer()->GetMaxSkillValue(SKILL_DEFENSE)
: ToPlayer()->GetSkillValue(SKILL_DEFENSE);
value += uint32(ToPlayer()->GetRatingBonusValue(CR_DEFENSE_SKILL));
return value;
}
else
return GetUnitMeleeSkill(target);
}
float Unit::GetUnitDodgeChance() const
{
if (IsNonMeleeSpellCasted(false) || HasUnitState(UNIT_STAT_CONTROLLED))
return 0.0f;
if (GetTypeId() == TYPEID_PLAYER)
return GetFloatValue(PLAYER_DODGE_PERCENTAGE);
else
{
if (ToCreature()->isTotem())
return 0.0f;
else
{
float dodge = 5.0f;
dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
return dodge > 0.0f ? dodge : 0.0f;
}
}
}
float Unit::GetUnitParryChance() const
{
if (IsNonMeleeSpellCasted(false) || HasUnitState(UNIT_STAT_CONTROLLED))
return 0.0f;
float chance = 0.0f;
if (Player const* player = ToPlayer())
{
if (player->CanParry())
{
Item* tmpitem = player->GetWeaponForAttack(BASE_ATTACK, true);
if (!tmpitem)
tmpitem = player->GetWeaponForAttack(OFF_ATTACK, true);
if (tmpitem)
chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE);
}
}
else if (GetTypeId() == TYPEID_UNIT)
{
if (GetCreatureType() == CREATURE_TYPE_HUMANOID)
{
chance = 5.0f;
chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
}
}
return chance > 0.0f ? chance : 0.0f;
}
float Unit::GetUnitMissChance(WeaponAttackType attType) const
{
float miss_chance = 5.00f;
if (Player const* player = ToPlayer())
miss_chance += player->GetMissPercentageFromDefence();
if (attType == RANGED_ATTACK)
miss_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
else
miss_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
return miss_chance;
}
float Unit::GetUnitBlockChance() const
{
if (IsNonMeleeSpellCasted(false) || HasUnitState(UNIT_STAT_CONTROLLED))
return 0.0f;
if (Player const* player = ToPlayer())
{
if (player->CanBlock())
{
Item* tmpitem = player->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
if (tmpitem && !tmpitem->IsBroken() && tmpitem->GetTemplate()->Block)
return GetFloatValue(PLAYER_BLOCK_PERCENTAGE);
}
// is player but has no block ability or no not broken shield equipped
return 0.0f;
}
else
{
if (ToCreature()->isTotem())
return 0.0f;
else
{
float block = 5.0f;
block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
return block > 0.0f ? block : 0.0f;
}
}
}
float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit* victim) const
{
float crit;
if (GetTypeId() == TYPEID_PLAYER)
{
switch (attackType)
{
case BASE_ATTACK:
crit = GetFloatValue(PLAYER_CRIT_PERCENTAGE);
break;
case OFF_ATTACK:
crit = GetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE);
break;
case RANGED_ATTACK:
crit = GetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE);
break;
// Just for good manner
default:
crit = 0.0f;
break;
}
}
else
{
crit = 5.0f;
crit += GetTotalAuraModifier(SPELL_AURA_MOD_WEAPON_CRIT_PERCENT);
crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PCT);
}
// flat aura mods
if (attackType == RANGED_ATTACK)
crit += victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE);
else
crit += victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE);
crit += victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
// reduce crit chance from Rating for players
if (attackType != RANGED_ATTACK)
{
ApplyResilience(victim, &crit, NULL, false, CR_CRIT_TAKEN_MELEE);
// Glyph of barkskin
if (victim->HasAura(63057) && victim->HasAura(22812))
crit -= 25.0f;
}
else
ApplyResilience(victim, &crit, NULL, false, CR_CRIT_TAKEN_RANGED);
// Apply crit chance from defence skill
crit += (int32(GetMaxSkillValueForLevel(victim)) - int32(victim->GetDefenseSkillValue(this))) * 0.04f;
if (crit < 0.0f)
crit = 0.0f;
return crit;
}
uint32 Unit::GetWeaponSkillValue (WeaponAttackType attType, Unit const* target) const
{
uint32 value = 0;
if (Player const* player = ToPlayer())
{
Item* item = player->GetWeaponForAttack(attType, true);
// feral or unarmed skill only for base attack
if (attType != BASE_ATTACK && !item)
return 0;
if (IsInFeralForm())
return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact
// weapon skill or (unarmed for base attack and fist weapons)
uint32 skill;
if (item && item->GetSkill() != SKILL_FIST_WEAPONS)
skill = item->GetSkill();
else
skill = SKILL_UNARMED;
// in PvP use full skill instead current skill value
value = (target && target->IsControlledByPlayer())
? player->GetMaxSkillValue(skill)
: player->GetSkillValue(skill);
// Modify value from ratings
value += uint32(player->GetRatingBonusValue(CR_WEAPON_SKILL));
switch (attType)
{
case BASE_ATTACK: value += uint32(player->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND)); break;
case OFF_ATTACK: value += uint32(player->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND)); break;
case RANGED_ATTACK: value += uint32(player->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED)); break;
default: break;
}
}
else
value = GetUnitMeleeSkill(target);
return value;
}
void Unit::_DeleteRemovedAuras()
{
while (!m_removedAuras.empty())
{
delete m_removedAuras.front();
m_removedAuras.pop_front();
}
}
void Unit::_UpdateSpells(uint32 time)
{
if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
_UpdateAutoRepeatSpell();
// remove finished spells from current pointers
for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
{
if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED)
{
m_currentSpells[i]->SetReferencedFromCurrent(false);
m_currentSpells[i] = NULL; // remove pointer
}
}
// m_auraUpdateIterator can be updated in indirect called code at aura remove to skip next planned to update but removed auras
for (m_auraUpdateIterator = m_ownedAuras.begin(); m_auraUpdateIterator != m_ownedAuras.end();)
{
Aura* i_aura = m_auraUpdateIterator->second;
++m_auraUpdateIterator; // need shift to next for allow update if need into aura update
i_aura->UpdateOwner(time, this);
}
// remove expired auras - do that after updates(used in scripts?)
for (AuraMap::iterator i = m_ownedAuras.begin(); i != m_ownedAuras.end();)
{
if (i->second->IsExpired())
RemoveOwnedAura(i, AURA_REMOVE_BY_EXPIRE);
else
++i;
}
for (VisibleAuraMap::iterator itr = m_visibleAuras.begin(); itr != m_visibleAuras.end(); ++itr)
if (itr->second->IsNeedClientUpdate())
itr->second->ClientUpdate();
_DeleteRemovedAuras();
if (!m_gameObj.empty())
{
GameObjectList::iterator itr;
for (itr = m_gameObj.begin(); itr != m_gameObj.end();)
{
if (!(*itr)->isSpawned())
{
(*itr)->SetOwnerGUID(0);
(*itr)->SetRespawnTime(0);
(*itr)->Delete();
m_gameObj.erase(itr++);
}
else
++itr;
}
}
}
void Unit::_UpdateAutoRepeatSpell()
{
// check "realtime" interrupts
if ((GetTypeId() == TYPEID_PLAYER && ToPlayer()->isMoving()) || IsNonMeleeSpellCasted(false, false, true, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id == 75))
{
// cancel wand shoot
if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75)
InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
m_AutoRepeatFirstCast = true;
return;
}
// apply delay (Auto Shot (spellID 75) not affected)
if (m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500 && m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75)
setAttackTimer(RANGED_ATTACK, 500);
m_AutoRepeatFirstCast = false;
// castroutine
if (isAttackReady(RANGED_ATTACK))
{
// Check if able to cast
if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CheckCast(true) != SPELL_CAST_OK)
{
InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
return;
}
// we want to shoot
Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, TRIGGERED_FULL_MASK);
spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets));
// all went good, reset attack
resetAttackTimer(RANGED_ATTACK);
}
}
void Unit::SetCurrentCastedSpell(Spell* pSpell)
{
ASSERT(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells
CurrentSpellTypes CSpellType = pSpell->GetCurrentContainer();
if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self
// break same type spell if it is not delayed
InterruptSpell(CSpellType, false);
// special breakage effects:
switch (CSpellType)
{
case CURRENT_GENERIC_SPELL:
{
// generic spells always break channeled not delayed spells
InterruptSpell(CURRENT_CHANNELED_SPELL, false);
// autorepeat breaking
if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
{
// break autorepeat if not Auto Shot
if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75)
InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
m_AutoRepeatFirstCast = true;
}
AddUnitState(UNIT_STAT_CASTING);
} break;
case CURRENT_CHANNELED_SPELL:
{
// channel spells always break generic non-delayed and any channeled spells
InterruptSpell(CURRENT_GENERIC_SPELL, false);
InterruptSpell(CURRENT_CHANNELED_SPELL);
// it also does break autorepeat if not Auto Shot
if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] &&
m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75)
InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
AddUnitState(UNIT_STAT_CASTING);
} break;
case CURRENT_AUTOREPEAT_SPELL:
{
// only Auto Shoot does not break anything
if (pSpell->m_spellInfo->Id != 75)
{
// generic autorepeats break generic non-delayed and channeled non-delayed spells
InterruptSpell(CURRENT_GENERIC_SPELL, false);
InterruptSpell(CURRENT_CHANNELED_SPELL, false);
}
// special action: set first cast flag
m_AutoRepeatFirstCast = true;
} break;
default:
{
// other spell types don't break anything now
} break;
}
// current spell (if it is still here) may be safely deleted now
if (m_currentSpells[CSpellType])
m_currentSpells[CSpellType]->SetReferencedFromCurrent(false);
// set new current spell
m_currentSpells[CSpellType] = pSpell;
pSpell->SetReferencedFromCurrent(true);
pSpell->m_selfContainer = &(m_currentSpells[pSpell->GetCurrentContainer()]);
}
void Unit::InterruptSpell(CurrentSpellTypes spellType, bool withDelayed, bool withInstant)
{
ASSERT(spellType < CURRENT_MAX_SPELL);
//sLog->outDebug(LOG_FILTER_UNITS, "Interrupt spell for unit %u.", GetEntry());
Spell* spell = m_currentSpells[spellType];
if (spell
&& (withDelayed || spell->getState() != SPELL_STATE_DELAYED)
&& (withInstant || spell->GetCastTime() > 0))
{
// for example, do not let self-stun aura interrupt itself
if (!spell->IsInterruptable())
return;
// send autorepeat cancel message for autorepeat spells
if (spellType == CURRENT_AUTOREPEAT_SPELL)
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->SendAutoRepeatCancel(this);
if (spell->getState() != SPELL_STATE_FINISHED)
spell->cancel();
m_currentSpells[spellType] = NULL;
spell->SetReferencedFromCurrent(false);
}
}
void Unit::FinishSpell(CurrentSpellTypes spellType, bool ok /*= true*/)
{
Spell* spell = m_currentSpells[spellType];
if (!spell)
return;
if (spellType == CURRENT_CHANNELED_SPELL)
spell->SendChannelUpdate(0);
spell->finish(ok);
}
bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat, bool isAutoshoot, bool skipInstant) const
{
// We don't do loop here to explicitly show that melee spell is excluded.
// Maybe later some special spells will be excluded too.
// if skipInstant then instant spells shouldn't count as being casted
if (skipInstant && m_currentSpells[CURRENT_GENERIC_SPELL] && !m_currentSpells[CURRENT_GENERIC_SPELL]->GetCastTime())
return false;
// generic spells are casted when they are not finished and not delayed
if (m_currentSpells[CURRENT_GENERIC_SPELL] &&
(m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
(withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED))
{
if (!isAutoshoot || !(m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->AttributesEx2 & SPELL_ATTR2_NOT_RESET_AUTO_ACTIONS))
return(true);
}
// channeled spells may be delayed, but they are still considered casted
else if (!skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] &&
(m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED))
{
if (!isAutoshoot || !(m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->AttributesEx2 & SPELL_ATTR2_NOT_RESET_AUTO_ACTIONS))
return(true);
}
// autorepeat spells may be finished or delayed, but they are still considered casted
else if (!skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
return(true);
return(false);
}
void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id, bool withInstant)
{
// generic spells are interrupted if they are not finished or delayed
if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id == spell_id))
InterruptSpell(CURRENT_GENERIC_SPELL, withDelayed, withInstant);
// autorepeat spells are interrupted if they are not finished or delayed
if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id == spell_id))
InterruptSpell(CURRENT_AUTOREPEAT_SPELL, withDelayed, withInstant);
// channeled spells are interrupted if they are not finished, even if they are delayed
if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id == spell_id))
InterruptSpell(CURRENT_CHANNELED_SPELL, true, true);
}
Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const
{
for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id == spell_id)
return m_currentSpells[i];
return NULL;
}
int32 Unit::GetCurrentSpellCastTime(uint32 spell_id) const
{
if (Spell const* spell = FindCurrentSpellBySpellId(spell_id))
return spell->GetCastTime();
return 0;
}
bool Unit::isInFrontInMap(Unit const* target, float distance, float arc) const
{
return IsWithinDistInMap(target, distance) && HasInArc(arc, target);
}
bool Unit::isInBackInMap(Unit const* target, float distance, float arc) const
{
return IsWithinDistInMap(target, distance) && !HasInArc(2 * M_PI - arc, target);
}
void Unit::SetFacingToObject(WorldObject* pObject)
{
// update orientation at server
SetOrientation(GetAngle(pObject));
// and client
WorldPacket data;
BuildHeartBeatMsg(&data);
SendMessageToSet(&data, false);
}
bool Unit::isInAccessiblePlaceFor(Creature const* c) const
{
if (IsInWater())
return c->canSwim();
else
return c->canWalk() || c->canFly();
}
bool Unit::IsInWater() const
{
return GetBaseMap()->IsInWater(GetPositionX(), GetPositionY(), GetPositionZ());
}
bool Unit::IsUnderWater() const
{
return GetBaseMap()->IsUnderWater(GetPositionX(), GetPositionY(), GetPositionZ());
}
void Unit::DeMorph()
{
SetDisplayId(GetNativeDisplayId());
}
Aura* Unit::_TryStackingOrRefreshingExistingAura(SpellInfo const* newAura, uint8 effMask, Unit* caster, int32* baseAmount /*= NULL*/, Item* castItem /*= NULL*/, uint64 casterGUID /*= 0*/)
{
ASSERT(casterGUID || caster);
if (!casterGUID)
casterGUID = caster->GetGUID();
// passive and Incanter's Absorption and auras with different type can stack with themselves any number of times
if (!newAura->IsMultiSlotAura())
{
// check if cast item changed
uint64 castItemGUID = 0;
if (castItem)
castItemGUID = castItem->GetGUID();
// find current aura from spell and change it's stackamount, or refresh it's duration
if (Aura* foundAura = GetOwnedAura(newAura->Id, casterGUID, (newAura->AttributesCu & SPELL_ATTR0_CU_ENCHANT_PROC) ? castItemGUID : 0, 0))
{
// effect masks do not match
// extremely rare case
// let's just recreate aura
if (effMask != foundAura->GetEffectMask())
return NULL;
// update basepoints with new values - effect amount will be recalculated in ModStackAmount
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (!foundAura->HasEffect(i))
continue;
int bp;
if (baseAmount)
bp = *(baseAmount + i);
else
bp = foundAura->GetSpellInfo()->Effects[i].BasePoints;
int32* oldBP = const_cast<int32*>(&(foundAura->GetEffect(i)->m_baseAmount));
*oldBP = bp;
}
// correct cast item guid if needed
if (castItemGUID != foundAura->GetCastItemGUID())
{
uint64* oldGUID = const_cast<uint64 *>(&foundAura->m_castItemGuid);
*oldGUID = castItemGUID;
}
// try to increase stack amount
foundAura->ModStackAmount(1);
return foundAura;
}
}
return NULL;
}
void Unit::_AddAura(UnitAura* aura, Unit* caster)
{
ASSERT(!m_cleanupDone);
m_ownedAuras.insert(AuraMap::value_type(aura->GetId(), aura));
_RemoveNoStackAurasDueToAura(aura);
if (aura->IsRemoved())
return;
aura->SetIsSingleTarget(caster && aura->GetSpellInfo()->IsSingleTarget());
if (aura->IsSingleTarget())
{
ASSERT((IsInWorld() && !IsDuringRemoveFromWorld()) || (aura->GetCasterGUID() == GetGUID()));
// register single target aura
caster->GetSingleCastAuras().push_back(aura);
// remove other single target auras
Unit::AuraList& scAuras = caster->GetSingleCastAuras();
for (Unit::AuraList::iterator itr = scAuras.begin(); itr != scAuras.end();)
{
if ((*itr) != aura &&
(*itr)->GetSpellInfo()->IsSingleTargetWith(aura->GetSpellInfo()))
{
(*itr)->Remove();
itr = scAuras.begin();
}
else
++itr;
}
}
}
// creates aura application instance and registers it in lists
// aura application effects are handled separately to prevent aura list corruption
AuraApplication * Unit::_CreateAuraApplication(Aura* aura, uint8 effMask)
{
// can't apply aura on unit which is going to be deleted - to not create a memory leak
ASSERT(!m_cleanupDone);
// aura musn't be removed
ASSERT(!aura->IsRemoved());
// aura mustn't be already applied on target
ASSERT (!aura->IsAppliedOnTarget(GetGUID()) && "Unit::_CreateAuraApplication: aura musn't be applied on target");
SpellInfo const* aurSpellInfo = aura->GetSpellInfo();
uint32 aurId = aurSpellInfo->Id;
// ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load)
if (!isAlive() && !aurSpellInfo->IsDeathPersistent() &&
(GetTypeId() != TYPEID_PLAYER || !ToPlayer()->GetSession()->PlayerLoading()))
return NULL;
Unit* caster = aura->GetCaster();
AuraApplication * aurApp = new AuraApplication(this, caster, aura, effMask);
m_appliedAuras.insert(AuraApplicationMap::value_type(aurId, aurApp));
if (aurSpellInfo->AuraInterruptFlags)
{
m_interruptableAuras.push_back(aurApp);
AddInterruptMask(aurSpellInfo->AuraInterruptFlags);
}
if (AuraStateType aState = aura->GetSpellInfo()->GetAuraState())
m_auraStateAuras.insert(AuraStateAurasMap::value_type(aState, aurApp));
aura->_ApplyForTarget(this, caster, aurApp);
return aurApp;
}
void Unit::_ApplyAuraEffect(Aura* aura, uint8 effIndex)
{
ASSERT(aura);
ASSERT(aura->HasEffect(effIndex));
AuraApplication * aurApp = aura->GetApplicationOfTarget(GetGUID());
ASSERT(aurApp);
if (!aurApp->GetEffectMask())
_ApplyAura(aurApp, 1<<effIndex);
else
aurApp->_HandleEffect(effIndex, true);
}
// handles effects of aura application
// should be done after registering aura in lists
void Unit::_ApplyAura(AuraApplication * aurApp, uint8 effMask)
{
Aura* aura = aurApp->GetBase();
_RemoveNoStackAurasDueToAura(aura);
if (aurApp->GetRemoveMode())
return;
// Update target aura state flag
if (AuraStateType aState = aura->GetSpellInfo()->GetAuraState())
ModifyAuraState(aState, true);
if (aurApp->GetRemoveMode())
return;
// Sitdown on apply aura req seated
if (aura->GetSpellInfo()->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED && !IsSitState())
SetStandState(UNIT_STAND_STATE_SIT);
Unit* caster = aura->GetCaster();
if (aurApp->GetRemoveMode())
return;
aura->HandleAuraSpecificMods(aurApp, caster, true, false);
// apply effects of the aura
for (uint8 i = 0 ; i < MAX_SPELL_EFFECTS; ++i)
{
if (effMask & 1<<i && (!aurApp->GetRemoveMode()))
aurApp->_HandleEffect(i, true);
}
}
// removes aura application from lists and unapplies effects
void Unit::_UnapplyAura(AuraApplicationMap::iterator &i, AuraRemoveMode removeMode)
{
AuraApplication * aurApp = i->second;
ASSERT(aurApp);
ASSERT(!aurApp->GetRemoveMode());
ASSERT(aurApp->GetTarget() == this);
aurApp->SetRemoveMode(removeMode);
Aura* aura = aurApp->GetBase();
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Aura %u now is remove mode %d", aura->GetId(), removeMode);
// dead loop is killing the server probably
ASSERT(m_removedAurasCount < 0xFFFFFFFF);
++m_removedAurasCount;
Unit* caster = aura->GetCaster();
// Remove all pointers from lists here to prevent possible pointer invalidation on spellcast/auraapply/auraremove
m_appliedAuras.erase(i);
if (aura->GetSpellInfo()->AuraInterruptFlags)
{
m_interruptableAuras.remove(aurApp);
UpdateInterruptMask();
}
bool auraStateFound = false;
AuraStateType auraState = aura->GetSpellInfo()->GetAuraState();
if (auraState)
{
bool canBreak = false;
// Get mask of all aurastates from remaining auras
for (AuraStateAurasMap::iterator itr = m_auraStateAuras.lower_bound(auraState); itr != m_auraStateAuras.upper_bound(auraState) && !(auraStateFound && canBreak);)
{
if (itr->second == aurApp)
{
m_auraStateAuras.erase(itr);
itr = m_auraStateAuras.lower_bound(auraState);
canBreak = true;
continue;
}
auraStateFound = true;
++itr;
}
}
aurApp->_Remove();
aura->_UnapplyForTarget(this, caster, aurApp);
// remove effects of the spell - needs to be done after removing aura from lists
for (uint8 itr = 0 ; itr < MAX_SPELL_EFFECTS; ++itr)
{
if (aurApp->HasEffect(itr))
aurApp->_HandleEffect(itr, false);
}
// all effect mustn't be applied
ASSERT(!aurApp->GetEffectMask());
// Remove totem at next update if totem loses its aura
if (aurApp->GetRemoveMode() == AURA_REMOVE_BY_EXPIRE && GetTypeId() == TYPEID_UNIT && ToCreature()->isTotem()&& ToTotem()->GetSummonerGUID() == aura->GetCasterGUID())
{
if (ToTotem()->GetSpell() == aura->GetId() && ToTotem()->GetTotemType() == TOTEM_PASSIVE)
ToTotem()->setDeathState(JUST_DIED);
}
// Remove aurastates only if were not found
if (!auraStateFound)
ModifyAuraState(auraState, false);
aura->HandleAuraSpecificMods(aurApp, caster, false, false);
// only way correctly remove all auras from list
//if (removedAuras != m_removedAurasCount) new aura may be added
i = m_appliedAuras.begin();
}
void Unit::_UnapplyAura(AuraApplication * aurApp, AuraRemoveMode removeMode)
{
// aura can be removed from unit only if it's applied on it, shouldn't happen
ASSERT(aurApp->GetBase()->GetApplicationOfTarget(GetGUID()) == aurApp);
uint32 spellId = aurApp->GetBase()->GetId();
for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);)
{
if (iter->second == aurApp)
{
_UnapplyAura(iter, removeMode);
return;
}
else
++iter;
}
ASSERT(false);
}
void Unit::_RemoveNoStackAurasDueToAura(Aura* aura)
{
SpellInfo const* spellProto = aura->GetSpellInfo();
// passive spell special case (only non stackable with ranks)
if (spellProto->IsPassiveStackableWithRanks())
return;
bool remove = false;
for (AuraMap::iterator i = m_ownedAuras.begin(); i != m_ownedAuras.end(); ++i)
{
if (remove)
{
remove = false;
i = m_ownedAuras.begin();
}
if (aura->CanStackWith(i->second))
continue;
RemoveOwnedAura(i, AURA_REMOVE_BY_DEFAULT);
if (i == m_ownedAuras.end())
break;
remove = true;
}
}
void Unit::_RegisterAuraEffect(AuraEffect* aurEff, bool apply)
{
if (apply)
m_modAuras[aurEff->GetAuraType()].push_back(aurEff);
else
m_modAuras[aurEff->GetAuraType()].remove(aurEff);
}
// All aura base removes should go threw this function!
void Unit::RemoveOwnedAura(AuraMap::iterator &i, AuraRemoveMode removeMode)
{
Aura* aura = i->second;
ASSERT(!aura->IsRemoved());
// if unit currently update aura list then make safe update iterator shift to next
if (m_auraUpdateIterator == i)
++m_auraUpdateIterator;
m_ownedAuras.erase(i);
m_removedAuras.push_back(aura);
// Unregister single target aura
if (aura->IsSingleTarget())
aura->UnregisterSingleTarget();
aura->_Remove(removeMode);
i = m_ownedAuras.begin();
}
void Unit::RemoveOwnedAura(uint32 spellId, uint64 casterGUID, uint8 reqEffMask, AuraRemoveMode removeMode)
{
for (AuraMap::iterator itr = m_ownedAuras.lower_bound(spellId); itr != m_ownedAuras.upper_bound(spellId);)
if (((itr->second->GetEffectMask() & reqEffMask) == reqEffMask) && (!casterGUID || itr->second->GetCasterGUID() == casterGUID))
{
RemoveOwnedAura(itr, removeMode);
itr = m_ownedAuras.lower_bound(spellId);
}
else
++itr;
}
void Unit::RemoveOwnedAura(Aura* aura, AuraRemoveMode removeMode)
{
if (aura->IsRemoved())
return;
ASSERT(aura->GetOwner() == this);
uint32 spellId = aura->GetId();
for (AuraMap::iterator itr = m_ownedAuras.lower_bound(spellId); itr != m_ownedAuras.upper_bound(spellId); ++itr)
if (itr->second == aura)
{
RemoveOwnedAura(itr, removeMode);
return;
}
ASSERT(false);
}
Aura* Unit::GetOwnedAura(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask, Aura* except) const
{
for (AuraMap::const_iterator itr = m_ownedAuras.lower_bound(spellId); itr != m_ownedAuras.upper_bound(spellId); ++itr)
if (((itr->second->GetEffectMask() & reqEffMask) == reqEffMask) && (!casterGUID || itr->second->GetCasterGUID() == casterGUID) && (!itemCasterGUID || itr->second->GetCastItemGUID() == itemCasterGUID) && (!except || except != itr->second))
return itr->second;
return NULL;
}
void Unit::RemoveAura(AuraApplicationMap::iterator &i, AuraRemoveMode mode)
{
AuraApplication * aurApp = i->second;
// Do not remove aura which is already being removed
if (aurApp->GetRemoveMode())
return;
Aura* aura = aurApp->GetBase();
_UnapplyAura(i, mode);
// Remove aura - for Area and Target auras
if (aura->GetOwner() == this)
aura->Remove(mode);
}
void Unit::RemoveAura(uint32 spellId, uint64 caster, uint8 reqEffMask, AuraRemoveMode removeMode)
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);)
{
Aura const* aura = iter->second->GetBase();
if (((aura->GetEffectMask() & reqEffMask) == reqEffMask)
&& (!caster || aura->GetCasterGUID() == caster))
{
RemoveAura(iter, removeMode);
return;
}
else
++iter;
}
}
void Unit::RemoveAura(AuraApplication * aurApp, AuraRemoveMode mode)
{
// we've special situation here, RemoveAura called while during aura removal
// this kind of call is needed only when aura effect removal handler
// or event triggered by it expects to remove
// not yet removed effects of an aura
if (aurApp->GetRemoveMode())
{
// remove remaining effects of an aura
for (uint8 itr = 0 ; itr < MAX_SPELL_EFFECTS; ++itr)
{
if (aurApp->HasEffect(itr))
aurApp->_HandleEffect(itr, false);
}
return;
}
// no need to remove
if (aurApp->GetBase()->GetApplicationOfTarget(GetGUID()) != aurApp || aurApp->GetBase()->IsRemoved())
return;
uint32 spellId = aurApp->GetBase()->GetId();
for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);)
{
if (aurApp == iter->second)
{
RemoveAura(iter, mode);
return;
}
else
++iter;
}
}
void Unit::RemoveAura(Aura* aura, AuraRemoveMode mode)
{
if (aura->IsRemoved())
return;
if (AuraApplication * aurApp = aura->GetApplicationOfTarget(GetGUID()))
RemoveAura(aurApp, mode);
}
void Unit::RemoveAurasDueToSpell(uint32 spellId, uint64 casterGUID, uint8 reqEffMask, AuraRemoveMode removeMode)
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);)
{
Aura const* aura = iter->second->GetBase();
if (((aura->GetEffectMask() & reqEffMask) == reqEffMask)
&& (!casterGUID || aura->GetCasterGUID() == casterGUID))
{
RemoveAura(iter, removeMode);
iter = m_appliedAuras.lower_bound(spellId);
}
else
++iter;
}
}
void Unit::RemoveAuraFromStack(uint32 spellId, uint64 casterGUID, AuraRemoveMode removeMode)
{
for (AuraMap::iterator iter = m_ownedAuras.lower_bound(spellId); iter != m_ownedAuras.upper_bound(spellId);)
{
Aura* aura = iter->second;
if ((aura->GetType() == UNIT_AURA_TYPE)
&& (!casterGUID || aura->GetCasterGUID() == casterGUID))
{
aura->ModStackAmount(-1, removeMode);
return;
}
else
++iter;
}
}
void Unit::RemoveAurasDueToSpellByDispel(uint32 spellId, uint64 casterGUID, Unit* dispeller, uint8 chargesRemoved/*= 1*/)
{
for (AuraMap::iterator iter = m_ownedAuras.lower_bound(spellId); iter != m_ownedAuras.upper_bound(spellId);)
{
Aura* aura = iter->second;
if (aura->GetCasterGUID() == casterGUID)
{
if (aura->GetSpellInfo()->AttributesEx7 & SPELL_ATTR7_DISPEL_CHARGES)
aura->ModCharges(-chargesRemoved, AURA_REMOVE_BY_ENEMY_SPELL);
else
aura->ModStackAmount(-chargesRemoved, AURA_REMOVE_BY_ENEMY_SPELL);
switch (aura->GetSpellInfo()->SpellFamilyName)
{
case SPELLFAMILY_WARLOCK:
{
// Unstable Affliction (crash if before removeaura?)
if (aura->GetSpellInfo()->SpellFamilyFlags[1] & 0x0100)
{
Unit* caster = aura->GetCaster();
if (!caster)
break;
if (AuraEffect const* aurEff = aura->GetEffect(EFFECT_0))
{
int32 damage = aurEff->GetAmount() * 9;
// backfire damage and silence
caster->CastCustomSpell(dispeller, 31117, &damage, NULL, NULL, true, NULL, aurEff);
}
}
break;
}
case SPELLFAMILY_DRUID:
{
// Lifebloom
if (aura->GetSpellInfo()->SpellFamilyFlags[1] & 0x10)
{
if (AuraEffect const* aurEff = aura->GetEffect(EFFECT_1))
{
// final heal
int32 healAmount = aurEff->GetAmount();
int32 stack = chargesRemoved;
CastCustomSpell(this, 33778, &healAmount, &stack, NULL, true, NULL, NULL, aura->GetCasterGUID());
// mana
if (Unit* caster = aura->GetCaster())
{
int32 mana = CalculatePctU(caster->GetCreateMana(), aura->GetSpellInfo()->ManaCostPercentage) * chargesRemoved / 2;
caster->CastCustomSpell(caster, 64372, &mana, NULL, NULL, true, NULL, NULL, aura->GetCasterGUID());
}
}
}
break;
}
case SPELLFAMILY_SHAMAN:
{
// Flame Shock
if (aura->GetSpellInfo()->SpellFamilyFlags[0] & 0x10000000)
{
if (Unit* caster = aura->GetCaster())
{
uint32 triggeredSpellId = 0;
// Lava Flows
if (AuraEffect const* aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_SHAMAN, 3087, 0))
{
switch (aurEff->GetId())
{
case 51482: // Rank 3
triggeredSpellId = 65264;
break;
case 51481: // Rank 2
triggeredSpellId = 65263;
break;
case 51480: // Rank 1
triggeredSpellId = 64694;
break;
default:
sLog->outError("Unit::RemoveAurasDueToSpellByDispel: Unknown rank of Lava Flows (%d) found", aurEff->GetId());
}
}
if (triggeredSpellId)
caster->CastSpell(caster, triggeredSpellId, true);
}
}
break;
}
default:
break;
}
return;
}
else
++iter;
}
}
void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit* stealer)
{
for (AuraMap::iterator iter = m_ownedAuras.lower_bound(spellId); iter != m_ownedAuras.upper_bound(spellId);)
{
Aura* aura = iter->second;
if (aura->GetCasterGUID() == casterGUID)
{
int32 damage[MAX_SPELL_EFFECTS];
int32 baseDamage[MAX_SPELL_EFFECTS];
uint8 effMask = 0;
uint8 recalculateMask = 0;
Unit* caster = aura->GetCaster();
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (aura->GetEffect(i))
{
baseDamage[i] = aura->GetEffect(i)->GetBaseAmount();
damage[i] = aura->GetEffect(i)->GetAmount();
effMask |= (1<<i);
if (aura->GetEffect(i)->CanBeRecalculated())
recalculateMask |= (1<<i);
}
else
{
baseDamage[i] = 0;
damage[i] = 0;
}
}
bool stealCharge = aura->GetSpellInfo()->AttributesEx7 & SPELL_ATTR7_DISPEL_CHARGES;
// Cast duration to unsigned to prevent permanent aura's such as Righteous Fury being permanently added to caster
uint32 dur = std::min(2u * MINUTE * IN_MILLISECONDS, uint32(aura->GetDuration()));
if (Aura* oldAura = stealer->GetAura(aura->GetId(), aura->GetCasterGUID()))
{
if (stealCharge)
oldAura->ModCharges(1);
else
oldAura->ModStackAmount(1);
oldAura->SetDuration(int32(dur));
}
else
{
// single target state must be removed before aura creation to preserve existing single target aura
if (aura->IsSingleTarget())
aura->UnregisterSingleTarget();
if (Aura* newAura = Aura::TryRefreshStackOrCreate(aura->GetSpellInfo(), effMask, stealer, NULL, &baseDamage[0], NULL, aura->GetCasterGUID()))
{
// created aura must not be single target aura,, so stealer won't loose it on recast
if (newAura->IsSingleTarget())
{
newAura->UnregisterSingleTarget();
// bring back single target aura status to the old aura
aura->SetIsSingleTarget(true);
caster->GetSingleCastAuras().push_back(aura);
}
// FIXME: using aura->GetMaxDuration() maybe not blizzlike but it fixes stealing of spells like Innervate
newAura->SetLoadedState(aura->GetMaxDuration(), int32(dur), stealCharge ? 1 : aura->GetCharges(), 1, recalculateMask, &damage[0]);
newAura->ApplyForTargets();
}
}
if (stealCharge)
aura->ModCharges(-1, AURA_REMOVE_BY_ENEMY_SPELL);
else
aura->ModStackAmount(-1, AURA_REMOVE_BY_ENEMY_SPELL);
return;
}
else
++iter;
}
}
void Unit::RemoveAurasDueToItemSpell(Item* castItem, uint32 spellId)
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);)
{
if (!castItem || iter->second->GetBase()->GetCastItemGUID() == castItem->GetGUID())
{
RemoveAura(iter);
iter = m_appliedAuras.upper_bound(spellId); // overwrite by more appropriate
}
else
++iter;
}
}
void Unit::RemoveAurasByType(AuraType auraType, uint64 casterGUID, Aura* except, bool negative, bool positive)
{
for (AuraEffectList::iterator iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end();)
{
Aura* aura = (*iter)->GetBase();
AuraApplication * aurApp = aura->GetApplicationOfTarget(GetGUID());
++iter;
if (aura != except && (!casterGUID || aura->GetCasterGUID() == casterGUID)
&& ((negative && !aurApp->IsPositive()) || (positive && aurApp->IsPositive())))
{
uint32 removedAuras = m_removedAurasCount;
RemoveAura(aurApp);
if (m_removedAurasCount > removedAuras + 1)
iter = m_modAuras[auraType].begin();
}
}
}
void Unit::RemoveAurasWithAttribute(uint32 flags)
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
{
SpellInfo const* spell = iter->second->GetBase()->GetSpellInfo();
if (spell->Attributes & flags)
RemoveAura(iter);
else
++iter;
}
}
void Unit::RemoveNotOwnSingleTargetAuras(uint32 newPhase)
{
// single target auras from other casters
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
{
AuraApplication const* aurApp = iter->second;
Aura const* aura = aurApp->GetBase();
if (aura->GetCasterGUID() != GetGUID() && aura->GetSpellInfo()->IsSingleTarget())
{
if (!newPhase)
RemoveAura(iter);
else
{
Unit* caster = aura->GetCaster();
if (!caster || !caster->InSamePhase(newPhase))
RemoveAura(iter);
else
++iter;
}
}
else
++iter;
}
// single target auras at other targets
AuraList& scAuras = GetSingleCastAuras();
for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end();)
{
Aura* aura = *iter;
if (aura->GetUnitOwner() != this && !aura->GetUnitOwner()->InSamePhase(newPhase))
{
aura->Remove();
iter = scAuras.begin();
}
else
++iter;
}
}
void Unit::RemoveAurasWithInterruptFlags(uint32 flag, uint32 except)
{
if (!(m_interruptMask & flag))
return;
// interrupt auras
for (AuraApplicationList::iterator iter = m_interruptableAuras.begin(); iter != m_interruptableAuras.end();)
{
Aura* aura = (*iter)->GetBase();
++iter;
if ((aura->GetSpellInfo()->AuraInterruptFlags & flag) && (!except || aura->GetId() != except))
{
uint32 removedAuras = m_removedAurasCount;
RemoveAura(aura);
if (m_removedAurasCount > removedAuras + 1)
iter = m_interruptableAuras.begin();
}
}
// interrupt channeled spell
if (Spell* spell = m_currentSpells[CURRENT_CHANNELED_SPELL])
if (spell->getState() == SPELL_STATE_CASTING
&& (spell->m_spellInfo->ChannelInterruptFlags & flag)
&& spell->m_spellInfo->Id != except)
InterruptNonMeleeSpells(false);
UpdateInterruptMask();
}
void Unit::RemoveAurasWithFamily(SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, uint64 casterGUID)
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
{
Aura const* aura = iter->second->GetBase();
if (!casterGUID || aura->GetCasterGUID() == casterGUID)
{
SpellInfo const* spell = aura->GetSpellInfo();
if (spell->SpellFamilyName == uint32(family) && spell->SpellFamilyFlags.HasFlag(familyFlag1, familyFlag2, familyFlag3))
{
RemoveAura(iter);
continue;
}
}
++iter;
}
}
void Unit::RemoveMovementImpairingAuras()
{
RemoveAurasWithMechanic((1<<MECHANIC_SNARE)|(1<<MECHANIC_ROOT));
}
void Unit::RemoveAurasWithMechanic(uint32 mechanic_mask, AuraRemoveMode removemode, uint32 except)
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
{
Aura const* aura = iter->second->GetBase();
if (!except || aura->GetId() != except)
{
if (aura->GetSpellInfo()->GetAllEffectsMechanicMask() & mechanic_mask)
{
RemoveAura(iter, removemode);
continue;
}
}
++iter;
}
}
void Unit::RemoveAreaAurasDueToLeaveWorld()
{
// make sure that all area auras not applied on self are removed - prevent access to deleted pointer later
for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();)
{
Aura* aura = iter->second;
++iter;
Aura::ApplicationMap const& appMap = aura->GetApplicationMap();
for (Aura::ApplicationMap::const_iterator itr = appMap.begin(); itr!= appMap.end();)
{
AuraApplication * aurApp = itr->second;
++itr;
Unit* target = aurApp->GetTarget();
if (target == this)
continue;
target->RemoveAura(aurApp);
// things linked on aura remove may apply new area aura - so start from the beginning
iter = m_ownedAuras.begin();
}
}
// remove area auras owned by others
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
{
if (iter->second->GetBase()->GetOwner() != this)
{
RemoveAura(iter);
}
else
++iter;
}
}
void Unit::RemoveAllAuras()
{
// this may be a dead loop if some events on aura remove will continiously apply aura on remove
// we want to have all auras removed, so use your brain when linking events
while (!m_appliedAuras.empty() || !m_ownedAuras.empty())
{
AuraApplicationMap::iterator aurAppIter;
for (aurAppIter = m_appliedAuras.begin(); aurAppIter != m_appliedAuras.end();)
_UnapplyAura(aurAppIter, AURA_REMOVE_BY_DEFAULT);
AuraMap::iterator aurIter;
for (aurIter = m_ownedAuras.begin(); aurIter != m_ownedAuras.end();)
RemoveOwnedAura(aurIter);
}
}
void Unit::RemoveArenaAuras()
{
// in join, remove positive buffs, on end, remove negative
// used to remove positive visible auras in arenas
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
{
AuraApplication const* aurApp = iter->second;
Aura const* aura = aurApp->GetBase();
if (!(aura->GetSpellInfo()->AttributesEx4 & SPELL_ATTR4_UNK21) // don't remove stances, shadowform, pally/hunter auras
&& !aura->IsPassive() // don't remove passive auras
&& (aurApp->IsPositive() || !(aura->GetSpellInfo()->AttributesEx3 & SPELL_ATTR3_DEATH_PERSISTENT))) // not negative death persistent auras
RemoveAura(iter);
else
++iter;
}
}
void Unit::RemoveAllAurasOnDeath()
{
// used just after dieing to remove all visible auras
// and disable the mods for the passive ones
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
{
Aura const* aura = iter->second->GetBase();
if (!aura->IsPassive() && !aura->IsDeathPersistent())
_UnapplyAura(iter, AURA_REMOVE_BY_DEATH);
else
++iter;
}
for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();)
{
Aura* aura = iter->second;
if (!aura->IsPassive() && !aura->IsDeathPersistent())
RemoveOwnedAura(iter, AURA_REMOVE_BY_DEATH);
else
++iter;
}
}
void Unit::RemoveAllAurasRequiringDeadTarget()
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
{
Aura const* aura = iter->second->GetBase();
if (!aura->IsPassive() && aura->GetSpellInfo()->IsRequiringDeadTarget())
_UnapplyAura(iter, AURA_REMOVE_BY_DEFAULT);
else
++iter;
}
for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();)
{
Aura* aura = iter->second;
if (!aura->IsPassive() && aura->GetSpellInfo()->IsRequiringDeadTarget())
RemoveOwnedAura(iter, AURA_REMOVE_BY_DEFAULT);
else
++iter;
}
}
void Unit::RemoveAllAurasExceptType(AuraType type)
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
{
Aura const* aura = iter->second->GetBase();
if (!aura->GetSpellInfo()->HasAura(type))
_UnapplyAura(iter, AURA_REMOVE_BY_DEFAULT);
else
++iter;
}
for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();)
{
Aura* aura = iter->second;
if (!aura->GetSpellInfo()->HasAura(type))
RemoveOwnedAura(iter, AURA_REMOVE_BY_DEFAULT);
else
++iter;
}
}
void Unit::DelayOwnedAuras(uint32 spellId, uint64 caster, int32 delaytime)
{
for (AuraMap::iterator iter = m_ownedAuras.lower_bound(spellId); iter != m_ownedAuras.upper_bound(spellId);++iter)
{
Aura* aura = iter->second;
if (!caster || aura->GetCasterGUID() == caster)
{
if (aura->GetDuration() < delaytime)
aura->SetDuration(0);
else
aura->SetDuration(aura->GetDuration() - delaytime);
// update for out of range group members (on 1 slot use)
aura->SetNeedClientUpdateForTargets();
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Aura %u partially interrupted on unit %u, new duration: %u ms", aura->GetId(), GetGUIDLow(), aura->GetDuration());
}
}
}
void Unit::_RemoveAllAuraStatMods()
{
for (AuraApplicationMap::iterator i = m_appliedAuras.begin(); i != m_appliedAuras.end(); ++i)
(*i).second->GetBase()->HandleAllEffects(i->second, AURA_EFFECT_HANDLE_STAT, false);
}
void Unit::_ApplyAllAuraStatMods()
{
for (AuraApplicationMap::iterator i = m_appliedAuras.begin(); i != m_appliedAuras.end(); ++i)
(*i).second->GetBase()->HandleAllEffects(i->second, AURA_EFFECT_HANDLE_STAT, true);
}
AuraEffect* Unit::GetAuraEffect(uint32 spellId, uint8 effIndex, uint64 caster) const
{
for (AuraApplicationMap::const_iterator itr = m_appliedAuras.lower_bound(spellId); itr != m_appliedAuras.upper_bound(spellId); ++itr)
if (itr->second->HasEffect(effIndex) && (!caster || itr->second->GetBase()->GetCasterGUID() == caster))
return itr->second->GetBase()->GetEffect(effIndex);
return NULL;
}
AuraEffect* Unit::GetAuraEffectOfRankedSpell(uint32 spellId, uint8 effIndex, uint64 caster) const
{
uint32 rankSpell = sSpellMgr->GetFirstSpellInChain(spellId);
while (rankSpell)
{
if (AuraEffect* aurEff = GetAuraEffect(rankSpell, effIndex, caster))
return aurEff;
rankSpell = sSpellMgr->GetNextSpellInChain(rankSpell);
}
return NULL;
}
AuraEffect* Unit::GetAuraEffect(AuraType type, SpellFamilyNames name, uint32 iconId, uint8 effIndex) const
{
AuraEffectList const& auras = GetAuraEffectsByType(type);
for (Unit::AuraEffectList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
{
if (effIndex != (*itr)->GetEffIndex())
continue;
SpellInfo const* spell = (*itr)->GetSpellInfo();
if (spell->SpellIconID == iconId && spell->SpellFamilyName == uint32(name) && !spell->SpellFamilyFlags)
return *itr;
}
return NULL;
}
AuraEffect* Unit::GetAuraEffect(AuraType type, SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, uint64 casterGUID)
{
AuraEffectList const& auras = GetAuraEffectsByType(type);
for (AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i)
{
SpellInfo const* spell = (*i)->GetSpellInfo();
if (spell->SpellFamilyName == uint32(family) && spell->SpellFamilyFlags.HasFlag(familyFlag1, familyFlag2, familyFlag3))
{
if (casterGUID && (*i)->GetCasterGUID() != casterGUID)
continue;
return (*i);
}
}
return NULL;
}
AuraApplication * Unit::GetAuraApplication(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask, AuraApplication * except) const
{
for (AuraApplicationMap::const_iterator itr = m_appliedAuras.lower_bound(spellId); itr != m_appliedAuras.upper_bound(spellId); ++itr)
{
Aura const* aura = itr->second->GetBase();
if (((aura->GetEffectMask() & reqEffMask) == reqEffMask) && (!casterGUID || aura->GetCasterGUID() == casterGUID) && (!itemCasterGUID || aura->GetCastItemGUID() == itemCasterGUID) && (!except || except != itr->second))
return itr->second;
}
return NULL;
}
Aura* Unit::GetAura(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask) const
{
AuraApplication * aurApp = GetAuraApplication(spellId, casterGUID, itemCasterGUID, reqEffMask);
return aurApp ? aurApp->GetBase() : NULL;
}
AuraApplication * Unit::GetAuraApplicationOfRankedSpell(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask, AuraApplication* except) const
{
uint32 rankSpell = sSpellMgr->GetFirstSpellInChain(spellId);
while (rankSpell)
{
if (AuraApplication * aurApp = GetAuraApplication(rankSpell, casterGUID, itemCasterGUID, reqEffMask, except))
return aurApp;
rankSpell = sSpellMgr->GetNextSpellInChain(rankSpell);
}
return NULL;
}
Aura* Unit::GetAuraOfRankedSpell(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask) const
{
AuraApplication * aurApp = GetAuraApplicationOfRankedSpell(spellId, casterGUID, itemCasterGUID, reqEffMask);
return aurApp ? aurApp->GetBase() : NULL;
}
bool Unit::HasAuraEffect(uint32 spellId, uint8 effIndex, uint64 caster) const
{
for (AuraApplicationMap::const_iterator itr = m_appliedAuras.lower_bound(spellId); itr != m_appliedAuras.upper_bound(spellId); ++itr)
if (itr->second->HasEffect(effIndex) && (!caster || itr->second->GetBase()->GetCasterGUID() == caster))
return true;
return false;
}
uint32 Unit::GetAuraCount(uint32 spellId) const
{
uint32 count = 0;
for (AuraApplicationMap::const_iterator itr = m_appliedAuras.lower_bound(spellId); itr != m_appliedAuras.upper_bound(spellId); ++itr)
{
if (!itr->second->GetBase()->GetStackAmount())
count++;
else
count += (uint32)itr->second->GetBase()->GetStackAmount();
}
return count;
}
bool Unit::HasAura(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask) const
{
if (GetAuraApplication(spellId, casterGUID, itemCasterGUID, reqEffMask))
return true;
return false;
}
bool Unit::HasAuraType(AuraType auraType) const
{
return (!m_modAuras[auraType].empty());
}
bool Unit::HasAuraTypeWithCaster(AuraType auratype, uint64 caster) const
{
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
if (caster == (*i)->GetCasterGUID())
return true;
return false;
}
bool Unit::HasAuraTypeWithMiscvalue(AuraType auratype, int32 miscvalue) const
{
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
if (miscvalue == (*i)->GetMiscValue())
return true;
return false;
}
bool Unit::HasAuraTypeWithAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const
{
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
if ((*i)->IsAffectedOnSpell(affectedSpell))
return true;
return false;
}
bool Unit::HasAuraTypeWithValue(AuraType auratype, int32 value) const
{
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
if (value == (*i)->GetAmount())
return true;
return false;
}
bool Unit::HasNegativeAuraWithInterruptFlag(uint32 flag, uint64 guid)
{
if (!(m_interruptMask & flag))
return false;
for (AuraApplicationList::iterator iter = m_interruptableAuras.begin(); iter != m_interruptableAuras.end(); ++iter)
{
if (!(*iter)->IsPositive() && (*iter)->GetBase()->GetSpellInfo()->AuraInterruptFlags & flag && (!guid || (*iter)->GetBase()->GetCasterGUID() == guid))
return true;
}
return false;
}
bool Unit::HasNegativeAuraWithAttribute(uint32 flag, uint64 guid)
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end(); ++iter)
{
Aura const* aura = iter->second->GetBase();
if (!iter->second->IsPositive() && aura->GetSpellInfo()->Attributes & flag && (!guid || aura->GetCasterGUID() == guid))
return true;
}
return false;
}
bool Unit::HasAuraWithMechanic(uint32 mechanicMask)
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end(); ++iter)
{
SpellInfo const* spellInfo = iter->second->GetBase()->GetSpellInfo();
if (spellInfo->Mechanic && (mechanicMask & (1 << spellInfo->Mechanic)))
return true;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (iter->second->HasEffect(i) && spellInfo->Effects[i].Effect && spellInfo->Effects[i].Mechanic)
if (mechanicMask & (1 << spellInfo->Effects[i].Mechanic))
return true;
}
return false;
}
AuraEffect* Unit::IsScriptOverriden(SpellInfo const* spell, int32 script) const
{
AuraEffectList const& auras = GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
for (AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i)
{
if ((*i)->GetMiscValue() == script)
if ((*i)->IsAffectedOnSpell(spell))
return (*i);
}
return NULL;
}
uint32 Unit::GetDiseasesByCaster(uint64 casterGUID, bool remove)
{
static const AuraType diseaseAuraTypes[] =
{
SPELL_AURA_PERIODIC_DAMAGE, // Frost Fever and Blood Plague
SPELL_AURA_LINKED, // Crypt Fever and Ebon Plague
SPELL_AURA_NONE
};
uint32 diseases = 0;
for (AuraType const* itr = &diseaseAuraTypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
{
for (AuraEffectList::iterator i = m_modAuras[*itr].begin(); i != m_modAuras[*itr].end();)
{
// Get auras with disease dispel type by caster
if ((*i)->GetSpellInfo()->Dispel == DISPEL_DISEASE
&& (*i)->GetCasterGUID() == casterGUID)
{
++diseases;
if (remove)
{
RemoveAura((*i)->GetId(), (*i)->GetCasterGUID());
i = m_modAuras[*itr].begin();
continue;
}
}
++i;
}
}
return diseases;
}
uint32 Unit::GetDoTsByCaster(uint64 casterGUID) const
{
static const AuraType diseaseAuraTypes[] =
{
SPELL_AURA_PERIODIC_DAMAGE,
SPELL_AURA_PERIODIC_DAMAGE_PERCENT,
SPELL_AURA_NONE
};
uint32 dots = 0;
for (AuraType const* itr = &diseaseAuraTypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
{
Unit::AuraEffectList const& auras = GetAuraEffectsByType(*itr);
for (AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i)
{
// Get auras by caster
if ((*i)->GetCasterGUID() == casterGUID)
++dots;
}
}
return dots;
}
int32 Unit::GetTotalAuraModifier(AuraType auratype) const
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
modifier += (*i)->GetAmount();
return modifier;
}
float Unit::GetTotalAuraMultiplier(AuraType auratype) const
{
float multiplier = 1.0f;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
AddPctN(multiplier, (*i)->GetAmount());
return multiplier;
}
int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype)
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->GetAmount() > modifier)
modifier = (*i)->GetAmount();
}
return modifier;
}
int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
if ((*i)->GetAmount() < modifier)
modifier = (*i)->GetAmount();
return modifier;
}
int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->GetMiscValue()& misc_mask)
modifier += (*i)->GetAmount();
}
return modifier;
}
float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const
{
std::map<SpellGroup, int32> SameEffectSpellGroup;
float multiplier = 1.0f;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if (((*i)->GetMiscValue() & misc_mask))
{
// Check if the Aura Effect has a the Same Effect Stack Rule and if so, use the highest amount of that SpellGroup
// If the Aura Effect does not have this Stack Rule, it returns false so we can add to the multiplier as usual
if (!sSpellMgr->AddSameEffectStackRuleSpellGroups((*i)->GetSpellInfo(), (*i)->GetAmount(), SameEffectSpellGroup))
AddPctN(multiplier, (*i)->GetAmount());
}
}
// Add the highest of the Same Effect Stack Rule SpellGroups to the multiplier
for (std::map<SpellGroup, int32>::const_iterator itr = SameEffectSpellGroup.begin(); itr != SameEffectSpellGroup.end(); ++itr)
{
AddPctN(multiplier, itr->second);
}
return multiplier;
}
int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask, const AuraEffect* except) const
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if (except != (*i) && (*i)->GetMiscValue()& misc_mask && (*i)->GetAmount() > modifier)
modifier = (*i)->GetAmount();
}
return modifier;
}
int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->GetMiscValue()& misc_mask && (*i)->GetAmount() < modifier)
modifier = (*i)->GetAmount();
}
return modifier;
}
int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->GetMiscValue() == misc_value)
modifier += (*i)->GetAmount();
}
return modifier;
}
float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const
{
float multiplier = 1.0f;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->GetMiscValue() == misc_value)
AddPctN(multiplier, (*i)->GetAmount());
}
return multiplier;
}
int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->GetMiscValue() == misc_value && (*i)->GetAmount() > modifier)
modifier = (*i)->GetAmount();
}
return modifier;
}
int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->GetMiscValue() == misc_value && (*i)->GetAmount() < modifier)
modifier = (*i)->GetAmount();
}
return modifier;
}
int32 Unit::GetTotalAuraModifierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->IsAffectedOnSpell(affectedSpell))
modifier += (*i)->GetAmount();
}
return modifier;
}
float Unit::GetTotalAuraMultiplierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const
{
float multiplier = 1.0f;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->IsAffectedOnSpell(affectedSpell))
AddPctN(multiplier, (*i)->GetAmount());
}
return multiplier;
}
int32 Unit::GetMaxPositiveAuraModifierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->IsAffectedOnSpell(affectedSpell) && (*i)->GetAmount() > modifier)
modifier = (*i)->GetAmount();
}
return modifier;
}
int32 Unit::GetMaxNegativeAuraModifierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->IsAffectedOnSpell(affectedSpell) && (*i)->GetAmount() < modifier)
modifier = (*i)->GetAmount();
}
return modifier;
}
void Unit::_RegisterDynObject(DynamicObject* dynObj)
{
m_dynObj.push_back(dynObj);
}
void Unit::_UnregisterDynObject(DynamicObject* dynObj)
{
m_dynObj.remove(dynObj);
}
DynamicObject* Unit::GetDynObject(uint32 spellId)
{
if (m_dynObj.empty())
return NULL;
for (DynObjectList::const_iterator i = m_dynObj.begin(); i != m_dynObj.end();++i)
{
DynamicObject* dynObj = *i;
if (dynObj->GetSpellId() == spellId)
return dynObj;
}
return NULL;
}
void Unit::RemoveDynObject(uint32 spellId)
{
if (m_dynObj.empty())
return;
for (DynObjectList::iterator i = m_dynObj.begin(); i != m_dynObj.end();)
{
DynamicObject* dynObj = *i;
if (dynObj->GetSpellId() == spellId)
{
dynObj->Remove();
i = m_dynObj.begin();
}
else
++i;
}
}
void Unit::RemoveAllDynObjects()
{
while (!m_dynObj.empty())
m_dynObj.front()->Remove();
}
GameObject* Unit::GetGameObject(uint32 spellId) const
{
for (GameObjectList::const_iterator i = m_gameObj.begin(); i != m_gameObj.end(); ++i)
if ((*i)->GetSpellId() == spellId)
return *i;
return NULL;
}
void Unit::AddGameObject(GameObject* gameObj)
{
if (!gameObj || !gameObj->GetOwnerGUID() == 0) return;
m_gameObj.push_back(gameObj);
gameObj->SetOwnerGUID(GetGUID());
if (GetTypeId() == TYPEID_PLAYER && gameObj->GetSpellId())
{
SpellInfo const* createBySpell = sSpellMgr->GetSpellInfo(gameObj->GetSpellId());
// Need disable spell use for owner
if (createBySpell && createBySpell->Attributes & SPELL_ATTR0_DISABLED_WHILE_ACTIVE)
// note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
ToPlayer()->AddSpellAndCategoryCooldowns(createBySpell, 0, NULL, true);
}
}
void Unit::RemoveGameObject(GameObject* gameObj, bool del)
{
if (!gameObj || !gameObj->GetOwnerGUID() == GetGUID()) return;
gameObj->SetOwnerGUID(0);
for (uint8 i = 0; i < MAX_GAMEOBJECT_SLOT; ++i)
{
if (m_ObjectSlot[i] == gameObj->GetGUID())
{
m_ObjectSlot[i] = 0;
break;
}
}
// GO created by some spell
if (uint32 spellid = gameObj->GetSpellId())
{
RemoveAurasDueToSpell(spellid);
if (GetTypeId() == TYPEID_PLAYER)
{
SpellInfo const* createBySpell = sSpellMgr->GetSpellInfo(spellid);
// Need activate spell use for owner
if (createBySpell && createBySpell->Attributes & SPELL_ATTR0_DISABLED_WHILE_ACTIVE)
// note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
ToPlayer()->SendCooldownEvent(createBySpell);
}
}
m_gameObj.remove(gameObj);
if (del)
{
gameObj->SetRespawnTime(0);
gameObj->Delete();
}
}
void Unit::RemoveGameObject(uint32 spellid, bool del)
{
if (m_gameObj.empty())
return;
GameObjectList::iterator i, next;
for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next)
{
next = i;
if (spellid == 0 || (*i)->GetSpellId() == spellid)
{
(*i)->SetOwnerGUID(0);
if (del)
{
(*i)->SetRespawnTime(0);
(*i)->Delete();
}
next = m_gameObj.erase(i);
}
else
++next;
}
}
void Unit::RemoveAllGameObjects()
{
// remove references to unit
while (!m_gameObj.empty())
{
GameObjectList::iterator i = m_gameObj.begin();
(*i)->SetOwnerGUID(0);
(*i)->SetRespawnTime(0);
(*i)->Delete();
m_gameObj.erase(i);
}
}
void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage* log)
{
WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+4+1+4+4+1+1+4+4+1)); // we guess size
data.append(log->target->GetPackGUID());
data.append(log->attacker->GetPackGUID());
data << uint32(log->SpellID);
data << uint32(log->damage); // damage amount
int32 overkill = log->damage - log->target->GetHealth();
data << uint32(overkill > 0 ? overkill : 0); // overkill
data << uint8 (log->schoolMask); // damage school
data << uint32(log->absorb); // AbsorbedDamage
data << uint32(log->resist); // resist
data << uint8 (log->physicalLog); // if 1, then client show spell name (example: %s's ranged shot hit %s for %u school or %s suffers %u school damage from %s's spell_name
data << uint8 (log->unused); // unused
data << uint32(log->blocked); // blocked
data << uint32(log->HitInfo);
data << uint8 (0); // flag to use extend data
SendMessageToSet(&data, true);
}
void Unit::SendSpellNonMeleeDamageLog(Unit* target, uint32 SpellID, uint32 Damage, SpellSchoolMask damageSchoolMask, uint32 AbsorbedDamage, uint32 Resist, bool PhysicalDamage, uint32 Blocked, bool CriticalHit)
{
SpellNonMeleeDamage log(this, target, SpellID, damageSchoolMask);
log.damage = Damage - AbsorbedDamage - Resist - Blocked;
log.absorb = AbsorbedDamage;
log.resist = Resist;
log.physicalLog = PhysicalDamage;
log.blocked = Blocked;
log.HitInfo = SPELL_HIT_TYPE_UNK1 | SPELL_HIT_TYPE_UNK3 | SPELL_HIT_TYPE_UNK6;
if (CriticalHit)
log.HitInfo |= SPELL_HIT_TYPE_CRIT;
SendSpellNonMeleeDamageLog(&log);
}
void Unit::ProcDamageAndSpell(Unit* victim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellInfo const* procSpell, SpellInfo const* procAura)
{
// Not much to do if no flags are set.
if (procAttacker)
ProcDamageAndSpellFor(false, victim, procAttacker, procExtra, attType, procSpell, amount, procAura);
// Now go on with a victim's events'n'auras
// Not much to do if no flags are set or there is no victim
if (victim && victim->isAlive() && procVictim)
victim->ProcDamageAndSpellFor(true, this, procVictim, procExtra, attType, procSpell, amount, procAura);
}
void Unit::SendPeriodicAuraLog(SpellPeriodicAuraLogInfo* pInfo)
{
AuraEffect const* aura = pInfo->auraEff;
WorldPacket data(SMSG_PERIODICAURALOG, 30);
data.append(GetPackGUID());
data.appendPackGUID(aura->GetCasterGUID());
data << uint32(aura->GetId()); // spellId
data << uint32(1); // count
data << uint32(aura->GetAuraType()); // auraId
switch (aura->GetAuraType())
{
case SPELL_AURA_PERIODIC_DAMAGE:
case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
data << uint32(pInfo->damage); // damage
data << uint32(pInfo->overDamage); // overkill?
data << uint32(aura->GetSpellInfo()->GetSchoolMask());
data << uint32(pInfo->absorb); // absorb
data << uint32(pInfo->resist); // resist
data << uint8(pInfo->critical); // new 3.1.2 critical tick
break;
case SPELL_AURA_PERIODIC_HEAL:
case SPELL_AURA_OBS_MOD_HEALTH:
data << uint32(pInfo->damage); // damage
data << uint32(pInfo->overDamage); // overheal
data << uint32(pInfo->absorb); // absorb
data << uint8(pInfo->critical); // new 3.1.2 critical tick
break;
case SPELL_AURA_OBS_MOD_POWER:
case SPELL_AURA_PERIODIC_ENERGIZE:
data << uint32(aura->GetMiscValue()); // power type
data << uint32(pInfo->damage); // damage
break;
case SPELL_AURA_PERIODIC_MANA_LEECH:
data << uint32(aura->GetMiscValue()); // power type
data << uint32(pInfo->damage); // amount
data << float(pInfo->multiplier); // gain multiplier
break;
default:
sLog->outError("Unit::SendPeriodicAuraLog: unknown aura %u", uint32(aura->GetAuraType()));
return;
}
SendMessageToSet(&data, true);
}
void Unit::SendSpellMiss(Unit* target, uint32 spellID, SpellMissInfo missInfo)
{
WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1));
data << uint32(spellID);
data << uint64(GetGUID());
data << uint8(0); // can be 0 or 1
data << uint32(1); // target count
// for (i = 0; i < target count; ++i)
data << uint64(target->GetGUID()); // target GUID
data << uint8(missInfo);
// end loop
SendMessageToSet(&data, true);
}
void Unit::SendSpellDamageResist(Unit* target, uint32 spellId)
{
WorldPacket data(SMSG_PROCRESIST, 8+8+4+1);
data << uint64(GetGUID());
data << uint64(target->GetGUID());
data << uint32(spellId);
data << uint8(0); // bool - log format: 0-default, 1-debug
SendMessageToSet(&data, true);
}
void Unit::SendSpellDamageImmune(Unit* target, uint32 spellId)
{
WorldPacket data(SMSG_SPELLORDAMAGE_IMMUNE, 8+8+4+1);
data << uint64(GetGUID());
data << uint64(target->GetGUID());
data << uint32(spellId);
data << uint8(0); // bool - log format: 0-default, 1-debug
SendMessageToSet(&data, true);
}
void Unit::SendAttackStateUpdate(CalcDamageInfo* damageInfo)
{
sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Sending SMSG_ATTACKERSTATEUPDATE");
uint32 count = 1;
size_t maxsize = 4+5+5+4+4+1+4+4+4+4+4+1+4+4+4+4+4*12;
WorldPacket data(SMSG_ATTACKERSTATEUPDATE, maxsize); // we guess size
data << uint32(damageInfo->HitInfo);
data.append(damageInfo->attacker->GetPackGUID());
data.append(damageInfo->target->GetPackGUID());
data << uint32(damageInfo->damage); // Full damage
int32 overkill = damageInfo->damage - damageInfo->target->GetHealth();
data << uint32(overkill < 0 ? 0 : overkill); // Overkill
data << uint8(count); // Sub damage count
for (uint32 i = 0; i < count; ++i)
{
data << uint32(damageInfo->damageSchoolMask); // School of sub damage
data << float(damageInfo->damage); // sub damage
data << uint32(damageInfo->damage); // Sub Damage
}
if (damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
{
for (uint32 i = 0; i < count; ++i)
data << uint32(damageInfo->absorb); // Absorb
}
if (damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
{
for (uint32 i = 0; i < count; ++i)
data << uint32(damageInfo->resist); // Resist
}
data << uint8(damageInfo->TargetState);
data << uint32(0);
data << uint32(0);
if (damageInfo->HitInfo & HITINFO_BLOCK)
data << uint32(damageInfo->blocked_amount);
if (damageInfo->HitInfo & HITINFO_UNK3)
data << uint32(0);
if (damageInfo->HitInfo & HITINFO_UNK1)
{
data << uint32(0);
data << float(0);
data << float(0);
data << float(0);
data << float(0);
data << float(0);
data << float(0);
data << float(0);
data << float(0);
data << float(0); // Found in a loop with 1 iteration
data << float(0); // ditto ^
data << uint32(0);
}
SendMessageToSet(&data, true);
}
void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit* target, uint8 /*SwingType*/, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount)
{
CalcDamageInfo dmgInfo;
dmgInfo.HitInfo = HitInfo;
dmgInfo.attacker = this;
dmgInfo.target = target;
dmgInfo.damage = Damage - AbsorbDamage - Resist - BlockedAmount;
dmgInfo.damageSchoolMask = damageSchoolMask;
dmgInfo.absorb = AbsorbDamage;
dmgInfo.resist = Resist;
dmgInfo.TargetState = TargetState;
dmgInfo.blocked_amount = BlockedAmount;
SendAttackStateUpdate(&dmgInfo);
}
bool Unit::HandleHasteAuraProc(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
{
SpellInfo const* hasteSpell = triggeredByAura->GetSpellInfo();
Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
? ToPlayer()->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
uint32 triggered_spell_id = 0;
Unit* target = victim;
int32 basepoints0 = 0;
switch (hasteSpell->SpellFamilyName)
{
case SPELLFAMILY_ROGUE:
{
switch (hasteSpell->Id)
{
// Blade Flurry
case 13877:
case 33735:
{
target = SelectNearbyTarget();
if (!target || target == victim)
return false;
basepoints0 = damage;
triggered_spell_id = 22482;
break;
}
}
break;
}
}
// processed charge only counting case
if (!triggered_spell_id)
return true;
SpellInfo const* triggerEntry = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!triggerEntry)
{
sLog->outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u", hasteSpell->Id, triggered_spell_id);
return false;
}
if (cooldown && GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(triggered_spell_id))
return false;
if (basepoints0)
CastCustomSpell(target, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
else
CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura);
if (cooldown && GetTypeId() == TYPEID_PLAYER)
ToPlayer()->AddSpellCooldown(triggered_spell_id, 0, time(NULL) + cooldown);
return true;
}
bool Unit::HandleSpellCritChanceAuraProc(Unit* victim, uint32 /*damage*/, AuraEffect* triggeredByAura, SpellInfo const* /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
{
SpellInfo const* triggeredByAuraSpell = triggeredByAura->GetSpellInfo();
Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
? ToPlayer()->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
uint32 triggered_spell_id = 0;
Unit* target = victim;
int32 basepoints0 = 0;
switch (triggeredByAuraSpell->SpellFamilyName)
{
case SPELLFAMILY_MAGE:
{
switch (triggeredByAuraSpell->Id)
{
// Focus Magic
case 54646:
{
Unit* caster = triggeredByAura->GetCaster();
if (!caster)
return false;
triggered_spell_id = 54648;
target = caster;
break;
}
}
}
}
// processed charge only counting case
if (!triggered_spell_id)
return true;
SpellInfo const* triggerEntry = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!triggerEntry)
{
sLog->outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u", triggeredByAuraSpell->Id, triggered_spell_id);
return false;
}
// default case
if (!target || (target != this && !target->isAlive()))
return false;
if (cooldown && GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(triggered_spell_id))
return false;
if (basepoints0)
CastCustomSpell(target, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
else
CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura);
if (cooldown && GetTypeId() == TYPEID_PLAYER)
ToPlayer()->AddSpellCooldown(triggered_spell_id, 0, time(NULL) + cooldown);
return true;
}
//victim may be NULL
bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
{
SpellInfo const* dummySpell = triggeredByAura->GetSpellInfo();
uint32 effIndex = triggeredByAura->GetEffIndex();
int32 triggerAmount = triggeredByAura->GetAmount();
Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
? ToPlayer()->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
uint32 triggered_spell_id = 0;
uint32 cooldown_spell_id = 0; // for random trigger, will be one of the triggered spell to avoid repeatable triggers
// otherwise, it's the triggered_spell_id by default
Unit* target = victim;
int32 basepoints0 = 0;
uint64 originalCaster = 0;
switch (dummySpell->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
switch (dummySpell->Id)
{
// Bloodworms Health Leech
case 50453:
{
if (Unit* owner = GetOwner())
{
basepoints0 = int32(damage * 1.50f);
target = owner;
triggered_spell_id = 50454;
break;
}
return false;
}
// Eye for an Eye
case 9799:
case 25988:
{
// return damage % to attacker but < 50% own total health
basepoints0 = int32(std::min(CalculatePctN(damage, triggerAmount), CountPctFromMaxHealth(50)));
triggered_spell_id = 25997;
break;
}
// Sweeping Strikes
case 18765:
case 35429:
{
target = SelectNearbyTarget();
if (!target)
return false;
triggered_spell_id = 26654;
break;
}
// Unstable Power
case 24658:
{
if (!procSpell || procSpell->Id == 24659)
return false;
// Need remove one 24659 aura
RemoveAuraFromStack(24659);
return true;
}
// Restless Strength
case 24661:
{
// Need remove one 24662 aura
RemoveAuraFromStack(24662);
return true;
}
// Adaptive Warding (Frostfire Regalia set)
case 28764:
{
if (!procSpell)
return false;
// find Mage Armor
if (!GetAuraEffect(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT, SPELLFAMILY_MAGE, 0x10000000, 0, 0))
return false;
switch (GetFirstSchoolInMask(procSpell->GetSchoolMask()))
{
case SPELL_SCHOOL_NORMAL:
case SPELL_SCHOOL_HOLY:
return false; // ignored
case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break;
case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break;
case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break;
case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break;
case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break;
default:
return false;
}
target = this;
break;
}
// Obsidian Armor (Justice Bearer`s Pauldrons shoulder)
case 27539:
{
if (!procSpell)
return false;
switch (GetFirstSchoolInMask(procSpell->GetSchoolMask()))
{
case SPELL_SCHOOL_NORMAL:
return false; // ignore
case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break;
case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break;
case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break;
case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break;
case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break;
case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break;
default:
return false;
}
target = this;
break;
}
// Mana Leech (Passive) (Priest Pet Aura)
case 28305:
{
// Cast on owner
target = GetOwner();
if (!target)
return false;
triggered_spell_id = 34650;
break;
}
// Mark of Malice
case 33493:
{
// Cast finish spell at last charge
if (triggeredByAura->GetBase()->GetCharges() > 1)
return false;
target = this;
triggered_spell_id = 33494;
break;
}
//Item - Icecrown 25 Normal Tank Weapon Proc
case 71871:
{
triggered_spell_id = 71870;
target = this;
break;
}
//Item - Icecrown 25 Heroic Tank Weapon Proc
case 71873:
{
triggered_spell_id = 71872;
target = this;
break;
}
// Twisted Reflection (boss spell)
case 21063:
triggered_spell_id = 21064;
break;
//Item - Icecrown 25 Normal Caster Weapon Proc
case 71845:
{
triggered_spell_id = 71843;
target = this;
break;
}
//Item - Icecrown 25 Heroic Caster Weapon Proc
case 71846:
{
triggered_spell_id = 71844;
target = this;
break;
}
// Vampiric Aura (boss spell)
case 38196:
{
basepoints0 = 3 * damage; // 300%
if (basepoints0 < 0)
return false;
triggered_spell_id = 31285;
target = this;
break;
}
// Aura of Madness (Darkmoon Card: Madness trinket)
//=====================================================
// 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
// 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
// 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
// 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
// 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
// 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
// 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
// 41011 Martyr Complex: +35 stamina (All classes)
// 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
// 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
case 39446:
{
if (GetTypeId() != TYPEID_PLAYER || !isAlive())
return false;
// Select class defined buff
switch (getClass())
{
case CLASS_PALADIN: // 39511, 40997, 40998, 40999, 41002, 41005, 41009, 41011, 41409
case CLASS_DRUID: // 39511, 40997, 40998, 40999, 41002, 41005, 41009, 41011, 41409
triggered_spell_id = RAND(39511, 40997, 40998, 40999, 41002, 41005, 41009, 41011, 41409);
cooldown_spell_id = 39511;
break;
case CLASS_ROGUE: // 39511, 40997, 40998, 41002, 41005, 41011
case CLASS_WARRIOR: // 39511, 40997, 40998, 41002, 41005, 41011
case CLASS_DEATH_KNIGHT:
triggered_spell_id = RAND(39511, 40997, 40998, 41002, 41005, 41011);
cooldown_spell_id = 39511;
break;
case CLASS_PRIEST: // 40999, 41002, 41005, 41009, 41011, 41406, 41409
case CLASS_SHAMAN: // 40999, 41002, 41005, 41009, 41011, 41406, 41409
case CLASS_MAGE: // 40999, 41002, 41005, 41009, 41011, 41406, 41409
case CLASS_WARLOCK: // 40999, 41002, 41005, 41009, 41011, 41406, 41409
triggered_spell_id = RAND(40999, 41002, 41005, 41009, 41011, 41406, 41409);
cooldown_spell_id = 40999;
break;
case CLASS_HUNTER: // 40997, 40999, 41002, 41005, 41009, 41011, 41406, 41409
triggered_spell_id = RAND(40997, 40999, 41002, 41005, 41009, 41011, 41406, 41409);
cooldown_spell_id = 40997;
break;
default:
return false;
}
target = this;
if (roll_chance_i(10))
ToPlayer()->Say("This is Madness!", LANG_UNIVERSAL); // TODO: It should be moved to database, shouldn't it?
break;
}
// Sunwell Exalted Caster Neck (??? neck)
// cast ??? Light's Wrath if Exalted by Aldor
// cast ??? Arcane Bolt if Exalted by Scryers
case 46569:
return false; // old unused version
// Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
// cast 45479 Light's Wrath if Exalted by Aldor
// cast 45429 Arcane Bolt if Exalted by Scryers
case 45481:
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
// Get Aldor reputation rank
if (ToPlayer()->GetReputationRank(932) == REP_EXALTED)
{
target = this;
triggered_spell_id = 45479;
break;
}
// Get Scryers reputation rank
if (ToPlayer()->GetReputationRank(934) == REP_EXALTED)
{
// triggered at positive/self casts also, current attack target used then
if (target && IsFriendlyTo(target))
{
target = getVictim();
if (!target)
{
uint64 selected_guid = ToPlayer()->GetSelection();
target = ObjectAccessor::GetUnit(*this, selected_guid);
if (!target)
return false;
}
if (IsFriendlyTo(target))
return false;
}
triggered_spell_id = 45429;
break;
}
return false;
}
// Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
// cast 45480 Light's Strength if Exalted by Aldor
// cast 45428 Arcane Strike if Exalted by Scryers
case 45482:
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
// Get Aldor reputation rank
if (ToPlayer()->GetReputationRank(932) == REP_EXALTED)
{
target = this;
triggered_spell_id = 45480;
break;
}
// Get Scryers reputation rank
if (ToPlayer()->GetReputationRank(934) == REP_EXALTED)
{
triggered_spell_id = 45428;
break;
}
return false;
}
// Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
// cast 45431 Arcane Insight if Exalted by Aldor
// cast 45432 Light's Ward if Exalted by Scryers
case 45483:
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
// Get Aldor reputation rank
if (ToPlayer()->GetReputationRank(932) == REP_EXALTED)
{
target = this;
triggered_spell_id = 45432;
break;
}
// Get Scryers reputation rank
if (ToPlayer()->GetReputationRank(934) == REP_EXALTED)
{
target = this;
triggered_spell_id = 45431;
break;
}
return false;
}
// Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
// cast 45478 Light's Salvation if Exalted by Aldor
// cast 45430 Arcane Surge if Exalted by Scryers
case 45484:
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
// Get Aldor reputation rank
if (ToPlayer()->GetReputationRank(932) == REP_EXALTED)
{
target = this;
triggered_spell_id = 45478;
break;
}
// Get Scryers reputation rank
if (ToPlayer()->GetReputationRank(934) == REP_EXALTED)
{
triggered_spell_id = 45430;
break;
}
return false;
}
// Living Seed
case 48504:
{
triggered_spell_id = 48503;
basepoints0 = triggerAmount;
target = this;
break;
}
// Kill command
case 58914:
{
// Remove aura stack from pet
RemoveAuraFromStack(58914);
Unit* owner = GetOwner();
if (!owner)
return true;
// reduce the owner's aura stack
owner->RemoveAuraFromStack(34027);
return true;
}
// Vampiric Touch (generic, used by some boss)
case 52723:
case 60501:
{
triggered_spell_id = 52724;
basepoints0 = damage / 2;
target = this;
break;
}
// Shadowfiend Death (Gain mana if pet dies with Glyph of Shadowfiend)
case 57989:
{
Unit* owner = GetOwner();
if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
return false;
// Glyph of Shadowfiend (need cast as self cast for owner, no hidden cooldown)
owner->CastSpell(owner, 58227, true, castItem, triggeredByAura);
return true;
}
// Divine purpose
case 31871:
case 31872:
{
// Roll chane
if (!victim || !victim->isAlive() || !roll_chance_i(triggerAmount))
return false;
// Remove any stun effect on target
victim->RemoveAurasWithMechanic(1<<MECHANIC_STUN, AURA_REMOVE_BY_ENEMY_SPELL);
return true;
}
// Glyph of Scourge Strike
case 58642:
{
triggered_spell_id = 69961; // Glyph of Scourge Strike
break;
}
// Glyph of Life Tap
case 63320:
{
triggered_spell_id = 63321; // Life Tap
break;
}
// Purified Shard of the Scale - Onyxia 10 Caster Trinket
case 69755:
{
triggered_spell_id = (procFlag & PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS) ? 69733 : 69729;
break;
}
// Shiny Shard of the Scale - Onyxia 25 Caster Trinket
case 69739:
{
triggered_spell_id = (procFlag & PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS) ? 69734 : 69730;
break;
}
case 71519: // Deathbringer's Will Normal
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
std::vector<uint32> RandomSpells;
switch (getClass())
{
case CLASS_WARRIOR:
case CLASS_PALADIN:
case CLASS_DEATH_KNIGHT:
RandomSpells.push_back(71484);
RandomSpells.push_back(71491);
RandomSpells.push_back(71492);
break;
case CLASS_SHAMAN:
case CLASS_ROGUE:
RandomSpells.push_back(71486);
RandomSpells.push_back(71485);
RandomSpells.push_back(71492);
break;
case CLASS_DRUID:
RandomSpells.push_back(71484);
RandomSpells.push_back(71485);
RandomSpells.push_back(71486);
break;
case CLASS_HUNTER:
RandomSpells.push_back(71486);
RandomSpells.push_back(71491);
RandomSpells.push_back(71485);
break;
default:
return false;
}
if (RandomSpells.empty()) // shouldn't happen
return false;
uint8 rand_spell = irand(0, (RandomSpells.size() - 1));
CastSpell(target, RandomSpells[rand_spell], true, castItem, triggeredByAura, originalCaster);
for (std::vector<uint32>::iterator itr = RandomSpells.begin(); itr != RandomSpells.end(); ++itr)
{
if (!ToPlayer()->HasSpellCooldown(*itr))
ToPlayer()->AddSpellCooldown(*itr, 0, time(NULL) + cooldown);
}
break;
}
case 71562: // Deathbringer's Will Heroic
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
std::vector<uint32> RandomSpells;
switch (getClass())
{
case CLASS_WARRIOR:
case CLASS_PALADIN:
case CLASS_DEATH_KNIGHT:
RandomSpells.push_back(71561);
RandomSpells.push_back(71559);
RandomSpells.push_back(71560);
break;
case CLASS_SHAMAN:
case CLASS_ROGUE:
RandomSpells.push_back(71558);
RandomSpells.push_back(71556);
RandomSpells.push_back(71560);
break;
case CLASS_DRUID:
RandomSpells.push_back(71561);
RandomSpells.push_back(71556);
RandomSpells.push_back(71558);
break;
case CLASS_HUNTER:
RandomSpells.push_back(71558);
RandomSpells.push_back(71559);
RandomSpells.push_back(71556);
break;
default:
return false;
}
if (RandomSpells.empty()) // shouldn't happen
return false;
uint8 rand_spell = irand(0, (RandomSpells.size() - 1));
CastSpell(target, RandomSpells[rand_spell], true, castItem, triggeredByAura, originalCaster);
for (std::vector<uint32>::iterator itr = RandomSpells.begin(); itr != RandomSpells.end(); ++itr)
{
if (!ToPlayer()->HasSpellCooldown(*itr))
ToPlayer()->AddSpellCooldown(*itr, 0, time(NULL) + cooldown);
}
break;
}
// Item - Shadowmourne Legendary
case 71903:
{
if (!victim || !victim->isAlive() || HasAura(73422)) // cant collect shards while under effect of Chaos Bane buff
return false;
CastSpell(this, 71905, true, NULL, triggeredByAura);
// this can't be handled in AuraScript because we need to know victim
Aura const* dummy = GetAura(71905);
if (!dummy || dummy->GetStackAmount() < 10)
return false;
RemoveAurasDueToSpell(71905);
triggered_spell_id = 71904;
target = victim;
break;
}
// Shadow's Fate (Shadowmourne questline)
case 71169:
{
target = triggeredByAura->GetCaster();
if (!target)
return false;
Player* player = target->ToPlayer();
if (!player)
return false;
// not checking Infusion auras because its in targetAuraSpell of credit spell
if (player->GetQuestStatus(24749) == QUEST_STATUS_INCOMPLETE) // Unholy Infusion
{
if (GetEntry() != 36678) // Professor Putricide
return false;
CastSpell(target, 71518, true); // Quest Credit
return true;
}
else if (player->GetQuestStatus(24756) == QUEST_STATUS_INCOMPLETE) // Blood Infusion
{
if (GetEntry() != 37955) // Blood-Queen Lana'thel
return false;
CastSpell(target, 72934, true); // Quest Credit
return true;
}
else if (player->GetQuestStatus(24757) == QUEST_STATUS_INCOMPLETE) // Frost Infusion
{
if (GetEntry() != 36853) // Sindragosa
return false;
CastSpell(target, 72289, true); // Quest Credit
return true;
}
else if (player->GetQuestStatus(24547) == QUEST_STATUS_INCOMPLETE) // A Feast of Souls
triggered_spell_id = 71203;
break;
}
// Essence of the Blood Queen
case 70871:
{
basepoints0 = CalculatePctN(int32(damage), triggerAmount);
CastCustomSpell(70872, SPELLVALUE_BASE_POINT0, basepoints0, this);
return true;
}
case 65032: // Boom aura (321 Boombot)
{
if (victim->GetEntry() != 33343) // Scrapbot
return false;
InstanceScript* instance = GetInstanceScript();
if (!instance)
return false;
instance->DoCastSpellOnPlayers(65037); // Achievement criteria marker
break;
}
// Dark Hunger (The Lich King encounter)
case 69383:
{
basepoints0 = CalculatePctN(int32(damage), 50);
triggered_spell_id = 69384;
break;
}
}
break;
}
case SPELLFAMILY_MAGE:
{
// Magic Absorption
if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura
{
if (getPowerType() != POWER_MANA)
return false;
// mana reward
basepoints0 = CalculatePctN(int32(GetMaxPower(POWER_MANA)), triggerAmount);
target = this;
triggered_spell_id = 29442;
break;
}
// Master of Elements
if (dummySpell->SpellIconID == 1920)
{
if (!procSpell)
return false;
// mana cost save
int32 cost = int32(procSpell->ManaCost + CalculatePctU(GetCreateMana(), procSpell->ManaCostPercentage));
basepoints0 = CalculatePctN(cost, triggerAmount);
if (basepoints0 <= 0)
return false;
target = this;
triggered_spell_id = 29077;
break;
}
// Arcane Potency
if (dummySpell->SpellIconID == 2120)
{
if (!procSpell)
return false;
target = this;
switch (dummySpell->Id)
{
case 31571: triggered_spell_id = 57529; break;
case 31572: triggered_spell_id = 57531; break;
default:
sLog->outError("Unit::HandleDummyAuraProc: non handled spell id: %u", dummySpell->Id);
return false;
}
break;
}
// Hot Streak
if (dummySpell->SpellIconID == 2999)
{
if (effIndex != 0)
return false;
AuraEffect* counter = triggeredByAura->GetBase()->GetEffect(EFFECT_1);
if (!counter)
return true;
// Count spell criticals in a row in second aura
if (procEx & PROC_EX_CRITICAL_HIT)
{
counter->SetAmount(counter->GetAmount() * 2);
if (counter->GetAmount() < 100) // not enough
return true;
// Crititcal counted -> roll chance
if (roll_chance_i(triggerAmount))
CastSpell(this, 48108, true, castItem, triggeredByAura);
}
counter->SetAmount(25);
return true;
}
// Burnout
if (dummySpell->SpellIconID == 2998)
{
if (!procSpell)
return false;
int32 cost = int32(procSpell->ManaCost + CalculatePctU(GetCreateMana(), procSpell->ManaCostPercentage));
basepoints0 = CalculatePctN(cost, triggerAmount);
if (basepoints0 <= 0)
return false;
triggered_spell_id = 44450;
target = this;
break;
}
// Incanter's Regalia set (add trigger chance to Mana Shield)
if (dummySpell->SpellFamilyFlags[0] & 0x8000)
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
target = this;
triggered_spell_id = 37436;
break;
}
switch (dummySpell->Id)
{
// Glyph of Polymorph
case 56375:
{
if(!target)
return false;
target->RemoveAurasByType(SPELL_AURA_PERIODIC_DAMAGE, 0, target->GetAura(32409)); // SW:D shall not be removed.
target->RemoveAurasByType(SPELL_AURA_PERIODIC_DAMAGE_PERCENT);
target->RemoveAurasByType(SPELL_AURA_PERIODIC_LEECH);
return true;
}
// Glyph of Icy Veins
case 56374:
{
RemoveAurasByType(SPELL_AURA_HASTE_SPELLS, 0, 0, true, false);
RemoveAurasByType(SPELL_AURA_MOD_DECREASE_SPEED);
return true;
}
// Ignite
case 11119:
case 11120:
case 12846:
case 12847:
case 12848:
{
switch (dummySpell->Id)
{
case 11119: basepoints0 = int32(0.04f * damage); break;
case 11120: basepoints0 = int32(0.08f * damage); break;
case 12846: basepoints0 = int32(0.12f * damage); break;
case 12847: basepoints0 = int32(0.16f * damage); break;
case 12848: basepoints0 = int32(0.20f * damage); break;
default:
sLog->outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)", dummySpell->Id);
return false;
}
triggered_spell_id = 12654;
basepoints0 += victim->GetRemainingPeriodicAmount(GetGUID(), triggered_spell_id, SPELL_AURA_PERIODIC_DAMAGE);
break;
}
// Glyph of Ice Block
case 56372:
{
Player* player = ToPlayer();
if (!player)
return false;
SpellCooldowns const cooldowns = player->GetSpellCooldowns();
// remove cooldowns on all ranks of Frost Nova
for (SpellCooldowns::const_iterator itr = cooldowns.begin(); itr != cooldowns.end(); ++itr)
{
SpellInfo const* cdSpell = sSpellMgr->GetSpellInfo(itr->first);
// Frost Nova
if (cdSpell && cdSpell->SpellFamilyName == SPELLFAMILY_MAGE
&& cdSpell->SpellFamilyFlags[0] & 0x00000040)
player->RemoveSpellCooldown(cdSpell->Id, true);
}
break;
}
// Blessing of Ancient Kings (Val'anyr, Hammer of Ancient Kings)
case 64411:
{
if(!victim)
return false;
basepoints0 = int32(CalculatePctN(damage, 15));
if (AuraEffect* aurEff = victim->GetAuraEffect(64413, 0, GetGUID()))
{
// The shield can grow to a maximum size of 20, 000 damage absorbtion
aurEff->SetAmount(std::max<int32>(aurEff->GetAmount() + basepoints0, 20000));
// Refresh and return to prevent replacing the aura
aurEff->GetBase()->RefreshDuration();
return true;
}
target = victim;
triggered_spell_id = 64413;
break;
}
case 47020: // Enter vehicle XT-002 (Scrapbot)
{
if (GetTypeId() != TYPEID_UNIT)
return false;
Unit* vehicleBase = GetVehicleBase();
if (!vehicleBase)
return false;
// Todo: Check if this amount is blizzlike
vehicleBase->ModifyHealth(int32(vehicleBase->CountPctFromMaxHealth(1)));
break;
}
}
break;
}
case SPELLFAMILY_WARRIOR:
{
switch (dummySpell->Id)
{
// Sweeping Strikes
case 12328:
{
target = SelectNearbyTarget();
if (!target)
return false;
triggered_spell_id = 26654;
break;
}
// Victorious
case 32216:
{
RemoveAura(dummySpell->Id);
return false;
}
// Improved Spell Reflection
case 59088:
case 59089:
{
triggered_spell_id = 59725;
target = this;
break;
}
}
// Retaliation
if (dummySpell->SpellFamilyFlags[1] & 0x8)
{
// check attack comes not from behind
if (!HasInArc(M_PI, victim))
return false;
triggered_spell_id = 22858;
break;
}
// Second Wind
if (dummySpell->SpellIconID == 1697)
{
// only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == victim)
return false;
// Need stun or root mechanic
if (!(procSpell->GetAllEffectsMechanicMask() & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_STUN))))
return false;
switch (dummySpell->Id)
{
case 29838: triggered_spell_id=29842; break;
case 29834: triggered_spell_id=29841; break;
case 42770: triggered_spell_id=42771; break;
default:
sLog->outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)", dummySpell->Id);
return false;
}
target = this;
break;
}
// Damage Shield
if (dummySpell->SpellIconID == 3214)
{
triggered_spell_id = 59653;
// % of amount blocked
basepoints0 = CalculatePctN(int32(GetShieldBlockValue()), triggerAmount);
break;
}
// Glyph of Blocking
if (dummySpell->Id == 58375)
{
triggered_spell_id = 58374;
break;
}
// Glyph of Sunder Armor
if (dummySpell->Id == 58387)
{
if (!victim || !victim->isAlive() || !procSpell)
return false;
target = SelectNearbyTarget();
if (!target || target == victim)
return false;
CastSpell(target, 58567, true);
return true;
}
break;
}
case SPELLFAMILY_WARLOCK:
{
// Seed of Corruption
if (dummySpell->SpellFamilyFlags[1] & 0x00000010)
{
if (procSpell && procSpell->SpellFamilyFlags[1] & 0x8000)
return false;
// if damage is more than need or target die from damage deal finish spell
if (triggeredByAura->GetAmount() <= int32(damage) || GetHealth() <= damage)
{
// remember guid before aura delete
uint64 casterGuid = triggeredByAura->GetCasterGUID();
// Remove aura (before cast for prevent infinite loop handlers)
RemoveAurasDueToSpell(triggeredByAura->GetId());
uint32 spell = sSpellMgr->GetSpellWithRank(27285, dummySpell->GetRank());
// Cast finish spell (triggeredByAura already not exist!)
if (Unit* caster = GetUnit(*this, casterGuid))
caster->CastSpell(this, spell, true, castItem);
return true; // no hidden cooldown
}
// Damage counting
triggeredByAura->SetAmount(triggeredByAura->GetAmount() - damage);
return true;
}
// Seed of Corruption (Mobs cast) - no die req
if (dummySpell->SpellFamilyFlags.IsEqual(0, 0, 0) && dummySpell->SpellIconID == 1932)
{
// if damage is more than need deal finish spell
if (triggeredByAura->GetAmount() <= int32(damage))
{
// remember guid before aura delete
uint64 casterGuid = triggeredByAura->GetCasterGUID();
// Remove aura (before cast for prevent infinite loop handlers)
RemoveAurasDueToSpell(triggeredByAura->GetId());
// Cast finish spell (triggeredByAura already not exist!)
if (Unit* caster = GetUnit(*this, casterGuid))
caster->CastSpell(this, 32865, true, castItem);
return true; // no hidden cooldown
}
// Damage counting
triggeredByAura->SetAmount(triggeredByAura->GetAmount() - damage);
return true;
}
// Fel Synergy
if (dummySpell->SpellIconID == 3222)
{
target = GetGuardianPet();
if (!target)
return false;
basepoints0 = CalculatePctN(int32(damage), triggerAmount);
triggered_spell_id = 54181;
break;
}
switch (dummySpell->Id)
{
// Siphon Life
case 63108:
{
// Glyph of Siphon Life
if (HasAura(56216))
triggerAmount += triggerAmount / 4;
triggered_spell_id = 63106;
target = this;
basepoints0 = CalculatePctN(int32(damage), triggerAmount);
break;
}
// Glyph of Shadowflame
case 63310:
{
triggered_spell_id = 63311;
break;
}
// Nightfall
case 18094:
case 18095:
// Glyph of corruption
case 56218:
{
target = this;
triggered_spell_id = 17941;
break;
}
// Soul Leech
case 30293:
case 30295:
case 30296:
{
// Improved Soul Leech
AuraEffectList const& SoulLeechAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY);
for (Unit::AuraEffectList::const_iterator i = SoulLeechAuras.begin(); i != SoulLeechAuras.end(); ++i)
{
if ((*i)->GetId() == 54117 || (*i)->GetId() == 54118)
{
if ((*i)->GetEffIndex() != 0)
continue;
basepoints0 = int32((*i)->GetAmount());
target = GetGuardianPet();
if (target)
{
// regen mana for pet
CastCustomSpell(target, 54607, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
}
// regen mana for caster
CastCustomSpell(this, 59117, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
// Get second aura of spell for replenishment effect on party
if (AuraEffect const* aurEff = (*i)->GetBase()->GetEffect(EFFECT_1))
{
// Replenishment - roll chance
if (roll_chance_i(aurEff->GetAmount()))
{
CastSpell(this, 57669, true, castItem, triggeredByAura);
}
}
break;
}
}
// health
basepoints0 = CalculatePctN(int32(damage), triggerAmount);
target = this;
triggered_spell_id = 30294;
break;
}
// Shadowflame (Voidheart Raiment set bonus)
case 37377:
{
triggered_spell_id = 37379;
break;
}
// Pet Healing (Corruptor Raiment or Rift Stalker Armor)
case 37381:
{
target = GetGuardianPet();
if (!target)
return false;
// heal amount
basepoints0 = CalculatePctN(int32(damage), triggerAmount);
triggered_spell_id = 37382;
break;
}
// Shadowflame Hellfire (Voidheart Raiment set bonus)
case 39437:
{
triggered_spell_id = 37378;
break;
}
// Glyph of Succubus
case 56250:
{
if (!target)
return false;
target->RemoveAurasByType(SPELL_AURA_PERIODIC_DAMAGE, 0, target->GetAura(32409)); // SW:D shall not be removed.
target->RemoveAurasByType(SPELL_AURA_PERIODIC_DAMAGE_PERCENT);
target->RemoveAurasByType(SPELL_AURA_PERIODIC_LEECH);
return true;
}
}
break;
}
case SPELLFAMILY_PRIEST:
{
// Vampiric Touch
if (dummySpell->SpellFamilyFlags[1] & 0x00000400)
{
if (!victim || !victim->isAlive())
return false;
if (effIndex != 0)
return false;
// victim is caster of aura
if (triggeredByAura->GetCasterGUID() != victim->GetGUID())
return false;
// Energize 0.25% of max. mana
victim->CastSpell(victim, 57669, true, castItem, triggeredByAura);
return true; // no hidden cooldown
}
// Divine Aegis
if (dummySpell->SpellIconID == 2820)
{
if(!target)
return false;
// Multiple effects stack, so let's try to find this aura.
int32 bonus = 0;
if (AuraEffect const* aurEff = target->GetAuraEffect(47753, 0))
bonus = aurEff->GetAmount();
basepoints0 = CalculatePctN(int32(damage), triggerAmount) + bonus;
if (basepoints0 > target->getLevel() * 125)
basepoints0 = target->getLevel() * 125;
triggered_spell_id = 47753;
break;
}
// Body and Soul
if (dummySpell->SpellIconID == 2218)
{
// Proc only from Abolish desease on self cast
if (procSpell->Id != 552 || victim != this || !roll_chance_i(triggerAmount))
return false;
triggered_spell_id = 64136;
target = this;
break;
}
switch (dummySpell->Id)
{
// Vampiric Embrace
case 15286:
{
if (!victim || !victim->isAlive() || procSpell->SpellFamilyFlags[1] & 0x80000)
return false;
// heal amount
int32 total = CalculatePctN(int32(damage), triggerAmount);
int32 team = total / 5;
int32 self = total - team;
CastCustomSpell(this, 15290, &team, &self, NULL, true, castItem, triggeredByAura);
return true; // no hidden cooldown
}
// Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
case 40438:
{
// Shadow Word: Pain
if (procSpell->SpellFamilyFlags[0] & 0x8000)
triggered_spell_id = 40441;
// Renew
else if (procSpell->SpellFamilyFlags[0] & 0x40)
triggered_spell_id = 40440;
else
return false;
target = this;
break;
}
// Glyph of Prayer of Healing
case 55680:
{
triggered_spell_id = 56161;
SpellInfo const* GoPoH = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!GoPoH)
return false;
int EffIndex = 0;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; i++)
{
if (GoPoH->Effects[i].Effect == SPELL_EFFECT_APPLY_AURA)
{
EffIndex = i;
break;
}
}
int32 tickcount = GoPoH->GetMaxDuration() / GoPoH->Effects[EffIndex].Amplitude;
if (!tickcount)
return false;
basepoints0 = CalculatePctN(int32(damage), triggerAmount) / tickcount;
break;
}
// Improved Shadowform
case 47570:
case 47569:
{
if (!roll_chance_i(triggerAmount))
return false;
RemoveMovementImpairingAuras();
break;
}
// Glyph of Dispel Magic
case 55677:
{
// Dispel Magic shares spellfamilyflag with abolish disease
if (procSpell->SpellIconID != 74)
return false;
if (!target || !target->IsFriendlyTo(this))
return false;
basepoints0 = int32(target->CountPctFromMaxHealth(triggerAmount));
triggered_spell_id = 56131;
break;
}
// Oracle Healing Bonus ("Garments of the Oracle" set)
case 26169:
{
// heal amount
basepoints0 = int32(CalculatePctN(damage, 10));
target = this;
triggered_spell_id = 26170;
break;
}
// Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
case 39372:
{
if (!procSpell || (procSpell->GetSchoolMask() & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW)) == 0)
return false;
// heal amount
basepoints0 = CalculatePctN(int32(damage), triggerAmount);
target = this;
triggered_spell_id = 39373;
break;
}
// Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
case 28809:
{
triggered_spell_id = 28810;
break;
}
// Priest T10 Healer 2P Bonus
case 70770:
// Flash Heal
if (procSpell->SpellFamilyFlags[0] & 0x800)
{
triggered_spell_id = 70772;
SpellInfo const* blessHealing = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!blessHealing)
return false;
basepoints0 = int32(CalculatePctN(damage, triggerAmount) / (blessHealing->GetMaxDuration() / blessHealing->Effects[0].Amplitude));
}
break;
}
break;
}
case SPELLFAMILY_DRUID:
{
switch (dummySpell->Id)
{
// Glyph of Innervate
case 54832:
{
if (procSpell->SpellIconID != 62)
return false;
int32 mana_perc = triggeredByAura->GetSpellInfo()->Effects[triggeredByAura->GetEffIndex()].CalcValue();
basepoints0 = int32(CalculatePctN(GetCreatePowers(POWER_MANA), mana_perc) / 10);
triggered_spell_id = 54833;
target = this;
break;
}
// Glyph of Starfire
case 54845:
{
triggered_spell_id = 54846;
break;
}
// Glyph of Shred
case 54815:
{
if(!target)
return false;
// try to find spell Rip on the target
if (AuraEffect const* AurEff = target->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00800000, 0x0, 0x0, GetGUID()))
{
// Rip's max duration, note: spells which modifies Rip's duration also counted like Glyph of Rip
uint32 CountMin = AurEff->GetBase()->GetMaxDuration();
// just Rip's max duration without other spells
uint32 CountMax = AurEff->GetSpellInfo()->GetMaxDuration();
// add possible auras' and Glyph of Shred's max duration
CountMax += 3 * triggerAmount * IN_MILLISECONDS; // Glyph of Shred -> +6 seconds
CountMax += HasAura(54818) ? 4 * IN_MILLISECONDS : 0; // Glyph of Rip -> +4 seconds
CountMax += HasAura(60141) ? 4 * IN_MILLISECONDS : 0; // Rip Duration/Lacerate Damage -> +4 seconds
// if min < max -> that means caster didn't cast 3 shred yet
// so set Rip's duration and max duration
if (CountMin < CountMax)
{
AurEff->GetBase()->SetDuration(AurEff->GetBase()->GetDuration() + triggerAmount * IN_MILLISECONDS);
AurEff->GetBase()->SetMaxDuration(CountMin + triggerAmount * IN_MILLISECONDS);
return true;
}
}
// if not found Rip
return false;
}
// Glyph of Rake
case 54821:
{
if (procSpell->SpellVisual[0] == 750 && procSpell->Effects[1].ApplyAuraName == 3)
{
if (target && target->GetTypeId() == TYPEID_UNIT)
{
triggered_spell_id = 54820;
break;
}
}
return false;
}
// Leader of the Pack
case 24932:
{
if (triggerAmount <= 0)
return false;
basepoints0 = int32(CountPctFromMaxHealth(triggerAmount));
target = this;
triggered_spell_id = 34299;
if (triggeredByAura->GetCasterGUID() != GetGUID())
break;
int32 basepoints1 = triggerAmount * 2;
// Improved Leader of the Pack
// Check cooldown of heal spell cooldown
if (GetTypeId() == TYPEID_PLAYER && !ToPlayer()->HasSpellCooldown(34299))
CastCustomSpell(this, 60889, &basepoints1, 0, 0, true, 0, triggeredByAura);
break;
}
// Healing Touch (Dreamwalker Raiment set)
case 28719:
{
// mana back
basepoints0 = int32(CalculatePctN(procSpell->ManaCost, 30));
target = this;
triggered_spell_id = 28742;
break;
}
// Glyph of Rejuvenation
case 54754:
{
if (!victim || !victim->HealthBelowPct(uint32(triggerAmount)))
return false;
basepoints0 = CalculatePctN(int32(damage), triggerAmount);
triggered_spell_id = 54755;
break;
}
// Healing Touch Refund (Idol of Longevity trinket)
case 28847:
{
target = this;
triggered_spell_id = 28848;
break;
}
// Mana Restore (Malorne Raiment set / Malorne Regalia set)
case 37288:
case 37295:
{
target = this;
triggered_spell_id = 37238;
break;
}
// Druid Tier 6 Trinket
case 40442:
{
float chance;
// Starfire
if (procSpell->SpellFamilyFlags[0] & 0x4)
{
triggered_spell_id = 40445;
chance = 25.0f;
}
// Rejuvenation
else if (procSpell->SpellFamilyFlags[0] & 0x10)
{
triggered_spell_id = 40446;
chance = 25.0f;
}
// Mangle (Bear) and Mangle (Cat)
else if (procSpell->SpellFamilyFlags[1] & 0x00000440)
{
triggered_spell_id = 40452;
chance = 40.0f;
}
else
return false;
if (!roll_chance_f(chance))
return false;
target = this;
break;
}
// Maim Interrupt
case 44835:
{
// Deadly Interrupt Effect
triggered_spell_id = 32747;
break;
}
// Item - Druid T10 Balance 4P Bonus
case 70723:
{
// Wrath & Starfire
if ((procSpell->SpellFamilyFlags[0] & 0x5) && (procEx & PROC_EX_CRITICAL_HIT))
{
triggered_spell_id = 71023;
SpellInfo const* triggeredSpell = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!triggeredSpell)
return false;
basepoints0 = CalculatePctN(int32(damage), triggerAmount) / (triggeredSpell->GetMaxDuration() / triggeredSpell->Effects[0].Amplitude);
// Add remaining ticks to damage done
basepoints0 += victim->GetRemainingPeriodicAmount(GetGUID(), triggered_spell_id, SPELL_AURA_PERIODIC_DAMAGE);
}
break;
}
// Item - Druid T10 Restoration 4P Bonus (Rejuvenation)
case 70664:
{
// Proc only from normal Rejuvenation
if (procSpell->SpellVisual[0] != 32)
return false;
Player* caster = ToPlayer();
if (!caster)
return false;
if (!caster->GetGroup() && victim == this)
return false;
CastCustomSpell(70691, SPELLVALUE_BASE_POINT0, damage, victim, true);
return true;
}
}
// Eclipse
if (dummySpell->SpellIconID == 2856 && GetTypeId() == TYPEID_PLAYER)
{
if (!procSpell || effIndex != 0)
return false;
bool isWrathSpell = (procSpell->SpellFamilyFlags[0] & 1);
if (!roll_chance_f(dummySpell->ProcChance * (isWrathSpell ? 0.6f : 1.0f)))
return false;
target = this;
if (target->HasAura(isWrathSpell ? 48517 : 48518))
return false;
triggered_spell_id = isWrathSpell ? 48518 : 48517;
break;
}
// Living Seed
else if (dummySpell->SpellIconID == 2860)
{
triggered_spell_id = 48504;
basepoints0 = CalculatePctN(int32(damage), triggerAmount);
break;
}
// King of the Jungle
else if (dummySpell->SpellIconID == 2850)
{
// Effect 0 - mod damage while having Enrage
if (effIndex == 0)
{
if (!(procSpell->SpellFamilyFlags[0] & 0x00080000))
return false;
triggered_spell_id = 51185;
basepoints0 = triggerAmount;
target = this;
break;
}
// Effect 1 - Tiger's Fury restore energy
else if (effIndex == 1)
{
if (!(procSpell->SpellFamilyFlags[2] & 0x00000800))
return false;
triggered_spell_id = 51178;
basepoints0 = triggerAmount;
target = this;
break;
}
}
break;
}
case SPELLFAMILY_ROGUE:
{
switch (dummySpell->Id)
{
case 56800: // Glyph of Backstab
{
triggered_spell_id = 63975;
break;
}
case 32748: // Deadly Throw Interrupt
{
// Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
if (this == victim)
return false;
triggered_spell_id = 32747;
break;
}
case 57934: // Tricks of the Trade
{
Unit* redirectTarget = GetMisdirectionTarget();
RemoveAura(57934);
if (!redirectTarget)
break;
redirectTarget->CastSpell(this,59628,true);
CastSpell(redirectTarget,57933,true);
break;
}
}
switch (dummySpell->SpellIconID)
{
case 2116: // Quick Recovery
{
if (!procSpell)
return false;
// energy cost save
basepoints0 = CalculatePctN(int32(procSpell->ManaCost), triggerAmount);
if (basepoints0 <= 0)
return false;
target = this;
triggered_spell_id = 31663;
break;
}
case 2909: // Cut to the Chase
{
// "refresh your Slice and Dice duration to its 5 combo point maximum"
// lookup Slice and Dice
if (AuraEffect const* aur = GetAuraEffect(SPELL_AURA_MOD_MELEE_HASTE, SPELLFAMILY_ROGUE, 0x40000, 0, 0))
{
aur->GetBase()->SetDuration(aur->GetSpellInfo()->GetMaxDuration(), true);
return true;
}
return false;
}
case 2963: // Deadly Brew
{
triggered_spell_id = 3409;
break;
}
}
break;
}
case SPELLFAMILY_HUNTER:
{
switch (dummySpell->SpellIconID)
{
case 267: // Improved Mend Pet
{
int32 chance = triggeredByAura->GetSpellInfo()->Effects[triggeredByAura->GetEffIndex()].CalcValue();
if (!roll_chance_i(chance))
return false;
triggered_spell_id = 24406;
break;
}
case 2236: // Thrill of the Hunt
{
if (!procSpell)
return false;
Spell* spell = ToPlayer()->m_spellModTakingSpell;
// Disable charge drop because of Lock and Load
ToPlayer()->SetSpellModTakingSpell(spell, false);
// Explosive Shot
if (procSpell->SpellFamilyFlags[2] & 0x200)
{
if(!victim)
return false;
if (AuraEffect const* pEff = victim->GetAuraEffect(SPELL_AURA_PERIODIC_DUMMY, SPELLFAMILY_HUNTER, 0x0, 0x80000000, 0x0, GetGUID()))
basepoints0 = pEff->GetSpellInfo()->CalcPowerCost(this, SpellSchoolMask(pEff->GetSpellInfo()->SchoolMask)) * 4/10/3;
}
else
basepoints0 = procSpell->CalcPowerCost(this, SpellSchoolMask(procSpell->SchoolMask)) * 4/10;
ToPlayer()->SetSpellModTakingSpell(spell, true);
if (basepoints0 <= 0)
return false;
target = this;
triggered_spell_id = 34720;
break;
}
case 3406: // Hunting Party
{
triggered_spell_id = 57669;
target = this;
break;
}
case 3560: // Rapid Recuperation
{
// This effect only from Rapid Killing (mana regen)
if (!(procSpell->SpellFamilyFlags[1] & 0x01000000))
return false;
target = this;
switch (dummySpell->Id)
{
case 53228: // Rank 1
triggered_spell_id = 56654;
break;
case 53232: // Rank 2
triggered_spell_id = 58882;
break;
}
break;
}
case 3579: // Lock and Load
{
// Proc only from periodic (from trap activation proc another aura of this spell)
if (!(procFlag & PROC_FLAG_DONE_PERIODIC) || !roll_chance_i(triggerAmount))
return false;
triggered_spell_id = 56453;
target = this;
break;
}
}
switch (dummySpell->Id)
{
case 34477: // Misdirection
{
triggered_spell_id = 35079; // 4 sec buff on self
target = this;
return true;
}
case 57870: // Glyph of Mend Pet
{
victim->CastSpell(victim, 57894, true, NULL, NULL, GetGUID());
return true;
}
}
break;
}
case SPELLFAMILY_PALADIN:
{
// Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.022*$AP+0.044*$SPH)} damage)
if (dummySpell->SpellFamilyFlags[0] & 0x8000000)
{
if (effIndex != 0)
return false;
triggered_spell_id = 25742;
float ap = GetTotalAttackPowerValue(BASE_ATTACK);
int32 holy = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, victim);
basepoints0 = (int32)GetAttackTime(BASE_ATTACK) * int32(ap * 0.022f + 0.044f * holy) / 1000;
break;
}
// Light's Beacon - Beacon of Light
if (dummySpell->Id == 53651)
{
// Get target of beacon of light
if (Unit* beaconTarget = triggeredByAura->GetBase()->GetCaster())
{
// do not proc when target of beacon of light is healed
if (beaconTarget == this)
return false;
// check if it was heal by paladin which casted this beacon of light
if (beaconTarget->GetAura(53563, victim->GetGUID()))
{
if (beaconTarget->IsWithinLOSInMap(victim))
{
basepoints0 = damage;
victim->CastCustomSpell(beaconTarget, 53654, &basepoints0, NULL, NULL, true);
return true;
}
}
}
return false;
}
// Judgements of the Wise
if (dummySpell->SpellIconID == 3017)
{
target = this;
triggered_spell_id = 31930;
// replenishment
CastSpell(this, 57669, true, castItem, triggeredByAura);
break;
}
// Sanctified Wrath
if (dummySpell->SpellIconID == 3029)
{
triggered_spell_id = 57318;
target = this;
basepoints0 = triggerAmount;
CastCustomSpell(target, triggered_spell_id, &basepoints0, &basepoints0, NULL, true, castItem, triggeredByAura);
return true;
}
// Sacred Shield
if (dummySpell->SpellFamilyFlags[1] & 0x80000)
{
if (procFlag & PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_POS)
{
if (procSpell->SpellFamilyName == SPELLFAMILY_PALADIN && (procSpell->SpellFamilyFlags[0] & 0x40000000))
{
basepoints0 = damage / 12;
if (basepoints0)
CastCustomSpell(this, 66922, &basepoints0, NULL, NULL, true, 0, triggeredByAura, victim->GetGUID());
return true;
}
else
return false;
}
else if (damage > 0)
triggered_spell_id = 58597;
// Item - Paladin T8 Holy 4P Bonus
if (Unit* caster = triggeredByAura->GetCaster())
if (AuraEffect const* aurEff = caster->GetAuraEffect(64895, 0))
cooldown = aurEff->GetAmount();
target = this;
break;
}
// Righteous Vengeance
if (dummySpell->SpellIconID == 3025)
{
// 4 damage tick
basepoints0 = triggerAmount * damage / 400;
triggered_spell_id = 61840;
// Add remaining ticks to damage done
basepoints0 += victim->GetRemainingPeriodicAmount(GetGUID(), triggered_spell_id, SPELL_AURA_PERIODIC_DAMAGE);
break;
}
// Sheath of Light
if (dummySpell->SpellIconID == 3030)
{
// 4 healing tick
basepoints0 = triggerAmount * damage / 400;
triggered_spell_id = 54203;
break;
}
switch (dummySpell->Id)
{
// Heart of the Crusader
case 20335: // rank 1
triggered_spell_id = 21183;
break;
case 20336: // rank 2
triggered_spell_id = 54498;
break;
case 20337: // rank 3
triggered_spell_id = 54499;
break;
// Judgement of Light
case 20185:
{
if (!victim)
return false;
// 2% of base mana
basepoints0 = int32(victim->CountPctFromMaxHealth(2));
victim->CastCustomSpell(victim, 20267, &basepoints0, 0, 0, true, 0, triggeredByAura);
return true;
}
// Judgement of Wisdom
case 20186:
{
if (victim && victim->isAlive() && victim->getPowerType() == POWER_MANA)
{
// 2% of base mana
basepoints0 = int32(CalculatePctN(victim->GetCreateMana(), 2));
victim->CastCustomSpell(victim, 20268, &basepoints0, NULL, NULL, true, 0, triggeredByAura);
}
return true;
}
// Holy Power (Redemption Armor set)
case 28789:
{
if (!victim)
return false;
// Set class defined buff
switch (victim->getClass())
{
case CLASS_PALADIN:
case CLASS_PRIEST:
case CLASS_SHAMAN:
case CLASS_DRUID:
triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
break;
case CLASS_MAGE:
case CLASS_WARLOCK:
triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
break;
case CLASS_HUNTER:
case CLASS_ROGUE:
triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
break;
case CLASS_WARRIOR:
triggered_spell_id = 28790; // Increases the friendly target's armor
break;
default:
return false;
}
break;
}
case 25899: // Greater Blessing of Sanctuary
case 20911: // Blessing of Sanctuary
{
target = this;
switch (target->getPowerType())
{
case POWER_MANA:
triggered_spell_id = 57319;
break;
default:
return false;
}
break;
}
// Seal of Vengeance (damage calc on apply aura)
case 31801:
{
if (effIndex != 0) // effect 1, 2 used by seal unleashing code
return false;
// At melee attack or Hammer of the Righteous spell damage considered as melee attack
bool stacker = !procSpell || procSpell->Id == 53595;
// spells with SPELL_DAMAGE_CLASS_MELEE excluding Judgements
bool damager = procSpell && procSpell->EquippedItemClass != -1;
if (!stacker && !damager)
return false;
triggered_spell_id = 31803;
// On target with 5 stacks of Holy Vengeance direct damage is done
if (Aura* aur = victim->GetAura(triggered_spell_id, GetGUID()))
{
if (aur->GetStackAmount() == 5)
{
if (stacker)
aur->RefreshDuration();
CastSpell(victim, 42463, true);
return true;
}
}
if (!stacker)
return false;
break;
}
// Seal of Corruption
case 53736:
{
if (effIndex != 0) // effect 1, 2 used by seal unleashing code
return false;
// At melee attack or Hammer of the Righteous spell damage considered as melee attack
bool stacker = !procSpell || procSpell->Id == 53595;
// spells with SPELL_DAMAGE_CLASS_MELEE excluding Judgements
bool damager = procSpell && procSpell->EquippedItemClass != -1;
if (!stacker && !damager)
return false;
triggered_spell_id = 53742;
// On target with 5 stacks of Blood Corruption direct damage is done
if (Aura* aur = victim->GetAura(triggered_spell_id, GetGUID()))
{
if (aur->GetStackAmount() == 5)
{
if (stacker)
aur->RefreshDuration();
CastSpell(victim, 53739, true);
return true;
}
}
if (!stacker)
return false;
break;
}
// Spiritual Attunement
case 31785:
case 33776:
{
// if healed by another unit (victim)
if (this == victim)
return false;
// heal amount
basepoints0 = int32(CalculatePctN(std::min(damage, GetMaxHealth() - GetHealth()), triggerAmount));
target = this;
if (basepoints0)
triggered_spell_id = 31786;
break;
}
// Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
case 40470:
{
if (!procSpell)
return false;
float chance;
// Flash of light/Holy light
if (procSpell->SpellFamilyFlags[0] & 0xC0000000)
{
triggered_spell_id = 40471;
chance = 15.0f;
}
// Judgement (any)
else if (procSpell->GetSpellSpecific() == SPELL_SPECIFIC_JUDGEMENT)
{
triggered_spell_id = 40472;
chance = 50.0f;
}
else
return false;
if (!roll_chance_f(chance))
return false;
break;
}
// Glyph of Holy Light
case 54937:
{
triggered_spell_id = 54968;
basepoints0 = CalculatePctN(int32(damage), triggerAmount);
break;
}
// Item - Paladin T8 Holy 2P Bonus
case 64890:
{
triggered_spell_id = 64891;
basepoints0 = triggerAmount * damage / 300;
break;
}
case 71406: // Tiny Abomination in a Jar
case 71545: // Tiny Abomination in a Jar (Heroic)
{
if (!victim || !victim->isAlive())
return false;
CastSpell(this, 71432, true, NULL, triggeredByAura);
Aura const* dummy = GetAura(71432);
if (!dummy || dummy->GetStackAmount() < (dummySpell->Id == 71406 ? 8 : 7))
return false;
RemoveAurasDueToSpell(71432);
triggered_spell_id = 71433; // default main hand attack
// roll if offhand
if (Player const* player = ToPlayer())
if (player->GetWeaponForAttack(OFF_ATTACK, true) && urand(0, 1))
triggered_spell_id = 71434;
target = victim;
break;
}
// Item - Icecrown 25 Normal Dagger Proc
case 71880:
{
switch (getPowerType())
{
case POWER_MANA:
triggered_spell_id = 71881;
break;
case POWER_RAGE:
triggered_spell_id = 71883;
break;
case POWER_ENERGY:
triggered_spell_id = 71882;
break;
case POWER_RUNIC_POWER:
triggered_spell_id = 71884;
break;
default:
return false;
}
break;
}
// Item - Icecrown 25 Heroic Dagger Proc
case 71892:
{
switch (getPowerType())
{
case POWER_MANA:
triggered_spell_id = 71888;
break;
case POWER_RAGE:
triggered_spell_id = 71886;
break;
case POWER_ENERGY:
triggered_spell_id = 71887;
break;
case POWER_RUNIC_POWER:
triggered_spell_id = 71885;
break;
default:
return false;
}
break;
}
}
break;
}
case SPELLFAMILY_SHAMAN:
{
switch (dummySpell->Id)
{
// Earthen Power (Rank 1, 2)
case 51523:
case 51524:
{
// Totem itself must be a caster of this spell
Unit* caster = NULL;
for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) {
if ((*itr)->GetEntry() != 2630)
continue;
caster = *itr;
break;
}
if (!caster)
return false;
caster->CastSpell(caster, 59566, true, castItem, triggeredByAura, originalCaster);
return true;
}
// Tidal Force
case 55198:
{
// Remove aura stack from caster
RemoveAuraFromStack(55166);
// drop charges
return false;
}
// Totemic Power (The Earthshatterer set)
case 28823:
{
if (!victim)
return false;
// Set class defined buff
switch (victim->getClass())
{
case CLASS_PALADIN:
case CLASS_PRIEST:
case CLASS_SHAMAN:
case CLASS_DRUID:
triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
break;
case CLASS_MAGE:
case CLASS_WARLOCK:
triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
break;
case CLASS_HUNTER:
case CLASS_ROGUE:
triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
break;
case CLASS_WARRIOR:
triggered_spell_id = 28827; // Increases the friendly target's armor
break;
default:
return false;
}
break;
}
// Lesser Healing Wave (Totem of Flowing Water Relic)
case 28849:
{
target = this;
triggered_spell_id = 28850;
break;
}
// Windfury Weapon (Passive) 1-5 Ranks
case 33757:
{
Player* player = ToPlayer();
if (!player || !castItem || !castItem->IsEquipped() || !victim || !victim->isAlive())
return false;
// custom cooldown processing case
if (cooldown && player->HasSpellCooldown(dummySpell->Id))
return false;
if (triggeredByAura->GetBase() && castItem->GetGUID() != triggeredByAura->GetBase()->GetCastItemGUID())
return false;
WeaponAttackType attType = WeaponAttackType(player->GetAttackBySlot(castItem->GetSlot()));
if ((attType != BASE_ATTACK && attType != OFF_ATTACK) || !isAttackReady(attType))
return false;
// Now compute real proc chance...
uint32 chance = 20;
player->ApplySpellMod(dummySpell->Id, SPELLMOD_CHANCE_OF_SUCCESS, chance);
Item* addWeapon = player->GetWeaponForAttack(attType == BASE_ATTACK ? OFF_ATTACK : BASE_ATTACK, true);
uint32 enchant_id_add = addWeapon ? addWeapon->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)) : 0;
SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id_add);
if (pEnchant && pEnchant->spellid[0] == dummySpell->Id)
chance += 14;
if (!roll_chance_i(chance))
return false;
// Now amount of extra power stored in 1 effect of Enchant spell
// Get it by item enchant id
uint32 spellId;
switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)))
{
case 283: spellId = 8232; break; // 1 Rank
case 284: spellId = 8235; break; // 2 Rank
case 525: spellId = 10486; break; // 3 Rank
case 1669:spellId = 16362; break; // 4 Rank
case 2636:spellId = 25505; break; // 5 Rank
case 3785:spellId = 58801; break; // 6 Rank
case 3786:spellId = 58803; break; // 7 Rank
case 3787:spellId = 58804; break; // 8 Rank
default:
{
sLog->outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)",
castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)), dummySpell->Id);
return false;
}
}
SpellInfo const* windfurySpellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!windfurySpellInfo)
{
sLog->outError("Unit::HandleDummyAuraProc: non existed spell id: %u (Windfury)", spellId);
return false;
}
int32 extra_attack_power = CalculateSpellDamage(victim, windfurySpellInfo, 1);
// Value gained from additional AP
basepoints0 = int32(extra_attack_power / 14.0f * GetAttackTime(BASE_ATTACK) / 1000);
triggered_spell_id = 25504;
// apply cooldown before cast to prevent processing itself
if (cooldown)
player->AddSpellCooldown(dummySpell->Id, 0, time(NULL) + cooldown);
// Attack Twice
for (uint32 i = 0; i < 2; ++i)
CastCustomSpell(victim, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
return true;
}
// Shaman Tier 6 Trinket
case 40463:
{
if (!procSpell)
return false;
float chance;
if (procSpell->SpellFamilyFlags[0] & 0x1)
{
triggered_spell_id = 40465; // Lightning Bolt
chance = 15.0f;
}
else if (procSpell->SpellFamilyFlags[0] & 0x80)
{
triggered_spell_id = 40465; // Lesser Healing Wave
chance = 10.0f;
}
else if (procSpell->SpellFamilyFlags[1] & 0x00000010)
{
triggered_spell_id = 40466; // Stormstrike
chance = 50.0f;
}
else
return false;
if (!roll_chance_f(chance))
return false;
target = this;
break;
}
// Glyph of Healing Wave
case 55440:
{
// Not proc from self heals
if (this == victim)
return false;
basepoints0 = CalculatePctN(int32(damage), triggerAmount);
target = this;
triggered_spell_id = 55533;
break;
}
// Spirit Hunt
case 58877:
{
// Cast on owner
target = GetOwner();
if (!target)
return false;
basepoints0 = CalculatePctN(int32(damage), triggerAmount);
triggered_spell_id = 58879;
break;
}
// Shaman T8 Elemental 4P Bonus
case 64928:
{
basepoints0 = CalculatePctN(int32(damage), triggerAmount);
triggered_spell_id = 64930; // Electrified
break;
}
// Shaman T9 Elemental 4P Bonus
case 67228:
{
// Lava Burst
if (procSpell->SpellFamilyFlags[1] & 0x1000)
{
triggered_spell_id = 71824;
SpellInfo const* triggeredSpell = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!triggeredSpell)
return false;
basepoints0 = CalculatePctN(int32(damage), triggerAmount) / (triggeredSpell->GetMaxDuration() / triggeredSpell->Effects[0].Amplitude);
}
break;
}
// Item - Shaman T10 Restoration 4P Bonus
case 70808:
{
// Chain Heal
if ((procSpell->SpellFamilyFlags[0] & 0x100) && (procEx & PROC_EX_CRITICAL_HIT))
{
triggered_spell_id = 70809;
SpellInfo const* triggeredSpell = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!triggeredSpell)
return false;
basepoints0 = CalculatePctN(int32(damage), triggerAmount) / (triggeredSpell->GetMaxDuration() / triggeredSpell->Effects[0].Amplitude);
// Add remaining ticks to healing done
basepoints0 += GetRemainingPeriodicAmount(GetGUID(), triggered_spell_id, SPELL_AURA_PERIODIC_HEAL);
}
break;
}
// Item - Shaman T10 Elemental 2P Bonus
case 70811:
{
// Lightning Bolt & Chain Lightning
if (procSpell->SpellFamilyFlags[0] & 0x3)
{
if (ToPlayer()->HasSpellCooldown(16166))
{
uint32 newCooldownDelay = ToPlayer()->GetSpellCooldownDelay(16166);
if (newCooldownDelay < 3)
newCooldownDelay = 0;
else
newCooldownDelay -= 2;
ToPlayer()->AddSpellCooldown(16166, 0, uint32(time(NULL) + newCooldownDelay));
WorldPacket data(SMSG_MODIFY_COOLDOWN, 4+8+4);
data << uint32(16166); // Spell ID
data << uint64(GetGUID()); // Player GUID
data << int32(-2000); // Cooldown mod in milliseconds
ToPlayer()->GetSession()->SendPacket(&data);
return true;
}
}
return false;
}
// Item - Shaman T10 Elemental 4P Bonus
case 70817:
{
if (!target)
return false;
// try to find spell Flame Shock on the target
if (AuraEffect const* aurEff = target->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, 0x10000000, 0x0, 0x0, GetGUID()))
{
Aura* flameShock = aurEff->GetBase();
int32 maxDuration = flameShock->GetMaxDuration();
int32 newDuration = flameShock->GetDuration() + 2 * aurEff->GetAmplitude();
flameShock->SetDuration(newDuration);
// is it blizzlike to change max duration for FS?
if (newDuration > maxDuration)
flameShock->SetMaxDuration(newDuration);
return true;
}
// if not found Flame Shock
return false;
}
case 63280: // Glyph of Totem of Wrath
{
if (procSpell->SpellIconID != 2019)
return false;
AuraEffect* aurEffA = NULL;
AuraEffectList const& auras = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE);
for (AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i)
{
SpellInfo const* spell = (*i)->GetSpellInfo();
if (spell->SpellFamilyName == uint32(SPELLFAMILY_SHAMAN) && spell->SpellFamilyFlags.HasFlag(0, 0x02000000, 0))
{
if ((*i)->GetCasterGUID() != GetGUID())
continue;
if (spell->Id == 63283)
continue;
aurEffA = (*i);
break;
}
}
if (aurEffA)
{
int32 bp0 = 0, bp1 = 0;
bp0 = CalculatePctN(triggerAmount, aurEffA->GetAmount());
if (AuraEffect* aurEffB = aurEffA->GetBase()->GetEffect(EFFECT_1))
bp1 = CalculatePctN(triggerAmount, aurEffB->GetAmount());
CastCustomSpell(this, 63283, &bp0, &bp1, NULL, true, NULL, triggeredByAura);
return true;
}
return false;
}
break;
}
// Frozen Power
if (dummySpell->SpellIconID == 3780)
{
if (!target)
return false;
if (GetDistance(target) < 15.0f)
return false;
float chance = (float)triggerAmount;
if (!roll_chance_f(chance))
return false;
triggered_spell_id = 63685;
break;
}
// Storm, Earth and Fire
if (dummySpell->SpellIconID == 3063)
{
// Earthbind Totem summon only
if (procSpell->Id != 2484)
return false;
float chance = (float)triggerAmount;
if (!roll_chance_f(chance))
return false;
triggered_spell_id = 64695;
break;
}
// Ancestral Awakening
if (dummySpell->SpellIconID == 3065)
{
triggered_spell_id = 52759;
basepoints0 = CalculatePctN(int32(damage), triggerAmount);
target = this;
break;
}
// Earth Shield
if (dummySpell->SpellFamilyFlags[1] & 0x00000400)
{
// 3.0.8: Now correctly uses the Shaman's own spell critical strike chance to determine the chance of a critical heal.
originalCaster = triggeredByAura->GetCasterGUID();
target = this;
basepoints0 = triggerAmount;
// Glyph of Earth Shield
if (AuraEffect* aur = GetAuraEffect(63279, 0))
AddPctN(basepoints0, aur->GetAmount());
triggered_spell_id = 379;
break;
}
// Flametongue Weapon (Passive)
if (dummySpell->SpellFamilyFlags[0] & 0x200000)
{
if (GetTypeId() != TYPEID_PLAYER || !victim || !victim->isAlive() || !castItem || !castItem->IsEquipped())
return false;
float fire_onhit = float(CalculatePctF(dummySpell->Effects[EFFECT_0]. CalcValue(), 1.0f));
float add_spellpower = (float)(SpellBaseDamageBonus(SPELL_SCHOOL_MASK_FIRE)
+ SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_FIRE, victim));
// 1.3speed = 5%, 2.6speed = 10%, 4.0 speed = 15%, so, 1.0speed = 3.84%
ApplyPctF(add_spellpower, 3.84f);
// Enchant on Off-Hand and ready?
if (castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND && isAttackReady(OFF_ATTACK))
{
float BaseWeaponSpeed = GetAttackTime(OFF_ATTACK) / 1000.0f;
// Value1: add the tooltip damage by swingspeed + Value2: add spelldmg by swingspeed
basepoints0 = int32((fire_onhit * BaseWeaponSpeed) + (add_spellpower * BaseWeaponSpeed));
triggered_spell_id = 10444;
}
// Enchant on Main-Hand and ready?
else if (castItem->GetSlot() == EQUIPMENT_SLOT_MAINHAND && isAttackReady(BASE_ATTACK))
{
float BaseWeaponSpeed = GetAttackTime(BASE_ATTACK) / 1000.0f;
// Value1: add the tooltip damage by swingspeed + Value2: add spelldmg by swingspeed
basepoints0 = int32((fire_onhit * BaseWeaponSpeed) + (add_spellpower * BaseWeaponSpeed));
triggered_spell_id = 10444;
}
// If not ready, we should return, shouldn't we?!
else
return false;
CastCustomSpell(victim, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
return true;
}
// Improved Water Shield
if (dummySpell->SpellIconID == 2287)
{
// Default chance for Healing Wave and Riptide
float chance = (float)triggeredByAura->GetAmount();
if (procSpell->SpellFamilyFlags[0] & 0x80)
// Lesser Healing Wave - 0.6 of default
chance *= 0.6f;
else if (procSpell->SpellFamilyFlags[0] & 0x100)
// Chain heal - 0.3 of default
chance *= 0.3f;
if (!roll_chance_f(chance))
return false;
// Water Shield
if (AuraEffect const* aurEff = GetAuraEffect(SPELL_AURA_PROC_TRIGGER_SPELL, SPELLFAMILY_SHAMAN, 0, 0x00000020, 0))
{
uint32 spell = aurEff->GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell;
CastSpell(this, spell, true, castItem, triggeredByAura);
return true;
}
return false;
}
// Lightning Overload
if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura
{
if (!procSpell || GetTypeId() != TYPEID_PLAYER || !victim)
return false;
// custom cooldown processing case
if (cooldown && GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(dummySpell->Id))
return false;
uint32 spellId = 0;
// Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost
switch (procSpell->Id)
{
// Lightning Bolt
case 403: spellId = 45284; break; // Rank 1
case 529: spellId = 45286; break; // Rank 2
case 548: spellId = 45287; break; // Rank 3
case 915: spellId = 45288; break; // Rank 4
case 943: spellId = 45289; break; // Rank 5
case 6041: spellId = 45290; break; // Rank 6
case 10391: spellId = 45291; break; // Rank 7
case 10392: spellId = 45292; break; // Rank 8
case 15207: spellId = 45293; break; // Rank 9
case 15208: spellId = 45294; break; // Rank 10
case 25448: spellId = 45295; break; // Rank 11
case 25449: spellId = 45296; break; // Rank 12
case 49237: spellId = 49239; break; // Rank 13
case 49238: spellId = 49240; break; // Rank 14
// Chain Lightning
case 421: spellId = 45297; break; // Rank 1
case 930: spellId = 45298; break; // Rank 2
case 2860: spellId = 45299; break; // Rank 3
case 10605: spellId = 45300; break; // Rank 4
case 25439: spellId = 45301; break; // Rank 5
case 25442: spellId = 45302; break; // Rank 6
case 49270: spellId = 49268; break; // Rank 7
case 49271: spellId = 49269; break; // Rank 8
default:
sLog->outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id);
return false;
}
// Chain Lightning
if (procSpell->SpellFamilyFlags[0] & 0x2)
{
// Chain lightning has [LightOverload_Proc_Chance] / [Max_Number_of_Targets] chance to proc of each individual target hit.
// A maxed LO would have a 33% / 3 = 11% chance to proc of each target.
// LO chance was already "accounted" at the proc chance roll, now need to divide the chance by [Max_Number_of_Targets]
float chance = 100.0f / procSpell->Effects[effIndex].ChainTarget;
if (!roll_chance_f(chance))
return false;
// Remove cooldown (Chain Lightning - have Category Recovery time)
ToPlayer()->RemoveSpellCooldown(spellId);
}
CastSpell(victim, spellId, true, castItem, triggeredByAura);
if (cooldown && GetTypeId() == TYPEID_PLAYER)
ToPlayer()->AddSpellCooldown(dummySpell->Id, 0, time(NULL) + cooldown);
return true;
}
// Static Shock
if (dummySpell->SpellIconID == 3059)
{
// Lightning Shield
if (AuraEffect const* aurEff = GetAuraEffect(SPELL_AURA_PROC_TRIGGER_SPELL, SPELLFAMILY_SHAMAN, 0x400, 0, 0))
{
uint32 spell = sSpellMgr->GetSpellWithRank(26364, aurEff->GetSpellInfo()->GetRank());
// custom cooldown processing case
if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(spell))
ToPlayer()->RemoveSpellCooldown(spell);
CastSpell(target, spell, true, castItem, triggeredByAura);
aurEff->GetBase()->DropCharge();
return true;
}
return false;
}
break;
}
case SPELLFAMILY_DEATHKNIGHT:
{
// Blood-Caked Strike - Blood-Caked Blade
if (dummySpell->SpellIconID == 138)
{
if (!target || !target->isAlive())
return false;
triggered_spell_id = dummySpell->Effects[effIndex].TriggerSpell;
break;
}
// Improved Blood Presence
if (dummySpell->SpellIconID == 2636)
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
basepoints0 = CalculatePctN(int32(damage), triggerAmount);
break;
}
// Butchery
if (dummySpell->SpellIconID == 2664)
{
basepoints0 = triggerAmount;
triggered_spell_id = 50163;
target = this;
break;
}
// Dancing Rune Weapon
if (dummySpell->Id == 49028)
{
// 1 dummy aura for dismiss rune blade
if (effIndex != 1)
return false;
Unit* pPet = NULL;
for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) // Find Rune Weapon
if ((*itr)->GetEntry() == 27893)
{
pPet = *itr;
break;
}
if (pPet && pPet->getVictim() && damage && procSpell)
{
uint32 procDmg = damage / 2;
pPet->SendSpellNonMeleeDamageLog(pPet->getVictim(), procSpell->Id, procDmg, procSpell->GetSchoolMask(), 0, 0, false, 0, false);
pPet->DealDamage(pPet->getVictim(), procDmg, NULL, SPELL_DIRECT_DAMAGE, procSpell->GetSchoolMask(), procSpell, true);
break;
}
else
return false;
}
// Mark of Blood
if (dummySpell->Id == 49005)
{
// TODO: need more info (cooldowns/PPM)
triggered_spell_id = 61607;
break;
}
// Unholy Blight
if (dummySpell->Id == 49194)
{
basepoints0 = CalculatePctN(int32(damage), triggerAmount);
// Glyph of Unholy Blight
if (AuraEffect* glyph=GetAuraEffect(63332, 0))
AddPctN(basepoints0, glyph->GetAmount());
triggered_spell_id = 50536;
basepoints0 += victim->GetRemainingPeriodicAmount(GetGUID(), triggered_spell_id, SPELL_AURA_PERIODIC_DAMAGE);
break;
}
// Vendetta
if (dummySpell->SpellFamilyFlags[0] & 0x10000)
{
basepoints0 = int32(CountPctFromMaxHealth(triggerAmount));
triggered_spell_id = 50181;
target = this;
break;
}
// Necrosis
if (dummySpell->SpellIconID == 2709)
{
basepoints0 = CalculatePctN(int32(damage), triggerAmount);
triggered_spell_id = 51460;
break;
}
// Threat of Thassarian
if (dummySpell->SpellIconID == 2023)
{
// Must Dual Wield
if (!procSpell || !haveOffhandWeapon())
return false;
// Chance as basepoints for dummy aura
if (!roll_chance_i(triggerAmount))
return false;
switch (procSpell->Id)
{
// Obliterate
case 49020: triggered_spell_id = 66198; break; // Rank 1
case 51423: triggered_spell_id = 66972; break; // Rank 2
case 51424: triggered_spell_id = 66973; break; // Rank 3
case 51425: triggered_spell_id = 66974; break; // Rank 4
// Frost Strike
case 49143: triggered_spell_id = 66196; break; // Rank 1
case 51416: triggered_spell_id = 66958; break; // Rank 2
case 51417: triggered_spell_id = 66959; break; // Rank 3
case 51418: triggered_spell_id = 66960; break; // Rank 4
case 51419: triggered_spell_id = 66961; break; // Rank 5
case 55268: triggered_spell_id = 66962; break; // Rank 6
// Plague Strike
case 45462: triggered_spell_id = 66216; break; // Rank 1
case 49917: triggered_spell_id = 66988; break; // Rank 2
case 49918: triggered_spell_id = 66989; break; // Rank 3
case 49919: triggered_spell_id = 66990; break; // Rank 4
case 49920: triggered_spell_id = 66991; break; // Rank 5
case 49921: triggered_spell_id = 66992; break; // Rank 6
// Death Strike
case 49998: triggered_spell_id = 66188; break; // Rank 1
case 49999: triggered_spell_id = 66950; break; // Rank 2
case 45463: triggered_spell_id = 66951; break; // Rank 3
case 49923: triggered_spell_id = 66952; break; // Rank 4
case 49924: triggered_spell_id = 66953; break; // Rank 5
// Rune Strike
case 56815: triggered_spell_id = 66217; break; // Rank 1
// Blood Strike
case 45902: triggered_spell_id = 66215; break; // Rank 1
case 49926: triggered_spell_id = 66975; break; // Rank 2
case 49927: triggered_spell_id = 66976; break; // Rank 3
case 49928: triggered_spell_id = 66977; break; // Rank 4
case 49929: triggered_spell_id = 66978; break; // Rank 5
case 49930: triggered_spell_id = 66979; break; // Rank 6
default:
return false;
}
break;
}
// Runic Power Back on Snare/Root
if (dummySpell->Id == 61257)
{
// only for spells and hit/crit (trigger start always) and not start from self casted spells
if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == victim)
return false;
// Need snare or root mechanic
if (!(procSpell->GetAllEffectsMechanicMask() & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_SNARE))))
return false;
triggered_spell_id = 61258;
target = this;
break;
}
// Wandering Plague
if (dummySpell->SpellIconID == 1614)
{
if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, victim)))
return false;
basepoints0 = CalculatePctN(int32(damage), triggerAmount);
triggered_spell_id = 50526;
break;
}
// Sudden Doom
if (dummySpell->SpellIconID == 1939 && GetTypeId() == TYPEID_PLAYER)
{
SpellChainNode const* chain = NULL;
// get highest rank of the Death Coil spell
PlayerSpellMap const& sp_list = ToPlayer()->GetSpellMap();
for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
{
// check if shown in spell book
if (!itr->second->active || itr->second->disabled || itr->second->state == PLAYERSPELL_REMOVED)
continue;
SpellInfo const* spellProto = sSpellMgr->GetSpellInfo(itr->first);
if (!spellProto)
continue;
if (spellProto->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT
&& spellProto->SpellFamilyFlags[0] & 0x2000)
{
SpellChainNode const* newChain = sSpellMgr->GetSpellChainNode(itr->first);
// No chain entry or entry lower than found entry
if (!chain || !newChain || (chain->rank < newChain->rank))
{
triggered_spell_id = itr->first;
chain = newChain;
}
else
continue;
// Found spell is last in chain - do not need to look more
// Optimisation for most common case
if (chain && chain->last->Id == itr->first)
break;
}
}
}
// Item - Death Knight T10 Melee 4P Bonus
if (dummySpell->Id == 70656)
{
Player* player = ToPlayer();
if (!player)
return false;
for (uint32 i = 0; i < MAX_RUNES; ++i)
if (player->GetRuneCooldown(i) == 0)
return false;
}
break;
}
case SPELLFAMILY_POTION:
{
// alchemist's stone
if (dummySpell->Id == 17619)
{
if (procSpell->SpellFamilyName == SPELLFAMILY_POTION)
{
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; i++)
{
if (procSpell->Effects[i].Effect == SPELL_EFFECT_HEAL)
{
triggered_spell_id = 21399;
}
else if (procSpell->Effects[i].Effect == SPELL_EFFECT_ENERGIZE)
{
triggered_spell_id = 21400;
}
else
continue;
basepoints0 = int32(CalculateSpellDamage(this, procSpell, i) * 0.4f);
CastCustomSpell(this, triggered_spell_id, &basepoints0, NULL, NULL, true, NULL, triggeredByAura);
}
return true;
}
}
break;
}
case SPELLFAMILY_PET:
{
switch (dummySpell->SpellIconID)
{
// Guard Dog
case 201:
{
if (!victim)
return false;
triggered_spell_id = 54445;
target = this;
float addThreat = float(CalculatePctN(procSpell->Effects[0].CalcValue(this), triggerAmount));
victim->AddThreat(this, addThreat);
break;
}
// Silverback
case 1582:
triggered_spell_id = dummySpell->Id == 62765 ? 62801 : 62800;
target = this;
break;
}
break;
}
default:
break;
}
// if not handled by custom case, get triggered spell from dummySpell proto
if (!triggered_spell_id)
triggered_spell_id = dummySpell->Effects[triggeredByAura->GetEffIndex()].TriggerSpell;
// processed charge only counting case
if (!triggered_spell_id)
return true;
SpellInfo const* triggerEntry = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!triggerEntry)
{
sLog->outError("Unit::HandleDummyAuraProc: Spell %u have not existed triggered spell %u", dummySpell->Id, triggered_spell_id);
return false;
}
if (cooldown_spell_id == 0)
cooldown_spell_id = triggered_spell_id;
if (cooldown && GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(cooldown_spell_id))
return false;
if (basepoints0)
CastCustomSpell(target, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura, originalCaster);
else
CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura, originalCaster);
if (cooldown && GetTypeId() == TYPEID_PLAYER)
ToPlayer()->AddSpellCooldown(cooldown_spell_id, 0, time(NULL) + cooldown);
return true;
}
bool Unit::HandleObsModEnergyAuraProc(Unit* victim, uint32 /*damage*/, AuraEffect* triggeredByAura, SpellInfo const* /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
{
SpellInfo const* dummySpell = triggeredByAura->GetSpellInfo();
//uint32 effIndex = triggeredByAura->GetEffIndex();
//int32 triggerAmount = triggeredByAura->GetAmount();
Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
? ToPlayer()->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
uint32 triggered_spell_id = 0;
Unit* target = victim;
int32 basepoints0 = 0;
switch (dummySpell->SpellFamilyName)
{
case SPELLFAMILY_HUNTER:
{
// Aspect of the Viper
if (dummySpell->SpellFamilyFlags[1] & 0x40000)
{
uint32 maxmana = GetMaxPower(POWER_MANA);
basepoints0 = CalculatePctF(maxmana, GetAttackTime(RANGED_ATTACK) / 1000.0f);
target = this;
triggered_spell_id = 34075;
break;
}
break;
}
}
// processed charge only counting case
if (!triggered_spell_id)
return true;
SpellInfo const* triggerEntry = sSpellMgr->GetSpellInfo(triggered_spell_id);
// Try handle unknown trigger spells
if (!triggerEntry)
{
sLog->outError("Unit::HandleObsModEnergyAuraProc: Spell %u have not existed triggered spell %u", dummySpell->Id, triggered_spell_id);
return false;
}
if (cooldown && GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(triggered_spell_id))
return false;
if (basepoints0)
CastCustomSpell(target, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
else
CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura);
if (cooldown && GetTypeId() == TYPEID_PLAYER)
ToPlayer()->AddSpellCooldown(triggered_spell_id, 0, time(NULL) + cooldown);
return true;
}
bool Unit::HandleModDamagePctTakenAuraProc(Unit* victim, uint32 /*damage*/, AuraEffect* triggeredByAura, SpellInfo const* /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
{
SpellInfo const* dummySpell = triggeredByAura->GetSpellInfo();
//uint32 effIndex = triggeredByAura->GetEffIndex();
//int32 triggerAmount = triggeredByAura->GetAmount();
Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
? ToPlayer()->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
uint32 triggered_spell_id = 0;
Unit* target = victim;
int32 basepoints0 = 0;
switch (dummySpell->SpellFamilyName)
{
case SPELLFAMILY_PALADIN:
{
// Blessing of Sanctuary
if (dummySpell->SpellFamilyFlags[0] & 0x10000000)
{
switch (getPowerType())
{
case POWER_MANA: triggered_spell_id = 57319; break;
default:
return false;
}
}
break;
}
}
// processed charge only counting case
if (!triggered_spell_id)
return true;
SpellInfo const* triggerEntry = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!triggerEntry)
{
sLog->outError("Unit::HandleModDamagePctTakenAuraProc: Spell %u have not existed triggered spell %u", dummySpell->Id, triggered_spell_id);
return false;
}
if (cooldown && GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(triggered_spell_id))
return false;
if (basepoints0)
CastCustomSpell(target, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
else
CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura);
if (cooldown && GetTypeId() == TYPEID_PLAYER)
ToPlayer()->AddSpellCooldown(triggered_spell_id, 0, time(NULL) + cooldown);
return true;
}
// Used in case when access to whole aura is needed
// All procs should be handled like this...
bool Unit::HandleAuraProc(Unit* victim, uint32 damage, Aura* triggeredByAura, SpellInfo const* procSpell, uint32 /*procFlag*/, uint32 procEx, uint32 cooldown, bool * handled)
{
SpellInfo const* dummySpell = triggeredByAura->GetSpellInfo();
switch (dummySpell->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
switch (dummySpell->Id)
{
// Nevermelting Ice Crystal
case 71564:
RemoveAuraFromStack(71564);
*handled = true;
break;
// Gaseous Bloat
case 70672:
case 72455:
case 72832:
case 72833:
{
*handled = true;
uint32 stack = triggeredByAura->GetStackAmount();
int32 const mod = (GetMap()->GetSpawnMode() & 1) ? 1500 : 1250;
int32 dmg = 0;
for (uint8 i = 1; i < stack; ++i)
dmg += mod * stack;
if (Unit* caster = triggeredByAura->GetCaster())
{
caster->CastCustomSpell(70701, SPELLVALUE_BASE_POINT0, dmg);
if (Creature* creature = caster->ToCreature())
creature->DespawnOrUnsummon(1);
}
break;
}
// Ball of Flames Proc
case 71756:
case 72782:
case 72783:
case 72784:
RemoveAuraFromStack(dummySpell->Id);
*handled = true;
break;
// Discerning Eye of the Beast
case 59915:
{
CastSpell(this, 59914, true); // 59914 already has correct basepoints in DBC, no need for custom bp
*handled = true;
break;
}
// Swift Hand of Justice
case 59906:
{
int32 bp0 = CalculatePctN(GetMaxHealth(), dummySpell->Effects[EFFECT_0]. CalcValue());
CastCustomSpell(this, 59913, &bp0, NULL, NULL, true);
*handled = true;
break;
}
}
break;
case SPELLFAMILY_PALADIN:
{
// Infusion of Light
if (dummySpell->SpellIconID == 3021)
{
// Flash of Light HoT on Flash of Light when Sacred Shield active
if (procSpell->SpellFamilyFlags[0] & 0x40000000 && procSpell->SpellIconID == 242)
{
*handled = true;
if (victim && victim->HasAura(53601))
{
int32 bp0 = CalculatePctN(int32(damage / 12), dummySpell->Effects[EFFECT_2]. CalcValue());
// Item - Paladin T9 Holy 4P Bonus
if (AuraEffect const* aurEff = GetAuraEffect(67191, 0))
AddPctN(bp0, aurEff->GetAmount());
CastCustomSpell(victim, 66922, &bp0, NULL, NULL, true);
return true;
}
}
// but should not proc on non-critical Holy Shocks
else if ((procSpell->SpellFamilyFlags[0] & 0x200000 || procSpell->SpellFamilyFlags[1] & 0x10000) && !(procEx & PROC_EX_CRITICAL_HIT))
*handled = true;
break;
}
// Judgements of the Just
else if (dummySpell->SpellIconID == 3015)
{
*handled = true;
CastSpell(victim, 68055, true);
return true;
}
// Glyph of Divinity
else if (dummySpell->Id == 54939)
{
*handled = true;
// Check if we are the target and prevent mana gain
if (triggeredByAura->GetCasterGUID() == victim->GetGUID())
return false;
// Lookup base amount mana restore
for (uint8 i = 0; i<MAX_SPELL_EFFECTS; i++)
{
if (procSpell->Effects[i].Effect == SPELL_EFFECT_ENERGIZE)
{
// value multiplied by 2 because you should get twice amount
int32 mana = procSpell->Effects[i].CalcValue() * 2;
CastCustomSpell(this, 54986, 0, &mana, NULL, true);
}
}
return true;
}
break;
}
case SPELLFAMILY_MAGE:
{
// Combustion
switch (dummySpell->Id)
{
case 11129:
{
*handled = true;
Unit* caster = triggeredByAura->GetCaster();
if (!caster || !damage)
return false;
// last charge and crit
if (triggeredByAura->GetCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT))
return true; // charge counting (will removed)
CastSpell(this, 28682, true);
return (procEx & PROC_EX_CRITICAL_HIT) ? true : false;
}
// Empowered Fire
case 31656:
case 31657:
case 31658:
{
*handled = true;
SpellInfo const* spInfo = sSpellMgr->GetSpellInfo(67545);
if (!spInfo)
return false;
int32 bp0 = int32(CalculatePctN(GetCreateMana(), spInfo->Effects[0].CalcValue()));
CastCustomSpell(this, 67545, &bp0, NULL, NULL, true, NULL, triggeredByAura->GetEffect(EFFECT_0), GetGUID());
return true;
}
}
break;
}
case SPELLFAMILY_DEATHKNIGHT:
{
// Blood of the North
// Reaping
// Death Rune Mastery
if (dummySpell->SpellIconID == 3041 || dummySpell->SpellIconID == 22 || dummySpell->SpellIconID == 2622)
{
*handled = true;
// Convert recently used Blood Rune to Death Rune
if (Player* player = ToPlayer())
{
if (player->getClass() != CLASS_DEATH_KNIGHT)
return false;
RuneType rune = ToPlayer()->GetLastUsedRune();
// can't proc from death rune use
if (rune == RUNE_DEATH)
return false;
AuraEffect* aurEff = triggeredByAura->GetEffect(EFFECT_0);
if (!aurEff)
return false;
// Reset amplitude - set death rune remove timer to 30s
aurEff->ResetPeriodic(true);
uint32 runesLeft;
if (dummySpell->SpellIconID == 2622)
runesLeft = 2;
else
runesLeft = 1;
for (uint8 i = 0; i < MAX_RUNES && runesLeft; ++i)
{
if (dummySpell->SpellIconID == 2622)
{
if (player->GetCurrentRune(i) == RUNE_DEATH ||
player->GetBaseRune(i) == RUNE_BLOOD)
continue;
}
else
{
if (player->GetCurrentRune(i) == RUNE_DEATH ||
player->GetBaseRune(i) != RUNE_BLOOD)
continue;
}
if (player->GetRuneCooldown(i) != player->GetRuneBaseCooldown(i))
continue;
--runesLeft;
// Mark aura as used
player->AddRuneByAuraEffect(i, RUNE_DEATH, aurEff);
}
return true;
}
return false;
}
switch (dummySpell->Id)
{
// Bone Shield cooldown
case 49222:
{
*handled = true;
if (cooldown && GetTypeId() == TYPEID_PLAYER)
{
if (ToPlayer()->HasSpellCooldown(100000))
return false;
ToPlayer()->AddSpellCooldown(100000, 0, time(NULL) + cooldown);
}
return true;
}
// Hungering Cold aura drop
case 51209:
*handled = true;
// Drop only in not disease case
if (procSpell && procSpell->Dispel == DISPEL_DISEASE)
return false;
return true;
}
break;
}
case SPELLFAMILY_WARRIOR:
{
switch (dummySpell->Id)
{
// Item - Warrior T10 Protection 4P Bonus
case 70844:
{
int32 basepoints0 = CalculatePctN(GetMaxHealth(), dummySpell->Effects[EFFECT_1]. CalcValue());
CastCustomSpell(this, 70845, &basepoints0, NULL, NULL, true);
break;
}
default:
break;
}
break;
}
}
return false;
}
bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
{
// Get triggered aura spell info
SpellInfo const* auraSpellInfo = triggeredByAura->GetSpellInfo();
// Basepoints of trigger aura
int32 triggerAmount = triggeredByAura->GetAmount();
// Set trigger spell id, target, custom basepoints
uint32 trigger_spell_id = auraSpellInfo->Effects[triggeredByAura->GetEffIndex()].TriggerSpell;
Unit* target = NULL;
int32 basepoints0 = 0;
if (triggeredByAura->GetAuraType() == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
basepoints0 = triggerAmount;
Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
? ToPlayer()->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
// Try handle unknown trigger spells
if (sSpellMgr->GetSpellInfo(trigger_spell_id) == NULL)
{
switch (auraSpellInfo->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
switch (auraSpellInfo->Id)
{
case 23780: // Aegis of Preservation (Aegis of Preservation trinket)
trigger_spell_id = 23781;
break;
case 33896: // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
trigger_spell_id = 33898;
break;
case 43820: // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
// Pct value stored in dummy
basepoints0 = victim->GetCreateHealth() * auraSpellInfo->Effects[1].CalcValue() / 100;
target = victim;
break;
case 57345: // Darkmoon Card: Greatness
{
float stat = 0.0f;
// strength
if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
// agility
if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
// intellect
if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
// spirit
if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235; }
break;
}
case 64568: // Blood Reserve
{
if (HealthBelowPctDamaged(35, damage))
{
CastCustomSpell(this, 64569, &triggerAmount, NULL, NULL, true);
RemoveAura(64568);
}
return false;
}
case 67702: // Death's Choice, Item - Coliseum 25 Normal Melee Trinket
{
float stat = 0.0f;
// strength
if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67708;stat = GetStat(STAT_STRENGTH); }
// agility
if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67703; }
break;
}
case 67771: // Death's Choice (heroic), Item - Coliseum 25 Heroic Melee Trinket
{
float stat = 0.0f;
// strength
if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67773;stat = GetStat(STAT_STRENGTH); }
// agility
if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67772; }
break;
}
// Mana Drain Trigger
case 27522:
case 40336:
{
// On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
if (this && isAlive())
CastSpell(this, 29471, true, castItem, triggeredByAura);
if (victim && victim->isAlive())
CastSpell(victim, 27526, true, castItem, triggeredByAura);
return true;
}
}
break;
case SPELLFAMILY_MAGE:
if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
{
switch (auraSpellInfo->Id)
{
case 31641: // Rank 1
case 31642: // Rank 2
trigger_spell_id = 31643;
break;
default:
sLog->outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed", auraSpellInfo->Id);
return false;
}
}
break;
case SPELLFAMILY_WARRIOR:
if (auraSpellInfo->Id == 50421) // Scent of Blood
{
CastSpell(this, 50422, true);
RemoveAuraFromStack(auraSpellInfo->Id);
return false;
}
break;
case SPELLFAMILY_WARLOCK:
{
// Drain Soul
if (auraSpellInfo->SpellFamilyFlags[0] & 0x4000)
{
// Improved Drain Soul
Unit::AuraEffectList const& mAddFlatModifier = GetAuraEffectsByType(SPELL_AURA_DUMMY);
for (Unit::AuraEffectList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i)
{
if ((*i)->GetMiscValue() == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellInfo()->SpellIconID == 113)
{
int32 value2 = CalculateSpellDamage(this, (*i)->GetSpellInfo(), 2);
basepoints0 = int32(CalculatePctN(GetMaxPower(POWER_MANA), value2));
// Drain Soul
CastCustomSpell(this, 18371, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
break;
}
}
// Not remove charge (aura removed on death in any cases)
// Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura
return false;
}
// Nether Protection
else if (auraSpellInfo->SpellIconID == 1985)
{
if (!procSpell)
return false;
switch (GetFirstSchoolInMask(procSpell->GetSchoolMask()))
{
case SPELL_SCHOOL_NORMAL:
return false; // ignore
case SPELL_SCHOOL_HOLY: trigger_spell_id = 54370; break;
case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break;
case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break;
case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break;
case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break;
case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
default:
return false;
}
}
break;
}
case SPELLFAMILY_PRIEST:
{
// Greater Heal Refund
if (auraSpellInfo->Id == 37594)
trigger_spell_id = 37595;
// Blessed Recovery
else if (auraSpellInfo->SpellIconID == 1875)
{
switch (auraSpellInfo->Id)
{
case 27811: trigger_spell_id = 27813; break;
case 27815: trigger_spell_id = 27817; break;
case 27816: trigger_spell_id = 27818; break;
default:
sLog->outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id);
return false;
}
basepoints0 = CalculatePctN(int32(damage), triggerAmount) / 3;
target = this;
// Add remaining ticks to healing done
basepoints0 += GetRemainingPeriodicAmount(GetGUID(), trigger_spell_id, SPELL_AURA_PERIODIC_HEAL);
}
break;
}
case SPELLFAMILY_DRUID:
{
switch (auraSpellInfo->Id)
{
// Druid Forms Trinket
case 37336:
{
switch (GetShapeshiftForm())
{
case FORM_NONE: trigger_spell_id = 37344; break;
case FORM_CAT: trigger_spell_id = 37341; break;
case FORM_BEAR:
case FORM_DIREBEAR: trigger_spell_id = 37340; break;
case FORM_TREE: trigger_spell_id = 37342; break;
case FORM_MOONKIN: trigger_spell_id = 37343; break;
default:
return false;
}
break;
}
// Druid T9 Feral Relic (Lacerate, Swipe, Mangle, and Shred)
case 67353:
{
switch (GetShapeshiftForm())
{
case FORM_CAT: trigger_spell_id = 67355; break;
case FORM_BEAR:
case FORM_DIREBEAR: trigger_spell_id = 67354; break;
default:
return false;
}
break;
}
default:
break;
}
break;
}
case SPELLFAMILY_HUNTER:
{
if (auraSpellInfo->SpellIconID == 3247) // Piercing Shots
{
switch (auraSpellInfo->Id)
{
case 53234: // Rank 1
case 53237: // Rank 2
case 53238: // Rank 3
trigger_spell_id = 63468;
break;
default:
sLog->outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Piercing Shots", auraSpellInfo->Id);
return false;
}
SpellInfo const* TriggerPS = sSpellMgr->GetSpellInfo(trigger_spell_id);
if (!TriggerPS)
return false;
basepoints0 = CalculatePctN(int32(damage), triggerAmount) / (TriggerPS->GetMaxDuration() / TriggerPS->Effects[0].Amplitude);
basepoints0 += victim->GetRemainingPeriodicAmount(GetGUID(), trigger_spell_id, SPELL_AURA_PERIODIC_DAMAGE);
break;
}
// Item - Hunter T9 4P Bonus
if (auraSpellInfo->Id == 67151)
{
trigger_spell_id = 68130;
target = this;
break;
}
break;
}
case SPELLFAMILY_PALADIN:
{
switch (auraSpellInfo->Id)
{
// Healing Discount
case 37705:
{
trigger_spell_id = 37706;
target = this;
break;
}
// Soul Preserver
case 60510:
{
switch (getClass())
{
case CLASS_DRUID:
trigger_spell_id = 60512;
break;
case CLASS_PALADIN:
trigger_spell_id = 60513;
break;
case CLASS_PRIEST:
trigger_spell_id = 60514;
break;
case CLASS_SHAMAN:
trigger_spell_id = 60515;
break;
}
target = this;
break;
}
case 37657: // Lightning Capacitor
case 54841: // Thunder Capacitor
case 67712: // Item - Coliseum 25 Normal Caster Trinket
case 67758: // Item - Coliseum 25 Heroic Caster Trinket
{
if (!victim || !victim->isAlive() || GetTypeId() != TYPEID_PLAYER)
return false;
uint32 stack_spell_id = 0;
switch (auraSpellInfo->Id)
{
case 37657:
stack_spell_id = 37658;
trigger_spell_id = 37661;
break;
case 54841:
stack_spell_id = 54842;
trigger_spell_id = 54843;
break;
case 67712:
stack_spell_id = 67713;
trigger_spell_id = 67714;
break;
case 67758:
stack_spell_id = 67759;
trigger_spell_id = 67760;
break;
}
CastSpell(this, stack_spell_id, true, NULL, triggeredByAura);
Aura* dummy = GetAura(stack_spell_id);
if (!dummy || dummy->GetStackAmount() < triggerAmount)
return false;
RemoveAurasDueToSpell(stack_spell_id);
target = victim;
break;
}
//Item - Icecrown 25 Normal Healer Weapon Proc
case 71865:
{
trigger_spell_id = 71864;
target = this;
break;
}
//Item - Icecrown 25 Heroic Healer Weapon Proc
case 71868:
{
trigger_spell_id = 71866;
target = this;
break;
}
default:
// Illumination
if (auraSpellInfo->SpellIconID == 241)
{
if (!procSpell)
return false;
// procspell is triggered spell but we need mana cost of original casted spell
uint32 originalSpellId = procSpell->Id;
// Holy Shock heal
if (procSpell->SpellFamilyFlags[1] & 0x00010000)
{
switch (procSpell->Id)
{
case 25914: originalSpellId = 20473; break;
case 25913: originalSpellId = 20929; break;
case 25903: originalSpellId = 20930; break;
case 27175: originalSpellId = 27174; break;
case 33074: originalSpellId = 33072; break;
case 48820: originalSpellId = 48824; break;
case 48821: originalSpellId = 48825; break;
default:
sLog->outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock", procSpell->Id);
return false;
}
}
SpellInfo const* originalSpell = sSpellMgr->GetSpellInfo(originalSpellId);
if (!originalSpell)
{
sLog->outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu", originalSpellId);
return false;
}
// percent stored in effect 1 (class scripts) base points
int32 cost = int32(originalSpell->ManaCost + CalculatePctU(GetCreateMana(), originalSpell->ManaCostPercentage));
basepoints0 = CalculatePctN(cost, auraSpellInfo->Effects[1].CalcValue());
trigger_spell_id = 20272;
target = this;
}
break;
}
break;
}
case SPELLFAMILY_SHAMAN:
{
switch (auraSpellInfo->Id)
{
// Lightning Shield (The Ten Storms set)
case 23551:
{
trigger_spell_id = 23552;
target = victim;
break;
}
// Damage from Lightning Shield (The Ten Storms set)
case 23552:
{
trigger_spell_id = 27635;
break;
}
// Mana Surge (The Earthfury set)
case 23572:
{
if (!procSpell)
return false;
basepoints0 = int32(CalculatePctN(procSpell->ManaCost, 35));
trigger_spell_id = 23571;
target = this;
break;
}
case 30881: // Nature's Guardian Rank 1
case 30883: // Nature's Guardian Rank 2
case 30884: // Nature's Guardian Rank 3
case 30885: // Nature's Guardian Rank 4
case 30886: // Nature's Guardian Rank 5
{
if (HealthBelowPct(30))
{
basepoints0 = int32(auraSpellInfo->Effects[EFFECT_0].CalcValue() * GetMaxHealth() / 100.0f);
target = this;
trigger_spell_id = 31616;
// TODO: Threat part
}
else
return false;
break;
}
default:
{
// Lightning Shield (overwrite non existing triggered spell call in spell.dbc
if (auraSpellInfo->SpellFamilyFlags[0] & 0x400)
{
trigger_spell_id = sSpellMgr->GetSpellWithRank(26364, auraSpellInfo->GetRank());
}
// Nature's Guardian
else if (auraSpellInfo->SpellIconID == 2013)
{
// Check health condition - should drop to less 30% (damage deal after this!)
if (!HealthBelowPctDamaged(30, damage))
return false;
if (victim && victim->isAlive())
victim->getThreatManager().modifyThreatPercent(this, -10);
basepoints0 = int32(CountPctFromMaxHealth(triggerAmount));
trigger_spell_id = 31616;
target = this;
}
}
}
break;
}
case SPELLFAMILY_DEATHKNIGHT:
{
// Acclimation
if (auraSpellInfo->SpellIconID == 1930)
{
if (!procSpell)
return false;
switch (GetFirstSchoolInMask(procSpell->GetSchoolMask()))
{
case SPELL_SCHOOL_NORMAL:
return false; // ignore
case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break;
case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break;
case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break;
case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break;
case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break;
case SPELL_SCHOOL_ARCANE: trigger_spell_id = 50486; break;
default:
return false;
}
}
// Blood Presence (Improved)
else if (auraSpellInfo->Id == 63611)
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
trigger_spell_id = 50475;
basepoints0 = CalculatePctN(int32(damage), triggerAmount);
}
break;
}
default:
break;
}
}
// All ok. Check current trigger spell
SpellInfo const* triggerEntry = sSpellMgr->GetSpellInfo(trigger_spell_id);
if (triggerEntry == NULL)
{
// Not cast unknown spell
// sLog->outError("Unit::HandleProcTriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?", auraSpellInfo->Id, triggeredByAura->GetEffIndex());
return false;
}
// not allow proc extra attack spell at extra attack
if (m_extraAttacks && triggerEntry->HasEffect(SPELL_EFFECT_ADD_EXTRA_ATTACKS))
return false;
// Custom requirements (not listed in procEx) Warning! damage dealing after this
// Custom triggered spells
switch (auraSpellInfo->Id)
{
// Deep Wounds
case 12834:
case 12849:
case 12867:
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
// now compute approximate weapon damage by formula from wowwiki.com
Item* item = NULL;
if (procFlags & PROC_FLAG_DONE_OFFHAND_ATTACK)
item = ToPlayer()->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
else
item = ToPlayer()->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
// dunno if it's really needed but will prevent any possible crashes
if (!item)
return false;
ItemTemplate const* weapon = item->GetTemplate();
float weaponDPS = weapon->getDPS();
float attackPower = GetTotalAttackPowerValue(BASE_ATTACK) / 14.0f;
float weaponSpeed = float(weapon->Delay) / 1000.0f;
basepoints0 = int32((weaponDPS + attackPower) * weaponSpeed);
break;
}
// Persistent Shield (Scarab Brooch trinket)
// This spell originally trigger 13567 - Dummy Trigger (vs dummy efect)
case 26467:
{
basepoints0 = int32(CalculatePctN(damage, 15));
target = victim;
trigger_spell_id = 26470;
break;
}
// Unyielding Knights (item exploit 29108\29109)
case 38164:
{
if (!victim || victim->GetEntry() != 19457) // Proc only if your target is Grillok
return false;
break;
}
// Deflection
case 52420:
{
if (!HealthBelowPct(35))
return false;
break;
}
// Cheat Death
case 28845:
{
// When your health drops below 20%
if (HealthBelowPctDamaged(20, damage) || HealthBelowPct(20))
return false;
break;
}
// Deadly Swiftness (Rank 1)
case 31255:
{
// whenever you deal damage to a target who is below 20% health.
if (!victim || !victim->isAlive() || victim->HealthAbovePct(20))
return false;
target = this;
trigger_spell_id = 22588;
}
// Greater Heal Refund (Avatar Raiment set)
case 37594:
{
if (!victim || !victim->isAlive())
return false;
// Not give if target already have full health
if (victim->IsFullHealth())
return false;
// If your Greater Heal brings the target to full health, you gain $37595s1 mana.
if (victim->GetHealth() + damage < victim->GetMaxHealth())
return false;
break;
}
// Bonus Healing (Crystal Spire of Karabor mace)
case 40971:
{
// If your target is below $s1% health
if (!victim || !victim->isAlive() || victim->HealthAbovePct(triggerAmount))
return false;
break;
}
// Rapid Recuperation
case 53228:
case 53232:
{
// This effect only from Rapid Fire (ability cast)
if (!(procSpell->SpellFamilyFlags[0] & 0x20))
return false;
break;
}
// Decimation
case 63156:
case 63158:
// Can proc only if target has hp below 35%
if (!victim || !victim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, procSpell, this))
return false;
break;
// Deathbringer Saurfang - Blood Beast's Blood Link
case 72176:
basepoints0 = 3;
break;
case 15337: // Improved Spirit Tap (Rank 1)
case 15338: // Improved Spirit Tap (Rank 2)
{
if (procSpell->SpellFamilyFlags[0] & 0x800000)
if ((procSpell->Id != 58381) || !roll_chance_i(50))
return false;
target = victim;
break;
}
// Professor Putricide - Ooze Spell Tank Protection
case 71770:
if (victim)
victim->CastSpell(victim, trigger_spell_id, true); // EffectImplicitTarget is self
return true;
case 45057: // Evasive Maneuvers (Commendation of Kael`thas trinket)
case 71634: // Item - Icecrown 25 Normal Tank Trinket 1
case 71640: // Item - Icecrown 25 Heroic Tank Trinket 1
case 75475: // Item - Chamber of Aspects 25 Normal Tank Trinket
case 75481: // Item - Chamber of Aspects 25 Heroic Tank Trinket
{
// Procs only if damage takes health below $s1%
if (!HealthBelowPctDamaged(triggerAmount, damage))
return false;
break;
}
default:
break;
}
// Blade Barrier
if (auraSpellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && auraSpellInfo->SpellIconID == 85)
{
Player* player = ToPlayer();
if (!player || player->getClass() != CLASS_DEATH_KNIGHT)
return false;
if (!player->IsBaseRuneSlotsOnCooldown(RUNE_BLOOD))
return false;
}
// Rime
else if (auraSpellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && auraSpellInfo->SpellIconID == 56)
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
// Howling Blast
ToPlayer()->RemoveSpellCategoryCooldown(1248, true);
}
// Custom basepoints/target for exist spell
// dummy basepoints or other customs
switch (trigger_spell_id)
{
// Auras which should proc on area aura source (caster in this case):
// Turn the Tables
case 52914:
case 52915:
case 52910:
// Honor Among Thieves
case 52916:
{
target = triggeredByAura->GetBase()->GetCaster();
if (!target)
return false;
if (cooldown && target->GetTypeId() == TYPEID_PLAYER && target->ToPlayer()->HasSpellCooldown(trigger_spell_id))
return false;
target->CastSpell(target, trigger_spell_id, true, castItem, triggeredByAura);
if (cooldown && GetTypeId() == TYPEID_PLAYER)
ToPlayer()->AddSpellCooldown(trigger_spell_id, 0, time(NULL) + cooldown);
return true;
}
// Cast positive spell on enemy target
case 7099: // Curse of Mending
case 39703: // Curse of Mending
case 29494: // Temptation
case 20233: // Improved Lay on Hands (cast on target)
{
target = victim;
break;
}
// Combo points add triggers (need add combopoint only for main target, and after possible combopoints reset)
case 15250: // Rogue Setup
{
// applied only for main target
if (!victim || (GetTypeId() == TYPEID_PLAYER && victim != ToPlayer()->GetSelectedUnit()))
return false;
break; // continue normal case
}
// Finish movies that add combo
case 14189: // Seal Fate (Netherblade set)
case 14157: // Ruthlessness
case 70802: // Rogue T10 4P Bonus
{
if (!victim || victim == this)
return false;
// Need add combopoint AFTER finish movie (or they dropped in finish phase)
break;
}
// Item - Druid T10 Balance 2P Bonus
case 16870:
{
if (HasAura(70718))
CastSpell(this, 70721, true);
break;
}
// Bloodthirst (($m/100)% of max health)
case 23880:
{
basepoints0 = int32(CountPctFromMaxHealth(triggerAmount));
break;
}
// Shamanistic Rage triggered spell
case 30824:
{
basepoints0 = int32(CalculatePctN(GetTotalAttackPowerValue(BASE_ATTACK), triggerAmount));
break;
}
// Enlightenment (trigger only from mana cost spells)
case 35095:
{
if (!procSpell || procSpell->PowerType != POWER_MANA || (procSpell->ManaCost == 0 && procSpell->ManaCostPercentage == 0 && procSpell->ManaCostPerlevel == 0))
return false;
break;
}
// Demonic Pact
case 48090:
{
// Get talent aura from owner
if (isPet())
if (Unit* owner = GetOwner())
{
if (AuraEffect* aurEff = owner->GetDummyAuraEffect(SPELLFAMILY_WARLOCK, 3220, 0))
{
basepoints0 = int32((aurEff->GetAmount() * owner->SpellBaseDamageBonus(SpellSchoolMask(SPELL_SCHOOL_MASK_MAGIC)) + 100.0f) / 100.0f); // TODO: Is it right?
CastCustomSpell(this, trigger_spell_id, &basepoints0, &basepoints0, NULL, true, castItem, triggeredByAura);
return true;
}
}
break;
}
// Sword and Board
case 50227:
{
// Remove cooldown on Shield Slam
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->RemoveSpellCategoryCooldown(1209, true);
break;
}
// Maelstrom Weapon
case 53817:
{
// Item - Shaman T10 Enhancement 4P Bonus
if (AuraEffect const* aurEff = GetAuraEffect(70832, 0))
if (Aura const* maelstrom = GetAura(53817))
if ((maelstrom->GetStackAmount() == maelstrom->GetSpellInfo()->StackAmount) && roll_chance_i(aurEff->GetAmount()))
CastSpell(this, 70831, true, castItem, triggeredByAura);
// have rank dependent proc chance, ignore too often cases
// PPM = 2.5 * (rank of talent),
uint32 rank = auraSpellInfo->GetRank();
// 5 rank -> 100% 4 rank -> 80% and etc from full rate
if (!roll_chance_i(20*rank))
return false;
break;
}
// Astral Shift
case 52179:
{
if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == victim)
return false;
// Need stun, fear or silence mechanic
if (!(procSpell->GetAllEffectsMechanicMask() & ((1<<MECHANIC_SILENCE)|(1<<MECHANIC_STUN)|(1<<MECHANIC_FEAR))))
return false;
break;
}
// Burning Determination
case 54748:
{
if (!procSpell)
return false;
// Need Interrupt or Silenced mechanic
if (!(procSpell->GetAllEffectsMechanicMask() & ((1<<MECHANIC_INTERRUPT)|(1<<MECHANIC_SILENCE))))
return false;
break;
}
// Lock and Load
case 56453:
{
// Proc only from Frost/Freezing trap activation or from Freezing Arrow (the periodic dmg proc handled elsewhere)
if (!(procFlags & PROC_FLAG_DONE_TRAP_ACTIVATION) || !procSpell || !(procSpell->SchoolMask & SPELL_SCHOOL_MASK_FROST) || !roll_chance_i(triggerAmount))
return false;
break;
}
// Glyph of Death's Embrace
case 58679:
{
// Proc only from healing part of Death Coil. Check is essential as all Death Coil spells have 0x2000 mask in SpellFamilyFlags
if (!procSpell || !(procSpell->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && procSpell->SpellFamilyFlags[0] == 0x80002000))
return false;
break;
}
// Glyph of Death Grip
case 58628:
{
// remove cooldown of Death Grip
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->RemoveSpellCooldown(49576, true);
return true;
}
// Savage Defense
case 62606:
{
basepoints0 = CalculatePctF(triggerAmount, GetTotalAttackPowerValue(BASE_ATTACK));
break;
}
// Body and Soul
case 64128:
case 65081:
{
// Proc only from PW:S cast
if (!(procSpell->SpellFamilyFlags[0] & 0x00000001))
return false;
break;
}
// Culling the Herd
case 70893:
{
// check if we're doing a critical hit
if (!(procSpell->SpellFamilyFlags[1] & 0x10000000) && (procEx != PROC_EX_CRITICAL_HIT) )
return false;
// check if we're procced by Claw, Bite or Smack (need to use the spell icon ID to detect it)
if (!(procSpell->SpellIconID == 262 || procSpell->SpellIconID == 1680 || procSpell->SpellIconID == 473 ))
return false;
break;
}
// Shadow's Fate (Shadowmourne questline)
case 71169:
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
Player* player = ToPlayer();
if (player->GetQuestStatus(24749) == QUEST_STATUS_INCOMPLETE) // Unholy Infusion
{
if (!player->HasAura(71516) || victim->GetEntry() != 36678) // Shadow Infusion && Professor Putricide
return false;
}
else if (player->GetQuestStatus(24756) == QUEST_STATUS_INCOMPLETE) // Blood Infusion
{
if (!player->HasAura(72154) || victim->GetEntry() != 37955) // Thirst Quenched && Blood-Queen Lana'thel
return false;
}
else if (player->GetQuestStatus(24757) == QUEST_STATUS_INCOMPLETE) // Frost Infusion
{
if (!player->HasAura(72290) || victim->GetEntry() != 36853) // Frost-Imbued Blade && Sindragosa
return false;
}
else if (player->GetQuestStatus(24547) != QUEST_STATUS_INCOMPLETE) // A Feast of Souls
return false;
if (victim->GetTypeId() != TYPEID_UNIT)
return false;
// critters are not allowed
if (victim->GetCreatureType() == CREATURE_TYPE_CRITTER)
return false;
break;
}
}
if (cooldown && GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(trigger_spell_id))
return false;
// try detect target manually if not set
if (target == NULL)
target = !(procFlags & (PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS | PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS)) && triggerEntry && triggerEntry->IsPositive() ? this : victim;
if (basepoints0)
CastCustomSpell(target, trigger_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
else
CastSpell(target, trigger_spell_id, true, castItem, triggeredByAura);
if (cooldown && GetTypeId() == TYPEID_PLAYER)
ToPlayer()->AddSpellCooldown(trigger_spell_id, 0, time(NULL) + cooldown);
return true;
}
bool Unit::HandleOverrideClassScriptAuraProc(Unit* victim, uint32 /*damage*/, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 cooldown)
{
int32 scriptId = triggeredByAura->GetMiscValue();
if (!victim || !victim->isAlive())
return false;
Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
? ToPlayer()->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
uint32 triggered_spell_id = 0;
switch (scriptId)
{
case 836: // Improved Blizzard (Rank 1)
{
if (!procSpell || procSpell->SpellVisual[0] != 9487)
return false;
triggered_spell_id = 12484;
break;
}
case 988: // Improved Blizzard (Rank 2)
{
if (!procSpell || procSpell->SpellVisual[0] != 9487)
return false;
triggered_spell_id = 12485;
break;
}
case 989: // Improved Blizzard (Rank 3)
{
if (!procSpell || procSpell->SpellVisual[0] != 9487)
return false;
triggered_spell_id = 12486;
break;
}
case 4533: // Dreamwalker Raiment 2 pieces bonus
{
// Chance 50%
if (!roll_chance_i(50))
return false;
switch (victim->getPowerType())
{
case POWER_MANA: triggered_spell_id = 28722; break;
case POWER_RAGE: triggered_spell_id = 28723; break;
case POWER_ENERGY: triggered_spell_id = 28724; break;
default:
return false;
}
break;
}
case 4537: // Dreamwalker Raiment 6 pieces bonus
triggered_spell_id = 28750; // Blessing of the Claw
break;
case 5497: // Improved Mana Gems
triggered_spell_id = 37445; // Mana Surge
break;
case 7010: // Revitalize - can proc on full hp target
case 7011:
case 7012:
{
if (!roll_chance_i(triggeredByAura->GetAmount()))
return false;
switch (victim->getPowerType())
{
case POWER_MANA: triggered_spell_id = 48542; break;
case POWER_RAGE: triggered_spell_id = 48541; break;
case POWER_ENERGY: triggered_spell_id = 48540; break;
case POWER_RUNIC_POWER: triggered_spell_id = 48543; break;
default:
break;
}
break;
}
default:
break;
}
// not processed
if (!triggered_spell_id)
return false;
// standard non-dummy case
SpellInfo const* triggerEntry = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!triggerEntry)
{
sLog->outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u", triggered_spell_id, scriptId);
return false;
}
if (cooldown && GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(triggered_spell_id))
return false;
CastSpell(victim, triggered_spell_id, true, castItem, triggeredByAura);
if (cooldown && GetTypeId() == TYPEID_PLAYER)
ToPlayer()->AddSpellCooldown(triggered_spell_id, 0, time(NULL) + cooldown);
return true;
}
void Unit::setPowerType(Powers new_powertype)
{
SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype);
if (GetTypeId() == TYPEID_PLAYER)
{
if (ToPlayer()->GetGroup())
ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE);
}
else if (Pet* pet = ToCreature()->ToPet())
{
if (pet->isControlled())
{
Unit* owner = GetOwner();
if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup())
owner->ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE);
}
}
switch (new_powertype)
{
default:
case POWER_MANA:
break;
case POWER_RAGE:
SetMaxPower(POWER_RAGE, GetCreatePowers(POWER_RAGE));
SetPower(POWER_RAGE, 0);
break;
case POWER_FOCUS:
SetMaxPower(POWER_FOCUS, GetCreatePowers(POWER_FOCUS));
SetPower(POWER_FOCUS, GetCreatePowers(POWER_FOCUS));
break;
case POWER_ENERGY:
SetMaxPower(POWER_ENERGY, GetCreatePowers(POWER_ENERGY));
break;
case POWER_HAPPINESS:
SetMaxPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS));
SetPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS));
break;
}
}
FactionTemplateEntry const* Unit::getFactionTemplateEntry() const
{
FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction());
if (!entry)
{
static uint64 guid = 0; // prevent repeating spam same faction problem
if (GetGUID() != guid)
{
if (Player const* player = ToPlayer())
sLog->outError("Player %s has invalid faction (faction template id) #%u", player->GetName(), getFaction());
else if (Creature const* creature = ToCreature())
sLog->outError("Creature (template id: %u) has invalid faction (faction template id) #%u", creature->GetCreatureInfo()->Entry, getFaction());
else
sLog->outError("Unit (name=%s, type=%u) has invalid faction (faction template id) #%u", GetName(), uint32(GetTypeId()), getFaction());
guid = GetGUID();
}
}
return entry;
}
// function based on function Unit::UnitReaction from 13850 client
ReputationRank Unit::GetReactionTo(Unit const* target) const
{
// always friendly to self
if (this == target)
return REP_FRIENDLY;
// always friendly to charmer or owner
if (GetCharmerOrOwnerOrSelf() == target->GetCharmerOrOwnerOrSelf())
return REP_FRIENDLY;
if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE))
{
if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE))
{
Player const* selfPlayerOwner = GetAffectingPlayer();
Player const* targetPlayerOwner = target->GetAffectingPlayer();
if (selfPlayerOwner && targetPlayerOwner)
{
// always friendly to other unit controlled by player, or to the player himself
if (selfPlayerOwner == targetPlayerOwner)
return REP_FRIENDLY;
// duel - always hostile to opponent
if (selfPlayerOwner->duel && selfPlayerOwner->duel->opponent == targetPlayerOwner && selfPlayerOwner->duel->startTime != 0)
return REP_HOSTILE;
// same group - checks dependant only on our faction - skip FFA_PVP for example
if (selfPlayerOwner->IsInRaidWith(targetPlayerOwner))
return REP_FRIENDLY; // return true to allow config option AllowTwoSide.Interaction.Group to work
// however client seems to allow mixed group parties, because in 13850 client it works like:
// return GetFactionReactionTo(getFactionTemplateEntry(), target);
}
// check FFA_PVP
if (GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP
&& target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP)
return REP_HOSTILE;
if (selfPlayerOwner)
{
if (FactionTemplateEntry const* targetFactionTemplateEntry = target->getFactionTemplateEntry())
{
if (ReputationRank const* repRank = selfPlayerOwner->GetReputationMgr().GetForcedRankIfAny(targetFactionTemplateEntry))
return *repRank;
if (!selfPlayerOwner->HasFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_IGNORE_REPUTATION))
{
if (FactionEntry const* targetFactionEntry = sFactionStore.LookupEntry(targetFactionTemplateEntry->faction))
{
if (targetFactionEntry->CanHaveReputation())
{
// check contested flags
if (targetFactionTemplateEntry->factionFlags & FACTION_TEMPLATE_FLAG_CONTESTED_GUARD
&& selfPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP))
return REP_HOSTILE;
// if faction have reputation then hostile state dependent only from at_war state
if (selfPlayerOwner->GetReputationMgr().IsAtWar(targetFactionEntry))
return REP_HOSTILE;
return REP_FRIENDLY;
}
}
}
}
}
}
}
// do checks dependant only on our faction
return GetFactionReactionTo(getFactionTemplateEntry(), target);
}
ReputationRank Unit::GetFactionReactionTo(FactionTemplateEntry const* factionTemplateEntry, Unit const* target)
{
// always neutral when no template entry found
if (!factionTemplateEntry)
return REP_NEUTRAL;
FactionTemplateEntry const* targetFactionTemplateEntry = target->getFactionTemplateEntry();
if (!targetFactionTemplateEntry)
return REP_NEUTRAL;
if (Player const* targetPlayerOwner = target->GetAffectingPlayer())
{
// check contested flags
if (factionTemplateEntry->factionFlags & FACTION_TEMPLATE_FLAG_CONTESTED_GUARD
&& targetPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP))
return REP_HOSTILE;
if (ReputationRank const* repRank = targetPlayerOwner->GetReputationMgr().GetForcedRankIfAny(factionTemplateEntry))
return *repRank;
if (!target->HasFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_IGNORE_REPUTATION))
{
if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction))
{
if (factionEntry->CanHaveReputation())
{
// CvP case - check reputation, don't allow state higher than neutral when at war
ReputationRank repRank = targetPlayerOwner->GetReputationMgr().GetRank(factionEntry);
if (targetPlayerOwner->GetReputationMgr().IsAtWar(factionEntry))
repRank = std::min(REP_NEUTRAL, repRank);
return repRank;
}
}
}
}
// common faction based check
if (factionTemplateEntry->IsHostileTo(*targetFactionTemplateEntry))
return REP_HOSTILE;
if (factionTemplateEntry->IsFriendlyTo(*targetFactionTemplateEntry))
return REP_FRIENDLY;
if (targetFactionTemplateEntry->IsFriendlyTo(*factionTemplateEntry))
return REP_FRIENDLY;
if (factionTemplateEntry->factionFlags & FACTION_TEMPLATE_FLAG_HOSTILE_BY_DEFAULT)
return REP_HOSTILE;
// neutral by default
return REP_NEUTRAL;
}
bool Unit::IsHostileTo(Unit const* unit) const
{
return GetReactionTo(unit) <= REP_HOSTILE;
}
bool Unit::IsFriendlyTo(Unit const* unit) const
{
return GetReactionTo(unit) >= REP_FRIENDLY;
}
bool Unit::IsHostileToPlayers() const
{
FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
if (!my_faction || !my_faction->faction)
return false;
FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
if (raw_faction && raw_faction->reputationListID >= 0)
return false;
return my_faction->IsHostileToPlayers();
}
bool Unit::IsNeutralToAll() const
{
FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
if (!my_faction || !my_faction->faction)
return true;
FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
if (raw_faction && raw_faction->reputationListID >= 0)
return false;
return my_faction->IsNeutralToAll();
}
bool Unit::Attack(Unit* victim, bool meleeAttack)
{
if (!victim || victim == this)
return false;
// dead units can neither attack nor be attacked
if (!isAlive() || !victim->IsInWorld() || !victim->isAlive())
return false;
// player cannot attack in mount state
if (GetTypeId() == TYPEID_PLAYER && IsMounted())
return false;
// nobody can attack GM in GM-mode
if (victim->GetTypeId() == TYPEID_PLAYER)
{
if (victim->ToPlayer()->isGameMaster())
return false;
}
else
{
if (victim->ToCreature()->IsInEvadeMode())
return false;
}
// remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack)
if (HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
RemoveAurasByType(SPELL_AURA_MOD_UNATTACKABLE);
if (m_attacking)
{
if (m_attacking == victim)
{
// switch to melee attack from ranged/magic
if (meleeAttack)
{
if (!HasUnitState(UNIT_STAT_MELEE_ATTACKING))
{
AddUnitState(UNIT_STAT_MELEE_ATTACKING);
SendMeleeAttackStart(victim);
return true;
}
}
else if (HasUnitState(UNIT_STAT_MELEE_ATTACKING))
{
ClearUnitState(UNIT_STAT_MELEE_ATTACKING);
SendMeleeAttackStop(victim);
return true;
}
return false;
}
// switch target
InterruptSpell(CURRENT_MELEE_SPELL);
if (!meleeAttack)
ClearUnitState(UNIT_STAT_MELEE_ATTACKING);
}
if (m_attacking)
m_attacking->_removeAttacker(this);
m_attacking = victim;
m_attacking->_addAttacker(this);
// Set our target
SetTarget(victim->GetGUID());
if (meleeAttack)
AddUnitState(UNIT_STAT_MELEE_ATTACKING);
// set position before any AI calls/assistance
//if (GetTypeId() == TYPEID_UNIT)
// ToCreature()->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ());
if (GetTypeId() == TYPEID_UNIT && !ToCreature()->isPet())
{
// should not let player enter combat by right clicking target - doesn't helps
SetInCombatWith(victim);
if (victim->GetTypeId() == TYPEID_PLAYER)
victim->SetInCombatWith(this);
AddThreat(victim, 0.0f);
ToCreature()->SendAIReaction(AI_REACTION_HOSTILE);
ToCreature()->CallAssistance();
}
// delay offhand weapon attack to next attack time
if (haveOffhandWeapon())
resetAttackTimer(OFF_ATTACK);
if (meleeAttack)
SendMeleeAttackStart(victim);
return true;
}
bool Unit::AttackStop()
{
if (!m_attacking)
return false;
Unit* victim = m_attacking;
m_attacking->_removeAttacker(this);
m_attacking = NULL;
// Clear our target
SetTarget(0);
ClearUnitState(UNIT_STAT_MELEE_ATTACKING);
InterruptSpell(CURRENT_MELEE_SPELL);
// reset only at real combat stop
if (Creature* creature = ToCreature())
{
creature->SetNoCallAssistance(false);
if (creature->HasSearchedAssistance())
{
creature->SetNoSearchAssistance(false);
UpdateSpeed(MOVE_RUN, false);
}
}
SendMeleeAttackStop(victim);
return true;
}
void Unit::CombatStop(bool includingCast)
{
if (includingCast && IsNonMeleeSpellCasted(false))
InterruptNonMeleeSpells(false);
AttackStop();
RemoveAllAttackers();
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel
ClearInCombat();
}
void Unit::CombatStopWithPets(bool includingCast)
{
CombatStop(includingCast);
for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
(*itr)->CombatStop(includingCast);
}
bool Unit::isAttackingPlayer() const
{
if (HasUnitState(UNIT_STAT_ATTACK_PLAYER))
return true;
for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
if ((*itr)->isAttackingPlayer())
return true;
for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i)
if (m_SummonSlot[i])
if (Creature* summon = GetMap()->GetCreature(m_SummonSlot[i]))
if (summon->isAttackingPlayer())
return true;
return false;
}
void Unit::RemoveAllAttackers()
{
while (!m_attackers.empty())
{
AttackerSet::iterator iter = m_attackers.begin();
if (!(*iter)->AttackStop())
{
sLog->outError("WORLD: Unit has an attacker that isn't attacking it!");
m_attackers.erase(iter);
}
}
}
void Unit::ModifyAuraState(AuraStateType flag, bool apply)
{
if (apply)
{
if (!HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)))
{
SetFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
if (GetTypeId() == TYPEID_PLAYER)
{
PlayerSpellMap const& sp_list = ToPlayer()->GetSpellMap();
for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
{
if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
continue;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first);
if (!spellInfo || !spellInfo->IsPassive())
continue;
if (spellInfo->CasterAuraState == uint32(flag))
CastSpell(this, itr->first, true, NULL);
}
}
else if (Pet* pet = ToCreature()->ToPet())
{
for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
{
if (itr->second.state == PETSPELL_REMOVED)
continue;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first);
if (!spellInfo || !spellInfo->IsPassive())
continue;
if (spellInfo->CasterAuraState == uint32(flag))
CastSpell(this, itr->first, true, NULL);
}
}
}
}
else
{
if (HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)))
{
RemoveFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
if (flag != AURA_STATE_ENRAGE) // enrage aura state triggering continues auras
{
Unit::AuraApplicationMap& tAuras = GetAppliedAuras();
for (Unit::AuraApplicationMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
{
SpellInfo const* spellProto = (*itr).second->GetBase()->GetSpellInfo();
if (spellProto->CasterAuraState == uint32(flag))
RemoveAura(itr);
else
++itr;
}
}
}
}
}
uint32 Unit::BuildAuraStateUpdateForTarget(Unit* target) const
{
uint32 auraStates = GetUInt32Value(UNIT_FIELD_AURASTATE) &~(PER_CASTER_AURA_STATE_MASK);
for (AuraStateAurasMap::const_iterator itr = m_auraStateAuras.begin(); itr != m_auraStateAuras.end(); ++itr)
if ((1<<(itr->first-1)) & PER_CASTER_AURA_STATE_MASK)
if (itr->second->GetBase()->GetCasterGUID() == target->GetGUID())
auraStates |= (1<<(itr->first-1));
return auraStates;
}
bool Unit::HasAuraState(AuraStateType flag, SpellInfo const* spellProto, Unit const* Caster) const
{
if (Caster)
{
if (spellProto)
{
AuraEffectList const& stateAuras = Caster->GetAuraEffectsByType(SPELL_AURA_ABILITY_IGNORE_AURASTATE);
for (AuraEffectList::const_iterator j = stateAuras.begin(); j != stateAuras.end(); ++j)
if ((*j)->IsAffectedOnSpell(spellProto))
return true;
}
// Check per caster aura state
// If aura with aurastate by caster not found return false
if ((1<<(flag-1)) & PER_CASTER_AURA_STATE_MASK)
{
for (AuraStateAurasMap::const_iterator itr = m_auraStateAuras.lower_bound(flag); itr != m_auraStateAuras.upper_bound(flag); ++itr)
if (itr->second->GetBase()->GetCasterGUID() == Caster->GetGUID())
return true;
return false;
}
}
return HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
}
Unit* Unit::GetOwner() const
{
if (uint64 ownerid = GetOwnerGUID())
{
return ObjectAccessor::GetUnit(*this, ownerid);
}
return NULL;
}
Unit* Unit::GetCharmer() const
{
if (uint64 charmerid = GetCharmerGUID())
return ObjectAccessor::GetUnit(*this, charmerid);
return NULL;
}
Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself() const
{
uint64 guid = GetCharmerOrOwnerGUID();
if (IS_PLAYER_GUID(guid))
return ObjectAccessor::GetPlayer(*this, guid);
return GetTypeId() == TYPEID_PLAYER ? (Player*)this : NULL;
}
Player* Unit::GetAffectingPlayer() const
{
if (!GetCharmerOrOwnerGUID())
return GetTypeId() == TYPEID_PLAYER ? (Player*)this : NULL;
if (Unit* owner = GetCharmerOrOwner())
return owner->GetCharmerOrOwnerPlayerOrPlayerItself();
return NULL;
}
Minion *Unit::GetFirstMinion() const
{
if (uint64 pet_guid = GetMinionGUID())
{
if (Creature* pet = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, pet_guid))
if (pet->HasUnitTypeMask(UNIT_MASK_MINION))
return (Minion*)pet;
sLog->outError("Unit::GetFirstMinion: Minion %u not exist.", GUID_LOPART(pet_guid));
const_cast<Unit*>(this)->SetMinionGUID(0);
}
return NULL;
}
Guardian* Unit::GetGuardianPet() const
{
if (uint64 pet_guid = GetPetGUID())
{
if (Creature* pet = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, pet_guid))
if (pet->HasUnitTypeMask(UNIT_MASK_GUARDIAN))
return (Guardian*)pet;
sLog->outCrash("Unit::GetGuardianPet: Guardian " UI64FMTD " not exist.", pet_guid);
const_cast<Unit*>(this)->SetPetGUID(0);
}
return NULL;
}
Unit* Unit::GetCharm() const
{
if (uint64 charm_guid = GetCharmGUID())
{
if (Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid))
return pet;
sLog->outError("Unit::GetCharm: Charmed creature %u not exist.", GUID_LOPART(charm_guid));
const_cast<Unit*>(this)->SetUInt64Value(UNIT_FIELD_CHARM, 0);
}
return NULL;
}
void Unit::SetMinion(Minion *minion, bool apply)
{
sLog->outDebug(LOG_FILTER_UNITS, "SetMinion %u for %u, apply %u", minion->GetEntry(), GetEntry(), apply);
if (apply)
{
if (!minion->AddUInt64Value(UNIT_FIELD_SUMMONEDBY, GetGUID()))
{
sLog->outCrash("SetMinion: Minion %u is not the minion of owner %u", minion->GetEntry(), GetEntry());
return;
}
m_Controlled.insert(minion);
if (GetTypeId() == TYPEID_PLAYER)
{
minion->m_ControlledByPlayer = true;
minion->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
}
// Can only have one pet. If a new one is summoned, dismiss the old one.
if (minion->IsGuardianPet())
{
if (Guardian* oldPet = GetGuardianPet())
{
if (oldPet != minion && (oldPet->isPet() || minion->isPet() || oldPet->GetEntry() != minion->GetEntry()))
{
// remove existing minion pet
if (oldPet->isPet())
((Pet*)oldPet)->Remove(PET_SAVE_AS_CURRENT);
else
oldPet->UnSummon();
SetPetGUID(minion->GetGUID());
SetMinionGUID(0);
}
}
else
{
SetPetGUID(minion->GetGUID());
SetMinionGUID(0);
}
}
if (minion->HasUnitTypeMask(UNIT_MASK_CONTROLABLE_GUARDIAN))
{
if (AddUInt64Value(UNIT_FIELD_SUMMON, minion->GetGUID()))
{
}
}
if (minion->m_Properties && minion->m_Properties->Type == SUMMON_TYPE_MINIPET)
{
SetCritterGUID(minion->GetGUID());
}
// PvP, FFAPvP
minion->SetByteValue(UNIT_FIELD_BYTES_2, 1, GetByteValue(UNIT_FIELD_BYTES_2, 1));
// FIXME: hack, speed must be set only at follow
if (GetTypeId() == TYPEID_PLAYER && minion->isPet())
for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i)
minion->SetSpeed(UnitMoveType(i), m_speed_rate[i], true);
// Ghoul pets have energy instead of mana (is anywhere better place for this code?)
if (minion->IsPetGhoul())
minion->setPowerType(POWER_ENERGY);
if (GetTypeId() == TYPEID_PLAYER)
{
// Send infinity cooldown - client does that automatically but after relog cooldown needs to be set again
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(minion->GetUInt32Value(UNIT_CREATED_BY_SPELL));
if (spellInfo && (spellInfo->Attributes & SPELL_ATTR0_DISABLED_WHILE_ACTIVE))
ToPlayer()->AddSpellAndCategoryCooldowns(spellInfo, 0, NULL, true);
}
}
else
{
if (minion->GetOwnerGUID() != GetGUID())
{
sLog->outCrash("SetMinion: Minion %u is not the minion of owner %u", minion->GetEntry(), GetEntry());
return;
}
m_Controlled.erase(minion);
if (minion->m_Properties && minion->m_Properties->Type == SUMMON_TYPE_MINIPET)
{
if (GetCritterGUID() == minion->GetGUID())
SetCritterGUID(0);
}
if (minion->IsGuardianPet())
{
if (GetPetGUID() == minion->GetGUID())
SetPetGUID(0);
}
else if (minion->isTotem())
{
// All summoned by totem minions must disappear when it is removed.
if (SpellInfo const* spInfo = sSpellMgr->GetSpellInfo(minion->ToTotem()->GetSpell()))
for (int i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (spInfo->Effects[i].Effect != SPELL_EFFECT_SUMMON)
continue;
RemoveAllMinionsByEntry(spInfo->Effects[i].MiscValue);
}
}
if (GetTypeId() == TYPEID_PLAYER)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(minion->GetUInt32Value(UNIT_CREATED_BY_SPELL));
// Remove infinity cooldown
if (spellInfo && (spellInfo->Attributes & SPELL_ATTR0_DISABLED_WHILE_ACTIVE))
ToPlayer()->SendCooldownEvent(spellInfo);
}
//if (minion->HasUnitTypeMask(UNIT_MASK_GUARDIAN))
{
if (RemoveUInt64Value(UNIT_FIELD_SUMMON, minion->GetGUID()))
{
// Check if there is another minion
for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
{
// do not use this check, creature do not have charm guid
//if (GetCharmGUID() == (*itr)->GetGUID())
if (GetGUID() == (*itr)->GetCharmerGUID())
continue;
//ASSERT((*itr)->GetOwnerGUID() == GetGUID());
if ((*itr)->GetOwnerGUID() != GetGUID())
{
OutDebugInfo();
(*itr)->OutDebugInfo();
ASSERT(false);
}
ASSERT((*itr)->GetTypeId() == TYPEID_UNIT);
if (!(*itr)->HasUnitTypeMask(UNIT_MASK_CONTROLABLE_GUARDIAN))
continue;
if (AddUInt64Value(UNIT_FIELD_SUMMON, (*itr)->GetGUID()))
{
// show another pet bar if there is no charm bar
if (GetTypeId() == TYPEID_PLAYER && !GetCharmGUID())
{
if ((*itr)->isPet())
ToPlayer()->PetSpellInitialize();
else
ToPlayer()->CharmSpellInitialize();
}
}
break;
}
}
}
}
}
void Unit::GetAllMinionsByEntry(std::list<Creature*>& Minions, uint32 entry)
{
for (Unit::ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end();)
{
Unit* unit = *itr;
++itr;
if (unit->GetEntry() == entry && unit->GetTypeId() == TYPEID_UNIT
&& unit->ToCreature()->isSummon()) // minion, actually
Minions.push_back(unit->ToCreature());
}
}
void Unit::RemoveAllMinionsByEntry(uint32 entry)
{
for (Unit::ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end();)
{
Unit* unit = *itr;
++itr;
if (unit->GetEntry() == entry && unit->GetTypeId() == TYPEID_UNIT
&& unit->ToCreature()->isSummon()) // minion, actually
unit->ToTempSummon()->UnSummon();
// i think this is safe because i have never heard that a despawned minion will trigger a same minion
}
}
void Unit::SetCharm(Unit* charm, bool apply)
{
if (apply)
{
if (GetTypeId() == TYPEID_PLAYER)
{
if (!AddUInt64Value(UNIT_FIELD_CHARM, charm->GetGUID()))
sLog->outCrash("Player %s is trying to charm unit %u, but it already has a charmed unit " UI64FMTD "", GetName(), charm->GetEntry(), GetCharmGUID());
charm->m_ControlledByPlayer = true;
// TODO: maybe we can use this flag to check if controlled by player
charm->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
}
else
charm->m_ControlledByPlayer = false;
// PvP, FFAPvP
charm->SetByteValue(UNIT_FIELD_BYTES_2, 1, GetByteValue(UNIT_FIELD_BYTES_2, 1));
if (!charm->AddUInt64Value(UNIT_FIELD_CHARMEDBY, GetGUID()))
sLog->outCrash("Unit %u is being charmed, but it already has a charmer " UI64FMTD "", charm->GetEntry(), charm->GetCharmerGUID());
if (charm->HasUnitMovementFlag(MOVEMENTFLAG_WALKING))
{
charm->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING);
charm->SendMovementFlagUpdate();
}
m_Controlled.insert(charm);
}
else
{
if (GetTypeId() == TYPEID_PLAYER)
{
if (!RemoveUInt64Value(UNIT_FIELD_CHARM, charm->GetGUID()))
sLog->outCrash("Player %s is trying to uncharm unit %u, but it has another charmed unit " UI64FMTD "", GetName(), charm->GetEntry(), GetCharmGUID());
}
if (!charm->RemoveUInt64Value(UNIT_FIELD_CHARMEDBY, GetGUID()))
sLog->outCrash("Unit %u is being uncharmed, but it has another charmer " UI64FMTD "", charm->GetEntry(), charm->GetCharmerGUID());
if (charm->GetTypeId() == TYPEID_PLAYER)
{
charm->m_ControlledByPlayer = true;
charm->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
charm->ToPlayer()->UpdatePvPState();
}
else if (Player* player = charm->GetCharmerOrOwnerPlayerOrPlayerItself())
{
charm->m_ControlledByPlayer = true;
charm->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
charm->SetByteValue(UNIT_FIELD_BYTES_2, 1, player->GetByteValue(UNIT_FIELD_BYTES_2, 1));
}
else
{
charm->m_ControlledByPlayer = false;
charm->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
charm->SetByteValue(UNIT_FIELD_BYTES_2, 1, 0);
}
if (charm->GetTypeId() == TYPEID_PLAYER
|| !charm->ToCreature()->HasUnitTypeMask(UNIT_MASK_MINION)
|| charm->GetOwnerGUID() != GetGUID())
m_Controlled.erase(charm);
}
}
int32 Unit::DealHeal(Unit* victim, uint32 addhealth)
{
int32 gain = 0;
if (victim->IsAIEnabled)
victim->GetAI()->HealReceived(this, addhealth);
if (IsAIEnabled)
GetAI()->HealDone(victim, addhealth);
if (addhealth)
gain = victim->ModifyHealth(int32(addhealth));
Unit* unit = this;
if (GetTypeId() == TYPEID_UNIT && ToCreature()->isTotem())
unit = GetOwner();
if (Player* player = unit->ToPlayer())
{
if (Battleground* bg = player->GetBattleground())
bg->UpdatePlayerScore(player, SCORE_HEALING_DONE, gain);
// use the actual gain, as the overheal shall not be counted, skip gain 0 (it ignored anyway in to criteria)
if (gain)
player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE, gain, 0, victim);
player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED, addhealth);
}
if (Player* player = victim->ToPlayer())
{
player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED, gain);
player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED, addhealth);
/** World of Warcraft Armory **/
if (Battleground *bgV = victim->ToPlayer()->GetBattleground())
bgV->UpdatePlayerScore((Player*)victim, SCORE_HEALING_TAKEN, gain);
/** World of Warcraft Armory **/
}
return gain;
}
Unit* Unit::SelectMagnetTarget(Unit* victim, SpellInfo const* spellInfo)
{
if (!victim)
return NULL;
// Magic case
if (spellInfo && (spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC))
{
// Patch 1.2 notes: Spell Reflection no longer reflects abilities
if (spellInfo->Attributes & SPELL_ATTR0_ABILITY || spellInfo->AttributesEx & SPELL_ATTR1_CANT_BE_REDIRECTED || spellInfo->Attributes & SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY)
return victim;
// I am not sure if this should be redirected.
if (spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE)
return victim;
Unit::AuraEffectList const& magnetAuras = victim->GetAuraEffectsByType(SPELL_AURA_SPELL_MAGNET);
for (Unit::AuraEffectList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
if (Unit* magnet = (*itr)->GetBase()->GetUnitOwner())
if (magnet->isAlive() && IsWithinLOSInMap(magnet))
{
(*itr)->GetBase()->DropCharge(AURA_REMOVE_BY_EXPIRE);
return magnet;
}
}
// Melee && ranged case
else
{
AuraEffectList const& hitTriggerAuras = victim->GetAuraEffectsByType(SPELL_AURA_ADD_CASTER_HIT_TRIGGER);
for (AuraEffectList::const_iterator i = hitTriggerAuras.begin(); i != hitTriggerAuras.end(); ++i)
if (Unit* magnet = (*i)->GetBase()->GetCaster())
if (magnet->isAlive() && magnet->IsWithinLOSInMap(this))
if (roll_chance_i((*i)->GetAmount()))
{
(*i)->GetBase()->DropCharge(AURA_REMOVE_BY_EXPIRE);
return magnet;
}
}
return victim;
}
Unit* Unit::GetFirstControlled() const
{
// Sequence: charmed, pet, other guardians
Unit* unit = GetCharm();
if (!unit)
if (uint64 guid = GetUInt64Value(UNIT_FIELD_SUMMON))
unit = ObjectAccessor::GetUnit(*this, guid);
return unit;
}
void Unit::RemoveAllControlled()
{
// possessed pet and vehicle
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->StopCastingCharm();
while (!m_Controlled.empty())
{
Unit* target = *m_Controlled.begin();
m_Controlled.erase(m_Controlled.begin());
if (target->GetCharmerGUID() == GetGUID())
target->RemoveCharmAuras();
else if (target->GetOwnerGUID() == GetGUID() && target->isSummon())
target->ToTempSummon()->UnSummon();
else
sLog->outError("Unit %u is trying to release unit %u which is neither charmed nor owned by it", GetEntry(), target->GetEntry());
}
if (GetPetGUID())
sLog->outCrash("Unit %u is not able to release its pet " UI64FMTD, GetEntry(), GetPetGUID());
if (GetMinionGUID())
sLog->outCrash("Unit %u is not able to release its minion " UI64FMTD, GetEntry(), GetMinionGUID());
if (GetCharmGUID())
sLog->outCrash("Unit %u is not able to release its charm " UI64FMTD, GetEntry(), GetCharmGUID());
}
Unit* Unit::GetNextRandomRaidMemberOrPet(float radius)
{
Player* player = NULL;
if (GetTypeId() == TYPEID_PLAYER)
player = ToPlayer();
// Should we enable this also for charmed units?
else if (GetTypeId() == TYPEID_UNIT && ToCreature()->isPet())
player = GetOwner()->ToPlayer();
if (!player)
return NULL;
Group* group = player->GetGroup();
// When there is no group check pet presence
if (!group)
{
// We are pet now, return owner
if (player != this)
return IsWithinDistInMap(player, radius) ? player : NULL;
Unit* pet = GetGuardianPet();
// No pet, no group, nothing to return
if (!pet)
return NULL;
// We are owner now, return pet
return IsWithinDistInMap(pet, radius) ? pet : NULL;
}
std::vector<Unit*> nearMembers;
// reserve place for players and pets because resizing vector every unit push is unefficient (vector is reallocated then)
nearMembers.reserve(group->GetMembersCount() * 2);
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
if (Player* Target = itr->getSource())
{
// IsHostileTo check duel and controlled by enemy
if (Target != this && Target->isAlive() && IsWithinDistInMap(Target, radius) && !IsHostileTo(Target))
nearMembers.push_back(Target);
// Push player's pet to vector
if (Unit* pet = Target->GetGuardianPet())
if (pet != this && pet->isAlive() && IsWithinDistInMap(pet, radius) && !IsHostileTo(pet))
nearMembers.push_back(pet);
}
if (nearMembers.empty())
return NULL;
uint32 randTarget = urand(0, nearMembers.size()-1);
return nearMembers[randTarget];
}
// only called in Player::SetSeer
// so move it to Player?
void Unit::AddPlayerToVision(Player* player)
{
if (m_sharedVision.empty())
{
setActive(true);
SetWorldObject(true);
}
m_sharedVision.push_back(player);
}
// only called in Player::SetSeer
void Unit::RemovePlayerFromVision(Player* player)
{
m_sharedVision.remove(player);
if (m_sharedVision.empty())
{
setActive(false);
SetWorldObject(false);
}
}
void Unit::RemoveBindSightAuras()
{
RemoveAurasByType(SPELL_AURA_BIND_SIGHT);
}
void Unit::RemoveCharmAuras()
{
RemoveAurasByType(SPELL_AURA_MOD_CHARM);
RemoveAurasByType(SPELL_AURA_MOD_POSSESS_PET);
RemoveAurasByType(SPELL_AURA_MOD_POSSESS);
RemoveAurasByType(SPELL_AURA_AOE_CHARM);
}
void Unit::UnsummonAllTotems()
{
for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i)
{
if (!m_SummonSlot[i])
continue;
if (Creature* OldTotem = GetMap()->GetCreature(m_SummonSlot[i]))
if (OldTotem->isSummon())
OldTotem->ToTempSummon()->UnSummon();
}
}
void Unit::SendHealSpellLog(Unit* victim, uint32 SpellID, uint32 Damage, uint32 OverHeal, uint32 Absorb, bool critical)
{
// we guess size
WorldPacket data(SMSG_SPELLHEALLOG, (8+8+4+4+4+4+1+1));
data.append(victim->GetPackGUID());
data.append(GetPackGUID());
data << uint32(SpellID);
data << uint32(Damage);
data << uint32(OverHeal);
data << uint32(Absorb); // Absorb amount
data << uint8(critical ? 1 : 0);
data << uint8(0); // unused
SendMessageToSet(&data, true);
}
int32 Unit::HealBySpell(Unit* victim, SpellInfo const* spellInfo, uint32 addHealth, bool critical)
{
uint32 absorb = 0;
// calculate heal absorb and reduce healing
CalcHealAbsorb(victim, spellInfo, addHealth, absorb);
int32 gain = DealHeal(victim, addHealth);
SendHealSpellLog(victim, spellInfo->Id, addHealth, uint32(addHealth - gain), absorb, critical);
return gain;
}
void Unit::SendEnergizeSpellLog(Unit* victim, uint32 spellID, uint32 damage, Powers powerType)
{
WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
data.append(victim->GetPackGUID());
data.append(GetPackGUID());
data << uint32(spellID);
data << uint32(powerType);
data << uint32(damage);
SendMessageToSet(&data, true);
}
void Unit::EnergizeBySpell(Unit* victim, uint32 spellID, uint32 damage, Powers powerType)
{
SendEnergizeSpellLog(victim, spellID, damage, powerType);
// needs to be called after sending spell log
victim->ModifyPower(powerType, damage);
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellID);
victim->getHostileRefManager().threatAssist(this, float(damage) * 0.5f, spellInfo);
}
uint32 Unit::SpellDamageBonus(Unit* victim, SpellInfo const* spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack)
{
if (!spellProto || !victim || damagetype == DIRECT_DAMAGE)
return pdamage;
// small exception for Deep Wounds, can't find any general rule
// should ignore ALL damage mods, they already calculated in trigger spell
if (spellProto->Id == 12721) // Deep Wounds
return pdamage;
// For totems get damage bonus from owner
if (GetTypeId() == TYPEID_UNIT && ToCreature()->isTotem())
if (Unit* owner = GetOwner())
return owner->SpellDamageBonus(victim, spellProto, pdamage, damagetype);
// Taken/Done total percent damage auras
float DoneTotalMod = 1.0f;
float ApCoeffMod = 1.0f;
int32 DoneTotal = 0;
int32 TakenTotal = 0;
// ..done
// Pet damage?
if (GetTypeId() == TYPEID_UNIT && !ToCreature()->isPet())
DoneTotalMod *= ToCreature()->GetSpellDamageMod(ToCreature()->GetCreatureInfo()->rank);
AuraEffectList const& mModDamagePercentDone = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
for (AuraEffectList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
{
if (spellProto->EquippedItemClass == -1 && (*i)->GetSpellInfo()->EquippedItemClass != -1) //prevent apply mods from weapon specific case to non weapon specific spells (Example: thunder clap and two-handed weapon specialization)
continue;
if ((*i)->GetMiscValue() & spellProto->GetSchoolMask())
{
if ((*i)->GetSpellInfo()->EquippedItemClass == -1)
AddPctN(DoneTotalMod, (*i)->GetAmount());
else if (!((*i)->GetSpellInfo()->AttributesEx5 & SPELL_ATTR5_SPECIAL_ITEM_CLASS_CHECK) && ((*i)->GetSpellInfo()->EquippedItemSubClassMask == 0))
AddPctN(DoneTotalMod, (*i)->GetAmount());
else if (ToPlayer() && ToPlayer()->HasItemFitToSpellRequirements((*i)->GetSpellInfo()))
AddPctN(DoneTotalMod, (*i)->GetAmount());
}
}
uint32 creatureTypeMask = victim->GetCreatureTypeMask();
// Add flat bonus from spell damage versus
DoneTotal += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask);
AuraEffectList const& mDamageDoneVersus = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
for (AuraEffectList::const_iterator i = mDamageDoneVersus.begin(); i != mDamageDoneVersus.end(); ++i)
if (creatureTypeMask & uint32((*i)->GetMiscValue()))
AddPctN(DoneTotalMod, (*i)->GetAmount());
// bonus against aurastate
AuraEffectList const& mDamageDoneVersusAurastate = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS_AURASTATE);
for (AuraEffectList::const_iterator i = mDamageDoneVersusAurastate.begin(); i != mDamageDoneVersusAurastate.end(); ++i)
if (victim->HasAuraState(AuraStateType((*i)->GetMiscValue())))
AddPctN(DoneTotalMod, (*i)->GetAmount());
// done scripted mod (take it from owner)
Unit* owner = GetOwner() ? GetOwner() : this;
AuraEffectList const& mOverrideClassScript= owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
{
if (!(*i)->IsAffectedOnSpell(spellProto))
continue;
switch ((*i)->GetMiscValue())
{
case 4920: // Molten Fury
case 4919:
case 6917: // Death's Embrace
case 6926:
case 6928:
{
if (victim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this))
AddPctN(DoneTotalMod, (*i)->GetAmount());
break;
}
// Soul Siphon
case 4992:
case 4993:
{
// effect 1 m_amount
int32 maxPercent = (*i)->GetAmount();
// effect 0 m_amount
int32 stepPercent = CalculateSpellDamage(this, (*i)->GetSpellInfo(), 0);
// count affliction effects and calc additional damage in percentage
int32 modPercent = 0;
AuraApplicationMap const& victimAuras = victim->GetAppliedAuras();
for (AuraApplicationMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
{
Aura const* aura = itr->second->GetBase();
SpellInfo const* m_spell = aura->GetSpellInfo();
if (m_spell->SpellFamilyName != SPELLFAMILY_WARLOCK || !(m_spell->SpellFamilyFlags[1] & 0x0004071B || m_spell->SpellFamilyFlags[0] & 0x8044C402))
continue;
modPercent += stepPercent * aura->GetStackAmount();
if (modPercent >= maxPercent)
{
modPercent = maxPercent;
break;
}
}
AddPctN(DoneTotalMod, modPercent);
break;
}
case 6916: // Death's Embrace
case 6925:
case 6927:
if (HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, spellProto, this))
AddPctN(DoneTotalMod, (*i)->GetAmount());
break;
case 5481: // Starfire Bonus
{
if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x200002, 0, 0))
AddPctN(DoneTotalMod, (*i)->GetAmount());
break;
}
case 4418: // Increased Shock Damage
case 4554: // Increased Lightning Damage
case 4555: // Improved Moonfire
case 5142: // Increased Lightning Damage
case 5147: // Improved Consecration / Libram of Resurgence
case 5148: // Idol of the Shooting Star
case 6008: // Increased Lightning Damage
case 8627: // Totem of Hex
{
DoneTotal += (*i)->GetAmount();
break;
}
// Tundra Stalker
// Merciless Combat
case 7277:
{
// Merciless Combat
if ((*i)->GetSpellInfo()->SpellIconID == 2656)
{
if (!victim->HealthAbovePct(35))
AddPctN(DoneTotalMod, (*i)->GetAmount());
}
// Tundra Stalker
else
{
// Frost Fever (target debuff)
if (victim->HasAura(55095))
AddPctN(DoneTotalMod, (*i)->GetAmount());
break;
}
break;
}
// Rage of Rivendare
case 7293:
{
if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0, 0x02000000, 0))
AddPctF(DoneTotalMod, (*i)->GetSpellInfo()->GetRank() * 2.0f);
break;
}
// Twisted Faith
case 7377:
{
if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x8000, 0, 0, GetGUID()))
AddPctN(DoneTotalMod, (*i)->GetAmount());
break;
}
// Marked for Death
case 7598:
case 7599:
case 7600:
case 7601:
case 7602:
{
if (victim->GetAuraEffect(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, 0x400, 0, 0))
AddPctN(DoneTotalMod, (*i)->GetAmount());
break;
}
// Dirty Deeds
case 6427:
case 6428:
case 6579:
case 6580:
{
if (victim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this))
{
// effect 0 have expected value but in negative state
int32 bonus = -(*i)->GetBase()->GetEffect(0)->GetAmount();
AddPctN(DoneTotalMod, bonus);
}
break;
}
}
}
// Custom scripted damage
switch (spellProto->SpellFamilyName)
{
case SPELLFAMILY_MAGE:
// Ice Lance
if (spellProto->SpellIconID == 186)
{
if (victim->HasAuraState(AURA_STATE_FROZEN, spellProto, this))
{
// Glyph of Ice Lance
if (owner->HasAura(56377) && victim->getLevel() > owner->getLevel())
DoneTotalMod *= 4.0f;
else
DoneTotalMod *= 3.0f;
}
}
// Torment the weak
if (spellProto->SpellFamilyFlags[0] & 0x20600021 || spellProto->SpellFamilyFlags[1] & 0x9000)
if (victim->HasAuraWithMechanic((1<<MECHANIC_SNARE)|(1<<MECHANIC_SLOW_ATTACK)))
{
AuraEffectList const& mDumyAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY);
for (AuraEffectList::const_iterator i = mDumyAuras.begin(); i != mDumyAuras.end(); ++i)
if ((*i)->GetSpellInfo()->SpellIconID == 3263)
{
AddPctN(DoneTotalMod, (*i)->GetAmount());
break;
}
}
break;
case SPELLFAMILY_PRIEST:
// Mind Flay
if (spellProto->SpellFamilyFlags[0] & 0x800000)
{
// Glyph of Shadow Word: Pain
if (AuraEffect* aurEff = GetAuraEffect(55687, 0))
// Increase Mind Flay damage if Shadow Word: Pain present on target
if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x8000, 0, 0, GetGUID()))
AddPctN(DoneTotalMod, aurEff->GetAmount());
// Twisted Faith - Mind Flay part
if (AuraEffect* aurEff = GetAuraEffect(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS, SPELLFAMILY_PRIEST, 2848, 1))
// Increase Mind Flay damage if Shadow Word: Pain present on target
if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x8000, 0, 0, GetGUID()))
AddPctN(DoneTotalMod, aurEff->GetAmount());
}
// Smite
else if (spellProto->SpellFamilyFlags[0] & 0x80)
{
// Glyph of Smite
if (AuraEffect* aurEff = GetAuraEffect(55692, 0))
if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x100000, 0, 0, GetGUID()))
AddPctN(DoneTotalMod, aurEff->GetAmount());
}
// Shadow Word: Death
else if (spellProto->SpellFamilyFlags[1] & 0x2)
{
// Glyph of Shadow Word: Death
if (AuraEffect* aurEff = GetAuraEffect(55682, 1))
if (victim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
AddPctN(DoneTotalMod, aurEff->GetAmount());
}
break;
case SPELLFAMILY_PALADIN:
// Judgement of Vengeance/Judgement of Corruption
if ((spellProto->SpellFamilyFlags[1] & 0x400000) && spellProto->SpellIconID == 2292)
{
// Get stack of Holy Vengeance/Blood Corruption on the target added by caster
uint32 stacks = 0;
Unit::AuraEffectList const& auras = victim->GetAuraEffectsByType(SPELL_AURA_PERIODIC_DAMAGE);
for (Unit::AuraEffectList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
if (((*itr)->GetId() == 31803 || (*itr)->GetId() == 53742) && (*itr)->GetCasterGUID() == GetGUID())
{
stacks = (*itr)->GetBase()->GetStackAmount();
break;
}
// + 10% for each application of Holy Vengeance/Blood Corruption on the target
if (stacks)
AddPctU(DoneTotalMod, 10 * stacks);
}
break;
case SPELLFAMILY_DRUID:
// Thorns
if (spellProto->SpellFamilyFlags[0] & 0x100)
{
// Brambles
if (AuraEffect* aurEff = GetAuraEffectOfRankedSpell(16836, 0))
AddPctN(DoneTotalMod, aurEff->GetAmount());
}
break;
case SPELLFAMILY_WARLOCK:
// Fire and Brimstone
if (spellProto->SpellFamilyFlags[1] & 0x00020040)
if (victim->HasAuraState(AURA_STATE_CONFLAGRATE))
{
AuraEffectList const& mDumyAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY);
for (AuraEffectList::const_iterator i = mDumyAuras.begin(); i != mDumyAuras.end(); ++i)
if ((*i)->GetSpellInfo()->SpellIconID == 3173)
{
AddPctN(DoneTotalMod, (*i)->GetAmount());
break;
}
}
// Drain Soul - increased damage for targets under 25 % HP
if (spellProto->SpellFamilyFlags[0] & 0x00004000)
if (HasAura(100001))
DoneTotalMod *= 4;
// Shadow Bite (15% increase from each dot)
if (spellProto->SpellFamilyFlags[1] & 0x00400000 && isPet())
if (uint8 count = victim->GetDoTsByCaster(GetOwnerGUID()))
AddPctN(DoneTotalMod, 15 * count);
break;
case SPELLFAMILY_HUNTER:
// Steady Shot
if (spellProto->SpellFamilyFlags[1] & 0x1)
if (AuraEffect* aurEff = GetAuraEffect(56826, 0)) // Glyph of Steady Shot
if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_HUNTER, 0x00004000, 0, 0, GetGUID()))
AddPctN(DoneTotalMod, aurEff->GetAmount());
break;
case SPELLFAMILY_DEATHKNIGHT:
// Improved Icy Touch
if (spellProto->SpellFamilyFlags[0] & 0x2)
if (AuraEffect* aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 2721, 0))
AddPctN(DoneTotalMod, aurEff->GetAmount());
// Sigil of the Vengeful Heart
if (spellProto->SpellFamilyFlags[0] & 0x2000)
if (AuraEffect* aurEff = GetAuraEffect(64962, EFFECT_1))
AddPctN(DoneTotal, aurEff->GetAmount());
// Glacier Rot
if (spellProto->SpellFamilyFlags[0] & 0x2 || spellProto->SpellFamilyFlags[1] & 0x6)
if (AuraEffect* aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 196, 0))
if (victim->GetDiseasesByCaster(owner->GetGUID()) > 0)
AddPctN(DoneTotalMod, aurEff->GetAmount());
// Impurity (dummy effect)
if (GetTypeId() == TYPEID_PLAYER)
{
PlayerSpellMap playerSpells = ToPlayer()->GetSpellMap();
for (PlayerSpellMap::const_iterator itr = playerSpells.begin(); itr != playerSpells.end(); ++itr)
{
if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
continue;
switch (itr->first)
{
case 49220:
case 49633:
case 49635:
case 49636:
case 49638:
{
if (SpellInfo const* proto = sSpellMgr->GetSpellInfo(itr->first))
AddPctN(ApCoeffMod, proto->Effects[0].CalcValue());
}
break;
}
}
}
break;
}
// ..taken
float TakenTotalMod = 1.0f;
// from positive and negative SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN
// multiplicative bonus, for example Dispersion + Shadowform (0.10*0.85=0.085)
TakenTotalMod *= victim->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN, spellProto->GetSchoolMask());
// .. taken pct: dummy auras
AuraEffectList const& mDummyAuras = victim->GetAuraEffectsByType(SPELL_AURA_DUMMY);
for (AuraEffectList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
{
switch ((*i)->GetSpellInfo()->SpellIconID)
{
// Cheat Death
case 2109:
if ((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL)
{
if (victim->GetTypeId() != TYPEID_PLAYER)
continue;
float mod = victim->ToPlayer()->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE) * (-8.0f);
AddPctF(TakenTotalMod, std::max(mod, float((*i)->GetAmount())));
}
break;
}
}
// From caster spells
AuraEffectList const& mOwnerTaken = victim->GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_FROM_CASTER);
for (AuraEffectList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i)
if ((*i)->GetCasterGUID() == GetGUID() && (*i)->IsAffectedOnSpell(spellProto))
AddPctN(TakenTotalMod, (*i)->GetAmount());
// Mod damage from spell mechanic
if (uint32 mechanicMask = spellProto->GetAllEffectsMechanicMask())
{
AuraEffectList const& mDamageDoneMechanic = victim->GetAuraEffectsByType(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT);
for (AuraEffectList::const_iterator i = mDamageDoneMechanic.begin(); i != mDamageDoneMechanic.end(); ++i)
if (mechanicMask & uint32(1<<((*i)->GetMiscValue())))
AddPctN(TakenTotalMod, (*i)->GetAmount());
}
// Taken/Done fixed damage bonus auras
int32 DoneAdvertisedBenefit = SpellBaseDamageBonus(spellProto->GetSchoolMask());
int32 TakenAdvertisedBenefit = SpellBaseDamageBonusForVictim(spellProto->GetSchoolMask(), victim);
// Pets just add their bonus damage to their spell damage
// note that their spell damage is just gain of their own auras
if (HasUnitTypeMask(UNIT_MASK_GUARDIAN))
DoneAdvertisedBenefit += ((Guardian*)this)->GetBonusDamage();
// Check for table values
float coeff = 0;
SpellBonusEntry const* bonus = sSpellMgr->GetSpellBonusData(spellProto->Id);
if (bonus)
{
if (damagetype == DOT)
{
coeff = bonus->dot_damage;
if (bonus->ap_dot_bonus > 0)
{
WeaponAttackType attType = (spellProto->IsRangedWeaponSpell() && spellProto->DmgClass != SPELL_DAMAGE_CLASS_MELEE) ? RANGED_ATTACK : BASE_ATTACK;
float APbonus = (float) victim->GetTotalAuraModifier(attType == BASE_ATTACK ? SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS : SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
APbonus += GetTotalAttackPowerValue(attType);
DoneTotal += int32(bonus->ap_dot_bonus * stack * ApCoeffMod * APbonus);
}
}
else
{
coeff = bonus->direct_damage;
if (bonus->ap_bonus > 0)
{
WeaponAttackType attType = (spellProto->IsRangedWeaponSpell() && spellProto->DmgClass != SPELL_DAMAGE_CLASS_MELEE) ? RANGED_ATTACK : BASE_ATTACK;
float APbonus = (float) victim->GetTotalAuraModifier(attType == BASE_ATTACK ? SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS : SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
APbonus += GetTotalAttackPowerValue(attType);
DoneTotal += int32(bonus->ap_bonus * stack * ApCoeffMod * APbonus);
}
}
}
// Default calculation
if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
{
if (!bonus || coeff < 0)
{
// Damage Done from spell damage bonus
int32 CastingTime = spellProto->IsChanneled() ? spellProto->GetDuration() : spellProto->CalcCastTime();
// Damage over Time spells bonus calculation
float DotFactor = 1.0f;
if (damagetype == DOT)
{
int32 DotDuration = spellProto->GetDuration();
// 200% limit
if (DotDuration > 0)
{
if (DotDuration > 30000)
DotDuration = 30000;
if (!spellProto->IsChanneled())
DotFactor = DotDuration / 15000.0f;
uint8 x = 0;
for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j)
{
if (spellProto->Effects[j].Effect == SPELL_EFFECT_APPLY_AURA && (
spellProto->Effects[j].ApplyAuraName == SPELL_AURA_PERIODIC_DAMAGE ||
spellProto->Effects[j].ApplyAuraName == SPELL_AURA_PERIODIC_LEECH))
{
x = j;
break;
}
}
int32 DotTicks = 6;
if (spellProto->Effects[x].Amplitude != 0)
DotTicks = DotDuration / spellProto->Effects[x].Amplitude;
if (DotTicks)
{
DoneAdvertisedBenefit /= DotTicks;
TakenAdvertisedBenefit /= DotTicks;
}
}
}
// Distribute Damage over multiple effects, reduce by AoE
CastingTime = GetCastingTimeForBonus(spellProto, damagetype, CastingTime);
// 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j)
{
if (spellProto->Effects[j].Effect == SPELL_EFFECT_HEALTH_LEECH ||
(spellProto->Effects[j].Effect == SPELL_EFFECT_APPLY_AURA && spellProto->Effects[j].ApplyAuraName == SPELL_AURA_PERIODIC_LEECH))
{
CastingTime /= 2;
break;
}
}
if (spellProto->SchoolMask != SPELL_SCHOOL_MASK_NORMAL)
coeff = (CastingTime / 3500.0f) * DotFactor;
else
coeff = DotFactor;
}
float factorMod = CalculateLevelPenalty(spellProto) * stack;
// level penalty still applied on Taken bonus - is it blizzlike?
TakenTotal+= int32(TakenAdvertisedBenefit * factorMod);
if (Player* modOwner = GetSpellModOwner())
{
coeff *= 100.0f;
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_BONUS_MULTIPLIER, coeff);
coeff /= 100.0f;
}
DoneTotal += int32(DoneAdvertisedBenefit * coeff * factorMod);
}
// Some spells don't benefit from done mods
if (spellProto->AttributesEx3 & SPELL_ATTR3_NO_DONE_BONUS)
{
DoneTotal = 0;
DoneTotalMod = 1.0f;
}
// Some spells don't benefit from pct done mods
// maybe should be implemented like SPELL_ATTR3_NO_DONE_BONUS,
// but then it may break spell power coeffs work on spell 31117
if (spellProto->AttributesEx6 & SPELL_ATTR6_NO_DONE_PCT_DAMAGE_MODS)
DoneTotalMod = 1.0f;
float tmpDamage = (int32(pdamage) + DoneTotal) * DoneTotalMod;
// apply spellmod to Done damage (flat and pct)
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
tmpDamage = (tmpDamage + TakenTotal) * TakenTotalMod;
return uint32(std::max(tmpDamage, 0.0f));
}
int32 Unit::SpellBaseDamageBonus(SpellSchoolMask schoolMask)
{
int32 DoneAdvertisedBenefit = 0;
// ..done
AuraEffectList const& mDamageDone = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE);
for (AuraEffectList::const_iterator i = mDamageDone.begin(); i != mDamageDone.end(); ++i)
if (((*i)->GetMiscValue() & schoolMask) != 0 &&
(*i)->GetSpellInfo()->EquippedItemClass == -1 &&
// -1 == any item class (not wand then)
(*i)->GetSpellInfo()->EquippedItemInventoryTypeMask == 0)
// 0 == any inventory type (not wand then)
DoneAdvertisedBenefit += (*i)->GetAmount();
if (GetTypeId() == TYPEID_PLAYER)
{
// Base value
DoneAdvertisedBenefit += ToPlayer()->GetBaseSpellPowerBonus();
// Damage bonus from stats
AuraEffectList const& mDamageDoneOfStatPercent = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT);
for (AuraEffectList::const_iterator i = mDamageDoneOfStatPercent.begin(); i != mDamageDoneOfStatPercent.end(); ++i)
{
if ((*i)->GetMiscValue() & schoolMask)
{
// stat used stored in miscValueB for this aura
Stats usedStat = Stats((*i)->GetMiscValueB());
DoneAdvertisedBenefit += int32(CalculatePctN(GetStat(usedStat), (*i)->GetAmount()));
}
}
// ... and attack power
AuraEffectList const& mDamageDonebyAP = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER);
for (AuraEffectList::const_iterator i =mDamageDonebyAP.begin(); i != mDamageDonebyAP.end(); ++i)
if ((*i)->GetMiscValue() & schoolMask)
DoneAdvertisedBenefit += int32(CalculatePctN(GetTotalAttackPowerValue(BASE_ATTACK), (*i)->GetAmount()));
}
return DoneAdvertisedBenefit > 0 ? DoneAdvertisedBenefit : 0;
}
int32 Unit::SpellBaseDamageBonusForVictim(SpellSchoolMask schoolMask, Unit* victim)
{
uint32 creatureTypeMask = victim->GetCreatureTypeMask();
int32 TakenAdvertisedBenefit = 0;
// ..done (for creature type by mask) in taken
AuraEffectList const& mDamageDoneCreature = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
for (AuraEffectList::const_iterator i = mDamageDoneCreature.begin(); i != mDamageDoneCreature.end(); ++i)
if (creatureTypeMask & uint32((*i)->GetMiscValue()))
TakenAdvertisedBenefit += (*i)->GetAmount();
// ..taken
AuraEffectList const& mDamageTaken = victim->GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
for (AuraEffectList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i)
if (((*i)->GetMiscValue() & schoolMask) != 0)
TakenAdvertisedBenefit += (*i)->GetAmount();
return TakenAdvertisedBenefit > 0 ? TakenAdvertisedBenefit : 0;
}
bool Unit::isSpellCrit(Unit* victim, SpellInfo const* spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType) const
{
//! Mobs can't crit with spells. Player Totems can
//! Fire Elemental (from totem) can too - but this part is a hack and needs more research
if (IS_CREATURE_GUID(GetGUID()) && !(isTotem() && IS_PLAYER_GUID(GetOwnerGUID())) && GetEntry() != 15438)
return false;
// not critting spell
if ((spellProto->AttributesEx2 & SPELL_ATTR2_CANT_CRIT))
return false;
float crit_chance = 0.0f;
switch (spellProto->DmgClass)
{
case SPELL_DAMAGE_CLASS_NONE:
// We need more spells to find a general way (if there is any)
switch (spellProto->Id)
{
case 379: // Earth Shield
case 33778: // Lifebloom Final Bloom
case 64844: // Divine Hymn
break;
default:
return false;
}
case SPELL_DAMAGE_CLASS_MAGIC:
{
if (schoolMask & SPELL_SCHOOL_MASK_NORMAL)
crit_chance = 0.0f;
// For other schools
else if (GetTypeId() == TYPEID_PLAYER)
crit_chance = GetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask));
else
{
crit_chance = (float)m_baseSpellCritChance;
crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
}
// taken
if (victim)
{
if (!spellProto->IsPositive())
{
// Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
crit_chance += victim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask);
// Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE
crit_chance += victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
ApplyResilience(victim, &crit_chance, NULL, false, CR_CRIT_TAKEN_SPELL);
}
// scripted (increase crit chance ... against ... target by x%
AuraEffectList const& mOverrideClassScript = GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
{
if (!((*i)->IsAffectedOnSpell(spellProto)))
continue;
int32 modChance = 0;
switch ((*i)->GetMiscValue())
{
// Shatter
case 911: modChance+= 16;
case 910: modChance+= 17;
case 849: modChance+= 17;
if (!victim->HasAuraState(AURA_STATE_FROZEN, spellProto, this))
break;
crit_chance+=modChance;
break;
case 7917: // Glyph of Shadowburn
if (victim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this))
crit_chance+=(*i)->GetAmount();
break;
case 7997: // Renewed Hope
case 7998:
if (victim->HasAura(6788))
crit_chance+=(*i)->GetAmount();
break;
default:
break;
}
}
// Custom crit by class
switch (spellProto->SpellFamilyName)
{
case SPELLFAMILY_MAGE:
// Glyph of Fire Blast
if (spellProto->SpellFamilyFlags[0] == 0x2 && spellProto->SpellIconID == 12)
if (victim->HasAuraWithMechanic((1<<MECHANIC_STUN) | (1<<MECHANIC_KNOCKOUT)))
if (AuraEffect const* aurEff = GetAuraEffect(56369, EFFECT_0))
crit_chance += aurEff->GetAmount();
break;
case SPELLFAMILY_DRUID:
// Improved Faerie Fire
if (victim->HasAuraState(AURA_STATE_FAERIE_FIRE))
if (AuraEffect const* aurEff = GetDummyAuraEffect(SPELLFAMILY_DRUID, 109, 0))
crit_chance += aurEff->GetAmount();
// cumulative effect - don't break
// Starfire
if (spellProto->SpellFamilyFlags[0] & 0x4 && spellProto->SpellIconID == 1485)
{
// Improved Insect Swarm
if (AuraEffect const* aurEff = GetDummyAuraEffect(SPELLFAMILY_DRUID, 1771, 0))
if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00000002, 0, 0))
crit_chance += aurEff->GetAmount();
break;
}
break;
case SPELLFAMILY_ROGUE:
// Shiv-applied poisons can't crit
if (FindCurrentSpellBySpellId(5938))
crit_chance = 0.0f;
break;
case SPELLFAMILY_PALADIN:
// Flash of light
if (spellProto->SpellFamilyFlags[0] & 0x40000000)
{
// Sacred Shield
if (AuraEffect const* aura = victim->GetAuraEffect(58597, 1, GetGUID()))
crit_chance += aura->GetAmount();
break;
}
// Exorcism
else if (spellProto->Category == 19)
{
if (victim->GetCreatureTypeMask() & CREATURE_TYPEMASK_DEMON_OR_UNDEAD)
return true;
break;
}
break;
case SPELLFAMILY_SHAMAN:
// Lava Burst
if (spellProto->SpellFamilyFlags[1] & 0x00001000)
{
if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, 0x10000000, 0, 0, GetGUID()))
if (victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE) > -100)
return true;
break;
}
break;
}
}
break;
}
case SPELL_DAMAGE_CLASS_MELEE:
if (victim)
{
// Custom crit by class
switch (spellProto->SpellFamilyName)
{
case SPELLFAMILY_DRUID:
// Rend and Tear - bonus crit chance for Ferocious Bite on bleeding targets
if (spellProto->SpellFamilyFlags[0] & 0x00800000
&& spellProto->SpellIconID == 1680
&& victim->HasAuraState(AURA_STATE_BLEEDING))
{
if (AuraEffect const* rendAndTear = GetDummyAuraEffect(SPELLFAMILY_DRUID, 2859, 1))
crit_chance += rendAndTear->GetAmount();
break;
}
break;
case SPELLFAMILY_WARRIOR:
// Victory Rush
if (spellProto->SpellFamilyFlags[1] & 0x100)
{
// Glyph of Victory Rush
if (AuraEffect const* aurEff = GetAuraEffect(58382, 0))
crit_chance += aurEff->GetAmount();
break;
}
break;
}
}
case SPELL_DAMAGE_CLASS_RANGED:
{
if (victim)
{
crit_chance += GetUnitCriticalChance(attackType, victim);
crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
}
break;
}
default:
return false;
}
// percent done
// only players use intelligence for critical chance computations
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance);
crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f;
if (roll_chance_f(crit_chance))
return true;
return false;
}
uint32 Unit::SpellCriticalDamageBonus(SpellInfo const* spellProto, uint32 damage, Unit* victim)
{
// Calculate critical bonus
int32 crit_bonus = damage;
float crit_mod = 0.0f;
switch (spellProto->DmgClass)
{
case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
case SPELL_DAMAGE_CLASS_RANGED:
// TODO: write here full calculation for melee/ranged spells
crit_bonus += damage;
break;
default:
crit_bonus += damage / 2; // for spells is 50%
break;
}
crit_mod += (GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS, spellProto->GetSchoolMask()) - 1.0f) * 100;
if (victim)
crit_mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, victim->GetCreatureTypeMask());
if (crit_bonus != 0)
AddPctF(crit_bonus, crit_mod);
crit_bonus -= damage;
// adds additional damage to crit_bonus (from talents)
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
crit_bonus += damage;
return crit_bonus;
}
uint32 Unit::SpellCriticalHealingBonus(SpellInfo const* spellProto, uint32 damage, Unit* victim)
{
// Calculate critical bonus
int32 crit_bonus;
switch (spellProto->DmgClass)
{
case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
case SPELL_DAMAGE_CLASS_RANGED:
// TODO: write here full calculation for melee/ranged spells
crit_bonus = damage;
break;
default:
crit_bonus = damage / 2; // for spells is 50%
break;
}
if (victim)
{
uint32 creatureTypeMask = victim->GetCreatureTypeMask();
crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
}
if (crit_bonus > 0)
damage += crit_bonus;
damage = int32(float(damage) * GetTotalAuraMultiplier(SPELL_AURA_MOD_CRITICAL_HEALING_AMOUNT));
return damage;
}
uint32 Unit::SpellHealingBonus(Unit* victim, SpellInfo const* spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack)
{
// For totems get healing bonus from owner (statue isn't totem in fact)
if (GetTypeId() == TYPEID_UNIT && ToCreature()->isTotem())
if (Unit* owner = GetOwner())
return owner->SpellHealingBonus(victim, spellProto, healamount, damagetype, stack);
// no bonus for heal potions/bandages
if (spellProto->SpellFamilyName == SPELLFAMILY_POTION)
return healamount;
// Healing Done
// Taken/Done total percent damage auras
float DoneTotalMod = 1.0f;
float TakenTotalMod = 1.0f;
int32 DoneTotal = 0;
int32 TakenTotal = 0;
// Healing done percent
AuraEffectList const& mHealingDonePct = GetAuraEffectsByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
for (AuraEffectList::const_iterator i = mHealingDonePct.begin(); i != mHealingDonePct.end(); ++i)
AddPctN(DoneTotalMod, (*i)->GetAmount());
// done scripted mod (take it from owner)
Unit* owner = GetOwner() ? GetOwner() : this;
AuraEffectList const& mOverrideClassScript= owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
{
if (!(*i)->IsAffectedOnSpell(spellProto))
continue;
switch ((*i)->GetMiscValue())
{
case 4415: // Increased Rejuvenation Healing
case 4953:
case 3736: // Hateful Totem of the Third Wind / Increased Lesser Healing Wave / LK Arena (4/5/6) Totem of the Third Wind / Savage Totem of the Third Wind
DoneTotal += (*i)->GetAmount();
break;
case 21: // Test of Faith
case 6935:
case 6918:
if (victim->HealthBelowPct(50))
AddPctN(DoneTotalMod, (*i)->GetAmount());
break;
case 7798: // Glyph of Regrowth
{
if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, 0x40, 0, 0))
AddPctN(DoneTotalMod, (*i)->GetAmount());
break;
}
case 8477: // Nourish Heal Boost
{
int32 stepPercent = (*i)->GetAmount();
int32 modPercent = 0;
AuraApplicationMap const& victimAuras = victim->GetAppliedAuras();
for (AuraApplicationMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
{
Aura const* aura = itr->second->GetBase();
if (aura->GetCasterGUID() != GetGUID())
continue;
SpellInfo const* m_spell = aura->GetSpellInfo();
if (m_spell->SpellFamilyName != SPELLFAMILY_DRUID ||
!(m_spell->SpellFamilyFlags[1] & 0x00000010 || m_spell->SpellFamilyFlags[0] & 0x50))
continue;
modPercent += stepPercent * aura->GetStackAmount();
}
AddPctN(DoneTotalMod, modPercent);
break;
}
case 7871: // Glyph of Lesser Healing Wave
{
if (victim->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 0, 0x00000400, 0, GetGUID()))
AddPctN(DoneTotalMod, (*i)->GetAmount());
break;
}
default:
break;
}
}
// Taken/Done fixed damage bonus auras
int32 DoneAdvertisedBenefit = SpellBaseHealingBonus(spellProto->GetSchoolMask());
int32 TakenAdvertisedBenefit = SpellBaseHealingBonusForVictim(spellProto->GetSchoolMask(), victim);
bool scripted = false;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
switch (spellProto->Effects[i].ApplyAuraName)
{
// These auras do not use healing coeff
case SPELL_AURA_PERIODIC_LEECH:
case SPELL_AURA_PERIODIC_HEALTH_FUNNEL:
scripted = true;
break;
}
if (spellProto->Effects[i].Effect == SPELL_EFFECT_HEALTH_LEECH)
scripted = true;
}
// Check for table values
SpellBonusEntry const* bonus = !scripted ? sSpellMgr->GetSpellBonusData(spellProto->Id) : NULL;
float coeff = 0;
float factorMod = 1.0f;
if (bonus)
{
if (damagetype == DOT)
{
coeff = bonus->dot_damage;
if (bonus->ap_dot_bonus > 0)
DoneTotal += int32(bonus->ap_dot_bonus * stack * GetTotalAttackPowerValue(
(spellProto->IsRangedWeaponSpell() && spellProto->DmgClass !=SPELL_DAMAGE_CLASS_MELEE)? RANGED_ATTACK : BASE_ATTACK));
}
else
{
coeff = bonus->direct_damage;
if (bonus->ap_bonus > 0)
DoneTotal += int32(bonus->ap_bonus * stack * GetTotalAttackPowerValue(
(spellProto->IsRangedWeaponSpell() && spellProto->DmgClass !=SPELL_DAMAGE_CLASS_MELEE)? RANGED_ATTACK : BASE_ATTACK));
}
}
else // scripted bonus
{
// Gift of the Naaru
if (spellProto->SpellFamilyFlags[2] & 0x80000000 && spellProto->SpellIconID == 329)
{
scripted = true;
int32 apBonus = int32(std::max(GetTotalAttackPowerValue(BASE_ATTACK), GetTotalAttackPowerValue(RANGED_ATTACK)));
if (apBonus > DoneAdvertisedBenefit)
DoneTotal += int32(apBonus * 0.22f); // 22% of AP per tick
else
DoneTotal += int32(DoneAdvertisedBenefit * 0.377f); // 37.7% of BH per tick
}
// Earthliving - 0.45% of normal hot coeff
else if (spellProto->SpellFamilyName == SPELLFAMILY_SHAMAN && spellProto->SpellFamilyFlags[1] & 0x80000)
factorMod *= 0.45f;
// Already set to scripted? so not uses healing bonus coefficient
// No heal coeff for SPELL_DAMAGE_CLASS_NONE class spells by default
else if (scripted || spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE)
{
scripted = true;
coeff = 0.0f;
}
}
// Default calculation
if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
{
if ((!bonus && !scripted) || coeff < 0)
{
// Damage Done from spell damage bonus
int32 CastingTime = !spellProto->IsChanneled() ? spellProto->CalcCastTime() : spellProto->GetDuration();
// Damage over Time spells bonus calculation
float DotFactor = 1.0f;
if (damagetype == DOT)
{
int32 DotDuration = spellProto->GetDuration();
// 200% limit
if (DotDuration > 0)
{
if (DotDuration > 30000) DotDuration = 30000;
if (!spellProto->IsChanneled()) DotFactor = DotDuration / 15000.0f;
uint32 x = 0;
for (uint8 j = 0; j < MAX_SPELL_EFFECTS; j++)
{
if (spellProto->Effects[j].Effect == SPELL_EFFECT_APPLY_AURA && (
spellProto->Effects[j].ApplyAuraName == SPELL_AURA_PERIODIC_DAMAGE ||
spellProto->Effects[j].ApplyAuraName == SPELL_AURA_PERIODIC_LEECH))
{
x = j;
break;
}
}
int32 DotTicks = 6;
if (spellProto->Effects[x].Amplitude != 0)
DotTicks = DotDuration / spellProto->Effects[x].Amplitude;
if (DotTicks)
{
DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
}
}
}
// Distribute Damage over multiple effects, reduce by AoE
CastingTime = GetCastingTimeForBonus(spellProto, damagetype, CastingTime);
// 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j)
{
if (spellProto->Effects[j].Effect == SPELL_EFFECT_HEALTH_LEECH ||
(spellProto->Effects[j].Effect == SPELL_EFFECT_APPLY_AURA && spellProto->Effects[j].ApplyAuraName == SPELL_AURA_PERIODIC_LEECH))
{
CastingTime /= 2;
break;
}
}
// As wowwiki says: C = (Cast Time / 3.5) * 1.88 (for healing spells)
coeff = (CastingTime / 3500.0f) * DotFactor * 1.88f;
}
factorMod *= CalculateLevelPenalty(spellProto) * stack;
// level penalty still applied on Taken bonus - is it blizzlike?
TakenTotal += int32(TakenAdvertisedBenefit * factorMod);
if (Player* modOwner = GetSpellModOwner())
{
coeff *= 100.0f;
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_BONUS_MULTIPLIER, coeff);
coeff /= 100.0f;
}
DoneTotal += int32(DoneAdvertisedBenefit * coeff * factorMod);
}
// use float as more appropriate for negative values and percent applying
float heal = (int32(healamount) + DoneTotal) * DoneTotalMod;
// apply spellmod to Done amount
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal);
// Nourish cast
if (spellProto->SpellFamilyName == SPELLFAMILY_DRUID && spellProto->SpellFamilyFlags[1] & 0x2000000)
{
// Rejuvenation, Regrowth, Lifebloom, or Wild Growth
if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, 0x50, 0x4000010, 0))
// increase healing by 20%
TakenTotalMod *= 1.2f;
}
// Taken mods
// Tenacity increase healing % taken
if (AuraEffect const* Tenacity = victim->GetAuraEffect(58549, 0))
AddPctN(TakenTotalMod, Tenacity->GetAmount());
// Healing taken percent
float minval = (float)victim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
if (minval)
AddPctF(TakenTotalMod, minval);
float maxval = (float)victim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
if (maxval)
AddPctF(TakenTotalMod, maxval);
if (damagetype == DOT)
{
// Healing over time taken percent
float minval_hot = (float)victim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HOT_PCT);
if (minval_hot)
AddPctF(TakenTotalMod, minval_hot);
float maxval_hot = (float)victim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HOT_PCT);
if (maxval_hot)
AddPctF(TakenTotalMod, maxval_hot);
}
AuraEffectList const& mHealingGet= victim->GetAuraEffectsByType(SPELL_AURA_MOD_HEALING_RECEIVED);
for (AuraEffectList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i)
if (GetGUID() == (*i)->GetCasterGUID() && (*i)->IsAffectedOnSpell(spellProto))
AddPctN(TakenTotalMod, (*i)->GetAmount());
heal = (int32(heal) + TakenTotal) * TakenTotalMod;
return uint32(std::max(heal, 0.0f));
}
int32 Unit::SpellBaseHealingBonus(SpellSchoolMask schoolMask)
{
int32 AdvertisedBenefit = 0;
AuraEffectList const& mHealingDone = GetAuraEffectsByType(SPELL_AURA_MOD_HEALING_DONE);
for (AuraEffectList::const_iterator i = mHealingDone.begin(); i != mHealingDone.end(); ++i)
if (!(*i)->GetMiscValue() || ((*i)->GetMiscValue() & schoolMask) != 0)
AdvertisedBenefit += (*i)->GetAmount();
// Healing bonus of spirit, intellect and strength
if (GetTypeId() == TYPEID_PLAYER)
{
// Base value
AdvertisedBenefit += ToPlayer()->GetBaseSpellPowerBonus();
// Healing bonus from stats
AuraEffectList const& mHealingDoneOfStatPercent = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT);
for (AuraEffectList::const_iterator i = mHealingDoneOfStatPercent.begin(); i != mHealingDoneOfStatPercent.end(); ++i)
{
// stat used dependent from misc value (stat index)
Stats usedStat = Stats((*i)->GetSpellInfo()->Effects[(*i)->GetEffIndex()].MiscValue);
AdvertisedBenefit += int32(CalculatePctN(GetStat(usedStat), (*i)->GetAmount()));
}
// ... and attack power
AuraEffectList const& mHealingDonebyAP = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER);
for (AuraEffectList::const_iterator i = mHealingDonebyAP.begin(); i != mHealingDonebyAP.end(); ++i)
if ((*i)->GetMiscValue() & schoolMask)
AdvertisedBenefit += int32(CalculatePctN(GetTotalAttackPowerValue(BASE_ATTACK), (*i)->GetAmount()));
}
return AdvertisedBenefit;
}
int32 Unit::SpellBaseHealingBonusForVictim(SpellSchoolMask schoolMask, Unit* victim)
{
int32 AdvertisedBenefit = 0;
AuraEffectList const& mDamageTaken = victim->GetAuraEffectsByType(SPELL_AURA_MOD_HEALING);
for (AuraEffectList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i)
if (((*i)->GetMiscValue() & schoolMask) != 0)
AdvertisedBenefit += (*i)->GetAmount();
return AdvertisedBenefit;
}
bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask)
{
// If m_immuneToSchool type contain this school type, IMMUNE damage.
SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
if (itr->type & shoolMask)
return true;
// If m_immuneToDamage type contain magic, IMMUNE damage.
SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
if (itr->type & shoolMask)
return true;
return false;
}
bool Unit::IsImmunedToDamage(SpellInfo const* spellInfo)
{
if (spellInfo->Attributes & SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY)
return false;
uint32 shoolMask = spellInfo->GetSchoolMask();
if (spellInfo->Id != 42292 && spellInfo->Id !=59752)
{
// If m_immuneToSchool type contain this school type, IMMUNE damage.
SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
if (itr->type & shoolMask && !spellInfo->CanPierceImmuneAura(sSpellMgr->GetSpellInfo(itr->spellId)))
return true;
}
// If m_immuneToDamage type contain magic, IMMUNE damage.
SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
if (itr->type & shoolMask)
return true;
return false;
}
bool Unit::IsImmunedToSpell(SpellInfo const* spellInfo)
{
if (!spellInfo)
return false;
// Single spell immunity.
SpellImmuneList const& idList = m_spellImmune[IMMUNITY_ID];
for (SpellImmuneList::const_iterator itr = idList.begin(); itr != idList.end(); ++itr)
if (itr->type == spellInfo->Id)
return true;
if (spellInfo->Attributes & SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY)
return false;
if (spellInfo->Dispel)
{
SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL];
for (SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr)
if (itr->type == spellInfo->Dispel)
return true;
}
if (spellInfo->Mechanic)
{
SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
if (itr->type == spellInfo->Mechanic)
return true;
}
for (int i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
// State/effect immunities applied by aura expect full spell immunity
// Ignore effects with mechanic, they are supposed to be checked separately
if (!spellInfo->Effects[i].Mechanic)
if (IsImmunedToSpellEffect(spellInfo, i))
return true;
}
if (spellInfo->Id != 42292 && spellInfo->Id !=59752)
{
SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
{
SpellInfo const* immuneSpellInfo = sSpellMgr->GetSpellInfo(itr->spellId);
if ((itr->type & spellInfo->GetSchoolMask())
&& !(immuneSpellInfo && immuneSpellInfo->IsPositive() && spellInfo->IsPositive())
&& !spellInfo->CanPierceImmuneAura(immuneSpellInfo))
return true;
}
}
return false;
}
bool Unit::IsImmunedToSpellEffect(SpellInfo const* spellInfo, uint32 index) const
{
if (!spellInfo)
return false;
// If m_immuneToEffect type contain this effect type, IMMUNE effect.
uint32 effect = spellInfo->Effects[index].Effect;
SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT];
for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr)
if (itr->type == effect)
return true;
if (uint32 mechanic = spellInfo->Effects[index].Mechanic)
{
SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
if (itr->type == mechanic)
return true;
}
if (uint32 aura = spellInfo->Effects[index].ApplyAuraName)
{
SpellImmuneList const& list = m_spellImmune[IMMUNITY_STATE];
for (SpellImmuneList::const_iterator itr = list.begin(); itr != list.end(); ++itr)
if (itr->type == aura)
return true;
// Check for immune to application of harmful magical effects
AuraEffectList const& immuneAuraApply = GetAuraEffectsByType(SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL);
for (AuraEffectList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
if (spellInfo->Dispel == DISPEL_MAGIC && // Magic debuff
((*iter)->GetMiscValue() & spellInfo->GetSchoolMask()) && // Check school
!spellInfo->IsPositiveEffect(index)) // Harmful
return true;
}
return false;
}
void Unit::MeleeDamageBonus(Unit* victim, uint32 *pdamage, WeaponAttackType attType, SpellInfo const* spellProto)
{
if (!victim)
return;
if (*pdamage == 0)
return;
uint32 creatureTypeMask = victim->GetCreatureTypeMask();
// Taken/Done fixed damage bonus auras
int32 DoneFlatBenefit = 0;
int32 TakenFlatBenefit = 0;
// ..done (for creature type by mask) in taken
AuraEffectList const& mDamageDoneCreature = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
for (AuraEffectList::const_iterator i = mDamageDoneCreature.begin(); i != mDamageDoneCreature.end(); ++i)
if (creatureTypeMask & uint32((*i)->GetMiscValue()))
DoneFlatBenefit += (*i)->GetAmount();
// ..done
// SPELL_AURA_MOD_DAMAGE_DONE included in weapon damage
// ..done (base at attack power for marked target and base at attack power for creature type)
int32 APbonus = 0;
if (attType == RANGED_ATTACK)
{
APbonus += victim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
// ..done (base at attack power and creature type)
AuraEffectList const& mCreatureAttackPower = GetAuraEffectsByType(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS);
for (AuraEffectList::const_iterator i = mCreatureAttackPower.begin(); i != mCreatureAttackPower.end(); ++i)
if (creatureTypeMask & uint32((*i)->GetMiscValue()))
APbonus += (*i)->GetAmount();
}
else
{
APbonus += victim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS);
// ..done (base at attack power and creature type)
AuraEffectList const& mCreatureAttackPower = GetAuraEffectsByType(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS);
for (AuraEffectList::const_iterator i = mCreatureAttackPower.begin(); i != mCreatureAttackPower.end(); ++i)
if (creatureTypeMask & uint32((*i)->GetMiscValue()))
APbonus += (*i)->GetAmount();
}
if (APbonus != 0) // Can be negative
{
bool normalized = false;
if (spellProto)
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (spellProto->Effects[i].Effect == SPELL_EFFECT_NORMALIZED_WEAPON_DMG)
{
normalized = true;
break;
}
DoneFlatBenefit += int32(APbonus/14.0f * GetAPMultiplier(attType, normalized));
}
// ..taken
AuraEffectList const& mDamageTaken = victim->GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
for (AuraEffectList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i)
if ((*i)->GetMiscValue() & GetMeleeDamageSchoolMask())
TakenFlatBenefit += (*i)->GetAmount();
if (attType != RANGED_ATTACK)
TakenFlatBenefit += victim->GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN);
else
TakenFlatBenefit += victim->GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN);
// Done/Taken total percent damage auras
float DoneTotalMod = 1.0f;
float TakenTotalMod = 1.0f;
// ..done
AuraEffectList const& mModDamagePercentDone = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
for (AuraEffectList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
{
if (spellProto)
{
if ((*i)->GetMiscValue() & spellProto->GetSchoolMask() && !(spellProto->GetSchoolMask() & SPELL_SCHOOL_MASK_NORMAL))
{
if ((*i)->GetSpellInfo()->EquippedItemClass == -1)
AddPctN(DoneTotalMod, (*i)->GetAmount());
else if (!((*i)->GetSpellInfo()->AttributesEx5 & SPELL_ATTR5_SPECIAL_ITEM_CLASS_CHECK) && ((*i)->GetSpellInfo()->EquippedItemSubClassMask == 0))
AddPctN(DoneTotalMod, (*i)->GetAmount());
else if (ToPlayer() && ToPlayer()->HasItemFitToSpellRequirements((*i)->GetSpellInfo()))
AddPctN(DoneTotalMod, (*i)->GetAmount());
}
}
}
AuraEffectList const& mDamageDoneVersus = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
for (AuraEffectList::const_iterator i = mDamageDoneVersus.begin(); i != mDamageDoneVersus.end(); ++i)
if (creatureTypeMask & uint32((*i)->GetMiscValue()))
AddPctN(DoneTotalMod, (*i)->GetAmount());
// bonus against aurastate
AuraEffectList const& mDamageDoneVersusAurastate = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS_AURASTATE);
for (AuraEffectList::const_iterator i = mDamageDoneVersusAurastate.begin(); i != mDamageDoneVersusAurastate.end(); ++i)
if (victim->HasAuraState(AuraStateType((*i)->GetMiscValue())))
AddPctN(DoneTotalMod, (*i)->GetAmount());
// done scripted mod (take it from owner)
Unit* owner = GetOwner() ? GetOwner() : this;
AuraEffectList const& mOverrideClassScript = owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
{
if (!(*i)->IsAffectedOnSpell(spellProto))
continue;
switch ((*i)->GetMiscValue())
{
// Tundra Stalker
// Merciless Combat
case 7277:
{
// Merciless Combat
if ((*i)->GetSpellInfo()->SpellIconID == 2656)
{
if (!victim->HealthAbovePct(35))
AddPctN(DoneTotalMod, (*i)->GetAmount());
}
// Tundra Stalker
else
{
// Frost Fever (target debuff)
if (victim->HasAura(55095))
AddPctN(DoneTotalMod, (*i)->GetAmount());
}
break;
}
// Rage of Rivendare
case 7293:
{
if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0, 0x02000000, 0))
AddPctF(DoneTotalMod, (*i)->GetSpellInfo()->GetRank() * 2.0f);
break;
}
// Marked for Death
case 7598:
case 7599:
case 7600:
case 7601:
case 7602:
{
if (victim->GetAuraEffect(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, 0x400, 0, 0))
AddPctN(DoneTotalMod, (*i)->GetAmount());
break;
}
// Dirty Deeds
case 6427:
case 6428:
{
if (victim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this))
{
// effect 0 have expected value but in negative state
int32 bonus = -(*i)->GetBase()->GetEffect(0)->GetAmount();
AddPctN(DoneTotalMod, bonus);
}
break;
}
}
}
// Custom scripted damage
if (spellProto)
switch (spellProto->SpellFamilyName)
{
case SPELLFAMILY_DEATHKNIGHT:
// Glacier Rot
if (spellProto->SpellFamilyFlags[0] & 0x2 || spellProto->SpellFamilyFlags[1] & 0x6)
if (AuraEffect* aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 196, 0))
if (victim->GetDiseasesByCaster(owner->GetGUID()) > 0)
AddPctN(DoneTotalMod, aurEff->GetAmount());
break;
}
// ..taken
TakenTotalMod *= victim->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN, GetMeleeDamageSchoolMask());
// From caster spells
AuraEffectList const& mOwnerTaken = victim->GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_FROM_CASTER);
for (AuraEffectList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i)
if ((*i)->GetCasterGUID() == GetGUID() && (*i)->IsAffectedOnSpell(spellProto))
AddPctN(TakenTotalMod, (*i)->GetAmount());
// .. taken pct (special attacks)
if (spellProto)
{
// Mod damage from spell mechanic
uint32 mechanicMask = spellProto->GetAllEffectsMechanicMask();
// Shred, Maul - "Effects which increase Bleed damage also increase Shred damage"
if (spellProto->SpellFamilyName == SPELLFAMILY_DRUID && spellProto->SpellFamilyFlags[0] & 0x00008800)
mechanicMask |= (1<<MECHANIC_BLEED);
if (mechanicMask)
{
AuraEffectList const& mDamageDoneMechanic = victim->GetAuraEffectsByType(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT);
for (AuraEffectList::const_iterator i = mDamageDoneMechanic.begin(); i != mDamageDoneMechanic.end(); ++i)
if (mechanicMask & uint32(1<<((*i)->GetMiscValue())))
AddPctN(TakenTotalMod, (*i)->GetAmount());
}
}
// .. taken pct: dummy auras
AuraEffectList const& mDummyAuras = victim->GetAuraEffectsByType(SPELL_AURA_DUMMY);
for (AuraEffectList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
{
switch ((*i)->GetSpellInfo()->SpellIconID)
{
// Cheat Death
case 2109:
if ((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL)
{
if (victim->GetTypeId() != TYPEID_PLAYER)
continue;
float mod = victim->ToPlayer()->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE) * (-8.0f);
AddPctF(TakenTotalMod, std::max(mod, float((*i)->GetAmount())));
}
break;
}
}
// .. taken pct: class scripts
/*AuraEffectList const& mclassScritAuras = GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
for (AuraEffectList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i)
{
switch ((*i)->GetMiscValue())
{
}
}*/
if (attType != RANGED_ATTACK)
{
AuraEffectList const& mModMeleeDamageTakenPercent = victim->GetAuraEffectsByType(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT);
for (AuraEffectList::const_iterator i = mModMeleeDamageTakenPercent.begin(); i != mModMeleeDamageTakenPercent.end(); ++i)
AddPctN(TakenTotalMod, (*i)->GetAmount());
}
else
{
AuraEffectList const& mModRangedDamageTakenPercent = victim->GetAuraEffectsByType(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT);
for (AuraEffectList::const_iterator i = mModRangedDamageTakenPercent.begin(); i != mModRangedDamageTakenPercent.end(); ++i)
AddPctN(TakenTotalMod, (*i)->GetAmount());
}
float tmpDamage = float(int32(*pdamage) + DoneFlatBenefit) * DoneTotalMod;
// apply spellmod to Done damage
if (spellProto)
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage);
tmpDamage = (tmpDamage + TakenFlatBenefit) * TakenTotalMod;
// bonus result can be negative
*pdamage = uint32(std::max(tmpDamage, 0.0f));
}
void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply)
{
if (apply)
{
for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next)
{
next = itr; ++next;
if (itr->type == type)
{
m_spellImmune[op].erase(itr);
next = m_spellImmune[op].begin();
}
}
SpellImmune Immune;
Immune.spellId = spellId;
Immune.type = type;
m_spellImmune[op].push_back(Immune);
}
else
{
for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr)
{
if (itr->spellId == spellId && itr->type == type)
{
m_spellImmune[op].erase(itr);
break;
}
}
}
}
void Unit::ApplySpellDispelImmunity(const SpellInfo* spellProto, DispelType type, bool apply)
{
ApplySpellImmune(spellProto->Id, IMMUNITY_DISPEL, type, apply);
if (apply && spellProto->AttributesEx & SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY)
{
// Create dispel mask by dispel type
uint32 dispelMask = SpellInfo::GetDispelMask(type);
// Dispel all existing auras vs current dispel type
AuraApplicationMap& auras = GetAppliedAuras();
for (AuraApplicationMap::iterator itr = auras.begin(); itr != auras.end();)
{
SpellInfo const* spell = itr->second->GetBase()->GetSpellInfo();
if (spell->GetDispelMask() & dispelMask)
{
// Dispel aura
RemoveAura(itr);
}
else
++itr;
}
}
}
float Unit::GetWeaponProcChance() const
{
// normalized proc chance for weapon attack speed
// (odd formula...)
if (isAttackReady(BASE_ATTACK))
return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f);
else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
return (GetAttackTime(OFF_ATTACK) * 1.6f / 1000.0f);
return 0;
}
float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM, const SpellInfo* spellProto) const
{
// proc per minute chance calculation
if (PPM <= 0) return 0.0f;
// Apply chance modifer aura
if (spellProto)
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_PROC_PER_MINUTE, PPM);
return floor((WeaponSpeed * PPM) / 600.0f); // result is chance in percents (probability = Speed_in_sec * (PPM / 60))
}
void Unit::Mount(uint32 mount, uint32 VehicleId, uint32 creatureEntry)
{
if (mount)
SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount);
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT);
if (Player* player = ToPlayer())
{
// mount as a vehicle
if (VehicleId)
{
if (CreateVehicleKit(VehicleId, creatureEntry))
{
GetVehicleKit()->Reset();
// Send others that we now have a vehicle
WorldPacket data(SMSG_PLAYER_VEHICLE_DATA, GetPackGUID().size()+4);
data.appendPackGUID(GetGUID());
data << uint32(VehicleId);
SendMessageToSet(&data, true);
data.Initialize(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
player->GetSession()->SendPacket(&data);
// mounts can also have accessories
GetVehicleKit()->InstallAllAccessories(false);
}
}
// unsummon pet
Pet* pet = player->GetPet();
if (pet)
{
Battleground* bg = ToPlayer()->GetBattleground();
// don't unsummon pet in arena but SetFlag UNIT_FLAG_STUNNED to disable pet's interface
if (bg && bg->isArena())
pet->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
else
player->UnsummonPetTemporaryIfAny();
}
WorldPacket data(SMSG_MOVE_SET_COLLISION_HGT, GetPackGUID().size() + 4 + 4);
data.append(GetPackGUID());
data << uint32(sWorld->GetGameTime()); // Packet counter
data << player->GetCollisionHeight(true);
player->GetSession()->SendPacket(&data);
}
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNT);
}
void Unit::Unmount()
{
if (!IsMounted())
return;
SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT);
if (Player* thisPlayer = ToPlayer())
{
WorldPacket data(SMSG_MOVE_SET_COLLISION_HGT, GetPackGUID().size() + 4 + 4);
data.append(GetPackGUID());
data << uint32(sWorld->GetGameTime()); // Packet counter
data << thisPlayer->GetCollisionHeight(false);
thisPlayer->GetSession()->SendPacket(&data);
}
WorldPacket data(SMSG_DISMOUNT, 8);
data.appendPackGUID(GetGUID());
SendMessageToSet(&data, true);
// unmount as a vehicle
if (GetTypeId() == TYPEID_PLAYER && GetVehicleKit())
{
// Send other players that we are no longer a vehicle
data.Initialize(SMSG_PLAYER_VEHICLE_DATA, 8+4);
data.appendPackGUID(GetGUID());
data << uint32(0);
ToPlayer()->SendMessageToSet(&data, true);
// Remove vehicle from player
RemoveVehicleKit();
}
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED);
// only resummon old pet if the player is already added to a map
// this prevents adding a pet to a not created map which would otherwise cause a crash
// (it could probably happen when logging in after a previous crash)
if (Player* player = ToPlayer())
{
if (Pet* pPet = player->GetPet())
{
if (pPet->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED) && !pPet->HasUnitState(UNIT_STAT_STUNNED))
pPet->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
}
else
player->ResummonPetTemporaryUnSummonedIfAny();
}
}
void Unit::SetInCombatWith(Unit* enemy)
{
Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf();
if (eOwner->IsPvP())
{
SetInCombatState(true, enemy);
return;
}
// check for duel
if (eOwner->GetTypeId() == TYPEID_PLAYER && eOwner->ToPlayer()->duel)
{
Unit const* myOwner = GetCharmerOrOwnerOrSelf();
if (((Player const*)eOwner)->duel->opponent == myOwner)
{
SetInCombatState(true, enemy);
return;
}
}
SetInCombatState(false, enemy);
}
void Unit::CombatStart(Unit* target, bool initialAggro)
{
if (initialAggro)
{
if (!target->IsStandState())
target->SetStandState(UNIT_STAND_STATE_STAND);
if (!target->isInCombat() && target->GetTypeId() != TYPEID_PLAYER
&& !target->ToCreature()->HasReactState(REACT_PASSIVE) && target->ToCreature()->IsAIEnabled)
{
target->ToCreature()->AI()->AttackStart(this);
}
SetInCombatWith(target);
target->SetInCombatWith(this);
}
Unit* who = target->GetCharmerOrOwnerOrSelf();
if (who->GetTypeId() == TYPEID_PLAYER)
SetContestedPvP(who->ToPlayer());
Player* me = GetCharmerOrOwnerPlayerOrPlayerItself();
if (me && who->IsPvP()
&& (who->GetTypeId() != TYPEID_PLAYER
|| !me->duel || me->duel->opponent != who))
{
me->UpdatePvP(true);
me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
}
}
void Unit::SetInCombatState(bool PvP, Unit* enemy)
{
// only alive units can be in combat
if (!isAlive())
return;
if (PvP)
m_CombatTimer = 5000;
if (isInCombat() || HasUnitState(UNIT_STAT_EVADE))
return;
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
if (Creature* creature = ToCreature())
{
// Set home position at place of engaging combat for escorted creatures
if ((IsAIEnabled && creature->AI()->IsEscorted()) ||
GetMotionMaster()->GetCurrentMovementGeneratorType() == WAYPOINT_MOTION_TYPE ||
GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE)
creature->SetHomePosition(GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
if (enemy)
{
if (IsAIEnabled)
{
creature->AI()->EnterCombat(enemy);
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE); // always remove Out of Combat Non Attackable flag if we enter combat and AI is enabled
}
if (creature->GetFormation())
creature->GetFormation()->MemberAttackStart(creature, enemy);
}
if (isPet())
{
UpdateSpeed(MOVE_RUN, true);
UpdateSpeed(MOVE_SWIM, true);
UpdateSpeed(MOVE_FLIGHT, true);
}
if (!(creature->GetCreatureInfo()->type_flags & CREATURE_TYPEFLAGS_MOUNTED_COMBAT))
Unmount();
}
for (Unit::ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
{
(*itr)->SetInCombatState(PvP, enemy);
(*itr)->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
}
}
void Unit::ClearInCombat()
{
m_CombatTimer = 0;
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
// Player's state will be cleared in Player::UpdateContestedPvP
if (Creature* creature = ToCreature())
{
if (creature->GetCreatureInfo() && creature->GetCreatureInfo()->unit_flags & UNIT_FLAG_OOC_NOT_ATTACKABLE)
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE); // re-apply Out of Combat Non Attackable flag if we leave combat, can be overriden in scripts in EnterEvadeMode()
ClearUnitState(UNIT_STAT_ATTACK_PLAYER);
if (HasFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TAPPED))
SetUInt32Value(UNIT_DYNAMIC_FLAGS, creature->GetCreatureInfo()->dynamicflags);
if (creature->isPet())
{
if (Unit* owner = GetOwner())
for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i)
if (owner->GetSpeedRate(UnitMoveType(i)) > GetSpeedRate(UnitMoveType(i)))
SetSpeed(UnitMoveType(i), owner->GetSpeedRate(UnitMoveType(i)), true);
}
else if (!isCharmed())
return;
}
else
ToPlayer()->UpdatePotionCooldown();
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
}
bool Unit::isTargetableForAttack(bool checkFakeDeath) const
{
if (!isAlive())
return false;
if (HasFlag(UNIT_FIELD_FLAGS,
UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE))
return false;
if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->isGameMaster())
return false;
return !HasUnitState(UNIT_STAT_UNATTACKABLE) && (!checkFakeDeath || !HasUnitState(UNIT_STAT_DIED));
}
bool Unit::IsValidAttackTarget(Unit const* target) const
{
return _IsValidAttackTarget(target, NULL);
}
// function based on function Unit::CanAttack from 13850 client
bool Unit::_IsValidAttackTarget(Unit const* target, SpellInfo const* bySpell) const
{
ASSERT(target);
// can't attack self
if (this == target)
return false;
// can't attack unattackable units or GMs
if (target->HasUnitState(UNIT_STAT_UNATTACKABLE)
|| (target->GetTypeId() == TYPEID_PLAYER && target->ToPlayer()->isGameMaster()))
return false;
// can't attack own vehicle or passenger
if (m_vehicle)
if (IsOnVehicle(target) || m_vehicle->GetBase()->IsOnVehicle(target))
return false;
// can't attack invisible (ignore stealth for aoe spells)
if ((!bySpell || !(bySpell->AttributesEx6 & SPELL_ATTR6_CAN_TARGET_INVISIBLE)) && !canSeeOrDetect(target, bySpell && bySpell->IsAOE()))
return false;
// can't attack dead
if ((!bySpell || !bySpell->IsAllowingDeadTarget()) && !target->isAlive())
return false;
// can't attack untargetable
if ((!bySpell || !(bySpell->AttributesEx6 & SPELL_ATTR6_CAN_TARGET_UNTARGETABLE))
&& target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE))
return false;
if (Player const* playerAttacker = ToPlayer())
{
if (playerAttacker->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_UNK19))
return false;
}
// check flags
if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_TAXI_FLIGHT | UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_UNK_16)
|| (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PASSIVE))
|| (!target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PASSIVE))
|| (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE))
|| (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE)))
return false;
// CvC case - can attack each other only when one of them is hostile
if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && !target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE))
return GetReactionTo(target) <= REP_HOSTILE || target->GetReactionTo(this) <= REP_HOSTILE;
// PvP, PvC, CvP case
// can't attack friendly targets
if ( GetReactionTo(target) > REP_NEUTRAL
|| target->GetReactionTo(this) > REP_NEUTRAL)
return false;
Creature const* creatureAttacker = ToCreature();
if (creatureAttacker && creatureAttacker->GetCreatureInfo()->type_flags & CREATURE_TYPEFLAGS_UNK26)
return false;
Player const* playerAffectingAttacker = HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) ? GetAffectingPlayer() : NULL;
Player const* playerAffectingTarget = target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) ? target->GetAffectingPlayer() : NULL;
// check duel - before sanctuary checks
if (playerAffectingAttacker && playerAffectingTarget)
if (playerAffectingAttacker->duel && playerAffectingAttacker->duel->opponent == playerAffectingTarget && playerAffectingAttacker->duel->startTime != 0)
return true;
// PvP case - can't attack when attacker or target are in sanctuary
// however, 13850 client doesn't allow to attack when one of the unit's has sanctuary flag and is pvp
if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE)
&& ((target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_SANCTUARY) || (GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_SANCTUARY)))
return false;
// additional checks - only PvP case
if (playerAffectingAttacker && playerAffectingTarget)
{
if (target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_PVP)
return true;
if (GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP
&& target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP)
return true;
return (GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_UNK1)
|| (target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_UNK1);
}
return true;
}
bool Unit::IsValidAssistTarget(Unit const* target) const
{
return _IsValidAssistTarget(target, NULL);
}
// function based on function Unit::CanAssist from 13850 client
bool Unit::_IsValidAssistTarget(Unit const* target, SpellInfo const* bySpell) const
{
ASSERT(target);
// can assist to self
if (this == target)
return true;
// can't assist unattackable units or GMs
if (target->HasUnitState(UNIT_STAT_UNATTACKABLE)
|| (target->GetTypeId() == TYPEID_PLAYER && target->ToPlayer()->isGameMaster()))
return false;
// can't assist own vehicle or passenger
if (m_vehicle)
if (IsOnVehicle(target) || m_vehicle->GetBase()->IsOnVehicle(target))
return false;
// can't assist invisible
if ((!bySpell || !(bySpell->AttributesEx6 & SPELL_ATTR6_CAN_TARGET_INVISIBLE)) && !canSeeOrDetect(target, bySpell && bySpell->IsAOE()))
return false;
// can't assist dead
if ((!bySpell || !bySpell->IsAllowingDeadTarget()) && !target->isAlive())
return false;
// can't assist untargetable
if ((!bySpell || !(bySpell->AttributesEx6 & SPELL_ATTR6_CAN_TARGET_UNTARGETABLE))
&& target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE))
return false;
if (!bySpell || !(bySpell->AttributesEx6 & SPELL_ATTR6_UNK3))
{
if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE))
{
if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE))
return false;
}
else
{
if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PASSIVE))
return false;
}
}
// can't assist non-friendly targets
if (GetReactionTo(target) <= REP_NEUTRAL
&& target->GetReactionTo(this) <= REP_NEUTRAL
&& (!ToCreature() || !(ToCreature()->GetCreatureInfo()->type_flags & CREATURE_TYPEFLAGS_UNK26)))
return false;
// PvP case
if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE))
{
Player const* targetPlayerOwner = target->GetAffectingPlayer();
if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE))
{
Player const* selfPlayerOwner = GetAffectingPlayer();
if (selfPlayerOwner && targetPlayerOwner)
{
// can't assist player which is dueling someone
if (selfPlayerOwner != targetPlayerOwner
&& targetPlayerOwner->duel)
return false;
}
// can't assist player in ffa_pvp zone from outside
if ((target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP)
&& !(GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP))
return false;
// can't assist player out of sanctuary from sanctuary if has pvp enabled
if (target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_PVP)
if ((GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_SANCTUARY) && !(target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_SANCTUARY))
return false;
}
}
// PvC case - player can assist creature only if has specific type flags
// !target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) &&
else if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE)
&& (!bySpell || !(bySpell->AttributesEx6 & SPELL_ATTR6_UNK3))
&& !((target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_PVP)))
{
if (Creature const* creatureTarget = target->ToCreature())
return creatureTarget->GetCreatureInfo()->type_flags & CREATURE_TYPEFLAGS_UNK26 || creatureTarget->GetCreatureInfo()->type_flags & CREATURE_TYPEFLAGS_AID_PLAYERS;
}
return true;
}
int32 Unit::ModifyHealth(int32 dVal)
{
int32 gain = 0;
if (dVal == 0)
return 0;
int32 curHealth = (int32)GetHealth();
int32 val = dVal + curHealth;
if (val <= 0)
{
SetHealth(0);
return -curHealth;
}
int32 maxHealth = (int32)GetMaxHealth();
if (val < maxHealth)
{
SetHealth(val);
gain = val - curHealth;
}
else if (curHealth != maxHealth)
{
SetHealth(maxHealth);
gain = maxHealth - curHealth;
}
return gain;
}
int32 Unit::GetHealthGain(int32 dVal)
{
int32 gain = 0;
if (dVal == 0)
return 0;
int32 curHealth = (int32)GetHealth();
int32 val = dVal + curHealth;
if (val <= 0)
{
return -curHealth;
}
int32 maxHealth = (int32)GetMaxHealth();
if (val < maxHealth)
gain = dVal;
else if (curHealth != maxHealth)
gain = maxHealth - curHealth;
return gain;
}
// returns negative amount on power reduction
int32 Unit::ModifyPower(Powers power, int32 dVal)
{
int32 gain = 0;
if (dVal == 0)
return 0;
int32 curPower = (int32)GetPower(power);
int32 val = dVal + curPower;
if (val <= 0)
{
SetPower(power, 0);
return -curPower;
}
int32 maxPower = (int32)GetMaxPower(power);
if (val < maxPower)
{
SetPower(power, val);
gain = val - curPower;
}
else if (curPower != maxPower)
{
SetPower(power, maxPower);
gain = maxPower - curPower;
}
return gain;
}
// returns negative amount on power reduction
int32 Unit::ModifyPowerPct(Powers power, float pct, bool apply)
{
float amount = (float)GetMaxPower(power);
ApplyPercentModFloatVar(amount, pct, apply);
return ModifyPower(power, (int32)amount - (int32)GetMaxPower(power));
}
bool Unit::IsAlwaysVisibleFor(WorldObject const* seer) const
{
if (WorldObject::IsAlwaysVisibleFor(seer))
return true;
// Always seen by owner
if (uint64 guid = GetCharmerOrOwnerGUID())
if (seer->GetGUID() == guid)
return true;
return false;
}
bool Unit::IsAlwaysDetectableFor(WorldObject const* seer) const
{
if (WorldObject::IsAlwaysDetectableFor(seer))
return true;
if (HasAuraTypeWithCaster(SPELL_AURA_MOD_STALKED, seer->GetGUID()))
return true;
return false;
}
void Unit::SetVisible(bool x)
{
if (!x)
m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GM, SEC_GAMEMASTER);
else
m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GM, SEC_PLAYER);
UpdateObjectVisibility();
}
void Unit::UpdateSpeed(UnitMoveType mtype, bool forced)
{
//if (this->ToPlayer())
// sAnticheatMgr->DisableAnticheatDetection(this->ToPlayer());
int32 main_speed_mod = 0;
float stack_bonus = 1.0f;
float non_stack_bonus = 1.0f;
switch (mtype)
{
// Only apply debuffs
case MOVE_FLIGHT_BACK:
case MOVE_RUN_BACK:
case MOVE_SWIM_BACK:
break;
case MOVE_WALK:
return;
case MOVE_RUN:
{
if (IsMounted()) // Use on mount auras
{
main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED);
stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS);
non_stack_bonus += GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK) / 100.0f;
}
else
{
main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED);
stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS);
non_stack_bonus += GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK) / 100.0f;
}
break;
}
case MOVE_SWIM:
{
main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED);
break;
}
case MOVE_FLIGHT:
{
if (GetTypeId() == TYPEID_UNIT && IsControlledByPlayer()) // not sure if good for pet
{
main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED);
stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_VEHICLE_SPEED_ALWAYS);
// for some spells this mod is applied on vehicle owner
int32 owner_speed_mod = 0;
if (Unit* owner = GetCharmer())
owner_speed_mod = owner->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED);
main_speed_mod = std::max(main_speed_mod, owner_speed_mod);
}
else if (IsMounted())
{
main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED);
stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_FLIGHT_SPEED_ALWAYS);
}
else // Use not mount (shapeshift for example) auras (should stack)
main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) + GetTotalAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED);
non_stack_bonus += GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK) / 100.0f;
// Update speed for vehicle if available
if (GetTypeId() == TYPEID_PLAYER && GetVehicle())
GetVehicleBase()->UpdateSpeed(MOVE_FLIGHT, true);
break;
}
default:
sLog->outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype);
return;
}
// now we ready for speed calculation
float speed = std::max(non_stack_bonus, stack_bonus);
if (main_speed_mod)
AddPctN(speed, main_speed_mod);
switch (mtype)
{
case MOVE_RUN:
case MOVE_SWIM:
case MOVE_FLIGHT:
{
// Set creature speed rate from CreatureInfo
if (GetTypeId() == TYPEID_UNIT)
speed *= ToCreature()->GetCreatureInfo()->speed_walk;
// Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need
// TODO: possible affect only on MOVE_RUN
if (int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED))
{
// Use speed from aura
float max_speed = normalization / (IsControlledByPlayer() ? playerBaseMoveSpeed[mtype] : baseMoveSpeed[mtype]);
if (speed > max_speed)
speed = max_speed;
}
break;
}
default:
break;
}
// for creature case, we check explicit if mob searched for assistance
if (GetTypeId() == TYPEID_UNIT)
{
if (ToCreature()->HasSearchedAssistance())
speed *= 0.66f; // best guessed value, so this will be 33% reduction. Based off initial speed, mob can then "run", "walk fast" or "walk".
}
// Apply strongest slow aura mod to speed
int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED);
if (slow)
{
AddPctN(speed, slow);
if (float minSpeedMod = (float)GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MINIMUM_SPEED))
{
float min_speed = minSpeedMod / 100.0f;
if (speed < min_speed)
speed = min_speed;
}
}
SetSpeed(mtype, speed, forced);
}
float Unit::GetSpeed(UnitMoveType mtype) const
{
return m_speed_rate[mtype]*(IsControlledByPlayer() ? playerBaseMoveSpeed[mtype] : baseMoveSpeed[mtype]);
}
void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced)
{
if (rate < 0)
rate = 0.0f;
// Update speed only on change
if (m_speed_rate[mtype] == rate)
return;
m_speed_rate[mtype] = rate;
propagateSpeedChange();
WorldPacket data;
if (!forced)
{
switch (mtype)
{
case MOVE_WALK:
data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4);
break;
case MOVE_RUN:
data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4);
break;
case MOVE_RUN_BACK:
data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
break;
case MOVE_SWIM:
data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4);
break;
case MOVE_SWIM_BACK:
data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
break;
case MOVE_TURN_RATE:
data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4);
break;
case MOVE_FLIGHT:
data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4);
break;
case MOVE_FLIGHT_BACK:
data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
break;
case MOVE_PITCH_RATE:
data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4);
break;
default:
sLog->outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.", mtype);
return;
}
data.append(GetPackGUID());
data << uint32(0); // movement flags
data << uint16(0); // unk flags
data << uint32(getMSTime());
data << float(GetPositionX());
data << float(GetPositionY());
data << float(GetPositionZ());
data << float(GetOrientation());
data << uint32(0); // fall time
data << float(GetSpeed(mtype));
SendMessageToSet(&data, true);
}
else
{
if (GetTypeId() == TYPEID_PLAYER)
{
// register forced speed changes for WorldSession::HandleForceSpeedChangeAck
// and do it only for real sent packets and use run for run/mounted as client expected
++ToPlayer()->m_forced_speed_changes[mtype];
if (!isInCombat())
if (Pet* pet = ToPlayer()->GetPet())
pet->SetSpeed(mtype, m_speed_rate[mtype], forced);
}
switch (mtype)
{
case MOVE_WALK:
data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16);
break;
case MOVE_RUN:
data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17);
break;
case MOVE_RUN_BACK:
data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16);
break;
case MOVE_SWIM:
data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16);
break;
case MOVE_SWIM_BACK:
data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16);
break;
case MOVE_TURN_RATE:
data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16);
break;
case MOVE_FLIGHT:
data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16);
break;
case MOVE_FLIGHT_BACK:
data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16);
break;
case MOVE_PITCH_RATE:
data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16);
break;
default:
sLog->outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.", mtype);
return;
}
data.append(GetPackGUID());
data << (uint32)0; // moveEvent, NUM_PMOVE_EVTS = 0x39
if (mtype == MOVE_RUN)
data << uint8(0); // new 2.1.0
data << float(GetSpeed(mtype));
SendMessageToSet(&data, true);
}
}
void Unit::SetHover(bool on)
{
if (on)
CastSpell(this, 11010, true);
else
RemoveAurasDueToSpell(11010);
}
void Unit::setDeathState(DeathState s)
{
// death state needs to be updated before RemoveAllAurasOnDeath() calls HandleChannelDeathItem(..) so that
// it can be used to check creation of death items (such as soul shards).
DeathState oldDeathState = m_deathState;
m_deathState = s;
if (s != ALIVE && s != JUST_ALIVED)
{
CombatStop();
DeleteThreatList();
getHostileRefManager().deleteReferences();
ClearComboPointHolders(); // any combo points pointed to unit lost at it death
if (IsNonMeleeSpellCasted(false))
InterruptNonMeleeSpells(false);
UnsummonAllTotems();
RemoveAllControlled();
RemoveAllAurasOnDeath();
}
if (s == JUST_DIED)
{
ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false);
// remove aurastates allowing special moves
ClearAllReactives();
ClearDiminishings();
GetMotionMaster()->Clear(false);
GetMotionMaster()->MoveIdle();
SendMonsterStop(true);
// without this when removing IncreaseMaxHealth aura player may stuck with 1 hp
// do not why since in IncreaseMaxHealth currenthealth is checked
SetHealth(0);
SetPower(getPowerType(), 0);
}
else if (s == JUST_ALIVED)
RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground)
if (oldDeathState != ALIVE && s == ALIVE)
{
// Reset display id on resurection - needed by corpse explosion to cleanup after display change
// TODO: fix this
if (!HasAuraType(SPELL_AURA_TRANSFORM))
SetDisplayId(GetNativeDisplayId());
}
}
/*########################################
######## ########
######## AGGRO SYSTEM ########
######## ########
########################################*/
bool Unit::CanHaveThreatList() const
{
// only creatures can have threat list
if (GetTypeId() != TYPEID_UNIT)
return false;
// only alive units can have threat list
if (!isAlive() || isDying())
return false;
// totems can not have threat list
if (ToCreature()->isTotem())
return false;
// vehicles can not have threat list
//if (ToCreature()->IsVehicle())
// return false;
// summons can not have a threat list, unless they are controlled by a creature
if (HasUnitTypeMask(UNIT_MASK_MINION | UNIT_MASK_GUARDIAN | UNIT_MASK_CONTROLABLE_GUARDIAN) && IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID()))
return false;
return true;
}
//======================================================================
float Unit::ApplyTotalThreatModifier(float fThreat, SpellSchoolMask schoolMask)
{
if (!HasAuraType(SPELL_AURA_MOD_THREAT) || fThreat < 0)
return fThreat;
SpellSchools school = GetFirstSchoolInMask(schoolMask);
return fThreat * m_threatModifier[school];
}
//======================================================================
void Unit::AddThreat(Unit* victim, float fThreat, SpellSchoolMask schoolMask, SpellInfo const* threatSpell)
{
// Only mobs can manage threat lists
if (CanHaveThreatList())
m_ThreatManager.addThreat(victim, fThreat, schoolMask, threatSpell);
}
//======================================================================
void Unit::DeleteThreatList()
{
if (CanHaveThreatList() && !m_ThreatManager.isThreatListEmpty())
SendClearThreatListOpcode();
m_ThreatManager.clearReferences();
}
//======================================================================
void Unit::TauntApply(Unit* taunter)
{
ASSERT(GetTypeId() == TYPEID_UNIT);
if (!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && taunter->ToPlayer()->isGameMaster()))
return;
if (!CanHaveThreatList())
return;
Creature* creature = ToCreature();
if (creature->HasReactState(REACT_PASSIVE))
return;
Unit* target = getVictim();
if (target && target == taunter)
return;
SetInFront(taunter);
if (creature->IsAIEnabled)
creature->AI()->AttackStart(taunter);
//m_ThreatManager.tauntApply(taunter);
}
//======================================================================
void Unit::TauntFadeOut(Unit* taunter)
{
ASSERT(GetTypeId() == TYPEID_UNIT);
if (!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && taunter->ToPlayer()->isGameMaster()))
return;
if (!CanHaveThreatList())
return;
Creature* creature = ToCreature();
if (creature->HasReactState(REACT_PASSIVE))
return;
Unit* target = getVictim();
if (!target || target != taunter)
return;
if (m_ThreatManager.isThreatListEmpty())
{
if (creature->IsAIEnabled)
creature->AI()->EnterEvadeMode();
return;
}
//m_ThreatManager.tauntFadeOut(taunter);
target = m_ThreatManager.getHostilTarget();
if (target && target != taunter)
{
SetInFront(target);
if (creature->IsAIEnabled)
creature->AI()->AttackStart(target);
}
}
//======================================================================
Unit* Creature::SelectVictim()
{
// function provides main threat functionality
// next-victim-selection algorithm and evade mode are called
// threat list sorting etc.
Unit* target = NULL;
// First checking if we have some taunt on us
AuraEffectList const& tauntAuras = GetAuraEffectsByType(SPELL_AURA_MOD_TAUNT);
if (!tauntAuras.empty())
{
Unit* caster = tauntAuras.back()->GetCaster();
// The last taunt aura caster is alive an we are happy to attack him
if (caster && caster->isAlive())
return getVictim();
else if (tauntAuras.size() > 1)
{
// We do not have last taunt aura caster but we have more taunt auras,
// so find first available target
// Auras are pushed_back, last caster will be on the end
AuraEffectList::const_iterator aura = --tauntAuras.end();
do
{
--aura;
caster = (*aura)->GetCaster();
if (caster && canSeeOrDetect(caster, true) && IsValidAttackTarget(caster) && caster->isInAccessiblePlaceFor(ToCreature()))
{
target = caster;
break;
}
} while (aura != tauntAuras.begin());
}
else
target = getVictim();
}
if (CanHaveThreatList())
{
if (!target && !m_ThreatManager.isThreatListEmpty())
// No taunt aura or taunt aura caster is dead standard target selection
target = m_ThreatManager.getHostilTarget();
}
else if (!HasReactState(REACT_PASSIVE))
{
// We have player pet probably
target = getAttackerForHelper();
if (!target && isSummon())
{
if (Unit* owner = ToTempSummon()->GetOwner())
{
if (owner->isInCombat())
target = owner->getAttackerForHelper();
if (!target)
{
for (ControlList::const_iterator itr = owner->m_Controlled.begin(); itr != owner->m_Controlled.end(); ++itr)
{
if ((*itr)->isInCombat())
{
target = (*itr)->getAttackerForHelper();
if (target)
break;
}
}
}
}
}
}
else
return NULL;
if (target && _IsTargetAcceptable(target))
{
SetInFront(target);
return target;
}
// last case when creature must not go to evade mode:
// it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list
// for example at owner command to pet attack some far away creature
// Note: creature not have targeted movement generator but have attacker in this case
for (AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr)
{
if ((*itr) && !canCreatureAttack(*itr) && (*itr)->GetTypeId() != TYPEID_PLAYER
&& !(*itr)->ToCreature()->HasUnitTypeMask(UNIT_MASK_CONTROLABLE_GUARDIAN))
return NULL;
}
// TODO: a vehicle may eat some mob, so mob should not evade
if (GetVehicle())
return NULL;
// search nearby enemy before enter evade mode
if (HasReactState(REACT_AGGRESSIVE))
{
target = SelectNearestTargetInAttackDistance(m_CombatDistance ? m_CombatDistance : ATTACK_DISTANCE);
if (target && _IsTargetAcceptable(target))
return target;
}
Unit::AuraEffectList const& iAuras = GetAuraEffectsByType(SPELL_AURA_MOD_INVISIBILITY);
if (!iAuras.empty())
{
for (Unit::AuraEffectList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
{
if ((*itr)->GetBase()->IsPermanent())
{
AI()->EnterEvadeMode();
break;
}
}
return NULL;
}
// enter in evade mode in other case
AI()->EnterEvadeMode();
return NULL;
}
//======================================================================
//======================================================================
//======================================================================
float Unit::ApplyEffectModifiers(SpellInfo const* spellProto, uint8 effect_index, float value) const
{
if (Player* modOwner = GetSpellModOwner())
{
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_ALL_EFFECTS, value);
switch (effect_index)
{
case 0:
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT1, value);
break;
case 1:
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT2, value);
break;
case 2:
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT3, value);
break;
}
}
return value;
}
// function uses real base points (typically value - 1)
int32 Unit::CalculateSpellDamage(Unit const* target, SpellInfo const* spellProto, uint8 effect_index, int32 const* basePoints) const
{
return spellProto->Effects[effect_index].CalcValue(this, basePoints, target);
}
int32 Unit::CalcSpellDuration(SpellInfo const* spellProto)
{
uint8 comboPoints = m_movedPlayer ? m_movedPlayer->GetComboPoints() : 0;
int32 minduration = spellProto->GetDuration();
int32 maxduration = spellProto->GetMaxDuration();
int32 duration;
if (comboPoints && minduration != -1 && minduration != maxduration)
duration = minduration + int32((maxduration - minduration) * comboPoints / 5);
else
duration = minduration;
return duration;
}
int32 Unit::ModSpellDuration(SpellInfo const* spellProto, Unit const* target, int32 duration, bool positive, uint32 effectMask)
{
// don't mod permanent auras duration
if (duration < 0)
return duration;
// cut duration only of negative effects
if (!positive)
{
int32 mechanic = spellProto->GetSpellMechanicMaskByEffectMask(effectMask);
int32 durationMod;
int32 durationMod_always = 0;
int32 durationMod_not_stack = 0;
for (uint8 i = 1; i <= MECHANIC_ENRAGED; ++i)
{
if (!(mechanic & 1<<i))
continue;
// Find total mod value (negative bonus)
int32 new_durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, i);
// Find max mod (negative bonus)
int32 new_durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, i);
// Check if mods applied before were weaker
if (new_durationMod_always < durationMod_always)
durationMod_always = new_durationMod_always;
if (new_durationMod_not_stack < durationMod_not_stack)
durationMod_not_stack = new_durationMod_not_stack;
}
// Select strongest negative mod
if (durationMod_always > durationMod_not_stack)
durationMod = durationMod_not_stack;
else
durationMod = durationMod_always;
if (durationMod != 0)
AddPctN(duration, durationMod);
// there are only negative mods currently
durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL, spellProto->Dispel);
durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL_NOT_STACK, spellProto->Dispel);
durationMod = 0;
if (durationMod_always > durationMod_not_stack)
durationMod += durationMod_not_stack;
else
durationMod += durationMod_always;
if (durationMod != 0)
AddPctN(duration, durationMod);
}
else
{
// else positive mods here, there are no currently
// when there will be, change GetTotalAuraModifierByMiscValue to GetTotalPositiveAuraModifierByMiscValue
// Mixology - duration boost
if (target->GetTypeId() == TYPEID_PLAYER)
{
if (spellProto->SpellFamilyName == SPELLFAMILY_POTION && (
sSpellMgr->IsSpellMemberOfSpellGroup(spellProto->Id, SPELL_GROUP_ELIXIR_BATTLE) ||
sSpellMgr->IsSpellMemberOfSpellGroup(spellProto->Id, SPELL_GROUP_ELIXIR_GUARDIAN)))
{
if (target->HasAura(53042) && target->HasSpell(spellProto->Effects[0].TriggerSpell))
duration *= 2;
}
}
}
// Glyphs which increase duration of selfcasted buffs
if (target == this)
{
switch (spellProto->SpellFamilyName)
{
case SPELLFAMILY_DRUID:
if (spellProto->SpellFamilyFlags[0] & 0x100)
{
// Glyph of Thorns
if (AuraEffect* aurEff = GetAuraEffect(57862, 0))
duration += aurEff->GetAmount() * MINUTE * IN_MILLISECONDS;
}
break;
case SPELLFAMILY_PALADIN:
if (spellProto->SpellFamilyFlags[0] & 0x00000002)
{
// Glyph of Blessing of Might
if (AuraEffect* aurEff = GetAuraEffect(57958, 0))
duration += aurEff->GetAmount() * MINUTE * IN_MILLISECONDS;
}
else if (spellProto->SpellFamilyFlags[0] & 0x00010000)
{
// Glyph of Blessing of Wisdom
if (AuraEffect* aurEff = GetAuraEffect(57979, 0))
duration += aurEff->GetAmount() * MINUTE * IN_MILLISECONDS;
}
break;
}
}
return std::max(duration, 0);
}
void Unit::ModSpellCastTime(SpellInfo const* spellProto, int32 & castTime, Spell* spell)
{
if (!spellProto || castTime < 0)
return;
// called from caster
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CASTING_TIME, castTime, spell);
if (!(spellProto->Attributes & (SPELL_ATTR0_ABILITY|SPELL_ATTR0_TRADESPELL)) && spellProto->SpellFamilyName)
castTime = int32(float(castTime) * GetFloatValue(UNIT_MOD_CAST_SPEED));
else if (spellProto->Attributes & SPELL_ATTR0_REQ_AMMO && !(spellProto->AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG))
castTime = int32(float(castTime) * m_modAttackSpeedPct[RANGED_ATTACK]);
else if (spellProto->SpellVisual[0] == 3881 && HasAura(67556)) // cooking with Chef Hat.
castTime = 500;
}
DiminishingLevels Unit::GetDiminishing(DiminishingGroup group)
{
for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
{
if (i->DRGroup != group)
continue;
if (!i->hitCount)
return DIMINISHING_LEVEL_1;
if (!i->hitTime)
return DIMINISHING_LEVEL_1;
// If last spell was casted more than 15 seconds ago - reset the count.
if (i->stack == 0 && getMSTimeDiff(i->hitTime, getMSTime()) > 15000)
{
i->hitCount = DIMINISHING_LEVEL_1;
return DIMINISHING_LEVEL_1;
}
// or else increase the count.
else
return DiminishingLevels(i->hitCount);
}
return DIMINISHING_LEVEL_1;
}
void Unit::IncrDiminishing(DiminishingGroup group)
{
// Checking for existing in the table
for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
{
if (i->DRGroup != group)
continue;
if (int32(i->hitCount) < GetDiminishingReturnsMaxLevel(group))
i->hitCount += 1;
return;
}
m_Diminishing.push_back(DiminishingReturn(group, getMSTime(), DIMINISHING_LEVEL_2));
}
float Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration, Unit* caster, DiminishingLevels Level, int32 limitduration)
{
if (duration == -1 || group == DIMINISHING_NONE)
return 1.0f;
// test pet/charm masters instead pets/charmeds
Unit const* targetOwner = GetCharmerOrOwner();
Unit const* casterOwner = caster->GetCharmerOrOwner();
// Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0)
if (limitduration > 0 && duration > limitduration)
{
Unit const* target = targetOwner ? targetOwner : this;
Unit const* source = casterOwner ? casterOwner : caster;
if ((target->GetTypeId() == TYPEID_PLAYER
|| ((Creature*)target)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_ALL_DIMINISH)
&& source->GetTypeId() == TYPEID_PLAYER)
duration = limitduration;
}
float mod = 1.0f;
if (group == DIMINISHING_TAUNT)
{
if (GetTypeId() == TYPEID_UNIT && (ToCreature()->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_TAUNT_DIMINISH))
{
DiminishingLevels diminish = Level;
switch (diminish)
{
case DIMINISHING_LEVEL_1: break;
case DIMINISHING_LEVEL_2: mod = 0.65f; break;
case DIMINISHING_LEVEL_3: mod = 0.4225f; break;
case DIMINISHING_LEVEL_4: mod = 0.274625f; break;
case DIMINISHING_LEVEL_TAUNT_IMMUNE: mod = 0.0f; break;
default: break;
}
}
}
// Some diminishings applies to mobs too (for example, Stun)
else if ((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER
&& ((targetOwner ? (targetOwner->GetTypeId() == TYPEID_PLAYER) : (GetTypeId() == TYPEID_PLAYER))
|| (GetTypeId() == TYPEID_UNIT && ToCreature()->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_ALL_DIMINISH)))
|| GetDiminishingReturnsGroupType(group) == DRTYPE_ALL)
{
DiminishingLevels diminish = Level;
switch (diminish)
{
case DIMINISHING_LEVEL_1: break;
case DIMINISHING_LEVEL_2: mod = 0.5f; break;
case DIMINISHING_LEVEL_3: mod = 0.25f; break;
case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f; break;
default: break;
}
}
duration = int32(duration * mod);
return mod;
}
void Unit::ApplyDiminishingAura(DiminishingGroup group, bool apply)
{
// Checking for existing in the table
for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
{
if (i->DRGroup != group)
continue;
if (apply)
i->stack += 1;
else if (i->stack)
{
i->stack -= 1;
// Remember time after last aura from group removed
if (i->stack == 0)
i->hitTime = getMSTime();
}
break;
}
}
float Unit::GetSpellMaxRangeForTarget(Unit const* target, SpellInfo const* spellInfo) const
{
if (!spellInfo->RangeEntry)
return 0;
if (spellInfo->RangeEntry->maxRangeFriend == spellInfo->RangeEntry->maxRangeHostile)
return spellInfo->GetMaxRange();
return spellInfo->GetMaxRange(!IsHostileTo(target));
}
float Unit::GetSpellMinRangeForTarget(Unit const* target, SpellInfo const* spellInfo) const
{
if (!spellInfo->RangeEntry)
return 0;
if (spellInfo->RangeEntry->minRangeFriend == spellInfo->RangeEntry->minRangeHostile)
return spellInfo->GetMinRange();
return spellInfo->GetMinRange(!IsHostileTo(target));
}
Unit* Unit::GetUnit(WorldObject& object, uint64 guid)
{
return ObjectAccessor::GetUnit(object, guid);
}
Player* Unit::GetPlayer(WorldObject& object, uint64 guid)
{
return ObjectAccessor::GetPlayer(object, guid);
}
Creature* Unit::GetCreature(WorldObject& object, uint64 guid)
{
return object.GetMap()->GetCreature(guid);
}
uint32 Unit::GetCreatureType() const
{
if (GetTypeId() == TYPEID_PLAYER)
{
ShapeshiftForm form = GetShapeshiftForm();
SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(form);
if (ssEntry && ssEntry->creatureType > 0)
return ssEntry->creatureType;
else
return CREATURE_TYPE_HUMANOID;
}
else
return ToCreature()->GetCreatureInfo()->type;
}
/*#######################################
######## ########
######## STAT SYSTEM ########
######## ########
#######################################*/
bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply)
{
if (unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
{
sLog->outError("ERROR in HandleStatModifier(): non existed UnitMods or wrong UnitModifierType!");
return false;
}
switch (modifierType)
{
case BASE_VALUE:
case TOTAL_VALUE:
m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount;
break;
case BASE_PCT:
case TOTAL_PCT:
ApplyPercentModFloatVar(m_auraModifiersGroup[unitMod][modifierType], amount, apply);
break;
default:
break;
}
if (!CanModifyStats())
return false;
switch (unitMod)
{
case UNIT_MOD_STAT_STRENGTH:
case UNIT_MOD_STAT_AGILITY:
case UNIT_MOD_STAT_STAMINA:
case UNIT_MOD_STAT_INTELLECT:
case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break;
case UNIT_MOD_ARMOR: UpdateArmor(); break;
case UNIT_MOD_HEALTH: UpdateMaxHealth(); break;
case UNIT_MOD_MANA:
case UNIT_MOD_RAGE:
case UNIT_MOD_FOCUS:
case UNIT_MOD_ENERGY:
case UNIT_MOD_HAPPINESS:
case UNIT_MOD_RUNE:
case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break;
case UNIT_MOD_RESISTANCE_HOLY:
case UNIT_MOD_RESISTANCE_FIRE:
case UNIT_MOD_RESISTANCE_NATURE:
case UNIT_MOD_RESISTANCE_FROST:
case UNIT_MOD_RESISTANCE_SHADOW:
case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break;
case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break;
case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break;
case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break;
case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break;
case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break;
default:
break;
}
return true;
}
float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const
{
if (unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
{
sLog->outError("trial to access non existed modifier value from UnitMods!");
return 0.0f;
}
if (modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f)
return 0.0f;
return m_auraModifiersGroup[unitMod][modifierType];
}
float Unit::GetTotalStatValue(Stats stat) const
{
UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat);
if (m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
return 0.0f;
// value = ((base_value * base_pct) + total_value) * total_pct
float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat);
value *= m_auraModifiersGroup[unitMod][BASE_PCT];
value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
return value;
}
float Unit::GetTotalAuraModValue(UnitMods unitMod) const
{
if (unitMod >= UNIT_MOD_END)
{
sLog->outError("trial to access non existed UnitMods in GetTotalAuraModValue()!");
return 0.0f;
}
if (m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
return 0.0f;
float value = m_auraModifiersGroup[unitMod][BASE_VALUE];
value *= m_auraModifiersGroup[unitMod][BASE_PCT];
value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
return value;
}
SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const
{
SpellSchools school = SPELL_SCHOOL_NORMAL;
switch (unitMod)
{
case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break;
case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break;
case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break;
case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break;
case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break;
case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break;
default:
break;
}
return school;
}
Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const
{
Stats stat = STAT_STRENGTH;
switch (unitMod)
{
case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break;
case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break;
case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break;
case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break;
case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break;
default:
break;
}
return stat;
}
Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const
{
switch (unitMod)
{
case UNIT_MOD_RAGE: return POWER_RAGE;
case UNIT_MOD_FOCUS: return POWER_FOCUS;
case UNIT_MOD_ENERGY: return POWER_ENERGY;
case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS;
case UNIT_MOD_RUNE: return POWER_RUNE;
case UNIT_MOD_RUNIC_POWER: return POWER_RUNIC_POWER;
default:
case UNIT_MOD_MANA: return POWER_MANA;
}
}
float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const
{
if (attType == RANGED_ATTACK)
{
int32 ap = GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS);
if (ap < 0)
return 0.0f;
return ap * (1.0f + GetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER));
}
else
{
int32 ap = GetInt32Value(UNIT_FIELD_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS);
if (ap < 0)
return 0.0f;
return ap * (1.0f + GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER));
}
}
float Unit::GetWeaponDamageRange(WeaponAttackType attType, WeaponDamageRange type) const
{
if (attType == OFF_ATTACK && !haveOffhandWeapon())
return 0.0f;
return m_weaponDamage[attType][type];
}
void Unit::SetLevel(uint8 lvl)
{
SetUInt32Value(UNIT_FIELD_LEVEL, lvl);
// group update
if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->GetGroup())
ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL);
}
void Unit::SetHealth(uint32 val)
{
if (getDeathState() == JUST_DIED)
val = 0;
else if (GetTypeId() == TYPEID_PLAYER && (getDeathState() == DEAD || getDeathState() == DEAD_FALLING))
val = 1;
else
{
uint32 maxHealth = GetMaxHealth();
if (maxHealth < val)
val = maxHealth;
}
SetUInt32Value(UNIT_FIELD_HEALTH, val);
// group update
if (Player* player = ToPlayer())
{
if (player->GetGroup())
player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP);
}
else if (Pet* pet = ToCreature()->ToPet())
{
if (pet->isControlled())
{
Unit* owner = GetOwner();
if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup())
owner->ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP);
}
}
}
void Unit::SetMaxHealth(uint32 val)
{
if (!val)
val = 1;
uint32 health = GetHealth();
SetUInt32Value(UNIT_FIELD_MAXHEALTH, val);
// group update
if (GetTypeId() == TYPEID_PLAYER)
{
if (ToPlayer()->GetGroup())
ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP);
}
else if (Pet* pet = ToCreature()->ToPet())
{
if (pet->isControlled())
{
Unit* owner = GetOwner();
if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup())
owner->ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP);
}
}
if (val < health)
SetHealth(val);
}
void Unit::SetPower(Powers power, uint32 val)
{
if (GetPower(power) == val)
return;
uint32 maxPower = GetMaxPower(power);
if (maxPower < val)
val = maxPower;
SetStatInt32Value(UNIT_FIELD_POWER1 + power, val);
WorldPacket data(SMSG_POWER_UPDATE);
data.append(GetPackGUID());
data << uint8(power);
data << uint32(val);
SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false);
// group update
if (Player* player = ToPlayer())
{
if (player->GetGroup())
player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
}
else if (Pet* pet = ToCreature()->ToPet())
{
if (pet->isControlled())
{
Unit* owner = GetOwner();
if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup())
owner->ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
}
// Update the pet's character sheet with happiness damage bonus
if (pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS)
pet->UpdateDamagePhysical(BASE_ATTACK);
}
}
void Unit::SetMaxPower(Powers power, uint32 val)
{
uint32 cur_power = GetPower(power);
SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val);
// group update
if (GetTypeId() == TYPEID_PLAYER)
{
if (ToPlayer()->GetGroup())
ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
}
else if (Pet* pet = ToCreature()->ToPet())
{
if (pet->isControlled())
{
Unit* owner = GetOwner();
if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup())
owner->ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
}
}
if (val < cur_power)
SetPower(power, val);
}
uint32 Unit::GetCreatePowers(Powers power) const
{
// POWER_FOCUS and POWER_HAPPINESS only have hunter pet
switch (power)
{
case POWER_MANA: return GetCreateMana();
case POWER_RAGE: return 1000;
case POWER_FOCUS: return (GetTypeId() == TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType() != HUNTER_PET ? 0 : 100);
case POWER_ENERGY: return 100;
case POWER_HAPPINESS: return (GetTypeId() == TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType() != HUNTER_PET ? 0 : 1050000);
case POWER_RUNIC_POWER: return 1000;
case POWER_RUNE: return 0;
case POWER_HEALTH: return 0;
default:
break;
}
return 0;
}
void Unit::AddToWorld()
{
if (!IsInWorld())
{
WorldObject::AddToWorld();
}
}
void Unit::RemoveFromWorld()
{
// cleanup
ASSERT(GetGUID());
if (IsInWorld())
{
m_duringRemoveFromWorld = true;
if (IsVehicle())
GetVehicleKit()->Uninstall();
RemoveCharmAuras();
RemoveBindSightAuras();
RemoveNotOwnSingleTargetAuras();
RemoveAllGameObjects();
RemoveAllDynObjects();
ExitVehicle();
UnsummonAllTotems();
RemoveAllControlled();
RemoveAreaAurasDueToLeaveWorld();
if (GetCharmerGUID())
{
sLog->outCrash("Unit %u has charmer guid when removed from world", GetEntry());
ASSERT(false);
}
if (Unit* owner = GetOwner())
{
if (owner->m_Controlled.find(this) != owner->m_Controlled.end())
{
sLog->outCrash("Unit %u is in controlled list of %u when removed from world", GetEntry(), owner->GetEntry());
ASSERT(false);
}
}
WorldObject::RemoveFromWorld();
m_duringRemoveFromWorld = false;
}
}
void Unit::CleanupBeforeRemoveFromMap(bool finalCleanup)
{
// This needs to be before RemoveFromWorld to make GetCaster() return a valid pointer on aura removal
InterruptNonMeleeSpells(true);
if (IsInWorld())
RemoveFromWorld();
ASSERT(GetGUID());
// A unit may be in removelist and not in world, but it is still in grid
// and may have some references during delete
RemoveAllAuras();
RemoveAllGameObjects();
if (finalCleanup)
m_cleanupDone = true;
m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList
CombatStop();
ClearComboPointHolders();
DeleteThreatList();
getHostileRefManager().setOnlineOfflineState(false);
GetMotionMaster()->Clear(false); // remove different non-standard movement generators.
}
void Unit::CleanupsBeforeDelete(bool finalCleanup)
{
CleanupBeforeRemoveFromMap(finalCleanup);
if (Creature* thisCreature = ToCreature())
if (GetTransport())
GetTransport()->RemovePassenger(thisCreature);
}
void Unit::UpdateCharmAI()
{
if (GetTypeId() == TYPEID_PLAYER)
return;
if (i_disabledAI) // disabled AI must be primary AI
{
if (!isCharmed())
{
delete i_AI;
i_AI = i_disabledAI;
i_disabledAI = NULL;
}
}
else
{
if (isCharmed())
{
i_disabledAI = i_AI;
if (isPossessed() || IsVehicle())
i_AI = new PossessedAI(ToCreature());
else
i_AI = new PetAI(ToCreature());
}
}
}
CharmInfo* Unit::InitCharmInfo()
{
if (!m_charmInfo)
m_charmInfo = new CharmInfo(this);
return m_charmInfo;
}
void Unit::DeleteCharmInfo()
{
if (!m_charmInfo)
return;
m_charmInfo->RestoreState();
delete m_charmInfo;
m_charmInfo = NULL;
}
CharmInfo::CharmInfo(Unit* unit)
: m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_petnumber(0), m_barInit(false),
m_isCommandAttack(false), m_isAtStay(false), m_isFollowing(false), m_isReturning(false)
{
for (uint8 i = 0; i < MAX_SPELL_CHARM; ++i)
m_charmspells[i].SetActionAndType(0, ACT_DISABLED);
if (m_unit->GetTypeId() == TYPEID_UNIT)
{
m_oldReactState = m_unit->ToCreature()->GetReactState();
m_unit->ToCreature()->SetReactState(REACT_PASSIVE);
}
}
CharmInfo::~CharmInfo()
{
}
void CharmInfo::RestoreState()
{
if (m_unit->GetTypeId() == TYPEID_UNIT)
if (Creature* creature = m_unit->ToCreature())
creature->SetReactState(m_oldReactState);
}
void CharmInfo::InitPetActionBar()
{
// the first 3 SpellOrActions are attack, follow and stay
for (uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_START - ACTION_BAR_INDEX_START; ++i)
SetActionBar(ACTION_BAR_INDEX_START + i, COMMAND_ATTACK - i, ACT_COMMAND);
// middle 4 SpellOrActions are spells/special attacks/abilities
for (uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_END-ACTION_BAR_INDEX_PET_SPELL_START; ++i)
SetActionBar(ACTION_BAR_INDEX_PET_SPELL_START + i, 0, ACT_PASSIVE);
// last 3 SpellOrActions are reactions
for (uint32 i = 0; i < ACTION_BAR_INDEX_END - ACTION_BAR_INDEX_PET_SPELL_END; ++i)
SetActionBar(ACTION_BAR_INDEX_PET_SPELL_END + i, COMMAND_ATTACK - i, ACT_REACTION);
}
void CharmInfo::InitEmptyActionBar(bool withAttack)
{
if (withAttack)
SetActionBar(ACTION_BAR_INDEX_START, COMMAND_ATTACK, ACT_COMMAND);
else
SetActionBar(ACTION_BAR_INDEX_START, 0, ACT_PASSIVE);
for (uint32 x = ACTION_BAR_INDEX_START+1; x < ACTION_BAR_INDEX_END; ++x)
SetActionBar(x, 0, ACT_PASSIVE);
}
void CharmInfo::InitPossessCreateSpells()
{
InitEmptyActionBar();
if (m_unit->GetTypeId() == TYPEID_UNIT)
{
for (uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
{
uint32 spellId = m_unit->ToCreature()->m_spells[i];
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (spellInfo && !(spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_DEAD))
{
if (spellInfo->IsPassive())
m_unit->CastSpell(m_unit, spellInfo, true);
else
AddSpellToActionBar(spellInfo, ACT_PASSIVE);
}
}
}
}
void CharmInfo::InitCharmCreateSpells()
{
if (m_unit->GetTypeId() == TYPEID_PLAYER) // charmed players don't have spells
{
InitEmptyActionBar();
return;
}
InitPetActionBar();
for (uint32 x = 0; x < MAX_SPELL_CHARM; ++x)
{
uint32 spellId = m_unit->ToCreature()->m_spells[x];
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo || spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_DEAD)
{
m_charmspells[x].SetActionAndType(spellId, ACT_DISABLED);
continue;
}
if (spellInfo->IsPassive())
{
m_unit->CastSpell(m_unit, spellInfo, true);
m_charmspells[x].SetActionAndType(spellId, ACT_PASSIVE);
}
else
{
m_charmspells[x].SetActionAndType(spellId, ACT_DISABLED);
ActiveStates newstate = ACT_PASSIVE;
if (!spellInfo->IsAutocastable())
newstate = ACT_PASSIVE;
else
{
bool autocast = false;
for (uint32 i = 0; i < MAX_SPELL_EFFECTS && !autocast; ++i)
if (spellInfo->Effects[i].TargetA.GetType() == TARGET_TYPE_UNIT_TARGET)
autocast = true;
if (autocast)
{
newstate = ACT_ENABLED;
ToggleCreatureAutocast(spellInfo, true);
}
else
newstate = ACT_DISABLED;
}
AddSpellToActionBar(spellInfo, newstate);
}
}
}
bool CharmInfo::AddSpellToActionBar(SpellInfo const* spellInfo, ActiveStates newstate)
{
uint32 spell_id = spellInfo->Id;
uint32 first_id = spellInfo->GetFirstRankSpell()->Id;
// new spell rank can be already listed
for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
{
if (uint32 action = PetActionBar[i].GetAction())
{
if (PetActionBar[i].IsActionBarForSpell() && sSpellMgr->GetFirstSpellInChain(action) == first_id)
{
PetActionBar[i].SetAction(spell_id);
return true;
}
}
}
// or use empty slot in other case
for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
{
if (!PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell())
{
SetActionBar(i, spell_id, newstate == ACT_DECIDE ? spellInfo->IsAutocastable() ? ACT_DISABLED : ACT_PASSIVE : newstate);
return true;
}
}
return false;
}
bool CharmInfo::RemoveSpellFromActionBar(uint32 spell_id)
{
uint32 first_id = sSpellMgr->GetFirstSpellInChain(spell_id);
for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
{
if (uint32 action = PetActionBar[i].GetAction())
{
if (PetActionBar[i].IsActionBarForSpell() && sSpellMgr->GetFirstSpellInChain(action) == first_id)
{
SetActionBar(i, 0, ACT_PASSIVE);
return true;
}
}
}
return false;
}
void CharmInfo::ToggleCreatureAutocast(SpellInfo const* spellInfo, bool apply)
{
if (spellInfo->IsPassive())
return;
for (uint32 x = 0; x < MAX_SPELL_CHARM; ++x)
if (spellInfo->Id == m_charmspells[x].GetAction())
m_charmspells[x].SetType(apply ? ACT_ENABLED : ACT_DISABLED);
}
void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow)
{
m_petnumber = petnumber;
if (statwindow)
m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber);
else
m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0);
}
void CharmInfo::LoadPetActionBar(const std::string& data)
{
InitPetActionBar();
Tokens tokens(data, ' ');
if (tokens.size() != (ACTION_BAR_INDEX_END-ACTION_BAR_INDEX_START) * 2)
return; // non critical, will reset to default
uint8 index;
Tokens::iterator iter;
for (iter = tokens.begin(), index = ACTION_BAR_INDEX_START; index < ACTION_BAR_INDEX_END; ++iter, ++index)
{
// use unsigned cast to avoid sign negative format use at long-> ActiveStates (int) conversion
ActiveStates type = ActiveStates(atol(*iter));
++iter;
uint32 action = uint32(atol(*iter));
PetActionBar[index].SetActionAndType(action, type);
// check correctness
if (PetActionBar[index].IsActionBarForSpell())
{
SpellInfo const* spelInfo = sSpellMgr->GetSpellInfo(PetActionBar[index].GetAction());
if (!spelInfo)
SetActionBar(index, 0, ACT_PASSIVE);
else if (!spelInfo->IsAutocastable())
SetActionBar(index, PetActionBar[index].GetAction(), ACT_PASSIVE);
}
}
}
void CharmInfo::BuildActionBar(WorldPacket* data)
{
for (uint32 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
*data << uint32(PetActionBar[i].packedData);
}
void CharmInfo::SetSpellAutocast(SpellInfo const* spellInfo, bool state)
{
for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
{
if (spellInfo->Id == PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell())
{
PetActionBar[i].SetType(state ? ACT_ENABLED : ACT_DISABLED);
break;
}
}
}
bool Unit::isFrozen() const
{
return HasAuraState(AURA_STATE_FROZEN);
}
struct ProcTriggeredData
{
ProcTriggeredData(Aura* _aura)
: aura(_aura)
{
effMask = 0;
spellProcEvent = NULL;
}
SpellProcEventEntry const* spellProcEvent;
Aura* aura;
uint32 effMask;
};
typedef std::list< ProcTriggeredData > ProcTriggeredList;
// List of auras that CAN be trigger but may not exist in spell_proc_event
// in most case need for drop charges
// in some types of aura need do additional check
// for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic
bool InitTriggerAuraData()
{
for (uint16 i = 0; i < TOTAL_AURAS; ++i)
{
isTriggerAura[i] = false;
isNonTriggerAura[i] = false;
isAlwaysTriggeredAura[i] = false;
}
isTriggerAura[SPELL_AURA_DUMMY] = true;
isTriggerAura[SPELL_AURA_MOD_CONFUSE] = true;
isTriggerAura[SPELL_AURA_MOD_THREAT] = true;
isTriggerAura[SPELL_AURA_MOD_STUN] = true; // Aura not have charges but need remove him on trigger
isTriggerAura[SPELL_AURA_MOD_DAMAGE_DONE] = true;
isTriggerAura[SPELL_AURA_MOD_DAMAGE_TAKEN] = true;
isTriggerAura[SPELL_AURA_MOD_RESISTANCE] = true;
isTriggerAura[SPELL_AURA_MOD_STEALTH] = true;
isTriggerAura[SPELL_AURA_MOD_FEAR] = true; // Aura not have charges but need remove him on trigger
isTriggerAura[SPELL_AURA_MOD_ROOT] = true;
isTriggerAura[SPELL_AURA_TRANSFORM] = true;
isTriggerAura[SPELL_AURA_REFLECT_SPELLS] = true;
isTriggerAura[SPELL_AURA_DAMAGE_IMMUNITY] = true;
isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL] = true;
isTriggerAura[SPELL_AURA_PROC_TRIGGER_DAMAGE] = true;
isTriggerAura[SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK] = true;
isTriggerAura[SPELL_AURA_SCHOOL_ABSORB] = true; // Savage Defense untested
isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true;
isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL] = true;
isTriggerAura[SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true;
isTriggerAura[SPELL_AURA_MECHANIC_IMMUNITY] = true;
isTriggerAura[SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true;
isTriggerAura[SPELL_AURA_SPELL_MAGNET] = true;
isTriggerAura[SPELL_AURA_MOD_ATTACK_POWER] = true;
isTriggerAura[SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true;
isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true;
isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true;
isTriggerAura[SPELL_AURA_MOD_MELEE_HASTE] = true;
isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE] = true;
isTriggerAura[SPELL_AURA_RAID_PROC_FROM_CHARGE] = true;
isTriggerAura[SPELL_AURA_RAID_PROC_FROM_CHARGE_WITH_VALUE] = true;
isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true;
isTriggerAura[SPELL_AURA_MOD_DAMAGE_FROM_CASTER] = true;
isTriggerAura[SPELL_AURA_MOD_SPELL_CRIT_CHANCE] = true;
isTriggerAura[SPELL_AURA_ABILITY_IGNORE_AURASTATE] = true;
isNonTriggerAura[SPELL_AURA_MOD_POWER_REGEN] = true;
isNonTriggerAura[SPELL_AURA_REDUCE_PUSHBACK] = true;
isAlwaysTriggeredAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
isAlwaysTriggeredAura[SPELL_AURA_MOD_FEAR] = true;
isAlwaysTriggeredAura[SPELL_AURA_MOD_ROOT] = true;
isAlwaysTriggeredAura[SPELL_AURA_MOD_STUN] = true;
isAlwaysTriggeredAura[SPELL_AURA_TRANSFORM] = true;
isAlwaysTriggeredAura[SPELL_AURA_SPELL_MAGNET] = true;
isAlwaysTriggeredAura[SPELL_AURA_SCHOOL_ABSORB] = true;
isAlwaysTriggeredAura[SPELL_AURA_MOD_STEALTH] = true;
return true;
}
uint32 createProcExtendMask(SpellNonMeleeDamage* damageInfo, SpellMissInfo missCondition)
{
uint32 procEx = PROC_EX_NONE;
// Check victim state
if (missCondition != SPELL_MISS_NONE)
switch (missCondition)
{
case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break;
case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break;
case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break;
case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break;
case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break;
case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break;
case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break;
case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break;
case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break;
case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break;
case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break;
default:
break;
}
else
{
// On block
if (damageInfo->blocked)
procEx|=PROC_EX_BLOCK;
// On absorb
if (damageInfo->absorb)
procEx|=PROC_EX_ABSORB;
// On crit
if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT)
procEx|=PROC_EX_CRITICAL_HIT;
else
procEx|=PROC_EX_NORMAL_HIT;
}
return procEx;
}
void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellInfo const* procSpell, uint32 damage, SpellInfo const* procAura)
{
// Player is loaded now - do not allow passive spell casts to proc
if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->GetSession()->PlayerLoading())
return;
// For melee/ranged based attack need update skills and set some Aura states if victim present
if (procFlag & MELEE_BASED_TRIGGER_MASK && target)
{
// Update skills here for players
if (GetTypeId() == TYPEID_PLAYER)
{
// On melee based hit/miss/resist need update skill (for victim and attacker)
if (procExtra & (PROC_EX_NORMAL_HIT|PROC_EX_MISS|PROC_EX_RESIST))
{
if (target->GetTypeId() != TYPEID_PLAYER && target->GetCreatureType() != CREATURE_TYPE_CRITTER)
ToPlayer()->UpdateCombatSkills(target, attType, isVictim);
}
// Update defence if player is victim and parry/dodge/block
else if (isVictim && procExtra & (PROC_EX_DODGE|PROC_EX_PARRY|PROC_EX_BLOCK))
ToPlayer()->UpdateCombatSkills(target, attType, true);
}
// If exist crit/parry/dodge/block need update aura state (for victim and attacker)
if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK))
{
// for victim
if (isVictim)
{
// if victim and dodge attack
if (procExtra & PROC_EX_DODGE)
{
// Update AURA_STATE on dodge
if (getClass() != CLASS_ROGUE) // skip Rogue Riposte
{
ModifyAuraState(AURA_STATE_DEFENSE, true);
StartReactiveTimer(REACTIVE_DEFENSE);
}
}
// if victim and parry attack
if (procExtra & PROC_EX_PARRY)
{
// For Hunters only Counterattack (skip Mongoose bite)
if (getClass() == CLASS_HUNTER)
{
ModifyAuraState(AURA_STATE_HUNTER_PARRY, true);
StartReactiveTimer(REACTIVE_HUNTER_PARRY);
}
else
{
ModifyAuraState(AURA_STATE_DEFENSE, true);
StartReactiveTimer(REACTIVE_DEFENSE);
}
}
// if and victim block attack
if (procExtra & PROC_EX_BLOCK)
{
ModifyAuraState(AURA_STATE_DEFENSE, true);
StartReactiveTimer(REACTIVE_DEFENSE);
}
}
else // For attacker
{
// Overpower on victim dodge
if (procExtra & PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR)
{
ToPlayer()->AddComboPoints(target, 1);
StartReactiveTimer(REACTIVE_OVERPOWER);
}
}
}
}
ProcTriggeredList procTriggered;
// Fill procTriggered list
for (AuraApplicationMap::const_iterator itr = GetAppliedAuras().begin(); itr!= GetAppliedAuras().end(); ++itr)
{
// Do not allow auras to proc from effect triggered by itself
if (procAura && procAura->Id == itr->first)
continue;
ProcTriggeredData triggerData(itr->second->GetBase());
// Defensive procs are active on absorbs (so absorption effects are not a hindrance)
bool active = (damage > 0) || (procExtra & (PROC_EX_ABSORB|PROC_EX_BLOCK) && isVictim);
if (isVictim)
procExtra &= ~PROC_EX_INTERNAL_REQ_FAMILY;
SpellInfo const* spellProto = itr->second->GetBase()->GetSpellInfo();
if (!IsTriggeredAtSpellProcEvent(target, triggerData.aura, procSpell, procFlag, procExtra, attType, isVictim, active, triggerData.spellProcEvent))
continue;
// Triggered spells not triggering additional spells
bool triggered = !(spellProto->AttributesEx3 & SPELL_ATTR3_CAN_PROC_WITH_TRIGGERED) ?
(procExtra & PROC_EX_INTERNAL_TRIGGERED && !(procFlag & PROC_FLAG_DONE_TRAP_ACTIVATION)) : false;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (itr->second->HasEffect(i))
{
AuraEffect* aurEff = itr->second->GetBase()->GetEffect(i);
// Skip this auras
if (isNonTriggerAura[aurEff->GetAuraType()])
continue;
// If not trigger by default and spellProcEvent == NULL - skip
if (!isTriggerAura[aurEff->GetAuraType()] && triggerData.spellProcEvent == NULL)
continue;
// Some spells must always trigger
if (!triggered || isAlwaysTriggeredAura[aurEff->GetAuraType()])
triggerData.effMask |= 1<<i;
}
}
if (triggerData.effMask)
procTriggered.push_front(triggerData);
}
// Nothing found
if (procTriggered.empty())
return;
if (procExtra & (PROC_EX_INTERNAL_TRIGGERED | PROC_EX_INTERNAL_CANT_PROC))
SetCantProc(true);
// Handle effects proceed this time
for (ProcTriggeredList::const_iterator i = procTriggered.begin(); i != procTriggered.end(); ++i)
{
// look for aura in auras list, it may be removed while proc event processing
if (i->aura->IsRemoved())
continue;
bool useCharges = i->aura->IsUsingCharges();
// no more charges to use, prevent proc
if (useCharges && !i->aura->GetCharges())
continue;
bool takeCharges = false;
SpellInfo const* spellInfo = i->aura->GetSpellInfo();
uint32 Id = i->aura->GetId();
// For players set spell cooldown if need
uint32 cooldown = 0;
if (GetTypeId() == TYPEID_PLAYER && i->spellProcEvent && i->spellProcEvent->cooldown)
cooldown = i->spellProcEvent->cooldown;
if (spellInfo->AttributesEx3 & SPELL_ATTR3_DISABLE_PROC)
SetCantProc(true);
// This bool is needed till separate aura effect procs are still here
bool handled = false;
if (HandleAuraProc(target, damage, i->aura, procSpell, procFlag, procExtra, cooldown, &handled))
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), Id);
takeCharges = true;
}
if (!handled)
for (uint8 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex)
{
if (!(i->effMask & (1<<effIndex)))
continue;
AuraEffect* triggeredByAura = i->aura->GetEffect(effIndex);
ASSERT(triggeredByAura);
switch (triggeredByAura->GetAuraType())
{
case SPELL_AURA_PROC_TRIGGER_SPELL:
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
// Don`t drop charge or add cooldown for not started trigger
if (HandleProcTriggerSpell(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
takeCharges = true;
break;
}
case SPELL_AURA_PROC_TRIGGER_DAMAGE:
{
// target has to be valid
if (!target)
return;
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: doing %u damage from spell id %u (triggered by %s aura of spell %u)", triggeredByAura->GetAmount(), spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
SpellNonMeleeDamage damageInfo(this, target, spellInfo->Id, spellInfo->SchoolMask);
uint32 newDamage = SpellDamageBonus(target, spellInfo, triggeredByAura->GetAmount(), SPELL_DIRECT_DAMAGE);
CalculateSpellDamageTaken(&damageInfo, newDamage, spellInfo);
DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb);
SendSpellNonMeleeDamageLog(&damageInfo);
DealSpellDamage(&damageInfo, true);
takeCharges = true;
break;
}
case SPELL_AURA_MANA_SHIELD:
case SPELL_AURA_DUMMY:
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s dummy aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
if (HandleDummyAuraProc(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
takeCharges = true;
break;
}
case SPELL_AURA_OBS_MOD_POWER:
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
if (HandleObsModEnergyAuraProc(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
takeCharges = true;
break;
case SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN:
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
if (HandleModDamagePctTakenAuraProc(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
takeCharges = true;
break;
case SPELL_AURA_MOD_MELEE_HASTE:
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s haste aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
if (HandleHasteAuraProc(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
takeCharges = true;
break;
}
case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
if (HandleOverrideClassScriptAuraProc(target, damage, triggeredByAura, procSpell, cooldown))
takeCharges = true;
break;
}
case SPELL_AURA_RAID_PROC_FROM_CHARGE_WITH_VALUE:
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
HandleAuraRaidProcFromChargeWithValue(triggeredByAura);
takeCharges = true;
break;
}
case SPELL_AURA_RAID_PROC_FROM_CHARGE:
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
HandleAuraRaidProcFromCharge(triggeredByAura);
takeCharges = true;
break;
}
case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
if (HandleProcTriggerSpell(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
takeCharges = true;
break;
}
case SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK:
// Skip melee hits or instant cast spells
if (procSpell && procSpell->CalcCastTime() != 0)
takeCharges = true;
break;
case SPELL_AURA_REFLECT_SPELLS_SCHOOL:
// Skip Melee hits and spells ws wrong school
if (procSpell && (triggeredByAura->GetMiscValue() & procSpell->SchoolMask)) // School check
takeCharges = true;
break;
case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT:
case SPELL_AURA_MOD_POWER_COST_SCHOOL:
// Skip melee hits and spells ws wrong school or zero cost
if (procSpell &&
(procSpell->ManaCost != 0 || procSpell->ManaCostPercentage != 0) && // Cost check
(triggeredByAura->GetMiscValue() & procSpell->SchoolMask)) // School check
takeCharges = true;
break;
case SPELL_AURA_MECHANIC_IMMUNITY:
// Compare mechanic
if (procSpell && procSpell->Mechanic == uint32(triggeredByAura->GetMiscValue()))
takeCharges = true;
break;
case SPELL_AURA_MOD_MECHANIC_RESISTANCE:
// Compare mechanic
if (procSpell && procSpell->Mechanic == uint32(triggeredByAura->GetMiscValue()))
takeCharges = true;
break;
case SPELL_AURA_MOD_DAMAGE_FROM_CASTER:
// Compare casters
if (triggeredByAura->GetCasterGUID() == target->GetGUID())
takeCharges = true;
break;
case SPELL_AURA_MOD_SPELL_CRIT_CHANCE:
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s spell crit chance aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
if (procSpell && HandleSpellCritChanceAuraProc(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
takeCharges = true;
break;
// CC Auras which use their amount amount to drop
// Are there any more auras which need this?
case SPELL_AURA_MOD_CONFUSE:
case SPELL_AURA_MOD_FEAR:
case SPELL_AURA_MOD_STUN:
case SPELL_AURA_MOD_ROOT:
case SPELL_AURA_TRANSFORM:
{
// chargeable mods are breaking on hit
if (useCharges)
takeCharges = true;
else
{
// Spell own direct damage at apply wont break the CC
if (procSpell && (procSpell->Id == triggeredByAura->GetId()))
{
Aura* aura = triggeredByAura->GetBase();
// called from spellcast, should not have ticked yet
if (aura->GetDuration() == aura->GetMaxDuration())
break;
}
int32 damageLeft = triggeredByAura->GetAmount();
// No damage left
if (damageLeft < int32(damage))
i->aura->Remove();
else
triggeredByAura->SetAmount(damageLeft - damage);
}
break;
}
//case SPELL_AURA_ADD_FLAT_MODIFIER:
//case SPELL_AURA_ADD_PCT_MODIFIER:
// HandleSpellModAuraProc
//break;
default:
// nothing do, just charges counter
takeCharges = true;
break;
}
}
// Remove charge (aura can be removed by triggers)
if (useCharges && takeCharges)
i->aura->DropCharge(AURA_REMOVE_BY_EXPIRE);
if (spellInfo->AttributesEx3 & SPELL_ATTR3_DISABLE_PROC)
SetCantProc(false);
}
// Cleanup proc requirements
if (procExtra & (PROC_EX_INTERNAL_TRIGGERED | PROC_EX_INTERNAL_CANT_PROC))
SetCantProc(false);
}
void Unit::GetProcAurasTriggeredOnEvent(std::list<AuraApplication*>& aurasTriggeringProc, std::list<AuraApplication*>* procAuras, ProcEventInfo eventInfo)
{
// use provided list of auras which can proc
if (procAuras)
{
for (std::list<AuraApplication*>::iterator itr = procAuras->begin(); itr!= procAuras->end(); ++itr)
{
ASSERT((*itr)->GetTarget() == this);
if (!(*itr)->GetRemoveMode())
if ((*itr)->GetBase()->IsProcTriggeredOnEvent(*itr, eventInfo))
{
(*itr)->GetBase()->PrepareProcToTrigger();
aurasTriggeringProc.push_back(*itr);
}
}
}
// or generate one on our own
else
{
for (AuraApplicationMap::iterator itr = GetAppliedAuras().begin(); itr!= GetAppliedAuras().end(); ++itr)
{
if (itr->second->GetBase()->IsProcTriggeredOnEvent(itr->second, eventInfo))
{
itr->second->GetBase()->PrepareProcToTrigger();
aurasTriggeringProc.push_back(itr->second);
}
}
}
}
void Unit::TriggerAurasProcOnEvent(CalcDamageInfo& damageInfo)
{
DamageInfo dmgInfo = DamageInfo(damageInfo);
TriggerAurasProcOnEvent(NULL, NULL, damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, 0, 0, damageInfo.procEx, NULL, &dmgInfo, NULL);
}
void Unit::TriggerAurasProcOnEvent(std::list<AuraApplication*>* myProcAuras, std::list<AuraApplication*>* targetProcAuras, Unit* actionTarget, uint32 typeMaskActor, uint32 typeMaskActionTarget, uint32 spellTypeMask, uint32 spellPhaseMask, uint32 hitMask, Spell* spell, DamageInfo* damageInfo, HealInfo* healInfo)
{
// prepare data for self trigger
ProcEventInfo myProcEventInfo = ProcEventInfo(this, actionTarget, actionTarget, typeMaskActor, spellTypeMask, spellPhaseMask, hitMask, spell, damageInfo, healInfo);
std::list<AuraApplication*> myAurasTriggeringProc;
GetProcAurasTriggeredOnEvent(myAurasTriggeringProc, myProcAuras, myProcEventInfo);
// prepare data for target trigger
ProcEventInfo targetProcEventInfo = ProcEventInfo(this, actionTarget, this, typeMaskActionTarget, spellTypeMask, spellPhaseMask, hitMask, spell, damageInfo, healInfo);
std::list<AuraApplication*> targetAurasTriggeringProc;
if (typeMaskActionTarget)
GetProcAurasTriggeredOnEvent(targetAurasTriggeringProc, targetProcAuras, targetProcEventInfo);
TriggerAurasProcOnEvent(myProcEventInfo, myAurasTriggeringProc);
if (typeMaskActionTarget)
TriggerAurasProcOnEvent(targetProcEventInfo, targetAurasTriggeringProc);
}
void Unit::TriggerAurasProcOnEvent(ProcEventInfo& eventInfo, std::list<AuraApplication*>& aurasTriggeringProc)
{
for (std::list<AuraApplication*>::iterator itr = aurasTriggeringProc.begin(); itr != aurasTriggeringProc.end(); ++itr)
{
if (!(*itr)->GetRemoveMode())
(*itr)->GetBase()->TriggerProcOnEvent(*itr, eventInfo);
}
}
SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const
{
return SPELL_SCHOOL_MASK_NORMAL;
}
Player* Unit::GetSpellModOwner() const
{
if (GetTypeId() == TYPEID_PLAYER)
return (Player*)this;
if (ToCreature()->isPet() || ToCreature()->isTotem())
{
Unit* owner = GetOwner();
if (owner && owner->GetTypeId() == TYPEID_PLAYER)
return (Player*)owner;
}
return NULL;
}
///----------Pet responses methods-----------------
void Unit::SendPetCastFail(uint32 spellid, SpellCastResult msg)
{
if (msg == SPELL_CAST_OK)
return;
Unit* owner = GetCharmerOrOwner();
if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
return;
WorldPacket data(SMSG_PET_CAST_FAILED, 1 + 4 + 1);
data << uint8(0); // cast count?
data << uint32(spellid);
data << uint8(msg);
// uint32 for some reason
// uint32 for some reason
owner->ToPlayer()->GetSession()->SendPacket(&data);
}
void Unit::SendPetActionFeedback (uint8 msg)
{
Unit* owner = GetOwner();
if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
return;
WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1);
data << uint8(msg);
owner->ToPlayer()->GetSession()->SendPacket(&data);
}
void Unit::SendPetTalk (uint32 pettalk)
{
Unit* owner = GetOwner();
if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
return;
WorldPacket data(SMSG_PET_ACTION_SOUND, 8 + 4);
data << uint64(GetGUID());
data << uint32(pettalk);
owner->ToPlayer()->GetSession()->SendPacket(&data);
}
void Unit::SendPetAIReaction(uint64 guid)
{
Unit* owner = GetOwner();
if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
return;
WorldPacket data(SMSG_AI_REACTION, 8 + 4);
data << uint64(guid);
data << uint32(AI_REACTION_HOSTILE);
owner->ToPlayer()->GetSession()->SendPacket(&data);
}
///----------End of Pet responses methods----------
void Unit::StopMoving()
{
ClearUnitState(UNIT_STAT_MOVING);
// send explicit stop packet
// rely on vmaps here because for example stormwind is in air
//float z = sMapMgr->GetBaseMap(GetMapId())->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), true);
//if (fabs(GetPositionZ() - z) < 2.0f)
// Relocate(GetPositionX(), GetPositionY(), z);
//Relocate(GetPositionX(), GetPositionY(), GetPositionZ());
if (!(GetUnitMovementFlags() & MOVEMENTFLAG_ONTRANSPORT))
SendMonsterStop();
}
void Unit::SendMovementFlagUpdate()
{
WorldPacket data;
BuildHeartBeatMsg(&data);
SendMessageToSet(&data, false);
}
bool Unit::IsSitState() const
{
uint8 s = getStandState();
return
s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR ||
s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR ||
s == UNIT_STAND_STATE_SIT;
}
bool Unit::IsStandState() const
{
uint8 s = getStandState();
return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL;
}
void Unit::SetStandState(uint8 state)
{
SetByteValue(UNIT_FIELD_BYTES_1, 0, state);
if (IsStandState())
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED);
if (GetTypeId() == TYPEID_PLAYER)
{
WorldPacket data(SMSG_STANDSTATE_UPDATE, 1);
data << (uint8)state;
ToPlayer()->GetSession()->SendPacket(&data);
}
}
bool Unit::IsPolymorphed() const
{
uint32 transformId = getTransForm();
if (!transformId)
return false;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(transformId);
if (!spellInfo)
return false;
return spellInfo->GetSpellSpecific() == SPELL_SPECIFIC_MAGE_POLYMORPH;
}
void Unit::SetDisplayId(uint32 modelId)
{
SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId);
if (GetTypeId() == TYPEID_UNIT && ToCreature()->isPet())
{
Pet* pet = ToPet();
if (!pet->isControlled())
return;
Unit* owner = GetOwner();
if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup())
owner->ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID);
}
}
void Unit::RestoreDisplayId()
{
AuraEffect* handledAura = NULL;
// try to receive model from transform auras
Unit::AuraEffectList const& transforms = GetAuraEffectsByType(SPELL_AURA_TRANSFORM);
if (!transforms.empty())
{
// iterate over already applied transform auras - from newest to oldest
for (Unit::AuraEffectList::const_reverse_iterator i = transforms.rbegin(); i != transforms.rend(); ++i)
{
if (AuraApplication const* aurApp = (*i)->GetBase()->GetApplicationOfTarget(GetGUID()))
{
if (!handledAura)
handledAura = (*i);
// prefer negative auras
if (!aurApp->IsPositive())
{
handledAura = (*i);
break;
}
}
}
}
// transform aura was found
if (handledAura)
handledAura->HandleEffect(this, AURA_EFFECT_HANDLE_SEND_FOR_CLIENT, true);
// we've found shapeshift
else if (uint32 modelId = GetModelForForm(GetShapeshiftForm()))
SetDisplayId(modelId);
// no auras found - set modelid to default
else
SetDisplayId(GetNativeDisplayId());
}
void Unit::ClearComboPointHolders()
{
while (!m_ComboPointHolders.empty())
{
uint32 lowguid = *m_ComboPointHolders.begin();
Player* player = ObjectAccessor::FindPlayer(MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER));
if (player && player->GetComboTarget() == GetGUID()) // recheck for safe
player->ClearComboPoints(); // remove also guid from m_ComboPointHolders;
else
m_ComboPointHolders.erase(lowguid); // or remove manually
}
}
void Unit::ClearAllReactives()
{
for (uint8 i = 0; i < MAX_REACTIVE; ++i)
m_reactiveTimer[i] = 0;
if (HasAuraState(AURA_STATE_DEFENSE))
ModifyAuraState(AURA_STATE_DEFENSE, false);
if (getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
if (getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
ToPlayer()->ClearComboPoints();
}
void Unit::UpdateReactives(uint32 p_time)
{
for (uint8 i = 0; i < MAX_REACTIVE; ++i)
{
ReactiveType reactive = ReactiveType(i);
if (!m_reactiveTimer[reactive])
continue;
if (m_reactiveTimer[reactive] <= p_time)
{
m_reactiveTimer[reactive] = 0;
switch (reactive)
{
case REACTIVE_DEFENSE:
if (HasAuraState(AURA_STATE_DEFENSE))
ModifyAuraState(AURA_STATE_DEFENSE, false);
break;
case REACTIVE_HUNTER_PARRY:
if (getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
break;
case REACTIVE_OVERPOWER:
if (getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
ToPlayer()->ClearComboPoints();
break;
default:
break;
}
}
else
{
m_reactiveTimer[reactive] -= p_time;
}
}
}
Unit* Unit::SelectNearbyTarget(float dist) const
{
std::list<Unit*> targets;
Trinity::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, dist);
Trinity::UnitListSearcher<Trinity::AnyUnfriendlyUnitInObjectRangeCheck> searcher(this, targets, u_check);
VisitNearbyObject(dist, searcher);
// remove current target
if (getVictim())
targets.remove(getVictim());
// remove not LoS targets
for (std::list<Unit*>::iterator tIter = targets.begin(); tIter != targets.end();)
{
if (!IsWithinLOSInMap(*tIter) || (*tIter)->isTotem() || (*tIter)->isSpiritService() || (*tIter)->GetCreatureType() == CREATURE_TYPE_CRITTER)
targets.erase(tIter++);
else
++tIter;
}
// no appropriate targets
if (targets.empty())
return NULL;
// select random
return SelectRandomContainerElement(targets);
}
void Unit::ApplyAttackTimePercentMod(WeaponAttackType att, float val, bool apply)
{
float remainingTimePct = (float)m_attackTimer[att] / (GetAttackTime(att) * m_modAttackSpeedPct[att]);
if (val > 0)
{
ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply);
ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att, val, !apply);
}
else
{
ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply);
ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att, -val, apply);
}
m_attackTimer[att] = uint32(GetAttackTime(att) * m_modAttackSpeedPct[att] * remainingTimePct);
}
void Unit::ApplyCastTimePercentMod(float val, bool apply)
{
if (val > 0)
ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED, val, !apply);
else
ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED, -val, apply);
}
uint32 Unit::GetCastingTimeForBonus(SpellInfo const* spellProto, DamageEffectType damagetype, uint32 CastingTime)
{
// Not apply this to creature casted spells with casttime == 0
if (CastingTime == 0 && GetTypeId() == TYPEID_UNIT && !ToCreature()->isPet())
return 3500;
if (CastingTime > 7000) CastingTime = 7000;
if (CastingTime < 1500) CastingTime = 1500;
if (damagetype == DOT && !spellProto->IsChanneled())
CastingTime = 3500;
int32 overTime = 0;
uint8 effects = 0;
bool DirectDamage = false;
bool AreaEffect = false;
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; i++)
{
switch (spellProto->Effects[i].Effect)
{
case SPELL_EFFECT_SCHOOL_DAMAGE:
case SPELL_EFFECT_POWER_DRAIN:
case SPELL_EFFECT_HEALTH_LEECH:
case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE:
case SPELL_EFFECT_POWER_BURN:
case SPELL_EFFECT_HEAL:
DirectDamage = true;
break;
case SPELL_EFFECT_APPLY_AURA:
switch (spellProto->Effects[i].ApplyAuraName)
{
case SPELL_AURA_PERIODIC_DAMAGE:
case SPELL_AURA_PERIODIC_HEAL:
case SPELL_AURA_PERIODIC_LEECH:
if (spellProto->GetDuration())
overTime = spellProto->GetDuration();
break;
default:
// -5% per additional effect
++effects;
break;
}
default:
break;
}
if (spellProto->Effects[i].IsArea())
AreaEffect = true;
}
// Combined Spells with Both Over Time and Direct Damage
if (overTime > 0 && CastingTime > 0 && DirectDamage)
{
// mainly for DoTs which are 3500 here otherwise
uint32 OriginalCastTime = spellProto->CalcCastTime();
if (OriginalCastTime > 7000) OriginalCastTime = 7000;
if (OriginalCastTime < 1500) OriginalCastTime = 1500;
// Portion to Over Time
float PtOT = (overTime / 15000.0f) / ((overTime / 15000.0f) + (OriginalCastTime / 3500.0f));
if (damagetype == DOT)
CastingTime = uint32(CastingTime * PtOT);
else if (PtOT < 1.0f)
CastingTime = uint32(CastingTime * (1 - PtOT));
else
CastingTime = 0;
}
// Area Effect Spells receive only half of bonus
if (AreaEffect)
CastingTime /= 2;
// -5% of total per any additional effect
for (uint8 i = 0; i < effects; ++i)
{
if (CastingTime > 175)
{
CastingTime -= 175;
}
else
{
CastingTime = 0;
break;
}
}
return CastingTime;
}
void Unit::UpdateAuraForGroup(uint8 slot)
{
if (slot >= MAX_AURAS) // slot not found, return
return;
if (Player* player = ToPlayer())
{
if (player->GetGroup())
{
player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS);
player->SetAuraUpdateMaskForRaid(slot);
}
}
else if (GetTypeId() == TYPEID_UNIT && ToCreature()->isPet())
{
Pet* pet = ((Pet*)this);
if (pet->isControlled())
{
Unit* owner = GetOwner();
if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup())
{
owner->ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_AURAS);
pet->SetAuraUpdateMaskForRaid(slot);
}
}
}
}
float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized)
{
if (!normalized || GetTypeId() != TYPEID_PLAYER)
return float(GetAttackTime(attType)) / 1000.0f;
Item* Weapon = ToPlayer()->GetWeaponForAttack(attType, true);
if (!Weapon)
return 2.4f; // fist attack
switch (Weapon->GetTemplate()->InventoryType)
{
case INVTYPE_2HWEAPON:
return 3.3f;
case INVTYPE_RANGED:
case INVTYPE_RANGEDRIGHT:
case INVTYPE_THROWN:
return 2.8f;
case INVTYPE_WEAPON:
case INVTYPE_WEAPONMAINHAND:
case INVTYPE_WEAPONOFFHAND:
default:
return Weapon->GetTemplate()->SubClass == ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7f : 2.4f;
}
}
bool Unit::IsUnderLastManaUseEffect() const
{
return getMSTimeDiff(m_lastManaUse, getMSTime()) < 5000;
}
void Unit::SetContestedPvP(Player* attackedPlayer)
{
Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
if (!player || (attackedPlayer && (attackedPlayer == player || (player->duel && player->duel->opponent == attackedPlayer))))
return;
player->SetContestedPvPTimer(30000);
if (!player->HasUnitState(UNIT_STAT_ATTACK_PLAYER))
{
player->AddUnitState(UNIT_STAT_ATTACK_PLAYER);
player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
// call MoveInLineOfSight for nearby contested guards
UpdateObjectVisibility();
}
if (!HasUnitState(UNIT_STAT_ATTACK_PLAYER))
{
AddUnitState(UNIT_STAT_ATTACK_PLAYER);
// call MoveInLineOfSight for nearby contested guards
UpdateObjectVisibility();
}
}
void Unit::AddPetAura(PetAura const* petSpell)
{
if (GetTypeId() != TYPEID_PLAYER)
return;
m_petAuras.insert(petSpell);
if (Pet* pet = ToPlayer()->GetPet())
pet->CastPetAura(petSpell);
}
void Unit::RemovePetAura(PetAura const* petSpell)
{
if (GetTypeId() != TYPEID_PLAYER)
return;
m_petAuras.erase(petSpell);
if (Pet* pet = ToPlayer()->GetPet())
pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
}
Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget, uint32 spell_id)
{
if (GetTypeId() != TYPEID_PLAYER)
return NULL;
Pet* pet = new Pet((Player*)this, HUNTER_PET);
if (!pet->CreateBaseAtCreature(creatureTarget))
{
delete pet;
return NULL;
}
uint8 level = creatureTarget->getLevel() + 5 < getLevel() ? (getLevel() - 5) : creatureTarget->getLevel();
InitTamedPet(pet, level, spell_id);
return pet;
}
Pet* Unit::CreateTamedPetFrom(uint32 creatureEntry, uint32 spell_id)
{
if (GetTypeId() != TYPEID_PLAYER)
return NULL;
CreatureTemplate const* creatureInfo = sObjectMgr->GetCreatureTemplate(creatureEntry);
if (!creatureInfo)
return NULL;
Pet* pet = new Pet((Player*)this, HUNTER_PET);
if (!pet->CreateBaseAtCreatureInfo(creatureInfo, this) || !InitTamedPet(pet, getLevel(), spell_id))
{
delete pet;
return NULL;
}
return pet;
}
bool Unit::InitTamedPet(Pet* pet, uint8 level, uint32 spell_id)
{
pet->SetCreatorGUID(GetGUID());
pet->setFaction(getFaction());
pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
if (GetTypeId() == TYPEID_PLAYER)
pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
if (!pet->InitStatsForLevel(level))
{
sLog->outError("Pet::InitStatsForLevel() failed for creature (Entry: %u)!", pet->GetEntry());
return false;
}
pet->GetCharmInfo()->SetPetNumber(sObjectMgr->GeneratePetNumber(), true);
// this enables pet details window (Shift+P)
pet->InitPetCreateSpells();
//pet->InitLevelupSpellsForLevel();
pet->SetFullHealth();
return true;
}
bool Unit::IsTriggeredAtSpellProcEvent(Unit* victim, Aura* aura, SpellInfo const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const* & spellProcEvent)
{
SpellInfo const* spellProto = aura->GetSpellInfo();
// let the aura be handled by new proc system if it has new entry
if (sSpellMgr->GetSpellProcEntry(spellProto->Id))
return false;
// Get proc Event Entry
spellProcEvent = sSpellMgr->GetSpellProcEvent(spellProto->Id);
// Get EventProcFlag
uint32 EventProcFlag;
if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
EventProcFlag = spellProcEvent->procFlags;
else
EventProcFlag = spellProto->ProcFlags; // else get from spell proto
// Continue if no trigger exist
if (!EventProcFlag)
return false;
// Additional checks for triggered spells (ignore trap casts)
if (procExtra & PROC_EX_INTERNAL_TRIGGERED && !(procFlag & PROC_FLAG_DONE_TRAP_ACTIVATION))
{
if (!(spellProto->AttributesEx3 & SPELL_ATTR3_CAN_PROC_WITH_TRIGGERED))
return false;
}
// Check spellProcEvent data requirements
if (!sSpellMgr->IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active))
return false;
// In most cases req get honor or XP from kill
if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
{
bool allow = false;
if (victim)
allow = ToPlayer()->isHonorOrXPTarget(victim);
// Shadow Word: Death - can trigger from every kill
if (aura->GetId() == 32409)
allow = true;
if (!allow)
return false;
}
// Aura added by spell can`t trigger from self (prevent drop charges/do triggers)
// But except periodic and kill triggers (can triggered from self)
if (procSpell && procSpell->Id == spellProto->Id
&& !(spellProto->ProcFlags&(PROC_FLAG_TAKEN_PERIODIC | PROC_FLAG_KILL)))
return false;
// Check if current equipment allows aura to proc
if (!isVictim && GetTypeId() == TYPEID_PLAYER)
{
Player* player = ToPlayer();
if (spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
{
Item* item = NULL;
if (attType == BASE_ATTACK)
item = player->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
else if (attType == OFF_ATTACK)
item = player->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
else
item = player->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
if (player->IsInFeralForm())
return false;
if (!item || item->IsBroken() || item->GetTemplate()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetTemplate()->SubClass) & spellProto->EquippedItemSubClassMask))
return false;
}
else if (spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
{
// Check if player is wearing shield
Item* item = player->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
if (!item || item->IsBroken() || item->GetTemplate()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetTemplate()->SubClass) & spellProto->EquippedItemSubClassMask))
return false;
}
}
// Get chance from spell
float chance = float(spellProto->ProcChance);
// If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
if (spellProcEvent && spellProcEvent->customChance)
chance = spellProcEvent->customChance;
// If PPM exist calculate chance from PPM
if (spellProcEvent && spellProcEvent->ppmRate != 0)
{
if (!isVictim)
{
uint32 WeaponSpeed = GetAttackTime(attType);
chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate, spellProto);
}
else
{
uint32 WeaponSpeed = victim->GetAttackTime(attType);
chance = victim->GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate, spellProto);
}
}
// Apply chance modifer aura
if (Player* modOwner = GetSpellModOwner())
{
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CHANCE_OF_SUCCESS, chance);
}
return roll_chance_f(chance);
}
bool Unit::HandleAuraRaidProcFromChargeWithValue(AuraEffect* triggeredByAura)
{
// aura can be deleted at casts
SpellInfo const* spellProto = triggeredByAura->GetSpellInfo();
int32 heal = triggeredByAura->GetAmount();
uint64 caster_guid = triggeredByAura->GetCasterGUID();
// Currently only Prayer of Mending
if (!(spellProto->SpellFamilyName == SPELLFAMILY_PRIEST && spellProto->SpellFamilyFlags[1] & 0x20))
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Unit::HandleAuraRaidProcFromChargeWithValue, received not handled spell: %u", spellProto->Id);
return false;
}
// jumps
int32 jumps = triggeredByAura->GetBase()->GetCharges()-1;
// current aura expire
triggeredByAura->GetBase()->SetCharges(1); // will removed at next charges decrease
// next target selection
if (jumps > 0)
{
if (Unit* caster = triggeredByAura->GetCaster())
{
float radius = triggeredByAura->GetSpellInfo()->Effects[triggeredByAura->GetEffIndex()].CalcRadius(caster);
if (Unit* target = GetNextRandomRaidMemberOrPet(radius))
{
CastCustomSpell(target, spellProto->Id, &heal, NULL, NULL, true, NULL, triggeredByAura, caster_guid);
if (Aura* aura = target->GetAura(spellProto->Id, caster->GetGUID()))
aura->SetCharges(jumps);
}
}
}
// heal
CastCustomSpell(this, 33110, &heal, NULL, NULL, true, NULL, NULL, caster_guid);
return true;
}
bool Unit::HandleAuraRaidProcFromCharge(AuraEffect* triggeredByAura)
{
// aura can be deleted at casts
SpellInfo const* spellProto = triggeredByAura->GetSpellInfo();
uint32 damageSpellId;
switch (spellProto->Id)
{
case 57949: // shiver
damageSpellId = 57952;
//animationSpellId = 57951; dummy effects for jump spell have unknown use (see also 41637)
break;
case 59978: // shiver
damageSpellId = 59979;
break;
case 43593: // Cold Stare
damageSpellId = 43594;
break;
default:
sLog->outError("Unit::HandleAuraRaidProcFromCharge, received not handled spell: %u", spellProto->Id);
return false;
}
uint64 caster_guid = triggeredByAura->GetCasterGUID();
// jumps
int32 jumps = triggeredByAura->GetBase()->GetCharges()-1;
// current aura expire
triggeredByAura->GetBase()->SetCharges(1); // will removed at next charges decrease
// next target selection
if (jumps > 0)
{
if (Unit* caster = triggeredByAura->GetCaster())
{
float radius = triggeredByAura->GetSpellInfo()->Effects[triggeredByAura->GetEffIndex()].CalcRadius(caster);
if (Unit* target= GetNextRandomRaidMemberOrPet(radius))
{
CastSpell(target, spellProto, true, NULL, triggeredByAura, caster_guid);
if (Aura* aura = target->GetAura(spellProto->Id, caster->GetGUID()))
aura->SetCharges(jumps);
}
}
}
CastSpell(this, damageSpellId, true, NULL, triggeredByAura, caster_guid);
return true;
}
void Unit::Kill(Unit* victim, bool durabilityLoss)
{
// Prevent killing unit twice (and giving reward from kill twice)
if (!victim->GetHealth())
return;
// Inform pets (if any) when player kills target)
if (Player* player = ToPlayer())
{
Pet* pet = player->GetPet();
if (pet && pet->isAlive() && pet->isControlled())
pet->AI()->KilledUnit(victim);
}
// find player: owner of controlled `this` or `this` itself maybe
Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
Creature* creature = victim->ToCreature();
bool isRewardAllowed = true;
if (creature)
{
isRewardAllowed = creature->IsDamageEnoughForLootingAndReward();
if (!isRewardAllowed)
creature->SetLootRecipient(NULL);
}
if (isRewardAllowed && creature && creature->GetLootRecipient())
player = creature->GetLootRecipient();
// Reward player, his pets, and group/raid members
// call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop)
if (isRewardAllowed && player && player != victim)
{
WorldPacket data(SMSG_PARTYKILLLOG, (8+8)); // send event PARTY_KILL
data << uint64(player->GetGUID()); // player with killing blow
data << uint64(victim->GetGUID()); // victim
Player* looter = player;
if (Group* group = player->GetGroup())
{
group->BroadcastPacket(&data, group->GetMemberGroup(player->GetGUID()));
if (creature)
{
group->UpdateLooterGuid(creature, true);
if (group->GetLooterGuid())
{
looter = ObjectAccessor::FindPlayer(group->GetLooterGuid());
if (looter)
{
creature->SetLootRecipient(looter); // update creature loot recipient to the allowed looter.
group->SendLooter(creature, looter);
}
else
group->SendLooter(creature, NULL);
}
else
group->SendLooter(creature, NULL);
group->UpdateLooterGuid(creature);
}
}
else
{
player->SendDirectMessage(&data);
if (creature)
{
WorldPacket data2(SMSG_LOOT_LIST, 8 + 1 + 1);
data2 << uint64(creature->GetGUID());
data2 << uint8(0); // unk1
data2 << uint8(0); // no group looter
player->SendMessageToSet(&data2, true);
}
}
if (creature)
{
Loot* loot = &creature->loot;
if (creature->lootForPickPocketed)
creature->lootForPickPocketed = false;
loot->clear();
if (uint32 lootid = creature->GetCreatureInfo()->lootid)
loot->FillLoot(lootid, LootTemplates_Creature, looter, false, false, creature->GetLootMode());
loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold, creature->GetCreatureInfo()->maxgold);
}
player->RewardPlayerAndGroupAtKill(victim, false);
}
// Do KILL and KILLED procs. KILL proc is called only for the unit who landed the killing blow (and its owner - for pets and totems) regardless of who tapped the victim
if (isPet() || isTotem())
if (Unit* owner = GetOwner())
owner->ProcDamageAndSpell(victim, PROC_FLAG_KILL, PROC_FLAG_NONE, PROC_EX_NONE, 0);
if (victim->GetCreatureType() != CREATURE_TYPE_CRITTER)
ProcDamageAndSpell(victim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0);
// Proc auras on death - must be before aura/combat remove
victim->ProcDamageAndSpell(NULL, PROC_FLAG_DEATH, PROC_FLAG_NONE, PROC_EX_NONE, 0, BASE_ATTACK, 0);
// update get killing blow achievements, must be done before setDeathState to be able to require auras on target
// and before Spirit of Redemption as it also removes auras
if (player)
player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS, 1, 0, victim);
// if talent known but not triggered (check priest class for speedup check)
bool spiritOfRedemption = false;
if (victim->GetTypeId() == TYPEID_PLAYER && victim->getClass() == CLASS_PRIEST)
{
AuraEffectList const& dummyAuras = victim->GetAuraEffectsByType(SPELL_AURA_DUMMY);
for (AuraEffectList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
{
if ((*itr)->GetSpellInfo()->SpellIconID == 1654)
{
AuraEffect const* aurEff = *itr;
// save value before aura remove
uint32 ressSpellId = victim->GetUInt32Value(PLAYER_SELF_RES_SPELL);
if (!ressSpellId)
ressSpellId = victim->ToPlayer()->GetResurrectionSpellId();
// Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers)
victim->RemoveAllAurasOnDeath();
// restore for use at real death
victim->SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
// FORM_SPIRITOFREDEMPTION and related auras
victim->CastSpell(victim, 27827, true, NULL, aurEff);
spiritOfRedemption = true;
break;
}
}
}
if (!spiritOfRedemption)
{
sLog->outStaticDebug("SET JUST_DIED");
victim->setDeathState(JUST_DIED);
}
// 10% durability loss on death
// clean InHateListOf
if (Player* plrVictim = victim->ToPlayer())
{
// remember victim PvP death for corpse type and corpse reclaim delay
// at original death (not at SpiritOfRedemtionTalent timeout)
plrVictim->SetPvPDeath(player != NULL);
// only if not player and not controlled by player pet. And not at BG
if ((durabilityLoss && !player && !victim->ToPlayer()->InBattleground()) || (player && sWorld->getBoolConfig(CONFIG_DURABILITY_LOSS_IN_PVP)))
{
sLog->outStaticDebug("We are dead, losing %f percent durability", sWorld->getRate(RATE_DURABILITY_LOSS_ON_DEATH));
plrVictim->DurabilityLossAll(sWorld->getRate(RATE_DURABILITY_LOSS_ON_DEATH), false);
// durability lost message
WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
plrVictim->GetSession()->SendPacket(&data);
}
// Call KilledUnit for creatures
if (GetTypeId() == TYPEID_UNIT && IsAIEnabled)
ToCreature()->AI()->KilledUnit(victim);
// last damage from non duel opponent or opponent controlled creature
if (plrVictim->duel)
{
plrVictim->duel->opponent->CombatStopWithPets(true);
plrVictim->CombatStopWithPets(true);
plrVictim->DuelComplete(DUEL_INTERRUPTED);
}
}
else // creature died
{
sLog->outStaticDebug("DealDamageNotPlayer");
if (!creature->isPet())
{
creature->DeleteThreatList();
CreatureTemplate const* cInfo = creature->GetCreatureInfo();
if (cInfo && (cInfo->lootid || cInfo->maxgold > 0))
creature->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
}
// Call KilledUnit for creatures, this needs to be called after the lootable flag is set
if (GetTypeId() == TYPEID_UNIT && IsAIEnabled)
ToCreature()->AI()->KilledUnit(victim);
// Call creature just died function
if (creature->IsAIEnabled)
creature->AI()->JustDied(this);
if (TempSummon* summon = creature->ToTempSummon())
if (Unit* summoner = summon->GetSummoner())
if (summoner->ToCreature() && summoner->IsAIEnabled)
summoner->ToCreature()->AI()->SummonedCreatureDies(creature, this);
// Dungeon specific stuff, only applies to players killing creatures
if (creature->GetInstanceId())
{
Map* instanceMap = creature->GetMap();
Player* creditedPlayer = GetCharmerOrOwnerPlayerOrPlayerItself();
// TODO: do instance binding anyway if the charmer/owner is offline
if (instanceMap->IsDungeon() && creditedPlayer)
{
if (instanceMap->IsRaidOrHeroicDungeon())
{
if (creature->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
{
((InstanceMap*)instanceMap)->PermBindAllPlayers(creditedPlayer);
creditedPlayer->CreateWowarmoryFeed(3, creature->GetCreatureInfo()->Entry, 0, 0);
}
}
else
{
// the reset time is set but not added to the scheduler
// until the players leave the instance
time_t resettime = creature->GetRespawnTimeEx() + 2 * HOUR;
if (InstanceSave* save = sInstanceSaveMgr->GetInstanceSave(creature->GetInstanceId()))
if (save->GetResetTime() < resettime) save->SetResetTime(resettime);
}
}
}
}
// outdoor pvp things, do these after setting the death state, else the player activity notify won't work... doh...
// handle player kill only if not suicide (spirit of redemption for example)
if (player && this != victim)
if (OutdoorPvP* pvp = player->GetOutdoorPvP())
pvp->HandleKill(player, victim);
//if (victim->GetTypeId() == TYPEID_PLAYER)
// if (OutdoorPvP* pvp = victim->ToPlayer()->GetOutdoorPvP())
// pvp->HandlePlayerActivityChangedpVictim->ToPlayer();
// battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill)
if (player && player->InBattleground())
{
if (Battleground* bg = player->GetBattleground())
{
if (victim->GetTypeId() == TYPEID_PLAYER)
bg->HandleKillPlayer((Player*)victim, player);
else
bg->HandleKillUnit(victim->ToCreature(), player);
}
}
// achievement stuff
if (victim->GetTypeId() == TYPEID_PLAYER)
{
if (GetTypeId() == TYPEID_UNIT)
victim->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE, GetEntry());
else if (GetTypeId() == TYPEID_PLAYER && victim != this)
victim->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER, 1, ToPlayer()->GetTeam());
}
// Hook for OnPVPKill Event
if (Player* killerPlr = ToPlayer())
{
if (Player* killedPlr = victim->ToPlayer())
sScriptMgr->OnPVPKill(killerPlr, killedPlr);
else if (Creature* killedCre = victim->ToCreature())
sScriptMgr->OnCreatureKill(killerPlr, killedCre);
}
else if (Creature* killerCre = ToCreature())
{
if (Player* killed = victim->ToPlayer())
sScriptMgr->OnPlayerKilledByCreature(killerCre, killed);
}
if (victim->GetVehicle())
victim->ExitVehicle();
}
void Unit::SetControlled(bool apply, UnitState state)
{
if (apply)
{
if (HasUnitState(state))
return;
AddUnitState(state);
switch (state)
{
case UNIT_STAT_STUNNED:
SetStunned(true);
CastStop();
break;
case UNIT_STAT_ROOT:
if (!HasUnitState(UNIT_STAT_STUNNED))
SetRooted(true);
break;
case UNIT_STAT_CONFUSED:
if (!HasUnitState(UNIT_STAT_STUNNED))
{
ClearUnitState(UNIT_STAT_MELEE_ATTACKING);
SendMeleeAttackStop();
// SendAutoRepeatCancel ?
SetConfused(true);
CastStop();
}
break;
case UNIT_STAT_FLEEING:
if (!HasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED))
{
ClearUnitState(UNIT_STAT_MELEE_ATTACKING);
SendMeleeAttackStop();
// SendAutoRepeatCancel ?
SetFeared(true);
CastStop();
}
break;
default:
break;
}
}
else
{
switch (state)
{
case UNIT_STAT_STUNNED: if (HasAuraType(SPELL_AURA_MOD_STUN)) return;
else SetStunned(false); break;
case UNIT_STAT_ROOT: if (HasAuraType(SPELL_AURA_MOD_ROOT) || GetVehicle()) return;
else SetRooted(false); break;
case UNIT_STAT_CONFUSED:if (HasAuraType(SPELL_AURA_MOD_CONFUSE)) return;
else SetConfused(false); break;
case UNIT_STAT_FLEEING: if (HasAuraType(SPELL_AURA_MOD_FEAR)) return;
else SetFeared(false); break;
default: return;
}
ClearUnitState(state);
if (HasUnitState(UNIT_STAT_STUNNED))
SetStunned(true);
else
{
if (HasUnitState(UNIT_STAT_ROOT))
SetRooted(true);
if (HasUnitState(UNIT_STAT_CONFUSED))
SetConfused(true);
else if (HasUnitState(UNIT_STAT_FLEEING))
SetFeared(true);
}
}
}
void Unit::SetStunned(bool apply)
{
if (apply)
{
SetTarget(0);
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
// MOVEMENTFLAG_ROOT cannot be used in conjunction with MOVEMENTFLAG_MASK_MOVING (tested 3.3.5a)
// this will freeze clients. That's why we remove MOVEMENTFLAG_MASK_MOVING before
// setting MOVEMENTFLAG_ROOT
RemoveUnitMovementFlag(MOVEMENTFLAG_MASK_MOVING);
AddUnitMovementFlag(MOVEMENTFLAG_ROOT);
// Creature specific
if (GetTypeId() != TYPEID_PLAYER)
ToCreature()->StopMoving();
else
SetStandState(UNIT_STAND_STATE_STAND);
WorldPacket data(SMSG_FORCE_MOVE_ROOT, 8);
data.append(GetPackGUID());
data << uint32(0);
SendMessageToSet(&data, true);
CastStop();
}
else
{
if (isAlive() && getVictim())
SetTarget(getVictim()->GetGUID());
// don't remove UNIT_FLAG_STUNNED for pet when owner is mounted (disabled pet's interface)
Unit* owner = GetOwner();
if (!owner || (owner->GetTypeId() == TYPEID_PLAYER && !owner->ToPlayer()->IsMounted()))
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
if (!HasUnitState(UNIT_STAT_ROOT)) // prevent allow move if have also root effect
{
WorldPacket data(SMSG_FORCE_MOVE_UNROOT, 8+4);
data.append(GetPackGUID());
data << uint32(0);
SendMessageToSet(&data, true);
RemoveUnitMovementFlag(MOVEMENTFLAG_ROOT);
}
}
}
void Unit::SetRooted(bool apply)
{
if (apply)
{
if (m_rootTimes > 0) // blizzard internal check?
m_rootTimes++;
// MOVEMENTFLAG_ROOT cannot be used in conjunction with MOVEMENTFLAG_MASK_MOVING (tested 3.3.5a)
// this will freeze clients. That's why we remove MOVEMENTFLAG_MASK_MOVING before
// setting MOVEMENTFLAG_ROOT
RemoveUnitMovementFlag(MOVEMENTFLAG_MASK_MOVING);
AddUnitMovementFlag(MOVEMENTFLAG_ROOT);
if (GetTypeId() == TYPEID_PLAYER)
{
WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
data.append(GetPackGUID());
data << m_rootTimes;
SendMessageToSet(&data, true);
}
else
{
WorldPacket data(SMSG_SPLINE_MOVE_ROOT, 8);
data.append(GetPackGUID());
SendMessageToSet(&data, true);
ToCreature()->StopMoving();
}
}
else
{
if (!HasUnitState(UNIT_STAT_STUNNED)) // prevent allow move if have also stun effect
{
if (GetTypeId() == TYPEID_PLAYER)
{
WorldPacket data(SMSG_FORCE_MOVE_UNROOT, 10);
data.append(GetPackGUID());
data << ++m_rootTimes;
SendMessageToSet(&data, true);
}
else
{
WorldPacket data(SMSG_SPLINE_MOVE_UNROOT, 8);
data.append(GetPackGUID());
SendMessageToSet(&data, true);
}
RemoveUnitMovementFlag(MOVEMENTFLAG_ROOT);
}
}
}
void Unit::SetFeared(bool apply)
{
if (apply)
{
SetTarget(0);
Unit* caster = NULL;
Unit::AuraEffectList const& fearAuras = GetAuraEffectsByType(SPELL_AURA_MOD_FEAR);
if (!fearAuras.empty())
caster = ObjectAccessor::GetUnit(*this, fearAuras.front()->GetCasterGUID());
if (!caster)
caster = getAttackerForHelper();
GetMotionMaster()->MoveFleeing(caster, fearAuras.empty() ? sWorld->getIntConfig(CONFIG_CREATURE_FAMILY_FLEE_DELAY) : 0); // caster == NULL processed in MoveFleeing
}
else
{
if (isAlive())
{
if (GetMotionMaster()->GetCurrentMovementGeneratorType() == FLEEING_MOTION_TYPE)
GetMotionMaster()->MovementExpired();
if (getVictim())
SetTarget(getVictim()->GetGUID());
}
}
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->SetClientControl(this, !apply);
}
void Unit::SetConfused(bool apply)
{
if (apply)
{
SetTarget(0);
GetMotionMaster()->MoveConfused();
}
else
{
if (isAlive())
{
if (GetMotionMaster()->GetCurrentMovementGeneratorType() == CONFUSED_MOTION_TYPE)
GetMotionMaster()->MovementExpired();
if (getVictim())
SetTarget(getVictim()->GetGUID());
}
}
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->SetClientControl(this, !apply);
}
bool Unit::SetCharmedBy(Unit* charmer, CharmType type, AuraApplication const* aurApp)
{
if (!charmer)
return false;
// unmount players when charmed
if (GetTypeId() == TYPEID_PLAYER)
Unmount();
ASSERT(type != CHARM_TYPE_POSSESS || charmer->GetTypeId() == TYPEID_PLAYER);
ASSERT((type == CHARM_TYPE_VEHICLE) == IsVehicle());
sLog->outDebug(LOG_FILTER_UNITS, "SetCharmedBy: charmer %u (GUID %u), charmed %u (GUID %u), type %u.", charmer->GetEntry(), charmer->GetGUIDLow(), GetEntry(), GetGUIDLow(), uint32(type));
if (this == charmer)
{
sLog->outCrash("Unit::SetCharmedBy: Unit %u (GUID %u) is trying to charm itself!", GetEntry(), GetGUIDLow());
return false;
}
//if (HasUnitState(UNIT_STAT_UNATTACKABLE))
// return false;
if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->GetTransport())
{
sLog->outCrash("Unit::SetCharmedBy: Player on transport is trying to charm %u (GUID %u)", GetEntry(), GetGUIDLow());
return false;
}
// Already charmed
if (GetCharmerGUID())
{
sLog->outCrash("Unit::SetCharmedBy: %u (GUID %u) has already been charmed but %u (GUID %u) is trying to charm it!", GetEntry(), GetGUIDLow(), charmer->GetEntry(), charmer->GetGUIDLow());
return false;
}
CastStop();
CombatStop(); // TODO: CombatStop(true) may cause crash (interrupt spells)
DeleteThreatList();
// Charmer stop charming
if (charmer->GetTypeId() == TYPEID_PLAYER)
{
charmer->ToPlayer()->StopCastingCharm();
charmer->ToPlayer()->StopCastingBindSight();
}
// Charmed stop charming
if (GetTypeId() == TYPEID_PLAYER)
{
ToPlayer()->StopCastingCharm();
ToPlayer()->StopCastingBindSight();
}
// StopCastingCharm may remove a possessed pet?
if (!IsInWorld())
{
sLog->outCrash("Unit::SetCharmedBy: %u (GUID %u) is not in world but %u (GUID %u) is trying to charm it!", GetEntry(), GetGUIDLow(), charmer->GetEntry(), charmer->GetGUIDLow());
return false;
}
// charm is set by aura, and aura effect remove handler was called during apply handler execution
// prevent undefined behaviour
if (aurApp && aurApp->GetRemoveMode())
return false;
// Set charmed
Map* map = GetMap();
if (!IsVehicle() || (IsVehicle() && map && !map->IsBattleground()))
setFaction(charmer->getFaction());
charmer->SetCharm(this, true);
if (GetTypeId() == TYPEID_UNIT)
{
ToCreature()->AI()->OnCharmed(true);
GetMotionMaster()->MoveIdle();
}
else
{
Player* player = ToPlayer();
if (player->isAFK())
player->ToggleAFK();
player->SetClientControl(this, 0);
}
// charm is set by aura, and aura effect remove handler was called during apply handler execution
// prevent undefined behaviour
if (aurApp && aurApp->GetRemoveMode())
return false;
// Pets already have a properly initialized CharmInfo, don't overwrite it.
if (type != CHARM_TYPE_VEHICLE && !GetCharmInfo())
{
InitCharmInfo();
if (type == CHARM_TYPE_POSSESS)
GetCharmInfo()->InitPossessCreateSpells();
else
GetCharmInfo()->InitCharmCreateSpells();
}
if (charmer->GetTypeId() == TYPEID_PLAYER)
{
switch (type)
{
case CHARM_TYPE_VEHICLE:
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
charmer->ToPlayer()->SetClientControl(this, 1);
charmer->ToPlayer()->SetViewpoint(this, true);
charmer->ToPlayer()->VehicleSpellInitialize();
break;
case CHARM_TYPE_POSSESS:
AddUnitState(UNIT_STAT_POSSESSED);
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
charmer->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE);
charmer->ToPlayer()->SetClientControl(this, 1);
charmer->ToPlayer()->SetViewpoint(this, true);
charmer->ToPlayer()->PossessSpellInitialize();
break;
case CHARM_TYPE_CHARM:
if (GetTypeId() == TYPEID_UNIT && charmer->getClass() == CLASS_WARLOCK)
{
CreatureTemplate const* cinfo = ToCreature()->GetCreatureInfo();
if (cinfo && cinfo->type == CREATURE_TYPE_DEMON)
{
// to prevent client crash
SetByteValue(UNIT_FIELD_BYTES_0, 1, (uint8)CLASS_MAGE);
// just to enable stat window
if (GetCharmInfo())
GetCharmInfo()->SetPetNumber(sObjectMgr->GeneratePetNumber(), true);
// if charmed two demons the same session, the 2nd gets the 1st one's name
SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(NULL))); // cast can't be helped
}
}
charmer->ToPlayer()->CharmSpellInitialize();
break;
default:
case CHARM_TYPE_CONVERT:
break;
}
}
return true;
}
void Unit::RemoveCharmedBy(Unit* charmer)
{
if (!isCharmed())
return;
if (!charmer)
charmer = GetCharmer();
if (charmer != GetCharmer()) // one aura overrides another?
{
// sLog->outCrash("Unit::RemoveCharmedBy: this: " UI64FMTD " true charmer: " UI64FMTD " false charmer: " UI64FMTD,
// GetGUID(), GetCharmerGUID(), charmer->GetGUID());
// ASSERT(false);
return;
}
CharmType type;
if (HasUnitState(UNIT_STAT_POSSESSED))
type = CHARM_TYPE_POSSESS;
else if (charmer && charmer->IsOnVehicle(this))
type = CHARM_TYPE_VEHICLE;
else
type = CHARM_TYPE_CHARM;
CastStop();
CombatStop(); // TODO: CombatStop(true) may cause crash (interrupt spells)
getHostileRefManager().deleteReferences();
DeleteThreatList();
Map* map = GetMap();
if (!IsVehicle() || (IsVehicle() && map && !map->IsBattleground()))
RestoreFaction();
GetMotionMaster()->InitDefault();
if (type == CHARM_TYPE_POSSESS)
{
ClearUnitState(UNIT_STAT_POSSESSED);
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
}
if (Creature* creature = ToCreature())
{
creature->AI()->OnCharmed(false);
if (type != CHARM_TYPE_VEHICLE) // Vehicles' AI is never modified
{
creature->AIM_Initialize();
if (creature->AI() && charmer && charmer->isAlive())
creature->AI()->AttackStart(charmer);
}
}
else
ToPlayer()->SetClientControl(this, 1);
// If charmer still exists
if (!charmer)
return;
ASSERT(type != CHARM_TYPE_POSSESS || charmer->GetTypeId() == TYPEID_PLAYER);
ASSERT(type != CHARM_TYPE_VEHICLE || (GetTypeId() == TYPEID_UNIT && IsVehicle()));
charmer->SetCharm(this, false);
if (charmer->GetTypeId() == TYPEID_PLAYER)
{
switch (type)
{
case CHARM_TYPE_VEHICLE:
charmer->ToPlayer()->SetClientControl(charmer, 1);
charmer->ToPlayer()->SetViewpoint(this, false);
charmer->ToPlayer()->SetClientControl(this, 0);
break;
case CHARM_TYPE_POSSESS:
charmer->ToPlayer()->SetClientControl(charmer, 1);
charmer->ToPlayer()->SetViewpoint(this, false);
charmer->ToPlayer()->SetClientControl(this, 0);
charmer->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE);
break;
case CHARM_TYPE_CHARM:
if (GetTypeId() == TYPEID_UNIT && charmer->getClass() == CLASS_WARLOCK)
{
CreatureTemplate const* cinfo = ToCreature()->GetCreatureInfo();
if (cinfo && cinfo->type == CREATURE_TYPE_DEMON)
{
SetByteValue(UNIT_FIELD_BYTES_0, 1, uint8(cinfo->unit_class));
if (GetCharmInfo())
GetCharmInfo()->SetPetNumber(0, true);
else
sLog->outError("Aura::HandleModCharm: target="UI64FMTD" with typeid=%d has a charm aura but no charm info!", GetGUID(), GetTypeId());
}
}
break;
default:
case CHARM_TYPE_CONVERT:
break;
}
}
// a guardian should always have charminfo
if (charmer->GetTypeId() == TYPEID_PLAYER && this != charmer->GetFirstControlled())
charmer->ToPlayer()->SendRemoveControlBar();
else if (GetTypeId() == TYPEID_PLAYER || (GetTypeId() == TYPEID_UNIT && !ToCreature()->isGuardian()))
DeleteCharmInfo();
}
void Unit::RestoreFaction()
{
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->setFactionForRace(getRace());
else
{
if (HasUnitTypeMask(UNIT_MASK_MINION))
{
if (Unit* owner = GetOwner())
{
setFaction(owner->getFaction());
return;
}
}
if (CreatureTemplate const* cinfo = ToCreature()->GetCreatureInfo()) // normal creature
{
FactionTemplateEntry const* faction = getFactionTemplateEntry();
setFaction((faction && faction->friendlyMask & 0x004) ? cinfo->faction_H : cinfo->faction_A);
}
}
}
bool Unit::CreateVehicleKit(uint32 id, uint32 creatureEntry)
{
VehicleEntry const* vehInfo = sVehicleStore.LookupEntry(id);
if (!vehInfo)
return false;
m_vehicleKit = new Vehicle(this, vehInfo, creatureEntry);
m_updateFlag |= UPDATEFLAG_VEHICLE;
m_unitTypeMask |= UNIT_MASK_VEHICLE;
return true;
}
void Unit::RemoveVehicleKit()
{
if (!m_vehicleKit)
return;
m_vehicleKit->Uninstall();
delete m_vehicleKit;
m_vehicleKit = NULL;
m_updateFlag &= ~UPDATEFLAG_VEHICLE;
m_unitTypeMask &= ~UNIT_MASK_VEHICLE;
RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_PLAYER_VEHICLE);
}
Unit* Unit::GetVehicleBase() const
{
return m_vehicle ? m_vehicle->GetBase() : NULL;
}
Creature* Unit::GetVehicleCreatureBase() const
{
if (Unit* veh = GetVehicleBase())
if (Creature* c = veh->ToCreature())
return c;
return NULL;
}
uint64 Unit::GetTransGUID() const
{
if (GetVehicle())
return GetVehicle()->GetBase()->GetGUID();
if (GetTransport())
return GetTransport()->GetGUID();
return 0;
}
bool Unit::IsInPartyWith(Unit const* unit) const
{
if (this == unit)
return true;
const Unit* u1 = GetCharmerOrOwnerOrSelf();
const Unit* u2 = unit->GetCharmerOrOwnerOrSelf();
if (u1 == u2)
return true;
if (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_PLAYER)
return u1->ToPlayer()->IsInSameGroupWith(u2->ToPlayer());
else
return false;
}
bool Unit::IsInRaidWith(Unit const* unit) const
{
if (this == unit)
return true;
const Unit* u1 = GetCharmerOrOwnerOrSelf();
const Unit* u2 = unit->GetCharmerOrOwnerOrSelf();
if (u1 == u2)
return true;
if (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_PLAYER)
return u1->ToPlayer()->IsInSameRaidWith(u2->ToPlayer());
else
return false;
}
bool Unit::IsTargetMatchingCheck(Unit const* target, SpellTargetSelectionCheckTypes check) const
{
switch (check)
{
case TARGET_SELECT_CHECK_ENEMY:
if (IsControlledByPlayer())
return !IsFriendlyTo(target);
else
return IsHostileTo(target);
case TARGET_SELECT_CHECK_ALLY:
return IsFriendlyTo(target);
case TARGET_SELECT_CHECK_PARTY:
return IsInPartyWith(target);
case TARGET_SELECT_CHECK_RAID:
return IsInRaidWith(target);
default:
return true;
}
}
void Unit::GetRaidMember(std::list<Unit*> &nearMembers, float radius)
{
Player* owner = GetCharmerOrOwnerPlayerOrPlayerItself();
if (!owner)
return;
Group* group = owner->GetGroup();
if (group)
{
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* Target = itr->getSource();
if (Target && !IsHostileTo(Target))
{
if (Target->isAlive() && IsWithinDistInMap(Target, radius))
nearMembers.push_back(Target);
if (Guardian* pet = Target->GetGuardianPet())
if (pet->isAlive() && IsWithinDistInMap(pet, radius))
nearMembers.push_back(pet);
}
}
}
else
{
if (owner->isAlive() && (owner == this || IsWithinDistInMap(owner, radius)))
nearMembers.push_back(owner);
if (Guardian* pet = owner->GetGuardianPet())
if (pet->isAlive() && (pet == this && IsWithinDistInMap(pet, radius)))
nearMembers.push_back(pet);
}
}
void Unit::GetPartyMemberInDist(std::list<Unit*> &TagUnitMap, float radius)
{
Unit* owner = GetCharmerOrOwnerOrSelf();
Group* group = NULL;
if (owner->GetTypeId() == TYPEID_PLAYER)
group = owner->ToPlayer()->GetGroup();
if (group)
{
uint8 subgroup = owner->ToPlayer()->GetSubGroup();
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* Target = itr->getSource();
// IsHostileTo check duel and controlled by enemy
if (Target && Target->GetSubGroup() == subgroup && !IsHostileTo(Target))
{
if (Target->isAlive() && IsWithinDistInMap(Target, radius))
TagUnitMap.push_back(Target);
if (Guardian* pet = Target->GetGuardianPet())
if (pet->isAlive() && IsWithinDistInMap(pet, radius))
TagUnitMap.push_back(pet);
}
}
}
else
{
if (owner->isAlive() && (owner == this || IsWithinDistInMap(owner, radius)))
TagUnitMap.push_back(owner);
if (Guardian* pet = owner->GetGuardianPet())
if (pet->isAlive() && (pet == this && IsWithinDistInMap(pet, radius)))
TagUnitMap.push_back(pet);
}
}
void Unit::GetPartyMembers(std::list<Unit*> &TagUnitMap)
{
Unit* owner = GetCharmerOrOwnerOrSelf();
Group* group = NULL;
if (owner->GetTypeId() == TYPEID_PLAYER)
group = owner->ToPlayer()->GetGroup();
if (group)
{
uint8 subgroup = owner->ToPlayer()->GetSubGroup();
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* Target = itr->getSource();
// IsHostileTo check duel and controlled by enemy
if (Target && Target->GetSubGroup() == subgroup && !IsHostileTo(Target))
{
if (Target->isAlive() && IsInMap(Target))
TagUnitMap.push_back(Target);
if (Guardian* pet = Target->GetGuardianPet())
if (pet->isAlive() && IsInMap(Target))
TagUnitMap.push_back(pet);
}
}
}
else
{
if (owner->isAlive() && (owner == this || IsInMap(owner)))
TagUnitMap.push_back(owner);
if (Guardian* pet = owner->GetGuardianPet())
if (pet->isAlive() && (pet == this || IsInMap(pet)))
TagUnitMap.push_back(pet);
}
}
Aura* Unit::AddAura(uint32 spellId, Unit* target)
{
if (!target)
return NULL;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo)
return NULL;
if (!target->isAlive() && !(spellInfo->Attributes & SPELL_ATTR0_PASSIVE) && !(spellInfo->AttributesEx2 & SPELL_ATTR2_CAN_TARGET_DEAD))
return NULL;
return AddAura(spellInfo, MAX_EFFECT_MASK, target);
}
Aura* Unit::AddAura(SpellInfo const* spellInfo, uint8 effMask, Unit* target)
{
if (!spellInfo)
return NULL;
if (target->IsImmunedToSpell(spellInfo))
return NULL;
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (!(effMask & (1<<i)))
continue;
if (target->IsImmunedToSpellEffect(spellInfo, i))
effMask &= ~(1<<i);
}
if (Aura* aura = Aura::TryRefreshStackOrCreate(spellInfo, effMask, target, this))
{
aura->ApplyForTargets();
return aura;
}
return NULL;
}
void Unit::SetAuraStack(uint32 spellId, Unit* target, uint32 stack)
{
Aura* aura = target->GetAura(spellId, GetGUID());
if (!aura)
aura = AddAura(spellId, target);
if (aura && stack)
aura->SetStackAmount(stack);
}
void Unit::SendPlaySpellVisual(uint32 id)
{
WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 8 + 4);
data << uint64(GetGUID());
data << uint32(id); // SpellVisualKit.dbc index
SendMessageToSet(&data, false);
}
void Unit::SendPlaySpellImpact(uint64 guid, uint32 id)
{
WorldPacket data(SMSG_PLAY_SPELL_IMPACT, 8 + 4);
data << uint64(guid); // target
data << uint32(id); // SpellVisualKit.dbc index
SendMessageToSet(&data, false);
}
void Unit::ApplyResilience(Unit const* victim, float* crit, int32* damage, bool isCrit, CombatRating type) const
{
// player mounted on multi-passenger mount is also classified as vehicle
if (IsVehicle() || (victim->IsVehicle() && victim->GetTypeId() != TYPEID_PLAYER))
return;
Unit const* source = NULL;
if (GetTypeId() == TYPEID_PLAYER)
source = this;
else if (GetTypeId() == TYPEID_UNIT && GetOwner() && GetOwner()->GetTypeId() == TYPEID_PLAYER)
source = GetOwner();
Unit const* target = NULL;
if (victim->GetTypeId() == TYPEID_PLAYER)
target = victim;
else if (victim->GetTypeId() == TYPEID_UNIT && victim->GetOwner() && victim->GetOwner()->GetTypeId() == TYPEID_PLAYER)
target = victim->GetOwner();
if (!target)
return;
switch (type)
{
case CR_CRIT_TAKEN_MELEE:
// Crit chance reduction works against nonpets
if (crit)
*crit -= target->GetMeleeCritChanceReduction();
if (source && damage)
{
if (isCrit)
*damage -= target->GetMeleeCritDamageReduction(*damage);
*damage -= target->GetMeleeDamageReduction(*damage);
}
break;
case CR_CRIT_TAKEN_RANGED:
// Crit chance reduction works against nonpets
if (crit)
*crit -= target->GetRangedCritChanceReduction();
if (source && damage)
{
if (isCrit)
*damage -= target->GetRangedCritDamageReduction(*damage);
*damage -= target->GetRangedDamageReduction(*damage);
}
break;
case CR_CRIT_TAKEN_SPELL:
// Crit chance reduction works against nonpets
if (crit)
*crit -= target->GetSpellCritChanceReduction();
if (source && damage)
{
if (isCrit)
*damage -= target->GetSpellCritDamageReduction(*damage);
*damage -= target->GetSpellDamageReduction(*damage);
}
break;
default:
break;
}
}
// Melee based spells can be miss, parry or dodge on this step
// Crit or block - determined on damage calculation phase! (and can be both in some time)
float Unit::MeleeSpellMissChance(const Unit* victim, WeaponAttackType attType, int32 skillDiff, uint32 spellId) const
{
//calculate miss chance
float missChance = victim->GetUnitMissChance(attType);
if (!spellId && haveOffhandWeapon())
missChance += 19;
// bonus from skills is 0.04%
//miss_chance -= skillDiff * 0.04f;
int32 diff = -skillDiff;
if (victim->GetTypeId() == TYPEID_PLAYER)
missChance += diff > 0 ? diff * 0.04f : diff * 0.02f;
else
missChance += diff > 10 ? 1 + (diff - 10) * 0.4f : diff * 0.1f;
// Calculate hit chance
float hitChance = 100.0f;
// Spellmod from SPELLMOD_RESIST_MISS_CHANCE
if (spellId)
{
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellId, SPELLMOD_RESIST_MISS_CHANCE, hitChance);
}
missChance += hitChance - 100.0f;
if (attType == RANGED_ATTACK)
missChance -= m_modRangedHitChance;
else
missChance -= m_modMeleeHitChance;
// Limit miss chance from 0 to 60%
if (missChance < 0.0f)
return 0.0f;
if (missChance > 60.0f)
return 60.0f;
return missChance;
}
void Unit::SetPhaseMask(uint32 newPhaseMask, bool update)
{
if (newPhaseMask == GetPhaseMask())
return;
if (IsInWorld())
RemoveNotOwnSingleTargetAuras(newPhaseMask); // we can lost access to caster or target
WorldObject::SetPhaseMask(newPhaseMask, update);
if (!IsInWorld())
return;
for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
if ((*itr)->GetTypeId() == TYPEID_UNIT)
(*itr)->SetPhaseMask(newPhaseMask, true);
for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i)
if (m_SummonSlot[i])
if (Creature* summon = GetMap()->GetCreature(m_SummonSlot[i]))
summon->SetPhaseMask(newPhaseMask, true);
}
void Unit::UpdateObjectVisibility(bool forced)
{
if (!forced)
AddToNotify(NOTIFY_VISIBILITY_CHANGED);
else
{
WorldObject::UpdateObjectVisibility(true);
// call MoveInLineOfSight for nearby creatures
Trinity::AIRelocationNotifier notifier(*this);
VisitNearbyObject(GetVisibilityRange(), notifier);
}
}
void Unit::KnockbackFrom(float x, float y, float speedXY, float speedZ)
{
//if (this->ToPlayer())
// sAnticheatMgr->DisableAnticheatDetection(this->ToPlayer());
Player* player = NULL;
if (GetTypeId() == TYPEID_PLAYER)
player = (Player*)this;
else if (Unit* charmer = GetCharmer())
{
player = charmer->ToPlayer();
if (player && player->m_mover != this)
player = NULL;
}
if (!player)
{
GetMotionMaster()->MoveKnockbackFrom(x, y, speedXY, speedZ);
}
else
{
// Bladestorm
if (player->HasAura(46924))
return;
float vcos, vsin;
GetSinCos(x, y, vsin, vcos);
WorldPacket data(SMSG_MOVE_KNOCK_BACK, (8+4+4+4+4+4));
data.append(GetPackGUID());
data << uint32(0); // counter
data << float(vcos); // x direction
data << float(vsin); // y direction
data << float(speedXY); // Horizontal speed
data << float(-speedZ); // Z Movement speed (vertical)
player->GetSession()->SendPacket(&data);
}
}
float Unit::GetCombatRatingReduction(CombatRating cr) const
{
if (Player const* player = ToPlayer())
return player->GetRatingBonusValue(cr);
// Player's pet get resilience from owner
else if (isPet() && GetOwner())
if (Player* owner = GetOwner()->ToPlayer())
return owner->GetRatingBonusValue(cr);
return 0.0f;
}
uint32 Unit::GetCombatRatingDamageReduction(CombatRating cr, float rate, float cap, uint32 damage) const
{
float percent = std::min(GetCombatRatingReduction(cr) * rate, cap);
return CalculatePctF(damage, percent);
}
uint32 Unit::GetModelForForm(ShapeshiftForm form)
{
switch (form)
{
case FORM_CAT:
// Based on Hair color
if (getRace() == RACE_NIGHTELF)
{
uint8 hairColor = GetByteValue(PLAYER_BYTES, 3);
switch (hairColor)
{
case 7: // Violet
case 8:
return 29405;
case 3: // Light Blue
return 29406;
case 0: // Green
case 1: // Light Green
case 2: // Dark Green
return 29407;
case 4: // White
return 29408;
default: // original - Dark Blue
return 892;
}
}
// Based on Skin color
else if (getRace() == RACE_TAUREN)
{
uint8 skinColor = GetByteValue(PLAYER_BYTES, 0);
// Male
if (getGender() == GENDER_MALE)
{
switch (skinColor)
{
case 12: // White
case 13:
case 14:
case 18: // Completly White
return 29409;
case 9: // Light Brown
case 10:
case 11:
return 29410;
case 6: // Brown
case 7:
case 8:
return 29411;
case 0: // Dark
case 1:
case 2:
case 3: // Dark Grey
case 4:
case 5:
return 29412;
default: // original - Grey
return 8571;
}
}
// Female
else switch (skinColor)
{
case 10: // White
return 29409;
case 6: // Light Brown
case 7:
return 29410;
case 4: // Brown
case 5:
return 29411;
case 0: // Dark
case 1:
case 2:
case 3:
return 29412;
default: // original - Grey
return 8571;
}
}
else if (Player::TeamForRace(getRace()) == ALLIANCE)
return 892;
else
return 8571;
case FORM_DIREBEAR:
case FORM_BEAR:
// Based on Hair color
if (getRace() == RACE_NIGHTELF)
{
uint8 hairColor = GetByteValue(PLAYER_BYTES, 3);
switch (hairColor)
{
case 0: // Green
case 1: // Light Green
case 2: // Dark Green
return 29413; // 29415?
case 6: // Dark Blue
return 29414;
case 4: // White
return 29416;
case 3: // Light Blue
return 29417;
default: // original - Violet
return 2281;
}
}
// Based on Skin color
else if (getRace() == RACE_TAUREN)
{
uint8 skinColor = GetByteValue(PLAYER_BYTES, 0);
// Male
if (getGender() == GENDER_MALE)
{
switch (skinColor)
{
case 0: // Dark (Black)
case 1:
case 2:
return 29418;
case 3: // White
case 4:
case 5:
case 12:
case 13:
case 14:
return 29419;
case 9: // Light Brown/Grey
case 10:
case 11:
case 15:
case 16:
case 17:
return 29420;
case 18: // Completly White
return 29421;
default: // original - Brown
return 2289;
}
}
// Female
else switch (skinColor)
{
case 0: // Dark (Black)
case 1:
return 29418;
case 2: // White
case 3:
return 29419;
case 6: // Light Brown/Grey
case 7:
case 8:
case 9:
return 29420;
case 10: // Completly White
return 29421;
default: // original - Brown
return 2289;
}
}
else if (Player::TeamForRace(getRace()) == ALLIANCE)
return 2281;
else
return 2289;
case FORM_FLIGHT:
if (Player::TeamForRace(getRace()) == ALLIANCE)
return 20857;
return 20872;
case FORM_FLIGHT_EPIC:
if (Player::TeamForRace(getRace()) == ALLIANCE)
return 21243;
return 21244;
default:
break;
}
uint32 modelid = 0;
SpellShapeshiftEntry const* formEntry = sSpellShapeshiftStore.LookupEntry(form);
if (formEntry && formEntry->modelID_A)
{
// Take the alliance modelid as default
if (GetTypeId() != TYPEID_PLAYER)
return formEntry->modelID_A;
else
{
if (Player::TeamForRace(getRace()) == ALLIANCE)
modelid = formEntry->modelID_A;
else
modelid = formEntry->modelID_H;
// If the player is horde but there are no values for the horde modelid - take the alliance modelid
if (!modelid && Player::TeamForRace(getRace()) == HORDE)
modelid = formEntry->modelID_A;
}
}
return modelid;
}
uint32 Unit::GetModelForTotem(PlayerTotemType totemType)
{
switch (getRace())
{
case RACE_ORC:
{
switch (totemType)
{
case SUMMON_TYPE_TOTEM_FIRE: // fire
return 30758;
case SUMMON_TYPE_TOTEM_EARTH: // earth
return 30757;
case SUMMON_TYPE_TOTEM_WATER: // water
return 30759;
case SUMMON_TYPE_TOTEM_AIR: // air
return 30756;
}
break;
}
case RACE_DWARF:
{
switch (totemType)
{
case SUMMON_TYPE_TOTEM_FIRE: // fire
return 30754;
case SUMMON_TYPE_TOTEM_EARTH: // earth
return 30753;
case SUMMON_TYPE_TOTEM_WATER: // water
return 30755;
case SUMMON_TYPE_TOTEM_AIR: // air
return 30736;
}
break;
}
case RACE_TROLL:
{
switch (totemType)
{
case SUMMON_TYPE_TOTEM_FIRE: // fire
return 30762;
case SUMMON_TYPE_TOTEM_EARTH: // earth
return 30761;
case SUMMON_TYPE_TOTEM_WATER: // water
return 30763;
case SUMMON_TYPE_TOTEM_AIR: // air
return 30760;
}
break;
}
case RACE_TAUREN:
{
switch (totemType)
{
case SUMMON_TYPE_TOTEM_FIRE: // fire
return 4589;
case SUMMON_TYPE_TOTEM_EARTH: // earth
return 4588;
case SUMMON_TYPE_TOTEM_WATER: // water
return 4587;
case SUMMON_TYPE_TOTEM_AIR: // air
return 4590;
}
break;
}
case RACE_DRAENEI:
{
switch (totemType)
{
case SUMMON_TYPE_TOTEM_FIRE: // fire
return 19074;
case SUMMON_TYPE_TOTEM_EARTH: // earth
return 19073;
case SUMMON_TYPE_TOTEM_WATER: // water
return 19075;
case SUMMON_TYPE_TOTEM_AIR: // air
return 19071;
}
break;
}
}
return 0;
}
void Unit::JumpTo(float speedXY, float speedZ, bool forward)
{
float angle = forward ? 0 : M_PI;
if (GetTypeId() == TYPEID_UNIT)
GetMotionMaster()->MoveJumpTo(angle, speedXY, speedZ);
else
{
float vcos = cos(angle+GetOrientation());
float vsin = sin(angle+GetOrientation());
WorldPacket data(SMSG_MOVE_KNOCK_BACK, (8+4+4+4+4+4));
data.append(GetPackGUID());
data << uint32(0); // Sequence
data << float(vcos); // x direction
data << float(vsin); // y direction
data << float(speedXY); // Horizontal speed
data << float(-speedZ); // Z Movement speed (vertical)
ToPlayer()->GetSession()->SendPacket(&data);
}
}
void Unit::JumpTo(WorldObject* obj, float speedZ)
{
float x, y, z;
obj->GetContactPoint(this, x, y, z);
float speedXY = GetExactDist2d(x, y) * 10.0f / speedZ;
GetMotionMaster()->MoveJump(x, y, z, speedXY, speedZ);
}
bool Unit::HandleSpellClick(Unit* clicker, int8 seatId)
{
bool success = false;
uint32 spellClickEntry = GetVehicleKit() ? GetVehicleKit()->GetCreatureEntry() : GetEntry();
SpellClickInfoMapBounds clickPair = sObjectMgr->GetSpellClickInfoMapBounds(spellClickEntry);
for (SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
{
if (itr->second.IsFitToRequirements(clicker, this))
{
Unit* caster = (itr->second.castFlags & NPC_CLICK_CAST_CASTER_CLICKER) ? clicker : this;
Unit* target = (itr->second.castFlags & NPC_CLICK_CAST_TARGET_CLICKER) ? clicker : this;
uint64 origCasterGUID = (itr->second.castFlags & NPC_CLICK_CAST_ORIG_CASTER_OWNER) ? GetOwnerGUID() : clicker->GetGUID();
SpellInfo const* spellEntry = sSpellMgr->GetSpellInfo(itr->second.spellId);
// if (!spellEntry) should be checked at npc_spellclick load
if (seatId > -1)
{
uint8 i = 0;
bool valid = false;
while (i < MAX_SPELL_EFFECTS && !valid)
{
if (spellEntry->Effects[i].ApplyAuraName == SPELL_AURA_CONTROL_VEHICLE)
{
valid = true;
break;
}
++i;
}
if (!valid)
{
sLog->outErrorDb("Spell %u specified in npc_spellclick_spells is not a valid vehicle enter aura!", itr->second.spellId);
return false;
}
if (IsInMap(caster))
caster->CastCustomSpell(itr->second.spellId, SpellValueMod(SPELLVALUE_BASE_POINT0+i), seatId+1, target, true, NULL, NULL, origCasterGUID);
else // This can happen during Player::_LoadAuras
{
int32 bp0 = seatId;
Aura::TryRefreshStackOrCreate(spellEntry, MAX_EFFECT_MASK, this, clicker, &bp0, NULL, origCasterGUID);
}
}
else
{
if (IsInMap(caster))
caster->CastSpell(target, spellEntry, true, NULL, NULL, origCasterGUID);
else
Aura::TryRefreshStackOrCreate(spellEntry, MAX_EFFECT_MASK, this, clicker, NULL, NULL, origCasterGUID);
}
success = true;
}
}
Creature* creature = ToCreature();
if (creature && creature->IsAIEnabled)
creature->AI()->DoAction(EVENT_SPELLCLICK);
return success;
}
void Unit::EnterVehicle(Unit* base, int8 seatId)
{
CastCustomSpell(VEHICLE_SPELL_RIDE_HARDCODED, SPELLVALUE_BASE_POINT0, seatId+1, base, false);
}
void Unit::_EnterVehicle(Vehicle* vehicle, int8 seatId, AuraApplication const* aurApp)
{
// Must be called only from aura handler
if (!isAlive() || GetVehicleKit() == vehicle || vehicle->GetBase()->IsOnVehicle(this))
return;
if (m_vehicle)
{
if (m_vehicle == vehicle)
{
if (seatId >= 0 && seatId != GetTransSeat())
{
sLog->outDebug(LOG_FILTER_VEHICLES, "EnterVehicle: %u leave vehicle %u seat %d and enter %d.", GetEntry(), m_vehicle->GetBase()->GetEntry(), GetTransSeat(), seatId);
ChangeSeat(seatId);
}
return;
}
else
{
sLog->outDebug(LOG_FILTER_VEHICLES, "EnterVehicle: %u exit %u and enter %u.", GetEntry(), m_vehicle->GetBase()->GetEntry(), vehicle->GetBase()->GetEntry());
ExitVehicle();
}
}
if (aurApp && aurApp->GetRemoveMode())
return;
if (Player* player = ToPlayer())
{
if (vehicle->GetBase()->GetTypeId() == TYPEID_PLAYER && player->isInCombat())
return;
InterruptNonMeleeSpells(false);
player->StopCastingCharm();
player->StopCastingBindSight();
Unmount();
RemoveAurasByType(SPELL_AURA_MOUNTED);
// drop flag at invisible in bg
if (Battleground* bg = player->GetBattleground())
bg->EventPlayerDroppedFlag(player);
WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
player->GetSession()->SendPacket(&data);
player->UnsummonPetTemporaryIfAny();
}
ASSERT(!m_vehicle);
m_vehicle = vehicle;
if (!m_vehicle->AddPassenger(this, seatId))
{
m_vehicle = NULL;
return;
}
}
void Unit::ChangeSeat(int8 seatId, bool next)
{
if (!m_vehicle)
return;
if (seatId < 0)
{
seatId = m_vehicle->GetNextEmptySeat(GetTransSeat(), next);
if (seatId < 0)
return;
}
else if (seatId == GetTransSeat() || !m_vehicle->HasEmptySeat(seatId))
return;
m_vehicle->RemovePassenger(this);
if (!m_vehicle->AddPassenger(this, seatId))
ASSERT(false);
}
void Unit::ExitVehicle(Position const* exitPosition)
{
// This function can be called at upper level code to initialize an exit from the passenger's side.
if (!m_vehicle)
return;
GetVehicleBase()->RemoveAurasByType(SPELL_AURA_CONTROL_VEHICLE, GetGUID());
_ExitVehicle(exitPosition);
}
void Unit::_ExitVehicle(Position const* exitPosition)
{
if (!m_vehicle)
return;
m_vehicle->RemovePassenger(this);
// This should be done before dismiss, because there may be some aura removal
Vehicle* vehicle = m_vehicle;
m_vehicle = NULL;
SetControlled(false, UNIT_STAT_ROOT); // SMSG_MOVE_FORCE_UNROOT, ~MOVEMENTFLAG_ROOT
Position pos;
if (!exitPosition) // Exit position not specified
vehicle->GetBase()->GetPosition(&pos);
else
pos = *exitPosition;
AddUnitState(UNIT_STAT_MOVE);
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->SetFallInformation(0, GetPositionZ());
else if (HasUnitMovementFlag(MOVEMENTFLAG_ROOT))
{
WorldPacket data(SMSG_SPLINE_MOVE_UNROOT, 8);
data.append(GetPackGUID());
SendMessageToSet(&data, false);
}
SendMonsterMoveExitVehicle(&pos);
Relocate(&pos);
if (Player* player = ToPlayer())
player->ResummonPetTemporaryUnSummonedIfAny();
WorldPacket data2;
BuildHeartBeatMsg(&data2);
SendMessageToSet(&data2, false);
if (vehicle->GetBase()->HasUnitTypeMask(UNIT_MASK_MINION))
if (((Minion*)vehicle->GetBase())->GetOwner() == this)
vehicle->Dismiss();
if (HasUnitTypeMask(UNIT_MASK_ACCESSORY))
{
// Vehicle just died, we die too
if (vehicle->GetBase()->getDeathState() == JUST_DIED)
setDeathState(JUST_DIED);
// If for other reason we as minion are exiting the vehicle (ejected, master unmounted) - unsummon
else
ToTempSummon()->UnSummon(2000); // Approximation
}
}
void Unit::BuildMovementPacket(ByteBuffer *data) const
{
switch (GetTypeId())
{
case TYPEID_UNIT:
if (canFly())
const_cast<Unit*>(this)->AddUnitMovementFlag(MOVEMENTFLAG_LEVITATING);
break;
case TYPEID_PLAYER:
// remove unknown, unused etc flags for now
const_cast<Unit*>(this)->RemoveUnitMovementFlag(MOVEMENTFLAG_SPLINE_ENABLED);
if (isInFlight())
{
WPAssert(const_cast<Unit*>(this)->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE);
const_cast<Unit*>(this)->AddUnitMovementFlag(MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_SPLINE_ENABLED);
}
break;
default:
break;
}
*data << uint32(GetUnitMovementFlags()); // movement flags
*data << uint16(m_movementInfo.flags2); // 2.3.0
*data << uint32(getMSTime()); // time
*data << GetPositionX();
*data << GetPositionY();
*data << GetPositionZ();
*data << GetOrientation();
// 0x00000200
if (GetUnitMovementFlags() & MOVEMENTFLAG_ONTRANSPORT)
{
if (m_vehicle)
data->append(m_vehicle->GetBase()->GetPackGUID());
else if (GetTransport())
data->append(GetTransport()->GetPackGUID());
else
*data << (uint8)0;
*data << float (GetTransOffsetX());
*data << float (GetTransOffsetY());
*data << float (GetTransOffsetZ());
*data << float (GetTransOffsetO());
*data << uint32(GetTransTime());
*data << uint8 (GetTransSeat());
}
// 0x02200000
if ((GetUnitMovementFlags() & (MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING))
|| (m_movementInfo.flags2 & MOVEMENTFLAG2_ALWAYS_ALLOW_PITCHING))
*data << (float)m_movementInfo.pitch;
*data << (uint32)m_movementInfo.fallTime;
// 0x00001000
if (GetUnitMovementFlags() & MOVEMENTFLAG_JUMPING)
{
*data << (float)m_movementInfo.j_zspeed;
*data << (float)m_movementInfo.j_sinAngle;
*data << (float)m_movementInfo.j_cosAngle;
*data << (float)m_movementInfo.j_xyspeed;
}
// 0x04000000
if (GetUnitMovementFlags() & MOVEMENTFLAG_SPLINE_ELEVATION)
*data << (float)m_movementInfo.splineElevation;
}
void Unit::SetFlying(bool apply)
{
if (apply)
{
SetByteFlag(UNIT_FIELD_BYTES_1, 3, 0x02);
AddUnitMovementFlag(MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_FLYING);
}
else
{
RemoveByteFlag(UNIT_FIELD_BYTES_1, 3, 0x02);
RemoveUnitMovementFlag(MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_FLYING);
}
}
void Unit::NearTeleportTo(float x, float y, float z, float orientation, bool casting /*= false*/)
{
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->TeleportTo(GetMapId(), x, y, z, orientation, TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET | (casting ? TELE_TO_SPELL : 0));
else
{
// FIXME: this interrupts spell visual
DestroyForNearbyPlayers();
UpdatePosition(x, y, z, orientation, true);
}
}
bool Unit::UpdatePosition(float x, float y, float z, float orientation, bool teleport)
{
// prevent crash when a bad coord is sent by the client
if (!Trinity::IsValidMapCoord(x, y, z, orientation))
{
sLog->outDebug(LOG_FILTER_UNITS, "Unit::UpdatePosition(%f, %f, %f) .. bad coordinates!", x, y, z);
return false;
}
bool turn = (GetOrientation() != orientation);
bool relocated = (teleport || GetPositionX() != x || GetPositionY() != y || GetPositionZ() != z);
if (turn)
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
if (relocated)
{
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE);
// move and update visible state if need
if (GetTypeId() == TYPEID_PLAYER)
GetMap()->PlayerRelocation(ToPlayer(), x, y, z, orientation);
else
GetMap()->CreatureRelocation(ToCreature(), x, y, z, orientation);
}
else if (turn)
SetOrientation(orientation);
if ((relocated || turn) && IsVehicle())
GetVehicleKit()->RelocatePassengers(x, y, z, orientation);
return (relocated || turn);
}
void Unit::SendThreatListUpdate()
{
if (!getThreatManager().isThreatListEmpty())
{
uint32 count = getThreatManager().getThreatList().size();
//sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Send SMSG_THREAT_UPDATE Message");
WorldPacket data(SMSG_THREAT_UPDATE, 8 + count * 8);
data.append(GetPackGUID());
data << uint32(count);
std::list<HostileReference*>& tlist = getThreatManager().getThreatList();
for (std::list<HostileReference*>::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr)
{
data.appendPackGUID((*itr)->getUnitGuid());
data << uint32((*itr)->getThreat() * 100);
}
SendMessageToSet(&data, false);
}
}
void Unit::SendChangeCurrentVictimOpcode(HostileReference* pHostileReference)
{
if (!getThreatManager().isThreatListEmpty())
{
uint32 count = getThreatManager().getThreatList().size();
sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Send SMSG_HIGHEST_THREAT_UPDATE Message");
WorldPacket data(SMSG_HIGHEST_THREAT_UPDATE, 8 + 8 + count * 8);
data.append(GetPackGUID());
data.appendPackGUID(pHostileReference->getUnitGuid());
data << uint32(count);
std::list<HostileReference*>& tlist = getThreatManager().getThreatList();
for (std::list<HostileReference*>::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr)
{
data.appendPackGUID((*itr)->getUnitGuid());
data << uint32((*itr)->getThreat());
}
SendMessageToSet(&data, false);
}
}
void Unit::SendClearThreatListOpcode()
{
sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Send SMSG_THREAT_CLEAR Message");
WorldPacket data(SMSG_THREAT_CLEAR, 8);
data.append(GetPackGUID());
SendMessageToSet(&data, false);
}
void Unit::SendRemoveFromThreatListOpcode(HostileReference* pHostileReference)
{
sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Send SMSG_THREAT_REMOVE Message");
WorldPacket data(SMSG_THREAT_REMOVE, 8 + 8);
data.append(GetPackGUID());
data.appendPackGUID(pHostileReference->getUnitGuid());
SendMessageToSet(&data, false);
}
void Unit::RewardRage(uint32 damage, uint32 weaponSpeedHitFactor, bool attacker)
{
float addRage;
float rageconversion = ((0.0091107836f * getLevel() * getLevel()) + 3.225598133f * getLevel()) + 4.2652911f;
// Unknown if correct, but lineary adjust rage conversion above level 70
if (getLevel() > 70)
rageconversion += 13.27f * (getLevel() - 70);
if (attacker)
{
addRage = (damage / rageconversion * 7.5f + weaponSpeedHitFactor) / 2;
// talent who gave more rage on attack
AddPctN(addRage, GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT));
}
else
{
addRage = damage / rageconversion * 2.5f;
// Berserker Rage effect
if (HasAura(18499))
addRage *= 2.0f;
}
addRage *= sWorld->getRate(RATE_POWER_RAGE_INCOME);
ModifyPower(POWER_RAGE, uint32(addRage * 10));
}
void Unit::StopAttackFaction(uint32 faction_id)
{
if (Unit* victim = getVictim())
{
if (victim->getFactionTemplateEntry()->faction == faction_id)
{
AttackStop();
if (IsNonMeleeSpellCasted(false))
InterruptNonMeleeSpells(false);
// melee and ranged forced attack cancel
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->SendAttackSwingCancelAttack();
}
}
AttackerSet const& attackers = getAttackers();
for (AttackerSet::const_iterator itr = attackers.begin(); itr != attackers.end();)
{
if ((*itr)->getFactionTemplateEntry()->faction == faction_id)
{
(*itr)->AttackStop();
itr = attackers.begin();
}
else
++itr;
}
getHostileRefManager().deleteReferencesForFaction(faction_id);
for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
(*itr)->StopAttackFaction(faction_id);
}
void Unit::OutDebugInfo() const
{
sLog->outError("Unit::OutDebugInfo");
sLog->outString("GUID "UI64FMTD", entry %u, type %u, name %s", GetGUID(), GetEntry(), (uint32)GetTypeId(), GetName());
sLog->outString("OwnerGUID "UI64FMTD", MinionGUID "UI64FMTD", CharmerGUID "UI64FMTD", CharmedGUID "UI64FMTD, GetOwnerGUID(), GetMinionGUID(), GetCharmerGUID(), GetCharmGUID());
sLog->outString("In world %u, unit type mask %u", (uint32)(IsInWorld() ? 1 : 0), m_unitTypeMask);
if (IsInWorld())
sLog->outString("Mapid %u", GetMapId());
sLog->outStringInLine("Summon Slot: ");
for (uint32 i = 0; i < MAX_SUMMON_SLOT; ++i)
sLog->outStringInLine(UI64FMTD", ", m_SummonSlot[i]);
sLog->outString();
sLog->outStringInLine("Controlled List: ");
for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
sLog->outStringInLine(UI64FMTD", ", (*itr)->GetGUID());
sLog->outString();
sLog->outStringInLine("Aura List: ");
for (AuraApplicationMap::const_iterator itr = m_appliedAuras.begin(); itr != m_appliedAuras.end(); ++itr)
sLog->outStringInLine("%u, ", itr->first);
sLog->outString();
if (IsVehicle())
{
sLog->outStringInLine("Passenger List: ");
for (SeatMap::iterator itr = GetVehicleKit()->Seats.begin(); itr != GetVehicleKit()->Seats.end(); ++itr)
if (Unit* passenger = ObjectAccessor::GetUnit(*GetVehicleBase(), itr->second.Passenger))
sLog->outStringInLine(UI64FMTD", ", passenger->GetGUID());
sLog->outString();
}
if (GetVehicle())
sLog->outString("On vehicle %u.", GetVehicleBase()->GetEntry());
}
uint32 Unit::GetRemainingPeriodicAmount(uint64 caster, uint32 spellId, AuraType auraType, uint8 effectIndex) const
{
uint32 amount = 0;
AuraEffectList const& periodicAuras = GetAuraEffectsByType(auraType);
for (AuraEffectList::const_iterator i = periodicAuras.begin(); i != periodicAuras.end(); ++i)
{
if ((*i)->GetCasterGUID() != caster || (*i)->GetId() != spellId || (*i)->GetEffIndex() != effectIndex || !(*i)->GetTotalTicks())
continue;
amount += uint32(((*i)->GetAmount() * std::max<int32>((*i)->GetTotalTicks() - int32((*i)->GetTickNumber()), 0)) / (*i)->GetTotalTicks());
break;
}
return amount;
}
void Unit::SendClearTarget()
{
WorldPacket data(SMSG_BREAK_TARGET, GetPackGUID().size());
data.append(GetPackGUID());
SendMessageToSet(&data, false);
}
uint32 Unit::GetResistance(SpellSchoolMask mask) const
{
int32 resist = -1;
for (int i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; ++i)
if (mask & (1 << i) && (resist < 0 || resist > int32(GetResistance(SpellSchools(i)))))
resist = int32(GetResistance(SpellSchools(i)));
// resist value will never be negative here
return uint32(resist);
}
void CharmInfo::SetIsCommandAttack(bool val)
{
m_isCommandAttack = val;
}
bool CharmInfo::IsCommandAttack()
{
return m_isCommandAttack;
}
void CharmInfo::SaveStayPosition()
{
m_unit->GetPosition(m_stayX, m_stayY, m_stayZ);
}
void CharmInfo::GetStayPosition(float &x, float &y, float &z)
{
x = m_stayX;
y = m_stayY;
z = m_stayZ;
}
void CharmInfo::SetIsAtStay(bool val)
{
m_isAtStay = val;
}
bool CharmInfo::IsAtStay()
{
return m_isAtStay;
}
void CharmInfo::SetIsFollowing(bool val)
{
m_isFollowing = val;
}
bool CharmInfo::IsFollowing()
{
return m_isFollowing;
}
void CharmInfo::SetIsReturning(bool val)
{
m_isReturning = val;
}
bool CharmInfo::IsReturning()
{
return m_isReturning;
}
| gpl-2.0 |
Southampton-RSG/genie | app/Controller/CategoriesController.php | 5090 | <?php
App::uses('AppController', 'Controller');
/**
* Categories Controller
*
* @property Category $Category
*/
class CategoriesController extends AppController {
/**
* admin_index method
*
* @return void
*/
public function admin_index() {
$this->Category->recursive = 0;
/*
* Facilitators and champions should not be able to see this page
*/
if ($this->Auth->user('role') === 'f' or $this->Auth->user('role') === 'c') {
$this->Session->setFlash(__('You don\'t have permissions to view this page.'));
$this->redirect('/');
}
$this->set('categories', $this->paginate());
}
/**
* admin_view method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function admin_view($id = null) {
if (!$this->Category->exists($id)) {
throw new NotFoundException(__('Invalid category'));
}
/*
* Facilitators and champions should not be able to see this page
*/
if ($this->Auth->user('role') === 'f' or $this->Auth->user('role') === 'c') {
$this->Session->setFlash(__('You don\'t have permissions to view this page.'));
$this->redirect('/');
}
$options = array('conditions' => array('Category.' . $this->Category->primaryKey => $id));
$this->set('category', $this->Category->find('first', $options));
}
/**
* admin_add method
*
* @return void
*/
public function admin_add() {
/*
* Facilitators and champions should not be able to see this page
*/
if ($this->Auth->user('role') === 'f' or $this->Auth->user('role') === 'c') {
$this->Session->setFlash(__('You don\'t have permissions to view this page.'));
$this->redirect('/');
}
$this->Category->locale = array_keys( Configure::read('Site.languages') );
if ($this->request->is('post')) {
$this->Category->create();
if ($this->Category->saveAssociated($this->request->data)) {
$this->Session->setFlash(__('The category has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The category could not be saved. Please, try again.'));
}
}
$parentCategories = $this->Category->find('list',array('conditions'=>array('parent_id'=>null)));
$services = $this->Category->Service->find('list');
$statements = $this->Category->Statement->find('list');
$this->set(compact('parentCategories', 'services', 'statements'));
}
/**
* admin_edit method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function admin_edit($id = null) {
/*
* Facilitators and champions should not be able to see this page
*/
if ($this->Auth->user('role') === 'f' or $this->Auth->user('role') === 'c') {
$this->Session->setFlash(__('You don\'t have permissions to view this page.'));
$this->redirect('/');
}
$this->Category->locale = array_keys( Configure::read('Site.languages') );
if (!$this->Category->exists($id)) {
throw new NotFoundException(__('Invalid category'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if( $this->Category->saveAssociated( $this->request->data ) ){
$this->Session->setFlash(__('The category has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The category could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('Category.' . $this->Category->primaryKey => $id));
$this->request->data = $this->Category->find('first', $options);
foreach( $this->Category->actsAs['Translate'] as $field => $fieldAlias ){
$translations = Set::combine( $this->request->data, $fieldAlias.'.{n}.locale', $fieldAlias.'.{n}.content' );
$this->request->data['Category'][$field] = $translations;
}
}
$parentCategories = $this->Category->find('list',array('conditions'=>array('parent_id'=>null)));
$services = $this->Category->Service->find('list');
$statements = $this->Category->Statement->find('list');
$this->set(compact('parentCategories', 'services', 'statements'));
}
/**
* admin_delete method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function admin_delete($id = null) {
/*
* Facilitators and champions should not be able to see this page
*/
if ($this->Auth->user('role') === 'f' or $this->Auth->user('role') === 'c') {
$this->Session->setFlash(__('You don\'t have permissions to view this page.'));
$this->redirect('/');
}
$this->Category->id = $id;
if (!$this->Category->exists()) {
throw new NotFoundException(__('Invalid category'));
}
$this->request->onlyAllow('post', 'delete');
if ($this->Category->delete()) {
$this->Session->setFlash(__('Category deleted'));
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Category was not deleted'));
$this->redirect(array('action' => 'index'));
}
}
| gpl-2.0 |
thesoftwarejedi/JediAppADay | Source/26.JediDiggSource/AnAppADay.JediDigg.WinApp/Properties/AssemblyInfo.cs | 1298 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AnAppADay.JediDigg.WinApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AnAppADay.JediDigg.WinApp")]
[assembly: AssemblyCopyright("Copyright © 2006")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3889a921-6cb8-4409-8278-56c56e1ffc2b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| gpl-2.0 |
ducdongmg/joomla_tut25 | plugins/jsnimageshow/themestrip/classes/jsn_is_stripdisplay.php | 14703 | <?php
/**
* @version $Id$
* @package JSN.ImageShow - Theme.Strip
* @author JoomlaShine Team <support@joomlashine.com>
* @copyright Copyright (C) 2012 JoomlaShine.com. All Rights Reserved.
* @license GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
*
* Websites: http://www.joomlashine.com
* Technical Support: Feedback - http://www.joomlashine.com/contact-us/get-support.html
*
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.model');
class JSNISStripDisplay extends JObject
{
var $_themename = 'themestrip';
var $_themetype = 'jsnimageshow';
var $_assetsPath = 'plugins/jsnimageshow/themestrip/assets/';
function JSNISStripDisplay() {}
function standardLayout($args)
{
$objJSNShowlist = JSNISFactory::getObj('classes.jsn_is_showlist');
$showlistInfo = $objJSNShowlist->getShowListByID($args->showlist['showlist_id'], true);
$dataObj = $objJSNShowlist->getShowlist2JSON($args->uri, $args->showlist['showlist_id']);
$images = $dataObj->showlist->images->image;
$document = JFactory::getDocument();
$plugin = false;
$minItems = 3;
if (!count($images)) return '';
$pluginOpenTagDiv = '';
$pluginCloseTagDiv = '';
$containerBorder = 0;
if (isset($args->plugin) && $args->plugin == true)
{
$plugin = true;
}
switch ($showlistInfo['image_loading_order'])
{
case 'backward':
krsort($images);
$tmpImageArray = $images;
$images = array_values($images);
break;
case 'random':
shuffle($images);
break;
case 'forward':
ksort($images);
}
JHTML::stylesheet('jquery.fancybox-1.3.4.css', $this->_assetsPath . 'css/fancybox/');
JHTML::stylesheet('elastislide.css', $this->_assetsPath . 'css/elastislide/');
JHTML::stylesheet('custom.css', $this->_assetsPath . 'css/elastislide/');
JHTML::script('modernizr.custom.17475.js',$this->_assetsPath . 'js/jquery/');
$document->addScriptDeclaration('');
$this->loadjQuery();
JHTML::script('jsn_is_conflict.js',$this->_assetsPath . 'js/');
$document->addScriptDeclaration('
if (typeof jQuery.fancybox != "function") {
document.write(\'<script type="text\/javascript" src="'.$this->_assetsPath.'js'.'/jquery/jquery.fancybox-1.3.4.js"><\/script>\');
}');
JHTML::script('jquery.elastislide.js', $this->_assetsPath . 'js/jquery/');
JHTML::script('jquery.imagesloaded.min.js', $this->_assetsPath . 'js/jquery/');
JHTML::script('jsn_is_themestrip.js',$this->_assetsPath . 'js/');
$percent = strpos($args->width, '%');
if ($plugin)
{
$pluginOpenTagDiv = '<div style="max-width:' .$args->width . ((!$percent) ? 'px' : '') . '; margin: 0 auto;">';
$pluginCloseTagDiv = '</div>';
$percent = true;
$args->width = '100%';
}
$themeData = $this->getThemeDataStandard($args);
$width = ($percent === false) ? $args->width . 'px' : $args->width;
$wrapID = 'jsn-'.$this->_themename.'-container-'.$args->random_number;
$galleryID = 'jsn-'.$this->_themename.'-gallery-'.$args->random_number;
$shadow = '';
$css = 'html, body {
overflow-x: hidden;
} ' ."\n";
$css .= '#' . $wrapID . ' .elastislide-carousel ul li a img {
border: ' . $themeData->image_border . 'px solid ' . $themeData->image_border_color . ';
}' ."\n";
$css .= '#' . $wrapID . ' {
direction: ltr;
}' ."\n";
if ($themeData->image_orientation == 'horizontal')
{
$css .= '#' . $wrapID . ' .elastislide-' . $themeData->image_orientation . ' ul li a {
padding: 0px;
padding-right: ' . $themeData->image_space . 'px;
}' ."\n";
$css .= '#' . $wrapID . ' {
max-width: ' . $width . ';
}' ."\n";
if ($themeData->image_shadow != 'no-shadow')
{
$css .= '#' . $wrapID . ' .elastislide-' . $themeData->image_orientation . ' ul {
padding-top: 5px !important;
padding-bottom: 5px !important;
padding-left: 5px !important;
}' ."\n";
}
}
else
{
$css .= '#' . $wrapID . ' .elastislide-' . $themeData->image_orientation . ' ul li a {
padding: 0px;
padding-bottom: ' . $themeData->image_space . 'px;
}' ."\n";
$minItems = floor($args->height / $themeData->image_height);
if ($themeData->image_shadow != 'no-shadow')
{
$css .= '#' . $wrapID . ' .elastislide-' . $themeData->image_orientation . ' ul {
padding-left: 5px !important;
padding-top: 5px !important;
}' ."\n";
}
}
$themeData->slideshow_min_items = $minItems;
$css .= '#' . $wrapID . ' .elastislide-' . $themeData->image_orientation . ' ul li a img {
-webkit-border-radius: ' . $themeData->image_rounded_corner . 'px;
-moz-border-radius: ' . $themeData->image_rounded_corner . 'px;
border-radius: ' . $themeData->image_rounded_corner . 'px;
}' ."\n";
switch ($themeData->image_shadow)
{
case 'no-shadow':
$shadow = 'box-shadow: 0px 0px 0px #888888;
-moz-box-shadow: 0px 0px 0px #888888;
-webkit-box-shadow: 0px 0px 0px #888888;';
$themeData->image_shadow = 0;
break;
case 'light-shadow':
$shadow = 'box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
moz-box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);';
$themeData->image_shadow = 5;
break;
case 'bold-shadow':
$shadow = 'box-shadow: 0 0 5px rgba(0, 0, 0, 0.8);
moz-box-shadow: 0 0 5px rgba(0, 0, 0, 0.8);
-webkit-box-shadow: 0 0 5px rgba(0, 0, 0, 0.8);';
$themeData->image_shadow = 5;
break;
}
switch ($themeData->container_type)
{
case 'elastislide-default':
if ($themeData->image_orientation == 'horizontal')
{
$css .= '#' . $wrapID . ' .elastislide-' . $themeData->image_orientation . ' {
border-radius: 10px/90px;
background-color: #fff;
box-shadow: 1px 1px 3px rgba(0,0,0,0.2);
box-shadow:
0 1px 3px rgba(0, 0, 0, 0.1),
inset -2px 0 3px 2px rgba(255, 255, 255, 0.6),
inset 2px 0 3px 2px rgba(255, 255, 255, 0.6),
inset -10px 0 10px 1px rgba(155, 155, 155, 0.1),
inset 10px 0 10px 1px rgba(155, 155, 155, 0.1);
}' ."\n";
}
else
{
$css .= '#' . $wrapID . ' .elastislide-' . $themeData->image_orientation . ' {
background-color: #fff;
box-shadow: 1px 1px 3px rgba(0,0,0,0.2);
border-radius: 90px/10px;
box-shadow:
0 1px 3px rgba(0, 0, 0, 0.1),
inset -2px 0 3px 2px rgba(255, 255, 255, 0.6),
inset 2px 0 3px 2px rgba(255, 255, 255, 0.6),
inset 0 -10px 10px 1px rgba(155, 155, 155, 0.1),
inset 0 10px 10px 1px rgba(155, 155, 155, 0.1);
}' ."\n";
}
break;
case 'customize':
$css .= '#' . $wrapID . ' .elastislide-' . $themeData->image_orientation . ' {
background-color:' . $themeData->container_background_color . ';
border-color:' . $themeData->container_border_color . ';
border-width:' . $themeData->container_border .'px;
border-style: solid;
border-radius: ' . $themeData->container_round_corner .'px;
-moz-border-radius: ' . $themeData->container_round_corner .'px;
-webkit-border-radius: ' . $themeData->container_round_corner .'px
}' ."\n";
if ($themeData->container_border > 0)
{
$containerBorder = $themeData->container_border;
}
break;
}
$themeData->container_border = $containerBorder;
$themeData->container_side_fade = $themeData->container_side_fade;
$themeDataJson = json_encode($themeData);
$css .= '#' . $wrapID . ' .elastislide-carousel ul li a img {
' . $shadow . '
}' ."\n";
if($themeData->show_caption == 'yes' && ($themeData->caption_show_title == 'yes' || $themeData->caption_show_description == 'yes'))
{
$backgroundColor = $this->hex2rgb($themeData->caption_background_color);
$backgroundOpacity = (float) $themeData->caption_opacity / 100;
$css .= '.jsn-themestrip-gallery-info-'.$args->random_number.' {padding:5px;display:block;background-color:rgb(' . $backgroundColor . ');background-color:rgba(' . $backgroundColor . ',' . $backgroundOpacity . ');}';
$css .= '.jsn-themestrip-gallery-info-title-'.$args->random_number.' {' . $themeData->caption_title_css . '}';
$css .= '.jsn-themestrip-gallery-info-description-'.$args->random_number.' {' . $themeData->caption_description_css . '}';
}
$document->addStyleDeclaration($css);
$html = $pluginOpenTagDiv. '<div class="themestrip-container" id="' . $wrapID . '"><ul class="elastislide-list jsn-themestrip-container" id="' . $galleryID . '">';
$i = 1;
$orientation = $themeData->image_orientation;
$imageSource = ($themeData->image_source == 'thumbnail') ? 'thumbnail' : 'image';
$imageLink = ($themeData->image_click_action == 'show-original-image') ? 'image' : 'link';
$openLinkIn = ($themeData->open_link_in == 'current_browser') ? '' : 'target="_blank"';
$descriptionLenghtLimit = (int) trim($themeData->caption_description_length_limitation);
foreach ($images as $image)
{
$caption = '';
$title = htmlspecialchars($image->title, ENT_QUOTES);
if ($themeData->show_caption == 'yes')
{
if ($themeData->caption_show_title == 'yes' && $image->title != '')
{
$caption .= '<div class="jsn-themestrip-gallery-info-title-' . $args->random_number . '">' . $image->title . '</div>';
}
if($themeData->caption_show_description == 'yes' && $image->description != '')
{
$desc = $this->_wordLimiter($image->description, $descriptionLenghtLimit);
$caption .= '<div class="jsn-themestrip-gallery-info-description-' . $args->random_number . '">' . $desc . '</div>';
}
$caption = htmlspecialchars($caption, ENT_QUOTES);
}
if ($themeData->image_click_action == 'no-action')
{
$imageClickAction = '';
$openLinkIn = '';
}
else
{
$imageClickAction = 'href="' . $image->$imageLink . '"';
}
$html .= '<li>';
$html .= '<a ' . $imageClickAction . ' ' . $openLinkIn . ' title="' . $title . '" rev="' . $caption . '" rel="jsn_is_striptheme_rel_' . $args->random_number . '">';
$html .= '<img height=' . $themeData->image_height . ' width=' . $themeData->image_width . ' style="height:' . $themeData->image_height . 'px; width:' . $themeData->image_width . 'px;" id="themestrip_img_' . $args->random_number . '_' . $i++ . '" src="' . $image->$imageSource . '" border="0" alt="' . $image->title . '"/>';
$html .= '</a></li>';
}
$html .= '</ul></div>' . $pluginCloseTagDiv;
$html .= '<script type="text/javascript">
jsnThemeStripjQuery(function() {
var base_height = 0;
var base_width = 0;
jsnThemeStripjQuery(window).load(function() {
jsnThemeStripjQuery("#' . $galleryID . '").jsnthemestrip("'.$args->random_number.'", ' . $themeDataJson . ');
// Get max height of theme strip items
jsnThemeStripjQuery("#' . $galleryID . '.jsn-themestrip-container img").each(function () {
if (jsnThemeStripjQuery(this).height() >= base_height) {
base_height = jsnThemeStripjQuery(this).height();
base_width = jsnThemeStripjQuery(this).width();
}
var self = this;
ThumbnailImageArray=new Image();
ThumbnailImageArray.src=jsnThemeStripjQuery(this).attr("src");
ThumbnailImageArray.onload=function(){ jsnThemeStripjQuery(window).trigger("resize") };
});
});
jsnThemeStripjQuery(window).resize(function () {
var scale_width = jsnThemeStripjQuery("#' . $galleryID . '.jsn-themestrip-container img").width();
var scale = scale_width / base_width;
jsnThemeStripjQuery("#' . $galleryID . '.jsn-themestrip-container img").height(base_height * scale);
});
});
</script>';
return $html;
}
function displayAlternativeContent()
{
return '';
}
function displaySEOContent($args)
{
$html = '<div class="jsn-'.$this->_themename.'-seocontent">'."\n";
if ($args->edition == 'free')
{
$html .= '<p>Joomla gallery extension by <a href="http://www.joomlashine.com" title="Joomla gallery">joomlashine.com</a></p>'."\n";
}
if (count($args->images))
{
$html .= '<div>';
$html .= '<p>' . @$args->showlist['showlist_title'] . '</p>';
$html .= '<p>' . @$args->showlist['description'] . '</p>';
$html .= '<ul>';
for ($i = 0, $n = count($args->images); $i < $n; $i++)
{
$row =& $args->images[$i];
$html .= '<li>';
if ($row->image_title != '')
{
$html .= '<p>' . $row->image_title . '</p>';
}
if ($row->image_description != '')
{
$html .= '<p>' . $row->image_description . '</p>';
}
if ($row->image_link != '')
{
$html .= '<p><a href="' . $row->image_link . '">' . $row->image_link . '</a></p>';
}
$html .= '</li>';
}
$html .= '</ul></div>';
}
$html .= '</div>' . "\n";
return $html;
}
function display($args)
{
$objUtils = JSNISFactory::getObj('classes.jsn_is_utils');
$string = '';
$args->uri = JURI::base();
$string .= $this->standardLayout($args);
$string .= $this->displaySEOContent($args);
return $string;
}
function getThemeDataStandard($args)
{
if (is_object($args))
{
$path = JPath::clean(JPATH_PLUGINS . DIRECTORY_SEPARATOR . $this->_themetype . DIRECTORY_SEPARATOR . $this->_themename . DIRECTORY_SEPARATOR . 'models');
JModel::addIncludePath($path);
$model = JModel::getInstance($this->_themename);
$themeData = $model->getTable($args->theme_id);
return $themeData;
}
return false;
}
function hex2rgb($hex)
{
$hex = str_replace("#", "", $hex);
if(strlen($hex) == 3)
{
$r = hexdec(substr($hex,0,1).substr($hex,0,1));
$g = hexdec(substr($hex,1,1).substr($hex,1,1));
$b = hexdec(substr($hex,2,1).substr($hex,2,1));
}
else
{
$r = hexdec(substr($hex,0,2));
$g = hexdec(substr($hex,2,2));
$b = hexdec(substr($hex,4,2));
}
$rgb = array($r, $g, $b);
return implode(",", $rgb);
}
function _wordLimiter($str, $limit = 100, $endChar = '…')
{
if (trim($str) == '')
{
return $str;
}
$append = '';
$str = strip_tags(trim($str), '<b><i><s><strong><em><strike><u><br>');
$words = explode(" ", $str);
if(count($words) > $limit)
{
$append = $endChar;
}
return implode(" ", array_splice($words, 0, $limit)) . $append;
}
function loadjQuery()
{
$objUtils = JSNISFactory::getObj('classes.jsn_is_utils');
if (method_exists($objUtils, 'loadJquery'))
{
$objUtils->loadJquery();
}
else
{
JHTML::script('jsn_is_jquery_safe.js',$this->_assetsPath . 'js/');
JHTML::script('jquery.min.js','https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/');
}
}
} | gpl-2.0 |
baxri/cvote | administrator/components/com_componentarchitect/tables/fieldtypes.php | 6756 | <?php
/**
* @version $Id: fieldtypes.php 411 2014-10-19 18:39:07Z BrianWade $
* @name Component Architect (Release 1.1.3)
* @author Component Architect (www.componentarchitect.com)
* @package com_componentarchitect
* @subpackage com_componentarchitect.admin
* @copyright Copyright (c)2013 - 2014 Simply Open Source Ltd. (trading as Component Architect). All Rights Reserved
* @license GNU General Public License version 3 or later; See http://www.gnu.org/copyleft/gpl.html
*
* The following Component Architect header section must remain in any distribution of this file
*
* @CAversion Id: compobjectplural.php 806 2013-12-24 13:24:16Z BrianWade $
* @CAauthor Component Architect (www.componentarchitect.com)
* @CApackage architectcomp
* @CAsubpackage architectcomp.admin
* @CAtemplate joomla_3_x_enhanced (Release 1.0.0)
* @CAcopyright Copyright (c)2013 - 2014 Simply Open Source Ltd. (trading as Component Architect). All Rights Reserved
* @Joomlacopyright Copyright (c)2005 - 2014 Open Source Matters, Inc. All rights reserved.
* @CAlicense GNU General Public License version 3 or later; See http://www.gnu.org/copyleft/gpl.html
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*/
defined('_JEXEC') or die;
if (version_compare(JVERSION, '3.0', 'lt'))
{
jimport('joomla.html.parameter');
}
/**
* FieldType table
*
*/
class ComponentArchitectTableFieldTypes extends JTable
{
/**
* Constructor
*
* @param JDatabaseDriver &$db Database connector object
*
*/
public function __construct(&$db)
{
parent::__construct('#__componentarchitect_fieldtypes', 'id', $db);
$date = JFactory::getDate();
$user = JFactory::getUser();
$this->created = $date->toSQL();
$this->created_by = $user->id;
$this->modified = $date->toSQL();
$this->modified_by = $user->id;
}
/**
* Overloaded check function
*
* @return boolean
*
*/
public function check()
{
// Set name
$this->name = htmlspecialchars_decode($this->name, ENT_QUOTES);
return true;
}
/**
* Overloaded bind function
*
* @param array $array Named array to bind
* @param mixed $ignore An optional array or space separated list of properties to ignore while binding.
*
* @return null|string null is operation was satisfactory, otherwise returns an error
*
*/
public function bind($array, $ignore = array())
{
if ( !array_key_exists('class',$array) )
{
$array['class'] = '0';
}
if ( !array_key_exists('size',$array) )
{
$array['size'] = '0';
}
if ( !array_key_exists('width',$array) )
{
$array['width'] = '0';
}
if ( !array_key_exists('maxlength',$array) )
{
$array['maxlength'] = '0';
}
if ( !array_key_exists('height',$array) )
{
$array['height'] = '0';
}
if ( !array_key_exists('cols',$array) )
{
$array['cols'] = '0';
}
if ( !array_key_exists('rows',$array) )
{
$array['rows'] = '0';
}
if ( !array_key_exists('value_source',$array) )
{
$array['value_source'] = '0';
}
if ( !array_key_exists('option_values',$array) )
{
$array['option_values'] = '0';
}
if ( !array_key_exists('multiple',$array) )
{
$array['multiple'] = '0';
}
if ( !array_key_exists('format',$array) )
{
$array['format'] = '0';
}
if ( !array_key_exists('first',$array) )
{
$array['first'] = '0';
}
if ( !array_key_exists('last',$array) )
{
$array['last'] = '0';
}
if ( !array_key_exists('step',$array) )
{
$array['step'] = '0';
}
if ( !array_key_exists('hide_none',$array) )
{
$array['hide_none'] = '0';
}
if ( !array_key_exists('hide_default',$array) )
{
$array['hide_default'] = '0';
}
if ( !array_key_exists('buttons',$array) )
{
$array['buttons'] = '0';
}
if ( !array_key_exists('hide_buttons',$array) )
{
$array['hide_buttons'] = '0';
}
if ( !array_key_exists('foreign_object_id',$array) )
{
$array['foreign_object_id'] = '0';
}
if ( !array_key_exists('field_filter',$array) )
{
$array['field_filter'] = '0';
}
if ( !array_key_exists('max_file_size',$array) )
{
$array['max_file_size'] = '0';
}
if ( !array_key_exists('exclude_files',$array) )
{
$array['exclude_files'] = '0';
}
if ( !array_key_exists('accept_file_types',$array) )
{
$array['accept_file_types'] = '0';
}
if ( !array_key_exists('directory',$array) )
{
$array['directory'] = '0';
}
if ( !array_key_exists('link',$array) )
{
$array['link'] = '0';
}
if ( !array_key_exists('sql_query',$array) )
{
$array['sql_query'] = '0';
}
if ( !array_key_exists('sql_key_field',$array) )
{
$array['sql_key_field'] = '0';
}
if ( !array_key_exists('sql_value_field',$array) )
{
$array['sql_value_field'] = '0';
}
if ( !array_key_exists('translate',$array) )
{
$array['translate'] = '0';
}
if ( !array_key_exists('client',$array) )
{
$array['client'] = '0';
}
if ( !array_key_exists('stripext',$array) )
{
$array['stripext'] = '0';
}
if ( !array_key_exists('preview',$array) )
{
$array['preview'] = '0';
}
if ( !array_key_exists('autocomplete',$array) )
{
$array['autocomplete'] = '0';
}
if ( !array_key_exists('onclick',$array) )
{
$array['onclick'] = '0';
}
if ( !array_key_exists('onchange',$array) )
{
$array['onchange'] = '0';
}
return parent::bind($array, $ignore);
}
/**
* Stores a Field Type
*
* @param boolean $update_nulls True to update fields even if they are null.
*
* @return boolean $result True on success, false on failure.
*
*/
public function store($update_nulls = false)
{
$date = JFactory::getDate();
$user = JFactory::getUser();
if (empty($this->id))
{
// New Field Type. A created and created_by field can be set by the user,
// so we don't touch either of these if they are set.
if (!intval($this->created))
{
$this->created = $date->toSQL();
}
if (empty($this->created_by))
{
$this->created_by = $user->get('id');
}
}
// Existing item
$this->modified = $date->toSQL();
$this->modified_by = $user->get('id');
// Attempt to store the data.
return parent::store($update_nulls);
}
}
| gpl-2.0 |
marioli/havp-ng | havp/scanners/avgscanner.cpp | 4971 | /***************************************************************************
avgscanner.cpp - description
-------------------
begin : Sa Feb 12 2005
copyright : (C) 2005 by Christian Hilgers
email : christian@havp.org
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "avgscanner.h"
bool AVGScanner::InitDatabase()
{
return true;
}
int AVGScanner::ReloadDatabase()
{
return 0;
}
string AVGScanner::Scan( const char *FileName )
{
if ( AVGSocket.ConnectToServer() == false )
{
AVGSocket.Close();
//Prevent log flooding, show error only once per minute
if ( (LastError == 0) || (LastError + 60 < time(NULL)) )
{
LogFile::ErrorMessage("AVG: Could not connect to scanner! Scanner down?\n");
LastError = time(NULL);
}
ScannerAnswer = "2Could not connect to scanner";
return ScannerAnswer;
}
string Response;
AVGSocket.Recv( Response, true, 5 );
if ( MatchSubstr( Response, "220 Ready", -1 ) == false )
{
AVGSocket.Close();
LogFile::ErrorMessage("AVG: Invalid greeting from scanner (%s)\n", Response.c_str());
ScannerAnswer = "2Invalid greeting from scanner";
return ScannerAnswer;
}
//Construct command for scanner
ScannerCmd = "SCAN ";
ScannerCmd += FileName;
ScannerCmd += "\r\n";
if ( AVGSocket.Send( ScannerCmd ) == false )
{
AVGSocket.Close();
LogFile::ErrorMessage("AVG: Could not connect to scanner\n");
ScannerAnswer = "2Could not call scanner";
return ScannerAnswer;
}
Response = "";
int ret;
ret = AVGSocket.Recv( Response, true, 600 );
if (ret < 0)
{
AVGSocket.Close();
LogFile::ErrorMessage("AVG: Could not read scanner response\n");
ScannerAnswer = "2Could not read scanner response";
return ScannerAnswer;
}
string Quit = "QUIT\r\n";
AVGSocket.Send( Quit );
AVGSocket.Recv( Quit, true, 2 );
AVGSocket.Close();
if ( Response.length() < 5 )
{
LogFile::ErrorMessage("AVG: Invalid response from scanner, report to developer (%s)\n", Response.c_str());
ScannerAnswer = "2Invalid response from scanner";
return ScannerAnswer;
}
if ( MatchSubstr( Response, "200 ok", -1 )
|| MatchSubstr( Response, "200 OK", -1 ) )
{
ScannerAnswer = "0Clean";
return ScannerAnswer;
}
string::size_type Position;
if ( ( Position = Response.find( "403 File" )) != string::npos )
{
string::size_type PositionEnd, PositionStart;
PositionEnd = Response.find("\n", Position + 10);
PositionStart = Response.rfind(" ", PositionEnd - 3);
string vname = Response.substr( PositionStart + 1, PositionEnd - PositionStart - 2);
if (vname.rfind(" ") == vname.length() - 1) vname = vname.substr( 0, vname.length() - 1 );
ScannerAnswer = "1" + vname;
return ScannerAnswer;
}
//If AVG is reloading patterns, it will give error, just skip it
if ( MatchSubstr( Response, "406 Error", -1 ) )
{
ScannerAnswer = "0Clean";
return ScannerAnswer;
}
// Log errors
if ( MatchSubstr( Response, "local error", -1 ) )
{
LogFile::ErrorMessage("AVG: Scanner error: %s\n", Response.c_str());
ScannerAnswer = "2Scanner error";
return ScannerAnswer;
}
//LogFile::ErrorMessage("AVG: Unknown response from scanner, report to developer (%s)\n", Response.c_str());
//ScannerAnswer = "2Unknown response from scanner: " + Response;
//return ScannerAnswer;
//Just return clean for anything else right now..
ScannerAnswer = "0Clean";
return ScannerAnswer;
}
void AVGScanner::FreeDatabase()
{
}
//Constructor
AVGScanner::AVGScanner()
{
ScannerName = "AVG Socket Scanner";
ScannerNameShort = "AVG";
LastError = 0;
if ( AVGSocket.SetDomainAndPort( Params::GetConfigString("AVGSERVER"), Params::GetConfigInt("AVGPORT") ) == false )
{
LogFile::ErrorMessage("AVG: Could not resolve scanner host\n");
}
ScannerAnswer.reserve(100);
}
//Destructor
AVGScanner::~AVGScanner()
{
}
| gpl-2.0 |
agutheil/ftds | example/src/main/java/de/agutheil/ftds/example/solid/ocp/Kreis.java | 133 | package de.agutheil.ftds.example.solid.ocp;
public class Kreis extends Geom {
public Kreis() {
super();
type = "Kreis";
}
}
| gpl-2.0 |
joseclavijo/gsclube | wp-content/plugins/gantry5/src/classes/Gantry/WordPress/Assignments/AssignmentsInterface.php | 558 | <?php
/**
* @package Gantry5
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2015 RocketTheme, LLC
* @license GNU/GPLv2 and later
*
* http://www.gnu.org/licenses/gpl-2.0.html
*/
namespace Gantry\WordPress\Assignments;
interface AssignmentsInterface
{
/**
* Returns list of rules which apply to the current page.
*
* @return array
*/
public function getRules();
/**
* List all the rules available.
*
* @return array
*/
public function listRules();
}
| gpl-2.0 |
candramelon/nsa | admin/views/manual_page/form.php | 3976 | <!-- Content Header (Page header) -->
<?php
if(isset($_GET['did']) && $_GET['did'] == 1){
?>
<section class="content_new">
<div class="alert alert-info alert-dismissable">
<i class="fa fa-check"></i>
<button class="close" aria-hidden="true" data-dismiss="alert" type="button">×</button>
<b>Simpan gagal !</b>
Password dan confirm password tidak sama
</div>
</section>
<?php
}
?>
<?php
if(isset($_GET['did']) && $_GET['did'] == 2){
?>
<section class="content_new">
<div class="alert alert-info alert-dismissable">
<i class="fa fa-check"></i>
<button class="close" aria-hidden="true" data-dismiss="alert" type="button">×</button>
<b>Simpan sukses!</b>
</div>
</section>
<?php
}
?>
<!-- Main content -->
<section class="content">
<div class="row">
<!-- right column -->
<div class="col-md-12">
<!-- general form elements disabled -->
<div class="title_page"> <?= $row->page_title ?></div>
<form class="cmxform" id="createForm" action="<?= $action?>" method="post" enctype="multipart/form-data" role="form">
<div class="box box-cokelat">
<div class="box-body">
<div class="col-md-12">
<div class="form-group">
<label>Title</label>
<input required type="text" name="i_title" class="form-control" placeholder="" value="<?= $row->page_title ?>" title="Kode kontrak tidak boleh kosong"/>
</div>
<textarea id="editor" name="editor" rows="10" cols="80">
<?php
echo $row->page_desc;
?>
</textarea>
</div>
<div style="clear:both;"></div>
</div><!-- /.box-body -->
<div class="box-footer">
<input class="btn btn-success" type="submit" value="Save"/>
<a href="<?= $close_button?>" class="btn btn-success" >Close</a>
</div>
</div><!-- /.box -->
</form>
</div><!--/.col (right) -->
</div> <!-- /.row -->
</section><!-- /.content --> | gpl-2.0 |
dos1/Gogomoku | java/game/Game.java | 2414 | package game;
import java.util.Date;
import playState.PlayState;
import pawn.BlackPawn;
import pawn.Pawn;
import pawn.WhitePawn;
import gameboard.Gameboard;
import gameboard.Gameboard.MoveOutOfBounds;
import history.History;
import field.Field;
import field.Field.UnallowedMove;
public class Game {
private PlayState state_play;
private Date time_begin;
private Date time_end;
private Pawn who_next;
private Gameboard board;
private History the_story;
private int moves_done;
public Game() {
who_next = null;
board = new Gameboard(this);
the_story = new History();
this.newGame();
}
public void finalize() {}
public void newGame() {
time_begin = new Date();
time_end = null;
who_next = new BlackPawn();
state_play = PlayState.InProgress;
moves_done = 0;
the_story.cleanHistory();
board.cleanBoard();
}
public int numberOfMoves() {
return moves_done;
}
private void nextTurn() {
if (who_next.getColor() == 0)
who_next = new BlackPawn();
else
who_next = new WhitePawn();
moves_done++;
}
private void undoTurn() {
if (who_next.getColor() == 0)
who_next = new BlackPawn();
else
who_next = new WhitePawn();
moves_done--;
}
public int getNextPlayer() {
return who_next.getColor();
}
public PlayState winning(int who) {
if (who == 0)
state_play = PlayState.WinWhite;
else
state_play = PlayState.WinBlack;
stopTimer();
return state_play;
}
public PlayState drawing() {
state_play = PlayState.Draw;
stopTimer();
return state_play;
}
public void addHistory(Field next) {
the_story.addToHistory(next);
}
public void revertLastMove() {
Field pom;
if (the_story.notEmpty()) {
pom = the_story.takeFromHistory();
board.revertMove(pom.getX(), pom.getY());
undoTurn();
}
}
public Pawn whoNext() {
return who_next;
}
public PlayState getState() {
return state_play;
}
public void stopTimer() {
time_end = new Date();
}
public Date gameTime() {
if (time_end != null)
return new Date(time_end.getTime() - time_begin.getTime());
else
return new Date(new Date().getTime() - time_begin.getTime());
}
public Gameboard getBoard() {
return board;
}
public void makeMove(int x, int y) throws UnallowedMove, MoveOutOfBounds {
board.makeMove(x, y);
this.nextTurn();
}
}
| gpl-2.0 |
matthias-fue/kipi-plugins | flickr/login.cpp | 3680 | /* ============================================================
*
* This file is a part of kipi-plugins project
* http://www.digikam.org
*
* Date : 2005-07-07
* Description : a kipi plugin to export images to Flickr web service
*
* Copyright (C) 2005-2008 by Vardhman Jain <vardhman at gmail dot com>
*
* This program is free software; you can redistribute it
* and/or modify it under the terms of the GNU General
* Public License as published by the Free Software Foundation;
* either version 2, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* ============================================================ */
#include "login.h"
// Qt includes
#include <QGridLayout>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QDialogButtonBox>
#include <QDialog>
#include <QFrame>
// KDE includes
#include <klocalizedstring.h>
#include <kconfiggroup.h>
namespace KIPIFlickrPlugin
{
FlickrLogin::FlickrLogin(QWidget* const parent, const QString& header,
const QString& _name, const QString& _passwd)
: QDialog(parent)
{
setWindowTitle(header);
const int spacing = QApplication::style()->pixelMetric(QStyle::PM_DefaultLayoutSpacing);
QDialogButtonBox* const buttonBox = new QDialogButtonBox(QDialogButtonBox::Help|QDialogButtonBox::Ok|QDialogButtonBox::Cancel);
QVBoxLayout* const mainLayout = new QVBoxLayout(this);
setLayout(mainLayout);
QPushButton* const okButton = buttonBox->button(QDialogButtonBox::Ok);
connect(buttonBox, SIGNAL(accepted()),
this, SLOT(accept()));
connect(buttonBox, SIGNAL(rejected()),
this, SLOT(reject()));
okButton->setDefault(true);
setModal(false);
m_headerLabel = new QLabel(this);
m_headerLabel->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed));
m_headerLabel->setText(header);
QFrame* const hline = new QFrame(this);
hline->setLineWidth(1);
hline->setMidLineWidth(0);
hline->setFrameShape(QFrame::HLine);
hline->setFrameShadow(QFrame::Sunken);
hline->setMinimumSize(0, 2);
hline->updateGeometry();
QGridLayout* const centerLayout = new QGridLayout();
m_nameEdit = new QLineEdit(this);
m_passwdEdit = new QLineEdit(this);
m_passwdEdit->setEchoMode(QLineEdit::Password);
QLabel* const nameLabel = new QLabel(this);
nameLabel->setText(i18nc("flickr login", "Username:"));
QLabel* const passwdLabel = new QLabel(this);
passwdLabel->setText(i18n("Password:"));
centerLayout->addWidget(m_nameEdit, 0, 1);
centerLayout->addWidget(m_passwdEdit, 1, 1);
centerLayout->addWidget(nameLabel, 0, 0);
centerLayout->addWidget(passwdLabel, 1, 0);
centerLayout->setContentsMargins(spacing, spacing, spacing, spacing);
centerLayout->setSpacing(spacing);
mainLayout->addWidget(m_headerLabel);
mainLayout->addWidget(hline);
mainLayout->addWidget(buttonBox);
mainLayout->addLayout(centerLayout);
mainLayout->setContentsMargins(QMargins());
mainLayout->setSpacing(spacing);
resize(QSize(300, 150).expandedTo(minimumSizeHint()));
m_nameEdit->setText(_name);
m_passwdEdit->setText(_passwd);
}
FlickrLogin::~FlickrLogin()
{
}
QString FlickrLogin::name() const
{
return m_nameEdit->text();
}
QString FlickrLogin::password() const
{
return m_passwdEdit->text();
}
} // namespace KIPIFlickrPlugin
| gpl-2.0 |
iWantMoneyMore/ykj | ykj-api/src/main/java/com/gnet/app/customerHouseProperty/CustomerHousePropertyErrorBuilder.java | 1394 | package com.gnet.app.customerHouseProperty;
import com.gnet.resource.errorBuilder.BaseErrorBuilder;
public class CustomerHousePropertyErrorBuilder extends BaseErrorBuilder{
/**
* 客户房产信息的编号为空
*/
public static final Integer ERROR_ID_NULL = 10701;
/**
* 客户房产信息为空
*/
public static final Integer ERROR_CUSTOMER_HOUSE_PROPERTY_NULL = 10702;
/** 楼盘名称为空 **/
public static final Integer ERROR_BUILDING_NAME_NULL = 10703;
/** 风格为空 **/
public static final Integer ERROR_ROOM_STYLE_NULL = 10704;
/** 装修进度为空 **/
public static final Integer ERROR_DECORATE_PROCESS_NULL = 10705;
/** 装修类型为空 **/
public static final Integer ERROR_DECORATE_TYPE_NULL = 10706;
/** 户型为空 **/
public static final Integer ERROR_ROOM_MODEL_NULL = 10707;
/** 没有这种装修风格 **/
public static final Integer ERROR_ROOM_STYLE = 10708;
/** 没有这种装修进度 **/
public static final Integer ERROR_DECORATE_PROCESS = 10709;
/** 没有这种装修类型 **/
public static final Integer ERROR_DECORATE_TYPE = 10710;
/** 没有这种户型 **/
public static final Integer ERROR_ROOM_MODEL = 10711;
public CustomerHousePropertyErrorBuilder(Integer code, String msg) {
super(code, msg);
}
}
| gpl-2.0 |
Pengfei-Gao/source-Insight-3-for-centos7 | SourceInsight3/NetFramework/ISymbolBinder.cs | 151 | public interface ISymbolBinder
{
// Methods
public abstract virtual ISymbolReader GetReader(int importer, string filename, string searchPath) {}
}
| gpl-2.0 |
abondoa/adaos | src/Adaos.Shell.Execution/VirtualMachine.cs | 7292 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Adaos.Shell.Interface;
using Adaos.Shell.Interface.SyntaxAnalysis;
using Adaos.Shell.Interface.Execution;
using Adaos.Shell.Interface.Exceptions;
using Adaos.Shell.SyntaxAnalysis.Parsing;
using System.IO;
using Adaos.Shell.ModuleHandling;
namespace Adaos.Shell.Execution
{
public class VirtualMachine : IVirtualMachine
{
private IShellParser _parser;
private StreamWriter _output;
private StreamWriter _log;
private IResolver _resolver;
private IModuleManager _moduleManager;
private IEnvironmentContainer _envContainer;
private IEnumerable<IArgument>[] NoArguments = new IEnumerable<IArgument>[] {new IArgument[0] };
private IShellExecutor _shellExecutor;
public VirtualMachine(StreamWriter output, StreamWriter log)
{
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
if (log == null)
{
throw new ArgumentNullException(nameof(log));
}
_output = output;
_log = log;
_parser = new Parser();
_resolver = new Resolver();
_moduleManager = new ModuleManager();
_shellExecutor = new ShellExecutor();
_envContainer = new EnvironmentContainer(Library.StandardLibraryContextBuilder.Instance.BuildEnvironments(this));
}
public VirtualMachine(StreamWriter output, StreamWriter log, IEnvironmentContainer container)
{
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
if (log == null)
{
throw new ArgumentNullException(nameof(log));
}
if (container == null)
{
throw new ArgumentNullException(nameof(container));
}
_output = output;
_log = log;
_envContainer = container;
_parser = new Parser();
_resolver = new Resolver();
_moduleManager = new ModuleManager();
_shellExecutor = new ShellExecutor();
}
public VirtualMachine(IVirtualMachine virtualMachine) : this(virtualMachine.Log,virtualMachine.Output, virtualMachine.EnvironmentContainer)
{
}
public virtual void Execute(string command)
{
try
{
InternExecute(command).ToArray();
}
catch (ExitTerminalException)
{
throw;
}
catch (AdaosException e)
{
HandleError(e);
}
/*catch (Exception e)
{
HandleError(new UndefinedException(-1,"Unknown", e));
}*/
}
public IEnumerable<IArgument> InternExecute(string command, int initialPosition = 0)
{
IExecutionSequence prog = _parser.Parse(command, initialPosition);
if (prog.Errors.Count() > 0)
{
foreach (var error in prog.Errors)
{
HandleError(error);
}
return new List<IArgument>();
}
return ShellExecutor.Execute(prog,this);
}
#region Properties
public IShellParser Parser
{
get
{
return _parser;
}
set
{
if (value == null) throw new ArgumentNullException("Parser");
_parser = value;
}
}
public StreamWriter Output
{
get
{
return _output;
}
set
{
if (value == null) throw new ArgumentNullException("Output");
_output = value;
}
}
public StreamWriter Log
{
get
{
return _log;
}
set
{
if (value == null) throw new ArgumentNullException("Log");
_log = value;
}
}
public IModuleManager ModuleManager
{
get
{
return _moduleManager;
}
set
{
if (value == null) throw new ArgumentNullException("ModuleManager");
_moduleManager = value;
}
}
public IResolver Resolver
{
get
{
return _resolver;
}
set
{
if (value == null) throw new ArgumentNullException("Resolver");
_resolver = value;
}
}
public IEnvironmentContainer EnvironmentContainer
{
get
{
return _envContainer;
}
set
{
if (value == null) throw new ArgumentNullException(nameof(EnvironmentContainer));
_envContainer = value;
}
}
public IShellExecutor ShellExecutor
{
get
{
return _shellExecutor;
}
set
{
if (value == null) throw new ArgumentNullException(nameof(ShellExecutor));
_shellExecutor = value;
}
}
public ErrorHandler HandleError
{
get
{
return ShellExecutor.HandleError;
}
set
{
ShellExecutor.HandleError = value;
}
}
#endregion Properties
public string SuggestCommand(string partialCommand)
{
IExecutionSequence prog = _parser.Parse(partialCommand);
var lastCommand = prog.Executions.LastOrDefault();
if (lastCommand == null)
return null;
string qualifiedEnvName = lastCommand.EnvironmentNames.Aggregate (
(x,y) => x + Parser.ScannerTable.EnvironmentSeparator + y);
var envs = EnvironmentContainer.EnabledEnvironments.Where(y => y.Name.StartsWith(qualifiedEnvName));
if (envs.FirstOrDefault() != null && envs.Skip(1).FirstOrDefault() == null)
{
StringBuilder suggestion = new StringBuilder (envs.First().Name);
if (envs.First().Name == qualifiedEnvName)
{
var cmds = envs.First ().Commands.Where(x => x.StartsWith(lastCommand.CommandName));
if (cmds.FirstOrDefault () != null && cmds.Skip (1).FirstOrDefault () == null)
{
suggestion.Append(_parser.ScannerTable.EnvironmentSeparator + cmds.First());
}
}
return suggestion.ToString();
}
return null;
}
public IEnumerable<IArgument> Execute(IExecutionSequence prog)
{
return ShellExecutor.Execute(prog, this);
}
public IEnumerable<IArgument> Execute(IExecutionSequence prog, IEnumerable<IArgument>[] args)
{
return ShellExecutor.Execute(prog, args, this);
}
}
}
| gpl-2.0 |
danyim/advanced-gulp-wordpress | src/comments.php | 2744 | <?php
/**
* The template for displaying comments.
*
* The area of the page that contains both current comments
* and the comment form.
*
* @package NeatBootstrap
*/
/*
* If the current post is protected by a password and
* the visitor has not yet entered the password we will
* return early without loading the comments.
*/
if ( post_password_required() ) {
return;
}
?>
<div id="comments" class="comments-area">
<?php // You can start editing here -- including this comment! ?>
<?php if ( have_comments() ) : ?>
<h2 class="comments-title">
<?php
printf(
esc_html( _nx( 'One thought on “%2$s”', '%1$s thoughts on “%2$s”', get_comments_number(), 'comments title', 'neat' ) ),
number_format_i18n( get_comments_number() ),
'<span>' . get_the_title() . '</span>'
);
?>
</h2>
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
<nav id="comment-nav-above" class="navigation comment-navigation" role="navigation">
<h2 class="screen-reader-text"><?php esc_html_e( 'Comment navigation', 'neat' ); ?></h2>
<div class="nav-links">
<div class="nav-previous"><?php previous_comments_link( esc_html__( 'Older Comments', 'neat' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( esc_html__( 'Newer Comments', 'neat' ) ); ?></div>
</div><!-- .nav-links -->
</nav><!-- #comment-nav-above -->
<?php endif; // check for comment navigation ?>
<ol class="comment-list">
<?php
wp_list_comments( array(
'style' => 'ol',
'short_ping' => true,
) );
?>
</ol><!-- .comment-list -->
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
<nav id="comment-nav-below" class="navigation comment-navigation" role="navigation">
<h2 class="screen-reader-text"><?php esc_html_e( 'Comment navigation', 'neat' ); ?></h2>
<div class="nav-links">
<div class="nav-previous"><?php previous_comments_link( esc_html__( 'Older Comments', 'neat' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( esc_html__( 'Newer Comments', 'neat' ) ); ?></div>
</div><!-- .nav-links -->
</nav><!-- #comment-nav-below -->
<?php endif; // check for comment navigation ?>
<?php endif; // have_comments() ?>
<?php
// If comments are closed and there are comments, let's leave a little note, shall we?
if ( ! comments_open() && '0' != get_comments_number() && post_type_supports( get_post_type(), 'comments' ) ) :
?>
<p class="no-comments"><?php esc_html_e( 'Comments are closed.', 'neat' ); ?></p>
<?php endif; ?>
<?php comment_form(); ?>
</div><!-- #comments -->
| gpl-2.0 |
jhonrsalcedo/sitio | wp-config.php | 3005 | <?php
/**
* The base configurations of the WordPress.
*
* This file has the following configurations: MySQL settings, Table Prefix,
* Secret Keys, and ABSPATH. You can find more information by visiting
* {@link https://codex.wordpress.org/Editing_wp-config.php Editing wp-config.php}
* Codex page. You can get the MySQL settings from your web host.
*
* This file is used by the wp-config.php creation script during the
* installation. You don't have to use the web site, you can just copy this file
* to "wp-config.php" and fill in the values.
*
* @package WordPress
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'viviend1_wp270');
/** MySQL database username */
define('DB_USER', 'root');
/** MySQL database password */
define('DB_PASSWORD', 'c0419004');
/** MySQL hostname */
define('DB_HOST', 'localhost');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define('AUTH_KEY', 'xbsa2k9bxz4g9ulsr8j9gxbemc0cdvgzjekkaanyqdvjhuq5flnvxryt7jfg7bhq');
define('SECURE_AUTH_KEY', '7b8vhv3mjwzazwhwf19mi3dpsskbxu7cgq4jncbbnm4lsgu5khtc943y1hqskap8');
define('LOGGED_IN_KEY', 'j3ubjatvyhh3hheqaui0umucqhpgd7h6kg0nzh1ycuqqfo4nuxrdbua4sq6xwvgq');
define('NONCE_KEY', 'xvstjcnlk5ivg5ertd7a8cqa8q9vsfadbs5rgjrlcvifcaybg9uswctuparmrwzn');
define('AUTH_SALT', 'eattsjcenwbvmit8ntxvy6kn5g63fa4kech3kakojsol2ycpudz1gk1dqlhscy2c');
define('SECURE_AUTH_SALT', 'sirqial1rokjdjfixblqqgjhtzeocgvaqlfw6la4tfkloomvev6awryfgufydq0q');
define('LOGGED_IN_SALT', '1ji1gdb9vmzpfzlshljd5isppxvkj6n6fpkzbtfhbdj7ruh2au241d9qgkmxcy67');
define('NONCE_SALT', 'oarjfo4anns3nunusjjfmkr8wnymchekhkl8ozhcvxuxymeq3luzxohagw41rziu');
/**#@-*/
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each a unique
* prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'wp_';
/**
* For developers: WordPress debugging mode.
*
* Change this to true to enable the display of notices during development.
* It is strongly recommended that plugin and theme developers use WP_DEBUG
* in their development environments.
*/
define('WP_DEBUG', false);
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
| gpl-2.0 |
mfursov/ugene | src/plugins/dbi_bam/src/SamReader.cpp | 21739 | /**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2017 UniPro <ugene@unipro.ru>
* http://ugene.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <U2Core/U2AssemblyUtils.h>
#include <U2Core/Log.h>
#include "BAMDbiPlugin.h"
#include "InvalidFormatException.h"
#include "SamReader.h"
#include "CigarValidator.h"
#include <SamtoolsAdapter.h>
namespace U2 {
namespace BAM {
const int SamReader::LOCAL_READ_BUFFER_SIZE = 100000;
Alignment SamReader::parseAlignmentString(QByteArray line) {
Alignment alignment;
if(line.isEmpty()) {
assert(0);
throw InvalidFormatException(BAMDbiPlugin::tr("Unexpected empty string"));
}
QByteArray recordTag;
QHash<QByteArray, QByteArray> fields;
QList<QByteArray> tokens = line.split('\t');
if (tokens.length() < 11) {
throw InvalidFormatException(BAMDbiPlugin::tr("Not enough fields in one of alignments"));
}
{
QByteArray &qname = tokens[0];
// workaround for malformed SAMs
if(!QRegExp("[ -~]{1,255}").exactMatch(qname)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid query template name: %1").arg(QString(qname)));
}
alignment.setName(qname);
}
{
bool ok = false;
int flagsValue = tokens[1].toInt(&ok);
if(!ok) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid FLAG value: %1").arg(QString(tokens[1])));
}
qint64 flags = 0;
if(flagsValue & 0x1) {
flags |= Fragmented;
}
if(flagsValue & 0x2) {
flags |= FragmentsAligned;
}
if(flagsValue & 0x4) {
flags |= Unmapped;
}
if(flagsValue & 0x8) {
flags |= NextUnmapped;
}
if(flagsValue & 0x10) {
flags |= Reverse;
}
if(flagsValue & 0x20) {
flags |= NextReverse;
}
if(flagsValue & 0x40) {
flags |= FirstInTemplate;
}
if(flagsValue & 0x80) {
flags |= LastInTemplate;
}
if(flagsValue & 0x100) {
flags |= SecondaryAlignment;
}
if(flagsValue & 0x200) {
flags |= FailsChecks;
}
if(flagsValue & 0x400) {
flags |= Duplicate;
}
alignment.setFlags(flags);
}
{
QByteArray &rname = tokens[2];
// workaround for malformed SAMs
if(!QRegExp("[*]|[!-()+-<>-~][ -~]*").exactMatch(rname)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid reference name: %1").arg(QString(rname)));
}
if ("*" == rname) {
alignment.setReferenceId(-1);
} else {
if (!referencesMap.contains(rname)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Undefined reference name: %1").arg(QString(rname)));
}
alignment.setReferenceId(referencesMap[rname]);
}
}
{
bool ok = false;
int position = tokens[3].toInt(&ok);
if(!ok) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid read position value: %1").arg(QString(tokens[3])));
}
if(position < 0) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid read position: %1").arg(position));
}
alignment.setPosition(position - 1); //to 0-based mapping
}
{
bool ok = false;
int mapQuality = tokens[4].toInt(&ok);
if(!ok) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mapping quality value: %1").arg(QString(tokens[4])));
}
if(mapQuality < 0 || mapQuality > 255) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mapping quality: %1").arg(mapQuality));
}
alignment.setMapQuality(mapQuality);
}
{
QByteArray &cigarString = tokens[5];
if(!QRegExp("[*]|([0-9]+[MIDNSHPX=])+").exactMatch(cigarString)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid cigar value: %1").arg(QString(cigarString)));
}
if ("*" != cigarString) {
QString err;
QList<U2CigarToken> res = U2AssemblyUtils::parseCigar(cigarString, err);
if (!err.isEmpty()) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid cigar value: %1").arg(QString(cigarString)));
}
QList<Alignment::CigarOperation> cigar;
for(int i = 0; i < res.length(); i++) {
Alignment::CigarOperation::Operation operation;
switch(res[i].op) {
case U2CigarOp_M:
operation = Alignment::CigarOperation::AlignmentMatch;
break;
case U2CigarOp_I:
operation = Alignment::CigarOperation::Insertion;
break;
case U2CigarOp_D:
operation = Alignment::CigarOperation::Deletion;
break;
case U2CigarOp_N:
operation = Alignment::CigarOperation::Skipped;
break;
case U2CigarOp_S:
operation = Alignment::CigarOperation::SoftClip;
break;
case U2CigarOp_H:
operation = Alignment::CigarOperation::HardClip;
break;
case U2CigarOp_P:
operation = Alignment::CigarOperation::Padding;
break;
case U2CigarOp_EQ:
operation = Alignment::CigarOperation::SequenceMatch;
break;
case U2CigarOp_X:
operation = Alignment::CigarOperation::SequenceMismatch;
break;
default:
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid cigar operation code: %1").arg(res[i].op));
}
int operatonLength = res[i].count;
cigar.append(Alignment::CigarOperation(operatonLength, operation));
}
alignment.setCigar(cigar);
}
}
{
QByteArray nextReference = tokens[6];
// workaround for malformed SAMs
if(!QRegExp("[*]|[=]|[!-()+-<>-~][ -~]*").exactMatch(nextReference)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mate reference name: %1").arg(QString(nextReference)));
}
if ("*" == nextReference) {
alignment.setNextReferenceId(-1);
} else if ("=" == nextReference) {
alignment.setNextReferenceId(alignment.getReferenceId());
} else {
if (!referencesMap.contains(nextReference)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Undefined mate reference name: %1").arg(QString(nextReference)));
}
alignment.setNextReferenceId(referencesMap[nextReference]);
}
alignment.setNextReferenceName(nextReference);
}
{
bool ok = false;
int nextPosition = tokens[7].toInt(&ok);
if(!ok) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mate position value: %1").arg(QString(tokens[7])));
}
if(nextPosition < 0) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mate position: %1").arg(nextPosition));
}
alignment.setNextPosition(nextPosition - 1); //to 0-based mapping
}
{
bool ok = false;
int templateLength = tokens[8].toInt(&ok);
if(!ok) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid template length value: %1").arg(QString(tokens[8])));
}
if(!(alignment.getFlags() & Fragmented)) {
if(0 != templateLength) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid template length of a single-fragment template: %1").arg(templateLength));
}
}
alignment.setTemplateLength(templateLength);
}
{
QByteArray sequence = tokens[9];
if(!QRegExp("[*]|[A-Za-z=.]+").exactMatch(sequence)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid sequence: %1").arg(QString(sequence)));
}
alignment.setSequence(sequence);
}
{
QByteArray quality = tokens[10];
if ("*" != quality) {
if(QRegExp("[!-~]+").exactMatch(quality)) {
alignment.setQuality(quality);
}
}
}
{
QByteArray samAuxString;
bool first = true;
QMap<QByteArray, QVariant> optionalFields;
for (int i = 11; i < tokens.length(); i++) {
if (!first) {
samAuxString += '\t';
}
samAuxString += tokens[i];
first = false;
}
alignment.setAuxData(SamtoolsAdapter::samString2aux(samAuxString));
}
{
// Validation of the CIGAR string.
int totalLength = 0;
int length = alignment.getSequence().length();
const QList<Alignment::CigarOperation> &cigar = alignment.getCigar();
CigarValidator validator(cigar);
validator.validate(&totalLength);
if(!cigar.isEmpty() && length != totalLength) {
const_cast<QList<Alignment::CigarOperation>&>(cigar).clear(); //Ignore invalid cigar
}
}
return alignment;
}
SamReader::SamReader(IOAdapter &ioAdapter):
Reader(ioAdapter),
readBuffer(LOCAL_READ_BUFFER_SIZE, '\0')
{
readHeader();
}
const Header &SamReader::getHeader()const {
return header;
}
Alignment SamReader::readAlignment(bool &eof) {
QByteArray alignmentString = readString(eof);
return parseAlignmentString(alignmentString);
}
bool SamReader::isEof()const {
return ioAdapter.isEof();
}
QByteArray SamReader::readString(bool &eof) {
char* buff = readBuffer.data();
bool lineOk = false;
int len = 0;
QByteArray result;
while((len = ioAdapter.readLine(buff, LOCAL_READ_BUFFER_SIZE, &lineOk)) == 0) {}
if (len == -1) {
eof = true;
} else {
result = QByteArray::fromRawData(buff, len);
}
return result;
}
void SamReader::readHeader() {
char* buff = readBuffer.data();
bool lineOk = false;
int len = 0;
qint64 bRead = ioAdapter.bytesRead();
QList<Header::Reference> references;
{
QList<Header::ReadGroup> readGroups;
QList<Header::Program> programs;
QList<QByteArray> previousProgramIds;
while ((len = ioAdapter.readLine(buff, LOCAL_READ_BUFFER_SIZE, &lineOk)) >= 0) {
if(isEof()){
break;
}
QByteArray line = QByteArray::fromRawData(buff, len);
if(line.isEmpty()) {
continue;
}
if(line.startsWith("@CO")) {
continue;
}
if(!line.startsWith('@')) {
ioAdapter.skip(bRead - ioAdapter.bytesRead());
break;
}
bRead = ioAdapter.bytesRead();
QByteArray recordTag;
QHash<QByteArray, QByteArray> fields;
{
QList<QByteArray> tokens = line.split('\t');
recordTag = tokens[0].mid(1);
if(!QRegExp("[A-Za-z][A-Za-z]").exactMatch(recordTag)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid header record tag: %1").arg(QString(recordTag)));
}
for(int index = 1;index < tokens.size();index++) {
QByteArray fieldTag;
QByteArray fieldValue;
{
int colonIndex = tokens[index].indexOf(':');
if(-1 != colonIndex) {
fieldTag = tokens[index].mid(0, colonIndex);
fieldValue = tokens[index].mid(colonIndex + 1);
} else if("PG" == recordTag) { // workaround for invalid headers produced by some programs
continue;
} else {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid header field: %1").arg(QString(tokens[index])));
}
}
if(!QRegExp("[A-Za-z][A-Za-z]").exactMatch(fieldTag) && "M5" != fieldTag) { //workaround for bug in the spec
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid header field tag: %1").arg(QString(fieldTag)));
}
// CL and PN tags of can contain any string
if(fieldTag!="CL" && fieldTag!="PN" && !QRegExp("[ -~]+").exactMatch(fieldValue)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid %1-%2 value: %3").arg(QString(recordTag)).arg(QString(fieldTag)).arg(QString(fieldValue)));
}
if(!fields.contains(fieldTag)) {
fields.insert(fieldTag, fieldValue);
} else {
throw InvalidFormatException(BAMDbiPlugin::tr("Duplicate header field: %1").arg(QString(fieldTag)));
}
}
}
if("HD" == recordTag) {
if(fields.contains("VN")) {
QByteArray value = fields["VN"];
if(!QRegExp("[0-9]+\\.[0-9]+").exactMatch(value)) {
//Do nothing to support malformed BAMs
//throw InvalidFormatException(BAMDbiPlugin::tr("Invalid HD-VN value: %1").arg(QString(value)));
}
header.setFormatVersion(Version::parseVersion(value));
} else {
throw InvalidFormatException(BAMDbiPlugin::tr("HD record without VN field"));
}
if(fields.contains("SO")) {
QByteArray value = fields["SO"];
if("unknown" == value) {
header.setSortingOrder(Header::Unknown);
} else if("unsorted" == value) {
header.setSortingOrder(Header::Unsorted);
} else if("queryname" == value) {
header.setSortingOrder(Header::QueryName);
} else if("coordinate" == value) {
header.setSortingOrder(Header::Coordinate);
} else if("sorted" == value) { // workaround for invalid headers produced by some programs
header.setSortingOrder(Header::Coordinate);
} else {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid HD-SO value: %1").arg(QString(value)));
}
} else {
header.setSortingOrder(Header::Unknown);
}
} else if("SQ" == recordTag) {
Header::Reference *reference = NULL;
QByteArray name;
if(fields.contains("SN")) {
name = fields["SN"];
} else {
throw InvalidFormatException(BAMDbiPlugin::tr("SQ record without SN field"));
}
if(fields.contains("LN")) {
QByteArray value = fields["LN"];
bool ok = false;
int length = value.toInt(&ok);
if(ok) {
Header::Reference newRef(name, length);
referencesMap.insert(name, references.size());
references.append(newRef);
reference = &(references.last());
} else {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid SQ-LN value: %1").arg(QString(value)));
}
} else {
throw InvalidFormatException(BAMDbiPlugin::tr("SQ record without LN field"));
}
assert(NULL != reference);
if(fields.contains("AS")) {
reference->setAssemblyId(fields["AS"]);
}
if(fields.contains("M5")) {
QByteArray value = fields["M5"];
//[a-f] is a workaround (not matching to SAM-1.3 spec) to open 1000 Genomes project BAMs
if(!QRegExp("[0-9A-Fa-f]+").exactMatch(value)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid SQ-M5 value: %1").arg(QString(value)));
}
reference->setMd5(fields["M5"]);
}
if(fields.contains("SP")) {
reference->setSpecies(fields["SP"]);
}
if(fields.contains("UR")) {
reference->setUri(fields["UR"]);
}
} else if("RG" == recordTag) {
Header::ReadGroup readGroup;
if(fields.contains("ID")) {
QByteArray value = fields["SN"];
readGroupsMap.insert(value, readGroups.size());
} else {
fields.insert("ID", "-1");
}
if(fields.contains("CN")) {
readGroup.setSequencingCenter(fields["CN"]);
}
if(fields.contains("DS")) {
readGroup.setDescription(fields["DS"]);
}
if(fields.contains("DT")) {
QByteArray value = fields["DT"];
QDateTime dateTime = QDateTime::fromString(value, Qt::ISODate);
if(dateTime.isValid()) {
readGroup.setDate(dateTime);
} else {
QDate date = QDate::fromString(value, Qt::ISODate);
if(date.isValid()) {
readGroup.setDate(date);
} else {
//Allow anything.
//throw InvalidFormatException(BAMDbiPlugin::tr("Invalid RG-DT field value: %1").arg(QString(value)));
}
}
}
if(fields.contains("LB")) {
readGroup.setLibrary(fields["LB"]);
}
if(fields.contains("PG")) {
readGroup.setPrograms(fields["PG"]);
}
if(fields.contains("PI")) {
QByteArray value = fields["PI"];
bool ok = false;
int predictedInsertSize = value.toInt(&ok);
if(ok) {
readGroup.setPredictedInsertSize(predictedInsertSize);
} else {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid RG-PI field value: %1").arg(QString(value)));
}
}
if(fields.contains("PL")) {
readGroup.setPlatform(fields["PL"]);
}
if(fields.contains("PU")) {
readGroup.setPlatformUnit(fields["PU"]);
}
if(fields.contains("SM")) {
readGroup.setSample(fields["SM"]);
}
readGroups.append(readGroup);
} else if("PG" == recordTag) {
Header::Program program;
if(!fields.contains("ID")) {
fields.insert("ID", QByteArray::number(programs.size()));
}
programsMap.insert(fields["ID"], programs.size());
if(fields.contains("PN")) {
program.setName(fields["PN"]);
}
if(fields.contains("CL")) {
program.setCommandLine(fields["CL"]);
}
if(fields.contains("PP")) {
previousProgramIds.append(fields["PP"]);
} else {
previousProgramIds.append(QByteArray());
}
if(fields.contains("VN")) {
program.setVersion(fields["VN"]);
}
programs.append(program);
}
}
for(int index = 0;index < programs.size();index++) {
const QByteArray &previousProgramId = previousProgramIds[index];
if(!previousProgramId.isEmpty()) {
if(programsMap.contains(previousProgramId)) {
programs[index].setPreviousId(programsMap[previousProgramId]);
} else {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid PG-PP field value: %1").arg(QString(previousProgramId)));
}
}
}
header.setReferences(references);
header.setReadGroups(readGroups);
header.setPrograms(programs);
}
}
} // namespace BAM
} // namespace U2
| gpl-2.0 |
redeanisioteixeira/aew_github | library/Sec/Global.php | 1262 | <?php
/**
* Classe Global
*
* @author diego
*
*/
class Sec_Global
{
/**
* Log uma mensagem no firebug
* @param $message
* @param $label
* @return void
*/
public static function fb($message, $label=null)
{
if ($label!=null) {
$message = array($label,$message);
}
if(Zend_Registry::isRegistered('logger')){
Zend_Registry::get('logger')->debug($message);
}
echo $message;
echo "<br/>";
}
/**
* Remove espaços e caracterres especiais da string
* @param String $string
*/
public static function sanitizeSlug($str, $replace=array(), $delimiter='-')
{
if( !empty($replace) ) {
$str = str_replace((array)$replace, ' ', $str);
}
$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
$clean = strtolower(trim($clean, '-'));
$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
return $clean;
}
/**
* Retorna o email do sistema
*/
public static function getSystemEmail()
{
// TODO Colocar no config.ini
return 'aew@educacao.ba.gov.br';
}
/**
* Remove espaços desnecessários
*/
public static function limpaString($str) {
return preg_replace('/ \s+/','',$str);
}
}
| gpl-2.0 |
openbu/client | source/src/saveload/afterload.cpp | 108587 | /* $Id$ */
/*
* This file is part of OpenTTD.
* OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
* OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file afterload.cpp Code updating data after game load */
#include "../stdafx.h"
#include "../void_map.h"
#include "../signs_base.h"
#include "../depot_base.h"
#include "../fios.h"
#include "../gamelog_internal.h"
#include "../network/network.h"
#include "../network/network_func.h"
#include "../gfxinit.h"
#include "../viewport_func.h"
#include "../industry.h"
#include "../clear_map.h"
#include "../vehicle_func.h"
#include "../string_func.h"
#include "../date_func.h"
#include "../roadveh.h"
#include "../train.h"
#include "../station_base.h"
#include "../waypoint_base.h"
#include "../roadstop_base.h"
#include "../tunnelbridge_map.h"
#include "../pathfinder/yapf/yapf_cache.h"
#include "../elrail_func.h"
#include "../signs_func.h"
#include "../aircraft.h"
#include "../object_map.h"
#include "../object_base.h"
#include "../tree_map.h"
#include "../company_func.h"
#include "../road_cmd.h"
#include "../ai/ai.hpp"
#include "../ai/ai_gui.hpp"
#include "../town.h"
#include "../economy_base.h"
#include "../animated_tile_func.h"
#include "../subsidy_base.h"
#include "../subsidy_func.h"
#include "../newgrf.h"
#include "../engine_func.h"
#include "../rail_gui.h"
#include "../core/backup_type.hpp"
#include "../core/mem_func.hpp"
#include "../smallmap_gui.h"
#include "../news_func.h"
#include "../order_backup.h"
#include "../error.h"
#include "../disaster_vehicle.h"
#include "../tracerestrict.h"
#include "saveload_internal.h"
#include <signal.h>
#include "../safeguards.h"
extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
/**
* Makes a tile canal or water depending on the surroundings.
*
* Must only be used for converting old savegames. Use WaterClass now.
*
* This as for example docks and shipdepots do not store
* whether the tile used to be canal or 'normal' water.
* @param t the tile to change.
* @param include_invalid_water_class Also consider WATER_CLASS_INVALID, i.e. industry tiles on land
*/
void SetWaterClassDependingOnSurroundings(TileIndex t, bool include_invalid_water_class)
{
/* If the slope is not flat, we always assume 'land' (if allowed). Also for one-corner-raised-shores.
* Note: Wrt. autosloping under industry tiles this is the most fool-proof behaviour. */
if (!IsTileFlat(t)) {
if (include_invalid_water_class) {
SetWaterClass(t, WATER_CLASS_INVALID);
return;
} else {
SlErrorCorrupt("Invalid water class for dry tile");
}
}
/* Mark tile dirty in all cases */
MarkTileDirtyByTile(t);
if (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1) {
/* tiles at map borders are always WATER_CLASS_SEA */
SetWaterClass(t, WATER_CLASS_SEA);
return;
}
bool has_water = false;
bool has_canal = false;
bool has_river = false;
for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
TileIndex neighbour = TileAddByDiagDir(t, dir);
switch (GetTileType(neighbour)) {
case MP_WATER:
/* clear water and shipdepots have already a WaterClass associated */
if (IsCoast(neighbour)) {
has_water = true;
} else if (!IsLock(neighbour)) {
switch (GetWaterClass(neighbour)) {
case WATER_CLASS_SEA: has_water = true; break;
case WATER_CLASS_CANAL: has_canal = true; break;
case WATER_CLASS_RIVER: has_river = true; break;
default: SlErrorCorrupt("Invalid water class for tile");
}
}
break;
case MP_RAILWAY:
/* Shore or flooded halftile */
has_water |= (GetRailGroundType(neighbour) == RAIL_GROUND_WATER);
break;
case MP_TREES:
/* trees on shore */
has_water |= (GB(_m[neighbour].m2, 4, 2) == TREE_GROUND_SHORE);
break;
default: break;
}
}
if (!has_water && !has_canal && !has_river && include_invalid_water_class) {
SetWaterClass(t, WATER_CLASS_INVALID);
return;
}
if (has_river && !has_canal) {
SetWaterClass(t, WATER_CLASS_RIVER);
} else if (has_canal || !has_water) {
SetWaterClass(t, WATER_CLASS_CANAL);
} else {
SetWaterClass(t, WATER_CLASS_SEA);
}
}
static void ConvertTownOwner()
{
for (TileIndex tile = 0; tile != MapSize(); tile++) {
switch (GetTileType(tile)) {
case MP_ROAD:
if (GB(_m[tile].m5, 4, 2) == ROAD_TILE_CROSSING && HasBit(_m[tile].m3, 7)) {
_m[tile].m3 = OWNER_TOWN;
}
/* FALL THROUGH */
case MP_TUNNELBRIDGE:
if (_m[tile].m1 & 0x80) SetTileOwner(tile, OWNER_TOWN);
break;
default: break;
}
}
}
/* since savegame version 4.1, exclusive transport rights are stored at towns */
static void UpdateExclusiveRights()
{
Town *t;
FOR_ALL_TOWNS(t) {
t->exclusivity = INVALID_COMPANY;
}
/* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
* could be implemented this way:
* 1.) Go through all stations
* Build an array town_blocked[ town_id ][ company_id ]
* that stores if at least one station in that town is blocked for a company
* 2.) Go through that array, if you find a town that is not blocked for
* one company, but for all others, then give him exclusivity.
*/
}
static const byte convert_currency[] = {
0, 1, 12, 8, 3,
10, 14, 19, 4, 5,
9, 11, 13, 6, 17,
16, 22, 21, 7, 15,
18, 2, 20,
};
/* since savegame version 4.2 the currencies are arranged differently */
static void UpdateCurrencies()
{
_settings_game.locale.currency = convert_currency[_settings_game.locale.currency];
}
/* Up to revision 1413 the invisible tiles at the southern border have not been
* MP_VOID, even though they should have. This is fixed by this function
*/
static void UpdateVoidTiles()
{
uint i;
for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
}
static inline RailType UpdateRailType(RailType rt, RailType min)
{
return rt >= min ? (RailType)(rt + 1): rt;
}
/**
* Update the viewport coordinates of all signs.
*/
void UpdateAllVirtCoords()
{
UpdateAllStationVirtCoords();
UpdateAllSignVirtCoords();
UpdateAllTownVirtCoords();
}
/**
* Initialization of the windows and several kinds of caches.
* This is not done directly in AfterLoadGame because these
* functions require that all saveload conversions have been
* done. As people tend to add savegame conversion stuff after
* the intialization of the windows and caches quite some bugs
* had been made.
* Moving this out of there is both cleaner and less bug-prone.
*/
static void InitializeWindowsAndCaches()
{
/* Initialize windows */
ResetWindowSystem();
SetupColoursAndInitialWindow();
/* Update coordinates of the signs. */
UpdateAllVirtCoords();
ResetViewportAfterLoadGame();
Company *c;
FOR_ALL_COMPANIES(c) {
/* For each company, verify (while loading a scenario) that the inauguration date is the current year and set it
* accordingly if it is not the case. No need to set it on companies that are not been used already,
* thus the MIN_YEAR (which is really nothing more than Zero, initialized value) test */
if (_file_to_saveload.filetype == FT_SCENARIO && c->inaugurated_year != MIN_YEAR) {
c->inaugurated_year = _cur_year;
}
}
/* Count number of objects per type */
Object *o;
FOR_ALL_OBJECTS(o) {
Object::IncTypeCount(o->type);
}
/* Identify owners of persistent storage arrays */
Industry *i;
FOR_ALL_INDUSTRIES(i) {
if (i->psa != NULL) {
i->psa->feature = GSF_INDUSTRIES;
i->psa->tile = i->location.tile;
}
}
Station *s;
FOR_ALL_STATIONS(s) {
if (s->airport.psa != NULL) {
s->airport.psa->feature = GSF_AIRPORTS;
s->airport.psa->tile = s->airport.tile;
}
}
Town *t;
FOR_ALL_TOWNS(t) {
for (std::list<PersistentStorage *>::iterator it = t->psa_list.begin(); it != t->psa_list.end(); ++it) {
(*it)->feature = GSF_FAKE_TOWNS;
(*it)->tile = t->xy;
}
}
RecomputePrices();
GroupStatistics::UpdateAfterLoad();
Station::RecomputeIndustriesNearForAll();
RebuildSubsidisedSourceAndDestinationCache();
/* Towns have a noise controlled number of airports system
* So each airport's noise value must be added to the town->noise_reached value
* Reset each town's noise_reached value to '0' before. */
UpdateAirportsNoise();
CheckTrainsLengths();
ShowNewGRFError();
ShowAIDebugWindowIfAIError();
/* Rebuild the smallmap list of owners. */
BuildOwnerLegend();
}
typedef void (CDECL *SignalHandlerPointer)(int);
static SignalHandlerPointer _prev_segfault = NULL;
static SignalHandlerPointer _prev_abort = NULL;
static SignalHandlerPointer _prev_fpe = NULL;
static void CDECL HandleSavegameLoadCrash(int signum);
/**
* Replaces signal handlers of SIGSEGV and SIGABRT
* and stores pointers to original handlers in memory.
*/
static void SetSignalHandlers()
{
_prev_segfault = signal(SIGSEGV, HandleSavegameLoadCrash);
_prev_abort = signal(SIGABRT, HandleSavegameLoadCrash);
_prev_fpe = signal(SIGFPE, HandleSavegameLoadCrash);
}
/**
* Resets signal handlers back to original handlers.
*/
static void ResetSignalHandlers()
{
signal(SIGSEGV, _prev_segfault);
signal(SIGABRT, _prev_abort);
signal(SIGFPE, _prev_fpe);
}
/**
* Try to find the overridden GRF identifier of the given GRF.
* @param c the GRF to get the 'previous' version of.
* @return the GRF identifier or \a c if none could be found.
*/
static const GRFIdentifier *GetOverriddenIdentifier(const GRFConfig *c)
{
const LoggedAction *la = &_gamelog_action[_gamelog_actions - 1];
if (la->at != GLAT_LOAD) return &c->ident;
const LoggedChange *lcend = &la->change[la->changes];
for (const LoggedChange *lc = la->change; lc != lcend; lc++) {
if (lc->ct == GLCT_GRFCOMPAT && lc->grfcompat.grfid == c->ident.grfid) return &lc->grfcompat;
}
return &c->ident;
}
/** Was the saveload crash because of missing NewGRFs? */
static bool _saveload_crash_with_missing_newgrfs = false;
/**
* Did loading the savegame cause a crash? If so,
* were NewGRFs missing?
* @return when the saveload crashed due to missing NewGRFs.
*/
bool SaveloadCrashWithMissingNewGRFs()
{
return _saveload_crash_with_missing_newgrfs;
}
/**
* Signal handler used to give a user a more useful report for crashes during
* the savegame loading process; especially when there's problems with the
* NewGRFs that are required by the savegame.
* @param signum received signal
*/
static void CDECL HandleSavegameLoadCrash(int signum)
{
ResetSignalHandlers();
char buffer[8192];
char *p = buffer;
p += seprintf(p, lastof(buffer), "Loading your savegame caused OpenTTD to crash.\n");
for (const GRFConfig *c = _grfconfig; !_saveload_crash_with_missing_newgrfs && c != NULL; c = c->next) {
_saveload_crash_with_missing_newgrfs = HasBit(c->flags, GCF_COMPATIBLE) || c->status == GCS_NOT_FOUND;
}
if (_saveload_crash_with_missing_newgrfs) {
p += seprintf(p, lastof(buffer),
"This is most likely caused by a missing NewGRF or a NewGRF that\n"
"has been loaded as replacement for a missing NewGRF. OpenTTD\n"
"cannot easily determine whether a replacement NewGRF is of a newer\n"
"or older version.\n"
"It will load a NewGRF with the same GRF ID as the missing NewGRF.\n"
"This means that if the author makes incompatible NewGRFs with the\n"
"same GRF ID OpenTTD cannot magically do the right thing. In most\n"
"cases OpenTTD will load the savegame and not crash, but this is an\n"
"exception.\n"
"Please load the savegame with the appropriate NewGRFs installed.\n"
"The missing/compatible NewGRFs are:\n");
for (const GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
if (HasBit(c->flags, GCF_COMPATIBLE)) {
const GRFIdentifier *replaced = GetOverriddenIdentifier(c);
char buf[40];
md5sumToString(buf, lastof(buf), replaced->md5sum);
p += seprintf(p, lastof(buffer), "NewGRF %08X (checksum %s) not found.\n Loaded NewGRF \"%s\" with same GRF ID instead.\n", BSWAP32(c->ident.grfid), buf, c->filename);
}
if (c->status == GCS_NOT_FOUND) {
char buf[40];
md5sumToString(buf, lastof(buf), c->ident.md5sum);
p += seprintf(p, lastof(buffer), "NewGRF %08X (%s) not found; checksum %s.\n", BSWAP32(c->ident.grfid), c->filename, buf);
}
}
} else {
p += seprintf(p, lastof(buffer),
"This is probably caused by a corruption in the savegame.\n"
"Please file a bug report and attach this savegame.\n");
}
ShowInfo(buffer);
SignalHandlerPointer call = NULL;
switch (signum) {
case SIGSEGV: call = _prev_segfault; break;
case SIGABRT: call = _prev_abort; break;
case SIGFPE: call = _prev_fpe; break;
default: NOT_REACHED();
}
if (call != NULL) call(signum);
}
/**
* Tries to change owner of this rail tile to a valid owner. In very old versions it could happen that
* a rail track had an invalid owner. When conversion isn't possible, track is removed.
* @param t tile to update
*/
static void FixOwnerOfRailTrack(TileIndex t)
{
assert(!Company::IsValidID(GetTileOwner(t)) && (IsLevelCrossingTile(t) || IsPlainRailTile(t)));
/* remove leftover rail piece from crossing (from very old savegames) */
Train *v = NULL, *w;
FOR_ALL_TRAINS(w) {
if (w->tile == t) {
v = w;
break;
}
}
if (v != NULL) {
/* when there is a train on crossing (it could happen in TTD), set owner of crossing to train owner */
SetTileOwner(t, v->owner);
return;
}
/* try to find any connected rail */
for (DiagDirection dd = DIAGDIR_BEGIN; dd < DIAGDIR_END; dd++) {
TileIndex tt = t + TileOffsByDiagDir(dd);
if (GetTileTrackStatus(t, TRANSPORT_RAIL, 0, dd) != 0 &&
GetTileTrackStatus(tt, TRANSPORT_RAIL, 0, ReverseDiagDir(dd)) != 0 &&
Company::IsValidID(GetTileOwner(tt))) {
SetTileOwner(t, GetTileOwner(tt));
return;
}
}
if (IsLevelCrossingTile(t)) {
/* else change the crossing to normal road (road vehicles won't care) */
MakeRoadNormal(t, GetCrossingRoadBits(t), GetRoadTypes(t), GetTownIndex(t),
GetRoadOwner(t, ROADTYPE_ROAD), GetRoadOwner(t, ROADTYPE_TRAM));
return;
}
/* if it's not a crossing, make it clean land */
MakeClear(t, CLEAR_GRASS, 0);
}
/**
* Fixes inclination of a vehicle. Older OpenTTD versions didn't update the bits correctly.
* @param v vehicle
* @param dir vehicle's direction, or # INVALID_DIR if it can be ignored
* @return inclination bits to set
*/
static uint FixVehicleInclination(Vehicle *v, Direction dir)
{
/* Compute place where this vehicle entered the tile */
int entry_x = v->x_pos;
int entry_y = v->y_pos;
switch (dir) {
case DIR_NE: entry_x |= TILE_UNIT_MASK; break;
case DIR_NW: entry_y |= TILE_UNIT_MASK; break;
case DIR_SW: entry_x &= ~TILE_UNIT_MASK; break;
case DIR_SE: entry_y &= ~TILE_UNIT_MASK; break;
case INVALID_DIR: break;
default: NOT_REACHED();
}
byte entry_z = GetSlopePixelZ(entry_x, entry_y);
/* Compute middle of the tile. */
int middle_x = (v->x_pos & ~TILE_UNIT_MASK) + TILE_SIZE / 2;
int middle_y = (v->y_pos & ~TILE_UNIT_MASK) + TILE_SIZE / 2;
byte middle_z = GetSlopePixelZ(middle_x, middle_y);
/* middle_z == entry_z, no height change. */
if (middle_z == entry_z) return 0;
/* middle_z < entry_z, we are going downwards. */
if (middle_z < entry_z) return 1U << GVF_GOINGDOWN_BIT;
/* middle_z > entry_z, we are going upwards. */
return 1U << GVF_GOINGUP_BIT;
}
/**
* Checks for the possibility that a bridge may be on this tile
* These are in fact all the tile types on which a bridge can be found
* @param t The tile to analyze
* @return True if a bridge might have been present prior to savegame 194.
*/
static inline bool MayHaveBridgeAbove(TileIndex t)
{
return IsTileType(t, MP_CLEAR) || IsTileType(t, MP_RAILWAY) || IsTileType(t, MP_ROAD) ||
IsTileType(t, MP_WATER) || IsTileType(t, MP_TUNNELBRIDGE) || IsTileType(t, MP_OBJECT);
}
/**
* Perform a (large) amount of savegame conversion *magic* in order to
* load older savegames and to fill the caches for various purposes.
* @return True iff conversion went without a problem.
*/
bool AfterLoadGame()
{
SetSignalHandlers();
TileIndex map_size = MapSize();
extern TileIndex _cur_tileloop_tile; // From landscape.cpp.
/* The LFSR used in RunTileLoop iteration cannot have a zeroed state, make it non-zeroed. */
if (_cur_tileloop_tile == 0) _cur_tileloop_tile = 1;
if (IsSavegameVersionBefore(98)) GamelogOldver();
GamelogTestRevision();
GamelogTestMode();
if (IsSavegameVersionBefore(98)) GamelogGRFAddList(_grfconfig);
if (IsSavegameVersionBefore(119)) {
_pause_mode = (_pause_mode == 2) ? PM_PAUSED_NORMAL : PM_UNPAUSED;
} else if (_network_dedicated && (_pause_mode & PM_PAUSED_ERROR) != 0) {
DEBUG(net, 0, "The loading savegame was paused due to an error state.");
DEBUG(net, 0, " The savegame cannot be used for multiplayer!");
/* Restore the signals */
ResetSignalHandlers();
return false;
} else if (!_networking || _network_server) {
/* If we are in single player, i.e. not networking, and loading the
* savegame or we are loading the savegame as network server we do
* not want to be bothered by being paused because of the automatic
* reason of a network server, e.g. joining clients or too few
* active clients. Note that resetting these values for a network
* client are very bad because then the client is going to execute
* the game loop when the server is not, i.e. it desyncs. */
_pause_mode &= ~PMB_PAUSED_NETWORK;
}
/* In very old versions, size of train stations was stored differently.
* They had swapped width and height if station was built along the Y axis.
* TTO and TTD used 3 bits for width/height, while OpenTTD used 4.
* Because the data stored by TTDPatch are unusable for rail stations > 7x7,
* recompute the width and height. Doing this unconditionally for all old
* savegames simplifies the code. */
if (IsSavegameVersionBefore(2)) {
Station *st;
FOR_ALL_STATIONS(st) {
st->train_station.w = st->train_station.h = 0;
}
for (TileIndex t = 0; t < map_size; t++) {
if (!IsTileType(t, MP_STATION)) continue;
if (_m[t].m5 > 7) continue; // is it a rail station tile?
st = Station::Get(_m[t].m2);
assert(st->train_station.tile != 0);
int dx = TileX(t) - TileX(st->train_station.tile);
int dy = TileY(t) - TileY(st->train_station.tile);
assert(dx >= 0 && dy >= 0);
st->train_station.w = max<uint>(st->train_station.w, dx + 1);
st->train_station.h = max<uint>(st->train_station.h, dy + 1);
}
}
if (IsSavegameVersionBefore(194) && SlXvIsFeatureMissing(XSLFI_HEIGHT_8_BIT)) {
_settings_game.construction.max_heightlevel = 15;
/* In old savegame versions, the heightlevel was coded in bits 0..3 of the type field */
for (TileIndex t = 0; t < map_size; t++) {
_m[t].height = GB(_m[t].type, 0, 4);
SB(_m[t].type, 0, 2, GB(_me[t].m6, 0, 2));
SB(_me[t].m6, 0, 2, 0);
if (MayHaveBridgeAbove(t)) {
SB(_m[t].type, 2, 2, GB(_me[t].m6, 6, 2));
SB(_me[t].m6, 6, 2, 0);
} else {
SB(_m[t].type, 2, 2, 0);
}
}
} else if (SlXvIsFeaturePresent(XSLFI_HEIGHT_8_BIT)) {
for (TileIndex t = 0; t < map_size; t++) {
SB(_m[t].type, 0, 2, GB(_me[t].m6, 0, 2));
SB(_me[t].m6, 0, 2, 0);
if (MayHaveBridgeAbove(t)) {
SB(_m[t].type, 2, 2, GB(_me[t].m6, 6, 2));
SB(_me[t].m6, 6, 2, 0);
} else {
SB(_m[t].type, 2, 2, 0);
}
}
}
/* in version 2.1 of the savegame, town owner was unified. */
if (IsSavegameVersionBefore(2, 1)) ConvertTownOwner();
/* from version 4.1 of the savegame, exclusive rights are stored at towns */
if (IsSavegameVersionBefore(4, 1)) UpdateExclusiveRights();
/* from version 4.2 of the savegame, currencies are in a different order */
if (IsSavegameVersionBefore(4, 2)) UpdateCurrencies();
/* In old version there seems to be a problem that water is owned by
* OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
* (4.3) version, so I just check when versions are older, and then
* walk through the whole map.. */
if (IsSavegameVersionBefore(4, 3)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_WATER) && GetTileOwner(t) >= MAX_COMPANIES) {
SetTileOwner(t, OWNER_WATER);
}
}
}
if (IsSavegameVersionBefore(84)) {
Company *c;
FOR_ALL_COMPANIES(c) {
c->name = CopyFromOldName(c->name_1);
if (c->name != NULL) c->name_1 = STR_SV_UNNAMED;
c->president_name = CopyFromOldName(c->president_name_1);
if (c->president_name != NULL) c->president_name_1 = SPECSTR_PRESIDENT_NAME;
}
Station *st;
FOR_ALL_STATIONS(st) {
st->name = CopyFromOldName(st->string_id);
/* generating new name would be too much work for little effect, use the station name fallback */
if (st->name != NULL) st->string_id = STR_SV_STNAME_FALLBACK;
}
Town *t;
FOR_ALL_TOWNS(t) {
t->name = CopyFromOldName(t->townnametype);
if (t->name != NULL) t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
}
}
/* From this point the old names array is cleared. */
ResetOldNames();
if (IsSavegameVersionBefore(106)) {
/* no station is determined by 'tile == INVALID_TILE' now (instead of '0') */
Station *st;
FOR_ALL_STATIONS(st) {
if (st->airport.tile == 0) st->airport.tile = INVALID_TILE;
if (st->dock_tile == 0) st->dock_tile = INVALID_TILE;
if (st->train_station.tile == 0) st->train_station.tile = INVALID_TILE;
}
/* the same applies to Company::location_of_HQ */
Company *c;
FOR_ALL_COMPANIES(c) {
if (c->location_of_HQ == 0 || (IsSavegameVersionBefore(4) && c->location_of_HQ == 0xFFFF)) {
c->location_of_HQ = INVALID_TILE;
}
}
}
/* convert road side to my format. */
if (_settings_game.vehicle.road_side) _settings_game.vehicle.road_side = 1;
/* Check if all NewGRFs are present, we are very strict in MP mode */
GRFListCompatibility gcf_res = IsGoodGRFConfigList(_grfconfig);
for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
if (c->status == GCS_NOT_FOUND) {
GamelogGRFRemove(c->ident.grfid);
} else if (HasBit(c->flags, GCF_COMPATIBLE)) {
GamelogGRFCompatible(&c->ident);
}
}
if (_networking && gcf_res != GLC_ALL_GOOD) {
SetSaveLoadError(STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH);
/* Restore the signals */
ResetSignalHandlers();
return false;
}
/* The value of _date_fract got divided, so make sure that old games are converted correctly. */
if (IsSavegameVersionBefore(11, 1) || (IsSavegameVersionBefore(147) && _date_fract > DAY_TICKS)) _date_fract /= 885;
if (SlXvIsFeaturePresent(XSLFI_SPRINGPP)) {
assert(_settings_game.economy.day_length_factor >= 1);
_tick_skip_counter = _date_fract % _settings_game.economy.day_length_factor;
_date_fract /= _settings_game.economy.day_length_factor;
assert(_date_fract < DAY_TICKS);
assert(_tick_skip_counter < _settings_game.economy.day_length_factor);
}
/* Update current year
* must be done before loading sprites as some newgrfs check it */
SetDate(_date, _date_fract);
/*
* Force the old behaviour for compatibility reasons with old savegames. As new
* settings can only be loaded from new savegames loading old savegames with new
* versions of OpenTTD will normally initialize settings newer than the savegame
* version with "new game" defaults which the player can define to their liking.
* For some settings we override that to keep the behaviour the same as when the
* game was saved.
*
* Note that there is no non-stop in here. This is because the setting could have
* either value in TTDPatch. To convert it properly the user has to make sure the
* right value has been chosen in the settings. Otherwise we will be converting
* it incorrectly in half of the times without a means to correct that.
*/
if (IsSavegameVersionBefore(4, 2)) _settings_game.station.modified_catchment = false;
if (IsSavegameVersionBefore(6, 1)) _settings_game.pf.forbid_90_deg = false;
if (IsSavegameVersionBefore(21)) _settings_game.vehicle.train_acceleration_model = 0;
if (IsSavegameVersionBefore(90)) _settings_game.vehicle.plane_speed = 4;
if (IsSavegameVersionBefore(95)) _settings_game.vehicle.dynamic_engines = 0;
if (IsSavegameVersionBefore(96)) _settings_game.economy.station_noise_level = false;
if (IsSavegameVersionBefore(133)) {
_settings_game.vehicle.roadveh_acceleration_model = 0;
_settings_game.vehicle.train_slope_steepness = 3;
}
if (IsSavegameVersionBefore(134)) _settings_game.economy.feeder_payment_share = 75;
if (IsSavegameVersionBefore(138)) _settings_game.vehicle.plane_crashes = 2;
if (IsSavegameVersionBefore(139)) _settings_game.vehicle.roadveh_slope_steepness = 7;
if (IsSavegameVersionBefore(143)) _settings_game.economy.allow_town_level_crossings = true;
if (IsSavegameVersionBefore(159)) {
_settings_game.vehicle.max_train_length = 50;
_settings_game.construction.max_bridge_length = 64;
_settings_game.construction.max_tunnel_length = 64;
}
if (IsSavegameVersionBefore(166)) _settings_game.economy.infrastructure_maintenance = false;
if (IsSavegameVersionBefore(183)) {
_settings_game.linkgraph.distribution_pax = DT_MANUAL;
_settings_game.linkgraph.distribution_mail = DT_MANUAL;
_settings_game.linkgraph.distribution_armoured = DT_MANUAL;
_settings_game.linkgraph.distribution_default = DT_MANUAL;
}
/* Load the sprites */
GfxLoadSprites();
LoadStringWidthTable();
/* Copy temporary data to Engine pool */
CopyTempEngineData();
/* Connect front and rear engines of multiheaded trains and converts
* subtype to the new format */
if (IsSavegameVersionBefore(17, 1)) ConvertOldMultiheadToNew();
/* Connect front and rear engines of multiheaded trains */
ConnectMultiheadedTrains();
/* Fix the CargoPackets *and* fix the caches of CargoLists.
* If this isn't done before Stations and especially Vehicles are
* running their AfterLoad we might get in trouble. In the case of
* vehicles we could give the wrong (cached) count of items in a
* vehicle which causes different results when getting their caches
* filled; and that could eventually lead to desyncs. */
CargoPacket::AfterLoad();
/* Oilrig was moved from id 15 to 9. We have to do this conversion
* here as AfterLoadVehicles can check it indirectly via the newgrf
* code. */
if (IsSavegameVersionBefore(139)) {
Station *st;
FOR_ALL_STATIONS(st) {
if (st->airport.tile != INVALID_TILE && st->airport.type == 15) {
st->airport.type = AT_OILRIG;
}
}
}
if (SlXvIsFeaturePresent(XSLFI_SPRINGPP)) {
/*
* Reject huge airports
* Annoyingly SpringPP v2.0.102 has a bug where it uses the same ID for AT_INTERCONTINENTAL2 and AT_OILRIG.
* Do this here as AfterLoadVehicles might also check it indirectly via the newgrf code.
*/
Station *st;
FOR_ALL_STATIONS(st) {
if (st->airport.tile == INVALID_TILE) continue;
StringID err = INVALID_STRING_ID;
if (st->airport.type == 9) {
if (st->dock_tile != INVALID_TILE && IsOilRig(st->dock_tile)) {
/* this airport is probably an oil rig, not a huge airport */
} else {
err = STR_GAME_SAVELOAD_ERROR_HUGE_AIRPORTS_PRESENT;
}
st->airport.type = AT_OILRIG;
} else if (st->airport.type == 10) {
err = STR_GAME_SAVELOAD_ERROR_HUGE_AIRPORTS_PRESENT;
}
if (err != INVALID_STRING_ID) {
SetSaveLoadError(err);
/* Restore the signals */
ResetSignalHandlers();
return false;
}
}
}
if (SlXvIsFeaturePresent(XSLFI_SPRINGPP, 1, 1)) {
/*
* Reject helicopters aproaching oil rigs using the wrong aircraft movement data
* Annoyingly SpringPP v2.0.102 has a bug where it uses the same ID for AT_INTERCONTINENTAL2 and AT_OILRIG
* Do this here as AfterLoadVehicles can also check it indirectly via the newgrf code.
*/
Aircraft *v;
FOR_ALL_AIRCRAFT(v) {
Station *st = GetTargetAirportIfValid(v);
if (st != NULL && ((st->dock_tile != INVALID_TILE && IsOilRig(st->dock_tile)) || st->airport.type == AT_OILRIG)) {
/* aircraft is on approach to an oil rig, bail out now */
SetSaveLoadError(STR_GAME_SAVELOAD_ERROR_HELI_OILRIG_BUG);
/* Restore the signals */
ResetSignalHandlers();
return false;
}
}
}
/* Update all vehicles */
AfterLoadVehicles(true);
/* Update template vehicles */
AfterLoadTemplateVehicles();
/* Make sure there is an AI attached to an AI company */
{
Company *c;
FOR_ALL_COMPANIES(c) {
if (c->is_ai && c->ai_instance == NULL) AI::StartNew(c->index);
}
}
/* make sure there is a town in the game */
if (_game_mode == GM_NORMAL && Town::GetNumItems() == 0) {
SetSaveLoadError(STR_ERROR_NO_TOWN_IN_SCENARIO);
/* Restore the signals */
ResetSignalHandlers();
return false;
}
/* The void tiles on the southern border used to belong to a wrong class (pre 4.3).
* This problem appears in savegame version 21 too, see r3455. But after loading the
* savegame and saving again, the buggy map array could be converted to new savegame
* version. It didn't show up before r12070. */
if (IsSavegameVersionBefore(87)) UpdateVoidTiles();
/* If Load Scenario / New (Scenario) Game is used,
* a company does not exist yet. So create one here.
* 1 exception: network-games. Those can have 0 companies
* But this exception is not true for non-dedicated network servers! */
if (!Company::IsValidID(COMPANY_FIRST) && (!_networking || (_networking && _network_server && !_network_dedicated))) {
DoStartupNewCompany(false);
Company *c = Company::Get(COMPANY_FIRST);
c->settings = _settings_client.company;
}
/* Fix the cache for cargo payments. */
CargoPayment *cp;
FOR_ALL_CARGO_PAYMENTS(cp) {
cp->front->cargo_payment = cp;
cp->current_station = cp->front->last_station_visited;
}
if (IsSavegameVersionBefore(72)) {
/* Locks in very old savegames had OWNER_WATER as owner */
for (TileIndex t = 0; t < MapSize(); t++) {
switch (GetTileType(t)) {
default: break;
case MP_WATER:
if (GetWaterTileType(t) == WATER_TILE_LOCK && GetTileOwner(t) == OWNER_WATER) SetTileOwner(t, OWNER_NONE);
break;
case MP_STATION: {
if (HasBit(_me[t].m6, 3)) SetBit(_me[t].m6, 2);
StationGfx gfx = GetStationGfx(t);
StationType st;
if ( IsInsideMM(gfx, 0, 8)) { // Rail station
st = STATION_RAIL;
SetStationGfx(t, gfx - 0);
} else if (IsInsideMM(gfx, 8, 67)) { // Airport
st = STATION_AIRPORT;
SetStationGfx(t, gfx - 8);
} else if (IsInsideMM(gfx, 67, 71)) { // Truck
st = STATION_TRUCK;
SetStationGfx(t, gfx - 67);
} else if (IsInsideMM(gfx, 71, 75)) { // Bus
st = STATION_BUS;
SetStationGfx(t, gfx - 71);
} else if (gfx == 75) { // Oil rig
st = STATION_OILRIG;
SetStationGfx(t, gfx - 75);
} else if (IsInsideMM(gfx, 76, 82)) { // Dock
st = STATION_DOCK;
SetStationGfx(t, gfx - 76);
} else if (gfx == 82) { // Buoy
st = STATION_BUOY;
SetStationGfx(t, gfx - 82);
} else if (IsInsideMM(gfx, 83, 168)) { // Extended airport
st = STATION_AIRPORT;
SetStationGfx(t, gfx - 83 + 67 - 8);
} else if (IsInsideMM(gfx, 168, 170)) { // Drive through truck
st = STATION_TRUCK;
SetStationGfx(t, gfx - 168 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
} else if (IsInsideMM(gfx, 170, 172)) { // Drive through bus
st = STATION_BUS;
SetStationGfx(t, gfx - 170 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
} else {
/* Restore the signals */
ResetSignalHandlers();
return false;
}
SB(_me[t].m6, 3, 3, st);
break;
}
}
}
}
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_STATION: {
BaseStation *bst = BaseStation::GetByTile(t);
/* Set up station spread */
bst->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
/* Waypoints don't have road stops/oil rigs in the old format */
if (!Station::IsExpected(bst)) break;
Station *st = Station::From(bst);
switch (GetStationType(t)) {
case STATION_TRUCK:
case STATION_BUS:
if (IsSavegameVersionBefore(6)) {
/* Before version 5 you could not have more than 250 stations.
* Version 6 adds large maps, so you could only place 253*253
* road stops on a map (no freeform edges) = 64009. So, yes
* someone could in theory create such a full map to trigger
* this assertion, it's safe to assume that's only something
* theoretical and does not happen in normal games. */
assert(RoadStop::CanAllocateItem());
/* From this version on there can be multiple road stops of the
* same type per station. Convert the existing stops to the new
* internal data structure. */
RoadStop *rs = new RoadStop(t);
RoadStop **head =
IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
*head = rs;
}
break;
case STATION_OILRIG: {
/* Very old savegames sometimes have phantom oil rigs, i.e.
* an oil rig which got shut down, but not completely removed from
* the map
*/
TileIndex t1 = TILE_ADDXY(t, 0, 1);
if (IsTileType(t1, MP_INDUSTRY) &&
GetIndustryGfx(t1) == GFX_OILRIG_1) {
/* The internal encoding of oil rigs was changed twice.
* It was 3 (till 2.2) and later 5 (till 5.1).
* Setting it unconditionally does not hurt.
*/
Station::GetByTile(t)->airport.type = AT_OILRIG;
} else {
DeleteOilRig(t);
}
break;
}
default: break;
}
break;
}
default: break;
}
}
/* In version 2.2 of the savegame, we have new airports, so status of all aircraft is reset.
* This has to be called after the oilrig airport_type update above ^^^ ! */
if (IsSavegameVersionBefore(2, 2)) UpdateOldAircraft();
/* In version 6.1 we put the town index in the map-array. To do this, we need
* to use m2 (16bit big), so we need to clean m2, and that is where this is
* all about ;) */
if (IsSavegameVersionBefore(6, 1)) {
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_HOUSE:
_m[t].m4 = _m[t].m2;
SetTownIndex(t, CalcClosestTownFromTile(t)->index);
break;
case MP_ROAD:
_m[t].m4 |= (_m[t].m2 << 4);
if ((GB(_m[t].m5, 4, 2) == ROAD_TILE_CROSSING ? (Owner)_m[t].m3 : GetTileOwner(t)) == OWNER_TOWN) {
SetTownIndex(t, CalcClosestTownFromTile(t)->index);
} else {
SetTownIndex(t, 0);
}
break;
default: break;
}
}
}
/* Force the freeform edges to false for old savegames. */
if (IsSavegameVersionBefore(111)) {
_settings_game.construction.freeform_edges = false;
}
/* From version 9.0, we update the max passengers of a town (was sometimes negative
* before that. */
if (IsSavegameVersionBefore(9)) {
Town *t;
FOR_ALL_TOWNS(t) UpdateTownMaxPass(t);
}
/* From version 16.0, we included autorenew on engines, which are now saved, but
* of course, we do need to initialize them for older savegames. */
if (IsSavegameVersionBefore(16)) {
Company *c;
FOR_ALL_COMPANIES(c) {
c->engine_renew_list = NULL;
c->settings.engine_renew = false;
c->settings.engine_renew_months = 6;
c->settings.engine_renew_money = 100000;
}
/* When loading a game, _local_company is not yet set to the correct value.
* However, in a dedicated server we are a spectator, so nothing needs to
* happen. In case we are not a dedicated server, the local company always
* becomes company 0, unless we are in the scenario editor where all the
* companies are 'invalid'.
*/
c = Company::GetIfValid(COMPANY_FIRST);
if (!_network_dedicated && c != NULL) {
c->settings = _settings_client.company;
}
}
if (IsSavegameVersionBefore(48)) {
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_RAILWAY:
if (IsPlainRail(t)) {
/* Swap ground type and signal type for plain rail tiles, so the
* ground type uses the same bits as for depots and waypoints. */
uint tmp = GB(_m[t].m4, 0, 4);
SB(_m[t].m4, 0, 4, GB(_m[t].m2, 0, 4));
SB(_m[t].m2, 0, 4, tmp);
} else if (HasBit(_m[t].m5, 2)) {
/* Split waypoint and depot rail type and remove the subtype. */
ClrBit(_m[t].m5, 2);
ClrBit(_m[t].m5, 6);
}
break;
case MP_ROAD:
/* Swap m3 and m4, so the track type for rail crossings is the
* same as for normal rail. */
Swap(_m[t].m3, _m[t].m4);
break;
default: break;
}
}
}
if (IsSavegameVersionBefore(61)) {
/* Added the RoadType */
bool old_bridge = IsSavegameVersionBefore(42);
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_ROAD:
SB(_m[t].m5, 6, 2, GB(_m[t].m5, 4, 2));
switch (GetRoadTileType(t)) {
default: SlErrorCorrupt("Invalid road tile type");
case ROAD_TILE_NORMAL:
SB(_m[t].m4, 0, 4, GB(_m[t].m5, 0, 4));
SB(_m[t].m4, 4, 4, 0);
SB(_me[t].m6, 2, 4, 0);
break;
case ROAD_TILE_CROSSING:
SB(_m[t].m4, 5, 2, GB(_m[t].m5, 2, 2));
break;
case ROAD_TILE_DEPOT: break;
}
SetRoadTypes(t, ROADTYPES_ROAD);
break;
case MP_STATION:
if (IsRoadStop(t)) SetRoadTypes(t, ROADTYPES_ROAD);
break;
case MP_TUNNELBRIDGE:
/* Middle part of "old" bridges */
if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
SetRoadTypes(t, ROADTYPES_ROAD);
}
break;
default: break;
}
}
}
if (IsSavegameVersionBefore(114)) {
bool fix_roadtypes = !IsSavegameVersionBefore(61);
bool old_bridge = IsSavegameVersionBefore(42);
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_ROAD:
if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_me[t].m7, 5, 3));
SB(_me[t].m7, 5, 1, GB(_m[t].m3, 7, 1)); // snow/desert
switch (GetRoadTileType(t)) {
default: SlErrorCorrupt("Invalid road tile type");
case ROAD_TILE_NORMAL:
SB(_me[t].m7, 0, 4, GB(_m[t].m3, 0, 4)); // road works
SB(_me[t].m6, 3, 3, GB(_m[t].m3, 4, 3)); // ground
SB(_m[t].m3, 0, 4, GB(_m[t].m4, 4, 4)); // tram bits
SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4)); // tram owner
SB(_m[t].m5, 0, 4, GB(_m[t].m4, 0, 4)); // road bits
break;
case ROAD_TILE_CROSSING:
SB(_me[t].m7, 0, 5, GB(_m[t].m4, 0, 5)); // road owner
SB(_me[t].m6, 3, 3, GB(_m[t].m3, 4, 3)); // ground
SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4)); // tram owner
SB(_m[t].m5, 0, 1, GB(_m[t].m4, 6, 1)); // road axis
SB(_m[t].m5, 5, 1, GB(_m[t].m4, 5, 1)); // crossing state
break;
case ROAD_TILE_DEPOT:
break;
}
if (!IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
const Town *town = CalcClosestTownFromTile(t);
if (town != NULL) SetTownIndex(t, town->index);
}
_m[t].m4 = 0;
break;
case MP_STATION:
if (!IsRoadStop(t)) break;
if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
SB(_me[t].m7, 0, 5, HasBit(_me[t].m6, 2) ? OWNER_TOWN : GetTileOwner(t));
SB(_m[t].m3, 4, 4, _m[t].m1);
_m[t].m4 = 0;
break;
case MP_TUNNELBRIDGE:
if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
Owner o = GetTileOwner(t);
SB(_me[t].m7, 0, 5, o); // road owner
SB(_m[t].m3, 4, 4, o == OWNER_NONE ? OWNER_TOWN : o); // tram owner
}
SB(_me[t].m6, 2, 4, GB(_m[t].m2, 4, 4)); // bridge type
SB(_me[t].m7, 5, 1, GB(_m[t].m4, 7, 1)); // snow/desert
_m[t].m2 = 0;
_m[t].m4 = 0;
break;
default: break;
}
}
}
if (IsSavegameVersionBefore(42)) {
Vehicle *v;
for (TileIndex t = 0; t < map_size; t++) {
if (MayHaveBridgeAbove(t)) ClearBridgeMiddle(t);
if (IsBridgeTile(t)) {
if (HasBit(_m[t].m5, 6)) { // middle part
Axis axis = (Axis)GB(_m[t].m5, 0, 1);
if (HasBit(_m[t].m5, 5)) { // transport route under bridge?
if (GB(_m[t].m5, 3, 2) == TRANSPORT_RAIL) {
MakeRailNormal(
t,
GetTileOwner(t),
axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
GetRailType(t)
);
} else {
TownID town = IsTileOwner(t, OWNER_TOWN) ? ClosestTownFromTile(t, UINT_MAX)->index : 0;
MakeRoadNormal(
t,
axis == AXIS_X ? ROAD_Y : ROAD_X,
ROADTYPES_ROAD,
town,
GetTileOwner(t), OWNER_NONE
);
}
} else {
if (GB(_m[t].m5, 3, 2) == 0) {
MakeClear(t, CLEAR_GRASS, 3);
} else {
if (!IsTileFlat(t)) {
MakeShore(t);
} else {
if (GetTileOwner(t) == OWNER_WATER) {
MakeSea(t);
} else {
MakeCanal(t, GetTileOwner(t), Random());
}
}
}
}
SetBridgeMiddle(t, axis);
} else { // ramp
Axis axis = (Axis)GB(_m[t].m5, 0, 1);
uint north_south = GB(_m[t].m5, 5, 1);
DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
TransportType type = (TransportType)GB(_m[t].m5, 1, 2);
_m[t].m5 = 1 << 7 | type << 2 | dir;
}
}
}
FOR_ALL_VEHICLES(v) {
if (!v->IsGroundVehicle()) continue;
if (IsBridgeTile(v->tile)) {
DiagDirection dir = GetTunnelBridgeDirection(v->tile);
if (dir != DirToDiagDir(v->direction)) continue;
switch (dir) {
default: SlErrorCorrupt("Invalid vehicle direction");
case DIAGDIR_NE: if ((v->x_pos & 0xF) != 0) continue; break;
case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
case DIAGDIR_NW: if ((v->y_pos & 0xF) != 0) continue; break;
}
} else if (v->z_pos > GetSlopePixelZ(v->x_pos, v->y_pos)) {
v->tile = GetNorthernBridgeEnd(v->tile);
} else {
continue;
}
if (v->type == VEH_TRAIN) {
Train::From(v)->track = TRACK_BIT_WORMHOLE;
} else {
RoadVehicle::From(v)->state = RVSB_WORMHOLE;
}
}
}
/* Elrails got added in rev 24 */
if (IsSavegameVersionBefore(24)) {
RailType min_rail = RAILTYPE_ELECTRIC;
Train *v;
FOR_ALL_TRAINS(v) {
RailType rt = RailVehInfo(v->engine_type)->railtype;
v->railtype = rt;
if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
}
/* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_RAILWAY:
SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
break;
case MP_ROAD:
if (IsLevelCrossing(t)) {
SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
}
break;
case MP_STATION:
if (HasStationRail(t)) {
SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
}
break;
case MP_TUNNELBRIDGE:
if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) {
SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
}
break;
default:
break;
}
}
FOR_ALL_TRAINS(v) {
if (v->IsFrontEngine() || v->IsFreeWagon()) v->ConsistChanged(CCF_TRACK);
}
}
/* In version 16.1 of the savegame a company can decide if trains, which get
* replaced, shall keep their old length. In all prior versions, just default
* to false */
if (IsSavegameVersionBefore(16, 1)) {
Company *c;
FOR_ALL_COMPANIES(c) c->settings.renew_keep_length = false;
}
if (IsSavegameVersionBefore(123)) {
/* Waypoints became subclasses of stations ... */
MoveWaypointsToBaseStations();
/* ... and buoys were moved to waypoints. */
MoveBuoysToWaypoints();
}
/* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
* room for PBS. Now in version 21 move it back :P. */
if (IsSavegameVersionBefore(21) && !IsSavegameVersionBefore(15)) {
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_RAILWAY:
if (HasSignals(t)) {
/* Original signal type/variant was stored in m4 but since saveload
* version 48 they are in m2. The bits has been already moved to m2
* (see the code somewhere above) so don't use m4, use m2 instead. */
/* convert PBS signals to combo-signals */
if (HasBit(_m[t].m2, 2)) SB(_m[t].m2, 0, 2, SIGTYPE_COMBO);
/* move the signal variant back */
SB(_m[t].m2, 2, 1, HasBit(_m[t].m2, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
ClrBit(_m[t].m2, 3);
}
/* Clear PBS reservation on track */
if (!IsRailDepotTile(t)) {
SB(_m[t].m4, 4, 4, 0);
} else {
ClrBit(_m[t].m3, 6);
}
break;
case MP_STATION: // Clear PBS reservation on station
ClrBit(_m[t].m3, 6);
break;
default: break;
}
}
}
if (IsSavegameVersionBefore(25)) {
RoadVehicle *rv;
FOR_ALL_ROADVEHICLES(rv) {
rv->vehstatus &= ~0x40;
}
}
if (IsSavegameVersionBefore(26)) {
Station *st;
FOR_ALL_STATIONS(st) {
st->last_vehicle_type = VEH_INVALID;
}
}
YapfNotifyTrackLayoutChange(INVALID_TILE, INVALID_TRACK);
if (IsSavegameVersionBefore(34)) {
Company *c;
FOR_ALL_COMPANIES(c) ResetCompanyLivery(c);
}
Company *c;
FOR_ALL_COMPANIES(c) {
c->avail_railtypes = GetCompanyRailtypes(c->index);
c->avail_roadtypes = GetCompanyRoadtypes(c->index);
}
if (!IsSavegameVersionBefore(27)) AfterLoadStations();
/* Time starts at 0 instead of 1920.
* Account for this in older games by adding an offset */
if (IsSavegameVersionBefore(31)) {
Station *st;
Waypoint *wp;
Engine *e;
Industry *i;
Vehicle *v;
_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
_cur_year += ORIGINAL_BASE_YEAR;
FOR_ALL_STATIONS(st) st->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
FOR_ALL_WAYPOINTS(wp) wp->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
FOR_ALL_ENGINES(e) e->intro_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
FOR_ALL_COMPANIES(c) c->inaugurated_year += ORIGINAL_BASE_YEAR;
FOR_ALL_INDUSTRIES(i) i->last_prod_year += ORIGINAL_BASE_YEAR;
FOR_ALL_VEHICLES(v) {
v->date_of_last_service += DAYS_TILL_ORIGINAL_BASE_YEAR;
v->build_year += ORIGINAL_BASE_YEAR;
}
}
/* From 32 on we save the industry who made the farmland.
* To give this prettiness to old savegames, we remove all farmfields and
* plant new ones. */
if (IsSavegameVersionBefore(32)) {
Industry *i;
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) {
/* remove fields */
MakeClear(t, CLEAR_GRASS, 3);
}
}
FOR_ALL_INDUSTRIES(i) {
uint j;
if (GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_PLANT_ON_BUILT) {
for (j = 0; j != 50; j++) PlantRandomFarmField(i);
}
}
}
/* Setting no refit flags to all orders in savegames from before refit in orders were added */
if (IsSavegameVersionBefore(36)) {
Order *order;
Vehicle *v;
FOR_ALL_ORDERS(order) {
order->SetRefit(CT_NO_REFIT);
}
FOR_ALL_VEHICLES(v) {
v->current_order.SetRefit(CT_NO_REFIT);
}
}
/* from version 38 we have optional elrails, since we cannot know the
* preference of a user, let elrails enabled; it can be disabled manually */
if (IsSavegameVersionBefore(38)) _settings_game.vehicle.disable_elrails = false;
/* do the same as when elrails were enabled/disabled manually just now */
SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
InitializeRailGUI();
/* From version 53, the map array was changed for house tiles to allow
* space for newhouses grf features. A new byte, m7, was also added. */
if (IsSavegameVersionBefore(53)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_HOUSE)) {
if (GB(_m[t].m3, 6, 2) != TOWN_HOUSE_COMPLETED) {
/* Move the construction stage from m3[7..6] to m5[5..4].
* The construction counter does not have to move. */
SB(_m[t].m5, 3, 2, GB(_m[t].m3, 6, 2));
SB(_m[t].m3, 6, 2, 0);
/* The "house is completed" bit is now in m6[2]. */
SetHouseCompleted(t, false);
} else {
/* The "lift has destination" bit has been moved from
* m5[7] to m7[0]. */
SB(_me[t].m7, 0, 1, HasBit(_m[t].m5, 7));
ClrBit(_m[t].m5, 7);
/* The "lift is moving" bit has been removed, as it does
* the same job as the "lift has destination" bit. */
ClrBit(_m[t].m1, 7);
/* The position of the lift goes from m1[7..0] to m6[7..2],
* making m1 totally free, now. The lift position does not
* have to be a full byte since the maximum value is 36. */
SetLiftPosition(t, GB(_m[t].m1, 0, 6 ));
_m[t].m1 = 0;
_m[t].m3 = 0;
SetHouseCompleted(t, true);
}
}
}
}
/* Check and update house and town values */
UpdateHousesAndTowns();
if (IsSavegameVersionBefore(43)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_INDUSTRY)) {
switch (GetIndustryGfx(t)) {
case GFX_POWERPLANT_SPARKS:
_m[t].m3 = GB(_m[t].m1, 2, 5);
break;
case GFX_OILWELL_ANIMATED_1:
case GFX_OILWELL_ANIMATED_2:
case GFX_OILWELL_ANIMATED_3:
_m[t].m3 = GB(_m[t].m1, 0, 2);
break;
case GFX_COAL_MINE_TOWER_ANIMATED:
case GFX_COPPER_MINE_TOWER_ANIMATED:
case GFX_GOLD_MINE_TOWER_ANIMATED:
_m[t].m3 = _m[t].m1;
break;
default: // No animation states to change
break;
}
}
}
}
if (IsSavegameVersionBefore(45)) {
Vehicle *v;
/* Originally just the fact that some cargo had been paid for was
* stored to stop people cheating and cashing in several times. This
* wasn't enough though as it was cleared when the vehicle started
* loading again, even if it didn't actually load anything, so now the
* amount that has been paid is stored. */
FOR_ALL_VEHICLES(v) {
ClrBit(v->vehicle_flags, 2);
}
}
/* Buoys do now store the owner of the previous water tile, which can never
* be OWNER_NONE. So replace OWNER_NONE with OWNER_WATER. */
if (IsSavegameVersionBefore(46)) {
Waypoint *wp;
FOR_ALL_WAYPOINTS(wp) {
if ((wp->facilities & FACIL_DOCK) != 0 && IsTileOwner(wp->xy, OWNER_NONE) && TileHeight(wp->xy) == 0) SetTileOwner(wp->xy, OWNER_WATER);
}
}
if (IsSavegameVersionBefore(50)) {
Aircraft *v;
/* Aircraft units changed from 8 mph to 1 km-ish/h */
FOR_ALL_AIRCRAFT(v) {
if (v->subtype <= AIR_AIRCRAFT) {
const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
v->cur_speed *= 128;
v->cur_speed /= 10;
v->acceleration = avi->acceleration;
}
}
}
if (IsSavegameVersionBefore(49)) FOR_ALL_COMPANIES(c) c->face = ConvertFromOldCompanyManagerFace(c->face);
if (IsSavegameVersionBefore(52)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_OBJECT) && _m[t].m5 == OBJECT_STATUE) {
_m[t].m2 = CalcClosestTownFromTile(t)->index;
}
}
}
/* A setting containing the proportion of towns that grow twice as
* fast was added in version 54. From version 56 this is now saved in the
* town as cities can be built specifically in the scenario editor. */
if (IsSavegameVersionBefore(56)) {
Town *t;
FOR_ALL_TOWNS(t) {
if (_settings_game.economy.larger_towns != 0 && (t->index % _settings_game.economy.larger_towns) == 0) {
t->larger_town = true;
}
}
}
if (IsSavegameVersionBefore(57)) {
Vehicle *v;
/* Added a FIFO queue of vehicles loading at stations */
FOR_ALL_VEHICLES(v) {
if ((v->type != VEH_TRAIN || Train::From(v)->IsFrontEngine()) && // for all locs
!(v->vehstatus & (VS_STOPPED | VS_CRASHED)) && // not stopped or crashed
v->current_order.IsType(OT_LOADING)) { // loading
Station::Get(v->last_station_visited)->loading_vehicles.push_back(v);
/* The loading finished flag is *only* set when actually completely
* finished. Because the vehicle is loading, it is not finished. */
ClrBit(v->vehicle_flags, VF_LOADING_FINISHED);
}
}
} else if (IsSavegameVersionBefore(59)) {
/* For some reason non-loading vehicles could be in the station's loading vehicle list */
Station *st;
FOR_ALL_STATIONS(st) {
std::list<Vehicle *>::iterator iter;
for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end();) {
Vehicle *v = *iter;
iter++;
if (!v->current_order.IsType(OT_LOADING)) st->loading_vehicles.remove(v);
}
}
}
if (IsSavegameVersionBefore(58)) {
/* Setting difficulty industry_density other than zero get bumped to +1
* since a new option (very low at position 1) has been added */
if (_settings_game.difficulty.industry_density > 0) {
_settings_game.difficulty.industry_density++;
}
/* Same goes for number of towns, although no test is needed, just an increment */
_settings_game.difficulty.number_towns++;
}
if (IsSavegameVersionBefore(64)) {
/* Since now we allow different signal types and variants on a single tile.
* Move signal states to m4 to make room and clone the signal type/variant. */
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_RAILWAY) && HasSignals(t)) {
/* move signal states */
SetSignalStates(t, GB(_m[t].m2, 4, 4));
SB(_m[t].m2, 4, 4, 0);
/* clone signal type and variant */
SB(_m[t].m2, 4, 3, GB(_m[t].m2, 0, 3));
}
}
}
if (IsSavegameVersionBefore(69)) {
/* In some old savegames a bit was cleared when it should not be cleared */
RoadVehicle *rv;
FOR_ALL_ROADVEHICLES(rv) {
if (rv->state == 250 || rv->state == 251) {
SetBit(rv->state, 2);
}
}
}
if (IsSavegameVersionBefore(70)) {
/* Added variables to support newindustries */
Industry *i;
FOR_ALL_INDUSTRIES(i) i->founder = OWNER_NONE;
}
/* From version 82, old style canals (above sealevel (0), WATER owner) are no longer supported.
Replace the owner for those by OWNER_NONE. */
if (IsSavegameVersionBefore(82)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_WATER) &&
GetWaterTileType(t) == WATER_TILE_CLEAR &&
GetTileOwner(t) == OWNER_WATER &&
TileHeight(t) != 0) {
SetTileOwner(t, OWNER_NONE);
}
}
}
/*
* Add the 'previous' owner to the ship depots so we can reset it with
* the correct values when it gets destroyed. This prevents that
* someone can remove canals owned by somebody else and it prevents
* making floods using the removal of ship depots.
*/
if (IsSavegameVersionBefore(83)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsShipDepotTile(t)) {
_m[t].m4 = (TileHeight(t) == 0) ? OWNER_WATER : OWNER_NONE;
}
}
}
if (IsSavegameVersionBefore(74)) {
Station *st;
FOR_ALL_STATIONS(st) {
for (CargoID c = 0; c < NUM_CARGO; c++) {
st->goods[c].last_speed = 0;
if (st->goods[c].cargo.AvailableCount() != 0) SetBit(st->goods[c].status, GoodsEntry::GES_RATING);
}
}
}
if (IsSavegameVersionBefore(78)) {
Industry *i;
uint j;
FOR_ALL_INDUSTRIES(i) {
const IndustrySpec *indsp = GetIndustrySpec(i->type);
for (j = 0; j < lengthof(i->produced_cargo); j++) {
i->produced_cargo[j] = indsp->produced_cargo[j];
}
for (j = 0; j < lengthof(i->accepts_cargo); j++) {
i->accepts_cargo[j] = indsp->accepts_cargo[j];
}
}
}
/* Before version 81, the density of grass was always stored as zero, and
* grassy trees were always drawn fully grassy. Furthermore, trees on rough
* land used to have zero density, now they have full density. Therefore,
* make all grassy/rough land trees have a density of 3. */
if (IsSavegameVersionBefore(81)) {
for (TileIndex t = 0; t < map_size; t++) {
if (GetTileType(t) == MP_TREES) {
TreeGround groundType = (TreeGround)GB(_m[t].m2, 4, 2);
if (groundType != TREE_GROUND_SNOW_DESERT) SB(_m[t].m2, 6, 2, 3);
}
}
}
if (IsSavegameVersionBefore(93)) {
/* Rework of orders. */
Order *order;
FOR_ALL_ORDERS(order) order->ConvertFromOldSavegame();
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->orders.list != NULL && v->orders.list->GetFirstOrder() != NULL && v->orders.list->GetFirstOrder()->IsType(OT_NOTHING)) {
v->orders.list->FreeChain();
v->orders.list = NULL;
}
v->current_order.ConvertFromOldSavegame();
if (v->type == VEH_ROAD && v->IsPrimaryVehicle() && v->FirstShared() == v) {
FOR_VEHICLE_ORDERS(v, order) order->SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
}
}
} else if (IsSavegameVersionBefore(94)) {
/* Unload and transfer are now mutual exclusive. */
Order *order;
FOR_ALL_ORDERS(order) {
if ((order->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
order->SetUnloadType(OUFB_TRANSFER);
order->SetLoadType(OLFB_NO_LOAD);
}
}
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if ((v->current_order.GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
v->current_order.SetUnloadType(OUFB_TRANSFER);
v->current_order.SetLoadType(OLFB_NO_LOAD);
}
}
}
if (IsSavegameVersionBefore(84)) {
/* Set all share owners to INVALID_COMPANY for
* 1) all inactive companies
* (when inactive companies were stored in the savegame - TTD, TTDP and some
* *really* old revisions of OTTD; else it is already set in InitializeCompanies())
* 2) shares that are owned by inactive companies or self
* (caused by cheating clients in earlier revisions) */
FOR_ALL_COMPANIES(c) {
for (uint i = 0; i < 4; i++) {
CompanyID company = c->share_owners[i];
if (company == INVALID_COMPANY) continue;
if (!Company::IsValidID(company) || company == c->index) c->share_owners[i] = INVALID_COMPANY;
}
}
}
/* The water class was moved/unified. */
if (IsSavegameVersionBefore(146)) {
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_STATION:
switch (GetStationType(t)) {
case STATION_OILRIG:
case STATION_DOCK:
case STATION_BUOY:
SetWaterClass(t, (WaterClass)GB(_m[t].m3, 0, 2));
SB(_m[t].m3, 0, 2, 0);
break;
default:
SetWaterClass(t, WATER_CLASS_INVALID);
break;
}
break;
case MP_WATER:
SetWaterClass(t, (WaterClass)GB(_m[t].m3, 0, 2));
SB(_m[t].m3, 0, 2, 0);
break;
case MP_OBJECT:
SetWaterClass(t, WATER_CLASS_INVALID);
break;
default:
/* No water class. */
break;
}
}
}
if (IsSavegameVersionBefore(86)) {
for (TileIndex t = 0; t < map_size; t++) {
/* Move river flag and update canals to use water class */
if (IsTileType(t, MP_WATER)) {
if (GetWaterClass(t) != WATER_CLASS_RIVER) {
if (IsWater(t)) {
Owner o = GetTileOwner(t);
if (o == OWNER_WATER) {
MakeSea(t);
} else {
MakeCanal(t, o, Random());
}
} else if (IsShipDepot(t)) {
Owner o = (Owner)_m[t].m4; // Original water owner
SetWaterClass(t, o == OWNER_WATER ? WATER_CLASS_SEA : WATER_CLASS_CANAL);
}
}
}
}
/* Update locks, depots, docks and buoys to have a water class based
* on its neighbouring tiles. Done after river and canal updates to
* ensure neighbours are correct. */
for (TileIndex t = 0; t < map_size; t++) {
if (!IsTileFlat(t)) continue;
if (IsTileType(t, MP_WATER) && IsLock(t)) SetWaterClassDependingOnSurroundings(t, false);
if (IsTileType(t, MP_STATION) && (IsDock(t) || IsBuoy(t))) SetWaterClassDependingOnSurroundings(t, false);
}
}
if (IsSavegameVersionBefore(87)) {
for (TileIndex t = 0; t < map_size; t++) {
/* skip oil rigs at borders! */
if ((IsTileType(t, MP_WATER) || IsBuoyTile(t)) &&
(TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1)) {
/* Some version 86 savegames have wrong water class at map borders (under buoy, or after removing buoy).
* This conversion has to be done before buoys with invalid owner are removed. */
SetWaterClass(t, WATER_CLASS_SEA);
}
if (IsBuoyTile(t) || IsDriveThroughStopTile(t) || IsTileType(t, MP_WATER)) {
Owner o = GetTileOwner(t);
if (o < MAX_COMPANIES && !Company::IsValidID(o)) {
Backup<CompanyByte> cur_company(_current_company, o, FILE_LINE);
ChangeTileOwner(t, o, INVALID_OWNER);
cur_company.Restore();
}
if (IsBuoyTile(t)) {
/* reset buoy owner to OWNER_NONE in the station struct
* (even if it is owned by active company) */
Waypoint::GetByTile(t)->owner = OWNER_NONE;
}
} else if (IsTileType(t, MP_ROAD)) {
/* works for all RoadTileType */
for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
/* update even non-existing road types to update tile owner too */
Owner o = GetRoadOwner(t, rt);
if (o < MAX_COMPANIES && !Company::IsValidID(o)) SetRoadOwner(t, rt, OWNER_NONE);
}
if (IsLevelCrossing(t)) {
if (!Company::IsValidID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
}
} else if (IsPlainRailTile(t)) {
if (!Company::IsValidID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
}
}
/* Convert old PF settings to new */
if (_settings_game.pf.yapf.rail_use_yapf || IsSavegameVersionBefore(28)) {
_settings_game.pf.pathfinder_for_trains = VPF_YAPF;
} else {
_settings_game.pf.pathfinder_for_trains = VPF_NPF;
}
if (_settings_game.pf.yapf.road_use_yapf || IsSavegameVersionBefore(28)) {
_settings_game.pf.pathfinder_for_roadvehs = VPF_YAPF;
} else {
_settings_game.pf.pathfinder_for_roadvehs = VPF_NPF;
}
if (_settings_game.pf.yapf.ship_use_yapf) {
_settings_game.pf.pathfinder_for_ships = VPF_YAPF;
} else {
_settings_game.pf.pathfinder_for_ships = (_settings_game.pf.new_pathfinding_all ? VPF_NPF : VPF_OPF);
}
}
if (IsSavegameVersionBefore(88)) {
/* Profits are now with 8 bit fract */
Vehicle *v;
FOR_ALL_VEHICLES(v) {
v->profit_this_year <<= 8;
v->profit_last_year <<= 8;
v->running_ticks = 0;
}
}
if (IsSavegameVersionBefore(91)) {
/* Increase HouseAnimationFrame from 5 to 7 bits */
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_HOUSE) && GetHouseType(t) >= NEW_HOUSE_OFFSET) {
SB(_me[t].m6, 2, 6, GB(_me[t].m6, 3, 5));
SB(_m[t].m3, 5, 1, 0);
}
}
}
if (IsSavegameVersionBefore(62)) {
/* Remove all trams from savegames without tram support.
* There would be trams without tram track under causing crashes sooner or later. */
RoadVehicle *v;
FOR_ALL_ROADVEHICLES(v) {
if (v->First() == v && HasBit(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM)) {
ShowErrorMessage(STR_WARNING_LOADGAME_REMOVED_TRAMS, INVALID_STRING_ID, WL_CRITICAL);
delete v;
}
}
}
if (IsSavegameVersionBefore(99)) {
for (TileIndex t = 0; t < map_size; t++) {
/* Set newly introduced WaterClass of industry tiles */
if (IsTileType(t, MP_STATION) && IsOilRig(t)) {
SetWaterClassDependingOnSurroundings(t, true);
}
if (IsTileType(t, MP_INDUSTRY)) {
if ((GetIndustrySpec(GetIndustryType(t))->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) {
SetWaterClassDependingOnSurroundings(t, true);
} else {
SetWaterClass(t, WATER_CLASS_INVALID);
}
}
/* Replace "house construction year" with "house age" */
if (IsTileType(t, MP_HOUSE) && IsHouseCompleted(t)) {
_m[t].m5 = Clamp(_cur_year - (_m[t].m5 + ORIGINAL_BASE_YEAR), 0, 0xFF);
}
}
}
/* Move the signal variant back up one bit for PBS. We don't convert the old PBS
* format here, as an old layout wouldn't work properly anyway. To be safe, we
* clear any possible PBS reservations as well. */
if (IsSavegameVersionBefore(100)) {
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_RAILWAY:
if (HasSignals(t)) {
/* move the signal variant */
SetSignalVariant(t, TRACK_UPPER, HasBit(_m[t].m2, 2) ? SIG_SEMAPHORE : SIG_ELECTRIC);
SetSignalVariant(t, TRACK_LOWER, HasBit(_m[t].m2, 6) ? SIG_SEMAPHORE : SIG_ELECTRIC);
ClrBit(_m[t].m2, 2);
ClrBit(_m[t].m2, 6);
}
/* Clear PBS reservation on track */
if (IsRailDepot(t)) {
SetDepotReservation(t, false);
} else {
SetTrackReservation(t, TRACK_BIT_NONE);
}
break;
case MP_ROAD: // Clear PBS reservation on crossing
if (IsLevelCrossing(t)) SetCrossingReservation(t, false);
break;
case MP_STATION: // Clear PBS reservation on station
if (HasStationRail(t)) SetRailStationReservation(t, false);
break;
case MP_TUNNELBRIDGE: // Clear PBS reservation on tunnels/bridges
if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) SetTunnelBridgeReservation(t, false);
break;
default: break;
}
}
}
/* Reserve all tracks trains are currently on. */
if (IsSavegameVersionBefore(101)) {
const Train *t;
FOR_ALL_TRAINS(t) {
if (t->First() == t) t->ReserveTrackUnderConsist();
}
}
if (IsSavegameVersionBefore(102)) {
for (TileIndex t = 0; t < map_size; t++) {
/* Now all crossings should be in correct state */
if (IsLevelCrossingTile(t)) UpdateLevelCrossing(t, false);
}
}
if (IsSavegameVersionBefore(103)) {
/* Non-town-owned roads now store the closest town */
UpdateNearestTownForRoadTiles(false);
/* signs with invalid owner left from older savegames */
Sign *si;
FOR_ALL_SIGNS(si) {
if (si->owner != OWNER_NONE && !Company::IsValidID(si->owner)) si->owner = OWNER_NONE;
}
/* Station can get named based on an industry type, but the current ones
* are not, so mark them as if they are not named by an industry. */
Station *st;
FOR_ALL_STATIONS(st) {
st->indtype = IT_INVALID;
}
}
if (IsSavegameVersionBefore(104)) {
Aircraft *a;
FOR_ALL_AIRCRAFT(a) {
/* Set engine_type of shadow and rotor */
if (!a->IsNormalAircraft()) {
a->engine_type = a->First()->engine_type;
}
}
/* More companies ... */
Company *c;
FOR_ALL_COMPANIES(c) {
if (c->bankrupt_asked == 0xFF) c->bankrupt_asked = 0xFFFF;
}
Engine *e;
FOR_ALL_ENGINES(e) {
if (e->company_avail == 0xFF) e->company_avail = 0xFFFF;
}
Town *t;
FOR_ALL_TOWNS(t) {
if (t->have_ratings == 0xFF) t->have_ratings = 0xFFFF;
for (uint i = 8; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
}
}
if (IsSavegameVersionBefore(112)) {
for (TileIndex t = 0; t < map_size; t++) {
/* Check for HQ bit being set, instead of using map accessor,
* since we've already changed it code-wise */
if (IsTileType(t, MP_OBJECT) && HasBit(_m[t].m5, 7)) {
/* Move size and part identification of HQ out of the m5 attribute,
* on new locations */
_m[t].m3 = GB(_m[t].m5, 0, 5);
_m[t].m5 = OBJECT_HQ;
}
}
}
if (IsSavegameVersionBefore(144)) {
for (TileIndex t = 0; t < map_size; t++) {
if (!IsTileType(t, MP_OBJECT)) continue;
/* Reordering/generalisation of the object bits. */
ObjectType type = _m[t].m5;
SB(_me[t].m6, 2, 4, type == OBJECT_HQ ? GB(_m[t].m3, 2, 3) : 0);
_m[t].m3 = type == OBJECT_HQ ? GB(_m[t].m3, 1, 1) | GB(_m[t].m3, 0, 1) << 4 : 0;
/* Make sure those bits are clear as well! */
_m[t].m4 = 0;
_me[t].m7 = 0;
}
}
if (IsSavegameVersionBefore(147) && Object::GetNumItems() == 0) {
/* Make real objects for object tiles. */
for (TileIndex t = 0; t < map_size; t++) {
if (!IsTileType(t, MP_OBJECT)) continue;
if (Town::GetNumItems() == 0) {
/* No towns, so remove all objects! */
DoClearSquare(t);
} else {
uint offset = _m[t].m3;
/* Also move the animation state. */
_m[t].m3 = GB(_me[t].m6, 2, 4);
SB(_me[t].m6, 2, 4, 0);
if (offset == 0) {
/* No offset, so make the object. */
ObjectType type = _m[t].m5;
int size = type == OBJECT_HQ ? 2 : 1;
if (!Object::CanAllocateItem()) {
/* Nice... you managed to place 64k lighthouses and
* antennae on the map... boohoo. */
SlError(STR_ERROR_TOO_MANY_OBJECTS);
}
Object *o = new Object();
o->location.tile = t;
o->location.w = size;
o->location.h = size;
o->build_date = _date;
o->town = type == OBJECT_STATUE ? Town::Get(_m[t].m2) : CalcClosestTownFromTile(t, UINT_MAX);
_m[t].m2 = o->index;
Object::IncTypeCount(type);
} else {
/* We're at an offset, so get the ID from our "root". */
TileIndex northern_tile = t - TileXY(GB(offset, 0, 4), GB(offset, 4, 4));
assert(IsTileType(northern_tile, MP_OBJECT));
_m[t].m2 = _m[northern_tile].m2;
}
}
}
}
if (IsSavegameVersionBefore(113)) {
/* allow_town_roads is added, set it if town_layout wasn't TL_NO_ROADS */
if (_settings_game.economy.town_layout == 0) { // was TL_NO_ROADS
_settings_game.economy.allow_town_roads = false;
_settings_game.economy.town_layout = TL_BETTER_ROADS;
} else {
_settings_game.economy.allow_town_roads = true;
_settings_game.economy.town_layout = _settings_game.economy.town_layout - 1;
}
/* Initialize layout of all towns. Older versions were using different
* generator for random town layout, use it if needed. */
Town *t;
FOR_ALL_TOWNS(t) {
if (_settings_game.economy.town_layout != TL_RANDOM) {
t->layout = _settings_game.economy.town_layout;
continue;
}
/* Use old layout randomizer code */
byte layout = TileHash(TileX(t->xy), TileY(t->xy)) % 6;
switch (layout) {
default: break;
case 5: layout = 1; break;
case 0: layout = 2; break;
}
t->layout = layout - 1;
}
}
if (IsSavegameVersionBefore(114)) {
/* There could be (deleted) stations with invalid owner, set owner to OWNER NONE.
* The conversion affects oil rigs and buoys too, but it doesn't matter as
* they have st->owner == OWNER_NONE already. */
Station *st;
FOR_ALL_STATIONS(st) {
if (!Company::IsValidID(st->owner)) st->owner = OWNER_NONE;
}
}
/* Trains could now stop in a specific location. */
if (IsSavegameVersionBefore(117)) {
Order *o;
FOR_ALL_ORDERS(o) {
if (o->IsType(OT_GOTO_STATION)) o->SetStopLocation(OSL_PLATFORM_FAR_END);
}
}
if (IsSavegameVersionBefore(120)) {
extern VehicleDefaultSettings _old_vds;
Company *c;
FOR_ALL_COMPANIES(c) {
c->settings.vehicle = _old_vds;
}
}
if (IsSavegameVersionBefore(121)) {
/* Delete small ufos heading for non-existing vehicles */
Vehicle *v;
FOR_ALL_DISASTERVEHICLES(v) {
if (v->subtype == 2 /* ST_SMALL_UFO */ && v->current_order.GetDestination() != 0) {
const Vehicle *u = Vehicle::GetIfValid(v->dest_tile);
if (u == NULL || u->type != VEH_ROAD || !RoadVehicle::From(u)->IsFrontEngine()) {
delete v;
}
}
}
/* We didn't store cargo payment yet, so make them for vehicles that are
* currently at a station and loading/unloading. If they don't get any
* payment anymore they just removed in the next load/unload cycle.
* However, some 0.7 versions might have cargo payment. For those we just
* add cargopayment for the vehicles that don't have it.
*/
Station *st;
FOR_ALL_STATIONS(st) {
std::list<Vehicle *>::iterator iter;
for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
/* There are always as many CargoPayments as Vehicles. We need to make the
* assert() in Pool::GetNew() happy by calling CanAllocateItem(). */
assert_compile(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
assert(CargoPayment::CanAllocateItem());
Vehicle *v = *iter;
if (v->cargo_payment == NULL) v->cargo_payment = new CargoPayment(v);
}
}
}
if (IsSavegameVersionBefore(122)) {
/* Animated tiles would sometimes not be actually animated or
* in case of old savegames duplicate. */
extern TileIndex *_animated_tile_list;
extern uint _animated_tile_count;
for (uint i = 0; i < _animated_tile_count; /* Nothing */) {
/* Remove if tile is not animated */
bool remove = _tile_type_procs[GetTileType(_animated_tile_list[i])]->animate_tile_proc == NULL;
/* and remove if duplicate */
for (uint j = 0; !remove && j < i; j++) {
remove = _animated_tile_list[i] == _animated_tile_list[j];
}
if (remove) {
DeleteAnimatedTile(_animated_tile_list[i]);
} else {
i++;
}
}
}
if (IsSavegameVersionBefore(124) && !IsSavegameVersionBefore(1)) {
/* The train station tile area was added, but for really old (TTDPatch) it's already valid. */
Waypoint *wp;
FOR_ALL_WAYPOINTS(wp) {
if (wp->facilities & FACIL_TRAIN) {
wp->train_station.tile = wp->xy;
wp->train_station.w = 1;
wp->train_station.h = 1;
} else {
wp->train_station.tile = INVALID_TILE;
wp->train_station.w = 0;
wp->train_station.h = 0;
}
}
}
if (IsSavegameVersionBefore(125)) {
/* Convert old subsidies */
Subsidy *s;
FOR_ALL_SUBSIDIES(s) {
if (s->remaining < 12) {
/* Converting nonawarded subsidy */
s->remaining = 12 - s->remaining; // convert "age" to "remaining"
s->awarded = INVALID_COMPANY; // not awarded to anyone
const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
switch (cs->town_effect) {
case TE_PASSENGERS:
case TE_MAIL:
/* Town -> Town */
s->src_type = s->dst_type = ST_TOWN;
if (Town::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
break;
case TE_GOODS:
case TE_FOOD:
/* Industry -> Town */
s->src_type = ST_INDUSTRY;
s->dst_type = ST_TOWN;
if (Industry::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
break;
default:
/* Industry -> Industry */
s->src_type = s->dst_type = ST_INDUSTRY;
if (Industry::IsValidID(s->src) && Industry::IsValidID(s->dst)) continue;
break;
}
} else {
/* Do our best for awarded subsidies. The original source or destination industry
* can't be determined anymore for awarded subsidies, so invalidate them.
* Town -> Town subsidies are converted using simple heuristic */
s->remaining = 24 - s->remaining; // convert "age of awarded subsidy" to "remaining"
const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
switch (cs->town_effect) {
case TE_PASSENGERS:
case TE_MAIL: {
/* Town -> Town */
const Station *ss = Station::GetIfValid(s->src);
const Station *sd = Station::GetIfValid(s->dst);
if (ss != NULL && sd != NULL && ss->owner == sd->owner &&
Company::IsValidID(ss->owner)) {
s->src_type = s->dst_type = ST_TOWN;
s->src = ss->town->index;
s->dst = sd->town->index;
s->awarded = ss->owner;
continue;
}
break;
}
default:
break;
}
}
/* Awarded non-town subsidy or invalid source/destination, invalidate */
delete s;
}
}
if (IsSavegameVersionBefore(126)) {
/* Recompute inflation based on old unround loan limit
* Note: Max loan is 500000. With an inflation of 4% across 170 years
* that results in a max loan of about 0.7 * 2^31.
* So taking the 16 bit fractional part into account there are plenty of bits left
* for unmodified savegames ...
*/
uint64 aimed_inflation = (_economy.old_max_loan_unround << 16 | _economy.old_max_loan_unround_fract) / _settings_game.difficulty.max_loan;
/* ... well, just clamp it then. */
if (aimed_inflation > MAX_INFLATION) aimed_inflation = MAX_INFLATION;
/* Simulate the inflation, so we also get the payment inflation */
while (_economy.inflation_prices < aimed_inflation) {
if (AddInflation(false)) break;
}
}
if (IsSavegameVersionBefore(128)) {
const Depot *d;
FOR_ALL_DEPOTS(d) {
_m[d->xy].m2 = d->index;
if (IsTileType(d->xy, MP_WATER)) _m[GetOtherShipDepotTile(d->xy)].m2 = d->index;
}
}
/* The behaviour of force_proceed has been changed. Now
* it counts signals instead of some random time out. */
if (IsSavegameVersionBefore(131)) {
Train *t;
FOR_ALL_TRAINS(t) {
if (t->force_proceed != TFP_NONE) {
t->force_proceed = TFP_STUCK;
}
}
}
/* The bits for the tree ground and tree density have
* been swapped (m2 bits 7..6 and 5..4. */
if (IsSavegameVersionBefore(135)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_CLEAR)) {
if (GetRawClearGround(t) == CLEAR_SNOW) {
SetClearGroundDensity(t, CLEAR_GRASS, GetClearDensity(t));
SetBit(_m[t].m3, 4);
} else {
ClrBit(_m[t].m3, 4);
}
}
if (IsTileType(t, MP_TREES)) {
uint density = GB(_m[t].m2, 6, 2);
uint ground = GB(_m[t].m2, 4, 2);
uint counter = GB(_m[t].m2, 0, 4);
_m[t].m2 = ground << 6 | density << 4 | counter;
}
}
}
/* Wait counter and load/unload ticks got split. */
if (IsSavegameVersionBefore(136)) {
Aircraft *a;
FOR_ALL_AIRCRAFT(a) {
a->turn_counter = a->current_order.IsType(OT_LOADING) ? 0 : a->load_unload_ticks;
}
Train *t;
FOR_ALL_TRAINS(t) {
t->wait_counter = t->current_order.IsType(OT_LOADING) ? 0 : t->load_unload_ticks;
}
}
/* Airport tile animation uses animation frame instead of other graphics id */
if (IsSavegameVersionBefore(137)) {
struct AirportTileConversion {
byte old_start;
byte num_frames;
};
static const AirportTileConversion atc[] = {
{31, 12}, // APT_RADAR_GRASS_FENCE_SW
{50, 4}, // APT_GRASS_FENCE_NE_FLAG
{62, 2}, // 1 unused tile
{66, 12}, // APT_RADAR_FENCE_SW
{78, 12}, // APT_RADAR_FENCE_NE
{101, 10}, // 9 unused tiles
{111, 8}, // 7 unused tiles
{119, 15}, // 14 unused tiles (radar)
{140, 4}, // APT_GRASS_FENCE_NE_FLAG_2
};
for (TileIndex t = 0; t < map_size; t++) {
if (IsAirportTile(t)) {
StationGfx old_gfx = GetStationGfx(t);
byte offset = 0;
for (uint i = 0; i < lengthof(atc); i++) {
if (old_gfx < atc[i].old_start) {
SetStationGfx(t, old_gfx - offset);
break;
}
if (old_gfx < atc[i].old_start + atc[i].num_frames) {
SetAnimationFrame(t, old_gfx - atc[i].old_start);
SetStationGfx(t, atc[i].old_start - offset);
break;
}
offset += atc[i].num_frames - 1;
}
}
}
}
if (IsSavegameVersionBefore(140)) {
Station *st;
FOR_ALL_STATIONS(st) {
if (st->airport.tile != INVALID_TILE) {
st->airport.w = st->airport.GetSpec()->size_x;
st->airport.h = st->airport.GetSpec()->size_y;
}
}
}
if (IsSavegameVersionBefore(141)) {
for (TileIndex t = 0; t < map_size; t++) {
/* Reset tropic zone for VOID tiles, they shall not have any. */
if (IsTileType(t, MP_VOID)) SetTropicZone(t, TROPICZONE_NORMAL);
}
/* We need to properly number/name the depots.
* The first step is making sure none of the depots uses the
* 'default' names, after that we can assign the names. */
Depot *d;
FOR_ALL_DEPOTS(d) d->town_cn = UINT16_MAX;
FOR_ALL_DEPOTS(d) MakeDefaultName(d);
}
if (IsSavegameVersionBefore(142)) {
Depot *d;
FOR_ALL_DEPOTS(d) d->build_date = _date;
}
if (SlXvIsFeatureMissing(XSLFI_INFRA_SHARING)) {
Company *c;
FOR_ALL_COMPANIES(c) {
/* yearly_expenses has 3*15 entries now, saveload code gave us 3*13.
* Move the old data to the right place in the new array and clear the new data.
* The move has to be done in reverse order (first 2, then 1). */
MemMoveT(&c->yearly_expenses[2][0], &c->yearly_expenses[1][11], 13);
MemMoveT(&c->yearly_expenses[1][0], &c->yearly_expenses[0][13], 13);
/* Clear the old location of just-moved data, so sharing income/expenses is set to 0 */
MemSetT(&c->yearly_expenses[0][13], 0, 2);
MemSetT(&c->yearly_expenses[1][13], 0, 2);
}
}
/* In old versions it was possible to remove an airport while a plane was
* taking off or landing. This gives all kind of problems when building
* another airport in the same station so we don't allow that anymore.
* For old savegames with such aircraft we just throw them in the air and
* treat the aircraft like they were flying already. */
if (IsSavegameVersionBefore(146)) {
Aircraft *v;
FOR_ALL_AIRCRAFT(v) {
if (!v->IsNormalAircraft()) continue;
Station *st = GetTargetAirportIfValid(v);
if (st == NULL && v->state != FLYING) {
v->state = FLYING;
UpdateAircraftCache(v);
AircraftNextAirportPos_and_Order(v);
/* get aircraft back on running altitude */
if ((v->vehstatus & VS_CRASHED) == 0) {
GetAircraftFlightLevelBounds(v, &v->z_pos, NULL);
SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
}
}
}
}
/* Move the animation frame to the same location (m7) for all objects. */
if (IsSavegameVersionBefore(147)) {
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_HOUSE:
if (GetHouseType(t) >= NEW_HOUSE_OFFSET) {
uint per_proc = _me[t].m7;
_me[t].m7 = GB(_me[t].m6, 2, 6) | (GB(_m[t].m3, 5, 1) << 6);
SB(_m[t].m3, 5, 1, 0);
SB(_me[t].m6, 2, 6, min(per_proc, 63));
}
break;
case MP_INDUSTRY: {
uint rand = _me[t].m7;
_me[t].m7 = _m[t].m3;
_m[t].m3 = rand;
break;
}
case MP_OBJECT:
_me[t].m7 = _m[t].m3;
_m[t].m3 = 0;
break;
default:
/* For stations/airports it's already at m7 */
break;
}
}
}
/* Add (random) colour to all objects. */
if (IsSavegameVersionBefore(148)) {
Object *o;
FOR_ALL_OBJECTS(o) {
Owner owner = GetTileOwner(o->location.tile);
o->colour = (owner == OWNER_NONE) ? Random() & 0xF : Company::Get(owner)->livery->colour1;
}
}
if (IsSavegameVersionBefore(149)) {
for (TileIndex t = 0; t < map_size; t++) {
if (!IsTileType(t, MP_STATION)) continue;
if (!IsBuoy(t) && !IsOilRig(t) && !(IsDock(t) && IsTileFlat(t))) {
SetWaterClass(t, WATER_CLASS_INVALID);
}
}
/* Waypoints with custom name may have a non-unique town_cn,
* renumber those. First set all affected waypoints to the
* highest possible number to get them numbered in the
* order they have in the pool. */
Waypoint *wp;
FOR_ALL_WAYPOINTS(wp) {
if (wp->name != NULL) wp->town_cn = UINT16_MAX;
}
FOR_ALL_WAYPOINTS(wp) {
if (wp->name != NULL) MakeDefaultName(wp);
}
}
if (IsSavegameVersionBefore(152)) {
_industry_builder.Reset(); // Initialize industry build data.
/* The moment vehicles go from hidden to visible changed. This means
* that vehicles don't always get visible anymore causing things to
* get messed up just after loading the savegame. This fixes that. */
Vehicle *v;
FOR_ALL_VEHICLES(v) {
/* Not all vehicle types can be inside a tunnel. Furthermore,
* testing IsTunnelTile() for invalid tiles causes a crash. */
if (!v->IsGroundVehicle()) continue;
/* Is the vehicle in a tunnel? */
if (!IsTunnelTile(v->tile)) continue;
/* Is the vehicle actually at a tunnel entrance/exit? */
TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
if (!IsTunnelTile(vtile)) continue;
/* Are we actually in this tunnel? Or maybe a lower tunnel? */
if (GetSlopePixelZ(v->x_pos, v->y_pos) != v->z_pos) continue;
/* What way are we going? */
const DiagDirection dir = GetTunnelBridgeDirection(vtile);
const DiagDirection vdir = DirToDiagDir(v->direction);
/* Have we passed the visibility "switch" state already? */
byte pos = (DiagDirToAxis(vdir) == AXIS_X ? v->x_pos : v->y_pos) & TILE_UNIT_MASK;
byte frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
extern const byte _tunnel_visibility_frame[DIAGDIR_END];
/* Should the vehicle be hidden or not? */
bool hidden;
if (dir == vdir) { // Entering tunnel
hidden = frame >= _tunnel_visibility_frame[dir];
v->tile = vtile;
} else if (dir == ReverseDiagDir(vdir)) { // Leaving tunnel
hidden = frame < TILE_SIZE - _tunnel_visibility_frame[dir];
/* v->tile changes at the moment when the vehicle leaves the tunnel. */
v->tile = hidden ? GetOtherTunnelBridgeEnd(vtile) : vtile;
} else {
/* We could get here in two cases:
* - for road vehicles, it is reversing at the end of the tunnel
* - it is crashed in the tunnel entry (both train or RV destroyed by UFO)
* Whatever case it is, do not change anything and use the old values.
* Especially changing RV's state would break its reversing in the middle. */
continue;
}
if (hidden) {
v->vehstatus |= VS_HIDDEN;
switch (v->type) {
case VEH_TRAIN: Train::From(v)->track = TRACK_BIT_WORMHOLE; break;
case VEH_ROAD: RoadVehicle::From(v)->state = RVSB_WORMHOLE; break;
default: NOT_REACHED();
}
} else {
v->vehstatus &= ~VS_HIDDEN;
switch (v->type) {
case VEH_TRAIN: Train::From(v)->track = DiagDirToDiagTrackBits(vdir); break;
case VEH_ROAD: RoadVehicle::From(v)->state = DiagDirToDiagTrackdir(vdir); RoadVehicle::From(v)->frame = frame; break;
default: NOT_REACHED();
}
}
}
}
if (IsSavegameVersionBefore(153)) {
RoadVehicle *rv;
FOR_ALL_ROADVEHICLES(rv) {
if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) continue;
bool loading = rv->current_order.IsType(OT_LOADING) || rv->current_order.IsType(OT_LEAVESTATION);
if (HasBit(rv->state, RVS_IN_ROAD_STOP)) {
extern const byte _road_stop_stop_frame[];
SB(rv->state, RVS_ENTERED_STOP, 1, loading || rv->frame > _road_stop_stop_frame[rv->state - RVSB_IN_ROAD_STOP + (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)]);
} else if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) {
SB(rv->state, RVS_ENTERED_STOP, 1, loading || rv->frame > RVC_DRIVE_THROUGH_STOP_FRAME);
}
}
}
if (IsSavegameVersionBefore(156)) {
/* The train's pathfinder lost flag got moved. */
Train *t;
FOR_ALL_TRAINS(t) {
if (!HasBit(t->flags, 5)) continue;
ClrBit(t->flags, 5);
SetBit(t->vehicle_flags, VF_PATHFINDER_LOST);
}
/* Introduced terraform/clear limits. */
Company *c;
FOR_ALL_COMPANIES(c) {
c->terraform_limit = _settings_game.construction.terraform_frame_burst << 16;
c->clear_limit = _settings_game.construction.clear_frame_burst << 16;
}
}
if (IsSavegameVersionBefore(158)) {
Vehicle *v;
FOR_ALL_VEHICLES(v) {
switch (v->type) {
case VEH_TRAIN: {
Train *t = Train::From(v);
/* Clear old GOINGUP / GOINGDOWN flags.
* It was changed in savegame version 139, but savegame
* version 158 doesn't use these bits, so it doesn't hurt
* to clear them unconditionally. */
ClrBit(t->flags, 1);
ClrBit(t->flags, 2);
/* Clear both bits first. */
ClrBit(t->gv_flags, GVF_GOINGUP_BIT);
ClrBit(t->gv_flags, GVF_GOINGDOWN_BIT);
/* Crashed vehicles can't be going up/down. */
if (t->vehstatus & VS_CRASHED) break;
/* Only X/Y tracks can be sloped. */
if (t->track != TRACK_BIT_X && t->track != TRACK_BIT_Y) break;
t->gv_flags |= FixVehicleInclination(t, t->direction);
break;
}
case VEH_ROAD: {
RoadVehicle *rv = RoadVehicle::From(v);
ClrBit(rv->gv_flags, GVF_GOINGUP_BIT);
ClrBit(rv->gv_flags, GVF_GOINGDOWN_BIT);
/* Crashed vehicles can't be going up/down. */
if (rv->vehstatus & VS_CRASHED) break;
if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) break;
TrackStatus ts = GetTileTrackStatus(rv->tile, TRANSPORT_ROAD, rv->compatible_roadtypes);
TrackBits trackbits = TrackStatusToTrackBits(ts);
/* Only X/Y tracks can be sloped. */
if (trackbits != TRACK_BIT_X && trackbits != TRACK_BIT_Y) break;
Direction dir = rv->direction;
/* Test if we are reversing. */
Axis a = trackbits == TRACK_BIT_X ? AXIS_X : AXIS_Y;
if (AxisToDirection(a) != dir &&
AxisToDirection(a) != ReverseDir(dir)) {
/* When reversing, the road vehicle is on the edge of the tile,
* so it can be safely compared to the middle of the tile. */
dir = INVALID_DIR;
}
rv->gv_flags |= FixVehicleInclination(rv, dir);
break;
}
case VEH_SHIP:
break;
default:
continue;
}
if (IsBridgeTile(v->tile) && TileVirtXY(v->x_pos, v->y_pos) == v->tile) {
/* In old versions, z_pos was 1 unit lower on bridge heads.
* However, this invalid state could be converted to new savegames
* by loading and saving the game in a new version. */
v->z_pos = GetSlopePixelZ(v->x_pos, v->y_pos);
DiagDirection dir = GetTunnelBridgeDirection(v->tile);
if (v->type == VEH_TRAIN && !(v->vehstatus & VS_CRASHED) &&
v->direction != DiagDirToDir(dir)) {
/* If the train has left the bridge, it shouldn't have
* track == TRACK_BIT_WORMHOLE - this could happen
* when the train was reversed while on the last "tick"
* on the ramp before leaving the ramp to the bridge. */
Train::From(v)->track = DiagDirToDiagTrackBits(dir);
}
}
/* If the vehicle is really above v->tile (not in a wormhole),
* it should have set v->z_pos correctly. */
assert(v->tile != TileVirtXY(v->x_pos, v->y_pos) || v->z_pos == GetSlopePixelZ(v->x_pos, v->y_pos));
}
/* Fill Vehicle::cur_real_order_index */
FOR_ALL_VEHICLES(v) {
if (!v->IsPrimaryVehicle()) continue;
/* Older versions are less strict with indices being in range and fix them on the fly */
if (v->cur_implicit_order_index >= v->GetNumOrders()) v->cur_implicit_order_index = 0;
v->cur_real_order_index = v->cur_implicit_order_index;
v->UpdateRealOrderIndex();
}
}
if (IsSavegameVersionBefore(159)) {
/* If the savegame is old (before version 100), then the value of 255
* for these settings did not mean "disabled". As such everything
* before then did reverse.
* To simplify stuff we disable all turning around or we do not
* disable anything at all. So, if some reversing was disabled we
* will keep reversing disabled, otherwise it'll be turned on. */
_settings_game.pf.reverse_at_signals = IsSavegameVersionBefore(100) || (_settings_game.pf.wait_oneway_signal != 255 && _settings_game.pf.wait_twoway_signal != 255 && _settings_game.pf.wait_for_pbs_path != 255);
Train *t;
FOR_ALL_TRAINS(t) {
_settings_game.vehicle.max_train_length = max<uint8>(_settings_game.vehicle.max_train_length, CeilDiv(t->gcache.cached_total_length, TILE_SIZE));
}
}
if (IsSavegameVersionBefore(160)) {
/* Setting difficulty industry_density other than zero get bumped to +1
* since a new option (minimal at position 1) has been added */
if (_settings_game.difficulty.industry_density > 0) {
_settings_game.difficulty.industry_density++;
}
}
if (IsSavegameVersionBefore(161)) {
/* Before savegame version 161, persistent storages were not stored in a pool. */
if (!IsSavegameVersionBefore(76)) {
Industry *ind;
FOR_ALL_INDUSTRIES(ind) {
assert(ind->psa != NULL);
/* Check if the old storage was empty. */
bool is_empty = true;
for (uint i = 0; i < sizeof(ind->psa->storage); i++) {
if (ind->psa->GetValue(i) != 0) {
is_empty = false;
break;
}
}
if (!is_empty) {
ind->psa->grfid = _industry_mngr.GetGRFID(ind->type);
} else {
delete ind->psa;
ind->psa = NULL;
}
}
}
if (!IsSavegameVersionBefore(145)) {
Station *st;
FOR_ALL_STATIONS(st) {
if (!(st->facilities & FACIL_AIRPORT)) continue;
assert(st->airport.psa != NULL);
/* Check if the old storage was empty. */
bool is_empty = true;
for (uint i = 0; i < sizeof(st->airport.psa->storage); i++) {
if (st->airport.psa->GetValue(i) != 0) {
is_empty = false;
break;
}
}
if (!is_empty) {
st->airport.psa->grfid = _airport_mngr.GetGRFID(st->airport.type);
} else {
delete st->airport.psa;
st->airport.psa = NULL;
}
}
}
}
/* This triggers only when old snow_lines were copied into the snow_line_height. */
if (IsSavegameVersionBefore(164) && _settings_game.game_creation.snow_line_height >= MIN_SNOWLINE_HEIGHT * TILE_HEIGHT) {
_settings_game.game_creation.snow_line_height /= TILE_HEIGHT;
}
if (IsSavegameVersionBefore(164) && !IsSavegameVersionBefore(32)) {
/* We store 4 fences in the field tiles instead of only SE and SW. */
for (TileIndex t = 0; t < map_size; t++) {
if (!IsTileType(t, MP_CLEAR) && !IsTileType(t, MP_TREES)) continue;
if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) continue;
uint fence = GB(_m[t].m4, 5, 3);
if (fence != 0 && IsTileType(TILE_ADDXY(t, 1, 0), MP_CLEAR) && IsClearGround(TILE_ADDXY(t, 1, 0), CLEAR_FIELDS)) {
SetFence(TILE_ADDXY(t, 1, 0), DIAGDIR_NE, fence);
}
fence = GB(_m[t].m4, 2, 3);
if (fence != 0 && IsTileType(TILE_ADDXY(t, 0, 1), MP_CLEAR) && IsClearGround(TILE_ADDXY(t, 0, 1), CLEAR_FIELDS)) {
SetFence(TILE_ADDXY(t, 0, 1), DIAGDIR_NW, fence);
}
SB(_m[t].m4, 2, 3, 0);
SB(_m[t].m4, 5, 3, 0);
}
}
/* The center of train vehicles was changed, fix up spacing. */
if (IsSavegameVersionBefore(164)) FixupTrainLengths();
if (IsSavegameVersionBefore(165)) {
Town *t;
FOR_ALL_TOWNS(t) {
/* Set the default cargo requirement for town growth */
switch (_settings_game.game_creation.landscape) {
case LT_ARCTIC:
if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_WINTER;
break;
case LT_TROPIC:
if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_DESERT;
if (FindFirstCargoWithTownEffect(TE_WATER) != NULL) t->goal[TE_WATER] = TOWN_GROWTH_DESERT;
break;
}
}
}
if (IsSavegameVersionBefore(165)) {
/* Adjust zoom level to account for new levels */
_saved_scrollpos_zoom = _saved_scrollpos_zoom + ZOOM_LVL_SHIFT;
_saved_scrollpos_x *= ZOOM_LVL_BASE;
_saved_scrollpos_y *= ZOOM_LVL_BASE;
}
/* When any NewGRF has been changed the availability of some vehicles might
* have been changed too. e->company_avail must be set to 0 in that case
* which is done by StartupEngines(). */
if (gcf_res != GLC_ALL_GOOD) StartupEngines();
if (IsSavegameVersionBefore(166)) {
/* Update cargo acceptance map of towns. */
for (TileIndex t = 0; t < map_size; t++) {
if (!IsTileType(t, MP_HOUSE)) continue;
Town::Get(GetTownIndex(t))->cargo_accepted.Add(t);
}
Town *town;
FOR_ALL_TOWNS(town) {
UpdateTownCargoes(town);
}
}
/* Set some breakdown-related variables to the correct values. */
if (SlXvIsFeatureMissing(XSLFI_IMPROVED_BREAKDOWNS)) {
Train *v;
FOR_ALL_TRAINS(v) {
if (v->IsFrontEngine()) {
if (v->breakdown_ctr == 1) SetBit(v->flags, VRF_BREAKDOWN_STOPPED);
} else if (v->IsEngine() || v->IsMultiheaded()) {
/** Non-front engines could have a reliability of 0.
* Set it to the reliability of the front engine or the maximum, whichever is lower. */
const Engine *e = Engine::Get(v->engine_type);
v->reliability_spd_dec = e->reliability_spd_dec;
v->reliability = min(v->First()->reliability, e->reliability);
}
}
}
if (!SlXvIsFeaturePresent(XSLFI_IMPROVED_BREAKDOWNS, 3)) {
Vehicle *v;
FOR_ALL_VEHICLES(v) {
switch(v->type) {
case VEH_TRAIN:
case VEH_ROAD:
v->breakdown_chance_factor = 128;
break;
case VEH_SHIP:
v->breakdown_chance_factor = 64;
break;
case VEH_AIRCRAFT:
v->breakdown_chance_factor = Clamp(64 + (AircraftVehInfo(v->engine_type)->max_speed >> 3), 0, 255);
v->breakdown_severity = 40;
break;
default:
break;
}
}
}
/* The road owner of standard road stops was not properly accounted for. */
if (IsSavegameVersionBefore(172)) {
for (TileIndex t = 0; t < map_size; t++) {
if (!IsStandardRoadStopTile(t)) continue;
Owner o = GetTileOwner(t);
SetRoadOwner(t, ROADTYPE_ROAD, o);
SetRoadOwner(t, ROADTYPE_TRAM, o);
}
}
if (IsSavegameVersionBefore(175)) {
/* Introduced tree planting limit. */
Company *c;
FOR_ALL_COMPANIES(c) c->tree_limit = _settings_game.construction.tree_frame_burst << 16;
}
if (IsSavegameVersionBefore(177)) {
/* Fix too high inflation rates */
if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION;
if (_economy.inflation_payment > MAX_INFLATION) _economy.inflation_payment = MAX_INFLATION;
/* We have to convert the quarters of bankruptcy into months of bankruptcy */
FOR_ALL_COMPANIES(c) {
c->months_of_bankruptcy = 3 * c->months_of_bankruptcy;
}
}
if (IsSavegameVersionBefore(178)) {
extern uint8 _old_diff_level;
/* Initialise script settings profile */
_settings_game.script.settings_profile = IsInsideMM(_old_diff_level, SP_BEGIN, SP_END) ? _old_diff_level : (uint)SP_MEDIUM;
}
if (IsSavegameVersionBefore(182)) {
Aircraft *v;
/* Aircraft acceleration variable was bonkers */
FOR_ALL_AIRCRAFT(v) {
if (v->subtype <= AIR_AIRCRAFT) {
const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
v->acceleration = avi->acceleration;
}
}
/* Blocked tiles could be reserved due to a bug, which causes
* other places to assert upon e.g. station reconstruction. */
for (TileIndex t = 0; t < map_size; t++) {
if (HasStationTileRail(t) && IsStationTileBlocked(t)) {
SetRailStationReservation(t, false);
}
}
}
if (IsSavegameVersionBefore(184)) {
/* The global units configuration is split up in multiple configurations. */
extern uint8 _old_units;
_settings_game.locale.units_velocity = Clamp(_old_units, 0, 2);
_settings_game.locale.units_power = Clamp(_old_units, 0, 2);
_settings_game.locale.units_weight = Clamp(_old_units, 1, 2);
_settings_game.locale.units_volume = Clamp(_old_units, 1, 2);
_settings_game.locale.units_force = 2;
_settings_game.locale.units_height = Clamp(_old_units, 0, 2);
}
if (IsSavegameVersionBefore(186)) {
/* Move ObjectType from map to pool */
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_OBJECT)) {
Object *o = Object::Get(_m[t].m2);
o->type = _m[t].m5;
_m[t].m5 = 0; // zero upper bits of (now bigger) ObjectID
}
}
}
if (SlXvIsFeaturePresent(XSLFI_SPRINGPP)) {
// re-arrange vehicle_flags
Vehicle *v;
FOR_ALL_VEHICLES(v) {
SB(v->vehicle_flags, VF_AUTOMATE_TIMETABLE, 1, GB(v->vehicle_flags, 6, 1));
SB(v->vehicle_flags, VF_STOP_LOADING, 4, GB(v->vehicle_flags, 7, 4));
}
}
if (IsSavegameVersionBefore(188)) {
/* Fix articulated road vehicles.
* Some curves were shorter than other curves.
* Now they have the same length, but that means that trailing articulated parts will
* take longer to go through the curve than the parts in front which already left the courve.
* So, make articulated parts catch up. */
RoadVehicle *v;
bool roadside = _settings_game.vehicle.road_side == 1;
SmallVector<uint, 16> skip_frames;
FOR_ALL_ROADVEHICLES(v) {
if (!v->IsFrontEngine()) continue;
skip_frames.Clear();
TileIndex prev_tile = v->tile;
uint prev_tile_skip = 0;
uint cur_skip = 0;
for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
if (u->tile != prev_tile) {
prev_tile_skip = cur_skip;
prev_tile = u->tile;
} else {
cur_skip = prev_tile_skip;
}
uint *this_skip = skip_frames.Append();
*this_skip = prev_tile_skip;
/* The following 3 curves now take longer than before */
switch (u->state) {
case 2:
cur_skip++;
if (u->frame <= (roadside ? 9 : 5)) *this_skip = cur_skip;
break;
case 4:
cur_skip++;
if (u->frame <= (roadside ? 5 : 9)) *this_skip = cur_skip;
break;
case 5:
cur_skip++;
if (u->frame <= (roadside ? 4 : 2)) *this_skip = cur_skip;
break;
default:
break;
}
}
while (cur_skip > skip_frames[0]) {
RoadVehicle *u = v;
RoadVehicle *prev = NULL;
for (uint *it = skip_frames.Begin(); it != skip_frames.End(); ++it, prev = u, u = u->Next()) {
extern bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev);
if (*it >= cur_skip) IndividualRoadVehicleController(u, prev);
}
cur_skip--;
}
}
}
if (SlXvIsFeatureMissing(XSLFI_REVERSE_AT_WAYPOINT)) {
Train *t;
FOR_ALL_TRAINS(t) {
t->reverse_distance = 0;
}
}
/*
* Only keep order-backups for network clients (and when replaying).
* If we are a network server or not networking, then we just loaded a previously
* saved-by-server savegame. There are no clients with a backup, so clear it.
* Furthermore before savegame version 192 the actual content was always corrupt.
*/
if (!_networking || _network_server || IsSavegameVersionBefore(192)) {
#ifndef DEBUG_DUMP_COMMANDS
/* Note: We cannot use CleanPool since that skips part of the destructor
* and then leaks un-reachable Orders in the order pool. */
OrderBackup *ob;
FOR_ALL_ORDER_BACKUPS(ob) {
delete ob;
}
#endif
}
if (SlXvIsFeatureMissing(XSLFI_TIMETABLES_START_TICKS)) {
// savegame timetable start is in days, but we want it in ticks, fix it up
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->timetable_start != 0) {
v->timetable_start *= DAY_TICKS;
}
}
}
if (SlXvIsFeaturePresent(XSLFI_SPRINGPP, 1, 1)) {
/*
* Cost scaling changes:
* SpringPP v2.0.102 divides all prices by the difficulty factor, effectively making things about 8 times cheaper.
* Adjust the inflation factor to compensate for this, as otherwise the game is unplayable on load if inflation has been running for a while.
* To avoid making things too cheap, clamp the price inflation factor to no lower than the payment inflation factor.
*/
DEBUG(sl, 3, "Inflation prices: %f", _economy.inflation_prices / 65536.0);
DEBUG(sl, 3, "Inflation payments: %f", _economy.inflation_payment / 65536.0);
_economy.inflation_prices >>= 3;
if (_economy.inflation_prices < _economy.inflation_payment) {
_economy.inflation_prices = _economy.inflation_payment;
}
DEBUG(sl, 3, "New inflation prices: %f", _economy.inflation_prices / 65536.0);
}
if (SlXvIsFeaturePresent(XSLFI_MIGHT_USE_PAX_SIGNALS) || SlXvIsFeatureMissing(XSLFI_TRACE_RESTRICT)) {
for (TileIndex t = 0; t < map_size; t++) {
if (HasStationTileRail(t)) {
/* clear station PAX bit */
ClrBit(_me[t].m6, 6);
}
if (IsTileType(t, MP_RAILWAY) && HasSignals(t)) {
/*
* tracerestrict uses same bit as 1st PAX signals bit
* only conditionally clear the bit, don't bother checking for whether to set it
*/
if (IsRestrictedSignal(t)) {
TraceRestrictSetIsSignalRestrictedBit(t);
}
/* clear 2nd signal PAX bit */
ClrBit(_m[t].m2, 13);
}
}
}
if (SlXvIsFeaturePresent(XSLFI_TRAFFIC_LIGHTS)) {
/* remove traffic lights */
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_ROAD) && (GetRoadTileType(t) == ROAD_TILE_NORMAL)) {
DeleteAnimatedTile(t);
ClrBit(_me[t].m7, 4);
}
}
}
if (SlXvIsFeaturePresent(XSLFI_RAIL_AGEING)) {
/* remove rail aging data */
for (TileIndex t = 0; t < map_size; t++) {
if (IsPlainRailTile(t)) {
SB(_me[t].m7, 0, 8, 0);
}
}
}
if (SlXvIsFeaturePresent(XSLFI_SPRINGPP)) {
/* convert wait for cargo orders to ordinary load if possible */
Order *order;
FOR_ALL_ORDERS(order) {
if (order->GetLoadType() == static_cast<OrderLoadFlags>(1)) order->SetLoadType(OLF_LOAD_IF_POSSIBLE);
}
}
if (SlXvIsFeaturePresent(XSLFI_SIG_TUNNEL_BRIDGE, 1, 1)) {
/* set the semaphore bit to match what it would have been in v1 */
/* clear the PBS bit, update the end signal state */
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_TUNNELBRIDGE) && GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL && HasWormholeSignals(t)) {
SetTunnelBridgeSemaphore(t, _cur_year < _settings_client.gui.semaphore_build_before);
SetTunnelBridgePBS(t, false);
UpdateSignalsOnSegment(t, INVALID_DIAGDIR, GetTileOwner(t));
}
}
}
/* Station acceptance is some kind of cache */
if (IsSavegameVersionBefore(127)) {
Station *st;
FOR_ALL_STATIONS(st) UpdateStationAcceptance(st, false);
}
// setting moved from game settings to company settings
if (SlXvIsFeaturePresent(XSLFI_ORDER_OCCUPANCY, 1, 1)) {
Company *c;
FOR_ALL_COMPANIES(c) {
c->settings.order_occupancy_smoothness = _settings_game.order.old_occupancy_smoothness;
}
}
/* Set lifetime vehicle profit to 0 if lifetime profit feature is missing */
if (SlXvIsFeatureMissing(XSLFI_VEH_LIFETIME_PROFIT)) {
Vehicle *v;
FOR_ALL_VEHICLES(v) v->profit_lifetime = 0;
}
// Before this version we didn't store the 5th bit of the tracktype here.
// So set it to 0 just in case there was garbage in there.
if (SlXvIsFeatureMissing(XSLFI_MORE_RAIL_TYPES)) {
for (TileIndex t = 0; t < map_size; t++) {
if (GetTileType(t) == MP_RAILWAY ||
IsLevelCrossingTile(t) ||
IsRailStationTile(t) ||
IsRailWaypointTile(t) ||
IsRailTunnelBridgeTile(t)) {
ClrBit(_m[t].m1, 7);
}
}
}
if (SlXvIsFeaturePresent(XSLFI_AUTO_TIMETABLE, 1, 3)) {
Vehicle *v;
FOR_ALL_VEHICLES(v) SB(v->vehicle_flags, VF_TIMETABLE_SEPARATION, 1, _settings_game.order.old_timetable_separation);
}
/* Road stops is 'only' updating some caches */
AfterLoadRoadStops();
AfterLoadLabelMaps();
AfterLoadCompanyStats();
AfterLoadStoryBook();
GamelogPrintDebug(1);
InitializeWindowsAndCaches();
/* Restore the signals */
ResetSignalHandlers();
AfterLoadLinkGraphs();
AfterLoadTraceRestrict();
AfterLoadTemplateVehiclesUpdateImage();
/* Show this message last to avoid covering up an error message if we bail out part way */
switch (gcf_res) {
case GLC_COMPATIBLE: ShowErrorMessage(STR_NEWGRF_COMPATIBLE_LOAD_WARNING, INVALID_STRING_ID, WL_CRITICAL); break;
case GLC_NOT_FOUND: ShowErrorMessage(STR_NEWGRF_DISABLED_WARNING, INVALID_STRING_ID, WL_CRITICAL); _pause_mode = PM_PAUSED_ERROR; break;
default: break;
}
return true;
}
/**
* Reload all NewGRF files during a running game. This is a cut-down
* version of AfterLoadGame().
* XXX - We need to reset the vehicle position hash because with a non-empty
* hash AfterLoadVehicles() will loop infinitely. We need AfterLoadVehicles()
* to recalculate vehicle data as some NewGRF vehicle sets could have been
* removed or added and changed statistics
*/
void ReloadNewGRFData()
{
RailTypeLabel rail_type_label_map[RAILTYPE_END];
for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
rail_type_label_map[rt] = GetRailTypeInfo(rt)->label;
}
/* reload grf data */
GfxLoadSprites();
LoadStringWidthTable();
RecomputePrices();
/* reload vehicles */
ResetVehicleHash();
AfterLoadVehicles(false);
StartupEngines();
GroupStatistics::UpdateAfterLoad();
/* update station graphics */
AfterLoadStations();
/* Update company statistics. */
AfterLoadCompanyStats();
/* Check and update house and town values */
UpdateHousesAndTowns();
/* Delete news referring to no longer existing entities */
DeleteInvalidEngineNews();
/* Update livery selection windows */
for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) InvalidateWindowData(WC_COMPANY_COLOUR, i);
/* Update company infrastructure counts. */
InvalidateWindowClassesData(WC_COMPANY_INFRASTRUCTURE);
/* redraw the whole screen */
MarkWholeScreenDirty();
CheckTrainsLengths();
AfterLoadTemplateVehiclesUpdateImage();
RailType rail_type_translate_map[RAILTYPE_END];
for (RailType old_type = RAILTYPE_BEGIN; old_type != RAILTYPE_END; old_type++) {
RailType new_type = GetRailTypeByLabel(rail_type_label_map[old_type]);
rail_type_translate_map[old_type] = (new_type == INVALID_RAILTYPE) ? RAILTYPE_RAIL : new_type;
}
/* Restore correct railtype for all rail tiles.*/
const TileIndex map_size = MapSize();
for (TileIndex t = 0; t < map_size; t++) {
if (GetTileType(t) == MP_RAILWAY ||
IsLevelCrossingTile(t) ||
IsRailStationTile(t) ||
IsRailWaypointTile(t) ||
IsRailTunnelBridgeTile(t)) {
SetRailType(t, rail_type_translate_map[GetRailType(t)]);
}
}
}
| gpl-2.0 |
FxNion/elgg-custom-index-widgets | views/default/widgets/latest_wire_index/content.php | 360 | <?php
$num_items = $vars['entity']->num_items;
if (!isset($num_items)) $num_items = 10;
elgg_set_context('search');
$widget_datas = elgg_list_entities(array(
'type'=>'object',
'subtype'=>'thewire',
'limit'=>$num_items,
'full_view' => false,
'list_type_toggle' => false,
'pagination' => false));
echo $widget_datas;
?>
| gpl-2.0 |
maxiunlm/NoMeOlvides | NoMeOlvides/Domain/Hepler/ResultPackageBase.cs | 572 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Domain.Hepler
{
public abstract class ResultPackageBase
{
private ErrorsPackageContent errors;
public ErrorsPackageContent Errors { get
{
if(errors == null)
{
errors = new ErrorsPackageContent();
}
return errors;
}
set
{
errors = value;
}
}
}
}
| gpl-2.0 |
leoloso/PoP | layers/CMSSchema/packages/user-roles/src/FieldResolvers/ObjectType/RootRolesObjectTypeFieldResolver.php | 3050 | <?php
declare(strict_types=1);
namespace PoPCMSSchema\UserRoles\FieldResolvers\ObjectType;
use PoP\ComponentModel\FieldResolvers\ObjectType\AbstractObjectTypeFieldResolver;
use PoP\ComponentModel\Schema\SchemaTypeModifiers;
use PoP\ComponentModel\TypeResolvers\ObjectType\ObjectTypeResolverInterface;
use PoP\Engine\TypeResolvers\ObjectType\RootObjectTypeResolver;
use PoP\ComponentModel\TypeResolvers\ScalarType\StringScalarTypeResolver;
use PoPCMSSchema\UserRoles\TypeAPIs\UserRoleTypeAPIInterface;
class RootRolesObjectTypeFieldResolver extends AbstractObjectTypeFieldResolver
{
use RolesObjectTypeFieldResolverTrait;
private ?StringScalarTypeResolver $stringScalarTypeResolver = null;
private ?UserRoleTypeAPIInterface $userRoleTypeAPI = null;
final public function setStringScalarTypeResolver(StringScalarTypeResolver $stringScalarTypeResolver): void
{
$this->stringScalarTypeResolver = $stringScalarTypeResolver;
}
final protected function getStringScalarTypeResolver(): StringScalarTypeResolver
{
return $this->stringScalarTypeResolver ??= $this->instanceManager->getInstance(StringScalarTypeResolver::class);
}
final public function setUserRoleTypeAPI(UserRoleTypeAPIInterface $userRoleTypeAPI): void
{
$this->userRoleTypeAPI = $userRoleTypeAPI;
}
final protected function getUserRoleTypeAPI(): UserRoleTypeAPIInterface
{
return $this->userRoleTypeAPI ??= $this->instanceManager->getInstance(UserRoleTypeAPIInterface::class);
}
public function getObjectTypeResolverClassesToAttachTo(): array
{
return [
RootObjectTypeResolver::class,
];
}
public function getFieldTypeModifiers(ObjectTypeResolverInterface $objectTypeResolver, string $fieldName): int
{
return match ($fieldName) {
'roles',
'capabilities'
=> SchemaTypeModifiers::NON_NULLABLE
| SchemaTypeModifiers::IS_ARRAY
| SchemaTypeModifiers::IS_NON_NULLABLE_ITEMS_IN_ARRAY,
default
=> parent::getFieldTypeModifiers($objectTypeResolver, $fieldName),
};
}
/**
* @param array<string, mixed> $fieldArgs
* @param array<string, mixed>|null $variables
* @param array<string, mixed>|null $expressions
* @param array<string, mixed> $options
*/
public function resolveValue(
ObjectTypeResolverInterface $objectTypeResolver,
object $object,
string $fieldName,
array $fieldArgs,
?array $variables = null,
?array $expressions = null,
array $options = []
): mixed {
switch ($fieldName) {
case 'roles':
return $this->getUserRoleTypeAPI()->getRoleNames();
case 'capabilities':
return $this->getUserRoleTypeAPI()->getCapabilities();
}
return parent::resolveValue($objectTypeResolver, $object, $fieldName, $fieldArgs, $variables, $expressions, $options);
}
}
| gpl-2.0 |
vishwaAbhinav/OpenNMS | integrations/opennms-jasper-extensions/target/generated-sources/castor/org/opennms/netmgt/jasper/rrdtool/descriptors/RowDescriptor.java | 7699 | /*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.1.2.1</a>, using an XML
* Schema.
* $Id$
*/
package org.opennms.netmgt.jasper.rrdtool.descriptors;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import org.opennms.netmgt.jasper.rrdtool.Row;
/**
* Class RowDescriptor.
*
* @version $Revision$ $Date$
*/
@SuppressWarnings("all") public class RowDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _elementDefinition.
*/
private boolean _elementDefinition;
/**
* Field _nsPrefix.
*/
private java.lang.String _nsPrefix;
/**
* Field _nsURI.
*/
private java.lang.String _nsURI;
/**
* Field _xmlName.
*/
private java.lang.String _xmlName;
/**
* Field _identity.
*/
private org.exolab.castor.xml.XMLFieldDescriptor _identity;
//----------------/
//- Constructors -/
//----------------/
public RowDescriptor() {
super();
_nsURI = "http://xmlns.opennms.org/xsd/config/rrdtool-xport";
_xmlName = "row";
_elementDefinition = true;
//-- set grouping compositor
setCompositorAsSequence();
org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null;
org.exolab.castor.mapping.FieldHandler handler = null;
org.exolab.castor.xml.FieldValidator fieldValidator = null;
//-- initialize attribute descriptors
//-- initialize element descriptors
//-- _t
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.opennms.netmgt.jasper.rrdtool.T.class, "_t", "t", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
Row target = (Row) object;
return target.getT();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
Row target = (Row) object;
target.setT( (org.opennms.netmgt.jasper.rrdtool.T) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new org.opennms.netmgt.jasper.rrdtool.T();
}
};
desc.setSchemaType("org.opennms.netmgt.jasper.rrdtool.T");
desc.setHandler(handler);
desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/config/rrdtool-xport");
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _t
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
}
desc.setValidator(fieldValidator);
//-- _vList
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.opennms.netmgt.jasper.rrdtool.V.class, "_vList", "v", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
Row target = (Row) object;
return target.getV();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
Row target = (Row) object;
target.addV( (org.opennms.netmgt.jasper.rrdtool.V) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
public void resetValue(Object object) throws IllegalStateException, IllegalArgumentException {
try {
Row target = (Row) object;
target.removeAllV();
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new org.opennms.netmgt.jasper.rrdtool.V();
}
};
desc.setSchemaType("org.opennms.netmgt.jasper.rrdtool.V");
desc.setHandler(handler);
desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/config/rrdtool-xport");
desc.setRequired(true);
desc.setMultivalued(true);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _vList
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
}
desc.setValidator(fieldValidator);
}
//-----------/
//- Methods -/
//-----------/
/**
* Method getAccessMode.
*
* @return the access mode specified for this class.
*/
@Override()
public org.exolab.castor.mapping.AccessMode getAccessMode(
) {
return null;
}
/**
* Method getIdentity.
*
* @return the identity field, null if this class has no
* identity.
*/
@Override()
public org.exolab.castor.mapping.FieldDescriptor getIdentity(
) {
return _identity;
}
/**
* Method getJavaClass.
*
* @return the Java class represented by this descriptor.
*/
@Override()
public java.lang.Class<?> getJavaClass(
) {
return org.opennms.netmgt.jasper.rrdtool.Row.class;
}
/**
* Method getNameSpacePrefix.
*
* @return the namespace prefix to use when marshaling as XML.
*/
@Override()
public java.lang.String getNameSpacePrefix(
) {
return _nsPrefix;
}
/**
* Method getNameSpaceURI.
*
* @return the namespace URI used when marshaling and
* unmarshaling as XML.
*/
@Override()
public java.lang.String getNameSpaceURI(
) {
return _nsURI;
}
/**
* Method getValidator.
*
* @return a specific validator for the class described by this
* ClassDescriptor.
*/
@Override()
public org.exolab.castor.xml.TypeValidator getValidator(
) {
return this;
}
/**
* Method getXMLName.
*
* @return the XML Name for the Class being described.
*/
@Override()
public java.lang.String getXMLName(
) {
return _xmlName;
}
/**
* Method isElementDefinition.
*
* @return true if XML schema definition of this Class is that
* of a global
* element or element with anonymous type definition.
*/
public boolean isElementDefinition(
) {
return _elementDefinition;
}
}
| gpl-2.0 |
Jacksson/mywmsnb | lib/richfaces/examples/richfaces-showcase/src/test/integration/org/richfaces/showcase/togglePanel/ITestSimple.java | 2371 | /*******************************************************************************
* JBoss, Home of Professional Open Source
* Copyright 2010-2014, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*******************************************************************************/
package org.richfaces.showcase.togglePanel;
import static org.jboss.arquillian.graphene.Graphene.guardAjax;
import static org.junit.Assert.assertTrue;
import org.jboss.arquillian.graphene.page.Page;
import org.junit.Test;
import org.openqa.selenium.WebElement;
import org.richfaces.showcase.AbstractWebDriverTest;
import org.richfaces.showcase.togglePanel.page.SimplePage;
/**
* @author <a href="mailto:jhuska@redhat.com">Juraj Huska</a>
* @version $Revision$
*/
public class ITestSimple extends AbstractWebDriverTest {
private static final String CONTENT_OF_TAB1 = "For now you are at Panel 1";
private static final String CONTENT_OF_TAB2 = "For now you are at Panel 2";
@Page
private SimplePage page;
@Test
public void testTogglePanelItem1() {
checkToggleTab(page.getToggleTab1(), CONTENT_OF_TAB1);
}
@Test
public void testTogglePanelItem2() {
checkToggleTab(page.getToggleTab2(), CONTENT_OF_TAB2);
}
private void checkToggleTab(WebElement button, String expectedContent) {
guardAjax(button).click();
assertTrue("The content of panel is diferent!", page.getPanelContent().getText().contains(expectedContent));
}
}
| gpl-2.0 |
northfacts/City-Skylines-AdvancedRoadAnarchy | AdvancedRoadAnarchyOptionBox.cs | 5224 | using ColossalFramework.UI;
using UnityEngine;
namespace AdvancedRoadAnarchy
{
public class AdvancedRoadAnarchyOptionBox : UIPanel
{
private readonly float OptionBoxTitleHeight = 50f;
private UITextureAtlas OnOffAtlas = AdvancedRoadAnarchyButton.CreateAtlas("OnOffAtlas", 316, 82, "OnOff.png", new[] { "AnarchyOn", "AnarchyOff", });
private UICheckBox m_unlock;
private UICheckBox m_startonload;
private UICheckBox m_infotext;
private UICheckBox m_elevationlimits;
private UICheckBox m_checknodeheights;
private UICheckBox m_outside;
public override void Awake()
{
base.Awake();
this.opacity = 0.01f;
this.transform.parent = AdvancedRoadAnarchy.Settings.uiView.transform;
this.size = new Vector2(295f,235f);
this.backgroundSprite = "MenuPanel";
var title = this.AddUIComponent<UILabel>();
title.width = this.width;
title.height = OptionBoxTitleHeight;
title.text = "OPTIONS";
title.textAlignment = UIHorizontalAlignment.Center;
title.relativePosition = new Vector2((this.width / 2f) - (title.width / 2f), (OptionBoxTitleHeight / 2f) - (title.height / 2f));
var logo = this.AddUIComponent<UIButton>();
logo.size = new Vector2(OptionBoxTitleHeight -10f, OptionBoxTitleHeight -10f);
logo.relativePosition = new Vector2(2f, 2f);
logo.atlas = AdvancedRoadAnarchyButton.ButtonAtlas;
logo.normalBgSprite = "AnarchyLogo";
var d = new GameObject("AdvancedRoadAnarchyTitleDrag");
d.transform.parent = this.cachedTransform;
d.transform.localPosition = Vector2.zero;
var DragHandle = d.AddComponent<UIDragHandle>();
DragHandle.size = new Vector2(this.width, OptionBoxTitleHeight);
var close = this.AddUIComponent<UIButton>();
close.size = new Vector2(30f, 30f);
close.relativePosition = new Vector2(this.width - 2f - close.width, 2f);
close.normalBgSprite = "buttonclose";
close.hoveredBgSprite = "buttonclosehover";
close.pressedBgSprite = "buttonclosepressed";
this.playAudioEvents = true;
close.eventMouseDown += (component, param) =>
{
this.Hide();
};
float start = 2 + OptionBoxTitleHeight;
m_unlock = CreateCheckbox("UnlockButton", "Draggable", ref start);
m_unlock.eventVisibilityChanged += (c, s) =>
{
PlayClickSound(this);
if (!m_unlock.isVisible)
{
m_unlock.isChecked = false;
}
};
m_startonload = CreateCheckbox("StartOnLoad", "Enable mod by default", ref start);
m_infotext = CreateCheckbox("InfoText", "Enable info text", ref start);
m_elevationlimits = CreateCheckbox("ElevationLimits", "Elevation limits", ref start);
m_checknodeheights = CreateCheckbox("CheckNodeHeights", "Slope Limits", ref start);
m_outside = CreateCheckbox("CreateNode", "Enable outside map", ref start);
this.height = start + 6;
this.absolutePosition = new Vector2(0f, (AdvancedRoadAnarchy.Settings.Resolutions.height / 2) - (this.height / 2));
this.opacity = 1f;
}
private UICheckBox CreateCheckbox(string name, string label, ref float start)
{
UICheckBox checkbox = this.AddUIComponent<UICheckBox>();
checkbox.size = new Vector2(251f, 30f);
checkbox.relativePosition = new Vector2(22f, start + 4);
checkbox.clipChildren = true;
checkbox.name = name;
checkbox.label = checkbox.AddUIComponent<UILabel>();
checkbox.label.text = label;
checkbox.label.relativePosition = new Vector2(0f, 2f);
UISprite sprite = checkbox.AddUIComponent<UISprite>();
sprite.atlas = OnOffAtlas;
sprite.spriteName = "AnarchyOff";
sprite.size = new Vector2(54f, 30f);
sprite.relativePosition = new Vector2(checkbox.width - sprite.width, 0f);
checkbox.checkedBoxObject = sprite.AddUIComponent<UISprite>();
((UISprite)checkbox.checkedBoxObject).atlas = OnOffAtlas;
((UISprite)checkbox.checkedBoxObject).spriteName = "AnarchyOn";
checkbox.checkedBoxObject.size = new Vector2(54f, 30f);
checkbox.checkedBoxObject.relativePosition = Vector3.zero;
checkbox.eventCheckChanged += (c, s) =>
{
AdvancedRoadAnarchy.Settings.GetType().GetProperty(name).SetValue(AdvancedRoadAnarchy.Settings, s, null);
};
checkbox.eventMouseDown += (c, p) =>
{
PlayClickSound(this);
};
checkbox.isChecked = (bool)AdvancedRoadAnarchy.Settings.GetType().GetProperty(name).GetValue(AdvancedRoadAnarchy.Settings, null);
start += checkbox.height + 4;
return checkbox;
}
}
} | gpl-2.0 |
alideny/ChgMangos_CTM | src/server/scripts/EasternKingdoms/MoltenCore/boss_baron_geddon.cpp | 3985 | /*
* Copyright (C) 2011-2012 ArkCORE2 <http://www.arkania.net/>
* Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2012 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Boss_Baron_Geddon
SD%Complete: 100
SDComment:
SDCategory: Molten Core
EndScriptData */
#include "ObjectMgr.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "molten_core.h"
#define EMOTE_SERVICE -1409000
enum Spells
{
SPELL_INFERNO = 19695,
SPELL_IGNITE_MANA = 19659,
SPELL_LIVING_BOMB = 20475,
SPELL_ARMAGEDDON = 20479,
};
enum Events
{
EVENT_INFERNO = 1,
EVENT_IGNITE_MANA = 2,
EVENT_LIVING_BOMB = 3,
};
class boss_baron_geddon : public CreatureScript
{
public:
boss_baron_geddon() : CreatureScript("boss_baron_geddon") { }
struct boss_baron_geddonAI : public BossAI
{
boss_baron_geddonAI(Creature* creature) : BossAI(creature, BOSS_BARON_GEDDON) {}
void EnterCombat(Unit* victim)
{
BossAI::EnterCombat(victim);
events.ScheduleEvent(EVENT_INFERNO, 45000);
events.ScheduleEvent(EVENT_IGNITE_MANA, 30000);
events.ScheduleEvent(EVENT_LIVING_BOMB, 35000);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
// If we are <2% hp cast Armageddon
if (!HealthAbovePct(2))
{
me->InterruptNonMeleeSpells(true);
DoCast(me, SPELL_ARMAGEDDON);
DoScriptText(EMOTE_SERVICE, me);
return;
}
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_INFERNO:
DoCast(me, SPELL_INFERNO);
events.ScheduleEvent(EVENT_INFERNO, 45000);
break;
case EVENT_IGNITE_MANA:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true, -SPELL_IGNITE_MANA))
DoCast(target, SPELL_IGNITE_MANA);
events.ScheduleEvent(EVENT_IGNITE_MANA, 30000);
break;
case EVENT_LIVING_BOMB:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true))
DoCast(target, SPELL_LIVING_BOMB);
events.ScheduleEvent(EVENT_LIVING_BOMB, 35000);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new boss_baron_geddonAI (creature);
}
};
void AddSC_boss_baron_geddon()
{
new boss_baron_geddon();
} | gpl-2.0 |
saahil/MSSegmentation | model/msr_dataset.py | 4553 | import os
import numpy
import glob
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix, DefaultViewConverter
SHAPE = [55, 55, 10]
NSAMPLING = 8000
NIMAGES = 20
N = NIMAGES*NSAMPLING
NTRAIN = NSAMPLING*12
NTEST = NSAMPLING*4
class MSRDataset(DenseDesignMatrix):
def __init__(self, path_to_data='/home/ognawala/data/PatientMS-R/', which_set='train', start=None, stop=None, axes=('b', 0, 1, 'c'), preprocessor=None):
self.axes = axes
self.path_to_data = path_to_data
if which_set == 'train':
X, y = self._load_data(path_to_data, True)
if which_set == 'test':
X, y = self._load_test_data(path_to_data, True)
# define numbers
#if isinstance(y,list):
# y = numpy.asarray(y)
if start is not None:
assert start >= 0
assert stop > start
assert stop <= X.shape[0]
X = X[start:stop, :]
y = y[start:stop]
assert X.shape[0] == y.shape[0]
view_converter = DefaultViewConverter(shape=SHAPE, axes=axes)
super(MSRDataset,self).__init__(X=X, y=y, view_converter = view_converter)
assert not numpy.any(numpy.isnan(self.X))
if preprocessor:
preprocessor.apply(self)
def _load_data(self, path, expect_labels):
dtype = 'uint8'
ntrain = NTRAIN
ntest = NTEST
self.img_shape = SHAPE[::-1] #just reversing the dimensions
self.img_size = numpy.prod(self.img_shape)
self.n_classes = 2
x = numpy.zeros((ntrain+ntest, self.img_size), dtype=dtype)
y = numpy.zeros((ntrain+ntest,2), dtype=dtype)
for i,fl in enumerate(glob.glob(path+'*X.npy')):
temp_x = numpy.load(fl)
x[i*NSAMPLING:(i+1)*NSAMPLING, :] = temp_x
i = 0
for fl in glob.glob(path+'*Y.npy'):
temp_y = numpy.load(fl)
for cur_y in temp_y:
classes = [0, 0]
classes[cur_y] = 1
y[i] = classes
i += 1
# WRONG: y needs to be a column vector, instead of array
# y = y.reshape((ntrain+ntest,1))
Xs = {
'train' : x[0:ntrain],
'test' : x[ntrain:ntrain+ntest]
}
Ys = {
'train' : y[0:ntrain],
'test' : y[ntrain:ntrain+ntest]
}
X = numpy.cast['float32'](Xs['train'])
if expect_labels:
y = Ys['train']
# shuffle both X and y
rng_state = numpy.random.get_state()
numpy.random.shuffle(X)
numpy.random.set_state(rng_state)
numpy.random.shuffle(y)
#only using for debugging
#x_file = open('/home/ognawala/pylearn/trainingData/X.npy', 'w+')
#numpy.save(x_file, X)
#y_file = open('/home/ognawala/pylearn/trainingData/y.npy', 'w+')
#numpy.save(y_file, y)
return X, y
def _load_test_data(self, path, expect_labels):
dtype = 'uint8'
ntrain = NTRAIN
ntest = NTEST
self.img_shape = SHAPE[::-1]
self.img_size = numpy.prod(self.img_shape)
self.n_classes = 2
x = numpy.zeros((ntrain+ntest, self.img_size), dtype=dtype)
y = numpy.zeros((ntrain+ntest,2), dtype=dtype)
for i,fl in enumerate(glob.glob(path+'*X.npy')):
temp_x = numpy.load(fl)
x[i*NSAMPLING:(i+1)*NSAMPLING, :] = temp_x
i = 0
for fl in glob.glob(path+'*Y.npy'):
temp_y = numpy.load(fl)
for cur_y in temp_y:
classes = [0, 0]
classes[cur_y] = 1
y[i] = classes
i += 1
# WRONG: y needs to be a column vector, instead of array
# y = y.reshape((ntrain+ntest,1))
Xs = {
'train' : x[0:ntrain],
'test' : x[ntrain:ntrain+ntest]
}
Ys = {
'train' : y[0:ntrain],
'test' : y[ntrain:ntrain+ntest]
}
X = numpy.cast['float32'](Xs['test'])
if expect_labels:
y = Ys['test']
# shuffle both X and y
rng_state = numpy.random.get_state()
numpy.random.shuffle(X)
numpy.random.set_state(rng_state)
numpy.random.shuffle(y)
return X, y
def get_test_set(self):
return MSRDataset(path_to_data=self.path_to_data, which_set='test', axes=self.axes)
| gpl-2.0 |
bmerry/dg_view | src/dg_view_options.cpp | 4325 | /*
This file is part of Datagrind, a tool for tracking data accesses.
Copyright (C) 2010 Bruce Merry
bmerry@users.sourceforge.net
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307, USA.
The GNU General Public License is contained in the file COPYING.
*/
#include <vector>
#include <string>
#include <cstdlib>
#include <cassert>
#include <stdio.h>
#include <getopt.h>
#include "dg_view_options.h"
using namespace std;
void dg_view_usage(const char *prog, int code)
{
fprintf(stderr, "Usage: %s [-m] [--ranges=r1,...] [--events=e1,...] <file>\n", prog);
exit(code);
}
/* Splits a string to pieces on commas. Empty parts are preserved, but if
* s is empty then no strings are returned.
*/
static vector<string> split_comma(const string &s)
{
vector<string> out;
string::size_type pos = 0;
if (s.empty()) return out;
while (true)
{
string::size_type next = s.find(',', pos);
if (next == string::npos)
{
/* End of string - capture the last element */
out.push_back(s.substr(pos));
return out;
}
out.push_back(s.substr(pos, next - pos));
pos = next + 1;
}
}
static void condition_set_parse(dg_view_options::condition_set &cs, const vector<string> &tokens, uint32_t valid_flags)
{
for (vector<string>::const_iterator i = tokens.begin(); i != tokens.end(); ++i)
{
const string &s = *i;
if ((valid_flags & CONDITION_SET_FLAG_MALLOC) && s == "malloc")
cs.flags |= CONDITION_SET_FLAG_MALLOC;
else if ((valid_flags & CONDITION_SET_FLAG_RANGE) && s == "range")
cs.flags |= CONDITION_SET_FLAG_RANGE;
else if (s.substr(0, 3) == "fn:")
cs.functions.insert(s.substr(3));
else if (s.substr(0, 5) == "file:")
cs.files.insert(s.substr(5));
else if (s.substr(0, 4) == "dso:")
cs.dsos.insert(s.substr(4));
else if (s.substr(0, 5) == "user:")
cs.user.insert(s.substr(5));
else
{
fprintf(stderr, "Invalid condition `%s'\n", s.c_str());
exit(2);
}
}
}
void dg_view_options::parse_opts(int *argc, char **argv)
{
static const struct option longopts[] =
{
{ "ranges", 1, NULL, 'r' },
{ "events", 1, NULL, 'e' },
{ NULL, 0, NULL, 0 }
};
int opt;
event_conditions.flags = CONDITION_SET_FLAG_ANY;
block_conditions.flags = CONDITION_SET_FLAG_ANY;
while ((opt = getopt_long(*argc, argv, "r:e:", longopts, NULL)) != -1)
{
switch (opt)
{
case 'r':
{
vector<string> ranges = split_comma(optarg);
condition_set_parse(block_conditions, ranges, CONDITION_SET_FLAG_MALLOC | CONDITION_SET_FLAG_RANGE);
block_conditions.flags &= ~CONDITION_SET_FLAG_ANY;
}
break;
case 'e':
{
vector<string> events = split_comma(optarg);
condition_set_parse(event_conditions, events, 0);
event_conditions.flags &= ~CONDITION_SET_FLAG_ANY;
}
break;
case '?':
case ':':
exit(2);
default:
assert(0);
}
}
/* Remove options from argv */
for (int i = optind; i < *argc; i++)
argv[i - optind + 1] = argv[i];
*argc -= optind - 1;
}
const dg_view_options::condition_set &dg_view_options::get_event_conditions() const
{
return event_conditions;
}
const dg_view_options::condition_set &dg_view_options::get_block_conditions() const
{
return block_conditions;
}
| gpl-2.0 |
hddevteam/luckyci | Project/common/BL/ConfigController.cs | 5838 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Xml;
using System.Xml.Linq;
using common.DAO;
using common.DTO;
namespace common.BL
{
public class ConfigController
{
/// <summary>
/// 查询配置信息
/// </summary>
/// <param name="nodePath"></param>
/// <returns></returns>
public XmlNodeList FindConfigInfo(string nodePath,string xmlConfigPath)
{
XmlDao dao = new XmlDao();
return dao.XmlQuery(nodePath, xmlConfigPath);
}
/// <summary>
/// 执行保存已经修改的ConfigInfo
/// </summary>
/// <param name="configInfo">传入configInfo实例对象</param>
/// <param name="xmlConfigPath">修改的xml文件</param>
/// <returns></returns>
public string SaveConfig(ConfigInfo configInfo,string xmlConfigPath)
{
string modifyPath = "preferences";
string result = "";
var value = new Dictionary<string, string>();
value.Add("SvnPath",configInfo.Svnpath);
value.Add("UpdateInterval",configInfo.Updateinterval);
value.Add("StandarOutput",configInfo.StandarOutput);
value.Add("ServiceSwitch", configInfo.ServiceSwitch);
value.Add("ReportFrom",configInfo.ReportFrom);
value.Add("Password",configInfo.Password);
value.Add("MailHost",configInfo.SmtpServer);
value.Add("ReportTo",configInfo.ReportTo);
try
{
XmlDao xmlDao = new XmlDao();
XElement xElement = xmlDao.SelectOneXElement(null, xmlConfigPath, modifyPath);
result = xmlDao.ModifyXNode(value, xElement, xmlConfigPath);
return result;
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
result = "failed";
return result;
}
}
/// <summary>
/// 执行恢复默认配置的操作
/// </summary>
/// <returns>返回configInfo的实例对象</returns>
public ConfigInfo RestoreDefault()
{
ConfigInfo configInfo = new ConfigInfo();
configInfo.Updateinterval = "30";
configInfo.Svnpath = "C:\\Program Files\\TortoiseSVN\\bin\\svn.exe";
configInfo.StandarOutput = "true";
configInfo.ServiceSwitch = "window";
configInfo.ReportFrom = "Demo_From@gmail.com";
configInfo.Password = "123456";
configInfo.ReportTo = "Demo_To@gmail.com";
configInfo.SmtpServer = "smtp.gmail.com";
return configInfo;
}
/// <summary>
/// 查询配置信息
/// </summary>
/// <param name="dataPath">节点路径</param>
/// <param name="xmlConfigPath">查询的xml文件路径</param>
/// <returns></returns>
public ConfigInfo ConfigQuery(string dataPath,string xmlConfigPath)
{
ConfigInfo configInfo = new ConfigInfo();
XmlDao xmlDao = new XmlDao();
try
{
XmlNodeList xmlNodeList = xmlDao.XmlQuery(dataPath, xmlConfigPath);
configInfo.Svnpath = xmlNodeList[0].SelectSingleNode("SvnPath").InnerText;
configInfo.Updateinterval = xmlNodeList[0].SelectSingleNode("UpdateInterval").InnerText;
configInfo.StandarOutput = xmlNodeList[0].SelectSingleNode("StandarOutput").InnerText;
configInfo.ServiceSwitch = xmlNodeList[0].SelectSingleNode("ServiceSwitch").InnerText;
configInfo.ReportFrom = xmlNodeList[0].SelectSingleNode("ReportFrom").InnerText;
configInfo.ReportTo = xmlNodeList[0].SelectSingleNode("ReportTo").InnerText;
configInfo.Password = xmlNodeList[0].SelectSingleNode("Password").InnerText;
configInfo.SmtpServer = xmlNodeList[0].SelectSingleNode("MailHost").InnerText;
return configInfo;
}
catch (Exception)
{
return configInfo;
}
}
/// <summary>
/// 获取人名对应表
/// </summary>
/// <param name="nodePath">人名对应表节点路径</param>
/// <param name="xmlPath">存放对应表的xml文件路径</param>
/// <returns></returns>
public XmlNodeList AcquireSlackPeople(string nodePath, string xmlPath)
{
XmlDao dao = new XmlDao();
return dao.XmlQuery(nodePath, xmlPath);
}
/// <summary>
/// 获取gitlab信息
/// </summary>
/// <param name="dataPath">节点路径</param>
/// <param name="xmlConfigPath">xml路径</param>
/// <returns></returns>
public GitInfo GitInfoQuery(string dataPath, string xmlConfigPath)
{
GitInfo gitlabInfo = new GitInfo();
XmlDao xmlDao = new XmlDao();
try
{
XmlNodeList xmlNodeList = xmlDao.XmlQuery(dataPath, xmlConfigPath);
gitlabInfo.Username = xmlNodeList[0].SelectSingleNode("Username").InnerText;
gitlabInfo.Password = xmlNodeList[0].SelectSingleNode("Password").InnerText;
gitlabInfo.Emailaddress = xmlNodeList[0].SelectSingleNode("Email").InnerText;
gitlabInfo.Gitreversion = xmlNodeList[0].SelectSingleNode("GitReversion").InnerText;
return gitlabInfo;
}
catch (Exception)
{
return gitlabInfo;
}
}
}
}
| gpl-2.0 |
uwosh/uwosh.filariasis | uwosh/filariasis/tests/base.py | 3059 | from Products.Five import zcml
from Products.Five import fiveconfigure
from Testing import ZopeTestCase as ztc
from Products.PloneTestCase import PloneTestCase as ptc
from Products.PloneTestCase.layer import onsetup
from AccessControl import Unauthorized
from mechanize._mechanize import LinkNotFoundError
from smtplib import SMTPRecipientsRefused
from Products.validation import validation
from Products.CMFCore.utils import getToolByName
import uwosh.filariasis
import uwosh.pfg.d2c
@onsetup
def setup_uwosh_filariasis():
fiveconfigure.debug_mode = True
zcml.load_config('configure.zcml', uwosh.pfg.d2c)
zcml.load_config('configure.zcml', uwosh.filariasis)
fiveconfigure.debug_mode = False
ztc.installPackage('uwosh.pfg.d2c')
ztc.installPackage('uwosh.filariasis')
setup_uwosh_filariasis()
ptc.setupPloneSite()
class MockMailHost(object):
"""A mock mail host to avoid actually sending emails when testing."""
def getId(self):
return 'MailHost'
def send(self, message, mto=None, mfrom=None, subject=None, encode=None):
isEmail = validation.validatorFor('isEmail')
if (isEmail(mto) == 1):
return
else:
raise SMTPRecipientsRefused
def secureSend(self, message, mto=None, mfrom=None, subject=None, encode=None):
isEmail = validation.validatorFor('isEmail')
if (isEmail(mto) == 1):
return
else:
raise SMTPRecipientsRefused
class TestCase(ptc.PloneTestCase):
"""A base class for all the tests in this package."""
def afterSetUp(self):
self.portal.MailHost = MockMailHost()
installer = getToolByName(self.portal, 'portal_quickinstaller')
self.loginAsPortalOwner()
installer.installProduct('Products.PloneFormGen')
installer.installProduct('uwosh.pfg.d2c')
self.createFolders()
self.importForm()
print 'installing filariasis ...',
installer.installProduct('uwosh.filariasis')
print 'done'
#check to see order form folder exists
self.checkForOrderFormsFolder()
def becomeManager(self):
self.setRoles(['Authenticated', 'Member', 'Manager', 'Owner'])
def createFolders(self):
self.portal.invokeFactory('Folder', 'parasite-resources')
self.portal['parasite-resources'].invokeFactory('Folder', 'requisitionUpdate')
def importForm(self):
print ''
print 'importing form ...',
self.portal['parasite-resources']['requisitionUpdate'].manage_importObject('filarial-research-materials-parasite-division-requisition-form.zexp')
print 'done'
#also turns off maileradapter
def checkForOrderFormsFolder(self):
form = self.portal['parasite-resources']['requisitionUpdate']['filarial-research-materials-parasite-division-requisition-form']['order-forms']
form.setActionAdapter(('order-forms','parasite_requisition'))
class FunctionalTestCase(TestCase, ptc.FunctionalTestCase):
pass
| gpl-2.0 |
spixi/wesnoth | src/play_controller.cpp | 39536 | /*
Copyright (C) 2006 - 2018 by Joerg Hinrichs <joerg.hinrichs@alice-dsl.de>
wesnoth playlevel Copyright (C) 2003 by David White <dave@whitevine.net>
Part of the Battle for Wesnoth Project https://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* @file
* Handle input via mouse & keyboard, events, schedule commands.
*/
#include "play_controller.hpp"
#include "actions/create.hpp"
#include "actions/heal.hpp"
#include "actions/undo.hpp"
#include "actions/vision.hpp"
#include "ai/manager.hpp"
#include "ai/testing.hpp"
#include "preferences/credentials.hpp"
#include "display_chat_manager.hpp"
#include "formula/string_utils.hpp"
#include "game_events/menu_item.hpp"
#include "game_events/pump.hpp"
#include "preferences/game.hpp"
#include "game_state.hpp"
#include "hotkey/hotkey_item.hpp"
#include "hotkey/hotkey_handler.hpp"
#include "map/label.hpp"
#include "gettext.hpp"
#include "gui/dialogs/loading_screen.hpp"
#include "gui/dialogs/transient_message.hpp"
#include "hotkey/command_executor.hpp"
#include "log.hpp"
#include "pathfind/teleport.hpp"
#include "preferences/display.hpp"
#include "random.hpp"
#include "replay.hpp"
#include "reports.hpp"
#include "resources.hpp"
#include "savegame.hpp"
#include "saved_game.hpp"
#include "save_blocker.hpp"
#include "scripting/game_lua_kernel.hpp"
#include "scripting/plugins/context.hpp"
#include "sound.hpp"
#include "soundsource.hpp"
#include "statistics.hpp"
#include "synced_context.hpp"
#include "terrain/type_data.hpp"
#include "tooltips.hpp"
#include "units/unit.hpp"
#include "units/id.hpp"
#include "whiteboard/manager.hpp"
#include "utils/functional.hpp"
static lg::log_domain log_aitesting("aitesting");
#define LOG_AIT LOG_STREAM(info, log_aitesting)
//If necessary, this define can be replaced with `#define LOG_AIT std::cout` to restore previous behavior
static lg::log_domain log_engine("engine");
#define LOG_NG LOG_STREAM(info, log_engine)
#define DBG_NG LOG_STREAM(debug, log_engine)
static lg::log_domain log_display("display");
#define ERR_DP LOG_STREAM(err, log_display)
static lg::log_domain log_enginerefac("enginerefac");
#define LOG_RG LOG_STREAM(info, log_enginerefac)
static lg::log_domain log_engine_enemies("engine/enemies");
#define DBG_EE LOG_STREAM(debug, log_engine_enemies)
/**
* Copies [scenario] attributes/tags that are not otherwise stored in C++ structs/clases.
*/
static void copy_persistent(const config& src, config& dst)
{
static const std::set<std::string> attrs {
"description",
"name",
"victory_when_enemies_defeated",
"remove_from_carryover_on_defeat",
"disallow_recall",
"experience_modifier",
"require_scenario"};
static const std::set<std::string> tags {
"terrain_graphics",
"modify_unit_type",
"lua"};
for (const std::string& attr : attrs)
{
dst[attr] = src[attr];
}
for (const std::string& tag : tags)
{
dst.append_children(src, tag);
}
}
static void clear_resources()
{
resources::controller = nullptr;
resources::filter_con = nullptr;
resources::gameboard = nullptr;
resources::gamedata = nullptr;
resources::game_events = nullptr;
resources::lua_kernel = nullptr;
resources::persist = nullptr;
resources::soundsources = nullptr;
resources::tod_manager = nullptr;
resources::tunnels = nullptr;
resources::undo_stack = nullptr;
resources::recorder = nullptr;
resources::whiteboard.reset();
resources::classification = nullptr;
}
play_controller::play_controller(const config& level, saved_game& state_of_game,
const ter_data_cache& tdata, bool skip_replay)
: controller_base()
, observer()
, quit_confirmation()
, ticks_(SDL_GetTicks())
, tdata_(tdata)
, gamestate_()
, level_()
, saved_game_(state_of_game)
, tooltips_manager_()
, whiteboard_manager_()
, plugins_context_()
, labels_manager_()
, help_manager_(&game_config_)
, mouse_handler_(nullptr, *this)
, menu_handler_(nullptr, *this)
, hotkey_handler_(new hotkey_handler(*this, saved_game_))
, soundsources_manager_()
, persist_()
, gui_()
, xp_mod_(new unit_experience_accelerator(level["experience_modifier"].to_int(100)))
, statistics_context_(new statistics::scenario_context(level["name"]))
, replay_(new replay(state_of_game.get_replay()))
, skip_replay_(skip_replay)
, skip_story_(state_of_game.skip_story())
, linger_(false)
, init_side_done_now_(false)
, map_start_()
, victory_when_enemies_defeated_(level["victory_when_enemies_defeated"].to_bool(true))
, remove_from_carryover_on_defeat_(level["remove_from_carryover_on_defeat"].to_bool(true))
, victory_music_()
, defeat_music_()
, scope_()
, ignore_replay_errors_(false)
, player_type_changed_(false)
{
copy_persistent(level, level_);
for(const config& modify_unit_type : level_.child_range("modify_unit_type")) {
unit_types.apply_scenario_fix(modify_unit_type);
}
resources::controller = this;
resources::persist = &persist_;
resources::recorder = replay_.get();
resources::classification = &saved_game_.classification();
persist_.start_transaction();
game_config::add_color_info(level);
hotkey::deactivate_all_scopes();
hotkey::set_scope_active(hotkey::SCOPE_GAME);
try {
init(level);
} catch (...) {
clear_resources();
throw;
}
}
play_controller::~play_controller()
{
unit_types.remove_scenario_fixes();
hotkey::delete_all_wml_hotkeys();
clear_resources();
}
struct throw_end_level
{
void operator()(const config&) const
{
throw_quit_game_exception();
}
};
void play_controller::init(const config& level)
{
gui2::dialogs::loading_screen::display([this, &level]() {
gui2::dialogs::loading_screen::progress(loading_stage::load_level);
LOG_NG << "initializing game_state..." << (SDL_GetTicks() - ticks()) << std::endl;
gamestate_.reset(new game_state(level, *this, tdata_));
resources::gameboard = &gamestate().board_;
resources::gamedata = &gamestate().gamedata_;
resources::tod_manager = &gamestate().tod_manager_;
resources::filter_con = &gamestate();
resources::undo_stack = &undo_stack();
resources::game_events = gamestate().events_manager_.get();
resources::lua_kernel = gamestate().lua_kernel_.get();
gamestate_->ai_manager_.add_observer(this);
gamestate_->init(level, *this);
resources::tunnels = gamestate().pathfind_manager_.get();
LOG_NG << "initializing whiteboard..." << (SDL_GetTicks() - ticks()) << std::endl;
gui2::dialogs::loading_screen::progress(loading_stage::init_whiteboard);
whiteboard_manager_.reset(new wb::manager());
resources::whiteboard = whiteboard_manager_;
LOG_NG << "loading units..." << (SDL_GetTicks() - ticks()) << std::endl;
gui2::dialogs::loading_screen::progress(loading_stage::load_units);
preferences::encounter_all_content(gamestate().board_);
LOG_NG << "initializing theme... " << (SDL_GetTicks() - ticks()) << std::endl;
gui2::dialogs::loading_screen::progress(loading_stage::init_theme);
const config& theme_cfg = controller_base::get_theme(game_config_, theme());
LOG_NG << "building terrain rules... " << (SDL_GetTicks() - ticks()) << std::endl;
gui2::dialogs::loading_screen::progress(loading_stage::build_terrain);
gui_.reset(new game_display(gamestate().board_, whiteboard_manager_, *gamestate().reports_, theme_cfg, level));
map_start_ = map_location(level.child_or_empty("display").child_or_empty("location"));
if (!gui_->video().faked()) {
if (saved_game_.mp_settings().mp_countdown)
gui_->get_theme().modify_label("time-icon", _ ("time left for current turn"));
else
gui_->get_theme().modify_label("time-icon", _ ("current local time"));
}
gui2::dialogs::loading_screen::progress(loading_stage::init_display);
mouse_handler_.set_gui(gui_.get());
menu_handler_.set_gui(gui_.get());
LOG_NG << "done initializing display... " << (SDL_GetTicks() - ticks()) << std::endl;
LOG_NG << "building gamestate to gui and whiteboard... " << (SDL_GetTicks() - ticks()) << std::endl;
// This *needs* to be created before the show_intro and show_map_scene
// as that functions use the manager state_of_game
// Has to be done before registering any events!
gamestate().set_game_display(gui_.get());
gui2::dialogs::loading_screen::progress(loading_stage::init_lua);
if(gamestate().first_human_team_ != -1) {
gui_->set_team(gamestate().first_human_team_);
}
else if(is_observer()) {
// Find first team that is allowed to be observed.
// If not set here observer would be without fog until
// the first turn of observable side
for (const team& t : gamestate().board_.teams())
{
if (!t.get_disallow_observers())
{
gui_->set_team(t.side() - 1);
}
}
}
init_managers();
gui2::dialogs::loading_screen::progress(loading_stage::start_game);
//loadscreen_manager->reset();
gamestate().gamedata_.set_phase(game_data::PRELOAD);
gamestate().lua_kernel_->load_game(level);
plugins_context_.reset(new plugins_context("Game"));
plugins_context_->set_callback("save_game", [this](const config& cfg) { save_game_auto(cfg["filename"]); }, true);
plugins_context_->set_callback("save_replay", [this](const config& cfg) { save_replay_auto(cfg["filename"]); }, true);
plugins_context_->set_callback("quit", throw_end_level(), false);
plugins_context_->set_accessor_string("scenario_name", [this](config) { return get_scenario_name(); });
});
//Do this after the loadingscreen, so that ita happens in the main thread.
gui_->join();
}
void play_controller::reset_gamestate(const config& level, int replay_pos)
{
resources::gameboard = nullptr;
resources::gamedata = nullptr;
resources::tod_manager = nullptr;
resources::filter_con = nullptr;
resources::lua_kernel = nullptr;
resources::game_events = nullptr;
resources::tunnels = nullptr;
resources::undo_stack = nullptr;
gui_->labels().set_team(nullptr);
/* First destroy the old game state, then create the new one.
This is necessary to ensure that while the old AI manager is being destroyed,
all its member objects access the old manager instead of the new. */
gamestate_.reset();
gamestate_.reset(new game_state(level, *this, tdata_));
resources::gameboard = &gamestate().board_;
resources::gamedata = &gamestate().gamedata_;
resources::tod_manager = &gamestate().tod_manager_;
resources::filter_con = &gamestate();
resources::undo_stack = &undo_stack();
resources::game_events = gamestate().events_manager_.get();
resources::lua_kernel = gamestate().lua_kernel_.get();
gamestate_->ai_manager_.add_observer(this);
gamestate_->init(level, *this);
gamestate().set_game_display(gui_.get());
resources::tunnels = gamestate().pathfind_manager_.get();
gui_->reset_reports(*gamestate().reports_);
gui_->change_display_context(&gamestate().board_);
saved_game_.get_replay().set_pos(replay_pos);
gamestate().gamedata_.set_phase(game_data::PRELOAD);
gamestate().lua_kernel_->load_game(level);
}
void play_controller::init_managers()
{
LOG_NG << "initializing managers... " << (SDL_GetTicks() - ticks()) << std::endl;
preferences::set_preference_display_settings();
tooltips_manager_.reset(new tooltips::manager());
soundsources_manager_.reset(new soundsource::manager(*gui_));
resources::soundsources = soundsources_manager_.get();
LOG_NG << "done initializing managers... " << (SDL_GetTicks() - ticks()) << std::endl;
}
void play_controller::fire_preload()
{
// Run initialization scripts, even if loading from a snapshot.
gamestate().gamedata_.get_variable("turn_number") = static_cast<int>(turn());
pump().fire("preload");
}
void play_controller::fire_prestart()
{
// pre-start events must be executed before any GUI operation,
// as those may cause the display to be refreshed.
update_locker lock_display(gui_->video());
gamestate().gamedata_.set_phase(game_data::PRESTART);
// Fire these right before prestart events, to catch only the units sides
// have started with.
for (const unit& u : gamestate().board_.units()) {
pump().fire("unit_placed", map_location(u.get_location()));
}
pump().fire("prestart");
// prestart event may modify start turn with WML, reflect any changes.
gamestate().gamedata_.get_variable("turn_number") = static_cast<int>(turn());
}
void play_controller::refresh_objectives() const
{
const config cfg("side", gui_->viewing_side());
gamestate().lua_kernel_->run_wml_action("show_objectives", vconfig(cfg),
game_events::queued_event("_from_interface", "", map_location(), map_location(), config()));
}
void play_controller::fire_start()
{
gamestate().gamedata_.set_phase(game_data::START);
pump().fire("start");
skip_story_ = false; // Show [message]s from now on even with --campaign-skip-story
// start event may modify start turn with WML, reflect any changes.
gamestate().gamedata_.get_variable("turn_number") = static_cast<int>(turn());
refresh_objectives();
check_objectives();
// prestart and start events may modify the initial gold amount,
// reflect any changes.
for (team& tm : gamestate().board_.teams_)
{
tm.set_start_gold(tm.gold());
}
gamestate_->init_side_done() = false;
gamestate().gamedata_.set_phase(game_data::PLAY);
}
void play_controller::init_gui()
{
gui_->begin_game();
gui_->update_tod();
}
void play_controller::init_side_begin()
{
mouse_handler_.set_side(current_side());
// If we are observers we move to watch next team if it is allowed
if ((is_observer() && !current_team().get_disallow_observers())
|| (current_team().is_local_human() && !this->is_replay()))
{
update_gui_to_player(current_side() - 1);
}
gui_->set_playing_team(std::size_t(current_side() - 1));
gamestate().gamedata_.last_selected = map_location::null_location();
}
void play_controller::maybe_do_init_side()
{
//
// We do side init only if not done yet for a local side when we are not replaying.
// For all other sides it is recorded in replay and replay handler has to handle
// calling do_init_side() functions.
//
if (gamestate_->init_side_done()) {
// We already executed do_init_side this can for example happe if we reload a game,
// but also if we changed control of a side during it's turn
return;
}
if (!current_team().is_local()) {
// We are in a mp game and execute do_init_side as soon as we receive [init_side] from the current player
// (see replay.cpp)
return;
}
if (is_replay()) {
// We are in a replay and execute do_init_side as soon as we reach the next [init_side] in the replay data
// (see replay.cpp)
return;
}
if (current_team().is_idle()) {
// In this case it can happen that we just gave control of this side to another player so doing init_side
// could lead to errors since we no longer own this side from the servers perspective.
// (see playturn.cpp)
return;
}
resources::recorder->init_side();
do_init_side();
}
void play_controller::do_init_side()
{
set_scontext_synced sync;
log_scope("player turn");
// In case we might end up calling sync:network during the side turn events,
// and we don't want do_init_side to be called when a player drops.
gamestate_->init_side_done() = true;
init_side_done_now_ = true;
const std::string turn_num = std::to_string(turn());
const std::string side_num = std::to_string(current_side());
gamestate().gamedata_.get_variable("side_number") = current_side();
// We might have skipped some sides because they were empty so it is not enough to check for side_num==1
if(!gamestate().tod_manager_.has_turn_event_fired())
{
pump().fire("turn_" + turn_num);
pump().fire("new_turn");
gamestate().tod_manager_.turn_event_fired();
}
pump().fire("side_turn");
pump().fire("side_" + side_num + "_turn");
pump().fire("side_turn_" + turn_num);
pump().fire("side_" + side_num + "_turn_" + turn_num);
// We want to work out if units for this player should get healed,
// and the player should get income now.
// Healing/income happen if it's not the first turn of processing,
// or if we are loading a game.
if (turn() > 1) {
gamestate().board_.new_turn(current_side());
current_team().new_turn();
// If the expense is less than the number of villages owned
// times the village support capacity,
// then we don't have to pay anything at all
int expense = gamestate().board_.side_upkeep(current_side()) -
current_team().support();
if(expense > 0) {
current_team().spend_gold(expense);
}
}
if (do_healing()) {
calculate_healing(current_side(), !is_skipping_replay());
}
// Do healing on every side turn except the very first side turn.
// (1.14 and earlier did healing whenever turn >= 2.)
set_do_healing(true);
// Set resting now after the healing has been done.
for(unit &patient : resources::gameboard->units()) {
if(patient.side() == current_side()) {
patient.set_resting(true);
}
}
// Prepare the undo stack.
undo_stack().new_side_turn(current_side());
pump().fire("turn_refresh");
pump().fire("side_" + side_num + "_turn_refresh");
pump().fire("turn_" + turn_num + "_refresh");
pump().fire("side_" + side_num + "_turn_" + turn_num + "_refresh");
// Make sure vision is accurate.
actions::clear_shroud(current_side(), true);
init_side_end();
check_victory();
sync.do_final_checkup();
}
void play_controller::init_side_end()
{
const time_of_day& tod = gamestate().tod_manager_.get_time_of_day();
if (current_side() == 1 || !init_side_done_now_)
sound::play_sound(tod.sounds, sound::SOUND_SOURCES);
if (!is_skipping_replay()){
gui_->invalidate_all();
}
if (!is_skipping_replay() && current_team().get_scroll_to_leader() && !map_start_.valid()){
gui_->scroll_to_leader(current_side(), game_display::ONSCREEN,false);
}
map_start_ = map_location();
whiteboard_manager_->on_init_side();
}
config play_controller::to_config() const
{
config cfg = level_;
cfg["replay_pos"] = saved_game_.get_replay().get_pos();
gamestate().write(cfg);
gui_->write(cfg.add_child("display"));
//Write the soundsources.
soundsources_manager_->write_sourcespecs(cfg);
gui_->labels().write(cfg);
sound::write_music_play_list(cfg);
return cfg;
}
void play_controller::finish_side_turn()
{
whiteboard_manager_->on_finish_side_turn(current_side());
{ //Block for set_scontext_synced
set_scontext_synced sync(1);
// Ending the turn commits all moves.
undo_stack().clear();
gamestate().board_.end_turn(current_side());
const std::string turn_num = std::to_string(turn());
const std::string side_num = std::to_string(current_side());
// Clear shroud, in case units had been slowed for the turn.
actions::clear_shroud(current_side());
pump().fire("side_turn_end");
pump().fire("side_"+ side_num + "_turn_end");
pump().fire("side_turn_" + turn_num + "_end");
pump().fire("side_" + side_num + "_turn_" + turn_num + "_end");
// This is where we refog, after all of a side's events are done.
actions::recalculate_fog(current_side());
check_victory();
sync.do_final_checkup();
}
mouse_handler_.deselect_hex();
gamestate_->init_side_done() = false;
}
void play_controller::finish_turn()
{
set_scontext_synced sync(2);
const std::string turn_num = std::to_string(turn());
pump().fire("turn_end");
pump().fire("turn_" + turn_num + "_end");
sync.do_final_checkup();
}
bool play_controller::enemies_visible() const
{
// If we aren't using fog/shroud, this is easy :)
if(current_team().uses_fog() == false && current_team().uses_shroud() == false)
return true;
// See if any enemies are visible
for (const unit& u : gamestate().board_.units()) {
if (current_team().is_enemy(u.side()) && !gui_->fogged(u.get_location())) {
return true;
}
}
return false;
}
void play_controller::enter_textbox()
{
if(menu_handler_.get_textbox().active() == false) {
return;
}
const std::string str = menu_handler_.get_textbox().box()->text();
const unsigned int team_num = current_side();
events::mouse_handler& mousehandler = mouse_handler_;
switch(menu_handler_.get_textbox().mode()) {
case gui::TEXTBOX_SEARCH:
menu_handler_.do_search(str);
menu_handler_.get_textbox().close(*gui_);
break;
case gui::TEXTBOX_MESSAGE:
menu_handler_.do_speak();
menu_handler_.get_textbox().close(*gui_); //need to close that one after executing do_speak() !
break;
case gui::TEXTBOX_COMMAND:
menu_handler_.get_textbox().close(*gui_);
menu_handler_.do_command(str);
break;
case gui::TEXTBOX_AI:
menu_handler_.get_textbox().close(*gui_);
menu_handler_.do_ai_formula(str, team_num, mousehandler);
break;
default:
menu_handler_.get_textbox().close(*gui_);
ERR_DP << "unknown textbox mode" << std::endl;
}
}
void play_controller::tab()
{
gui::TEXTBOX_MODE mode = menu_handler_.get_textbox().mode();
std::set<std::string> dictionary;
switch(mode) {
case gui::TEXTBOX_SEARCH:
{
for (const unit& u : gamestate().board_.units()){
const map_location& loc = u.get_location();
if(!gui_->fogged(loc) &&
!(gamestate().board_.teams()[gui_->viewing_team()].is_enemy(u.side()) && u.invisible(loc)))
dictionary.insert(u.name());
}
//TODO List map labels
break;
}
case gui::TEXTBOX_COMMAND:
{
std::vector<std::string> commands = menu_handler_.get_commands_list();
dictionary.insert(commands.begin(), commands.end());
FALLTHROUGH; // we also want player names from the next case
}
case gui::TEXTBOX_MESSAGE:
{
for (const team& t : gamestate().board_.teams()) {
if(!t.is_empty())
dictionary.insert(t.current_player());
}
// Add observers
for (const std::string& o : gui_->observers()){
dictionary.insert(o);
}
// Add nicks who whispered you
for (const std::string& w : gui_->get_chat_manager().whisperers()){
dictionary.insert(w);
}
// Add nicks from friendlist
const std::map<std::string, std::string> friends = preferences::get_acquaintances_nice("friend");
for(std::map<std::string, std::string>::const_iterator iter = friends.begin(); iter != friends.end(); ++iter){
dictionary.insert((*iter).first);
}
//Exclude own nick from tab-completion.
//NOTE why ?
dictionary.erase(preferences::login());
break;
}
default:
ERR_DP << "unknown textbox mode" << std::endl;
} //switch(mode)
menu_handler_.get_textbox().tab(dictionary);
}
team& play_controller::current_team()
{
assert(gamestate().board_.has_team(current_side()));
return gamestate().board_.get_team(current_side());
}
const team& play_controller::current_team() const
{
assert(gamestate().board_.has_team(current_side()));
return gamestate().board_.get_team(current_side());
}
/// @returns: the number n in [min, min+mod ) so that (n - num) is a multiple of mod.
static int modulo(int num, int mod, int min)
{
assert(mod > 0);
int n = (num - min) % mod;
if (n < 0)
n += mod;
//n is now in [0, mod)
n = n + min;
return n;
// the following properties are easy to verify:
// 1) For all m: modulo(num, mod, min) == modulo(num + mod*m, mod, min)
// 2) For all 0 <= m < mod: modulo(min + m, mod, min) == min + m
}
bool play_controller::is_team_visible(int team_num, bool observer) const
{
const team& t = gamestate().board_.get_team(team_num);
if(observer) {
return !t.get_disallow_observers() && !t.is_empty();
}
else {
return t.is_local_human() && !t.is_idle();
}
}
int play_controller::find_last_visible_team() const
{
assert(current_side() <= static_cast<int>(gamestate().board_.teams().size()));
const int num_teams = gamestate().board_.teams().size();
const bool is_observer = this->is_observer();
for(int i = 0; i < num_teams; i++) {
const int team_num = modulo(current_side() - i, num_teams, 1);
if(is_team_visible(team_num, is_observer)) {
return team_num;
}
}
return 0;
}
events::mouse_handler& play_controller::get_mouse_handler_base()
{
return mouse_handler_;
}
std::shared_ptr<wb::manager> play_controller::get_whiteboard() const
{
return whiteboard_manager_;
}
const mp_game_settings& play_controller::get_mp_settings()
{
return saved_game_.mp_settings();
}
game_classification& play_controller::get_classification()
{
return saved_game_.classification();
}
game_display& play_controller::get_display()
{
return *gui_;
}
bool play_controller::have_keyboard_focus()
{
return !menu_handler_.get_textbox().active();
}
void play_controller::process_focus_keydown_event(const SDL_Event& event)
{
if(event.key.keysym.sym == SDLK_ESCAPE) {
menu_handler_.get_textbox().close(*gui_);
} else if(event.key.keysym.sym == SDLK_TAB) {
tab();
} else if(event.key.keysym.sym == SDLK_RETURN || event.key.keysym.sym == SDLK_KP_ENTER) {
enter_textbox();
}
}
void play_controller::process_keydown_event(const SDL_Event& event)
{
if (event.key.keysym.sym == SDLK_TAB) {
whiteboard_manager_->set_invert_behavior(true);
}
}
void play_controller::process_keyup_event(const SDL_Event& event)
{
// If the user has pressed 1 through 9, we want to show
// how far the unit can move in that many turns
if(event.key.keysym.sym >= '1' && event.key.keysym.sym <= '9') {
const int new_path_turns = (event.type == SDL_KEYDOWN) ?
event.key.keysym.sym - '1' : 0;
if(new_path_turns != mouse_handler_.get_path_turns()) {
mouse_handler_.set_path_turns(new_path_turns);
const unit_map::iterator u = mouse_handler_.selected_unit();
if(u.valid()) {
// if it's not the unit's turn, we reset its moves
unit_movement_resetter move_reset(*u, u->side() != current_side());
mouse_handler_.set_current_paths(pathfind::paths(*u, false,
true, gamestate().board_.teams_[gui_->viewing_team()],
mouse_handler_.get_path_turns()));
gui_->highlight_reach(mouse_handler_.current_paths());
} else {
mouse_handler_.select_hex(mouse_handler_.get_selected_hex(), false, false, false);
}
}
} else if (event.key.keysym.sym == SDLK_TAB) {
CKey keys;
if (!keys[SDLK_TAB]) {
whiteboard_manager_->set_invert_behavior(false);
}
}
}
replay& play_controller::get_replay() {
assert(replay_);
return *replay_.get();
}
void play_controller::save_game()
{
if(save_blocker::try_block()) {
// Saving while an event is running isn't supported
// because it may lead to expired event handlers being saved.
assert(!gamestate().events_manager_->is_event_running());
save_blocker::save_unblocker unblocker;
scoped_savegame_snapshot snapshot(*this);
savegame::ingame_savegame save(saved_game_, preferences::save_compression_format());
save.save_game_interactive("", savegame::savegame::OK_CANCEL);
} else {
save_blocker::on_unblock(this,&play_controller::save_game);
}
}
void play_controller::save_game_auto(const std::string& filename)
{
if(save_blocker::try_block()) {
save_blocker::save_unblocker unblocker;
scoped_savegame_snapshot snapshot(*this);
savegame::ingame_savegame save(saved_game_, preferences::save_compression_format());
save.save_game_automatic(false, filename);
}
}
void play_controller::save_replay()
{
if(save_blocker::try_block()) {
save_blocker::save_unblocker unblocker;
savegame::replay_savegame save(saved_game_, preferences::save_compression_format());
save.save_game_interactive("", savegame::savegame::OK_CANCEL);
} else {
save_blocker::on_unblock(this,&play_controller::save_replay);
}
}
void play_controller::save_replay_auto(const std::string& filename)
{
if(save_blocker::try_block()) {
save_blocker::save_unblocker unblocker;
savegame::replay_savegame save(saved_game_, preferences::save_compression_format());
save.save_game_automatic(false, filename);
}
}
void play_controller::save_map()
{
if(save_blocker::try_block()) {
save_blocker::save_unblocker unblocker;
menu_handler_.save_map();
} else {
save_blocker::on_unblock(this,&play_controller::save_map);
}
}
void play_controller::load_game()
{
savegame::loadgame load(game_config_, saved_game_);
load.load_game_ingame();
}
void play_controller::undo()
{
mouse_handler_.deselect_hex();
undo_stack().undo();
}
void play_controller::redo()
{
mouse_handler_.deselect_hex();
undo_stack().redo();
}
bool play_controller::can_undo() const
{
return !linger_ && !is_browsing() && !events::commands_disabled && undo_stack().can_undo();
}
bool play_controller::can_redo() const
{
return !linger_ && !is_browsing() && !events::commands_disabled && undo_stack().can_redo();
}
const std::string& play_controller::select_music(bool victory) const
{
const std::vector<std::string>& music_list = victory
? (gamestate_->get_game_data()->get_victory_music().empty() ? game_config::default_victory_music : gamestate_->get_game_data()->get_victory_music())
: (gamestate_->get_game_data()->get_defeat_music().empty() ? game_config::default_defeat_music : gamestate_->get_game_data()->get_defeat_music());
if(music_list.empty()) {
// Since this function returns a reference, we can't return a temporary empty string.
static const std::string empty_str = "";
return empty_str;
}
return music_list[randomness::rng::default_instance().get_random_int(0, music_list.size()-1)];
}
void play_controller::check_victory()
{
if(linger_)
{
return;
}
if (is_regular_game_end()) {
return;
}
bool continue_level, found_player, found_network_player, invalidate_all;
std::set<unsigned> not_defeated;
gamestate().board_.check_victory(continue_level, found_player, found_network_player, invalidate_all, not_defeated, remove_from_carryover_on_defeat_);
if (invalidate_all) {
gui_->invalidate_all();
}
if (continue_level) {
return ;
}
if (found_player || found_network_player) {
pump().fire("enemies_defeated");
if (is_regular_game_end()) {
return;
}
}
DBG_EE << "victory_when_enemies_defeated: " << victory_when_enemies_defeated_ << std::endl;
DBG_EE << "found_player: " << found_player << std::endl;
DBG_EE << "found_network_player: " << found_network_player << std::endl;
if (!victory_when_enemies_defeated_ && (found_player || found_network_player)) {
// This level has asked not to be ended by this condition.
return;
}
if (gui_->video().non_interactive()) {
LOG_AIT << "winner: ";
for (unsigned l : not_defeated) {
std::string ai = ai::manager::get_singleton().get_active_ai_identifier_for_side(l);
if (ai.empty()) ai = "default ai";
LOG_AIT << l << " (using " << ai << ") ";
}
LOG_AIT << std::endl;
ai_testing::log_victory(not_defeated);
}
DBG_EE << "throwing end level exception..." << std::endl;
//Also proceed to the next scenario when another player survived.
end_level_data el_data;
el_data.proceed_to_next_level = found_player || found_network_player;
el_data.is_victory = found_player;
set_end_level_data(el_data);
}
void play_controller::process_oos(const std::string& msg) const
{
if (gui_->video().non_interactive()) {
throw game::game_error(msg);
}
if (game_config::ignore_replay_errors) return;
std::stringstream message;
message << _("The game is out of sync. It might not make much sense to continue. Do you want to save your game?");
message << "\n\n" << _("Error details:") << "\n\n" << msg;
scoped_savegame_snapshot snapshot(*this);
savegame::oos_savegame save(saved_game_, ignore_replay_errors_);
save.save_game_interactive(message.str(), savegame::savegame::YES_NO); // can throw quit_game_exception
}
void play_controller::update_gui_to_player(const int team_index, const bool observe)
{
gui_->set_team(team_index, observe);
gui_->recalculate_minimap();
gui_->invalidate_all();
}
void play_controller::do_autosave()
{
scoped_savegame_snapshot snapshot(*this);
savegame::autosave_savegame save(saved_game_, preferences::save_compression_format());
save.autosave(false, preferences::autosavemax(), preferences::INFINITE_AUTO_SAVES);
}
void play_controller::do_consolesave(const std::string& filename)
{
scoped_savegame_snapshot snapshot(*this);
savegame::ingame_savegame save(saved_game_, preferences::save_compression_format());
save.save_game_automatic(true, filename);
}
void play_controller::update_savegame_snapshot() const
{
//note: this writes to level_ if this is not a replay.
this->saved_game_.set_snapshot(to_config());
}
game_events::wml_event_pump& play_controller::pump()
{
return gamestate().events_manager_->pump();
}
int play_controller::get_ticks() const
{
return ticks_;
}
soundsource::manager* play_controller::get_soundsource_man()
{
return soundsources_manager_.get();
}
plugins_context* play_controller::get_plugins_context()
{
return plugins_context_.get();
}
hotkey::command_executor* play_controller::get_hotkey_command_executor()
{
return hotkey_handler_.get();
}
bool play_controller::is_browsing() const
{
if(linger_ || !gamestate_->init_side_done() || gamestate().gamedata_.phase() != game_data::PLAY) {
return true;
}
const team& t = current_team();
return !t.is_local_human() || !t.is_proxy_human();
}
void play_controller::play_slice_catch()
{
if(should_return_to_play_side()) {
return;
}
try
{
play_slice();
}
catch(const return_to_play_side_exception&)
{
assert(should_return_to_play_side());
}
}
void play_controller::start_game()
{
fire_preload();
if(!gamestate().start_event_fired_)
{
gamestate().start_event_fired_ = true;
map_start_ = map_location();
resources::recorder->add_start_if_not_there_yet();
resources::recorder->get_next_action();
set_scontext_synced sync;
fire_prestart();
if (is_regular_game_end()) {
return;
}
for (const team& t : gamestate().board_.teams()) {
actions::clear_shroud(t.side(), false, false);
}
init_gui();
LOG_NG << "first_time..." << (is_skipping_replay() ? "skipping" : "no skip") << "\n";
fire_start();
if (is_regular_game_end()) {
return;
}
sync.do_final_checkup();
gui_->recalculate_minimap();
// Initialize countdown clock.
for (const team& t : gamestate().board_.teams())
{
if (saved_game_.mp_settings().mp_countdown) {
t.set_countdown_time(1000 * saved_game_.mp_settings().mp_countdown_init_time);
}
}
}
else
{
init_gui();
gamestate().gamedata_.set_phase(game_data::PLAY);
gui_->recalculate_minimap();
}
}
bool play_controller::can_use_synced_wml_menu() const
{
const team& viewing_team = get_teams_const()[gui_->viewing_team()];
return gui_->viewing_team() == gui_->playing_team() && !events::commands_disabled && viewing_team.is_local_human() && !is_lingering() && !is_browsing();
}
std::set<std::string> play_controller::all_players() const
{
std::set<std::string> res = gui_->observers();
for (const team& t : get_teams_const())
{
if (t.is_human()) {
res.insert(t.current_player());
}
}
return res;
}
void play_controller::play_side()
{
//check for team-specific items in the scenario
gui_->parse_team_overlays();
do {
update_viewing_player();
{
save_blocker blocker;
maybe_do_init_side();
if(is_regular_game_end()) {
return;
}
}
// This flag can be set by derived classes (in overridden functions).
player_type_changed_ = false;
statistics::reset_turn_stats(gamestate().board_.get_team(current_side()).save_id_or_number());
play_side_impl();
if(is_regular_game_end()) {
return;
}
} while (player_type_changed_);
// Keep looping if the type of a team (human/ai/networked)
// has changed mid-turn
sync_end_turn();
}
void play_controller::play_turn()
{
whiteboard_manager_->on_gamestate_change();
gui_->new_turn();
gui_->invalidate_game_status();
LOG_NG << "turn: " << turn() << "\n";
if(gui_->video().non_interactive()) {
LOG_AIT << "Turn " << turn() << ":" << std::endl;
}
int last_player_number = gamestate_->player_number_;
int next_player_number = gamestate_->next_player_number_;
while(gamestate_->player_number_ <= static_cast<int>(gamestate().board_.teams().size())) {
gamestate_->next_player_number_ = gamestate_->player_number_ + 1;
next_player_number = gamestate_->next_player_number_;
last_player_number = gamestate_->player_number_;
// If a side is empty skip over it.
if (!current_team().is_empty()) {
init_side_begin();
if(gamestate_->init_side_done()) {
// This is the case in a reloaded game where the side was initialized before saving the game.
init_side_end();
}
ai_testing::log_turn_start(current_side());
play_side();
//ignore any changes to next_player_number_ that happen after the [end_turn] is sended to the server, otherwise we will get OOS.
next_player_number = gamestate_->next_player_number_;
assert(next_player_number <= 2 * static_cast<int>(gamestate().board_.teams().size()));
if(is_regular_game_end()) {
return;
}
//note: play_side() send the [end_turn] to the sever and finish_side_turn() callsie the side turn end events.
// this means that during the side turn end events the clients think it is still the last sides turn while
// the server thinks that it is already the next plyers turn. i don'T think this is a problem though.
finish_side_turn();
if(is_regular_game_end()) {
return;
}
if(gui_->video().non_interactive()) {
LOG_AIT << " Player " << current_side() << ": " <<
current_team().villages().size() << " Villages" <<
std::endl;
ai_testing::log_turn_end(current_side());
}
}
gamestate_->player_number_ = next_player_number;
}
// If the loop exits due to the last team having been processed.
gamestate_->player_number_ = last_player_number;
finish_turn();
// Time has run out
check_time_over();
if (!is_regular_game_end()) {
gamestate_->player_number_ = modulo(next_player_number, gamestate().board_.teams().size(), 1);
}
}
void play_controller::check_time_over()
{
const bool time_left = gamestate().tod_manager_.next_turn(&gamestate().gamedata_);
if(!time_left) {
LOG_NG << "firing time over event...\n";
set_scontext_synced_base sync;
pump().fire("time_over");
LOG_NG << "done firing time over event...\n";
// If turns are added while handling 'time over' event.
if (gamestate().tod_manager_.is_time_left()) {
return;
}
if(gui_->video().non_interactive()) {
LOG_AIT << "time over (draw)\n";
ai_testing::log_draw();
}
check_victory();
if (is_regular_game_end()) {
return;
}
end_level_data e;
e.proceed_to_next_level = false;
e.is_victory = false;
set_end_level_data(e);
}
}
play_controller::scoped_savegame_snapshot::scoped_savegame_snapshot(const play_controller& controller)
: controller_(controller)
{
controller_.update_savegame_snapshot();
}
play_controller::scoped_savegame_snapshot::~scoped_savegame_snapshot()
{
controller_.saved_game_.remove_snapshot();
}
void play_controller::show_objectives() const
{
const team& t = gamestate().board_.teams()[gui_->viewing_team()];
static const std::string no_objectives(_("No objectives available"));
std::string objectives = utils::interpolate_variables_into_string(t.objectives(), *gamestate_->get_game_data());
gui2::show_transient_message(get_scenario_name(), (objectives.empty() ? no_objectives : objectives), "", true);
t.reset_objectives_changed();
}
void play_controller::toggle_skipping_replay()
{
skip_replay_ = !skip_replay_;
const std::shared_ptr<gui::button> skip_animation_button = get_display().find_action_button("skip-animation");
if (skip_animation_button) {
skip_animation_button->set_check(skip_replay_);
}
}
| gpl-2.0 |
sunnycase/MPF | src/MPF.Core/Interop/INativeWindow.cs | 1091 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace MPF.Interop
{
[ComImport]
[Guid("12DCA941-A675-4A79-81E0-2378753D6DAF")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface INativeWindowCallback
{
void OnClosing();
void OnLocationChanged(Point location);
void OnSizeChanged(Size size);
}
[ComImport]
[Guid("2705FA1D-68BA-4E2B-92D4-846AE0A8D208")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface INativeWindow
{
bool HasMaximize { [return: MarshalAs(UnmanagedType.Bool)]get; [param: MarshalAs(UnmanagedType.Bool)]set; }
string Title { [return: MarshalAs(UnmanagedType.BStr)]get; [param: MarshalAs(UnmanagedType.BStr)]set; }
IntPtr NativeHandle { get; }
Point Location { get; set; }
Size Size { get; set; }
Size ClientSize { get; }
void Show();
void Hide();
void Close();
void Destroy();
}
}
| gpl-2.0 |
angelblue05/Embytest.Kodi | contextmenu.py | 6951 | # -*- coding: utf-8 -*-
#################################################################################################
import os
import sys
import urlparse
import xbmc
import xbmcaddon
import xbmcgui
addon_ = xbmcaddon.Addon(id='plugin.video.emby')
addon_path = addon_.getAddonInfo('path').decode('utf-8')
base_resource = xbmc.translatePath(os.path.join(addon_path, 'resources', 'lib')).decode('utf-8')
sys.path.append(base_resource)
import artwork
import utils
import clientinfo
import downloadutils
import librarysync
import read_embyserver as embyserver
import embydb_functions as embydb
import kodidb_functions as kodidb
import musicutils as musicutils
import api
def logMsg(msg, lvl=1):
utils.logMsg("%s %s" % ("EMBY", "Contextmenu"), msg, lvl)
#Kodi contextmenu item to configure the emby settings
#for now used to set ratings but can later be used to sync individual items etc.
if __name__ == '__main__':
itemid = xbmc.getInfoLabel("ListItem.DBID").decode("utf-8")
itemtype = xbmc.getInfoLabel("ListItem.DBTYPE").decode("utf-8")
emby = embyserver.Read_EmbyServer()
embyid = ""
if not itemtype and xbmc.getCondVisibility("Container.Content(albums)"): itemtype = "album"
if not itemtype and xbmc.getCondVisibility("Container.Content(artists)"): itemtype = "artist"
if not itemtype and xbmc.getCondVisibility("Container.Content(songs)"): itemtype = "song"
if not itemtype and xbmc.getCondVisibility("Container.Content(pictures)"): itemtype = "picture"
if (not itemid or itemid == "-1") and xbmc.getInfoLabel("ListItem.Property(embyid)"):
embyid = xbmc.getInfoLabel("ListItem.Property(embyid)")
else:
embyconn = utils.kodiSQL('emby')
embycursor = embyconn.cursor()
emby_db = embydb.Embydb_Functions(embycursor)
item = emby_db.getItem_byKodiId(itemid, itemtype)
embycursor.close()
if item: embyid = item[0]
logMsg("Contextmenu opened for embyid: %s - itemtype: %s" %(embyid,itemtype))
if embyid:
item = emby.getItem(embyid)
API = api.API(item)
userdata = API.getUserData()
likes = userdata['Likes']
favourite = userdata['Favorite']
options=[]
if likes == True:
#clear like for the item
options.append(utils.language(30402))
if likes == False or likes == None:
#Like the item
options.append(utils.language(30403))
if likes == True or likes == None:
#Dislike the item
options.append(utils.language(30404))
if favourite == False:
#Add to emby favourites
options.append(utils.language(30405))
if favourite == True:
#Remove from emby favourites
options.append(utils.language(30406))
if itemtype == "song":
#Set custom song rating
options.append(utils.language(30407))
#delete item
options.append(utils.language(30409))
#addon settings
options.append(utils.language(30408))
#display select dialog and process results
header = utils.language(30401)
ret = xbmcgui.Dialog().select(header, options)
if ret != -1:
if options[ret] == utils.language(30402):
emby.updateUserRating(embyid, deletelike=True)
if options[ret] == utils.language(30403):
emby.updateUserRating(embyid, like=True)
if options[ret] == utils.language(30404):
emby.updateUserRating(embyid, like=False)
if options[ret] == utils.language(30405):
emby.updateUserRating(embyid, favourite=True)
if options[ret] == utils.language(30406):
emby.updateUserRating(embyid, favourite=False)
if options[ret] == utils.language(30407):
kodiconn = utils.kodiSQL('music')
kodicursor = kodiconn.cursor()
query = ' '.join(("SELECT rating", "FROM song", "WHERE idSong = ?" ))
kodicursor.execute(query, (itemid,))
currentvalue = int(round(float(kodicursor.fetchone()[0]),0))
newvalue = xbmcgui.Dialog().numeric(0, "Set custom song rating (0-5)", str(currentvalue))
if newvalue:
newvalue = int(newvalue)
if newvalue > 5: newvalue = "5"
if utils.settings('enableUpdateSongRating') == "true":
musicutils.updateRatingToFile(newvalue, API.getFilePath())
if utils.settings('enableExportSongRating') == "true":
like, favourite, deletelike = musicutils.getEmbyRatingFromKodiRating(newvalue)
emby.updateUserRating(embyid, like, favourite, deletelike)
query = ' '.join(( "UPDATE song","SET rating = ?", "WHERE idSong = ?" ))
kodicursor.execute(query, (newvalue,itemid,))
kodiconn.commit()
if options[ret] == utils.language(30408):
#Open addon settings
xbmc.executebuiltin("Addon.OpenSettings(plugin.video.emby)")
if options[ret] == utils.language(30409):
#delete item from the server
delete = True
if utils.settings('skipContextMenu') != "true":
resp = xbmcgui.Dialog().yesno(
heading="Confirm delete",
line1=("Delete file from Emby Server? This will "
"also delete the file(s) from disk!"))
if not resp:
logMsg("User skipped deletion for: %s." % embyid, 1)
delete = False
if delete:
import downloadutils
doUtils = downloadutils.DownloadUtils()
url = "{server}/emby/Items/%s?format=json" % embyid
logMsg("Deleting request: %s" % embyid, 0)
doUtils.downloadUrl(url, type="DELETE")
'''if utils.settings('skipContextMenu') != "true":
if xbmcgui.Dialog().yesno(
heading="Confirm delete",
line1=("Delete file on Emby Server? This will "
"also delete the file(s) from disk!")):
import downloadutils
doUtils = downloadutils.DownloadUtils()
url = "{server}/emby/Items/%s?format=json" % embyid
doUtils.downloadUrl(url, type="DELETE")'''
xbmc.sleep(500)
xbmc.executebuiltin("Container.Update") | gpl-2.0 |
radiowarwick/digiplay_legacy | src/www/DPS/models/DPSStationMoveJingleModel.class.php | 2391 | <?php
/**
* @package DPS
*/
include_once($cfg['DBAL']['dir']['root'] . '/Database.class.php');
include_once($cfg['MVC']['dir']['root'] . '/MVCUtils.class.php');
MVCUtils::includeModel('Model', 'tkfecommon');
class DPSStationMoveJingleModel extends Model {
const module = 'DPS';
protected function processValid() {
global $cfg;
$db = Database::getInstance($cfg['DPS']['dsn']);
$auth = Auth::getInstance();
$userID = $auth->getUserID();
if ($this->formName == "dpsStationMoveJingleForm") {
$jingleID = pg_escape_string($this->fieldData['jingleID']);
$jinglepkgID = pg_escape_string($this->fieldData['jinglepkgID']);
if(AuthUtil::getDetailedUserrealmAccess(array(35,22,3), $userID)) {
$sql = "SELECT jinglepkgid FROM audiojinglepkgs WHERE audioid = $jingleID";
$oldjinglepkgID = $db->getOne($sql);
if (($jinglepkgID == $oldjinglepkgID) && ($this->fieldData['newPackageName'] == '')) {
return;
}
$sql = "SELECT id FROM audiojinglepkgs WHERE audioid = $jingleID AND jinglepkgid = $oldjinglepkgID";
$rowID = $db->getOne($sql);
if ($rowID != 0) {
$Where = "id = $rowID";
$db->delete('audiojinglepkgs',$Where,true);
}
$sql = "SELECT COUNT(*) from audiojinglepkgs WHERE jinglepkgid = $oldjinglepkgID";
$remainingjingles = $db->getOne($sql);
if ($remainingjingles == 0) {
$Where = "id = ". $oldjinglepkgID;
$db->delete('jinglepkgs',$Where,true);
}
if($this->fieldData['newPackageName'] != '') {
$jinglePkgName = pg_escape_string($this->fieldData['newPackageName']);
$sql = "SELECT id FROM jinglepkgs WHERE name = '$jinglePkgName'";
$numRows = count($db->getAll($sql));
if($numRows != 0) {
$jinglepkgID = $db->getOne($sql);
} else {
$newjinglepkg['name'] = $jinglePkgName;
$newjinglepkg['description'] = pg_escape_string($this->fieldData['newPackageDesc']);
$newjinglepkg['enabled'] = 'f';
$db->insert('jinglepkgs',$newjinglepkg,true);
$sql = "SELECT id FROM jinglepkgs WHERE name = '$jinglePkgName'";
$jinglepkgID = $db->getOne($sql);
}
}
$newpkg['audioid'] = $jingleID;
$newpkg['jinglepkgid'] = $jinglepkgID;
$newpkg['jingletypeid'] = 1;
$db->insert('audiojinglepkgs',$newpkg,true);
}
}
}
protected function processInvalid() {
//No invalid processing required
}
}
?>
| gpl-2.0 |
netgen/NetgenInformationCollectionBundle | tests/old/FieldHandler/FieldHandlerRegistryTest.php | 2179 | <?php
namespace Netgen\Bundle\InformationCollectionBundle\Tests\FieldHandler;
use eZ\Publish\Core\FieldType\Integer\Value as TestValue;
use Netgen\Bundle\InformationCollectionBundle\FieldHandler\Custom\CustomFieldHandlerInterface;
use Netgen\Bundle\InformationCollectionBundle\FieldHandler\FieldHandlerRegistry;
use PHPUnit\Framework\TestCase;
class FieldHandlerRegistryTest extends TestCase
{
/**
* @var FieldHandlerRegistry
*/
protected $registry;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $customHandler1;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $customHandler2;
public function setUp()
{
$this->registry = new FieldHandlerRegistry();
$this->customHandler1 = $this->getMockBuilder(CustomFieldHandlerInterface::class)
->disableOriginalConstructor()
->setMethods(array('supports', 'toString'))
->getMock();
$this->customHandler2 = $this->getMockBuilder(CustomFieldHandlerInterface::class)
->disableOriginalConstructor()
->setMethods(array('supports', 'toString'))
->getMock();
parent::setUp();
}
public function testAddingHandlers()
{
$this->registry->addHandler($this->customHandler1);
$this->registry->addHandler($this->customHandler2);
}
public function testItReturnsProperHandler()
{
$value = new TestValue(2);
$this->registry->addHandler($this->customHandler1);
$this->registry->addHandler($this->customHandler2);
$this->customHandler1->expects($this->once())
->method('supports')
->willReturn(false);
$this->customHandler2->expects($this->once())
->method('supports')
->willReturn(true);
$handler = $this->registry->handle($value);
$this->assertSame($this->customHandler2, $handler);
}
public function testItReturnsNullWhenSupportedHandlerNotFound()
{
$value = new TestValue(2);
$handler = $this->registry->handle($value);
$this->assertNull($handler);
}
}
| gpl-2.0 |
bringert/plan | src/primitives/Eq.java | 956 | /* Copyright (C) 2003 Bjorn Bringert (bjorn@bringert.net)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package primitives;
import env.*;
public class Eq extends ComparisonPrimitive {
public Eq () {
super("=");
}
public boolean test (int comp) {
return comp == 0;
}
}
| gpl-2.0 |
dwagon/Scheduler | scheduler/report/urls.py | 735 | from django.conf.urls import patterns, url
from .reports import reportIndex, displayMonth, displayYear
from .reports import displayDay, exportData, clientReport
urlpatterns = patterns(
'',
url(r'^$', reportIndex, name='reportIndex'),
url(r"^month/(\d+)/(\d+)/$", displayMonth, name='displayYearMonth'),
url(r"^month/(\d+)/$", displayMonth),
url(r"^month$", displayMonth, name='displayThisMonth'),
url(r"^year/$", displayYear, name='displayYear'),
url(r"^year/(?P<year>\d+)$", displayYear, name='displayYear'),
url(r"^day/(\d+)/(\d+)/(\d+)/$", displayDay, name='displayDay'),
url(r'^exportData$', exportData, name='exportData'),
url(r'^client$', clientReport, name='clientReport'),
)
# EOF
| gpl-2.0 |
OasisProject/WebVR-Template | node_modules/webvr-polyfill/gyro-position-sensor-vr-device.js | 3173 | /*
* Copyright 2015 Boris Smus. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var PositionSensorVRDevice = require('./base.js').PositionSensorVRDevice;
var THREE = require('./three-math.js');
/**
* The positional sensor, implemented using web DeviceOrientation APIs.
*/
function GyroPositionSensorVRDevice() {
// Subscribe to deviceorientation events.
window.addEventListener('deviceorientation', this.onDeviceOrientationChange.bind(this));
window.addEventListener('orientationchange', this.onScreenOrientationChange.bind(this));
this.deviceOrientation = null;
this.screenOrientation = window.orientation;
// Helper objects for calculating orientation.
this.finalQuaternion = new THREE.Quaternion();
this.deviceEuler = new THREE.Euler();
this.screenTransform = new THREE.Quaternion();
// -PI/2 around the x-axis.
this.worldTransform = new THREE.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
}
GyroPositionSensorVRDevice.prototype = new PositionSensorVRDevice();
/**
* Returns {orientation: {x,y,z,w}, position: null}.
* Position is not supported since we can't do 6DOF.
*/
GyroPositionSensorVRDevice.prototype.getState = function() {
return {
orientation: this.getOrientation(),
position: null
}
};
GyroPositionSensorVRDevice.prototype.onDeviceOrientationChange =
function(deviceOrientation) {
this.deviceOrientation = deviceOrientation;
};
GyroPositionSensorVRDevice.prototype.onScreenOrientationChange =
function(screenOrientation) {
this.screenOrientation = window.orientation;
};
GyroPositionSensorVRDevice.prototype.getOrientation = function() {
if (this.deviceOrientation == null) {
return null;
}
// Rotation around the z-axis.
var alpha = THREE.Math.degToRad(this.deviceOrientation.alpha);
// Front-to-back (in portrait) rotation (x-axis).
var beta = THREE.Math.degToRad(this.deviceOrientation.beta);
// Left to right (in portrait) rotation (y-axis).
var gamma = THREE.Math.degToRad(this.deviceOrientation.gamma);
var orient = THREE.Math.degToRad(this.screenOrientation);
// Use three.js to convert to quaternion. Lifted from
// https://github.com/richtr/threeVR/blob/master/js/DeviceOrientationController.js
this.deviceEuler.set(beta, alpha, -gamma, 'YXZ');
this.finalQuaternion.setFromEuler(this.deviceEuler);
this.minusHalfAngle = -orient / 2;
this.screenTransform.set(0, Math.sin(this.minusHalfAngle), 0, Math.cos(this.minusHalfAngle));
this.finalQuaternion.multiply(this.screenTransform);
this.finalQuaternion.multiply(this.worldTransform);
return this.finalQuaternion;
};
module.exports = GyroPositionSensorVRDevice;
| gpl-2.0 |
Mosheman/TesisProyect-CustomWebPlataform | test/controllers/searches_controller_test.rb | 1257 | require 'test_helper'
class SearchesControllerTest < ActionController::TestCase
setup do
@search = searches(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:searches)
end
test "should get new" do
get :new
assert_response :success
end
test "should create search" do
assert_difference('Search.count') do
post :create, search: { depth_level: @search.depth_level, georeference: @search.georeference, keywords: @search.keywords, search_type: @search.search_type }
end
assert_redirected_to search_path(assigns(:search))
end
test "should show search" do
get :show, id: @search
assert_response :success
end
test "should get edit" do
get :edit, id: @search
assert_response :success
end
test "should update search" do
patch :update, id: @search, search: { depth_level: @search.depth_level, georeference: @search.georeference, keywords: @search.keywords, search_type: @search.search_type }
assert_redirected_to search_path(assigns(:search))
end
test "should destroy search" do
assert_difference('Search.count', -1) do
delete :destroy, id: @search
end
assert_redirected_to searches_path
end
end
| gpl-2.0 |
hkaj/CoFITS | mt4j/CoFiTS/src/utc/bsfile/util/PropertyManager.java | 2177 | package utc.bsfile.util;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;
/**
* Class used for managing the project properties
* give facilities for some properties
* Give the path to directories where are stored binaries of certain type
*/
public class PropertyManager {
public static String CONF_FILENAME = "rsc/config/cofits.properties";
public static String JSON_STRUCTURE_FILENAME = "rsc/config/structure.json";
public static String FILE_PATH = "file-path";
public static String ICONE_DIR = "icone-dir";
public static String MAIN_FONT = "main-font";
public static String PDF_FONT = "pdf-font";
public static String PICK_FONT = "pick-font";
public static String DEVICE = "device";
private static Properties props;
private static PropertyManager propertymanager;
public enum Orientation {
BOTTOM,
LEFT,
TOP,
RIGHT
}
public static PropertyManager getInstance() {
if (propertymanager == null) {
propertymanager = new PropertyManager();
props = new Properties();
try {
props.load(new FileReader(CONF_FILENAME));
} catch (FileNotFoundException e) {
System.out.printf("Configuration file %s not found",
CONF_FILENAME);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return propertymanager;
}
public String getProperty(String key) {
return props.getProperty(key);
}
public String getDirProperty (String key) {
String dir = props.getProperty(key);
if (dir.startsWith("~")) {
dir = dir.substring(1);
dir = System.getProperty("user.home").concat(dir);
System.out.println("Directory of files " + dir);
}
return dir;
}
public Set<Object> keys() {
return props.keySet();
}
public int getIntProperty(String key) {
String s = getProperty(key);
return Integer.parseInt(s);
}
public boolean getBooleanProperty(String key) {
boolean r = false;
String s = getProperty(key);
if (s.equalsIgnoreCase("true")) {
r = true;
}
return r;
}
}
| gpl-2.0 |
phpbb-extensions/teamsecurity | tests/event/team_passwords_test.php | 2597 | <?php
/**
*
* Team Security Measures extension for the phpBB Forum Software package.
*
* @copyright (c) 2015 phpBB Limited <https://www.phpbb.com>
* @license GNU General Public License, version 2 (GPL-2.0)
*
*/
namespace phpbb\teamsecurity\tests\event;
class team_passwords_test extends listener_base
{
/**
* Data set for test_set_team_password_configs
*
* @return array Array of test data
*/
public function set_team_password_configs_data()
{
return array(
array('core.acp_users_overview_before', 'reg_details', array(), true, true, 30, 'PASS_TYPE_SYMBOL',),
array('core.acp_users_overview_before', 'overview', array(), true, true, 30, 'PASS_TYPE_SYMBOL',),
array('core.acp_users_overview_before', 'reg_details', array(), false, true, 0, '',),
array('core.acp_users_overview_before', 'overview', array(), false, true, 0, '',),
array('core.acp_users_overview_before', 'reg_details', array(), true, false, 0, '',),
array('core.acp_users_overview_before', 'overview', array(), true, false, 0, '',),
array('core.ucp_display_module_before', 'reg_details', array(), true, true, 30, 'PASS_TYPE_SYMBOL',),
array('core.ucp_display_module_before', 'overview', array(), true, true, 30, 'PASS_TYPE_SYMBOL',),
array('core.ucp_display_module_before', 'reg_details', array(), false, true, 0, '',),
array('core.ucp_display_module_before', 'overview', array(), false, true, 0, '',),
array('core.ucp_display_module_before', 'reg_details', array(), true, false, 0, '',),
array('core.ucp_display_module_before', 'overview', array(), true, false, 0, '',),
);
}
/**
* Test team password configs are being updated
*
* @dataProvider set_team_password_configs_data
*/
public function test_set_team_password_configs($listener, $mode, $user_row, $sec_strong_pass, $in_watch_group, $sec_min_pass_chars, $expected)
{
$this->config = new \phpbb\config\config(array(
'pass_complex' => '',
'min_pass_chars' => 0,
'sec_strong_pass' => $sec_strong_pass,
'sec_min_pass_chars' => $sec_min_pass_chars,
));
$this->set_listener();
$this->listener->expects(self::atMost(1))
->method('in_watch_group')
->willReturn($in_watch_group);
$dispatcher = new \phpbb\event\dispatcher();
$dispatcher->addListener($listener, array($this->listener, 'set_team_password_configs'));
$event_data = array('mode', 'user_row');
$dispatcher->trigger_event($listener, compact($event_data));
self::assertEquals($expected, $this->config['pass_complex']);
self::assertEquals($sec_min_pass_chars, $this->config['min_pass_chars']);
}
}
| gpl-2.0 |
estrategasdigitales/dictobas | wp-content/themes/decibel/includes/customizer-css.php | 2735 | <?php
/**
* Customizer CSS
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
/**
* Inline CSS with the customizer options
*/
function wolf_customizer_css() {
$css = wolf_get_customizer_bg_options( 'body_bg', 'body' );
$css .= wolf_get_customizer_bg_options( 'site_footer_bg', '.site-footer' );
if ( 'boxed-layout' == get_theme_mod( 'layout' ) && ( get_theme_mod( 'body_bg_color' ) || get_theme_mod( 'body_bg_img' ) ) )
$css .= '#page{background:none;}';
if ( WOLF_DEBUG ) {
return $css;
} else {
return wolf_compact_css( $css );
}
} // end function
if ( ! function_exists( 'wolf_output_customizer_options' ) ) {
/**
* Output the custom CSS
*/
function wolf_output_customizer_options() {
echo '<style>';
echo '/* Customizer */' . "\n";
echo wolf_customizer_css();
echo '</style>';
}
//add_action( 'wp_head', 'wolf_output_customizer_options' );
}
function wolf_get_customizer_bg_options( $id, $selector ) {
$css = '';
$img = '';
$color = get_theme_mod( $id . '_color' );
$repeat = get_theme_mod( $id . '_repeat' );
$position = get_theme_mod( $id . '_position' );
$attachment = get_theme_mod( $id . '_attachment' );
$size = get_theme_mod( $id . '_size' );
$none = get_theme_mod( $id . '_none' );
$parallax = get_theme_mod( $id . '_parallax' );
$opacity = intval(get_theme_mod( $id . '_opacity', 100 )) / 100;
$color_rgba = 'rgba(' . wolf_hex_to_rgb( $color ) . ', ' . $opacity .')';
/* Backgrounds
---------------------------------*/
if ( '' == $none ) {
if ( get_theme_mod( $id . '_img' ) )
$img = 'url("'. get_theme_mod( $id . '_img' ) .'")';
if ( $color || $img ) {
if ( ! $img ) {
$css .= "$selector {background-color:$color;background-color:$color_rgba;}";
}
if ( $img ) {
if ( $parallax ) {
$css .= "$selector {background : $color $img $repeat fixed}";
$css .= "$selector {background-position : 50% 0}";
} else {
$css .= "$selector {background : $color $img $position $repeat $attachment}";
}
if ( 'cover' == $size ) {
$css .= "$selector {
-webkit-background-size: 100%;
-o-background-size: 100%;
-moz-background-size: 100%;
background-size: 100%;
-webkit-background-size: cover;
-o-background-size: cover;
background-size: cover;
}";
}
if ( 'resize' == $size ) {
$css .= "$selector {
-webkit-background-size: 100%;
-o-background-size: 100%;
-moz-background-size: 100%;
background-size: 100%;
}";
}
}
}
} else {
$css .= "$selector {background:none;}";
}
return $css;
}
| gpl-2.0 |
kthblmfld/poopscavator | components/pins.js | 247 | module.exports = {
arm:{
base: 0,
elbow: 2,
shoulder: 4,
head: 6
},
speaker: 11,
lid: 8,
motionSensor: 9,
panicButton: 10,
lidButton: 5,
light:{
rgb:{
red: 14,
green: 12,
blue: 13
}
}
}; | gpl-2.0 |
bulhaa/translate-dhivehi | src/main/java/org/jboss/samples/webservices/HelloWorld.java | 359 | package org.jboss.samples.webservices;
import javax.jws.WebMethod;
import javax.jws.WebService;
import com.gmail.freestyle_reunion.Translator;
@WebService()
public class HelloWorld {
@WebMethod()
public String sayHello(String eText) {
String dText = Translator.translate(eText.split("\\s"), -1).getTranslatedText();
return "test"+ dText;
}
}
| gpl-2.0 |
pleonex/UniversityCP | P7/Tetris/src/data/Punto.java | 1884 | /*
* Copyright (C) 2014 Benito Palacios Sánchez
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package data;
/**
* Representa un punton en el espacio de 2 dimensiones.
*
* @author Benito Palacios Sánchez
*/
public class Punto {
private final int coordX;
private final int coordY;
/**
* Crea una nueva instancia de la clase a partir de las coordenadas.
*
* @param coordX Coordenada del eje X.
* @param coordY Coordenada del eje Y.
*/
public Punto(int coordX, int coordY) {
this.coordX = coordX;
this.coordY = coordY;
}
/**
* Obtiene la coordenada del eje X.
*
* @return Coordenada X.
*/
public int getCoordX() {
return coordX;
}
/**
* Obtiene la coordenada del eje Y.
*
* @return Coordenada Y.
*/
public int getCoordY() {
return coordY;
}
/**
* Desplaza un punto la cantidad indicada.
*
* @param dx Número de puntos a desplazar en el eje X.
* @param dy Número de puntos a desplazar en el eje Y.
* @return Nuevo punto con las nuevas coordenadas.
*/
public Punto offset(final int dx, final int dy) {
return new Punto(this.getCoordX() + dx, this.getCoordY() + dy);
}
}
| gpl-2.0 |
kunj1988/Magento2 | app/code/Magento/Sales/Model/ResourceModel/Order/Payment/Transaction/Collection.php | 5600 | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Model\ResourceModel\Order\Payment\Transaction;
use Magento\Sales\Api\Data\TransactionSearchResultInterface;
use Magento\Sales\Model\ResourceModel\Order\Collection\AbstractCollection;
/**
* Payment transactions collection
*
* @author Magento Core Team <core@magentocommerce.com>
*/
class Collection extends AbstractCollection implements TransactionSearchResultInterface
{
/**
* Order ID filter
*
* @var int
*/
protected $_orderId = null;
/**
* Columns of order info that should be selected
*
* @var string[]
*/
protected $_addOrderInformation = [];
/**
* Columns of payment info that should be selected
*
* @var array
*/
protected $_addPaymentInformation = [];
/**
* Order Store ids
*
* @var int[]
*/
protected $_storeIds = [];
/**
* Payment ID filter
*
* @var int
*/
protected $_paymentId = null;
/**
* Parent ID filter
*
* @var int
*/
protected $_parentId = null;
/**
* Filter by transaction type
*
* @var string[]
*/
protected $_txnTypes = null;
/**
* Order field for setOrderFilter
*
* @var string
*/
protected $_orderField = 'order_id';
/**
* Initialize collection items factory class
*
* @return void
*/
protected function _construct()
{
$this->_init(
\Magento\Sales\Model\Order\Payment\Transaction::class,
\Magento\Sales\Model\ResourceModel\Order\Payment\Transaction::class
);
$this->addFilterToMap('created_at', 'main_table.created_at');
parent::_construct();
}
/**
* Join order information
*
* @param string[] $keys
* @return $this
*/
public function addOrderInformation(array $keys)
{
$this->_addOrderInformation = array_merge($this->_addOrderInformation, $keys);
return $this;
}
/**
* Join payment information
*
* @param array $keys
* @return $this
*/
public function addPaymentInformation(array $keys)
{
$this->_addPaymentInformation = array_merge($this->_addPaymentInformation, $keys);
return $this;
}
/**
* Order ID filter setter
*
* @param int $orderId
* @return $this
*/
public function addOrderIdFilter($orderId)
{
$this->_orderId = (int)$orderId;
return $this;
}
/**
* Payment ID filter setter
* Can take either the integer id or the payment instance
*
* @param \Magento\Sales\Model\Order\Payment|int $payment
* @return $this
*/
public function addPaymentIdFilter($payment)
{
$id = $payment;
if (is_object($payment)) {
$id = $payment->getId();
}
$this->_paymentId = (int)$id;
return $this;
}
/**
* Parent ID filter setter
*
* @param int $parentId
* @return $this
*/
public function addParentIdFilter($parentId)
{
$this->_parentId = (int)$parentId;
return $this;
}
/**
* Transaction type filter setter
*
* @param string[]|string $txnType
* @return $this
*/
public function addTxnTypeFilter($txnType)
{
if (!is_array($txnType)) {
$txnType = [$txnType];
}
$this->_txnTypes = $txnType;
return $this;
}
/**
* Add filter by store ids
*
* @param int|int[] $storeIds
* @return $this
*/
public function addStoreFilter($storeIds)
{
$storeIds = is_array($storeIds) ? $storeIds : [$storeIds];
$this->_storeIds = array_merge($this->_storeIds, $storeIds);
return $this;
}
/**
* Render additional filters and joins
*
* @return void
*/
protected function _renderFiltersBefore()
{
if ($this->_paymentId) {
$this->getSelect()->where('main_table.payment_id = ?', $this->_paymentId);
}
if ($this->_parentId) {
$this->getSelect()->where('main_table.parent_id = ?', $this->_parentId);
}
if ($this->_txnTypes) {
$this->getSelect()->where('main_table.txn_type IN(?)', $this->_txnTypes);
}
if ($this->_orderId) {
$this->getSelect()->where('main_table.order_id = ?', $this->_orderId);
}
if ($this->_addPaymentInformation) {
$this->getSelect()->joinInner(
['sop' => $this->getTable('sales_order_payment')],
'main_table.payment_id = sop.entity_id',
$this->_addPaymentInformation
);
}
if ($this->_storeIds) {
$this->getSelect()->where('so.store_id IN(?)', $this->_storeIds);
$this->addOrderInformation(['store_id']);
}
if ($this->_addOrderInformation) {
$this->getSelect()->joinInner(
['so' => $this->getTable('sales_order')],
'main_table.order_id = so.entity_id',
$this->_addOrderInformation
);
}
}
/**
* Unserialize additional_information in each item
*
* @return $this
*/
protected function _afterLoad()
{
foreach ($this->_items as $item) {
$this->getResource()->unserializeFields($item);
}
return parent::_afterLoad();
}
}
| gpl-2.0 |
carvalhomb/tsmells | sample/poco/poco/XML/samples/PrettyPrint/src/PrettyPrint.cpp | 2638 | //
// PrettyPrint.cpp
//
// $Id: //poco/svn/XML/samples/PrettyPrint/src/PrettyPrint.cpp#1 $
//
// This sample demonstrates the SAXParser, WhitespaceFilter,
// InputSource and XMLWriter classes.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/SAX/SAXParser.h"
#include "Poco/SAX/WhitespaceFilter.h"
#include "Poco/SAX/InputSource.h"
#include "Poco/XML/XMLWriter.h"
#include "Poco/Exception.h"
#include <iostream>
using Poco::XML::SAXParser;
using Poco::XML::XMLReader;
using Poco::XML::WhitespaceFilter;
using Poco::XML::InputSource;
using Poco::XML::XMLWriter;
using Poco::Exception;
int main(int argc, char** argv)
{
// read XML from standard input and pretty-print it to standard output
SAXParser parser;
WhitespaceFilter filter(&parser);
XMLWriter writer(std::cout, XMLWriter::CANONICAL | XMLWriter::PRETTY_PRINT);
writer.setNewLine(XMLWriter::NEWLINE_LF);
filter.setContentHandler(&writer);
filter.setDTDHandler(&writer);
filter.setProperty(XMLReader::PROPERTY_LEXICAL_HANDLER, static_cast<Poco::XML::LexicalHandler*>(&writer));
try
{
InputSource source(std::cin);
filter.parse(&source);
}
catch (Exception& exc)
{
std::cerr << exc.displayText() << std::endl;
return 1;
}
return 0;
}
| gpl-2.0 |
siiiiilvio/moviesite | wp-content/themes/portthemetrust/footer.php | 914 | <div id="footer" >
<img style="display: none;" src="http://gerontophilia-thefilm.com/wp-content/uploads/2014/04/blogOn.png">
<img style="display: none;" src="http://gerontophilia-thefilm.com/wp-content/uploads/2014/04/blogOff.png">
<img style="display: none;" src="http://gerontophilia-thefilm.com/wp-content/uploads/2014/04/doNotOn.png">
<img style="display: none;" src="http://gerontophilia-thefilm.com/wp-content/uploads/2014/04/doNotOff.png">
<div class="main">
<div class="inside clearfix">
<?php
$id=615;
$post = get_post($id);
$content = apply_filters('the_content', $post->post_content);
$newContent = preg_replace('#</?br(\s[^>]*)?>#i', '', $content);
echo $newContent;
?>
</div>
</div>
</div><!-- end footer -->
</div><!-- end container -->
<?php wp_footer(); ?>
</body>
</html> | gpl-2.0 |
jacontrerasp/lab8-commons-io | src/main/java/org/apache/commons/io/filefilter/OrFileFilter.java | 4940 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A {@link java.io.FileFilter} providing conditional OR logic across a list of
* file filters. This filter returns {@code true} if any filters in the
* list return {@code true}. Otherwise, it returns {@code false}.
* Checking of the file filter list stops when the first filter returns
* {@code true}.
*
* @since 1.0
* @version $Id$
* @see FileFilterUtils#or(IOFileFilter...)
*/
public class OrFileFilter
extends AbstractFileFilter
implements ConditionalFileFilter, Serializable {
private static final long serialVersionUID = 5767770777065432721L;
/** The list of file filters. */
private final List<IOFileFilter> fileFilters;
/**
* Constructs a new instance of <code>OrFileFilter</code>.
*
* @since 1.1
*/
protected OrFileFilter() {
this.fileFilters = new ArrayList<IOFileFilter>();
}
/**
* Constructs a new instance of <code>OrFileFilter</code>
* with the specified filters.
*
* @param fileFilters the file filters for this filter, copied, null ignored
* @since 1.1
*/
protected OrFileFilter(final List<IOFileFilter> fileFilters) {
if (fileFilters == null) {
this.fileFilters = new ArrayList<IOFileFilter>();
} else {
this.fileFilters = new ArrayList<IOFileFilter>(fileFilters);
}
}
/**
* Constructs a new file filter that ORs the result of two other filters.
*
* @param filter1 the first filter, must not be null
* @param filter2 the second filter, must not be null
* @throws IllegalArgumentException if either filter is null
*/
public OrFileFilter(final IOFileFilter filter1, final IOFileFilter filter2) {
if (filter1 == null || filter2 == null) {
throw new IllegalArgumentException("The filters must not be null");
}
this.fileFilters = new ArrayList<IOFileFilter>(2);
addFileFilter(filter1);
addFileFilter(filter2);
}
/**
* {@inheritDoc}
*/
public void addFileFilter(final IOFileFilter ioFileFilter) {
this.fileFilters.add(ioFileFilter);
}
/**
* {@inheritDoc}
*/
public List<IOFileFilter> getFileFilters() {
return Collections.unmodifiableList(this.fileFilters);
}
/**
* {@inheritDoc}
*/
public boolean removeFileFilter(final IOFileFilter ioFileFilter) {
return this.fileFilters.remove(ioFileFilter);
}
/**
* {@inheritDoc}
*/
public void setFileFilters(final List<IOFileFilter> fileFilters) {
this.fileFilters.clear();
this.fileFilters.addAll(fileFilters);
}
/**
* {@inheritDoc}
*/
@Override
public boolean accept(final File file) {
for (final IOFileFilter fileFilter : fileFilters) {
if (fileFilter.accept(file)) {
return true;
}
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean accept(final File file, final String name) {
for (final IOFileFilter fileFilter : fileFilters) {
if (fileFilter.accept(file, name)) {
return true;
}
}
return false;
}
/**
* Provide a String representaion of this file filter.
*
* @return a String representaion
*/
@Override
public String toString() {
final StringBuilder buffer = new StringBuilder();
buffer.append(super.toString());
buffer.append("(");
if (fileFilters != null) {
for (int i = 0; i < fileFilters.size(); i++) {
if (i > 0) {
buffer.append(",");
}
final Object filter = fileFilters.get(i);
buffer.append(filter == null ? "null" : filter.toString());
}
}
buffer.append(")");
return buffer.toString();
}
}
| gpl-2.0 |
pg18/perso_website | vendor/ezsystems/ezplatform-solr-search-engine/lib/Query/Location/CriterionVisitor/ContentTypeGroupIdIn.php | 1941 | <?php
/**
* This file is part of the eZ Platform Solr Search Engine package.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*
* @version //autogentag//
*/
namespace EzSystems\EzPlatformSolrSearchEngine\Query\Location\CriterionVisitor;
use EzSystems\EzPlatformSolrSearchEngine\Query\CriterionVisitor;
use eZ\Publish\API\Repository\Values\Content\Query\Criterion;
use eZ\Publish\API\Repository\Values\Content\Query\Criterion\Operator;
/**
* Visits the ContentTypeGroupId criterion.
*/
class ContentTypeGroupIdIn extends CriterionVisitor
{
/**
* Check if visitor is applicable to current criterion.
*
* @param \eZ\Publish\API\Repository\Values\Content\Query\Criterion $criterion
*
* @return bool
*/
public function canVisit(Criterion $criterion)
{
return
$criterion instanceof Criterion\ContentTypeGroupId &&
(
($criterion->operator ?: Operator::IN) === Operator::IN ||
$criterion->operator === Operator::EQ
);
}
/**
* Map field value to a proper Solr representation.
*
* @param \eZ\Publish\API\Repository\Values\Content\Query\Criterion $criterion
* @param \EzSystems\EzPlatformSolrSearchEngine\Query\CriterionVisitor $subVisitor
*
* @return string
*/
public function visit(Criterion $criterion, CriterionVisitor $subVisitor = null)
{
return '(' .
implode(
' OR ',
array_map(
function ($value) {
return 'content_group_mid:"' . $value . '"';
},
// TODO this should have been casted by criterion???
(array)$criterion->value
)
) .
')';
}
}
| gpl-2.0 |
mor10/kuhn | header.php | 1784 | <?php
/**
* The header for our theme
*
* This is the template that displays all of the <head> section and everything up until <div id="content">
*
* @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
*
* @package Kuhn
*/
?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div id="page" class="site">
<a class="skip-link screen-reader-text" href="#main"><?php esc_html_e( 'Skip to content', 'kuhn' ); ?></a>
<header id="masthead" class="site-header" role="banner">
<div class="site-branding">
<?php the_custom_logo(); ?>
<?php
if ( is_front_page() && is_home() ) : ?>
<h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
<?php else : ?>
<p class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></p>
<?php
endif;
$description = get_bloginfo( 'description', 'display' );
if ( $description || is_customize_preview() ) : ?>
<p class="site-description"><?php echo $description; /* WPCS: xss ok. */ ?></p>
<?php
endif; ?>
</div><!-- .site-branding -->
<nav id="site-navigation" class="main-navigation" role="navigation">
<button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false"><?php esc_html_e( 'Primary Menu', 'kuhn' ); ?></button>
<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_id' => 'primary-menu' ) ); ?>
</nav><!-- #site-navigation -->
</header><!-- #masthead -->
| gpl-2.0 |
godiard/log-activity | logcollect.py | 19456 | # Copyright (C) 2007, Pascal Scheffers <pascal@scheffers.net>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# log-collect for OLPC
#
# Compile a report containing:
# * Basic system information:
# ** Serial number
# ** Battery type
# ** Build number
# ** Uptime
# ** disk free space
# ** ...
# * Installed packages list
# * All relevant log files (all of them, at first)
#
# The report is output as a tarfile
#
# This file has two modes:
# 1. It is a stand-alone python script, when invoked as 'log-collect'
# 2. It is a python module.
import os
import zipfile
import glob
import sys
import time
# The next couple are used by LogSend
import httplib
import mimetypes
import urlparse
MFG_DATA_PATHS = ['/ofw/mfg-data/', '/proc/device-tree/mfg-data/']
class MachineProperties:
"""Various machine properties in easy to access chunks.
"""
def __read_file(self, filename):
"""Read the entire contents of a file and return it as a string"""
data = ''
f = open(filename)
try:
data = f.read()
finally:
f.close()
return data
def olpc_build(self):
"""Buildnumber, from /etc/issue"""
# Is there a better place to get the build number?
if not os.path.exists('/etc/issue'):
return '#/etc/issue not found'
# Needed, because we want to default to the first non blank line:
first_line = ''
for line in self.__read_file('/etc/issue').splitlines():
if line.lower().find('olpc build') > -1:
return line
if first_line == '':
first_line = line
return first_line
def uptime(self):
for line in self.__read_file('/proc/uptime').splitlines():
if line != '':
return line
return ''
def loadavg(self):
for line in self.__read_file('/proc/loadavg').splitlines():
if line != '':
return line
return ''
def kernel_version(self):
for line in self.__read_file('/proc/version').splitlines():
if line != '':
return line
return ''
def memfree(self):
line = ''
for line in self.__read_file('/proc/meminfo').splitlines():
if line.find('MemFree:') > -1:
return line[8:].strip()
def _trim_null(self, v):
if v != '' and ord(v[len(v) - 1]) == 0:
v = v[:len(v) - 1]
return v
def _mfg_data(self, item):
"""Return mfg data item from mfg-data directory"""
mfg_path = None
for test_path in MFG_DATA_PATHS:
if os.path.exists(test_path + item):
mfg_path = test_path + item
break
if mfg_path is None:
return ''
v = self._trim_null(self.__read_file(mfg_path))
return v
def laptop_serial_number(self):
return self._mfg_data('SN')
def laptop_motherboard_number(self):
return self._mfg_data('B#')
def laptop_board_revision(self):
s = self._mfg_data('SG')[0:1]
if s == '':
return ''
return '%02X' % ord(self._mfg_data('SG')[0:1])
def laptop_uuid(self):
return self._mfg_data('U#')
def laptop_keyboard(self):
kb = self._mfg_data('KM') + '-'
kb += self._mfg_data('KL') + '-'
kb += self._mfg_data('KV')
return kb
def laptop_wireless_mac(self):
return self._mfg_data('WM')
def laptop_bios_version(self):
try:
d = open('/proc/device-tree/openprom/model', 'r').read()
v = self._trim_null(d)
return v
except:
pass
try:
d = open('/ofw/openprom/model', 'r').read()
v = self._trim_null(d)
return v
except:
pass
try:
d = open('/sys/class/dmi/id/bios_version', 'r').read()
v = self._trim_null(d)
return v
except:
pass
return ''
def laptop_country(self):
return self._mfg_data('LA')
def laptop_localization(self):
return self._mfg_data('LO')
def _battery_info(self, item):
root = '/sys/class/power_supply/olpc-battery/'
if not os.path.exists(root + item):
return ''
return self.__read_file(root + item).strip()
def battery_serial_number(self):
return self._battery_info('serial_number')
def battery_capacity(self):
return self._battery_info('capacity') + ' ' + \
self._battery_info('capacity_level')
def battery_info(self):
# Should be just:
# return self._battery_info('uevent')
# But because of a bug in the kernel, that has trash, lets filter:
bi = ''
for line in self._battery_info('uevent').splitlines():
if line.startswith('POWER_'):
bi += line + '\n'
return bi
def disksize(self, path):
return os.statvfs(path).f_bsize * os.statvfs(path).f_blocks
def diskfree(self, path):
return os.statvfs(path).f_bsize * os.statvfs(path).f_bavail
def _read_popen(self, cmd):
p = os.popen(cmd)
s = ''
try:
for line in p:
s += line
finally:
p.close()
return s
def ifconfig(self):
return self._read_popen('/sbin/ifconfig')
def route_n(self):
return self._read_popen('/sbin/route -n')
def df_a(self):
return self._read_popen('/bin/df -a')
def ps_auxfwww(self):
return self._read_popen('/bin/ps auxfwww')
def usr_bin_free(self):
return self._read_popen('/usr/bin/free')
def top(self):
return self._read_popen('/usr/bin/top -bn2')
def installed_activities(self):
s = ''
for path in glob.glob('/usr/share/sugar/activities/*.activity'):
s += os.path.basename(path) + '\n'
home = os.path.expanduser('~')
for path in glob.glob(os.path.join(home, 'Activities', '*')):
s += '~' + os.path.basename(path) + '\n'
return s
class LogCollect:
"""Collect XO logfiles and machine metadata for reporting to OLPC
"""
def __init__(self):
self._mp = MachineProperties()
def write_logs(self, archive='', logbytes=15360):
"""Write a zipfile containing the tails of the logfiles and
machine info of the XO
Arguments:
archive - Specifies the location where to store the data
defaults to /dev/shm/logs-<xo-serial>.zip
logbytes - Maximum number of bytes to read from each log file.
0 means complete logfiles, not just the tail
-1 means only save machine info, no logs
"""
# This function is crammed with try...except to make sure we
# get as much data as possible, if anything fails.
if archive == '':
archive = '/dev/shm/logs.zip'
try:
# With serial number is more convenient, but might
# fail for some reason...
archive = '/dev/shm/logs-%s.zip' % \
self._mp.laptop_serial_number()
except Exception:
pass
z = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)
try:
try:
z.writestr('info.txt', self.laptop_info())
except Exception, e:
z.writestr('info.txt',
"logcollect: could not add info.txt: %s" % e)
if logbytes > -1:
# Include some log files from /var/log.
for fn in ['dmesg', 'messages', 'cron', 'maillog', 'rpmpkgs',
'Xorg.0.log', 'spooler']:
try:
if os.access('/var/log/' + fn, os.F_OK):
if logbytes == 0:
z.write('/var/log/' + fn, 'var-log/' + fn)
else:
z.writestr('var-log/' + fn,
self.file_tail('/var/log/' + fn,
logbytes))
except Exception, e:
z.writestr('var-log/' + fn,
"logcollect: could not add %s: %s" %
(fn, e))
home = os.path.expanduser('~')
here = os.path.join(home, '.sugar/default/logs/*.log')
for path in glob.glob(here):
if os.access(path, os.F_OK):
pref = 'sugar-logs/'
name = os.path.join(pref, os.path.basename(path))
try:
if logbytes == 0:
z.write(path, name)
else:
z.writestr(name,
self.file_tail(path, logbytes))
except Exception, e:
z.writestr(name,
"logcollect: could not add %s: %s" %
(name, e))
here = os.path.join(home, '.sugar/default/logs/*/*.log')
for path in glob.glob(here):
if os.access(path, os.F_OK):
when = os.path.basename(os.path.dirname(path))
pref = 'sugar-logs-%s/' % when
name = os.path.join(pref, os.path.basename(path))
try:
if logbytes == 0:
z.write(path, name)
else:
z.writestr(name,
self.file_tail(path, logbytes))
except Exception, e:
z.writestr(name,
"logcollect: could not add %s: %s" %
(name, e))
try:
z.write('/etc/resolv.conf')
except Exception, e:
z.writestr('/etc/resolv.conf',
"logcollect: could not add resolv.conf: %s" % e)
except Exception, e:
print 'While creating zip archive: %s' % e
z.close()
return archive
def file_tail(self, filename, tailbytes):
"""Read the tail (end) of the file
Arguments:
filename The name of the file to read
tailbytes Number of bytes to include or 0 for entire file
"""
data = ''
f = open(filename)
try:
fsize = os.stat(filename).st_size
if tailbytes > 0 and fsize > tailbytes:
f.seek(-tailbytes, 2)
data = f.read()
finally:
f.close()
return data
def make_report(self, target='stdout'):
"""Create the report
Arguments:
target - where to save the logs, a path or stdout
"""
li = self.laptop_info()
for k, v in li.iteritems():
print k + ': ' + v
print self._mp.battery_info()
def laptop_info(self):
"""Return a string with laptop serial, battery type, build,
memory info, etc."""
s = ''
try:
# Do not include UUID!
s += 'laptop-info-version: 1.0\n'
s += 'clock: %f\n' % time.clock()
s += 'date: %s\n' % time.strftime("%a, %d %b %Y %H:%M:%S +0000",
time.gmtime())
s += 'memfree: %s\n' % self._mp.memfree()
s += 'disksize: %s MB\n' % (self._mp.disksize('/') / (1024 * 1024))
s += 'diskfree: %s MB\n' % (self._mp.diskfree('/') / (1024 * 1024))
s += 'olpc_build: %s\n' % self._mp.olpc_build()
s += 'kernel_version: %s\n' % self._mp.kernel_version()
s += 'uptime: %s\n' % self._mp.uptime()
s += 'loadavg: %s\n' % self._mp.loadavg()
s += 'serial-number: %s\n' % self._mp.laptop_serial_number()
s += 'motherboard-number: %s\n' % \
self._mp.laptop_motherboard_number()
s += 'board-revision: %s\n' % self._mp.laptop_board_revision()
s += 'keyboard: %s\n' % self._mp.laptop_keyboard()
s += 'wireless_mac: %s\n' % self._mp.laptop_wireless_mac()
s += 'firmware: %s\n' % self._mp.laptop_bios_version()
s += 'country: %s\n' % self._mp.laptop_country()
s += 'localization: %s\n' % self._mp.laptop_localization()
s += self._mp.battery_info()
s += "\n[/sbin/ifconfig]\n%s\n" % self._mp.ifconfig()
s += "\n[/sbin/route -n]\n%s\n" % self._mp.route_n()
s += '\n[Installed Activities]\n%s\n' % \
self._mp.installed_activities()
s += '\n[df -a]\n%s\n' % self._mp.df_a()
s += '\n[ps auxwww]\n%s\n' % self._mp.ps_auxfwww()
s += '\n[free]\n%s\n' % self._mp.usr_bin_free()
s += '\n[top -bn2]\n%s\n' % self._mp.top()
except Exception, e:
s += '\nException while building info:\n%s\n' % e
return s
class LogSend:
# post_multipart and encode_multipart_formdata have been taken from
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
def post_multipart(self, host, selector, fields, files):
"""
Post fields and files to an http host as multipart/form-data.
fields is a sequence of (name, value) elements for regular
form fields. files is a sequence of (name, filename, value)
elements for data to be uploaded as files Return the server's
response page.
"""
content_type, body = self.encode_multipart_formdata(fields, files)
h = httplib.HTTP(host)
h.putrequest('POST', selector)
h.putheader('content-type', content_type)
h.putheader('content-length', str(len(body)))
h.putheader('Host', host)
h.endheaders()
h.send(body)
errcode, errmsg, headers = h.getreply()
return h.file.read()
def encode_multipart_formdata(self, fields, files):
"""
fields is a sequence of (name, value) elements for regular
form fields. files is a sequence of (name, filename, value)
elements for data to be uploaded as files Return
(content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
CRLF = '\r\n'
L = []
for (key, value) in fields:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for (key, filename, value) in files:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; '
'name="%s"; filename="%s"' % (key, filename))
L.append('Content-Type: %s' % self.get_content_type(filename))
L.append('')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
def read_file(self, filename):
"""Read the entire contents of a file and return it as a string"""
data = ''
f = open(filename)
try:
data = f.read()
finally:
f.close()
return data
def get_content_type(self, filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
def http_post_logs(self, url, archive):
# host, selector, fields, files
files = ('logs', os.path.basename(archive), self.read_file(archive)),
# Client= olpc will make the server return just "OK" or "FAIL"
fields = ('client', 'xo'),
urlparts = urlparse.urlsplit(url)
print "Sending logs to %s" % url
r = self.post_multipart(urlparts[1], urlparts[2], fields, files)
print r
return (r == 'OK')
# This script is dual-mode, it can be used as a command line tool and as
# a library.
if sys.argv[0].endswith('logcollect.py') or \
sys.argv[0].endswith('logcollect'):
print 'log-collect utility 1.0'
lc = LogCollect()
ls = LogSend()
logs = ''
mode = 'http'
if len(sys.argv) == 1:
print """logcollect.py - send your XO logs to OLPC
Usage:
logcollect.py http://server.name/submit.php
- submit logs to a server
logcollect.py file:/media/xxxx-yyyy/mylog.zip
- save the zip file on a USB device or SD card
logcollect.py all file:/media/xxxx-yyyy/mylog.zip
- Save to zip file and include ALL logs
logcollect.py none http
- Just send info.txt, but no logs via http.
logcollect.py none file
- Just save info.txt in /dev/shm/logs-SN123.zip
If you specify 'all' or 'none' you must specify http or file as well.
"""
sys.exit()
logbytes = 15360
if len(sys.argv) > 1:
mode = sys.argv[len(sys.argv) - 1]
if sys.argv[1] == 'all':
logbytes = 0
if sys.argv[1] == 'none':
logbytes = -1
if mode.startswith('file'):
# file://
logs = mode[5:]
logs = lc.write_logs(logs, logbytes)
print 'Logs saved in %s' % logs
sent_ok = False
if len(sys.argv) > 1:
mode = sys.argv[len(sys.argv) - 1]
if mode.startswith('http'):
print "Trying to send the logs using HTTP (web)"
if len(mode) == 4:
print "No default log destination, aborting"
sys.exit(1)
else:
url = mode
if ls.http_post_logs(url, logs):
print "Logs were sent."
sent_ok = True
else:
print "FAILED to send logs."
if sent_ok:
os.remove(logs)
print "Logs were sent, tempfile deleted."
| gpl-2.0 |
hojsimpson/LiSA | src/xml/lisa_xml.cpp | 45050 | #include <string>
#include <vector>
#include <sstream>
#include <map>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#define LISA_XML_IMPL
#include "LisaXmlFile.hpp"
#include "xmldefs.hpp"
#include "../basics/matrix.hpp"
#include "../basics/pair.hpp"
#include "../basics/graph.hpp"
#include "../lisa/lvalues.hpp"
#include "../lisa/ptype.hpp"
#include "../lisa/ctrlpara.hpp"
#include "../scheduling/schedule.hpp"
#include "../main/global.hpp"
#include "xmldefs.hpp"
#include "Lisa_NativeDataHandler.hpp"
#include "Lisa_IO_Factory.hpp"
using namespace std;
#define MAP_PAIRS(PROP, PROP_VAL, ATTR, ATTR_VAL) WriteMap[pair<int,int>((PROP),(PROP_VAL))] = pair<string,string >((ATTR),(ATTR_VAL)); \
ReadMap[pair<string,string>((ATTR),(ATTR_VAL))] = pair<int,int >((PROP),(PROP_VAL))
const string VALUE_ATTRIBUTE = "";
void LisaXmlFile::init_maps()
{
//Problem Type Mapping
//default values are commented out
// +++++++++++++++++++++++++++++++
// ++++++ ALPHA ++++++++++++++
// +++++++++++++++++++++++++++++++
//Machine enironment
MAP_PAIRS(M_ENV,ONE,"env","1");
MAP_PAIRS(M_ENV,O,"env","O");
MAP_PAIRS(M_ENV,F,"env","F");
MAP_PAIRS(M_ENV,J,"env","J");
MAP_PAIRS(M_ENV,X,"env","X");
MAP_PAIRS(M_ENV,G,"env","G");
MAP_PAIRS(M_ENV,P,"env","P");
MAP_PAIRS(M_ENV,Q,"env","Q");
MAP_PAIRS(M_ENV,R,"env","R");
//Multi-purpose stuff
MAP_PAIRS(M_MPT,1,"mpt","yes");
// MAP_PAIRS(M_MPT,FALSE,"mpt","no");
MAP_PAIRS(M_MPM,1,"mpm","yes");
// MAP_PAIRS(M_MPM,FALSE,"mpm","no");
//Machine number
// MAP_PAIRS(M_NUMBER,M_ARB,"m","arbitrary");
MAP_PAIRS(M_NUMBER,M_VAL,"m",VALUE_ATTRIBUTE); // m is placed here
MAP_PAIRS(M_NUMBER,M_FIX,"m","fixed");
// +++++++++++++++++++++++++++++++
// ++++++ BETA +++++++++++++++
// +++++++++++++++++++++++++++++++
//Preemtion
MAP_PAIRS(PMTN,1,"pmtn","yes");
// MAP_PAIRS(PMTN,FALSE,"pmtn","no");
//Preceedence
// MAP_PAIRS(PRECEDENCE,FALSE,"prec","no");
MAP_PAIRS(PRECEDENCE,INTREE,"prec","intree");
MAP_PAIRS(PRECEDENCE,OUTTREE,"prec","outtree");
MAP_PAIRS(PRECEDENCE,TREE,"prec","tree");
MAP_PAIRS(PRECEDENCE,SP_GRAPH,"prec","sp_graph");
MAP_PAIRS(PRECEDENCE,CHAINS,"prec","chains");
MAP_PAIRS(PRECEDENCE,PREC,"prec","yes");
//Release times
MAP_PAIRS(RI,1,"release_times","yes");
// MAP_PAIRS(RI,FALSE,"release_times","no");
//Due dates
MAP_PAIRS(DI,1,"due_dates","yes");
// MAP_PAIRS(DI,FALSE,"due_dates","no");
//Processing times
// MAP_PAIRS(PIJ,FALSE,"processing_times","arbitrary");
MAP_PAIRS(PIJ,PIJ_1,"processing_times","unit");
MAP_PAIRS(PIJ,PIJ_P,"processing_times","uniform");
//Batch
// MAP_PAIRS(BATCH,FALSE,"batch","no");
MAP_PAIRS(BATCH,S_BATCH,"batch","s_batch");
MAP_PAIRS(BATCH,P_BATCH,"batch","p_batch");
//Bounded Batch
// MAP_PAIRS(BOUNDED_BATCH,FALSE,"batch_bounded","no");
MAP_PAIRS(BOUNDED_BATCH,1,"batch_bounded","yes");
//Job number
// MAP_PAIRS(JOB_NR,J_ARB,"n","arbitrary");
MAP_PAIRS(JOB_NR,J_VAL,"n",VALUE_ATTRIBUTE); // n is placed here
MAP_PAIRS(JOB_NR,J_FIX,"n","fixed");
//No wait
MAP_PAIRS(NO_WAIT,1,"no-wait","yes");
// MAP_PAIRS(NO_WAIT,FALSE,"no-wait","no");
//Size --what's that ?
MAP_PAIRS(SIZE,1,"size","yes");
// MAP_PAIRS(SIZE,FALSE,"size","no");
//Timelags
// MAP_PAIRS(TIME_LAGS,FALSE,"time-lags","no");
MAP_PAIRS(TIME_LAGS,UNIT_TL,"time-lags","unit");
MAP_PAIRS(TIME_LAGS,CONST_TL,"time-lags","constant");
MAP_PAIRS(TIME_LAGS,GENERAL_TL,"time-lags","given");
//Transportation delays
// MAP_PAIRS(TRANSPORTATION_DELAYS,FALSE,"transp-delays","no");
MAP_PAIRS(TRANSPORTATION_DELAYS,TIK_T,"transp-delays","t_ik--T");
MAP_PAIRS(TRANSPORTATION_DELAYS,TIKL_T,"transp-delays","t_ikl--T");
MAP_PAIRS(TRANSPORTATION_DELAYS,TI_IN,"transp-delays","t_i--T_1-T_2");
MAP_PAIRS(TRANSPORTATION_DELAYS,TKL_TLK,"transp-delays","t_kl--t_lk");
MAP_PAIRS(TRANSPORTATION_DELAYS,TIKL_TILK,"transp-delays","t_ikl--t_ilk");
MAP_PAIRS(TRANSPORTATION_DELAYS,TI,"transp-delays","t_i");
MAP_PAIRS(TRANSPORTATION_DELAYS,TK,"transp-delays","t_k");
MAP_PAIRS(TRANSPORTATION_DELAYS,TKL,"transp-delays","t_kl");
MAP_PAIRS(TRANSPORTATION_DELAYS,TIK,"transp-delays","t_ik");
MAP_PAIRS(TRANSPORTATION_DELAYS,TIKL,"transp-delays","t_ikl");
//SERVER_FLAGS
// MAP_PAIRS(SERVER_FLAGS,FALSE,"server-flags","no");
MAP_PAIRS(SERVER_FLAGS,SI,"server-flags","yes");
MAP_PAIRS(SERVER_FLAGS,SI_1,"server-flags","1");
MAP_PAIRS(SERVER_FLAGS,SI_S,"server-flags","s");
// +++++++++++++++++++++++++++++++
// ++++++ GAMMA +++++++++++++++
// +++++++++++++++++++++++++++++++
//Objective
MAP_PAIRS(OBJECTIVE,CMAX,"objective","Cmax");
MAP_PAIRS(OBJECTIVE,LMAX,"objective","Lmax");
MAP_PAIRS(OBJECTIVE,SUM_CI,"objective","Sum_Ci");
MAP_PAIRS(OBJECTIVE,SUM_WICI,"objective","Sum_wiCi");
MAP_PAIRS(OBJECTIVE,SUM_UI,"objective","Sum_Ui");
MAP_PAIRS(OBJECTIVE,SUM_WIUI,"objective","Sum_wiUi");
MAP_PAIRS(OBJECTIVE,SUM_TI,"objective","Sum_Ti");
MAP_PAIRS(OBJECTIVE,SUM_WITI,"objective","Sum_wiTi");
MAP_PAIRS(OBJECTIVE,IRREG1,"objective","irreg_1");
MAP_PAIRS(OBJECTIVE,IRREG2,"objective","irreg_2");
MAP_PAIRS(OBJECTIVE,ANY_OBJECTIVE,"objective","*");
}
// ++++++++++++ functions for internal use only ++++++++++
// problemType - numeric handlers
string handleSpecialAttribute(const int prop, const Lisa_ProblemType& P){
stringstream s;
switch(prop)
{
case M_NUMBER:
s << P.m_no;
break;
case JOB_NR:
s << P.n_no;
break;
default:
break;
}
return s.str();
}
bool handleSpecialAttribute(const string attr, const string attr_val, Lisa_ProblemType& P){
stringstream s(attr_val);
int value;
s >> value;
if(s.fail())
return false;
if(attr == "m")
{
P.set_property(M_NUMBER,M_VAL);
P.m_no = value;
return true;
}
if(attr == "n")
{
P.set_property(JOB_NR,J_VAL);
P.n_no = value;
return true;
}
return false;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++
// each of the following functions hooks the objcect's XML-representation
// into the current XML-document
//
// both, <<- and >>-operator have to take care about LisaXmlFile's internal
// hook pointer, i.e. set it appropriately in advance to each call of one of
// these functions
// If you want to add a serialization of an object to XML
// you may want to declare a friend function in your class to access
// private and/or protected data of your class interface
//the following functions assume existence of a proper document
//and Hook set to the desired parent node
void LisaXmlFile::write(const Lisa_ProblemType& P)
{
const char* node_names[3] = {"alpha", "beta", "gamma"};
const int advance_list[4] = {0,
NUMBER_ALPHA ,
NUMBER_ALPHA + NUMBER_BETA ,
NUMBER_ALPHA + NUMBER_BETA + NUMBER_GAMMA };
int tag = 0, curr_node = 0;
map< pair<int,int> , pair< string, string> > ::iterator finder;
xmlNodePtr problem;
if(xmlStrcmp(Hook->name, (const xmlChar *) "problem") == 0)
problem = Hook;
else
problem = xmlAddChild(Hook,xmlNewNode(NULL,(const xmlChar *) "problem"));
xmlNodePtr current;
for(curr_node = 0; curr_node < 3 ; curr_node++)
{
current = xmlAddChild(problem, xmlNewNode(NULL, (const xmlChar *) node_names[curr_node]));
for(tag = advance_list[curr_node]; tag < advance_list[curr_node + 1]; tag++)
{
finder = WriteMap.find(pair<int,int>(tag,P.get_property(tag)));
if(finder == WriteMap.end()) // not found
continue; //throw something
if(finder->second.second == VALUE_ATTRIBUTE)
xmlSetProp(current,
(const xmlChar *) finder->second.first.c_str(),
(const xmlChar *) handleSpecialAttribute(finder->first.first,P).c_str());
else
xmlSetProp(current,
(const xmlChar *) finder->second.first.c_str(),
(const xmlChar *) finder->second.second.c_str());
}
}
}
bool LisaXmlFile::read(Lisa_ProblemType& P)
{
P.reset();
if(!xmlStrEqual(Hook->name, (const xmlChar *) "problem"))
{
raiseError(BAD_ROOT,"problem",(const char*) Hook->name);
return false;
}
map< pair<string,string> , pair< int, int> > ::iterator finder;
xmlChar* attValue;
string value_str;
for(xmlNodePtr cur = Hook->children;cur;cur=cur->next)
{
if(cur->type != XML_ELEMENT_NODE)
continue;
for(xmlAttrPtr attPtr = cur->properties; attPtr; attPtr=attPtr->next)
{
attValue = xmlGetProp(cur, attPtr->name);
if(attValue)
{
value_str = string((char*) attValue);
xmlFree(attValue);
}
else
value_str = "";
finder = ReadMap.find(pair<string,string>((const char*) attPtr->name, value_str));
//ignore unknown elements
if(finder != ReadMap.end())
{
P.set_property(finder->second.first, finder->second.second);
}
else if(!handleSpecialAttribute( (const char*) attPtr->name , value_str, P))
{
raiseError(BAD_ATTRIBUTE, (const char*) attPtr->name );
return false;
}
}
}
return true;
}
void LisaXmlFile::write(const Lisa_Values& V)
{
xmlNodePtr l_parent;
stringstream pipe;
if(xmlStrEqual(Hook->name, (const xmlChar *) "values"))
l_parent = Hook;
else
l_parent = xmlAddChild(Hook,xmlNewNode(NULL,(const xmlChar *) "values"));
pipe.str("");
const int n = V.get_n() , m = V.get_m();
pipe << m;
xmlSetProp(l_parent,(const xmlChar *) "m", (const xmlChar *) pipe.str().c_str());
pipe.str("");
pipe << n;
xmlSetProp(l_parent,(const xmlChar *) "n", (const xmlChar *) pipe.str().c_str());
xmlNodePtr child;
pipe.str("");
pipe.clear();
Lisa_DataHandler* dh = Lisa_IO_Factory::createHandler(coding);
if(dh == NULL)
{
raiseError(BAD_MODEL,coding);
return;
}
if (V.PT)
{
dh->write(V,"processing_times",pipe);
child = xmlNewTextChild(l_parent,
NULL,
(const xmlChar *) "processing_times",
(const xmlChar *) pipe.str().c_str());
xmlSetProp(child,(const xmlChar *) "model", (const xmlChar *) coding.c_str());
pipe.str("");
pipe.clear();
}
if (V.SIJ)
{
dh->write(V,"operation_set",pipe);
child = xmlNewTextChild(l_parent,
NULL,
(const xmlChar *) "operation_set",
(const xmlChar *) pipe.str().c_str());
xmlSetProp(child,(const xmlChar *) "model", (const xmlChar *) coding.c_str());
pipe.str("");
pipe.clear();
}
if (V.MO)
{
dh->write(V,"machine_order",pipe);
child = xmlNewTextChild(l_parent,
NULL,
(const xmlChar *) "machine_order",
(const xmlChar *) pipe.str().c_str());
xmlSetProp(child,(const xmlChar *) "model", (const xmlChar *) coding.c_str());
pipe.str("");
pipe.clear();
}
if (V.RD)
{
dh->write(V,"release_times",pipe);
child = xmlNewTextChild(l_parent,
NULL,
(const xmlChar *) "release_times",
(const xmlChar *) pipe.str().c_str());
xmlSetProp(child,(const xmlChar *) "model", (const xmlChar *) coding.c_str());
pipe.str("");
pipe.clear();
}
if (V.DD)
{
dh->write(V,"due_dates",pipe);
child = xmlNewTextChild(l_parent,
NULL,
(const xmlChar *) "due_dates",
(const xmlChar *) pipe.str().c_str());
pipe.str("");
pipe.clear();
}
if (V.WI)
{
dh->write(V,"weights",pipe);
child = xmlNewTextChild(l_parent,
NULL,
(const xmlChar *) "weights",
(const xmlChar *) pipe.str().c_str());
xmlSetProp(child,(const xmlChar *) "model", (const xmlChar *) coding.c_str());
pipe.str("");
pipe.clear();
}
if (V.WI2)
{
dh->write(V,"weights2",pipe);
child = xmlNewTextChild(l_parent,
NULL,
(const xmlChar *) "weights_2",
(const xmlChar *) pipe.str().c_str());
xmlSetProp(child,(const xmlChar *) "model", (const xmlChar *) coding.c_str());
pipe.str("");
pipe.clear();
}
if (V.EXTRA)
{
dh->write(V,"extra",pipe);
child = xmlNewTextChild(l_parent,
NULL,
(const xmlChar *) "extra",
(const xmlChar *) pipe.str().c_str());
xmlSetProp(child,(const xmlChar *) "model", (const xmlChar *) coding.c_str());
}
delete dh;
}
void LisaXmlFile::write(const Lisa_Schedule& S)
{
xmlNodePtr l_parent;
stringstream pipe;
if(xmlStrEqual(Hook->name, (const xmlChar *) "schedule"))
l_parent = Hook;
else
l_parent = xmlAddChild(Hook,xmlNewNode(NULL,(const xmlChar *) "schedule"));
int n = S.get_n(), m = S.get_m();
pipe.str(""); pipe << m;
xmlSetProp(l_parent,(const xmlChar *) "m", (const xmlChar *) pipe.str().c_str());
pipe.str(""); pipe << n;
xmlSetProp(l_parent,(const xmlChar *) "n", (const xmlChar *) pipe.str().c_str());
pipe.str("");
pipe.clear();
if(S.semiactive == 1)
xmlSetProp(l_parent,(const xmlChar *) "semiactive", (const xmlChar *) "yes");
else
xmlSetProp(l_parent,(const xmlChar *) "semiactive", (const xmlChar *) "no");
xmlNodePtr child;
Lisa_DataHandler* dh = Lisa_IO_Factory::createHandler(coding);
if(dh == NULL)
{
raiseError(BAD_MODEL,coding);
return;
}
if(S.LR)
{
dh->write(S,"plan",pipe);
child = xmlNewTextChild(l_parent,
NULL,
(const xmlChar *) "plan",
(const xmlChar *) pipe.str().c_str());
xmlSetProp(child,(const xmlChar *) "model", (const xmlChar *) coding.c_str());
pipe.str("");
pipe.clear();
}
if(S.NMO)
{
dh->write(S,"machine_sequences",pipe);
child = xmlNewTextChild(l_parent,
NULL,
(const xmlChar *) "machine_sequences",
(const xmlChar *) pipe.str().c_str());
xmlSetProp(child,(const xmlChar *) "model", (const xmlChar *) coding.c_str());
pipe.str("");
pipe.clear();
}
if(S.NJO)
{
dh->write(S,"job_sequences",pipe);
child = xmlNewTextChild(l_parent,
NULL,
(const xmlChar *) "job_sequences",
(const xmlChar *) pipe.str().c_str());
xmlSetProp(child,(const xmlChar *) "model", (const xmlChar *) coding.c_str());
pipe.str("");
pipe.clear();
}
if(S.CIJ)
{
dh->write(S,"completion_times",pipe);
child = xmlNewTextChild(l_parent,
NULL,
(const xmlChar *) "completion_times",
(const xmlChar *) pipe.str().c_str());
xmlSetProp(child,(const xmlChar *) "model", (const xmlChar *) coding.c_str());
}
delete dh;
}
void LisaXmlFile::write(const Lisa_ScheduleNode& S)
{
if(S.actual_schedule)
write(*(S.actual_schedule));
}
void LisaXmlFile::write(const Lisa_ControlParameters& Cp)
{
xmlNodePtr l_parent;
stringstream pipe;
if(xmlStrEqual(Hook->name, (const xmlChar *) "controls"))
l_parent = Hook;
else
l_parent = xmlAddChild(Hook,xmlNewNode(NULL,(const xmlChar *) "controls"));
//+++++++++++++++++++++++++++++++++++++++
// ++ copied from lsa-write +++++++++++++
//+++++++++++++++++++++++++++++++++++++++
//copy all contents: this is totally stupid, but reading a list would
// change its internal bookmark and we are in a const method here
Lisa_List<string> kl, sl;
Lisa_List<double> dl;
Lisa_List<long> il;
kl=Cp.IntKeyList;
xmlNodePtr child;
xmlChar* conv_name, *conv_value;
if (!kl.empty())
{
il=Cp.IntList; kl.reset(); il.reset();
//do strm << "long " << kl.get() << " " << il.get() << "\n";
do {
pipe.str("");pipe << il.get();
conv_name = string2xmlChar(kl.get());
conv_value = string2xmlChar(pipe.str());
if(!conv_name)
conv_name = xmlStrdup((const xmlChar*) kl.get().c_str());
if(!conv_value)
conv_value = xmlStrdup((const xmlChar*) pipe.str().c_str());
child = xmlAddChild(l_parent,
xmlNewNode(NULL,(const xmlChar *) "parameter"));
xmlSetProp(child, (const xmlChar *) "type", (const xmlChar *) "integer");
xmlSetProp(child, (const xmlChar *) "name", conv_name);
xmlSetProp(child, (const xmlChar *) "value",conv_value);
xmlFree(conv_name);
xmlFree(conv_value);
}
while (kl.next(), il.next());
}
kl=Cp.DoubleKeyList;
if (!kl.empty())
{
dl=Cp.DoubleList; kl.reset(); dl.reset();
do {
pipe.str("");pipe << dl.get();
conv_name = string2xmlChar(kl.get());
conv_value = string2xmlChar(pipe.str());
if(!conv_name)
conv_name = xmlStrdup((const xmlChar*) kl.get().c_str());
if(!conv_value)
conv_value = xmlStrdup((const xmlChar*) pipe.str().c_str());
child = xmlAddChild(l_parent,
xmlNewNode(NULL,(const xmlChar *) "parameter"));
xmlSetProp(child, (const xmlChar *) "type", (const xmlChar *) "real");
xmlSetProp(child, (const xmlChar *) "name", conv_name);
xmlSetProp(child, (const xmlChar *) "value",conv_value);
xmlFree(conv_name);
xmlFree(conv_value);
}
while (kl.next(), dl.next());
}
kl=Cp.StringKeyList;
if (!kl.empty())
{
sl=Cp.StringList; kl.reset(); sl.reset();
//do strm << "string " << kl.get() << " " << sl.get() << "\n";
do {
conv_name = string2xmlChar(kl.get());
conv_value = string2xmlChar(sl.get());
if(!conv_name)
conv_name = xmlStrdup((const xmlChar*) kl.get().c_str());
if(!conv_value)
conv_value = xmlStrdup((const xmlChar*) sl.get().c_str());
child = xmlAddChild(l_parent,
xmlNewNode(NULL,(const xmlChar *) "parameter"));
xmlSetProp(child, (const xmlChar *) "type", (const xmlChar *) "string");
xmlSetProp(child, (const xmlChar *) "name", conv_name);
xmlSetProp(child, (const xmlChar *) "value",conv_value);
xmlFree(conv_name);
xmlFree(conv_value);
}
while (kl.next(), sl.next());
}
//++++++++++++++++++++++++++++++++++++++++++
}
void LisaXmlFile::write(const Lisa_Graph& G)
{
xmlNodePtr graphPtr;
stringstream pipe;
pipe << G.get_vertices();
xmlSetProp(graphPtr,(const xmlChar *) "n", (const xmlChar *) pipe.str().c_str());
xmlSetProp(graphPtr,(const xmlChar *) "model", (const xmlChar *) coding.c_str());
//get the hanlder for the model
Lisa_DataHandler* dh = Lisa_IO_Factory::createHandler(coding);
if(dh == NULL)
{
raiseError(BAD_MODEL,coding);
return;
}
pipe.str("");
pipe.clear();
dh->write(G,"graph",pipe);
delete dh;
graphPtr = Hook;
if(xmlStrEqual(Hook->name, (const xmlChar *) "graph"))
graphPtr = xmlAddChild(Hook,xmlNewText((const xmlChar *) pipe.str().c_str()));
else
xmlNewTextChild(Hook,
NULL,
(const xmlChar *) "graph",
(const xmlChar *) pipe.str().c_str());
}
bool LisaXmlFile::read(Lisa_Values& V)
{
if(!xmlStrEqual(Hook->name, (const xmlChar *) "values"))
{
raiseError(BAD_ROOT,"values",(const char*) Hook->name);
return false;
}
xmlNodePtr cur = Hook;
stringstream pipe;
int n,m;
bool okay = true;
xmlChar* attr_m = xmlGetProp(cur,(const xmlChar*) "m");
xmlChar* attr_n = xmlGetProp(cur,(const xmlChar*) "n");
if(attr_m)
{
pipe.clear();
pipe.str("");
pipe << (char*) attr_m;
pipe >> m;
if(pipe.fail())
okay = false;
xmlFree(attr_m);
}
else okay = false;
if(attr_n)
{
pipe.clear();
pipe.str("");
pipe << (char*) attr_n;
pipe >> n;
if(pipe.fail())
okay = false;
xmlFree(attr_n);
}
else okay = false;
if(okay)
V.init(n,m);
else
{
raiseError(MISSING_SIZE,"values");
return false;
}
string node_name, content, model_name;
xmlChar* c_model;
for(xmlNodePtr child = cur->children;child;child=child->next)
{
if(child->type != XML_ELEMENT_NODE)
continue;
node_name = (const char*) child->name;
c_model = xmlGetProp(child,(const xmlChar*) "model");
if(!c_model)
model_name = Lisa_NativeDataHandler::getName();
else
{
model_name = (const char*) c_model;
xmlFree(c_model);
}
Lisa_DataHandler* dh = Lisa_IO_Factory::createHandler(model_name);
if(dh == NULL)
{
raiseError(BAD_MODEL,model_name);
return false;
}
pipe.clear();
pipe.str("");
//retrieve all text content of this node
content = "";
for(xmlNodePtr text = child->children; text; text=text->next)
{
if(text->type == XML_TEXT_NODE)
{
content = (text->content) ? (const char*) text->content : "";
pipe << content;
}
}
if(!dh->read(V,node_name,pipe))
{
raiseError(BAD_NODE,node_name);
delete dh;
return false;
}
delete dh;
}
return true;
}
bool LisaXmlFile::read(Lisa_Schedule& S)
{
if(!xmlStrEqual(Hook->name, (const xmlChar *) "schedule"))
{
raiseError(BAD_ROOT,"schedule",(const char*) Hook->name);
return false;
}
xmlNodePtr cur = Hook;
stringstream pipe;
int n,m;
bool okay = true;
xmlChar* attr_m = xmlGetProp(cur,(const xmlChar*) "m");
xmlChar* attr_n = xmlGetProp(cur,(const xmlChar*) "n");
xmlChar* attr_sem = xmlGetProp(cur,(const xmlChar*) "semiactive");
if(attr_m)
{
pipe.clear();
pipe.str("");
pipe << (char*) attr_m;
pipe >> m;
if(pipe.fail())
okay = false;
xmlFree(attr_m);
}
else okay = false;
if(attr_n)
{
pipe.clear();
pipe.str("");
pipe << (char*) attr_n;
pipe >> n;
if(pipe.fail())
okay = false;
xmlFree(attr_n);
}
else okay = false;
if(okay)
S.init(n,m);
else
{
raiseError(MISSING_SIZE,"schedule");
return false;
}
S.semiactive=0;
if(attr_sem && xmlStrEqual(attr_sem, (const xmlChar *) "yes"))
{
S.semiactive=1;
xmlFree(attr_sem);
}
string node_name, content, model_name;
xmlChar *c_model;
for(xmlNodePtr child = cur->children;child;child=child->next)
{
if(child->type != XML_ELEMENT_NODE)
continue;
node_name = (const char*) child->name;
c_model = xmlGetProp(child,(const xmlChar*) "model");
if(!c_model)
model_name = Lisa_NativeDataHandler::getName();
else
{
model_name = (const char*) c_model;
xmlFree(c_model);
}
Lisa_DataHandler* dh = Lisa_IO_Factory::createHandler(model_name);
if(dh == NULL)
{
raiseError(BAD_MODEL,model_name);
return false;
}
pipe.clear();
pipe.str("");
//retrieve all text content of this node
content = "";
for(xmlNodePtr text = child->children; text; text=text->next)
{
if(text->type == XML_TEXT_NODE)
{
content = (text->content) ? (const char*) text->content : "";
pipe << content;
}
}
if(!dh->read(S,node_name,pipe))
{
raiseError(BAD_NODE,node_name);
delete dh;
return false;
}
delete dh;
}
S.valid = 1;
return true;
}
bool LisaXmlFile::read(Lisa_ScheduleNode& S)
{
if(!S.actual_schedule)
S.actual_schedule = new Lisa_Schedule();
if(!read(*(S.actual_schedule)))
{
delete S.actual_schedule;
S.actual_schedule = NULL;
return false;
}
return true;
}
bool LisaXmlFile::read(Lisa_ControlParameters& Cp)
{
if(!xmlStrEqual(Hook->name, (const xmlChar *) "controls"))
{
raiseError(BAD_ROOT,"controls",(const char*) Hook->name);
return false;
}
xmlNodePtr cur = Hook;
stringstream pipe;
long vl;
double vd;
string para_type;
string para_name;
string para_value;
xmlChar* c_name,*c_value,*c_type;;
for(cur = cur->children; cur; cur = cur->next)
{
if(cur->type !=XML_ELEMENT_NODE)
continue;
if(!xmlStrEqual(cur->name, (const xmlChar*) "parameter"))
continue;
//get type
para_type = "";
if((c_type = xmlGetProp(cur, (const xmlChar*) "type")) != NULL){
xmlChar2string(c_type,para_type);
xmlFree(c_type);
}
para_name = "";
if((c_name = xmlGetProp(cur, (const xmlChar*) "name")) != NULL){
xmlChar2string(c_name,para_name);
xmlFree(c_name);
}
para_value = "";
if((c_value = xmlGetProp(cur, (const xmlChar*) "value")) != NULL){
xmlChar2string(c_value,para_value);
xmlFree(c_value);
}
pipe.clear();
pipe.str("");
pipe << para_value;
if(para_type == "integer")
{
pipe >> vl;
if(!pipe.fail())
Cp.add_key(para_name,vl);
else
cerr << "conversion error attribute value : " << para_name << endl;
}
else if(para_type == "real")
{
pipe >> vd;
if(!pipe.fail())
Cp.add_key(para_name,vd);
else
cerr << "conversion error in attribute value : " << para_name << endl;
}
else if(para_type == "string")
{
Cp.add_key(para_name,pipe.str());
}
else
continue;
}
return true;
}
bool LisaXmlFile::read(Lisa_Graph& G)
{
if(!xmlStrEqual(Hook->name, (const xmlChar *) "graph"))
{
raiseError(BAD_ROOT,"graph",(const char*) Hook->name);
return false;
}
xmlNodePtr cur = Hook;
stringstream pipe;
int n;
bool okay = true;
xmlChar* attr_n = xmlGetProp(cur,(const xmlChar*) "n");
if(attr_n)
{
pipe.clear();
pipe.str("");
pipe << (char*) attr_n;
pipe >> n;
if(pipe.fail())
okay = false;
xmlFree(attr_n);
}
else
okay = false;
if(okay)
G.init(n);
else
{
raiseError(MISSING_SIZE,"graph");
return false;
}
xmlChar* c_model = xmlGetProp(cur,(const xmlChar*) "model");
string model_name;
if(!c_model)
model_name = Lisa_NativeDataHandler::getName();
else
{
model_name = (const char*) c_model;
xmlFree(c_model);
}
Lisa_DataHandler* dh = Lisa_IO_Factory::createHandler(model_name);
if(dh == NULL)
{
raiseError(BAD_MODEL,model_name);
return false;
}
pipe.clear();
pipe.str("");
string content;
for(xmlNodePtr text = cur->children; text; text=text->next)
{
if(text->type == XML_TEXT_NODE)
{
content = (text->content) ? (const char*) text->content : "";
pipe << content;
}
}
if(!dh->read(G,"graph",pipe))
{
raiseError(BAD_NODE,"graph");
delete dh;
return false;
}
delete dh;
return true;
}
bool LisaXmlFile::read_ExtAlg(Lisa_ExtAlg& Alg, const string& filename)
{
xmlDocPtr Document = xmlParseFile(filename.c_str());
if(Document == NULL)
{
raiseError(LIB_XML,"Failed to parse file \"" + filename + "\"");
return false;
}
xmlNodePtr root = NULL;
stringstream pipe;
root = xmlDocGetRootElement(Document);
if(root == NULL || !xmlStrEqual(root->name, (const xmlChar*) "algorithm"))
{
if(!root)
raiseError(READ_EMPTY_DOCUMENT,filename);
else
raiseError(BAD_ROOT,"algorithm", (const char*) root->name);
xmlFreeDoc(Document);
return false;
}
string converted;
xmlChar* prop = xmlGetProp(root,(const xmlChar*) "name");
if(prop)
{
if(!xmlChar2string(prop,converted))
converted = (const char*) prop;
Alg.name = converted;
xmlFree(prop);
}
prop = xmlGetProp(root,(const xmlChar*) "type");
if(prop)
{
if(!xmlChar2string(prop,converted))
converted = (const char*) prop;
Alg.type = converted;
xmlFree(prop);
}
prop = xmlGetProp(root,(const xmlChar*) "call");
if(prop)
{
if(!xmlChar2string(prop,converted))
converted = (const char*) prop;
Alg.call = converted;
xmlFree(prop);
}
prop = xmlGetProp(root,(const xmlChar*) "code");
if(prop)
{
if(!xmlChar2string(prop,converted))
converted = (const char*) prop;
Alg.code = converted;
xmlFree(prop);
}
prop = xmlGetProp(root,(const xmlChar*) "help_file");
if(prop)
{
if(!xmlChar2string(prop,converted))
converted = (const char*) prop;
Alg.helpFile = converted;
xmlFree(prop);
}
Alg.handle_heuristic.clear();
Alg.handle_exact.clear();
Lisa_ProblemType P;
LisaXmlFile xmlFile;
string node_name;
for(xmlNodePtr child = root->children;child;child=child->next)
{
if(child->type != XML_ELEMENT_NODE)
continue;
node_name = (const char*) child->name;
P.reset();
if(node_name == "heuristic")
{
for(xmlNodePtr prob = child->children;prob;prob=prob->next)
{
if(prob->type != XML_ELEMENT_NODE)
continue;
if(xmlStrEqual(prob->name,(const xmlChar*) "problem"))
{
Alg.handle_heuristic.push_back(P);
//changing hook -> take care
xmlFile.Hook = prob;
if(!xmlFile.read(Alg.handle_heuristic.back()))
return false;
}
}
}
else if(node_name == "exact")
{
for(xmlNodePtr prob = child->children;prob;prob=prob->next)
{
if(prob->type != XML_ELEMENT_NODE)
continue;
if(xmlStrEqual(prob->name,(const xmlChar*) "problem"))
{
Alg.handle_exact.push_back(P);
//changing hook -> take care
xmlFile.Hook = prob;
if(!xmlFile.read(Alg.handle_exact.back()))
return false;
}
}
}
else if(node_name == "alg_controls")
{
string cntr_type, cnt_name, cnt_caption;
for(xmlNodePtr cntr = child->children;cntr;cntr=cntr->next)
{
if(cntr->type != XML_ELEMENT_NODE)
continue;
xmlChar* attr;
cntr_type = (const char*) cntr->name;
if(cntr_type == "integer")
{
Integer_Control IntC;
//name attribute
attr = xmlGetProp(cntr,(const xmlChar*) "name");
if(attr)
{
if(!xmlChar2string(attr,converted))
converted = (const char*) prop;
IntC.name = converted;
xmlFree(attr);
}
else
{
raiseError(MISSING_ATTRIBUTE,"name");
return false;
}
//caption attribute
attr = xmlGetProp(cntr,(const xmlChar*) "caption");
if(attr)
{
if(!xmlChar2string(attr,converted))
converted = (const char*) prop;
IntC.caption = converted;
xmlFree(attr);
}
else
{
raiseError(MISSING_ATTRIBUTE,"caption");
return false;
}
//default_value
attr = xmlGetProp(cntr,(const xmlChar*) "default");
if(attr)
{
pipe.str("");
pipe.clear();
pipe << (char*) attr;
pipe >> IntC.default_value;
xmlFree(attr);
if(pipe.fail())
{
raiseError(BAD_ATTR_VALUE,"default",(const char*) attr);
return false;
}
}
else
{
raiseError(MISSING_ATTRIBUTE,"default");
return false;
}
Alg.Integer_Controls.push_back(IntC);
}
else if(cntr_type == "real")
{
Real_Control RealC;
//name attribute
attr = xmlGetProp(cntr,(const xmlChar*) "name");
if(attr)
{
if(!xmlChar2string(attr,converted))
converted = (const char*) prop;
RealC.name = converted;
xmlFree(attr);
}
else
{
raiseError(MISSING_ATTRIBUTE,"name");
return false;
}
//caption attribute
attr = xmlGetProp(cntr,(const xmlChar*) "caption");
if(attr)
{
if(!xmlChar2string(attr,converted))
converted = (const char*) prop;
RealC.caption = converted;
xmlFree(attr);
}
else
{
raiseError(MISSING_ATTRIBUTE,"caption");
return false;
}
//default_value
attr = xmlGetProp(cntr,(const xmlChar*) "default");
if(attr)
{
pipe.str("");
pipe.clear();
pipe << (char*) attr;
pipe >> RealC.default_value;
xmlFree(attr);
if(pipe.fail())
{
raiseError(BAD_ATTR_VALUE,"default",(const char*)attr);
return false;
}
}
else
{
raiseError(MISSING_ATTRIBUTE,"default");
return false;
}
Alg.Real_Controls.push_back(RealC);
}
else if(cntr_type == "choice")
{
Choice_Control ChoiceC;
//name attribute
attr = xmlGetProp(cntr,(const xmlChar*) "name");
if(attr)
{
if(!xmlChar2string(attr,converted))
converted = (const char*) prop;
ChoiceC.name = converted;
xmlFree(attr);
}
else
{
raiseError(MISSING_ATTRIBUTE,"name");
return false;
}
//caption attribute
attr = xmlGetProp(cntr,(const xmlChar*) "caption");
if(attr)
{
if(!xmlChar2string(attr,converted))
converted = (const char*) prop;
ChoiceC.caption = converted;
xmlFree(attr);
}
else
{
raiseError(MISSING_ATTRIBUTE,"caption");
return false;
}
//parse items
for(xmlNodePtr item=cntr->children;item;item=item->next)
{
if(item->type != XML_ELEMENT_NODE)
continue;
attr = xmlGetProp(item,(const xmlChar*) "name");
if(attr)
{
if(!xmlChar2string(attr,converted))
converted = (const char*) prop;
ChoiceC.items.push_back(converted);
xmlFree(attr);
}
else
{
raiseError(MISSING_ATTRIBUTE,"name");
return false;
}
}
Alg.Choice_Controls.push_back(ChoiceC);
}
else if(cntr_type == "fixed")
{
Lisa_ExtAlg::Fixed_Control FixC;
attr = xmlGetProp(cntr,(const xmlChar*) "name");
if(attr)
{
if(!xmlChar2string(attr,converted))
converted = (const char*) prop;
FixC.first = converted;
xmlFree(attr);
}
else
{
raiseError(MISSING_ATTRIBUTE,"name");
return false;
}
attr = xmlGetProp(cntr,(const xmlChar*) "value");
if(attr)
{
if(!xmlChar2string(attr,converted))
converted = (const char*) prop;
FixC.second = converted;
xmlFree(attr);
}
else
{
raiseError(MISSING_ATTRIBUTE,"name");
return false;
}
Alg.Fixed_Controls.push_back(FixC);
}
else
{
raiseError(BAD_NODE,cntr_type);
return false;
}
}
}
//ignore other stuff
}
return true;
}
void LisaXmlFile::write_ExtAlg(const Lisa_ExtAlg& Alg, const string& filename)
{
xmlDocPtr Document = xmlNewDoc((const xmlChar* ) "1.0");
xmlNodePtr Root = xmlNewDocRawNode(Document,
NULL,
(const xmlChar* ) "algorithm",
NULL);
xmlDocSetRootElement(Document, Root);
//fill out the form
Root = xmlDocGetRootElement(Document);
stringstream pipe;
LisaXmlFile xmlFile;
xmlChar* converted;
converted = string2xmlChar(Alg.name);
if(!converted)
converted = xmlStrdup((const xmlChar*) Alg.name.c_str());
xmlSetProp(Root, (const xmlChar*) "name", converted);
xmlFree(converted);
converted = string2xmlChar(Alg.type);
if(!converted)
converted = xmlStrdup((const xmlChar*) Alg.type.c_str());
xmlSetProp(Root, (const xmlChar*) "type", (const xmlChar*) Alg.type.c_str());
xmlFree(converted);
converted = string2xmlChar(Alg.call);
if(!converted)
converted = xmlStrdup((const xmlChar*) Alg.call.c_str());
xmlSetProp(Root, (const xmlChar*) "call", (const xmlChar*) Alg.call.c_str());
xmlFree(converted);
converted = string2xmlChar(Alg.code);
if(!converted)
converted = xmlStrdup((const xmlChar*) Alg.code.c_str());
xmlSetProp(Root, (const xmlChar*) "code", (const xmlChar*) Alg.code.c_str());
xmlFree(converted);
converted = string2xmlChar(Alg.helpFile);
if(!converted)
converted = xmlStrdup((const xmlChar*) Alg.helpFile.c_str());
xmlSetProp(Root, (const xmlChar*) "help_file", (const xmlChar*) Alg.helpFile.c_str());
xmlFree(converted);
xmlNodePtr cur;
if(!Alg.handle_heuristic.empty())
{
cur = xmlAddChild(Root,xmlNewNode(NULL,(const xmlChar*) "heuristic"));
for(unsigned i = 0; i < Alg.handle_heuristic.size(); i++)
{
//changing hook -> take care
xmlFile.Hook = cur;
xmlFile.write(Alg.handle_heuristic[i]);
}
}
if(!Alg.handle_exact.empty())
{
cur = xmlAddChild(Root,xmlNewNode(NULL,(const xmlChar*) "exact"));
for(unsigned i = 0; i < Alg.handle_exact.size(); i++)
{
//changing hook -> take care
xmlFile.Hook = cur;
xmlFile.write(Alg.handle_exact[i]);
}
}
cur = xmlAddChild(Root,xmlNewNode(NULL,(const xmlChar*) "alg_controls"));
xmlNodePtr cntr;
for(unsigned i = 0; i < Alg.Integer_Controls.size(); i++)
{
cntr = xmlAddChild(cur,xmlNewNode(NULL,(const xmlChar*) "integer"));
converted = string2xmlChar(Alg.Integer_Controls[i].name);
if(!converted)
converted = xmlStrdup((const xmlChar*) Alg.Integer_Controls[i].name.c_str());
xmlSetProp(cntr, (const xmlChar*) "name", converted);
xmlFree(converted);
converted = string2xmlChar(Alg.Integer_Controls[i].caption);
if(!converted)
converted = xmlStrdup((const xmlChar*) Alg.Integer_Controls[i].caption.c_str());
xmlSetProp(cntr, (const xmlChar*) "caption", converted);
xmlFree(converted);
pipe.str("");
pipe << Alg.Integer_Controls[i].default_value;
xmlSetProp(cntr, (const xmlChar*) "default", (const xmlChar*) pipe.str().c_str());
}
for(unsigned i = 0; i < Alg.Real_Controls.size(); i++)
{
cntr = xmlAddChild(cur,xmlNewNode(NULL,(const xmlChar*) "real"));
converted = string2xmlChar(Alg.Real_Controls[i].name);
if(!converted)
converted = xmlStrdup((const xmlChar*) Alg.Real_Controls[i].name.c_str());
xmlSetProp(cntr, (const xmlChar*) "name", converted);
xmlFree(converted);
converted = string2xmlChar(Alg.Real_Controls[i].caption);
if(!converted)
converted = xmlStrdup((const xmlChar*) Alg.Real_Controls[i].caption.c_str());
xmlSetProp(cntr, (const xmlChar*) "caption", converted);
xmlFree(converted);
pipe.str("");
pipe << Alg.Real_Controls[i].default_value;
xmlSetProp(cntr, (const xmlChar*) "default", (const xmlChar*) pipe.str().c_str());
}
for(unsigned i = 0; i < Alg.Choice_Controls.size(); i++)
{
cntr = xmlAddChild(cur,xmlNewNode(NULL,(const xmlChar*) "choice"));
converted = string2xmlChar(Alg.Choice_Controls[i].name);
if(!converted)
converted = xmlStrdup((const xmlChar*) Alg.Choice_Controls[i].name.c_str());
xmlSetProp(cntr, (const xmlChar*) "name", converted);
xmlFree(converted);
converted = string2xmlChar(Alg.Choice_Controls[i].caption);
if(!converted)
converted = xmlStrdup((const xmlChar*) Alg.Choice_Controls[i].caption.c_str());
xmlSetProp(cntr, (const xmlChar*) "caption", converted);
xmlFree(converted);
xmlNodePtr item;
for(unsigned j = 0; j < Alg.Choice_Controls[i].items.size(); j++)
{
item = xmlAddChild(cntr,xmlNewNode(NULL,(const xmlChar*) "item"));
xmlSetProp(item, (const xmlChar*) "name", (const xmlChar*) Alg.Choice_Controls[i].items[j].c_str());
}
}
for(unsigned i = 0; i < Alg.Fixed_Controls.size(); i++)
{
cntr = xmlAddChild(cur,xmlNewNode(NULL,(const xmlChar*) "fixed"));
converted = string2xmlChar(Alg.Fixed_Controls[i].first);
if(!converted)
converted = xmlStrdup((const xmlChar*) Alg.Fixed_Controls[i].first.c_str());
xmlSetProp(cntr, (const xmlChar*) "name", converted);
xmlFree(converted);
converted = string2xmlChar(Alg.Fixed_Controls[i].second);
if(!converted)
converted = xmlStrdup((const xmlChar*) Alg.Fixed_Controls[i].second.c_str());
xmlSetProp(cntr, (const xmlChar*) "value", converted);
xmlFree(converted);
}
//okay flush everything to the file
xmlNewNs(xmlDocGetRootElement(Document),
(const xmlChar*) LisaXmlFile::NAMESPACE.c_str(),
(const xmlChar*) LisaXmlFile::NAMESPACE_PREFIX.c_str());
xmlCreateIntSubset(Document,
(const xmlChar*) "algorithm",
(const xmlChar*) DTD_EXTERN_PHRASE.c_str(),
(const xmlChar*) DTD_SYSTEM_PHRASE.c_str());
xmlKeepBlanksDefault(0);
xmlIndentTreeOutput = 1;
if(xmlSaveFormatFileEnc(filename.c_str(),
Document,
LisaXmlFile::ENCODING.c_str(),
1) == -1)
{
raiseError(LIB_XML,"Failed to write file \"" + filename + "\"");
}
xmlFreeDoc(Document);
}
void LisaXmlFile::raiseError(ERROR_MODE error,
string info1,
string info2)
{
stringstream output;
switch(error)
{
case LIB_XML:
output << "Error : " << info1;
break;
case MISSING_ATTRIBUTE:
output << "LisaXMLFile - error : " << "missing attribute \"" << info1 << '\"';
break;
case BAD_ROOT:
output << "LisaXMLFile - error : Bad root-node; expected \"" << info1 << "\" - got \"" << info2 << '"';
break;
case BAD_NODE:
output << "LisaXMLFile - error : Bad node : " << info1;
break;
case BAD_ATTRIBUTE:
output << "LisaXMLFile - error : Unknown attribute : " << info1;
break;
case BAD_ATTR_VALUE:
output << "LisaXMLFile - error : Value \"" << info2 << "\" is not valid for \"" << info1 <<"\"-attribute";
break;
case MISSING_SIZE:
output << "LisaXMLFile - error : missing proper size specification in \"" << info1 << '\"';
break;
case NO_DATA_TO_WRITE:
output << "LisaXMLFile - error: trying to write empty document to file \"" << info1 << "\"";
break;
case NO_DATA_FOR_READ:
output << "LisaXMLFile - error: trying retrieve data from empty document";
break;
case WRITE_INVALID_DOCUMENT:
output << "LisaXMLFile - error: attempt to write invalid document to file \"" << info1 << "\"";
break;
case READ_EMPTY_DOCUMENT:
output << "LisaXMLFile - error: attempt to read empty document from file \"" << info1 << "\"";
break;
case READ_DOC_OBJ_MISSMATCH:
output << "LisaXMLFile - error: attempt to retrieve \"" << info1 << "\"-entry from not matching document type";
break;
case WRITE_DOC_OBJ_MISSMATCH:
output << "LisaXMLFile - error: attempt to add \"" << info1 << "\"-entry to not matching document type" ;
break;
case READ_BAD_DOC_TYPE:
output << "LisaXMLFile - error: expected \"" << info1 << "\"-document instead of \"" << info2 << "\"";
break;
case READ_ENTRY_FROM_INVALID:
output << "LisaXMLFile - error: attempt to retrieve data in inconsitent state";
break;
case WRITE_ENTRY_TO_INVALID:
output << "LisaXMLFile - error: attempt to submit data when state is inconsitent";
break;
case BAD_MODEL:
output << "LisaXMLFile - error: cannot handle data model \"" << info1 << "\"";
break;
default:
output << "error: LisaXmlFile encountered unknown error";
break;
}
cerr << output.str() << endl;
}
xmlChar* string2xmlChar(const string& input){
//cout << "converting string \"" << input << "\"\t\t-> ";
int temp, size, out_size;
temp = size = input.size() + 1; /*terminating null included*/
out_size = size*2-1; /*terminating null is just one byte*/
xmlChar* out = (xmlChar*) xmlMalloc((sizeof(xmlChar))* out_size);
// returns -1 or -2 on error, otherwise, depending in libxml2 version
// 0 or number of bytes written
if (isolat1ToUTF8(out, &out_size, (const unsigned char*) input.c_str(), &temp) < 0 || temp-size) {
xmlFree(out);
cerr << "Warning : string2xmlChar : Failed to encode token \"" << input << "\"" << endl;
return NULL;
}
//cout << '\"' << (char*) out << '\"' << endl;
return out;
}
bool xmlChar2string(const xmlChar* in , string& result){
//cout << "converting string \"" << (const char*) in << "\"\t\t-> ";
int chars = xmlUTF8Strlen(in);
int in_len = xmlUTF8Strsize(in, chars);
int out_len = chars + 1;
unsigned char* out = new unsigned char[out_len];
// returns -1 or -2 on error, otherwise, depending in libxml2 version
// 0 or number of bytes written
if(UTF8Toisolat1(out, &out_len, in, &in_len) < 0){
cerr << "Warning : xmlChar2string : Failed to decode token \"" << (char*) in << "\"" << endl;
delete[] out;
return false;
}
out[out_len] = '\0';
result = reinterpret_cast<char*>(out);
delete[] out;
return true;
}
bool LisaXmlFile::validateDocument()
{
if(Doc == NULL)
return false;
//get the document's dtd
xmlDtdPtr doc_dtd = xmlGetIntSubset(Doc);
xmlDtdPtr parsed_dtd = NULL;
//try to use system dtd if not found
if(doc_dtd) //foun dtd ... try parse it
{
parsed_dtd = xmlParseDTD (doc_dtd->ExternalID, doc_dtd->SystemID);
}
xmlValidCtxt context;
context.userData = stderr;
context.error = (xmlValidityErrorFunc) fprintf;
context.warning = (xmlValidityWarningFunc) fprintf;
if(parsed_dtd == NULL) //no dtd found
cout << "LisaXmlFile:: WARNING : Dtd of document not available, using internal Dtd." << endl;
else
{
int ret = xmlValidateDtd(&context, Doc, parsed_dtd);
xmlFreeDtd(parsed_dtd);
if(ret)
return true;
return false;
}
if(DtdPtr == NULL)
{
cout << "LisaXmlFile:: ERROR : Don't have Dtd to validate." << endl;
return false;
}
if(xmlValidateDtd(&context, Doc, DtdPtr))
return true;
return false;
}
| gpl-2.0 |
shiminghua/front_end_practice | webpack.dist.debug.config.js | 1623 | 'use strict';
// process.env.NODE_ENV = 'production';
let Webpack = require('webpack');
let Path = require('path');
let PackageConfig = require('./package.json');
let Configure = require('./webpack/configure');
let WebpackBaseConfig = require('./webpack.base.config');
let WebpackDistDebugConfig = WebpackBaseConfig;
let webpackBasePlugins = WebpackBaseConfig.plugins;
let webpackEntrys = WebpackBaseConfig.entry;
for (let key in webpackEntrys) {
// 'webpack/hot/only-dev-server'
webpackEntrys[key].unshift('webpack-dev-server/client?' + Configure.http, 'webpack/hot/dev-server');
}
let pluginsArr = [
// 热加载
new Webpack.HotModuleReplacementPlugin(),
// js压缩
new Webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
},
comments: false,
except: ['$', 'exports', 'require'],
mangle: true
})
];
WebpackDistDebugConfig.plugins = webpackBasePlugins.concat(pluginsArr);
WebpackDistDebugConfig.entry = webpackEntrys;
// webpack-dev-server 配置
WebpackDistDebugConfig.devServer = {
hot: true,
host: Configure.host,
port: Configure.port,
inline: true,
progress: true,
contentBase: Configure.build,
outputPath: Configure.build,
publicPath: WebpackDistDebugConfig.output.publicPath,
stats: {
color: true
},
historyApiFallback: true
};
console.log('----------------------WebpackDistDebugConfig:\n\r', WebpackDistDebugConfig, '\n\r-------------NODE_ENV:\n\r', process.env.NODE_ENV, '\n\r');
module.exports = WebpackDistDebugConfig;
| gpl-2.0 |
arg0/rss | public.php | 1619 | <?php
set_include_path(dirname(__FILE__) ."/include" . PATH_SEPARATOR .
get_include_path());
/* remove ill effects of magic quotes */
if (get_magic_quotes_gpc()) {
function stripslashes_deep($value) {
$value = is_array($value) ?
array_map('stripslashes_deep', $value) : stripslashes($value);
return $value;
}
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
$_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
require_once "sessions.php";
require_once "functions.php";
require_once "sanity_check.php";
require_once "config.php";
require_once "db.php";
require_once "db-prefs.php";
startup_gettext();
$script_started = microtime(true);
$link = db_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (!init_connection($link)) return;
if (ENABLE_GZIP_OUTPUT && function_exists("ob_gzhandler")) {
ob_start("ob_gzhandler");
}
$method = $_REQUEST["op"];
global $pluginhost;
$override = $pluginhost->lookup_handler("public", $method);
if ($override) {
$handler = $override;
} else {
$handler = new Handler_Public($link, $_REQUEST);
}
if (implements_interface($handler, "IHandler") && $handler->before($method)) {
if ($method && method_exists($handler, $method)) {
$handler->$method();
} else if (method_exists($handler, 'index')) {
$handler->index();
}
$handler->after();
return;
}
header("Content-Type: text/plain");
print json_encode(array("error" => array("code" => 7)));
// We close the connection to database.
db_close($link);
?>
| gpl-2.0 |
daiogo/LaserHarpists | app/LaserHarpists/app/src/main/java/com/rmscore/laserharpists/Welcome.java | 2053 | package com.rmscore.laserharpists;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import com.rmscore.bases.BaseActivity;
public class Welcome extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wellcome);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public void onBackPressed() {
UnbindService();
}
@Override
public void ServiceStarted() {
super.ServiceStarted();
Button btnLearnToPlay = (Button) findViewById(R.id.btnLearnToPlay);
btnLearnToPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (rmsService.IsBluetoothConnected()) {
Intent intent = new Intent(Welcome.this, ScoreGame.class);
startActivity(intent);
}
else {
MakeBluetoothHappen();
}
}
});
Button btnFreeStyle = (Button) findViewById(R.id.btnFreeStyle);
btnFreeStyle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (rmsService.IsBluetoothConnected()) {
Intent intent = new Intent(Welcome.this, FreeStyle.class);
startActivity(intent);
}
else {
MakeBluetoothHappen();
}
}
});
ImageButton imgBtnAngle = (ImageButton) findViewById(R.id.imgBtnAngle);
imgBtnAngle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MakeBluetoothHappen();
}
});
}
}
| gpl-2.0 |
steffe/MT4J_KTSI | ktsi/ch/mitoco/main/BuildRadialMenu.java | 27786 | /**
*
*/
package ch.mitoco.main;
import gov.pnnl.components.visibleComponents.widgets.radialMenu.MTRadialMenu;
import gov.pnnl.components.visibleComponents.widgets.radialMenu.item.MTMenuItem;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.mt4j.MTApplication;
import org.mt4j.components.MTComponent;
import org.mt4j.components.StateChange;
import org.mt4j.components.StateChangeEvent;
import org.mt4j.components.StateChangeListener;
import org.mt4j.components.TransformSpace;
import org.mt4j.components.visibleComponents.widgets.MTTextArea;
import org.mt4j.components.visibleComponents.widgets.keyboard.MTTextKeyboard;
import org.mt4j.input.IMTInputEventListener;
import org.mt4j.input.inputData.InputCursor;
import org.mt4j.input.inputData.MTFingerInputEvt;
import org.mt4j.input.inputData.MTInputEvent;
import org.mt4j.input.inputProcessors.componentProcessors.tapProcessor.TapEvent;
import org.mt4j.util.MT4jSettings;
import org.mt4j.util.MTColor;
import org.mt4j.util.font.FontManager;
import org.mt4j.util.font.IFont;
import org.mt4j.util.math.ToolsMath;
import org.mt4j.util.math.Vector3D;
import org.mt4jx.components.visibleComponents.widgets.MTWebBrowser;
import ch.mitoco.components.visibleComponents.MyMTObject;
import ch.mitoco.components.visibleComponents.filechooser.FileChooser;
import ch.mitoco.components.visibleComponents.filechooser.PDFViewer;
import ch.mitoco.dataController.DataController;
import ch.mitoco.model.ModelSceneList;
import ch.mitoco.model.ModelTypDescription;
import ch.mitoco.reporting.MitocoReporting;
import ch.mitoco.startmenu.SceneMitoco;
/**
* @author steffe
*
*/
public class BuildRadialMenu extends MTComponent{
private DataController dataController;
/**InputCursor for RadialMenu. */
private InputCursor ic;
/**RadialMenu. */
private MTRadialMenu mtRadialMenu1;
private MTApplication mtApplication;
private MitocoScene Mitoco;
/** Object Counter and Object ID. */
private int counter;
/**Filechooser objekt. */
private static FileChooser fileChooser;
private MTTextArea textarea;
/** Object Index */
private int objectindex;
/** Test Objektausrichtung */
private float endxGestureVector;
private float startxGestureVector;
private float endyGestureVector;
private float startyGestureVector;
private String filename;
/** Spezifische ScenenDaten */
private ModelSceneList sceneData;
/** Transparenc Color for keyboard (fix). */
private MTColor trans = new MTColor(0, 0, 0, 10);
/**Builds the whole Contextmenu based on RadialMenu
* It reads the Objekttyps an Builds the only the selectable Objects
*
* @param mtAppl MTApplication
* @param dataController DataController object to acces the XMLs
* @param Mitoco the Scene for drawing on it
* @param sceneData the Datamodel
* @param ic the Gesture Coordinates to calculate the direction
*/
public BuildRadialMenu(final MTApplication mtAppl, final DataController dataController, final MitocoScene Mitoco, final ModelSceneList sceneData, final InputCursor ic) {
super(mtAppl);
this.dataController = dataController;
this.mtApplication = mtAppl;
this.Mitoco = Mitoco;
this.sceneData = sceneData;
this.ic = ic;
startyGestureVector = ic.getStartPosY();
startxGestureVector = ic.getStartPosX();
endyGestureVector = ic.getCurrentEvtPosY();
endxGestureVector = ic.getCurrentEvtPosX();
/**
* Listener to create a new Object, depend on the choosen Type
*/
final IMTInputEventListener createObjectInput = new IMTInputEventListener() {
@Override
public boolean processInputEvent(final MTInputEvent inEvt) {
// Most input events in MT4j are an instance of AbstractCursorInputEvt (mouse, multi-touch..)
if (inEvt instanceof MTFingerInputEvt) {
final MTFingerInputEvt cursorInputEvt = (MTFingerInputEvt) inEvt;
switch (cursorInputEvt.getId()) {
case TapEvent.GESTURE_STARTED:
/**
* To-Do: Laden der Objettypen von XML (Solved)
*/
//System.out.println("Object add Menu: \"" + inEvt.getCurrentTarget().getName() + "\"");
System.out.println("Counter befor creation: " + counter);
for (ModelTypDescription it2 : dataController.getObjectetyps().getObjectdescription()) {
//System.out.println("Objecttyp Desc: " + it2.getObjectdescription());
//System.out.println("Objecttyp Data: " + it2.getObjectypeid());
//System.out.println("Objecttyp Menu: " + inEvt.getCurrentTarget().getName());
if (inEvt.getCurrentTarget().getName().equals(it2.getObjectdescription())){
objectindex = dataController.createObject(it2.getObjectypeid());
dataController.getMyobjectList().get(objectindex).setPositionGlobal(new Vector3D(ToolsMath.nextRandomInt(140, 800), ToolsMath.nextRandomInt(140, 700)));
System.out.println("Objekttyp gefunden");
break;
}
}
Mitoco.getCanvas().addChild(dataController.getMyobjectList().get(objectindex));
//getCanvas().addChild(myobjectList.get(counter).getMyObjectBack());
counter++;
break;
default:
break;
}
} else {
//LOG.warn("Some other event occured:" + inEvt);
}
return false;
}
};
/**
* Listener to Exit the entire Application
*/
final IMTInputEventListener exitButtonInput = new IMTInputEventListener() {
@Override
public boolean processInputEvent(final MTInputEvent inEvt) {
// Most input events in MT4j are an instance of AbstractCursorInputEvt (mouse, multi-touch..)
if (inEvt instanceof MTFingerInputEvt) {
final MTFingerInputEvt cursorInputEvt = (MTFingerInputEvt) inEvt;
switch (cursorInputEvt.getId()) {
case TapEvent.GESTURE_STARTED:
//Runtime.getRuntime().exit(0);
break;
default:
break;
}
} else {
//LOG.warn("Some other event occured:" + inEvt);
}
return false;
}
};
/**
* Listener to save a Scene in a XML File, Filename changeable over Keyboard
*/
final IMTInputEventListener saveButtonInput = new IMTInputEventListener() {
@Override
public boolean processInputEvent(final MTInputEvent inEvt) {
filename = "";
// Most input events in MT4j are an instance of AbstractCursorInputEvt (mouse, multi-touch..)
if (inEvt instanceof MTFingerInputEvt) {
final MTFingerInputEvt cursorInputEvt = (MTFingerInputEvt) inEvt;
switch (cursorInputEvt.getId()) {
case TapEvent.GESTURE_STARTED:
final IFont font = FontManager.getInstance().createFont(mtApplication, "arial.ttf",
16, // Font size
new MTColor(255, 255, 255, 255), // Font fill color
true);
MTTextKeyboard textKeyboard = new MTTextKeyboard(mtApplication);
textKeyboard.setFillColor(trans);
textKeyboard.setNoStroke(true);
textKeyboard.setPositionRelativeToParent(new Vector3D(textKeyboard.getWidthXY(TransformSpace.LOCAL) / 2, (textKeyboard.getHeightXY(TransformSpace.LOCAL) / 2) + 50));
textarea = new MTTextArea(mtApplication, 35, -20, 100, 16, font);
textarea.setInnerPadding(0);
textarea.setInnerPaddingLeft(3);
textarea.setInnerPaddingTop(0);
textarea.setText("Filename");
textarea.setFillColor(new MTColor(0, 0, 0, 0));
textarea.setNoStroke(false);
textKeyboard.addTextInputListener(textarea);
Mitoco.getCanvas().addChild(textKeyboard);
textKeyboard.addChild(textarea);
textKeyboard.addStateChangeListener(StateChange.COMPONENT_DESTROYED, new StateChangeListener() {
@Override
public void stateChanged(final StateChangeEvent evt) {
filename = textarea.getText();
dataController.saveSceneXML(filename);
Mitoco.getMTApplication().saveFrame(SceneMitoco.getExportPath() + filename + "_Output-###.png");
}
}
);
break;
case TapEvent.GESTURE_ENDED:
default:
break;
}
} else {
//LOG.warn("Some other event occured:" + inEvt);
}
return false;
}
};
final IMTInputEventListener savePicture = new IMTInputEventListener() {
@Override
public boolean processInputEvent(final MTInputEvent inEvt) {
filename = "";
// Most input events in MT4j are an instance of AbstractCursorInputEvt (mouse, multi-touch..)
if (inEvt instanceof MTFingerInputEvt) {
final MTFingerInputEvt cursorInputEvt = (MTFingerInputEvt) inEvt;
switch (cursorInputEvt.getId()) {
case TapEvent.GESTURE_STARTED:
Mitoco.getMTApplication().saveFrame(SceneMitoco.getExportPath() + "out.png");
break;
case TapEvent.GESTURE_ENDED:
default:
break;
}
} else {
//LOG.warn("Some other event occured:" + inEvt);
}
return false;
}
};
/**
* Listener to load show the Filechooser und choose an XML Scene
*/
final IMTInputEventListener loadButtonInput = new IMTInputEventListener() {
@Override
public boolean processInputEvent(final MTInputEvent inEvt) {
// Most input events in MT4j are an instance of AbstractCursorInputEvt (mouse, multi-touch..)
if (inEvt instanceof MTFingerInputEvt) {
final MTFingerInputEvt cursorInputEvt = (MTFingerInputEvt) inEvt;
switch (cursorInputEvt.getId()) {
case TapEvent.GESTURE_STARTED:
//fileChooser.toggleFileChooser("xml");
//fileChooser.getUI().sendToFront();
//fileChooser = new FileChooser("C:\\", BuildRadialMenu.this.Mitoco);
//Mitoco.getCanvas().addChild(fileChooser.getUI());
MitocoScene.setImageload(true);
Mitoco.drawFilechooser("xml");
//fileChooser.toggleFileChooser("xml");
//fileChooser.getUI().sendToFront();
//linker.setTapAndHoldListener(); //TODO: Test
break;
default:
break;
}
} else {
//LOG.warn("Some other event occured:" + inEvt);
}
return false;
}
};
/**
* Alternativ load with a fixed XML for Testing
*/
final IMTInputEventListener loadButtonInput2 = new IMTInputEventListener() {
@Override
public boolean processInputEvent(final MTInputEvent inEvt) {
// Most input events in MT4j are an instance of AbstractCursorInputEvt (mouse, multi-touch..)
if (inEvt instanceof MTFingerInputEvt) {
final MTFingerInputEvt cursorInputEvt = (MTFingerInputEvt) inEvt;
switch (cursorInputEvt.getId()) {
case TapEvent.GESTURE_STARTED:
if (!dataController.loadSceneXML("xstream.xml")) {
for (Iterator<MyMTObject> it = dataController.getMyobjectList().iterator(); it.hasNext();) {
Mitoco.getCanvas().removeChild(dataController.getMyobjectList().get(it.next().getID()));
}
dataController.clearScene();
} else {
for (Iterator<MyMTObject> it = dataController.getMyobjectList().iterator(); it.hasNext();) {
Mitoco.getCanvas().addChild(dataController.getMyobjectList().get(it.next().getID()));
}
counter = dataController.getObjectcounter();
}
//linker.setTapAndHoldListener(); //TODO: Test
break;
default:
break;
}
} else {
//LOG.warn("Some other event occured:" + inEvt);
}
return false;
}
};
/**
* Start the Reporting task
*/
final IMTInputEventListener startReporting = new IMTInputEventListener() {
@Override
public boolean processInputEvent(final MTInputEvent inEvt) {
// Most input events in MT4j are an instance of AbstractCursorInputEvt (mouse, multi-touch..)
if (inEvt instanceof MTFingerInputEvt) {
final MTFingerInputEvt cursorInputEvt = (MTFingerInputEvt) inEvt;
switch (cursorInputEvt.getId()) {
case TapEvent.GESTURE_STARTED:
new MitocoReporting(mtApplication, "ReportingAp", Mitoco, dataController, 1);
break;
default:
break;
}
} else {
//LOG.warn("Some other event occured:" + inEvt);
}
return false;
}
};
/**
* Listener to create an PDF Component on the Scene
*/
final IMTInputEventListener showPDFlistener = new IMTInputEventListener() {
@Override
public boolean processInputEvent(final MTInputEvent inEvt) {
// Most input events in MT4j are an instance of AbstractCursorInputEvt (mouse, multi-touch..)
if (inEvt instanceof MTFingerInputEvt) {
final MTFingerInputEvt cursorInputEvt = (MTFingerInputEvt) inEvt;
switch (cursorInputEvt.getId()) {
case TapEvent.GESTURE_STARTED:
PDFViewer testpdf = new PDFViewer(mtApplication, "Test", "D:/Test.pdf");
Mitoco.getCanvas().addChild(testpdf);
testpdf.setVisible(true);
testpdf.sendToFront();
break;
default:
break;
}
} else {
//LOG.warn("Some other event occured:" + inEvt);
}
return false;
}
};
/**
* Make hiden Objects visible over an Animation
*/
final IMTInputEventListener showInputListener = new IMTInputEventListener() {
@Override
public boolean processInputEvent(final MTInputEvent inEvt) {
// Most input events in MT4j are an instance of AbstractCursorInputEvt (mouse, multi-touch..)
if (inEvt instanceof MTFingerInputEvt) {
final MTFingerInputEvt cursorInputEvt = (MTFingerInputEvt) inEvt;
switch (cursorInputEvt.getId()) {
case TapEvent.GESTURE_STARTED:
for (MyMTObject it : dataController.getMyobjectList()) {
if (it.getTagFlag()) {
Mitoco.showObjects(it);
dataController.showlink(it.getID());
//dataController.getMyobjectList()
it.setVisible(true);
//AnimationUtil.scaleIn(it);
}
System.out.println("hide2:"+it);
}
//AnimationUtil.scaleIn(dataController.getMyobjectList().get(0));
break;
default:
break;
}
} else {
//LOG.warn("Some other event occured:" + inEvt);
}
return false;
}
};
/**
* Listener Object to Hide an Component on the Scene. It will hide the Object of the Scene with an Animation
* and will hide the link over the DataController without an Animation
*/
final IMTInputEventListener hide2InputListener = new IMTInputEventListener() {
@Override
public boolean processInputEvent(final MTInputEvent inEvt) {
// Most input events in MT4j are an instance of AbstractCursorInputEvt (mouse, multi-touch..)
if (inEvt instanceof MTFingerInputEvt) {
final MTFingerInputEvt cursorInputEvt = (MTFingerInputEvt) inEvt;
switch (cursorInputEvt.getId()) {
case TapEvent.GESTURE_STARTED:
for (MyMTObject it : dataController.getMyobjectList()) {
if (it.getTagFlag()) {
//AnimationUtil.scaleOut(it, false);
Mitoco.hideObjects(it);
dataController.hideLink(it.getID());
//it.setVisible(false);
}
System.out.println("hide2:"+it);
}
break;
default:
break;
}
} else {
//LOG.warn("Some other event occured:" + inEvt);
}
return false;
}
};
/**
* Create a Webbrowser component on the Scene, only 32bit
*/
final IMTInputEventListener browserListener = new IMTInputEventListener() {
@Override
public boolean processInputEvent(final MTInputEvent inEvt) {
// Most input events in MT4j are an instance of AbstractCursorInputEvt (mouse, multi-touch..)
if (inEvt instanceof MTFingerInputEvt) {
final MTFingerInputEvt cursorInputEvt = (MTFingerInputEvt) inEvt;
switch (cursorInputEvt.getId()) {
case TapEvent.GESTURE_STARTED:
MTWebBrowser browser = new MTWebBrowser(Mitoco.getMTApplication(), 800, 600);
browser.setFillColor(new MTColor(180,180,180,200));
browser.setStrokeColor(MTColor.BLACK);
Mitoco.getCanvas().addChild(browser);
browser.setPositionGlobal(MT4jSettings.getInstance().getWindowCenter());
break;
default:
break;
}
} else {
//LOG.warn("Some other event occured:" + inEvt);
}
return false;
}
};
/**
* Delete Listener, loops trough the Object List and removes the Components from the Canvas wich are tagged
* Runs a method from the dataController witch will delete the datamodel and link
*/
final IMTInputEventListener deleteListener = new IMTInputEventListener() {
@Override
public boolean processInputEvent(final MTInputEvent inEvt) {
// Most input events in MT4j are an instance of AbstractCursorInputEvt (mouse, multi-touch..)
if (inEvt instanceof MTFingerInputEvt) {
final MTFingerInputEvt cursorInputEvt = (MTFingerInputEvt) inEvt;
switch (cursorInputEvt.getId()) {
case TapEvent.GESTURE_STARTED:
//hideObjects(dataController.getMyobjectList().get(0));
dataController.deleteObject();
for (MyMTObject it : dataController.getMyobjectList()) {
if (it.getTagFlag()) {
Mitoco.getCanvas().removeChild(it);
}
}
break;
default:
break;
}
} else {
//LOG.warn("Some other event occured:" + inEvt);
}
return false;
}
};
// Build list of menu items
final List<MTMenuItem> menuItems = new ArrayList<MTMenuItem>();
final MTMenuItem objectsmenu = new MTMenuItem("New", null);
if (sceneData.getShowAll()) {
for (Iterator<ModelTypDescription> it = dataController.getObjectetyps().getObjectdescription().iterator(); it.hasNext();) {
final MTMenuItem subMenu11 = new MTMenuItem(it.next().getObjectdescription(), null);
//menu1.addSubMenuItem(new MTMenuItem(it.next().getObjectdescription(), null));
//final IMTInputEventListener createObjectInput = new IMTInputEventListener() {
//menu1.addSubMenuItem(new MTMenuItem(it.next().getObjectdescription(), new ConcurrentHashMap<Class<? extends IInputProcessor>, IGestureEventListener>(){
objectsmenu.addSubMenuItem(subMenu11);
subMenu11.addInputEventListener(createObjectInput);
}
} else {
//for(ModelTypDescription it : dataController.getObjectetyps().getObjectdescription()){
for (ModelTypDescription it : sceneData.getSceneobjekte()) {
//if(sceneData.getSceneobjekte().get(index)){
final MTMenuItem subMenu11 = new MTMenuItem(it.getObjectdescription(), null);
//menu1.addSubMenuItem(new MTMenuItem(it.next().getObjectdescription(), null));
//final IMTInputEventListener createObjectInput = new IMTInputEventListener() {
//menu1.addSubMenuItem(new MTMenuItem(it.next().getObjectdescription(), new ConcurrentHashMap<Class<? extends IInputProcessor>, IGestureEventListener>(){
objectsmenu.addSubMenuItem(subMenu11);
subMenu11.addInputEventListener(createObjectInput);
//}
}
}
final MTMenuItem viewmenu = new MTMenuItem("View", null);
final MTMenuItem browser = new MTMenuItem("Browser", null);
browser.addInputEventListener(browserListener);
if(System.getProperty("sun.arch.data.model").equals("32")){
viewmenu.addSubMenuItem(browser);
}
final MTMenuItem pdf = new MTMenuItem("PDF", null);
pdf.addInputEventListener(showPDFlistener);
viewmenu.addSubMenuItem(pdf);
final MTMenuItem actionmenu = new MTMenuItem("Action", null);
final MTMenuItem loadfile = new MTMenuItem("Load File", null);
final MTMenuItem loadfileTest = new MTMenuItem("LoadThomas", null);
final MTMenuItem saveFile = new MTMenuItem("Save File", null);
final MTMenuItem submenu21 = new MTMenuItem("Reporting", null);
final MTMenuItem savePic = new MTMenuItem("Save Picture", null);
submenu21.addInputEventListener(startReporting);
actionmenu.addSubMenuItem(submenu21);
actionmenu.addSubMenuItem(loadfile);
actionmenu.addSubMenuItem(loadfileTest);
actionmenu.addSubMenuItem(saveFile);
actionmenu.addSubMenuItem(savePic);
savePic.addInputEventListener(savePicture);
loadfileTest.addInputEventListener(loadButtonInput2);
loadfile.addInputEventListener(loadButtonInput);
saveFile.addInputEventListener(saveButtonInput);
//actionmenu.addSubMenuItem(new MTMenuItem("Copy Objecet", null));
//actionmenu.addSubMenuItem(new MTMenuItem("Paste", null));
actionmenu.addSubMenuItem(new MTMenuItem("Clear", null));
final MTMenuItem maximizemenu = new MTMenuItem("Maximize", null);
final MTMenuItem minimizemenu = new MTMenuItem("Minimize", null);
final MTMenuItem deletemenu = new MTMenuItem("Delete selected", null);
maximizemenu.addInputEventListener(showInputListener);
minimizemenu.addInputEventListener(hide2InputListener);
deletemenu.addInputEventListener(deleteListener);
final MTMenuItem menu5 = new MTMenuItem("Exit", null);
menu5.addInputEventListener(exitButtonInput);
menuItems.add(objectsmenu);
menuItems.add(viewmenu);
menuItems.add(actionmenu);
menuItems.add(maximizemenu);
menuItems.add(minimizemenu);
menuItems.add(deletemenu);
menuItems.add(menu5);
// Create menu
final Vector3D vector = new Vector3D(ic.getCurrentEvtPosX(), ic.getCurrentEvtPosY());
final IFont font = FontManager.getInstance().createFont(mtApplication, "arial.ttf",
16, // Font size
new MTColor(255, 255, 255, 255), // Font fill color
true); // Anti-alias
this.mtRadialMenu1 = new MTRadialMenu(mtApplication, vector, font, 1f, menuItems);
if (startxGestureVector < endxGestureVector) {
this.mtRadialMenu1.rotateZ(mtRadialMenu1.getCenterPointLocal(), 0);
} else if (startyGestureVector < endyGestureVector) {
this.mtRadialMenu1.rotateZ(mtRadialMenu1.getCenterPointLocal(), 90);
} else if (startxGestureVector > endxGestureVector) {
this.mtRadialMenu1.rotateZ(mtRadialMenu1.getCenterPointLocal(), 180);
} else if (startyGestureVector > endyGestureVector) {
this.mtRadialMenu1.rotateZ(mtRadialMenu1.getCenterPointLocal(), 270);
}
System.out.println("start x " + startxGestureVector);
System.out.println("start y " + startyGestureVector);
System.out.println("end x " + endxGestureVector);
System.out.println("end y " + endyGestureVector);
//AnimationUtil.rotate2D(mtRectangle, 720);
Mitoco.getCanvas().addChild(mtRadialMenu1);
}
}
| gpl-2.0 |
donaldinou/nuked-module-userbox | lang/french.lang.php | 1703 | <?php
if (!defined("INDEX_CHECK"))
{
exit('You can\'t run this file alone.');
}
define("_POSTMESS","Poster un message");
define("_AUTHOR","Auteur");
define("_USERFOR","Pour");
define("_SUBJECT","Sujet");
define("_USERMESS","Message");
define("_SEND","Envoyer");
define("_BACK","Retour");
define("_EMPTYFIELD","Assurez vous que tous les champs soient remplis");
define("_UNKNOWMEMBER","Désolé, le membre est inconnu.");
define("_MESSSEND","Message envoyé avec succès.");
define("_PRIVATEMESS","Messages Privés");
define("_OF","De");
define("_THE","le");
define("_WROTE","a ecrit");
define("_REPLY","Répondre");
define("_DEL","Supprimer");
define("_NOSELECTMESS","Aucun message sélectionné");
define("_MESSDEL","Message supprimé avec succès.");
define("_DELETEMESS","Vous êtes sur le point de supprimer le message de");
define("_DELETEMESSAGES","Vous êtes sur le point de supprimer les messages");
define("_MESSAGESDEL","Messages supprimés avec succès.");
define("_CONFIRM","Continuer ?");
define("_BY","Par");
define("_CLEARSUCCES","effacé avec succès.");
define("_DELCONFIRM","Confirmer");
define("_CANCEL","Annuler");
define("_DELBOX","Sup");
define("_FROM","Provenant de");
define("_DATE","Date");
define("_SEEDETAILUSER","Voir les détails de l'auteur");
define("_READMESS","Lire message");
define("_STATUS","Status");
define("_READ","Lu");
define("_NOTREAD","Non lu");
define("_CHECKALL","Tout Cocher");
define("_UNCHECKALL","Tout Décocher");
define("_NOMESSPV","Vous n'avez pas de message...");
define("_SENDNEWMESS","Nouveau");
define("_NOFLOOD","Vous avez déja posté un email il y'a moins de " . $nuked['post_flood'] . " secondes,<br />veuillez patienter avant de renvoyer un autre email...");
?> | gpl-2.0 |
judgels/uriel | app/org/iatoki/judgels/uriel/contest/scoreboard/ioi/IOIScoreboardAdapter.java | 8252 | package org.iatoki.judgels.uriel.contest.scoreboard.ioi;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import org.iatoki.judgels.play.jid.AbstractBaseJidCacheServiceImpl;
import org.iatoki.judgels.sandalphon.problem.programming.submission.ProgrammingSubmission;
import org.iatoki.judgels.uriel.contest.Contest;
import org.iatoki.judgels.uriel.contest.scoreboard.Scoreboard;
import org.iatoki.judgels.uriel.contest.scoreboard.ScoreboardContent;
import org.iatoki.judgels.uriel.contest.scoreboard.ScoreboardEntryComparator;
import org.iatoki.judgels.uriel.contest.scoreboard.ScoreboardState;
import org.iatoki.judgels.uriel.contest.scoreboard.ScoreboardAdapter;
import org.iatoki.judgels.uriel.contest.scoreboard.ioi.html.ioiScoreboardView;
import play.i18n.Messages;
import play.twirl.api.Html;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public final class IOIScoreboardAdapter implements ScoreboardAdapter {
@Override
public ScoreboardContent computeScoreboardContent(Contest contest, ScoreboardState state, List<ProgrammingSubmission> submissions, Map<String, Date> contestantStartTimes) {
IOIContestStyleConfig styleConfig = (IOIContestStyleConfig) contest.getStyleConfig();
ScoreboardEntryComparator<IOIScoreboardEntry> comparator;
if (styleConfig.usingLastAffectingPenalty()) {
comparator = new UsingLastAffectingPenaltyIOIScoreboardEntryComparator();
} else {
comparator = new StandardIOIScoreboardEntryComparator();
}
Map<String, Map<String, Integer>> scores = Maps.newHashMap();
Map<String, Long> lastAffectingPenalties = Maps.newHashMap();
for (String contestantJid : state.getContestantJids()) {
scores.put(contestantJid, Maps.newHashMap());
lastAffectingPenalties.put(contestantJid, 0L);
}
for (ProgrammingSubmission submission : submissions) {
String contestantJid = submission.getAuthorJid();
if (!scores.containsKey(contestantJid)) {
continue;
}
String problemJid = submission.getProblemJid();
int score = submission.getLatestScore();
boolean updateLastAffectingPenalty = false;
if (scores.get(contestantJid).containsKey(problemJid)) {
int oldScore = scores.get(contestantJid).get(problemJid);
if (score > oldScore) {
updateLastAffectingPenalty = true;
} else {
score = oldScore;
}
} else if (score > 0) {
updateLastAffectingPenalty = true;
}
scores.get(contestantJid).put(problemJid, score);
if (updateLastAffectingPenalty) {
long lastAffectingPenalty = computeLastAffectingPenalty(contest, contestantStartTimes.get(contestantJid), submission.getTime());
lastAffectingPenalties.put(contestantJid, lastAffectingPenalty);
}
}
List<IOIScoreboardEntry> entries = Lists.newArrayList();
for (String contestantJid : state.getContestantJids()) {
IOIScoreboardEntry entry = new IOIScoreboardEntry();
entry.contestantJid = contestantJid;
int totalScores = 0;
for (String problemJid : state.getProblemJids()) {
Integer score = scores.get(contestantJid).get(problemJid);
entry.scores.add(score);
if (score != null) {
totalScores += score;
}
}
entry.totalScores = totalScores;
entry.lastAffectingPenalty = lastAffectingPenalties.get(contestantJid);
entries.add(entry);
}
sortEntriesAndAssignRanks(comparator, entries);
return new IOIScoreboardContent(entries);
}
@Override
public Scoreboard parseScoreboardFromJson(String json) {
return new Gson().fromJson(json, IOIScoreboard.class);
}
@Override
public Scoreboard createScoreboard(ScoreboardState state, ScoreboardContent content) {
return new IOIScoreboard(state, (IOIScoreboardContent) content);
}
@Override
public Scoreboard filterOpenProblems(Contest contest, Scoreboard scoreboard, Set<String> openProblemJids) {
IOIContestStyleConfig styleConfig = (IOIContestStyleConfig) contest.getStyleConfig();
ScoreboardEntryComparator<IOIScoreboardEntry> comparator;
if (styleConfig.usingLastAffectingPenalty()) {
comparator = new UsingLastAffectingPenaltyIOIScoreboardEntryComparator();
} else {
comparator = new StandardIOIScoreboardEntryComparator();
}
ScoreboardState state = scoreboard.getState();
IOIScoreboardContent content = (IOIScoreboardContent) scoreboard.getContent();
if (state.getProblemJids().size() == openProblemJids.size()) {
return scoreboard;
}
ImmutableList.Builder<Integer> openProblemIndicesBuilder = ImmutableList.builder();
for (int i = 0; i < state.getProblemJids().size(); i++) {
if (openProblemJids.contains(state.getProblemJids().get(i))) {
openProblemIndicesBuilder.add(i);
}
}
List<Integer> openProblemIndices = openProblemIndicesBuilder.build();
ScoreboardState newState = new ScoreboardState(
filterIndices(state.getProblemJids(), openProblemIndices),
filterIndices(state.getProblemAliases(), openProblemIndices),
state.getContestantJids()
);
List<IOIScoreboardEntry> newEntries = Lists.newArrayList();
for (IOIScoreboardEntry entry : content.getEntries()) {
IOIScoreboardEntry newEntry = new IOIScoreboardEntry();
newEntry.scores = filterIndices(entry.scores, openProblemIndices);
newEntry.contestantJid = entry.contestantJid;
newEntry.totalScores = newEntry.scores.stream().filter(s -> s != null).mapToInt(s -> s).sum();
newEntries.add(newEntry);
}
sortEntriesAndAssignRanks(comparator, newEntries);
return new IOIScoreboard(newState, new IOIScoreboardContent(newEntries));
}
@Override
public Html renderScoreboard(Scoreboard scoreboard, Date lastUpdateTime, AbstractBaseJidCacheServiceImpl<?> jidCacheService, String currentContestantJid, boolean hiddenRank, Set<String> filterContestantJids) {
if (scoreboard == null) {
return new Html(Messages.get("scoreboard.not_available"));
}
IOIScoreboard castScoreboard = (IOIScoreboard) scoreboard;
return ioiScoreboardView.render(castScoreboard.getState(), castScoreboard.getContent().getEntries().stream().filter(e -> filterContestantJids.contains(e.contestantJid)).collect(Collectors.toList()), lastUpdateTime, jidCacheService, currentContestantJid, hiddenRank);
}
private <T> List<T> filterIndices(List<T> list, List<Integer> indices) {
return indices.stream().map(i -> list.get(i)).collect(Collectors.toList());
}
private void sortEntriesAndAssignRanks(ScoreboardEntryComparator<IOIScoreboardEntry> comparator, List<IOIScoreboardEntry> entries) {
Collections.sort(entries, comparator);
int currentRank = 0;
for (int i = 0; i < entries.size(); i++) {
currentRank++;
if (i == 0 || comparator.compareWithoutTieBreakerForEqualRanks(entries.get(i), entries.get(i - 1)) != 0) {
entries.get(i).rank = currentRank;
} else {
entries.get(i).rank = entries.get(i - 1).rank;
}
}
}
private long computeLastAffectingPenalty(Contest contest, Date contestStartTime, Date submissionTime) {
if (contestStartTime != null) {
return submissionTime.getTime() - contestStartTime.getTime();
}
return submissionTime.getTime() - contest.getBeginTime().getTime();
}
}
| gpl-2.0 |
timattox/lammps_USER-DPD | src/OPT/pair_eam_opt.cpp | 10950 | /* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Contributing authors:
James Fischer, High Performance Technologies, Inc.
Charles Cornwell, High Performance Technologies, Inc.
David Richie, Stone Ridge Technology
Vincent Natoli, Stone Ridge Technology
------------------------------------------------------------------------- */
#include <cmath>
#include <cstdlib>
#include "pair_eam_opt.h"
#include "atom.h"
#include "comm.h"
#include "force.h"
#include "neigh_list.h"
#include "memory.h"
using namespace LAMMPS_NS;
/* ---------------------------------------------------------------------- */
PairEAMOpt::PairEAMOpt(LAMMPS *lmp) : PairEAM(lmp) {}
/* ---------------------------------------------------------------------- */
void PairEAMOpt::compute(int eflag, int vflag)
{
ev_init(eflag,vflag);
if (evflag) {
if (eflag) {
if (force->newton_pair) return eval<1,1,1>();
else return eval<1,1,0>();
} else {
if (force->newton_pair) return eval<1,0,1>();
else return eval<1,0,0>();
}
} else {
if (force->newton_pair) return eval<0,0,1>();
else return eval<0,0,0>();
}
}
/* ---------------------------------------------------------------------- */
template < int EVFLAG, int EFLAG, int NEWTON_PAIR >
void PairEAMOpt::eval()
{
typedef struct { double x,y,z; } vec3_t;
typedef struct {
double rhor0i,rhor1i,rhor2i,rhor3i;
double rhor0j,rhor1j,rhor2j,rhor3j;
} fast_alpha_t;
typedef struct {
double rhor4i,rhor5i,rhor6i;
double rhor4j,rhor5j,rhor6j;
double z2r0,z2r1,z2r2,z2r3,z2r4,z2r5,z2r6;
double _pad[3];
} fast_gamma_t;
int i,j,ii,jj,inum,jnum,itype,jtype;
double evdwl = 0.0;
double* _noalias coeff;
// grow energy array if necessary
if (atom->nmax > nmax) {
memory->sfree(rho);
memory->sfree(fp);
nmax = atom->nmax;
rho = (double *) memory->smalloc(nmax*sizeof(double),"pair:rho");
fp = (double *) memory->smalloc(nmax*sizeof(double),"pair:fp");
}
double** _noalias x = atom->x;
double** _noalias f = atom->f;
int* _noalias type = atom->type;
int nlocal = atom->nlocal;
vec3_t* _noalias xx = (vec3_t*)x[0];
vec3_t* _noalias ff = (vec3_t*)f[0];
double tmp_cutforcesq = cutforcesq;
double tmp_rdr = rdr;
int nr2 = nr-2;
int nr1 = nr-1;
inum = list->inum;
int* _noalias ilist = list->ilist;
int** _noalias firstneigh = list->firstneigh;
int* _noalias numneigh = list->numneigh;
int ntypes = atom->ntypes;
int ntypes2 = ntypes*ntypes;
fast_alpha_t* _noalias fast_alpha =
(fast_alpha_t*) malloc(ntypes2*(nr+1)*sizeof(fast_alpha_t));
for (i = 0; i < ntypes; i++) for (j = 0; j < ntypes; j++) {
fast_alpha_t* _noalias tab = &fast_alpha[i*ntypes*nr+j*nr];
if (type2rhor[i+1][j+1] >= 0) {
for(int m = 1; m <= nr; m++) {
tab[m].rhor0i = rhor_spline[type2rhor[i+1][j+1]][m][6];
tab[m].rhor1i = rhor_spline[type2rhor[i+1][j+1]][m][5];
tab[m].rhor2i = rhor_spline[type2rhor[i+1][j+1]][m][4];
tab[m].rhor3i = rhor_spline[type2rhor[i+1][j+1]][m][3];
}
}
if (type2rhor[j+1][i+1] >= 0) {
for(int m = 1; m <= nr; m++) {
tab[m].rhor0j = rhor_spline[type2rhor[j+1][i+1]][m][6];
tab[m].rhor1j = rhor_spline[type2rhor[j+1][i+1]][m][5];
tab[m].rhor2j = rhor_spline[type2rhor[j+1][i+1]][m][4];
tab[m].rhor3j = rhor_spline[type2rhor[j+1][i+1]][m][3];
}
}
}
fast_alpha_t* _noalias tabeight = fast_alpha;
fast_gamma_t* _noalias fast_gamma =
(fast_gamma_t*) malloc(ntypes2*(nr+1)*sizeof(fast_gamma_t));
for (i = 0; i < ntypes; i++) for (j = 0; j < ntypes; j++) {
fast_gamma_t* _noalias tab = &fast_gamma[i*ntypes*nr+j*nr];
if (type2rhor[i+1][j+1] >= 0) {
for(int m = 1; m <= nr; m++) {
tab[m].rhor4i = rhor_spline[type2rhor[i+1][j+1]][m][2];
tab[m].rhor5i = rhor_spline[type2rhor[i+1][j+1]][m][1];
tab[m].rhor6i = rhor_spline[type2rhor[i+1][j+1]][m][0];
}
}
if (type2rhor[j+1][i+1] >= 0) {
for(int m = 1; m <= nr; m++) {
tab[m].rhor4j = rhor_spline[type2rhor[j+1][i+1]][m][2];
tab[m].rhor5j = rhor_spline[type2rhor[j+1][i+1]][m][1];
tab[m].rhor6j = rhor_spline[type2rhor[j+1][i+1]][m][0];
tab[m].z2r6 = z2r_spline[type2z2r[i+1][j+1]][m][0];
}
}
if (type2z2r[i+1][j+1] >= 0) {
for(int m = 1; m <= nr; m++) {
tab[m].z2r0 = z2r_spline[type2z2r[i+1][j+1]][m][6];
tab[m].z2r1 = z2r_spline[type2z2r[i+1][j+1]][m][5];
tab[m].z2r2 = z2r_spline[type2z2r[i+1][j+1]][m][4];
tab[m].z2r3 = z2r_spline[type2z2r[i+1][j+1]][m][3];
tab[m].z2r4 = z2r_spline[type2z2r[i+1][j+1]][m][2];
tab[m].z2r5 = z2r_spline[type2z2r[i+1][j+1]][m][1];
tab[m].z2r6 = z2r_spline[type2z2r[i+1][j+1]][m][0];
}
}
}
fast_gamma_t* _noalias tabss = fast_gamma;
// zero out density
if (NEWTON_PAIR) {
int m = nlocal + atom->nghost;
for (i = 0; i < m; i++) rho[i] = 0.0;
} else for (i = 0; i < nlocal; i++) rho[i] = 0.0;
// rho = density at each atom
// loop over neighbors of my atoms
// loop over neighbors of my atoms
for (ii = 0; ii < inum; ii++) {
i = ilist[ii];
double xtmp = xx[i].x;
double ytmp = xx[i].y;
double ztmp = xx[i].z;
itype = type[i] - 1;
int* _noalias jlist = firstneigh[i];
jnum = numneigh[i];
double tmprho = rho[i];
fast_alpha_t* _noalias tabeighti = &tabeight[itype*ntypes*nr];
for (jj = 0; jj < jnum; jj++) {
j = jlist[jj];
j &= NEIGHMASK;
double delx = xtmp - xx[j].x;
double dely = ytmp - xx[j].y;
double delz = ztmp - xx[j].z;
double rsq = delx*delx + dely*dely + delz*delz;
if (rsq < tmp_cutforcesq) {
jtype = type[j] - 1;
double p = sqrt(rsq)*tmp_rdr;
if ( (int)p <= nr2 ) {
int m = (int)p + 1;
p -= (double)((int)p);
fast_alpha_t& a = tabeighti[jtype*nr+m];
tmprho += ((a.rhor3j*p+a.rhor2j)*p+a.rhor1j)*p+a.rhor0j;
if (NEWTON_PAIR || j < nlocal) {
rho[j] += ((a.rhor3i*p+a.rhor2i)*p+a.rhor1i)*p+a.rhor0i;
}
} else {
fast_alpha_t& a = tabeighti[jtype*nr+nr1];
tmprho += a.rhor3j+a.rhor2j+a.rhor1j+a.rhor0j;
if (NEWTON_PAIR || j < nlocal) {
rho[j] += a.rhor3i+a.rhor2i+a.rhor1i+a.rhor0i;
}
}
}
}
rho[i] = tmprho;
}
// communicate and sum densities
if (NEWTON_PAIR) comm->reverse_comm_pair(this);
// fp = derivative of embedding energy at each atom
// phi = embedding energy at each atom
// if rho > rhomax (e.g. due to close approach of two atoms),
// will exceed table, so add linear term to conserve energy
for (ii = 0; ii < inum; ii++) {
i = ilist[ii];
double p = rho[i]*rdrho;
int m = MIN((int)p,nrho-2);
p -= (double)m;
++m;
coeff = frho_spline[type2frho[type[i]]][m];
fp[i] = (coeff[0]*p + coeff[1])*p + coeff[2];
if (EFLAG) {
double phi = ((coeff[3]*p + coeff[4])*p + coeff[5])*p + coeff[6];
if (rho[i] > rhomax) phi += fp[i] * (rho[i]-rhomax);
phi *= scale[type[i]][type[i]];
if (eflag_global) eng_vdwl += phi;
if (eflag_atom) eatom[i] += phi;
}
}
// communicate derivative of embedding function
comm->forward_comm_pair(this);
// compute forces on each atom
// loop over neighbors of my atoms
for (ii = 0; ii < inum; ii++) {
i = ilist[ii];
double xtmp = xx[i].x;
double ytmp = xx[i].y;
double ztmp = xx[i].z;
int itype1 = type[i] - 1;
int* _noalias jlist = firstneigh[i];
jnum = numneigh[i];
double tmpfx = 0.0;
double tmpfy = 0.0;
double tmpfz = 0.0;
fast_gamma_t* _noalias tabssi = &tabss[itype1*ntypes*nr];
double* _noalias scale_i = scale[itype1+1]+1;
for (jj = 0; jj < jnum; jj++) {
j = jlist[jj];
j &= NEIGHMASK;
double delx = xtmp - xx[j].x;
double dely = ytmp - xx[j].y;
double delz = ztmp - xx[j].z;
double rsq = delx*delx + dely*dely + delz*delz;
if (rsq < tmp_cutforcesq) {
jtype = type[j] - 1;
double r = sqrt(rsq);
double rhoip,rhojp,z2,z2p;
double p = r*tmp_rdr;
if ( (int)p <= nr2 ) {
int m = (int) p + 1;
p -= (double)((int) p);
fast_gamma_t& a = tabssi[jtype*nr+m];
rhoip = (a.rhor6i*p + a.rhor5i)*p + a.rhor4i;
rhojp = (a.rhor6j*p + a.rhor5j)*p + a.rhor4j;
z2 = ((a.z2r3*p + a.z2r2)*p + a.z2r1)*p + a.z2r0;
z2p = (a.z2r6*p + a.z2r5)*p + a.z2r4;
} else {
fast_gamma_t& a = tabssi[jtype*nr+nr1];
rhoip = a.rhor6i + a.rhor5i + a.rhor4i;
rhojp = a.rhor6j + a.rhor5j + a.rhor4j;
z2 = a.z2r3 + a.z2r2 + a.z2r1 + a.z2r0;
z2p = a.z2r6 + a.z2r5 + a.z2r4;
}
// rhoip = derivative of (density at atom j due to atom i)
// rhojp = derivative of (density at atom i due to atom j)
// phi = pair potential energy
// phip = phi'
// z2 = phi * r
// z2p = (phi * r)' = (phi' r) + phi
// psip needs both fp[i] and fp[j] terms since r_ij appears in two
// terms of embed eng: Fi(sum rho_ij) and Fj(sum rho_ji)
// hence embed' = Fi(sum rho_ij) rhojp + Fj(sum rho_ji) rhoip
// scale factor can be applied by thermodynamic integration
double recip = 1.0/r;
double phi = z2*recip;
double phip = z2p*recip - phi*recip;
double psip = fp[i]*rhojp + fp[j]*rhoip + phip;
double fpair = -scale_i[jtype]*psip*recip;
tmpfx += delx*fpair;
tmpfy += dely*fpair;
tmpfz += delz*fpair;
if (NEWTON_PAIR || j < nlocal) {
ff[j].x -= delx*fpair;
ff[j].y -= dely*fpair;
ff[j].z -= delz*fpair;
}
if (EFLAG) evdwl = scale_i[jtype]*phi;
if (EVFLAG) ev_tally(i,j,nlocal,NEWTON_PAIR,
evdwl,0.0,fpair,delx,dely,delz);
}
}
ff[i].x += tmpfx;
ff[i].y += tmpfy;
ff[i].z += tmpfz;
}
free(fast_alpha); fast_alpha = 0;
free(fast_gamma); fast_gamma = 0;
if (vflag_fdotr) virial_fdotr_compute();
}
| gpl-2.0 |
Bamboo3000/searchit | wp-content/themes/searchit/metaboxes/contact_spec.php | 348 | <?php
$contact_mb = $contact = new WPAlchemy_MetaBox(array
(
'id' => '_contact',
'title' => 'Contact',
'context' => 'normal',
'priority' => 'high',
'autosave' => TRUE,
'template' => TEMPLATEPATH . '/metaboxes/contact_meta.php',
'include_template' => 'contact-page.php',
'mode' => WPALCHEMY_MODE_EXTRACT,
'prefix' => '_my_',
));
/* eof */ | gpl-2.0 |
eestec/eestec.portal-2 | wp-content/plugins/EESTEC-permissions/EESTEC-permissions.php | 5094 | <?php
/**
* @package EESTEC permissions
*/
/*
Plugin Name: EESTEC permissions
Plugin URI: http://erik.plestenjak.com
Description: The plugin implement EESTEC specific access permissions which are not available by using the other plugins.
Version: 1.0
Author: Erik Plestenjak
Author URI: http://erik.plestenjak.com
License: GPLv2 or later
*/
/*
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// Make sure we don't expose any info if called directly
/*if ( !function_exists( 'add_action' ) ) {
echo 'Hi there! I\'m just a plugin, not much I can do when called directly.';
exit;
}*/
define('EESTEC_PERMISSIONS_VERSION', '1.0');
define('EESTEC_PERMISSIONS_PLUGIN_URL', plugin_dir_url( __FILE__ ));
//give int board access to editing menu
//give lc board permssion to add events
//automate locking meta of lc on events
//store organizer lc on the event
//restrict user editing to same lc
function get_current_user_roles(){
global $current_user;
return $current_user->roles;
return $user_roles;
}
function current_user_has_role($role)
{
return in_array($role,get_current_user_roles());
}
add_filter( 'user_has_cap', 'edit_lcs', 100, 3 );
function edit_lcs($allcaps, $cap, $args)
{
global $current_user;
if(array_key_exists('manage_options',$allcaps))//user is admin
return $allcaps;
if(get_post_type()=='lcs'){
if(current_user_has_role('lcboard'))
if($args[0]=='edit_post')
$allcaps[$cap[0]] = ($args[2]==get_cimyFieldValue($current_user->ID,'lc'));//only members of the LC can edit the lc
}
return $allcaps;
}
add_filter( 'user_has_cap', 'edit_users', 100, 3 );//restricts editable users to same LC only
function edit_users($allcaps, $cap, $args)
{
global $current_user;
if(array_key_exists('manage_options',$allcaps))//user is admin
return $allcaps;
//print_r($cap);
//print_r($args);
if($args[0]=='edit_user')
if(get_cimyFieldValue($args[2],'lc')!=get_cimyFieldValue($current_user->ID,'lc'))
{
$allcaps['edit_users']=false;
$allcaps['edit_user']=false;
}
return $allcaps;
}
add_action('save_post', 'link_event_to_lc'); // the temporary organizer has to be removed! Not working :(
function link_event_to_lc($post_id)
{
global $current_user;
if(get_post_meta($post_id,'lc', true)=='')
{
$lc=get_cimyFieldValue($current_user->ID,'lc');
add_post_meta($post_id,'lc', $lc, true);
}
}
add_filter( 'user_has_cap', 'edit_events', 100, 3 );
function edit_events($allcaps, $cap, $args)
{
global $current_user;
if(array_key_exists('manage_options',$allcaps))//user is admin
return $allcaps;
if(get_post_type()=='events'){
//print_r($cap);
//print_r($allcaps);
//print_r($args);
if(current_user_has_role('lcboard'))
{
$allcaps['delete_published_eventss']=false;
//$allcaps['edit_eventss']=false;
$allcaps['edit_others_eventss']=false;
$allcaps['delete_others_eventss']=false;
if(is_admin())
$allcaps['read_private_eventss'] = False;
$lc=get_cimyFieldValue($current_user->ID,'lc'); //only members of the LC can edit the lc events
if (get_post_meta($args[2],'lc',true)==$lc)
{
$allcaps['delete_published_eventss']=true;
$allcaps['edit_eventss']=true;
$allcaps['edit_others_eventss']=true;
$allcaps['delete_others_eventss']=true;
}
}
}
return $allcaps;
}
add_action( 'admin_menu', 'remove_menus',100,3 ); //cleaning up the menu for average users.
function remove_menus(){
global $submenu;
if( !current_user_can( 'manage_options' ))
{
remove_menu_page( 'tools.php' ); //Tools
remove_menu_page( 'rs-category-restrictions_t' ); //Removing role scoper menu
remove_menu_page( 'rs-general_roles' ); // role scoper menu
remove_submenu_page( 'users.php','rs-groups' ); // removing role scoper option from users menu
}
}
?> | gpl-2.0 |
cyjseagull/SHMA | zsim-nvmain/pin_kit/source/tools/ToolUnitTests/rtn_insert_call1.cpp | 6553 | /*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2013 Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. Redistributions
in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution. Neither the name of
the Intel Corporation nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR
ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
END_LEGAL */
// This tool test RTN_InsHead RTN_InsHeadOnly and RTN_InsertCall (before)
#include <stdio.h>
#include <stdlib.h>
#include "pin.H"
ADDRINT curRtnAddr = 0;
int numAtRtn = 0;
int numBeforeInsHeadOnly = 0;
int numAfterInsHeadOnly = 0;
int numBeforeInsHead = 0;
int numAfterInsHead = 0;
int numRtnsFoundInImageCallback = 0;
int numRtnsInstrumentedFromImageCallback = 0;
int numRtnsFoundInRtnCallback = 0;
VOID AtRtn(ADDRINT rtnAddr)
{
if (curRtnAddr != 0)
{
printf ("**** expected rtnAddr to be 0\n");
exit(-1);
}
curRtnAddr = rtnAddr;
numAtRtn++;
}
VOID BeforeInsHeadOnly(ADDRINT insAddr)
{
if (curRtnAddr == 0)
{
printf ("**** BeforeInsHeadOnly expected curRtnAddr to be non-0\n");
exit(-1);
}
if (curRtnAddr != insAddr)
{
printf ("**** BeforeInsHeadOnly got unexpected insAddr\n");
exit(-1);
}
numBeforeInsHeadOnly++;
}
VOID AfterInsHeadOnly(ADDRINT insAddr)
{
if (curRtnAddr == 0)
{
printf ("**** AfterInsHeadOnly expected curRtnAddr to be non-0\n");
exit(-1);
}
if (curRtnAddr != insAddr)
{
printf ("**** AfterInsHeadOnly got unexpected insAddr\n");
exit(-1);
}
numAfterInsHeadOnly++;
}
VOID BeforeInsHead(ADDRINT insAddr)
{
if (curRtnAddr == 0)
{
printf ("**** BeforeInsHead expected curRtnAddr to be non-0\n");
exit(-1);
}
if (curRtnAddr != insAddr)
{
printf ("**** BeforeInsHead got unexpected insAddr\n");
exit(-1);
}
numBeforeInsHead++;
}
VOID AfterInsHead(ADDRINT insAddr)
{
if (curRtnAddr == 0)
{
printf ("**** AfterInsHead expected curRtnAddr to be non-0\n");
exit(-1);
}
if (curRtnAddr != insAddr)
{
printf ("**** AfterInsHead got unexpected insAddr\n");
exit(-1);
}
numAfterInsHead++;
curRtnAddr = 0;
}
VOID Image(IMG img, void *v)
{
for (SEC sec = IMG_SecHead(img); SEC_Valid(sec); sec = SEC_Next(sec))
{
for (RTN rtn = SEC_RtnHead(sec); RTN_Valid(rtn); rtn = RTN_Next(rtn))
{
RTN_Open(rtn);
numRtnsFoundInImageCallback++;
INS ins = RTN_InsHeadOnly(rtn);
if (INS_Invalid() == ins)
{ // no instruction found - assert that RTN_InsHead(rtn) also doesn't find any INS
ASSERTX (INS_Invalid() == RTN_InsHead(rtn));
RTN_Close(rtn);
continue;
}
if (INS_HasFallThrough(ins))
{
ADDRINT insAddress = INS_Address(ins);
numRtnsInstrumentedFromImageCallback++;
RTN_InsertCall( rtn, IPOINT_BEFORE, AFUNPTR(AtRtn), IARG_ADDRINT, RTN_Address(rtn), IARG_END);
INS_InsertCall (ins, IPOINT_BEFORE, AFUNPTR(BeforeInsHeadOnly), IARG_ADDRINT, INS_Address(ins), IARG_END);
INS_InsertCall (ins, IPOINT_AFTER, AFUNPTR(AfterInsHeadOnly), IARG_ADDRINT, INS_Address(ins), IARG_END);
ins = RTN_InsHead(rtn);
ASSERTX(INS_Invalid() != ins);
ASSERTX(INS_Address(ins)==insAddress);
INS_InsertCall (ins, IPOINT_BEFORE, AFUNPTR(BeforeInsHead), IARG_ADDRINT, insAddress, IARG_END);
INS_InsertCall (ins, IPOINT_AFTER, AFUNPTR(AfterInsHead), IARG_ADDRINT, insAddress, IARG_END);
}
RTN_Close(rtn);
}
}
}
VOID Fini (INT32 code, VOID *v)
{
if (numRtnsInstrumentedFromImageCallback == 0)
{
printf ("***** expected numRtnsInstrumentedFromImageCallback to be > 0\n");
exit(-1);
}
if (numRtnsFoundInImageCallback == 0)
{
printf ("***** expected numRtnsFoundInImageCallback to be > 0\n");
exit(-1);
}
if (numRtnsFoundInImageCallback != numRtnsFoundInRtnCallback)
{
printf ("***** expected numRtnsFoundInImageCallback == numRtnsFoundInRtnCallback\n");
exit(-1);
}
if (numAtRtn == 0)
{
printf ("***** expected numAtRtn to be > 0\n");
exit(-1);
}
if (numAtRtn != numBeforeInsHeadOnly)
{
printf ("***** expected numAtRtn == numBeforeInsHeadOnly\n");
exit(-1);
}
if (numAtRtn != numAfterInsHeadOnly)
{
printf ("***** expected numAtRtn == numAfterInsHeadOnly\n");
exit(-1);
}
if (numAtRtn != numBeforeInsHead)
{
printf ("***** expected numAtRtn == numBeforeInsHead\n");
exit(-1);
}
if (numAtRtn != numAfterInsHead)
{
printf ("***** expected numAtRtn == numAfterInsHead\n");
exit(-1);
}
}
VOID Rtn(RTN rtn, VOID *)
{
numRtnsFoundInRtnCallback++;
}
int main(int argc, char **argv)
{
PIN_Init(argc, argv);
PIN_InitSymbols();
IMG_AddInstrumentFunction(Image, 0);
RTN_AddInstrumentFunction(Rtn, 0);
PIN_AddFiniFunction(Fini, 0);
PIN_StartProgram();
return 0;
}
| gpl-2.0 |
mixerp6/mixerp | src/Libraries/DAL/Office/GetStoreIdByStoreNameProcedure.cs | 4253 | // ReSharper disable All
/********************************************************************************
Copyright (C) MixERP Inc. (http://mixof.org).
This file is part of MixERP.
MixERP is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 2 of the License.
MixERP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with MixERP. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************************/
using MixERP.Net.DbFactory;
using MixERP.Net.Framework;
using MixERP.Net.Framework.Extensions;
using PetaPoco;
using MixERP.Net.Entities.Office;
using Npgsql;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
namespace MixERP.Net.Schemas.Office.Data
{
/// <summary>
/// Prepares, validates, and executes the function "office.get_store_id_by_store_name(_store_name text)" on the database.
/// </summary>
public class GetStoreIdByStoreNameProcedure : DbAccess
{
/// <summary>
/// The schema of this PostgreSQL function.
/// </summary>
public override string _ObjectNamespace => "office";
/// <summary>
/// The schema unqualified name of this PostgreSQL function.
/// </summary>
public override string _ObjectName => "get_store_id_by_store_name";
/// <summary>
/// Login id of application user accessing this PostgreSQL function.
/// </summary>
public long _LoginId { get; set; }
/// <summary>
/// User id of application user accessing this table.
/// </summary>
public int _UserId { get; set; }
/// <summary>
/// The name of the database on which queries are being executed to.
/// </summary>
public string _Catalog { get; set; }
/// <summary>
/// Maps to "_store_name" argument of the function "office.get_store_id_by_store_name".
/// </summary>
public string StoreName { get; set; }
/// <summary>
/// Prepares, validates, and executes the function "office.get_store_id_by_store_name(_store_name text)" on the database.
/// </summary>
public GetStoreIdByStoreNameProcedure()
{
}
/// <summary>
/// Prepares, validates, and executes the function "office.get_store_id_by_store_name(_store_name text)" on the database.
/// </summary>
/// <param name="storeName">Enter argument value for "_store_name" parameter of the function "office.get_store_id_by_store_name".</param>
public GetStoreIdByStoreNameProcedure(string storeName)
{
this.StoreName = storeName;
}
/// <summary>
/// Prepares and executes the function "office.get_store_id_by_store_name".
/// </summary>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public int Execute()
{
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Execute, this._LoginId, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the function \"GetStoreIdByStoreNameProcedure\" was denied to the user with Login ID {LoginId}.", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
string query = "SELECT * FROM office.get_store_id_by_store_name(@StoreName);";
query = query.ReplaceWholeWord("@StoreName", "@0::text");
List<object> parameters = new List<object>();
parameters.Add(this.StoreName);
return Factory.Scalar<int>(this._Catalog, query, parameters.ToArray());
}
}
} | gpl-2.0 |
Khira/La-Confrerie | src/game/GameObject.cpp | 59892 | /*
* Copyright (C) 2005-2010 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "GameObject.h"
#include "QuestDef.h"
#include "ObjectMgr.h"
#include "PoolManager.h"
#include "SpellMgr.h"
#include "Spell.h"
#include "UpdateMask.h"
#include "Opcodes.h"
#include "WorldPacket.h"
#include "World.h"
#include "Database/DatabaseEnv.h"
#include "LootMgr.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "CellImpl.h"
#include "InstanceData.h"
#include "BattleGround.h"
#include "BattleGroundAV.h"
#include "Util.h"
#include "ScriptCalls.h"
GameObject::GameObject() : WorldObject()
{
m_objectType |= TYPEMASK_GAMEOBJECT;
m_objectTypeId = TYPEID_GAMEOBJECT;
m_updateFlag = (UPDATEFLAG_HIGHGUID | UPDATEFLAG_HAS_POSITION | UPDATEFLAG_POSITION | UPDATEFLAG_ROTATION);
m_valuesCount = GAMEOBJECT_END;
m_respawnTime = 0;
m_respawnDelayTime = 25;
m_lootState = GO_NOT_READY;
m_spawnedByDefault = true;
m_useTimes = 0;
m_spellId = 0;
m_cooldownTime = 0;
m_goInfo = NULL;
m_DBTableGuid = 0;
m_rotation = 0;
}
GameObject::~GameObject()
{
}
void GameObject::AddToWorld()
{
///- Register the gameobject for guid lookup
if(!IsInWorld())
GetMap()->GetObjectsStore().insert<GameObject>(GetGUID(), (GameObject*)this);
Object::AddToWorld();
}
void GameObject::RemoveFromWorld()
{
///- Remove the gameobject from the accessor
if(IsInWorld())
{
// Remove GO from owner
ObjectGuid owner_guid = GetOwnerGUID();
if (!owner_guid.IsEmpty())
{
if (Unit* owner = ObjectAccessor::GetUnit(*this,owner_guid))
owner->RemoveGameObject(this,false);
else
{
sLog.outError("Delete %s with SpellId %u LinkedGO %u that lost references to owner %s GO list. Crash possible later.",
GetObjectGuid().GetString().c_str(), m_spellId, GetGOInfo()->GetLinkedGameObjectEntry(), owner_guid.GetString().c_str());
}
}
GetMap()->GetObjectsStore().erase<GameObject>(GetGUID(), (GameObject*)NULL);
}
Object::RemoveFromWorld();
}
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, uint8 animprogress, GOState go_state)
{
MANGOS_ASSERT(map);
Relocate(x,y,z,ang);
SetMap(map);
SetPhaseMask(phaseMask,false);
if(!IsPositionValid())
{
sLog.outError("Gameobject (GUID: %u Entry: %u ) not created. Suggested coordinates isn't valid (X: %f Y: %f)",guidlow,name_id,x,y);
return false;
}
GameObjectInfo const* goinfo = ObjectMgr::GetGameObjectInfo(name_id);
if (!goinfo)
{
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);
return false;
}
Object::_Create(guidlow, goinfo->id, HIGHGUID_GAMEOBJECT);
m_goInfo = goinfo;
if (goinfo->type >= MAX_GAMEOBJECT_TYPE)
{
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);
return false;
}
SetObjectScale(goinfo->size);
SetFloatValue(GAMEOBJECT_PARENTROTATION+0, rotation0);
SetFloatValue(GAMEOBJECT_PARENTROTATION+1, rotation1);
UpdateRotationFields(rotation2,rotation3); // GAMEOBJECT_FACING, GAMEOBJECT_ROTATION, GAMEOBJECT_PARENTROTATION+2/3
SetUInt32Value(GAMEOBJECT_FACTION, goinfo->faction);
SetUInt32Value(GAMEOBJECT_FLAGS, goinfo->flags);
if (goinfo->type == GAMEOBJECT_TYPE_TRANSPORT)
SetFlag(GAMEOBJECT_FLAGS, (GO_FLAG_TRANSPORT | GO_FLAG_NODESPAWN));
SetEntry(goinfo->id);
SetUInt32Value(GAMEOBJECT_DISPLAYID, goinfo->displayId);
// GAMEOBJECT_BYTES_1, index at 0, 1, 2 and 3
SetGoState(go_state);
SetGoType(GameobjectTypes(goinfo->type));
SetGoArtKit(0); // unknown what this is
SetGoAnimProgress(animprogress);
//Notify the map's instance data.
//Only works if you create the object in it, not if it is moves to that map.
//Normally non-players do not teleport to other maps.
if(map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
{
((InstanceMap*)map)->GetInstanceData()->OnObjectCreate(this);
}
return true;
}
void GameObject::Update(uint32 /*p_time*/)
{
if (GetObjectGuid().IsMOTransport())
{
//((Transport*)this)->Update(p_time);
return;
}
switch (m_lootState)
{
case GO_NOT_READY:
{
switch(GetGoType())
{
case GAMEOBJECT_TYPE_TRAP:
{
// Arming Time for GAMEOBJECT_TYPE_TRAP (6)
Unit* owner = GetOwner();
if (owner && ((Player*)owner)->isInCombat())
m_cooldownTime = time(NULL) + GetGOInfo()->trap.startDelay;
m_lootState = GO_READY;
break;
}
case GAMEOBJECT_TYPE_FISHINGNODE:
{
// fishing code (bobber ready)
if (time(NULL) > m_respawnTime - FISHING_BOBBER_READY_TIME)
{
// splash bobber (bobber ready now)
Unit* caster = GetOwner();
if (caster && caster->GetTypeId() == TYPEID_PLAYER)
{
SetGoState(GO_STATE_ACTIVE);
// SetUInt32Value(GAMEOBJECT_FLAGS, GO_FLAG_NODESPAWN);
UpdateData udata;
WorldPacket packet;
BuildValuesUpdateBlockForPlayer(&udata,((Player*)caster));
udata.BuildPacket(&packet);
((Player*)caster)->GetSession()->SendPacket(&packet);
SendGameObjectCustomAnim(GetGUID());
}
m_lootState = GO_READY; // can be successfully open with some chance
}
return;
}
default:
m_lootState = GO_READY; // for other GO is same switched without delay to GO_READY
break;
}
// NO BREAK for switch (m_lootState)
}
case GO_READY:
{
if (m_respawnTime > 0) // timer on
{
if (m_respawnTime <= time(NULL)) // timer expired
{
m_respawnTime = 0;
ClearAllUsesData();
switch (GetGoType())
{
case GAMEOBJECT_TYPE_FISHINGNODE: // can't fish now
{
Unit* caster = GetOwner();
if (caster && caster->GetTypeId() == TYPEID_PLAYER)
{
caster->FinishSpell(CURRENT_CHANNELED_SPELL);
WorldPacket data(SMSG_FISH_NOT_HOOKED,0);
((Player*)caster)->GetSession()->SendPacket(&data);
}
// can be deleted
m_lootState = GO_JUST_DEACTIVATED;
return;
}
case GAMEOBJECT_TYPE_DOOR:
case GAMEOBJECT_TYPE_BUTTON:
//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)
if (GetGoState() != GO_STATE_READY)
ResetDoorOrButton();
//flags in AB are type_button and we need to add them here so no break!
default:
if (!m_spawnedByDefault) // despawn timer
{
// can be despawned or destroyed
SetLootState(GO_JUST_DEACTIVATED);
return;
}
// respawn timer
GetMap()->Add(this);
break;
}
}
}
if (isSpawned())
{
// traps can have time and can not have
GameObjectInfo const* goInfo = GetGOInfo();
if (goInfo->type == GAMEOBJECT_TYPE_TRAP)
{
if (m_cooldownTime >= time(NULL))
return;
// traps
Unit* owner = GetOwner();
Unit* ok = NULL; // pointer to appropriate target if found any
bool IsBattleGroundTrap = false;
//FIXME: this is activation radius (in different casting radius that must be selected from spell data)
//TODO: move activated state code (cast itself) to GO_ACTIVATED, in this place only check activating and set state
float radius = float(goInfo->trap.radius);
if (!radius)
{
if (goInfo->trap.cooldown != 3) // cast in other case (at some triggering/linked go/etc explicit call)
return;
else
{
if (m_respawnTime > 0)
break;
// battlegrounds gameobjects has data2 == 0 && data5 == 3
radius = float(goInfo->trap.cooldown);
IsBattleGroundTrap = true;
}
}
// Note: this hack with search required until GO casting not implemented
// search unfriendly creature
if (owner && goInfo->trap.charges > 0) // hunter trap
{
MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, owner, radius);
MaNGOS::UnitSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> checker(ok, u_check);
Cell::VisitGridObjects(this,checker, radius);
if (!ok)
Cell::VisitWorldObjects(this,checker, radius);
}
else // environmental trap
{
// environmental damage spells already have around enemies targeting but this not help in case nonexistent GO casting support
// affect only players
Player* p_ok = NULL;
MaNGOS::AnyPlayerInObjectRangeCheck p_check(this, radius);
MaNGOS::PlayerSearcher<MaNGOS::AnyPlayerInObjectRangeCheck> checker(p_ok, p_check);
Cell::VisitWorldObjects(this,checker, radius);
ok = p_ok;
}
if (ok)
{
Unit *caster = owner ? owner : ok;
caster->CastSpell(ok, goInfo->trap.spellId, true, NULL, NULL, GetGUID());
// use template cooldown if provided
m_cooldownTime = time(NULL) + (goInfo->trap.cooldown ? goInfo->trap.cooldown : uint32(4));
// count charges
if (goInfo->trap.charges > 0)
AddUse();
if (IsBattleGroundTrap && ok->GetTypeId() == TYPEID_PLAYER)
{
//BattleGround gameobjects case
if (((Player*)ok)->InBattleGround())
if (BattleGround *bg = ((Player*)ok)->GetBattleGround())
bg->HandleTriggerBuff(GetGUID());
}
}
}
if (uint32 max_charges = goInfo->GetCharges())
{
if (m_useTimes >= max_charges)
{
m_useTimes = 0;
SetLootState(GO_JUST_DEACTIVATED); // can be despawned or destroyed
}
}
}
break;
}
case GO_ACTIVATED:
{
switch(GetGoType())
{
case GAMEOBJECT_TYPE_DOOR:
case GAMEOBJECT_TYPE_BUTTON:
if (GetGOInfo()->GetAutoCloseTime() && (m_cooldownTime < time(NULL)))
ResetDoorOrButton();
break;
case GAMEOBJECT_TYPE_GOOBER:
if (m_cooldownTime < time(NULL))
{
RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
SetLootState(GO_JUST_DEACTIVATED);
m_cooldownTime = 0;
}
break;
default:
break;
}
break;
}
case GO_JUST_DEACTIVATED:
{
// if Gameobject should cast spell, then this, but some GOs (type = 10) should be destroyed
if (GetGoType() == GAMEOBJECT_TYPE_GOOBER)
{
uint32 spellId = GetGOInfo()->goober.spellId;
if (spellId)
{
for (GuidsSet::const_iterator itr = m_UniqueUsers.begin(); itr != m_UniqueUsers.end(); ++itr)
{
if (Player* owner = GetMap()->GetPlayer(*itr))
owner->CastSpell(owner, spellId, false, NULL, NULL, GetGUID());
}
ClearAllUsesData();
}
SetGoState(GO_STATE_READY);
//any return here in case battleground traps
}
if (GetOwnerGUID())
{
if (Unit* owner = GetOwner())
owner->RemoveGameObject(this, false);
SetRespawnTime(0);
Delete();
return;
}
// burning flags in some battlegrounds, if you find better condition, just add it
if (GetGOInfo()->IsDespawnAtAction() || GetGoAnimProgress() > 0)
{
SendObjectDeSpawnAnim(GetGUID());
//reset flags
SetUInt32Value(GAMEOBJECT_FLAGS, GetGOInfo()->flags);
}
loot.clear();
SetLootState(GO_READY);
if (!m_respawnDelayTime)
return;
// since pool system can fail to roll unspawned object, this one can remain spawned, so must set respawn nevertheless
m_respawnTime = m_spawnedByDefault ? time(NULL) + m_respawnDelayTime : 0;
// if option not set then object will be saved at grid unload
if (sWorld.getConfig(CONFIG_BOOL_SAVE_RESPAWN_TIME_IMMEDIATLY))
SaveRespawnTime();
// if part of pool, let pool system schedule new spawn instead of just scheduling respawn
if (uint16 poolid = GetDBTableGUIDLow() ? sPoolMgr.IsPartOfAPool<GameObject>(GetDBTableGUIDLow()) : 0)
sPoolMgr.UpdatePool<GameObject>(poolid, GetDBTableGUIDLow());
// can be not in world at pool despawn
if (IsInWorld())
UpdateObjectVisibility();
break;
}
}
}
void GameObject::Refresh()
{
// not refresh despawned not casted GO (despawned casted GO destroyed in all cases anyway)
if(m_respawnTime > 0 && m_spawnedByDefault)
return;
if(isSpawned())
GetMap()->Add(this);
}
void GameObject::AddUniqueUse(Player* player)
{
AddUse();
if (m_firstUser.IsEmpty())
m_firstUser = player->GetObjectGuid();
m_UniqueUsers.insert(player->GetObjectGuid());
}
void GameObject::Delete()
{
SendObjectDeSpawnAnim(GetGUID());
SetGoState(GO_STATE_READY);
SetUInt32Value(GAMEOBJECT_FLAGS, GetGOInfo()->flags);
uint16 poolid = GetDBTableGUIDLow() ? sPoolMgr.IsPartOfAPool<GameObject>(GetDBTableGUIDLow()) : 0;
if (poolid)
sPoolMgr.UpdatePool<GameObject>(poolid, GetDBTableGUIDLow());
else
AddObjectToRemoveList();
}
void GameObject::getFishLoot(Loot *fishloot, Player* loot_owner)
{
fishloot->clear();
uint32 zone, subzone;
GetZoneAndAreaId(zone,subzone);
// if subzone loot exist use it
if (!fishloot->FillLoot(subzone, LootTemplates_Fishing, loot_owner, true, true))
// else use zone loot (must exist in like case)
fishloot->FillLoot(zone, LootTemplates_Fishing, loot_owner,true);
}
void GameObject::SaveToDB()
{
// this should only be used when the gameobject has already been loaded
// preferably after adding to map, because mapid may not be valid otherwise
GameObjectData const *data = sObjectMgr.GetGOData(m_DBTableGuid);
if(!data)
{
sLog.outError("GameObject::SaveToDB failed, cannot get gameobject data!");
return;
}
SaveToDB(GetMapId(), data->spawnMask, data->phaseMask);
}
void GameObject::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask)
{
const GameObjectInfo *goI = GetGOInfo();
if (!goI)
return;
if (!m_DBTableGuid)
m_DBTableGuid = GetGUIDLow();
// update in loaded data (changing data only in this place)
GameObjectData& data = sObjectMgr.NewGOData(m_DBTableGuid);
// data->guid = guid don't must be update at save
data.id = GetEntry();
data.mapid = mapid;
data.phaseMask = phaseMask;
data.posX = GetPositionX();
data.posY = GetPositionY();
data.posZ = GetPositionZ();
data.orientation = GetOrientation();
data.rotation0 = GetFloatValue(GAMEOBJECT_PARENTROTATION+0);
data.rotation1 = GetFloatValue(GAMEOBJECT_PARENTROTATION+1);
data.rotation2 = GetFloatValue(GAMEOBJECT_PARENTROTATION+2);
data.rotation3 = GetFloatValue(GAMEOBJECT_PARENTROTATION+3);
data.spawntimesecs = m_spawnedByDefault ? (int32)m_respawnDelayTime : -(int32)m_respawnDelayTime;
data.animprogress = GetGoAnimProgress();
data.go_state = GetGoState();
data.spawnMask = spawnMask;
// updated in DB
std::ostringstream ss;
ss << "INSERT INTO gameobject VALUES ( "
<< m_DBTableGuid << ", "
<< GetEntry() << ", "
<< mapid << ", "
<< uint32(spawnMask) << "," // cast to prevent save as symbol
<< uint16(GetPhaseMask()) << "," // prevent out of range error
<< GetPositionX() << ", "
<< GetPositionY() << ", "
<< GetPositionZ() << ", "
<< GetOrientation() << ", "
<< GetFloatValue(GAMEOBJECT_PARENTROTATION) << ", "
<< GetFloatValue(GAMEOBJECT_PARENTROTATION+1) << ", "
<< GetFloatValue(GAMEOBJECT_PARENTROTATION+2) << ", "
<< GetFloatValue(GAMEOBJECT_PARENTROTATION+3) << ", "
<< m_respawnDelayTime << ", "
<< uint32(GetGoAnimProgress()) << ", "
<< uint32(GetGoState()) << ")";
WorldDatabase.BeginTransaction();
WorldDatabase.PExecuteLog("DELETE FROM gameobject WHERE guid = '%u'", m_DBTableGuid);
WorldDatabase.PExecuteLog("%s", ss.str().c_str());
WorldDatabase.CommitTransaction();
}
bool GameObject::LoadFromDB(uint32 guid, Map *map)
{
GameObjectData const* data = sObjectMgr.GetGOData(guid);
if( !data )
{
sLog.outErrorDb("Gameobject (GUID: %u) not found in table `gameobject`, can't load. ",guid);
return false;
}
uint32 entry = data->id;
//uint32 map_id = data->mapid; // already used before call
uint32 phaseMask = data->phaseMask;
float x = data->posX;
float y = data->posY;
float z = data->posZ;
float ang = data->orientation;
float rotation0 = data->rotation0;
float rotation1 = data->rotation1;
float rotation2 = data->rotation2;
float rotation3 = data->rotation3;
uint8 animprogress = data->animprogress;
GOState go_state = data->go_state;
m_DBTableGuid = guid;
if (map->GetInstanceId() != 0) guid = sObjectMgr.GenerateLowGuid(HIGHGUID_GAMEOBJECT);
if (!Create(guid,entry, map, phaseMask, x, y, z, ang, rotation0, rotation1, rotation2, rotation3, animprogress, go_state) )
return false;
if (!GetGOInfo()->GetDespawnPossibility() && !GetGOInfo()->IsDespawnAtAction() && data->spawntimesecs >= 0)
{
SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NODESPAWN);
m_spawnedByDefault = true;
m_respawnDelayTime = 0;
m_respawnTime = 0;
}
else
{
if(data->spawntimesecs >= 0)
{
m_spawnedByDefault = true;
m_respawnDelayTime = data->spawntimesecs;
m_respawnTime = sObjectMgr.GetGORespawnTime(m_DBTableGuid, map->GetInstanceId());
// ready to respawn
if(m_respawnTime && m_respawnTime <= time(NULL))
{
m_respawnTime = 0;
sObjectMgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),0);
}
}
else
{
m_spawnedByDefault = false;
m_respawnDelayTime = -data->spawntimesecs;
m_respawnTime = 0;
}
}
return true;
}
void GameObject::DeleteFromDB()
{
sObjectMgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),0);
sObjectMgr.DeleteGOData(m_DBTableGuid);
WorldDatabase.PExecuteLog("DELETE FROM gameobject WHERE guid = '%u'", m_DBTableGuid);
WorldDatabase.PExecuteLog("DELETE FROM game_event_gameobject WHERE guid = '%u'", m_DBTableGuid);
WorldDatabase.PExecuteLog("DELETE FROM gameobject_battleground WHERE guid = '%u'", m_DBTableGuid);
}
GameObjectInfo const *GameObject::GetGOInfo() const
{
return m_goInfo;
}
/*********************************************************/
/*** QUEST SYSTEM ***/
/*********************************************************/
bool GameObject::HasQuest(uint32 quest_id) const
{
QuestRelationsMapBounds bounds = sObjectMgr.GetGOQuestRelationsMapBounds(GetEntry());
for(QuestRelationsMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr)
{
if (itr->second == quest_id)
return true;
}
return false;
}
bool GameObject::HasInvolvedQuest(uint32 quest_id) const
{
QuestRelationsMapBounds bounds = sObjectMgr.GetGOQuestInvolvedRelationsMapBounds(GetEntry());
for(QuestRelationsMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr)
{
if (itr->second == quest_id)
return true;
}
return false;
}
bool GameObject::IsTransport() const
{
// If something is marked as a transport, don't transmit an out of range packet for it.
GameObjectInfo const * gInfo = GetGOInfo();
if(!gInfo) return false;
return gInfo->type == GAMEOBJECT_TYPE_TRANSPORT || gInfo->type == GAMEOBJECT_TYPE_MO_TRANSPORT;
}
Unit* GameObject::GetOwner() const
{
return ObjectAccessor::GetUnit(*this, GetOwnerGUID());
}
void GameObject::SaveRespawnTime()
{
if(m_respawnTime > time(NULL) && m_spawnedByDefault)
sObjectMgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
}
bool GameObject::isVisibleForInState(Player const* u, WorldObject const* viewPoint, bool inVisibleList) const
{
// Not in world
if(!IsInWorld() || !u->IsInWorld())
return false;
// invisible at client always
if(!GetGOInfo()->displayId)
return false;
// Transport always visible at this step implementation
if(IsTransport() && IsInMap(u))
return true;
// quick check visibility false cases for non-GM-mode
if(!u->isGameMaster())
{
// despawned and then not visible for non-GM in GM-mode
if(!isSpawned())
return false;
// special invisibility cases
/* TODO: implement trap stealth, take look at spell 2836
if(GetGOInfo()->type == GAMEOBJECT_TYPE_TRAP && GetGOInfo()->trap.stealthed && u->IsHostileTo(GetOwner()))
{
if(check stuff here)
return false;
}*/
}
// check distance
return IsWithinDistInMap(viewPoint,World::GetMaxVisibleDistanceForObject() +
(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), false);
}
void GameObject::Respawn()
{
if(m_spawnedByDefault && m_respawnTime > 0)
{
m_respawnTime = time(NULL);
sObjectMgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),0);
}
}
bool GameObject::ActivateToQuest(Player *pTarget)const
{
// if GO is ReqCreatureOrGoN for quest
if (pTarget->HasQuestForGO(GetEntry()))
return true;
if (!sObjectMgr.IsGameObjectForQuests(GetEntry()))
return false;
switch(GetGoType())
{
case GAMEOBJECT_TYPE_QUESTGIVER:
{
// Not fully clear when GO's can activate/deactivate
// For cases where GO has additional (except quest itself),
// these conditions are not sufficient/will fail.
// Never expect flags|4 for these GO's? (NF-note: It doesn't appear it's expected)
QuestRelationsMapBounds bounds = sObjectMgr.GetGOQuestRelationsMapBounds(GetEntry());
for(QuestRelationsMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr)
{
const Quest *qInfo = sObjectMgr.GetQuestTemplate(itr->second);
if (pTarget->CanTakeQuest(qInfo, false))
return true;
}
bounds = sObjectMgr.GetGOQuestInvolvedRelationsMapBounds(GetEntry());
for(QuestRelationsMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr)
{
if ((pTarget->GetQuestStatus(itr->second) == QUEST_STATUS_INCOMPLETE || pTarget->GetQuestStatus(itr->second) == QUEST_STATUS_COMPLETE)
&& !pTarget->GetQuestRewardStatus(itr->second))
return true;
}
break;
}
// scan GO chest with loot including quest items
case GAMEOBJECT_TYPE_CHEST:
{
if (pTarget->GetQuestStatus(GetGOInfo()->chest.questId) == QUEST_STATUS_INCOMPLETE)
return true;
if (LootTemplates_Gameobject.HaveQuestLootForPlayer(GetGOInfo()->GetLootId(), pTarget))
{
//look for battlegroundAV for some objects which are only activated after mine gots captured by own team
if (GetEntry() == BG_AV_OBJECTID_MINE_N || GetEntry() == BG_AV_OBJECTID_MINE_S)
if (BattleGround *bg = pTarget->GetBattleGround())
if (bg->GetTypeID() == BATTLEGROUND_AV && !(((BattleGroundAV*)bg)->PlayerCanDoMineQuest(GetEntry(),pTarget->GetTeam())))
return false;
return true;
}
break;
}
case GAMEOBJECT_TYPE_GENERIC:
{
if (pTarget->GetQuestStatus(GetGOInfo()->_generic.questID) == QUEST_STATUS_INCOMPLETE)
return true;
break;
}
case GAMEOBJECT_TYPE_SPELL_FOCUS:
{
if (pTarget->GetQuestStatus(GetGOInfo()->spellFocus.questID) == QUEST_STATUS_INCOMPLETE)
return true;
break;
}
case GAMEOBJECT_TYPE_GOOBER:
{
if (pTarget->GetQuestStatus(GetGOInfo()->goober.questId) == QUEST_STATUS_INCOMPLETE)
return true;
break;
}
default:
break;
}
return false;
}
void GameObject::SummonLinkedTrapIfAny()
{
uint32 linkedEntry = GetGOInfo()->GetLinkedGameObjectEntry();
if (!linkedEntry)
return;
GameObject* linkedGO = new GameObject;
if (!linkedGO->Create(sObjectMgr.GenerateLowGuid(HIGHGUID_GAMEOBJECT), linkedEntry, GetMap(),
GetPhaseMask(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, GO_ANIMPROGRESS_DEFAULT, GO_STATE_READY))
{
delete linkedGO;
linkedGO = NULL;
return;
}
linkedGO->SetRespawnTime(GetRespawnDelay());
linkedGO->SetSpellId(GetSpellId());
if (GetOwnerGUID())
{
linkedGO->SetOwnerGUID(GetOwnerGUID());
linkedGO->SetUInt32Value(GAMEOBJECT_LEVEL, GetUInt32Value(GAMEOBJECT_LEVEL));
}
GetMap()->Add(linkedGO);
}
void GameObject::TriggeringLinkedGameObject( uint32 trapEntry, Unit* target)
{
GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(trapEntry);
if(!trapInfo || trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
return;
SpellEntry const* trapSpell = sSpellStore.LookupEntry(trapInfo->trap.spellId);
if(!trapSpell) // checked at load already
return;
float range = GetSpellMaxRange(sSpellRangeStore.LookupEntry(trapSpell->rangeIndex));
// search nearest linked GO
GameObject* trapGO = NULL;
{
// using original GO distance
MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*target,trapEntry,range);
MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(trapGO,go_check);
Cell::VisitGridObjects(this, checker, range);
}
// found correct GO
// FIXME: when GO casting will be implemented trap must cast spell to target
if(trapGO)
target->CastSpell(target, trapSpell, true, NULL, NULL, GetGUID());
}
GameObject* GameObject::LookupFishingHoleAround(float range)
{
GameObject* ok = NULL;
MaNGOS::NearestGameObjectFishingHoleCheck u_check(*this, range);
MaNGOS::GameObjectSearcher<MaNGOS::NearestGameObjectFishingHoleCheck> checker(ok, u_check);
Cell::VisitGridObjects(this,checker, range);
return ok;
}
void GameObject::ResetDoorOrButton()
{
if (m_lootState == GO_READY || m_lootState == GO_JUST_DEACTIVATED)
return;
SwitchDoorOrButton(false);
SetLootState(GO_JUST_DEACTIVATED);
m_cooldownTime = 0;
}
void GameObject::UseDoorOrButton(uint32 time_to_restore, bool alternative /* = false */)
{
if(m_lootState != GO_READY)
return;
if(!time_to_restore)
time_to_restore = GetGOInfo()->GetAutoCloseTime();
SwitchDoorOrButton(true,alternative);
SetLootState(GO_ACTIVATED);
m_cooldownTime = time(NULL) + time_to_restore;
}
void GameObject::SwitchDoorOrButton(bool activate, bool alternative /* = false */)
{
if(activate)
SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
else
RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
if(GetGoState() == GO_STATE_READY) //if closed -> open
SetGoState(alternative ? GO_STATE_ACTIVE_ALTERNATIVE : GO_STATE_ACTIVE);
else //if open -> close
SetGoState(GO_STATE_READY);
}
void GameObject::Use(Unit* user)
{
// by default spell caster is user
Unit* spellCaster = user;
uint32 spellId = 0;
bool triggered = false;
if (user->GetTypeId() == TYPEID_PLAYER && Script->GOHello((Player*)user, this))
return;
switch(GetGoType())
{
case GAMEOBJECT_TYPE_DOOR: //0
{
//doors never really despawn, only reset to default state/flags
UseDoorOrButton();
// activate script
GetMap()->ScriptsStart(sGameObjectScripts, GetDBTableGUIDLow(), spellCaster, this);
return;
}
case GAMEOBJECT_TYPE_BUTTON: //1
{
//buttons never really despawn, only reset to default state/flags
UseDoorOrButton();
// activate script
GetMap()->ScriptsStart(sGameObjectScripts, GetDBTableGUIDLow(), spellCaster, this);
// triggering linked GO
if (uint32 trapEntry = GetGOInfo()->button.linkedTrapId)
TriggeringLinkedGameObject(trapEntry, user);
return;
}
case GAMEOBJECT_TYPE_QUESTGIVER: //2
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
if (!Script->GOGossipHello(player, this))
{
player->PrepareGossipMenu(this, GetGOInfo()->questgiver.gossipID);
player->SendPreparedGossip(this);
}
return;
}
case GAMEOBJECT_TYPE_CHEST:
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
// TODO: possible must be moved to loot release (in different from linked triggering)
if (GetGOInfo()->chest.eventId)
{
DEBUG_LOG("Chest ScriptStart id %u for GO %u", GetGOInfo()->chest.eventId, GetDBTableGUIDLow());
if (!Script->ProcessEventId(GetGOInfo()->chest.eventId, user, this, true))
GetMap()->ScriptsStart(sEventScripts, GetGOInfo()->chest.eventId, user, this);
}
// triggering linked GO
if (uint32 trapEntry = GetGOInfo()->chest.linkedTrapId)
TriggeringLinkedGameObject(trapEntry, user);
return;
}
case GAMEOBJECT_TYPE_GENERIC: // 5
{
// No known way to exclude some - only different approach is to select despawnable GOs by Entry
SetLootState(GO_JUST_DEACTIVATED);
return;
}
case GAMEOBJECT_TYPE_CHAIR: //7 Sitting: Wooden bench, chairs
{
GameObjectInfo const* info = GetGOInfo();
if (!info)
return;
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
// a chair may have n slots. we have to calculate their positions and teleport the player to the nearest one
// check if the db is sane
if (info->chair.slots > 0)
{
float lowestDist = DEFAULT_VISIBILITY_DISTANCE;
float x_lowest = GetPositionX();
float y_lowest = GetPositionY();
// the object orientation + 1/2 pi
// every slot will be on that straight line
float orthogonalOrientation = GetOrientation()+M_PI_F*0.5f;
// find nearest slot
for(uint32 i=0; i<info->chair.slots; ++i)
{
// the distance between this slot and the center of the go - imagine a 1D space
float relativeDistance = (info->size*i)-(info->size*(info->chair.slots-1)/2.0f);
float x_i = GetPositionX() + relativeDistance * cos(orthogonalOrientation);
float y_i = GetPositionY() + relativeDistance * sin(orthogonalOrientation);
// calculate the distance between the player and this slot
float thisDistance = player->GetDistance2d(x_i, y_i);
/* debug code. It will spawn a npc on each slot to visualize them.
Creature* helper = player->SummonCreature(14496, x_i, y_i, GetPositionZ(), GetOrientation(), TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 10000);
std::ostringstream output;
output << i << ": thisDist: " << thisDistance;
helper->MonsterSay(output.str().c_str(), LANG_UNIVERSAL, 0);
*/
if (thisDistance <= lowestDist)
{
lowestDist = thisDistance;
x_lowest = x_i;
y_lowest = y_i;
}
}
player->TeleportTo(GetMapId(), x_lowest, y_lowest, GetPositionZ(), GetOrientation(),TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET);
}
else
{
// fallback, will always work
player->TeleportTo(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation(),TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET);
}
player->SetStandState(UNIT_STAND_STATE_SIT_LOW_CHAIR+info->chair.height);
return;
}
case GAMEOBJECT_TYPE_SPELL_FOCUS:
{
// triggering linked GO
if (uint32 trapEntry = GetGOInfo()->spellFocus.linkedTrapId)
TriggeringLinkedGameObject(trapEntry, user);
// some may be activated in addition? Conditions for this? (ex: entry 181616)
break;
}
case GAMEOBJECT_TYPE_GOOBER: //10
{
GameObjectInfo const* info = GetGOInfo();
if (user->GetTypeId() == TYPEID_PLAYER)
{
Player* player = (Player*)user;
if (info->goober.pageId) // show page...
{
WorldPacket data(SMSG_GAMEOBJECT_PAGETEXT, 8);
data << GetGUID();
player->GetSession()->SendPacket(&data);
}
else if (info->goober.gossipID) // ...or gossip, if page does not exist
{
if (!Script->GOGossipHello(player, this))
{
player->PrepareGossipMenu(this, info->goober.gossipID);
player->SendPreparedGossip(this);
}
}
if (info->goober.eventId)
{
DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Goober ScriptStart id %u for GO entry %u (GUID %u).", info->goober.eventId, GetEntry(), GetDBTableGUIDLow());
if (!Script->ProcessEventId(info->goober.eventId, player, this, true))
GetMap()->ScriptsStart(sEventScripts, info->goober.eventId, player, this);
}
// possible quest objective for active quests
if (info->goober.questId && sObjectMgr.GetQuestTemplate(info->goober.questId))
{
//Quest require to be active for GO using
if (player->GetQuestStatus(info->goober.questId) != QUEST_STATUS_INCOMPLETE)
break;
}
player->RewardPlayerAndGroupAtCast(this);
}
if (uint32 trapEntry = info->goober.linkedTrapId)
TriggeringLinkedGameObject(trapEntry, user);
SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
SetLootState(GO_ACTIVATED);
uint32 time_to_restore = info->GetAutoCloseTime();
// this appear to be ok, however others exist in addition to this that should have custom (ex: 190510, 188692, 187389)
if (time_to_restore && info->goober.customAnim)
SendGameObjectCustomAnim(GetGUID());
else
SetGoState(GO_STATE_ACTIVE);
m_cooldownTime = time(NULL) + time_to_restore;
// cast this spell later if provided
spellId = info->goober.spellId;
// database may contain a dummy spell, so it need replacement by actually existing
switch(spellId)
{
case 34448: spellId = 26566; break;
case 34452: spellId = 26572; break;
case 37639: spellId = 36326; break;
case 45367: spellId = 45371; break;
case 45370: spellId = 45368; break;
}
break;
}
case GAMEOBJECT_TYPE_CAMERA: //13
{
GameObjectInfo const* info = GetGOInfo();
if (!info)
return;
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
if (info->camera.cinematicId)
player->SendCinematicStart(info->camera.cinematicId);
if (info->camera.eventID)
{
if (!Script->ProcessEventId(info->camera.eventID, player, this, true))
GetMap()->ScriptsStart(sEventScripts, info->camera.eventID, player, this);
}
return;
}
case GAMEOBJECT_TYPE_FISHINGNODE: //17 fishing bobber
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
if (player->GetGUID() != GetOwnerGUID())
return;
switch(getLootState())
{
case GO_READY: // ready for loot
{
// 1) skill must be >= base_zone_skill
// 2) if skill == base_zone_skill => 5% chance
// 3) chance is linear dependence from (base_zone_skill-skill)
uint32 zone, subzone;
GetZoneAndAreaId(zone,subzone);
int32 zone_skill = sObjectMgr.GetFishingBaseSkillLevel(subzone);
if (!zone_skill)
zone_skill = sObjectMgr.GetFishingBaseSkillLevel(zone);
//provide error, no fishable zone or area should be 0
if (!zone_skill)
sLog.outErrorDb("Fishable areaId %u are not properly defined in `skill_fishing_base_level`.",subzone);
int32 skill = player->GetSkillValue(SKILL_FISHING);
int32 chance = skill - zone_skill + 5;
int32 roll = irand(1,100);
DEBUG_LOG("Fishing check (skill: %i zone min skill: %i chance %i roll: %i",skill,zone_skill,chance,roll);
if (skill >= zone_skill && chance >= roll)
{
// prevent removing GO at spell cancel
player->RemoveGameObject(this,false);
SetOwnerGUID(player->GetGUID());
//fish catched
player->UpdateFishingSkill();
//TODO: find reasonable value for fishing hole search
GameObject* ok = LookupFishingHoleAround(20.0f + CONTACT_DISTANCE);
if (ok)
{
ok->Use(player);
SetLootState(GO_JUST_DEACTIVATED);
}
else
player->SendLoot(GetObjectGuid(),LOOT_FISHING);
}
else
{
// fish escaped, can be deleted now
SetLootState(GO_JUST_DEACTIVATED);
WorldPacket data(SMSG_FISH_ESCAPED, 0);
player->GetSession()->SendPacket(&data);
}
break;
}
case GO_JUST_DEACTIVATED: // nothing to do, will be deleted at next update
break;
default:
{
SetLootState(GO_JUST_DEACTIVATED);
WorldPacket data(SMSG_FISH_NOT_HOOKED, 0);
player->GetSession()->SendPacket(&data);
break;
}
}
player->FinishSpell(CURRENT_CHANNELED_SPELL);
return;
}
case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
Unit* owner = GetOwner();
GameObjectInfo const* info = GetGOInfo();
if (owner)
{
if (owner->GetTypeId() != TYPEID_PLAYER)
return;
// accept only use by player from same group as owner, excluding owner itself (unique use already added in spell effect)
if (player == (Player*)owner || (info->summoningRitual.castersGrouped && !player->IsInSameRaidWith(((Player*)owner))))
return;
// expect owner to already be channeling, so if not...
if (!owner->GetCurrentSpell(CURRENT_CHANNELED_SPELL))
return;
// in case summoning ritual caster is GO creator
spellCaster = owner;
}
else
{
if (!m_firstUser.IsEmpty() && player->GetObjectGuid() != m_firstUser && info->summoningRitual.castersGrouped)
{
if (Group* group = player->GetGroup())
{
if (!group->IsMember(m_firstUser))
return;
}
else
return;
}
spellCaster = player;
}
AddUniqueUse(player);
if (info->summoningRitual.animSpell)
{
player->CastSpell(player, info->summoningRitual.animSpell, true);
// for this case, summoningRitual.spellId is always triggered
triggered = true;
}
// full amount unique participants including original summoner, need more
if (GetUniqueUseCount() < info->summoningRitual.reqParticipants)
return;
spellCaster = GetMap()->GetPlayer(m_firstUser);
spellId = info->summoningRitual.spellId;
if (spellId == 62330) // GO store nonexistent spell, replace by expected
spellId = 61993;
// spell have reagent and mana cost but it not expected use its
// it triggered spell in fact casted at currently channeled GO
triggered = true;
// finish owners spell
if (owner)
owner->FinishSpell(CURRENT_CHANNELED_SPELL);
// can be deleted now, if
if (!info->summoningRitual.ritualPersistent)
SetLootState(GO_JUST_DEACTIVATED);
// reset ritual for this GO
else
ClearAllUsesData();
// go to end function to spell casting
break;
}
case GAMEOBJECT_TYPE_SPELLCASTER: //22
{
SetUInt32Value(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED);
GameObjectInfo const* info = GetGOInfo();
if (!info)
return;
if (info->spellcaster.partyOnly)
{
Unit* caster = GetOwner();
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
if (user->GetTypeId() != TYPEID_PLAYER || !((Player*)user)->IsInSameRaidWith((Player*)caster))
return;
}
spellId = info->spellcaster.spellId;
AddUse();
break;
}
case GAMEOBJECT_TYPE_MEETINGSTONE: //23
{
GameObjectInfo const* info = GetGOInfo();
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
Player* targetPlayer = ObjectAccessor::FindPlayer(player->GetSelectionGuid());
// accept only use by player from same group for caster except caster itself
if (!targetPlayer || targetPlayer == player || !targetPlayer->IsInSameGroupWith(player))
return;
//required lvl checks!
uint8 level = player->getLevel();
if (level < info->meetingstone.minLevel || level > info->meetingstone.maxLevel)
return;
level = targetPlayer->getLevel();
if (level < info->meetingstone.minLevel || level > info->meetingstone.maxLevel)
return;
if (info->id == 194097)
spellId = 61994; // Ritual of Summoning
else
spellId = 59782; // Summoning Stone Effect
break;
}
case GAMEOBJECT_TYPE_FLAGSTAND: // 24
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
if (player->CanUseBattleGroundObject())
{
// in battleground check
BattleGround *bg = player->GetBattleGround();
if (!bg)
return;
// BG flag click
// AB:
// 15001
// 15002
// 15003
// 15004
// 15005
bg->EventPlayerClickedOnFlag(player, this);
return; //we don't need to delete flag ... it is despawned!
}
break;
}
case GAMEOBJECT_TYPE_FISHINGHOLE: // 25
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
player->SendLoot(GetObjectGuid(), LOOT_FISHINGHOLE);
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT, GetGOInfo()->id);
return;
}
case GAMEOBJECT_TYPE_FLAGDROP: // 26
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
if (player->CanUseBattleGroundObject())
{
// in battleground check
BattleGround *bg = player->GetBattleGround();
if (!bg)
return;
// BG flag dropped
// WS:
// 179785 - Silverwing Flag
// 179786 - Warsong Flag
// EotS:
// 184142 - Netherstorm Flag
GameObjectInfo const* info = GetGOInfo();
if (info)
{
switch(info->id)
{
case 179785: // Silverwing Flag
// check if it's correct bg
if (bg->GetTypeID() == BATTLEGROUND_WS)
bg->EventPlayerClickedOnFlag(player, this);
break;
case 179786: // Warsong Flag
if (bg->GetTypeID() == BATTLEGROUND_WS)
bg->EventPlayerClickedOnFlag(player, this);
break;
case 184142: // Netherstorm Flag
if (bg->GetTypeID() == BATTLEGROUND_EY)
bg->EventPlayerClickedOnFlag(player, this);
break;
}
}
//this cause to call return, all flags must be deleted here!!
spellId = 0;
Delete();
}
break;
}
case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
{
GameObjectInfo const* info = GetGOInfo();
if (!info)
return;
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
// fallback, will always work
player->TeleportTo(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation(),TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET);
WorldPacket data(SMSG_ENABLE_BARBER_SHOP, 0);
player->GetSession()->SendPacket(&data);
player->SetStandState(UNIT_STAND_STATE_SIT_LOW_CHAIR+info->barberChair.chairheight);
return;
}
default:
sLog.outError("GameObject::Use unhandled GameObject type %u (entry %u).", GetGoType(), GetEntry());
break;
}
if (!spellId)
return;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
if (!spellInfo)
{
sLog.outError("WORLD: unknown spell id %u at use action for gameobject (Entry: %u GoType: %u )", spellId,GetEntry(),GetGoType());
return;
}
Spell *spell = new Spell(spellCaster, spellInfo, triggered,GetGUID());
// spell target is user of GO
SpellCastTargets targets;
targets.setUnitTarget(user);
spell->prepare(&targets);
}
// overwrite WorldObject function for proper name localization
const char* GameObject::GetNameForLocaleIdx(int32 loc_idx) const
{
if (loc_idx >= 0)
{
GameObjectLocale const *cl = sObjectMgr.GetGameObjectLocale(GetEntry());
if (cl)
{
if (cl->Name.size() > (size_t)loc_idx && !cl->Name[loc_idx].empty())
return cl->Name[loc_idx].c_str();
}
}
return GetName();
}
void GameObject::UpdateRotationFields(float rotation2 /*=0.0f*/, float rotation3 /*=0.0f*/)
{
static double const atan_pow = atan(pow(2.0f, -20.0f));
double f_rot1 = sin(GetOrientation() / 2.0f);
double f_rot2 = cos(GetOrientation() / 2.0f);
int64 i_rot1 = int64(f_rot1 / atan_pow *(f_rot2 >= 0 ? 1.0f : -1.0f));
int64 rotation = (i_rot1 << 43 >> 43) & 0x00000000001FFFFF;
//float f_rot2 = sin(0.0f / 2.0f);
//int64 i_rot2 = f_rot2 / atan(pow(2.0f, -20.0f));
//rotation |= (((i_rot2 << 22) >> 32) >> 11) & 0x000003FFFFE00000;
//float f_rot3 = sin(0.0f / 2.0f);
//int64 i_rot3 = f_rot3 / atan(pow(2.0f, -21.0f));
//rotation |= (i_rot3 >> 42) & 0x7FFFFC0000000000;
m_rotation = rotation;
if(rotation2==0.0f && rotation3==0.0f)
{
rotation2 = (float)f_rot1;
rotation3 = (float)f_rot2;
}
SetFloatValue(GAMEOBJECT_PARENTROTATION+2, rotation2);
SetFloatValue(GAMEOBJECT_PARENTROTATION+3, rotation3);
}
bool GameObject::IsHostileTo(Unit const* unit) const
{
// always non-hostile to GM in GM mode
if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
return false;
// test owner instead if have
if (Unit const* owner = GetOwner())
return owner->IsHostileTo(unit);
if (Unit const* targetOwner = unit->GetCharmerOrOwner())
return IsHostileTo(targetOwner);
// for not set faction case (wild object) use hostile case
if(!GetGOInfo()->faction)
return true;
// faction base cases
FactionTemplateEntry const*tester_faction = sFactionTemplateStore.LookupEntry(GetGOInfo()->faction);
FactionTemplateEntry const*target_faction = unit->getFactionTemplateEntry();
if(!tester_faction || !target_faction)
return false;
// GvP forced reaction and reputation case
if(unit->GetTypeId()==TYPEID_PLAYER)
{
// forced reaction
if(tester_faction->faction)
{
if(ReputationRank const* force = ((Player*)unit)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
return *force <= REP_HOSTILE;
// apply reputation state
FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction);
if(raw_tester_faction && raw_tester_faction->reputationListID >=0 )
return ((Player const*)unit)->GetReputationMgr().GetRank(raw_tester_faction) <= REP_HOSTILE;
}
}
// common faction based case (GvC,GvP)
return tester_faction->IsHostileTo(*target_faction);
}
bool GameObject::IsFriendlyTo(Unit const* unit) const
{
// always friendly to GM in GM mode
if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
return true;
// test owner instead if have
if (Unit const* owner = GetOwner())
return owner->IsFriendlyTo(unit);
if (Unit const* targetOwner = unit->GetCharmerOrOwner())
return IsFriendlyTo(targetOwner);
// for not set faction case (wild object) use hostile case
if(!GetGOInfo()->faction)
return false;
// faction base cases
FactionTemplateEntry const*tester_faction = sFactionTemplateStore.LookupEntry(GetGOInfo()->faction);
FactionTemplateEntry const*target_faction = unit->getFactionTemplateEntry();
if(!tester_faction || !target_faction)
return false;
// GvP forced reaction and reputation case
if(unit->GetTypeId()==TYPEID_PLAYER)
{
// forced reaction
if(tester_faction->faction)
{
if(ReputationRank const* force =((Player*)unit)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
return *force >= REP_FRIENDLY;
// apply reputation state
if(FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction))
if(raw_tester_faction->reputationListID >=0 )
return ((Player const*)unit)->GetReputationMgr().GetRank(raw_tester_faction) >= REP_FRIENDLY;
}
}
// common faction based case (GvC,GvP)
return tester_faction->IsFriendlyTo(*target_faction);
}
float GameObject::GetObjectBoundingRadius() const
{
//FIXME:
// 1. This is clearly hack way because GameObjectDisplayInfoEntry have 6 floats related to GO sizes, but better that use DEFAULT_WORLD_OBJECT_SIZE
// 2. In some cases this must be only interactive size, not GO size, current way can affect creature target point auto-selection in strange ways for big underground/virtual GOs
if (GameObjectDisplayInfoEntry const* dispEntry = sGameObjectDisplayInfoStore.LookupEntry(GetGOInfo()->displayId))
return fabs(dispEntry->unknown12) * GetObjectScale();
return DEFAULT_WORLD_OBJECT_SIZE;
}
bool GameObject::IsInSkillupList(Player* player) const
{
return m_SkillupSet.find(player->GetObjectGuid()) != m_SkillupSet.end();
}
void GameObject::AddToSkillupList(Player* player)
{
m_SkillupSet.insert(player->GetObjectGuid());
} | gpl-2.0 |
swobspace/boskop | spec/features/networks_spec.rb | 2287 | require 'rails_helper'
RSpec.describe "Networks", :type => :feature do
let!(:net1) {FactoryBot.create(:network, netzwerk: '192.168.1.64/27')}
let!(:net2) {FactoryBot.create(:network, netzwerk: '192.168.0.0/23')}
let!(:net3) {FactoryBot.create(:network, netzwerk: '192.168.7.0/24')}
describe "GET /networks" do
it "visits networks#index" do
login_user
visit networks_path
expect(current_path).to eq(networks_path)
end
it "search for subsets of '192.168.1.0/24' get '192.168.1.64/27'" do
login_user
visit search_form_networks_path
within 'form' do
fill_in 'netzwerk', with: '192.168.1.0/24'
check 'is_subset'
uncheck 'is_superset'
click_button 'Suche'
end
expect(page).to have_content "192.168.1.64/27"
expect(page).not_to have_content "192.168.0.0/23"
expect(page).not_to have_content "192.168.7.0/24"
end
it "search for supersets of '192.168.1.0/24' get '192.168.0.0/23'" do
login_user
visit search_form_networks_path
within 'form' do
fill_in 'netzwerk', with: '192.168.1.0/24'
check 'is_superset'
uncheck 'is_subset'
click_button 'Suche'
end
expect(page).not_to have_content "192.168.1.64/27"
expect(page).to have_content "192.168.0.0/23"
expect(page).not_to have_content "192.168.7.0/24"
end
it "search for subset AND superset of '192.168.1.0/24' get '192.168.0.0/23' and '192.168.1.64/27'" do
login_user
visit search_form_networks_path
within 'form' do
fill_in 'netzwerk', with: '192.168.1.0/24'
check 'is_subset'
check 'is_superset'
click_button 'Suche'
end
expect(page).to have_content "192.168.1.64/27"
expect(page).to have_content "192.168.0.0/23"
expect(page).not_to have_content "192.168.7.0/24"
end
it "search for '192.168.7.0/24'" do
login_user
visit search_form_networks_path
within 'form' do
fill_in 'netzwerk', with: '192.168.7.0/24'
click_button 'Suche'
end
expect(page).not_to have_content "192.168.1.64/27"
expect(page).not_to have_content "192.168.0.0/23"
expect(page).to have_content "192.168.7.0/24"
end
end
end
| gpl-2.0 |
jonaseicher/faster-than-kerbal | Assets/UnityKit/Editor/UKEditorProgressBar.cs | 2985 | using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Text;
public class UKEditorProgressBar {
public class ProgressInfo {
public string Text;
public int MaxSteps;
public int Step;
public float Percentage {
get {
if (MaxSteps == 0) return 0f;
else return Mathf.Clamp01((float)(Step-1) / (float)MaxSteps);
}
}
public float PercentagePart {
get {
if (MaxSteps == 0) return 0f;
else return 1f / (float)MaxSteps;
}
}
public void Next(string text) {
++Step;
Text = text;
}
public override string ToString ()
{
return string.Format ("[ProgressInfo: Percentage={0}, PercentagePart={1}]", Percentage, PercentagePart);
}
}
public string Title;
public double LastUpdateTime = 0f;
public double UpdateTimeout = 1f;
public List<ProgressInfo> ProgressStack;
public UKEditorProgressBar(string title) {
Title = title;
ProgressStack = new List<ProgressInfo>();
}
public string Text() {
StringBuilder sb = new StringBuilder();
foreach(var p in ProgressStack) {
sb.Append(" / ");
sb.Append(p.Text);
}
return sb.ToString();
}
private float LayerMaxSize(int layer) {
if (layer <= 0) return 1f;
else {
return LayerMaxSize(layer - 1) * ProgressStack[layer - 1].PercentagePart;
}
}
public float Progress() {
if (ProgressStack.Count == 0) return 0f;
else if (ProgressStack.Count == 1) return ProgressStack[0].Percentage;
else {
float sum = 0f;
for(int layer = 0; layer < ProgressStack.Count; ++layer) {
sum += ProgressStack[layer].Percentage * LayerMaxSize(layer);
}
return sum;
}
}
public void Update() {
if (EditorApplication.timeSinceStartup - LastUpdateTime > UpdateTimeout) {
LastUpdateTime = EditorApplication.timeSinceStartup;
EditorUtility.DisplayProgressBar(Title, Text(), Progress());
}
/*
Debug.Log(Progress());
for(int layer = 0; layer < ProgressStack.Count; ++layer) {
Debug.Log(ProgressStack[layer]);
}
*/
}
public void Begin(int maxSteps) {
ProgressStack.Add(new ProgressInfo(){
MaxSteps = maxSteps,
Text = "",
Step = 0,
});
Update();
}
public void End() {
ProgressStack.RemoveAt(ProgressStack.Count - 1);
if (ProgressStack.Count == 0) EditorUtility.ClearProgressBar();
}
public void Next(string text) {
ProgressStack[ProgressStack.Count - 1].Next(text);
Update();
}
// -------------------------
private static UKEditorProgressBar TheBar = null;
public static void TheBarPrepare(string title) {
if (TheBar == null) {
EditorUtility.ClearProgressBar();
TheBar = new UKEditorProgressBar(title);
}
}
public static void TheBarBegin(int maxSteps) {
if (TheBar != null) TheBar.Begin(maxSteps);
}
public static void TheBarEnd() {
if (TheBar != null) TheBar.End();
if (TheBar.ProgressStack.Count == 0) TheBar = null;
}
public static void TheBarNext(string text) {
if (TheBar != null) TheBar.Next(text);
}
}
| gpl-2.0 |
mttronc/joomla_template_fwrethen | html/com_einsatzkomponente/einsatzarchiv/main_layout_1.php | 25260 | <?php
/**
* @version 3.15.0
* @package com_einsatzkomponente
* @copyright Copyright (C) 2017 by Ralf Meyer. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @author Ralf Meyer <ralf.meyer@mail.de> - https://einsatzkomponente.de
*/
// no direct access
defined('_JEXEC') or die;
?>
<style>
table#einsaetze {
margin: 10px 0 0 0;
}
table#einsaetze h3 {
margin: 0;
}
table#einsaetze tr.row0 {
background-color: #f9f9f9;
}
table#einsaetze tr.link:hover {
background-color: #e9f5ff;
cursor: pointer;
}
table#einsaetze td, table#einsaetze th {
padding: 10px;
}
@media(max-width:767px) {
table#einsaetze td:nth-of-type(n+2), table#einsaetze th:nth-of-type(n+2) {
display: inline-block;
}
}
</style>
<?php echo '<span class="mobile_hide_320">'.$this->modulepos_2.'</span>';?>
<form action="#" method="post" name="adminForm" id="adminForm">
<?php echo JLayoutHelper::render('default_filter', array('view' => $this), dirname(__FILE__)); ?>
<?php /* create table header */
$theader = '<tr class="hidden-phone">';
$col = 0;
if ($this->params->get('display_home_number','1')) :
$theader .= '<th>Nr.</th>';
$col++;
endif;
if ($this->params->get('display_home_alertimage','0')) :
$theader .= '<th>Alarm über</th>';
$col++;
endif;
$theader .= '<th>Datum</th>';
$theader .= '<th colspan="2">Beschreibung</th>';
$theader .= '<th>Einsatzort</th>';
$col += 4;
if ($this->params->get('display_home_orga','0')) :
$theader .= '<th>Organisationen</th>';
$col++;
endif;
if ($this->params->get('display_home_image')) :
$theader .= '<th>Bild</th>';
$col++;
endif;
$theader .= '</tr>';
?>
<table id="einsaetze" class="table table-bordered">
<?php /*
<thead >
<tr class="mobile_hide_480 ">
<?php $eiko_col = 0;?>
<?php if ($this->params->get('display_home_number','1') ) : ?>
<th class='left'>
<?php echo 'Nr.'; ?>
<?php $eiko_col = $eiko_col+1;?>
</th>
<?php endif;?>
<th class='left'>
<!--<?php echo JHtml::_('grid.sort', 'COM_EINSATZKOMPONENTE_EINSATZBERICHTE_DATE1', 'a.date1', $listDirn, $listOrder);?>-->
<?php echo JText::_('COM_EINSATZKOMPONENTE_EINSATZBERICHTE_DATE1');?>
<?php $eiko_col = $eiko_col+1;?>
</th>
<th class='left'>
<?php echo ''; ?>
<?php $eiko_col = $eiko_col+1;?>
</th>
<?php if ($this->params->get('display_home_image')) : ?>
<th class='left mobile_hide_480 '>
<!--<?php echo JHtml::_('grid.sort', 'COM_EINSATZKOMPONENTE_EINSATZBERICHTE_IMAGE', 'a.image', $listDirn, $listOrder); ?>-->
<?php echo JText::_('COM_EINSATZKOMPONENTE_EINSATZBERICHTE_IMAGE');?>
<?php $eiko_col = $eiko_col+1;?>
</th>
<?php endif;?>
<!-- <th class='left'>
<?php echo JHtml::_('grid.sort', 'COM_EINSATZKOMPONENTE_EINSATZBERICHTE_IMAGES', 'a.images', $listDirn, $listOrder); ?>
<?php $eiko_col = $eiko_col+1;?>
</th> -->
<th class='left mobile_hide_480'>
<!--<?php echo JHtml::_('grid.sort', 'COM_EINSATZKOMPONENTE_EINSATZBERICHTE_SUMMARY', 'a.summary', $listDirn, $listOrder);?>-->
<?php echo JText::_('COM_EINSATZKOMPONENTE_EINSATZBERICHTE_SUMMARY');?>
<?php $eiko_col = $eiko_col+1;?>
</th>
<?php if ($this->params->get('display_home_orga','0')) : ?>
<th class='left'>
<!--<?php echo JHtml::_('grid.sort', 'COM_EINSATZKOMPONENTE_EINSATZBERICHTE_AUSWAHLORGA', 'a.auswahl_orga', $listDirn, $listOrder); ?>-->
<?php echo JText::_('COM_EINSATZKOMPONENTE_EINSATZBERICHTE_AUSWAHLORGA');?>
<?php $eiko_col = $eiko_col+1;?>
</th>
<?php endif; ?>
<?php if ($this->params->get('display_home_presse','0') ) : ?>
<th class='left'>
<?php echo JText::_('COM_EINSATZKOMPONENTE_EINSATZBERICHTE_PRESSEBERICHT'); ?>
<?php $eiko_col = $eiko_col+1;?>
</th>
<?php endif;?>
<!-- <th class='left'>
<?php echo JHtml::_('grid.sort', 'COM_EINSATZKOMPONENTE_EINSATZBERICHTE_VEHICLES', 'a.vehicles', $listDirn, $listOrder); ?>
<?php $eiko_col = $eiko_col+1;?>
</th> -->
<?php if ($this->params->get('display_home_counter','1')) : ?>
<th class='left mobile_hide_480 '>
<!--<?php echo JHtml::_('grid.sort', 'COM_EINSATZKOMPONENTE_EINSATZBERICHTE_ZUGRIFFE', 'a.counter', $listDirn, $listOrder); ?>-->
<?php echo JText::_('COM_EINSATZKOMPONENTE_EINSATZBERICHTE_ZUGRIFFE');?>
<?php $eiko_col = $eiko_col+1;?>
</th>
<?php endif;?>
<!-- <th class='left'>
<?php echo JHtml::_('grid.sort', 'COM_EINSATZKOMPONENTE_EINSATZBERICHTE_CREATED_BY', 'a.created_by', $listDirn, $listOrder); ?>
<?php $eiko_col = $eiko_col+1;?>
</th> -->
<?php if (isset($this->items[0]->id)): ?>
<!-- <th width="1%" class="nowrap center hidden-phone">
<?php echo JHtml::_('grid.sort', 'JGRID_HEADING_ID', 'a.id', $listDirn, $listOrder); ?>
<?php $eiko_col = $eiko_col+1;?>
</th> -->
<?php endif; ?>
<?php if ($canEdit || $canDelete): ?>
<?php if (isset($this->items[0]->state)): ?>
<th width="1%" class="nowrap center">
<?php echo JText::_('Actions'); ?>
<?php $eiko_col = $eiko_col+1;?>
</th>
<?php endif; ?>
<?php endif; ?>
</tr>
<?php if ($canCreate): ?>
<tr class="eiko_action_button">
<td colspan="<?php echo $eiko_col;?>">
<a href="<?php echo JRoute::_('index.php?option=com_einsatzkomponente&view=einsatzberichtform&layout=edit&id=0&addlink=1', false, 2); ?>"
class="btn btn-success btn-small"><i
class="icon-plus"></i> <?php echo JText::_('COM_EINSATZKOMPONENTE_ADD'); ?></a>
</td></tr>
<?php endif; ?>
</thead>
*/ ?>
<tbody>
<?php $m ='';
$y=''; //print_r ($this->items);
$eiko_col = $col;
?>
<?php foreach ($this->items as $i => $item) : ?>
<?php $canEdit = $user->authorise('core.edit', 'com_einsatzkomponente'); ?>
<?php if (!$canEdit && $user->authorise('core.edit.own', 'com_einsatzkomponente')): ?>
<?php $canEdit = JFactory::getUser()->id == $item->created_by; ?>
<?php endif; ?>
<?php /*
<!--Anzeige des Jahres-->
<?php if ($item->date1_year != $y&& $this->params->get('display_home_jahr','1')) : ?>
<tr class="eiko_einsatzarchiv_jahr_tr"><td class="eiko_einsatzarchiv_jahr_td" colspan="<?php echo $eiko_col; ?>">
<?php $y= $item->date1_year;?>
<?php $m= ''; ?>
<?php echo '<div class="eiko_einsatzarchiv_jahr_div">';?>
<?php echo 'Einsatzberichte '. $item->date1_year.'';?>
<?php echo '</div>';?>
</td></tr>
<?php endif;?>
<!--Anzeige des Jahres ENDE-->
*/ ?>
<!--Anzeige des Monatsnamen-->
<?php if (($item->date1_month != $m || $item->date1_year != $y) && $this->params->get('display_home_monat','1')) : ?>
<?php $y = $item->date1_year; // $y may not have been set before if display_home_jahr is 0 ?>
<tr><td colspan="<?php echo $col; ?>">
<?php $m= $item->date1_month;?>
<?php echo '<h3>'.(new JDate)->monthToString($m).'</h3>';?>
</td></tr>
<?php echo $theader; ?>
<?php endif;?>
<!--Anzeige des Monatsnamen ENDE-->
<tr class="link row<?php echo $i % 2; ?>" onClick="parent.location='<?php echo JRoute::_('index.php?option=com_einsatzkomponente&view=einsatzbericht&id='.(int) $item->id); ?>'">
<?php if ($this->params->get('display_home_number','1') ) : ?>
<?php $style = ''; ?>
<?php if ($this->params->get('display_home_marker','1')) : ?>
<?php $style = sprintf('style="border-left: 3px solid %s;"', $item->marker); ?>
<?php endif;?>
<td <?= $style ?>><?= EinsatzkomponenteHelper::ermittle_einsatz_nummer($item->date1,$item->data1_id); ?></td>
<?php endif;?>
<?php if ($this->params->get('display_home_date_image','1')=='1') : ?>
<td class="eiko_td_kalender_main_1">
<div class="home_cal_icon">
<div class="home_cal_monat"><?php echo date('M', $item->date1);?></div>
<div class="home_cal_tag"><?php echo date('d', $item->date1);?></div>
<div class="home_cal_jahr"><span style="font-size:10px;"><?php echo date('Y', $item->date1);?></span></div>
</div>
</td>
<?php endif;?>
<?php if ($this->params->get('display_home_date_image','1')=='2') : ?>
<td class="eiko_td_datum_main_1"> <?php echo date('d.m.Y ', $item->date1);?><br /><?php echo date('H:i ', $item->date1); ?>Uhr</td>
<?php endif;?>
<?php if ($this->params->get('display_home_date_image','1')=='0') : ?>
<td class="eiko_td_datum_main_1"> <?php echo date('d.m.Y ', $item->date1);?></td>
<?php endif;?>
<?php if ($this->params->get('display_home_date_image','1')=='3') : ?>
<td class="eiko_td_kalender_main_1">
<div class="home_cal_icon">
<div class="home_cal_monat"><?php echo date('M', $item->date1);?></div>
<div class="home_cal_tag"><?php echo date('d', $item->date1);?></div>
<div class="home_cal_jahr"><span style="font-size:10px;"><?php echo date('Y', $item->date1);?></span></div>
<?php echo '<div style="font-size:12px;white-space: nowrap;">'.date('H:i ', $item->date1).' Uhr</div>'; ?>
</div>
</td>
<?php endif;?>
<td>
<?php if (isset($item->checked_out) && $item->checked_out) : ?>
<?php echo JHtml::_('jgrid.checkedout', $i, $item->editor, $item->checked_out_time, 'einsatzarchiv.', $canCheckin); ?>
<?php endif; ?>
<?php if ($this->params->get('display_home_links_2','1')) : ?>
<a href="<?php echo JRoute::_('index.php?option=com_einsatzkomponente&view=einsatzbericht&id='.(int) $item->id); ?>">
<?php endif; ?>
<?php if ($this->params->get('display_home_alertimage','0')) : ?>
<img class="eiko_icon " src="<?php echo JURI::Root();?><?php echo $item->alerting_image;?>" title="Alarmierung über: <?php echo $item->alerting;?>" />
<?php endif;?>
<?php if ($this->params->get('display_list_icon')) : ?>
<img class="eiko_icon " src="<?php echo JURI::Root();?><?php echo $item->list_icon;?>" alt="<?php echo $item->list_icon;?>" title="Einsatzart: <?php echo $item->data1;?>"/>
<?php endif;?>
<?php if ($this->params->get('display_tickerkat_icon')) : ?>
<img class="eiko_icon " src="<?php echo JURI::Root();?><?php echo $item->tickerkat_image;?>" alt="<?php echo $item->tickerkat;?>" title="Kategorie: <?php echo $item->tickerkat;?>"/>
<?php endif;?>
<span class="eiko_nowrap"><?php echo $item->data1; ?></span>
<?php if ($this->params->get('display_home_links_2','1')) : ?>
</a>
<?php endif;?>
<br/>
<!-- Einsatzstärke -->
<?php if ($this->params->get('display_home_einsatzstaerke','1')) { ?>
<?php if ($item->people) : $people = $item->people; endif;?>
<?php if (!$item->people) : $people = '0'; endif;?>
<?php $vehicles = explode (",",$item->vehicles);?>
<?php $vehicles = count($vehicles); ?>
<?php $auswahl_orga = explode (",",$item->auswahl_orga);?>
<?php $auswahl_orga = count($auswahl_orga); ?>
<?php $strength = ($people*$this->params->get('einsatzstaerke_people','0.5')) + ($vehicles*$this->params->get('einsatzstaerke_vehicles','2')) + ($auswahl_orga*$this->params->get('einsatzstaerke_orga','15')) ; ?>
<div class="progress progress-danger progress-striped " style="margin-top:5px;margin-bottom:5px;color:#000000 !important;width:180px;" title="<?php echo JText::_('COM_EINSATZKOMPONENTE_EINSATZKRAFT'); ?>: <?php if ($auswahl_orga) :echo $auswahl_orga;?> <?php echo JText::_('COM_EINSATZKOMPONENTE_ORGANISATIONEN'); ?> //<?php endif;?> <?php if ($vehicles):echo $vehicles;?> <?php echo JText::_('COM_EINSATZKOMPONENTE_EINSATZFAHRZEUGE'); ?> <?php endif;?><?php if ($people) :echo '// '.$people;?> Einsatzkräfte <?php endif;?>">
<div class="bar" style="color:#000000 !important;width:<?php echo $strength;?>px"></div></div>
<?php } ?>
<!-- Einsatzstärke ENDE -->
<?php if ($this->params->get('display_home_info','1') or $this->params->get('display_home_links','1')) : ?>
<div class="eiko_td_buttons_main_1">
<?php endif;?>
<!-- Button Kurzinfo -->
<?php if ($this->params->get('display_home_info','1')) : ?>
<input type="button" class="btn btn-primary" onClick="jQuery.toggle<?php echo $item->id;?>(div<?php echo $item->id;?>)" value="<?php echo JTEXT::_('COM_EINSATZKOMPONENTE_KURZINFO');?>"></input>
<script type="text/javascript">
jQuery.toggle<?php echo $item->id;?> = function(query)
{
jQuery(query).slideToggle("5000");
jQuery("#tr<?php echo $item->id;?>").fadeToggle("fast");
}
</script>
<?php endif;?>
<!-- Button Detaillink -->
<?php if ($this->params->get('display_home_links','1')) : ?>
<a href="<?php echo JRoute::_('index.php?option=com_einsatzkomponente&view=einsatzbericht&id='.(int) $item->id); ?>" type="button" class="btn btn-primary"><?php echo JText::_('COM_EINSATZKOMPONENTE_DETAILS'); ?></a>
<?php endif;?>
<br/>
</td>
<td>
<a href="<?php echo JRoute::_('index.php?option=com_einsatzkomponente&view=einsatzbericht&id='.(int) $item->id); ?>">
<?php echo $item->summary; ?>
</a>
<?php if ($item->image) : ?>
<i class="icon-picture"></i>
<?php endif; ?>
</td>
<!-- Einsatzbild -->
<?php if ($this->params->get('display_home_image')) : ?>
<td class="mobile_hide_480 eiko_td_einsatzbild_main_1">
<?php if ($item->image) : ?>
<?php if (isset($item->checked_out) && $item->checked_out) : ?>
<?php echo JHtml::_('jgrid.checkedout', $i, $item->editor, $item->checked_out_time, 'einsatzarchiv.', $canCheckin); ?>
<?php endif; ?>
<?php if ($this->params->get('display_home_links_3','0')) : ?>
<a href="<?php echo JRoute::_('index.php?option=com_einsatzkomponente&view=einsatzbericht&id='.(int) $item->id); ?>">
<?php endif; ?>
<img class="img-rounded eiko_img_einsatzbild_main_1" style="width:<?php echo $this->params->get('display_home_image_width','80px');?>;" src="<?php echo JURI::Root();?><?php echo $item->image;?>"/>
<?php if ($this->params->get('display_home_links_3','0')) : ?>
</a>
<?php endif;?>
<?php endif;?>
<?php if (!$item->image AND $this->params->get('display_home_image_nopic','0')) : ?>
<?php if (isset($item->checked_out) && $item->checked_out) : ?>
<?php echo JHtml::_('jgrid.checkedout', $i, $item->editor, $item->checked_out_time, 'einsatzarchiv.', $canCheckin); ?>
<?php endif; ?>
<?php if ($this->params->get('display_home_links_3','0')) : ?>
<a href="<?php echo JRoute::_('index.php?option=com_einsatzkomponente&view=einsatzbericht&id='.(int) $item->id); ?>">
<?php endif; ?>
<img class="img-rounded eiko_img_einsatzbild_main_1" style="width:<?php echo $this->params->get('display_home_image_width','80px');?>;" src="<?php echo JURI::Root().'images/com_einsatzkomponente/einsatzbilder/nopic.png';?>"/>
<?php if ($this->params->get('display_home_links_3','0')) : ?>
</a>
<?php endif;?>
<?php endif;?>
</td>
<?php endif;?>
<!-- Einsatzbild ENDE -->
<td>
<?php if ($item->address): ?>
<?php echo $this->escape($item->address); ?>
<?php endif;?>
</td>
<?php if ($this->params->get('display_home_orga','0')) : ?>
<?php
$data = array();
foreach(explode(',',$item->auswahl_orga) as $value):
if($value){
$data[] = '<!-- <span class="label label-info"> --!>'.$value.'<!-- </span>--!>';
}
endforeach;
$auswahl_orga= implode('</br>',$data);
?>
<td nowrap class="eiko_td_organisationen_main_1 mobile_hide_480"> <?php echo $auswahl_orga;?></td>
<?php endif;?>
<?php if ($this->params->get('display_home_presse','0')) : ?>
<td class="mobile_hide_480 ">
<?php if ($item->presse or $item->presse2 or $item->presse3) : ?>
<?php if ($this->params->get('presse_image','')) : ?>
<img class="eiko_icon_press" src="<?php echo JURI::Root();?><?php echo $this->params->get('presse_image','');?>" title="" />
<?php else:?>
<?php echo ''.JText::_('COM_EINSATZKOMPONENTE_EINSATZBERICHTE_PRESSEBERICHT').''; ?>
<?php endif;?>
<?php endif;?>
</td>
<?php endif; ?>
<!-- <td>
<?php echo $item->vehicles; ?>
</td> -->
<?php if ($this->params->get('display_home_counter','1')) : ?>
<td class="mobile_hide_480 ">
<?php echo $item->counter; ?>
</td>
<?php endif; ?>
<?php if (isset($this->items[0]->id)): ?>
<!-- <td class="center hidden-phone">
<?php echo (int)$item->id; ?>
</td> -->
<?php endif; ?>
<?php /*
<?php if (isset($this->items[0]->state)): ?>
<?php $class = ($canEdit || $canChange) ? 'active' : 'disabled'; ?>
<td class="center">
<?php if ($canEdit): ?>
<a class="btn btn-mini <?php echo $class; ?> eiko_action_button"
href="<?php echo ($canChange) ? JRoute::_('index.php?option=com_einsatzkomponente&task=einsatzberichtform.publish&id=' . $item->id . '&state=' . (($item->state + 1) % 2), false, 2) : '#'; ?>">
<?php if ($item->state == 1): ?>
<i class="icon-save"></i>
<?php else: ?>
<i class="icon-radio-unchecked"></i>
<?php endif; ?>
</a>
<?php endif; ?>
<?php if ($canEdit): ?>
<a href="<?php echo JRoute::_('index.php?option=com_einsatzkomponente&task=einsatzberichtform.edit&layout=edit&id=' . $item->id, true, 2); ?>" class="btn btn-mini eiko_action_button" type="button"><i class="icon-edit" ></i></a>
<?php endif; ?>
<?php if ($canDelete): ?>
<button data-item-id="<?php echo $item->id; ?>" class="btn btn-mini delete-button eiko_action_button" type="button"><i class="icon-trash" ></i></button>
<?php endif; ?>
</td>
<?php endif; ?>
*/ ?>
</tr>
<!-- Zusatzinformation Kurzinfo -->
<?php if ($this->params->get('display_home_info','1')) : ?>
<?php
$data = array();
foreach(explode(',',$item->auswahl_orga) as $value):
if($value){
$data[] = '<!-- <span class="label label-info"> --!>'.$value.'<!-- </span>--!>';
}
endforeach;
$auswahl_orga= implode(' +++ ',$data); ?>
<tr id="tr<?php echo $item->id;?>" class="eiko_tr_zusatz_main_1" style=" display:none;" >
<?php if ($this->params->get('display_home_marker','1')) : ?>
<?php $rgba = hex2rgba($item->marker,0.7);?>
<style>
.td<?php echo $item->id;?> {
background: -moz-linear-gradient(top, <?php echo $rgba;?> 0%, rgba(125,185,232,0) 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,<?php echo $rgba;?>), color-stop(100%,rgba(125,185,232,0))); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, <?php echo $rgba;?> 0%,rgba(125,185,232,0) 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, <?php echo $rgba;?> 0%,rgba(125,185,232,0) 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, <?php echo $rgba;?> 0%,rgba(125,185,232,0) 100%); /* IE10+ */
background: linear-gradient(to bottom, <?php echo $rgba;?> 0%,rgba(125,185,232,0) 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='<?php echo $item->marker;?>', endColorstr='#007db9e8',GradientType=0 ); /* IE6-9 */
}
</style>
<td class="td<?php echo $item->id;?>" >
<?php else:?>
<td>
<?php endif;?>
</td>
<td colspan="<?php echo $eiko_col-1; ?>" class="eiko_td_zusatz_main_1">
<div id ="div<?php echo $item->id;?>" style="display:none;">
<h3 style="text-decoration:underline;"><?php echo JText::_('COM_EINSATZKOMPONENTE_ALARMIERUNGSZEIT');?> </h3><?php echo date('d.m.Y', $item->date1);?> um <?php echo date('H:i', $item->date1);?> Uhr
<h3 style="text-decoration:underline;"><?php echo JText::_('COM_EINSATZKOMPONENTE_EINSATZKRAEFTE');?> </h3><?php echo $auswahl_orga;?><br/>
<?php if ($item->desc) : ?>
<?php jimport('joomla.html.content'); ?>
<?php $Desc = JHTML::_('content.prepare', $item->desc); ?>
<h3 style="text-decoration:underline;"><?php echo JText::_('COM_EINSATZKOMPONENTE_TITLE_MAIN_3');?> </h3><?php echo $Desc;?>
<?php endif;?>
<br /><input type="button" class="btn btn-info" onClick="jQuery.toggle<?php echo $item->id;?>(div<?php echo $item->id;?>)" value="<?php echo JText::_('COM_EINSATZKOMPONENTE_INFO_SCHLIESSEN');?>"></input>
<?php if ($this->params->get('display_home_links','1')) : ?>
<a href="<?php echo JRoute::_('index.php?option=com_einsatzkomponente&view=einsatzbericht&id='.(int) $item->id); ?>" type="button" class="btn btn-primary"><?php echo JText::_('COM_EINSATZKOMPONENTE_DETAILS'); ?></a>
<?php endif;?>
</div>
</td>
</tr>
<?php endif;?>
<!-- Zusatzinformation Kurzinfo ENDE -->
<?php endforeach; ?>
</tbody>
<tfoot>
<!--Prüfen, ob Pagination angezeigt werden soll-->
<?php if ($this->params->get('display_home_pagination')) : ?>
<tr>
<td colspan="<?php echo $eiko_col; ?>">
<form action="#" method=post>
<?php echo $this->pagination->getListFooter(); ?><!--Pagination anzeigen-->
</form>
</td></tr>
<?php endif;?><!--Prüfen, ob Pagination angezeigt werden soll ENDE -->
</tfoot>
<input type="hidden" name="task" value=""/>
<input type="hidden" name="boxchecked" value="0"/>
<input type="hidden" name="filter_order" value="<?php echo $listOrder; ?>"/>
<input type="hidden" name="filter_order_Dir" value="<?php echo $listDirn; ?>"/>
<?php echo JHtml::_('form.token'); ?>
</form>
<?php if ($this->params->get('display_home_map')) : ?>
<tr><td colspan="<?php echo $eiko_col;?>" class="eiko_td_gmap_main_1">
<h4>Einsatzgebiet</h4>
<?php if ($this->params->get('gmap_action','0') == '1') :?>
<div id="map-canvas" style="width:100%; height:<?php echo $this->params->get('home_map_height','300px');?>;">
<noscript>Dieser Teil der Seite erfordert die JavaScript Unterstützung Ihres Browsers!</noscript>
</div>
<?php endif;?>
<?php if ($this->params->get('gmap_action','0') == '2') :?>
<body onLoad="drawmap();">
<!--<div id="descriptionToggle" onClick="toggleInfo()">Informationen zur Karte anzeigen</div>
<div id="description" class="">Einsatzkarte</div>-->
<div id="map" style="width:100%; height:<?php echo $this->params->get('home_map_height','300px');?>;"></div>
<noscript>Dieser Teil der Seite erfordert die JavaScript Unterstützung Ihres Browsers!</noscript>
<?php endif;?>
</td></tr>
<?php endif;?>
</table>
<?php echo '<span class="mobile_hide_320">'.$this->modulepos_1.'</span>'; ?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('.delete-button').click(deleteItem);
});
function deleteItem() {
var item_id = jQuery(this).attr('data-item-id');
if (confirm("<?php echo JText::_('COM_EINSATZKOMPONENTE_WIRKLICH_LOESCHEN'); ?>")) {
window.location.href = '<?php echo JRoute::_('index.php?option=com_einsatzkomponente&task=einsatzberichtform.remove&id=', false, 2) ?>' + item_id;
}
}
</script>
<?php function hex2rgba($color, $opacity = false) { // Farbe von HEX zu RGBA umwandeln
$default = 'rgb(0,0,0)';
//Return default if no color provided
if(empty($color))
return $default;
//Sanitize $color if "#" is provided
if ($color[0] == '#' ) {
$color = substr( $color, 1 );
}
//Check if color has 6 or 3 characters and get values
if (strlen($color) == 6) {
$hex = array( $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] );
} elseif ( strlen( $color ) == 3 ) {
$hex = array( $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] );
} else {
return $default;
}
//Convert hexadec to rgb
$rgb = array_map('hexdec', $hex);
//Check if opacity is set(rgba or rgb)
if($opacity){
if(abs($opacity) > 1)
$opacity = 1.0;
$output = 'rgba('.implode(",",$rgb).','.$opacity.')';
} else {
$output = 'rgb('.implode(",",$rgb).')';
}
//Return rgb(a) color string
return $output;
}
?>
| gpl-2.0 |
drazenzadravec/nequeo | Tools/PjSIP/Wrapper/Swig_Generation/PersistentDocument.cs | 9817 | //------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 3.0.7
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
public class PersistentDocument : global::System.IDisposable {
private global::System.Runtime.InteropServices.HandleRef swigCPtr;
protected bool swigCMemOwn;
internal PersistentDocument(global::System.IntPtr cPtr, bool cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
}
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(PersistentDocument obj) {
return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
}
~PersistentDocument() {
Dispose();
}
public virtual void Dispose() {
lock(this) {
if (swigCPtr.Handle != global::System.IntPtr.Zero) {
if (swigCMemOwn) {
swigCMemOwn = false;
pjsua2PINVOKE.delete_PersistentDocument(swigCPtr);
}
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
}
global::System.GC.SuppressFinalize(this);
}
}
public virtual void loadFile(SWIGTYPE_p_string filename) {
pjsua2PINVOKE.PersistentDocument_loadFile(swigCPtr, SWIGTYPE_p_string.getCPtr(filename));
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
}
public virtual void loadString(SWIGTYPE_p_string input) {
pjsua2PINVOKE.PersistentDocument_loadString(swigCPtr, SWIGTYPE_p_string.getCPtr(input));
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
}
public virtual void saveFile(SWIGTYPE_p_string filename) {
pjsua2PINVOKE.PersistentDocument_saveFile(swigCPtr, SWIGTYPE_p_string.getCPtr(filename));
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
}
public virtual SWIGTYPE_p_string saveString() {
SWIGTYPE_p_string ret = new SWIGTYPE_p_string(pjsua2PINVOKE.PersistentDocument_saveString(swigCPtr), true);
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public virtual ContainerNode getRootContainer() {
ContainerNode ret = new ContainerNode(pjsua2PINVOKE.PersistentDocument_getRootContainer(swigCPtr), false);
return ret;
}
public bool hasUnread() {
bool ret = pjsua2PINVOKE.PersistentDocument_hasUnread(swigCPtr);
return ret;
}
public SWIGTYPE_p_string unreadName() {
SWIGTYPE_p_string ret = new SWIGTYPE_p_string(pjsua2PINVOKE.PersistentDocument_unreadName(swigCPtr), true);
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public int readInt(SWIGTYPE_p_string name) {
int ret = pjsua2PINVOKE.PersistentDocument_readInt__SWIG_0(swigCPtr, SWIGTYPE_p_string.getCPtr(name));
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public int readInt() {
int ret = pjsua2PINVOKE.PersistentDocument_readInt__SWIG_1(swigCPtr);
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public float readNumber(SWIGTYPE_p_string name) {
float ret = pjsua2PINVOKE.PersistentDocument_readNumber__SWIG_0(swigCPtr, SWIGTYPE_p_string.getCPtr(name));
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public float readNumber() {
float ret = pjsua2PINVOKE.PersistentDocument_readNumber__SWIG_1(swigCPtr);
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public bool readBool(SWIGTYPE_p_string name) {
bool ret = pjsua2PINVOKE.PersistentDocument_readBool__SWIG_0(swigCPtr, SWIGTYPE_p_string.getCPtr(name));
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public bool readBool() {
bool ret = pjsua2PINVOKE.PersistentDocument_readBool__SWIG_1(swigCPtr);
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public SWIGTYPE_p_string readString(SWIGTYPE_p_string name) {
SWIGTYPE_p_string ret = new SWIGTYPE_p_string(pjsua2PINVOKE.PersistentDocument_readString__SWIG_0(swigCPtr, SWIGTYPE_p_string.getCPtr(name)), true);
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public SWIGTYPE_p_string readString() {
SWIGTYPE_p_string ret = new SWIGTYPE_p_string(pjsua2PINVOKE.PersistentDocument_readString__SWIG_1(swigCPtr), true);
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public SWIGTYPE_p_StringVector readStringVector(SWIGTYPE_p_string name) {
SWIGTYPE_p_StringVector ret = new SWIGTYPE_p_StringVector(pjsua2PINVOKE.PersistentDocument_readStringVector__SWIG_0(swigCPtr, SWIGTYPE_p_string.getCPtr(name)), true);
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public SWIGTYPE_p_StringVector readStringVector() {
SWIGTYPE_p_StringVector ret = new SWIGTYPE_p_StringVector(pjsua2PINVOKE.PersistentDocument_readStringVector__SWIG_1(swigCPtr), true);
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public void readObject(PersistentObject obj) {
pjsua2PINVOKE.PersistentDocument_readObject(swigCPtr, PersistentObject.getCPtr(obj));
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
}
public ContainerNode readContainer(SWIGTYPE_p_string name) {
ContainerNode ret = new ContainerNode(pjsua2PINVOKE.PersistentDocument_readContainer__SWIG_0(swigCPtr, SWIGTYPE_p_string.getCPtr(name)), true);
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public ContainerNode readContainer() {
ContainerNode ret = new ContainerNode(pjsua2PINVOKE.PersistentDocument_readContainer__SWIG_1(swigCPtr), true);
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public ContainerNode readArray(SWIGTYPE_p_string name) {
ContainerNode ret = new ContainerNode(pjsua2PINVOKE.PersistentDocument_readArray__SWIG_0(swigCPtr, SWIGTYPE_p_string.getCPtr(name)), true);
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public ContainerNode readArray() {
ContainerNode ret = new ContainerNode(pjsua2PINVOKE.PersistentDocument_readArray__SWIG_1(swigCPtr), true);
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public void writeNumber(SWIGTYPE_p_string name, float num) {
pjsua2PINVOKE.PersistentDocument_writeNumber(swigCPtr, SWIGTYPE_p_string.getCPtr(name), num);
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
}
public void writeInt(SWIGTYPE_p_string name, int num) {
pjsua2PINVOKE.PersistentDocument_writeInt(swigCPtr, SWIGTYPE_p_string.getCPtr(name), num);
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
}
public void writeBool(SWIGTYPE_p_string name, bool value) {
pjsua2PINVOKE.PersistentDocument_writeBool(swigCPtr, SWIGTYPE_p_string.getCPtr(name), value);
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
}
public void writeString(SWIGTYPE_p_string name, SWIGTYPE_p_string value) {
pjsua2PINVOKE.PersistentDocument_writeString(swigCPtr, SWIGTYPE_p_string.getCPtr(name), SWIGTYPE_p_string.getCPtr(value));
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
}
public void writeStringVector(SWIGTYPE_p_string name, SWIGTYPE_p_StringVector arr) {
pjsua2PINVOKE.PersistentDocument_writeStringVector(swigCPtr, SWIGTYPE_p_string.getCPtr(name), SWIGTYPE_p_StringVector.getCPtr(arr));
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
}
public void writeObject(PersistentObject obj) {
pjsua2PINVOKE.PersistentDocument_writeObject(swigCPtr, PersistentObject.getCPtr(obj));
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
}
public ContainerNode writeNewContainer(SWIGTYPE_p_string name) {
ContainerNode ret = new ContainerNode(pjsua2PINVOKE.PersistentDocument_writeNewContainer(swigCPtr, SWIGTYPE_p_string.getCPtr(name)), true);
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public ContainerNode writeNewArray(SWIGTYPE_p_string name) {
ContainerNode ret = new ContainerNode(pjsua2PINVOKE.PersistentDocument_writeNewArray(swigCPtr, SWIGTYPE_p_string.getCPtr(name)), true);
if (pjsua2PINVOKE.SWIGPendingException.Pending) throw pjsua2PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
| gpl-2.0 |
amk221/train-up | class/base/helper_installer.php | 2730 | <?php
/**
* Helper class for installing the plugin
*
* @package Train-Up!
*/
namespace TU;
class Installer {
/**
* __construct
*
* - Fired when this plugin is being activated for the first time.
* - Register the 'static' post types and cache them for the first time.
* - Instantiate the pages, their related posts will be created automatically.
* - Create the table that houses the archived result data.
* - Add a marker `tu_installed` so we don't install the plugin more than once
*
* @access public
*/
public function __construct() {
$this->register_post_types();
$this->create_pages();
$this->create_archive();
update_option('tu_installed', true);
}
/**
* create_pages
*
* Instantiate the pages, if their corresponding WordPress post does not exist
* it will be created automatically.
*
* @access private
*/
private function create_pages() {
new Login_page;
new Logout_page;
new Sign_up_page;
new Forgotten_password_page;
new Reset_password_page;
new My_account_page;
new Edit_my_details_page;
new My_results_page;
}
/**
* register_post_types
*
* Instantiate the static post types and cache them in the DB, so they will
* get registered automatically on future requests.
*
* @access private
*/
private function register_post_types() {
$levels = new Level_post_type;
$levels->cache();
$tests = new Test_post_type;
$tests->cache();
$groups = new Group_post_type;
$groups->cache();
$pages = new Page_post_type;
$pages->cache();
do_action('tu_install_cpt');
}
/**
* create_archive
*
* Create the table that houses the Trainee's Result data.
*
* @access private
*/
private function create_archive() {
global $wpdb;
$wpdb->query("
CREATE TABLE `{$wpdb->prefix}tu_archive` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`date_submitted` datetime DEFAULT NULL,
`duration` int(11) unsigned DEFAULT NULL,
`user_id` int(11) unsigned DEFAULT NULL,
`test_id` int(11) unsigned DEFAULT NULL,
`user_name` varchar(128) DEFAULT NULL,
`test_title` varchar(255) DEFAULT NULL,
`answers` longtext,
`mark` int(10) unsigned DEFAULT NULL,
`out_of` int(10) unsigned DEFAULT NULL,
`percentage` tinyint(10) unsigned DEFAULT NULL,
`grade` varchar(128) DEFAULT NULL,
`passed` tinyint(1) DEFAULT NULL,
`resit_number` tinyint(4) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `test_id` (`test_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
");
}
}
| gpl-2.0 |
mfursov/ugene | src/plugins/GUITestBase/src/runnables/ugene/corelibs/U2Gui/ImportToDatabaseDialogFiller.cpp | 13166 | /**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2017 UniPro <ugene@unipro.ru>
* http://ugene.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#if (QT_VERSION < 0x050000) //Qt 5
#include <QtGui/QApplication>
#include <QtGui/QHeaderView>
#include <QtGui/QTreeWidget>
#else
#include <QtWidgets/QApplication>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QTreeWidget>
#endif
#include "ImportToDatabaseDialogFiller.h"
#include <base_dialogs/GTFileDialog.h>
#include <drivers/GTKeyboardDriver.h>
#include "primitives/GTMenu.h"
#include <drivers/GTMouseDriver.h>
#include <primitives/GTWidget.h>
#include "primitives/PopupChooser.h"
#include "runnables/ugene/corelibs/U2Gui/CommonImportOptionsDialogFiller.h"
#include "runnables/ugene/corelibs/U2Gui/ItemToImportEditDialogFiller.h"
#include "runnables/ugene/corelibs/U2Gui/ProjectTreeItemSelectorDialogFiller.h"
#include <U2Core/U2SafePoints.h>
namespace U2 {
using namespace HI;
namespace {
QMap<QString, QStringList> convertProjectItemsMap(const QMap<QString, QVariant>& map) {
QMap<QString, QStringList> result;
foreach (const QString& key, map.keys()) {
result.insert(key, map.value(key).toStringList());
}
return result;
}
} // an unnamed namespace
#define GT_CLASS_NAME "GTUtilsDialog::ImportToDatabaseDialogFiller"
const QString ImportToDatabaseDialogFiller::Action::ACTION_DATA__ITEM = "ACTION_DATA__ITEM";
const QString ImportToDatabaseDialogFiller::Action::ACTION_DATA__ITEMS_LIST = "ACTION_DATA__ITEMS_LIST";
const QString ImportToDatabaseDialogFiller::Action::ACTION_DATA__DESTINATION_FOLDER = "ACTION_DATA__DESTINATION_FOLDER";
const QString ImportToDatabaseDialogFiller::Action::ACTION_DATA__PATHS_LIST = "ACTION_DATA__PATHS_LIST";
const QString ImportToDatabaseDialogFiller::Action::ACTION_DATA__PROJECT_ITEMS_LIST = "ACTION_DATA__PROJECT_ITEMS_LIST";
ImportToDatabaseDialogFiller::Action::Action(ImportToDatabaseDialogFiller::Action::Type type, const QVariantMap &data) :
type(type),
data(data)
{
}
ImportToDatabaseDialogFiller::ImportToDatabaseDialogFiller(HI::GUITestOpStatus &os, const QList<Action> &actions) :
Filler(os, "ImportToDatabaseDialog"),
actions(actions)
{
}
#define GT_METHOD_NAME "run"
void ImportToDatabaseDialogFiller::commonScenario() {
dialog = QApplication::activeModalWidget();
GT_CHECK(NULL != dialog, "activeModalWidget is NULL");
foreach (const Action &action, actions) {
switch (action.type) {
case Action::ADD_FILES:
addFiles(action);
break;
case Action::ADD_DIRS:
addDirs(action);
break;
case Action::ADD_PROJECT_ITEMS:
addProjectItems(action);
break;
case Action::SELECT_ITEMS:
selectItems(action);
break;
case Action::EDIT_DESTINATION_FOLDER:
editDestinationFolder(action);
break;
case Action::EDIT_GENERAL_OPTIONS:
editGeneralOptions(action);
break;
case Action::EDIT_PRIVATE_OPTIONS:
editPrivateOptions(action);
break;
case Action::RESET_PRIVATE_OPTIONS:
resetPrivateOptions(action);
break;
case Action::REMOVE:
remove(action);
break;
case Action::IMPORT:
import(action);
break;
case Action::CANCEL:
cancel(action);
break;
default:
GT_CHECK(false, "An unrecognized action");
}
CHECK_OP(os, );
GTGlobals::sleep(200);
}
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "addFiles"
void ImportToDatabaseDialogFiller::addFiles(const Action &action) {
GT_CHECK(Action::ADD_FILES == action.type, "Invalid action type");
GT_CHECK(action.data.contains(Action::ACTION_DATA__PATHS_LIST), "Not enough parameters to perform the action");
const QStringList filePaths = action.data.value(Action::ACTION_DATA__PATHS_LIST).toStringList();
foreach (const QString& filePath, filePaths) {
GTUtilsDialog::waitForDialog(os, new GTFileDialogUtils(os, filePath));
QWidget* addFilesButton = GTWidget::findWidget(os, "pbAddFiles");
GT_CHECK(NULL != addFilesButton, "addFilesButton is NULL");
GTWidget::click(os, addFilesButton);
GTGlobals::sleep(200);
}
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "addDirs"
void ImportToDatabaseDialogFiller::addDirs(const Action& action) {
GT_CHECK(Action::ADD_DIRS == action.type, "Invalid action type");
GT_CHECK(action.data.contains(Action::ACTION_DATA__PATHS_LIST), "Not enough parameters to perform the action");
const QStringList dirPaths = action.data.value(Action::ACTION_DATA__PATHS_LIST).toStringList();
foreach (const QString& dirPath, dirPaths) {
QFileInfo fi(dirPath);
GTUtilsDialog::waitForDialog(os, new GTFileDialogUtils(os, fi.dir().path(), fi.fileName(), GTFileDialogUtils::Choose));
QWidget* addDirsButton = GTWidget::findWidget(os, "pbAddFolder");
GT_CHECK(NULL != addDirsButton, "addDirsButton is NULL");
GTWidget::click(os, addDirsButton);
GTGlobals::sleep(200);
}
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "addProjectItems"
void ImportToDatabaseDialogFiller::addProjectItems(const Action &action) {
GT_CHECK(Action::ADD_PROJECT_ITEMS == action.type, "Invalid action type");
GT_CHECK(action.data.contains(Action::ACTION_DATA__PROJECT_ITEMS_LIST), "Not enough parameters to perform the action");
const QMap<QString, QStringList> projectItems = convertProjectItemsMap(action.data.value(Action::ACTION_DATA__PROJECT_ITEMS_LIST).toMap());
GTUtilsDialog::waitForDialog(os, new ProjectTreeItemSelectorDialogFiller(os, projectItems));
QWidget* addProjectItemsButton = GTWidget::findWidget(os, "pbAddObjects");
GT_CHECK(NULL != addProjectItemsButton, "addProjectItemsButton is NULL");
GTWidget::click(os, addProjectItemsButton);
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "selectItems"
void ImportToDatabaseDialogFiller::selectItems(const Action &action) {
GT_CHECK(Action::SELECT_ITEMS == action.type, "Invalid action type");
GT_CHECK(action.data.contains(Action::ACTION_DATA__ITEMS_LIST), "Not enough parameters to perform the action");
const QStringList itemList = action.data.value(Action::ACTION_DATA__ITEMS_LIST).toStringList();
GT_CHECK(!itemList.isEmpty(), "Items list to select is empty");
if (itemList.size() > 1) {
GTKeyboardDriver::keyPress(Qt::Key_Control);
}
foreach (const QString& itemText, itemList) {
const QPoint itemCenter = getItemCenter(itemText);
GTMouseDriver::moveTo(itemCenter);
GTMouseDriver::click();
}
GTKeyboardDriver::keyRelease( Qt::Key_Control);
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "editDestinationFolder"
void ImportToDatabaseDialogFiller::editDestinationFolder(const Action &action) {
GT_CHECK(Action::EDIT_DESTINATION_FOLDER == action.type, "Invalid action type");
GT_CHECK(action.data.contains(Action::ACTION_DATA__ITEM), "Not enough parameters to perform the action");
GT_CHECK(action.data.contains(Action::ACTION_DATA__DESTINATION_FOLDER), "Not enough parameters to perform the action");
const QPoint itemCenter = getFolderColumnCenter(action.data.value(Action::ACTION_DATA__ITEM).toString());
GTMouseDriver::moveTo(itemCenter);
GTMouseDriver::doubleClick();
const QString dstFolder = action.data.value(Action::ACTION_DATA__DESTINATION_FOLDER).toString();
GTKeyboardDriver::keySequence(dstFolder);
GTKeyboardDriver::keyClick( Qt::Key_Enter);
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "editGeneralOptions"
void ImportToDatabaseDialogFiller::editGeneralOptions(const Action &action) {
GT_CHECK(Action::EDIT_GENERAL_OPTIONS == action.type, "Invalid action type");
GTUtilsDialog::waitForDialog(os, new CommonImportOptionsDialogFiller(os, action.data));
QWidget* optionsButton = GTWidget::findWidget(os, "pbOptions");
GT_CHECK(NULL != optionsButton, "optionsButton is NULL");
GTWidget::click(os, optionsButton);
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "editPrivateOptions"
void ImportToDatabaseDialogFiller::editPrivateOptions(const Action &action) {
GT_CHECK(Action::EDIT_PRIVATE_OPTIONS == action.type, "Invalid action type");
GT_CHECK(action.data.contains(Action::ACTION_DATA__ITEM), "Not enough parameters to perform the action");
GTUtilsDialog::waitForDialog(os, new ItemToImportEditDialogFiller(os, action.data));
GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Override options"));
const QPoint itemCenter = getItemCenter(action.data.value(Action::ACTION_DATA__ITEM).toString());
GTMouseDriver::moveTo(itemCenter);
GTMouseDriver::click(Qt::RightButton);
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "resetPrivateOptions"
void ImportToDatabaseDialogFiller::resetPrivateOptions(const Action &action) {
GT_CHECK(Action::RESET_PRIVATE_OPTIONS == action.type, "Invalid action type");
GT_CHECK(action.data.contains(Action::ACTION_DATA__ITEM), "Not enough parameters to perform the action");
GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Reset to general options"));
const QPoint itemCenter = getItemCenter(action.data.value(Action::ACTION_DATA__ITEM).toString());
GTMouseDriver::moveTo(itemCenter);
GTMouseDriver::click(Qt::RightButton);
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "remove"
void ImportToDatabaseDialogFiller::remove(const Action &action) {
GT_CHECK(Action::REMOVE == action.type, "Invalid action type");
QWidget* removeButton = GTWidget::findWidget(os, "pbRemove");
GT_CHECK(NULL != removeButton, "removeButton is NULL");
GTWidget::click(os, removeButton);
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "import"
void ImportToDatabaseDialogFiller::import(const Action &action) {
GT_CHECK(Action::IMPORT == action.type, "Invalid action type");
QWidget* importButton = GTWidget::findWidget(os, "import_button");
GT_CHECK(NULL != importButton, "importButton is NULL");
GTWidget::click(os, importButton);
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "cancel"
void ImportToDatabaseDialogFiller::cancel(const Action &action) {
GT_CHECK(Action::CANCEL == action.type, "Invalid action type");
QWidget* cancelButton = GTWidget::findWidget(os, "cancel_button");
GT_CHECK(NULL != cancelButton, "cancelButton is NULL");
GTWidget::click(os, cancelButton);
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "getItemCenter"
QPoint ImportToDatabaseDialogFiller::getItemCenter(const QString &text) {
QTreeWidget* treeWidget = qobject_cast<QTreeWidget*>(GTWidget::findWidget(os, "twOrders", dialog));
GT_CHECK_RESULT(NULL != treeWidget, "treeWidget is NULL", QPoint());
QTreeWidgetItem* item = findItem(text);
CHECK_OP(os, QPoint());
const QPoint headerOffset = QPoint(0, treeWidget->header()->height());
return treeWidget->mapToGlobal(treeWidget->visualItemRect(item).center() + headerOffset);
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "getFolderColumnCenter"
QPoint ImportToDatabaseDialogFiller::getFolderColumnCenter(const QString &text) {
QTreeWidget* treeWidget = qobject_cast<QTreeWidget*>(GTWidget::findWidget(os, "twOrders", dialog));
GT_CHECK_RESULT(NULL != treeWidget, "treeWidget is NULL", QPoint());
const QPoint itemCenter = treeWidget->mapFromGlobal(getItemCenter(text));
const QPoint columnCenter(treeWidget->columnViewportPosition(1) + treeWidget->columnWidth(1) / 2, itemCenter.y());
return treeWidget->mapToGlobal(columnCenter);
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "findItem"
QTreeWidgetItem *ImportToDatabaseDialogFiller::findItem(const QString &text) {
QTreeWidget* treeWidget = qobject_cast<QTreeWidget*>(GTWidget::findWidget(os, "twOrders", dialog));
GT_CHECK_RESULT(NULL != treeWidget, "treeWidget is NULL", NULL);
QList<QTreeWidgetItem*> items = treeWidget->findItems(text, Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive));
GT_CHECK_RESULT(!items.isEmpty(), "Item was not found", NULL);
GT_CHECK_RESULT(items.size() == 1, "Several items were found unexpectedly", NULL);
return items.first();
}
#undef GT_METHOD_NAME
#undef GT_CLASS_NAME
} // namespace U2
| gpl-2.0 |
gbentley/ezpublish-kernel | eZ/Bundle/EzPublishCoreBundle/DependencyInjection/Compiler/XmlTextConverterPass.php | 1242 | <?php
/**
* File containing the XmlTextConverterPass class.
*
* @copyright Copyright (C) 1999-2013 eZ Systems AS. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
* @version //autogentag//
*/
namespace eZ\Bundle\EzPublishCoreBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* Compiler pass adding pre-converters to HTML5 converter.
* Useful for manipulating internal XML before XSLT rendering.
*/
class XmlTextConverterPass implements CompilerPassInterface
{
public function process( ContainerBuilder $container )
{
if ( !$container->hasDefinition( 'ezpublish.fieldType.ezxmltext.converter.html5' ) )
{
return;
}
$html5ConverterDef = $container->getDefinition( 'ezpublish.fieldType.ezxmltext.converter.html5' );
foreach ( $container->findTaggedServiceIds( 'ezpublish.ezxml.converter' ) as $id => $attributes )
{
$html5ConverterDef->addMethodCall( 'addPreConverter', array( new Reference( $id ) ) );
}
}
}
| gpl-2.0 |
andresmaeso/neno | libraries/neno/error/error.php | 1357 | <?php
/**
* @package Neno
* @subpackage Error
*
* @copyright Copyright (c) 2014 Jensen Technologies S.L. All rights reserved
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* Class Error
*/
class NenoError
{
public static function error($errorNumber, $errorMessage, $file, $line)
{
$errorType = 'none';
switch ($errorNumber)
{
case E_ERROR:
$errorType = 'error';
break;
case E_WARNING:
$errorType = 'warning';
break;
case E_PARSE:
$errorType = 'parse';
break;
case E_NOTICE:
$errorType = 'notice';
break;
case E_CORE_ERROR:
$errorType = 'core error';
break;
case E_CORE_WARNING:
$errorType = 'core warning';
break;
case E_USER_ERROR:
$errorType = 'user error';
break;
case E_USER_WARNING:
$errorType = 'user warning';
break;
case E_USER_NOTICE:
$errorType = 'user notice';
break;
case E_STRICT:
$errorType = 'strict';
break;
case E_RECOVERABLE_ERROR:
$errorType = 'recoverable error';
break;
case E_DEPRECATED:
$errorType = 'deprecated';
break;
case E_USER_DEPRECATED:
$errorType = 'user deprecated';
break;
}
NenoLog::log("Encountered $errorType error in $file, line $line: $errorMessage", NenoLog::PRIORITY_ERROR);
}
} | gpl-2.0 |
MESH-Dev/CMANY | wp-content/themes/CMANEW/template-currentex.php | 1645 | <?php
/**
* Template Name: Current Exhibitions
*/
get_header();
get_sidebar('mainnew');
get_header('nav');
?>
<!--PAGE-NEW-->
<div id="page-new" >
<!--PAGE-CONTAINER -->
<div id="page-container" class="new_page">
<!--TITLE -->
<div class="block">
<h2 class="page-title<?php echo $currentcolor; ?>">
Current Exhibitions
</h2>
</div>
<div class="block">
<!-- Header Text Custom Field-->
<div class="headline"><?php the_field('header-text'); ?></div>
</div>
<?php while ( have_posts() ) : the_post(); ?>
<!-- Box Repeater Custom Field-->
<div class="block">
<?php while(the_repeater_field('blocks')): ?>
<div class="overview-item" href="<?php the_sub_field('block-link');?>">
<?php
$attachment_id = get_sub_field('block-image');
$size = "blockimage";
$image = wp_get_attachment_image( $attachment_id, $size ); ?>
<img src="<?php the_sub_field('block-image')?>" />
<a href="<?php the_sub_field('block-link');?>" >
<div class="subtitle">
<div style="display:none">hahahaha</div>
<h3><?php the_sub_field('block-title');?></h3>
<p><?php the_sub_field('block-description');?></p>
<a class="read-more" href="<?php the_sub_field('block-link');?>" >READ MORE >></a>
</div>
</a>
</div>
<?php endwhile ?>
</div>
<?php endwhile; ?>
<div class="clear"> </div>
<!--CLEAR-->
<!--END PAGE-CONTAINER -->
</div>
<!--END PAGE-NEW-->
</div>
<?php get_footer(); ?>
| gpl-2.0 |
elggem/redditbot | src/com/cd/reddit/json/util/RedditComments.java | 1130 | package com.cd.reddit.json.util;
import java.util.List;
import com.cd.reddit.json.mapping.RedditComment;
import com.cd.reddit.json.mapping.RedditLink;
import com.cd.reddit.json.mapping.RedditMore;
public class RedditComments {
private final RedditLink parentLink;
private final List<RedditComment> comments;
private final RedditMore more;
public RedditComments(final RedditLink theParentLink,
final List<RedditComment> theParsedTypes,
final RedditMore theMore){
parentLink = theParentLink;
comments = theParsedTypes;
more = theMore;
}
public RedditLink getParentLink(){
return parentLink;
}
public List<RedditComment> getComments() {
return comments;
}
public RedditMore getMore() {
return more;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("RedditComments [parentLink=");
builder.append(parentLink);
builder.append(", comments=");
builder.append(comments);
builder.append(", more=");
builder.append(more);
builder.append("]");
return builder.toString();
}
}
| gpl-2.0 |
felixonmars/app | extensions/wikia/WikiaHubsServices/models/WikiaHubsPollsModel.class.php | 422 | <?
class WikiaHubsPollsModel extends WikiaModel {
const MANDATORY_OPTIONS_LIMIT = 2;
const VOLUNTARY_OPTIONS_LIMIT = 8;
public function getMandatoryOptionsLimit() {
return self::MANDATORY_OPTIONS_LIMIT;
}
public function getVoluntaryOptionsLimit() {
return self::VOLUNTARY_OPTIONS_LIMIT;
}
public function getTotalOptionsLimit() {
return self::MANDATORY_OPTIONS_LIMIT + self::VOLUNTARY_OPTIONS_LIMIT;
}
}
| gpl-2.0 |
btb/punbb-legacy | lang/English/admin_common.php | 1885 | <?php
// Language definitions used in all admin files
$lang_admin_common = array(
// Common items
'Save changes' => 'Save changes',
'Redirect' => 'Redirecting…',
'Add' => 'Add',
'Add new' => 'Add new',
'Delete' => 'Delete',
'Edit' => 'Edit',
'Update' => 'Update',
'Remove' => 'Remove',
'Update all' => 'Update all',
'Yes' => 'Yes',
'No' => 'No',
'Save changes' => 'Save changes',
'Save' => 'Save',
'E-mail' => 'E-mail',
'Cancel' => 'Cancel',
'Cancel redirect' => 'Operation cancelled. Redirecting…',
'Unknown' => 'Unknown',
'Delete help' => 'Requires confirmation via separate form.',
'Select all' => 'Select all',
'Required' => '(Required)',
'Required warn' => 'All fields labelled %s must be completed before the form is submitted.',
// Main Admin Menu Items and Title
'Forum administration' => 'Administration',
'Start' => 'Start',
'Settings' => 'Settings',
'Users' => 'Users',
'Options' => 'Options',
'Management' => 'Management',
'Extensions' => 'Extensions',
'Moderate' => 'Moderate',
// Start Submenu
'Information' => 'Information',
'Categories' => 'Categories',
'Forums' => 'Forums',
// Settings Submenu
'Setup' => 'Setup',
'Features' => 'Features',
'Announcements' => 'Announcements',
'Registration' => 'Registration',
'E-mail' => 'E-mail',
'Censoring' => 'Censoring',
// Users Submenu
'Searches' => 'Searches',
'Groups' => 'Groups',
'Ranks' => 'Ranks',
'Bans' => 'Bans',
// Management Submenu
'Reports' => 'Reports',
'Prune topics' => 'Prune topics',
'Maintenance mode' => 'Maintenance mode',
'Rebuild index' => 'Rebuild index',
// Extensions Submenu
'Manage extensions' => 'Manage extensions',
'Manage hotfixes' => 'Manage hotfixes',
); | gpl-2.0 |
jbelborja/lavid | components/com_jevents/jevents.php | 9243 | <?php
/**
* JEvents Component for Joomla 1.5.x
*
* @version $Id: jevents.php 3551 2012-04-20 09:41:37Z geraintedwards $
* @package JEvents
* @copyright Copyright (C) 2008-2009 GWE Systems Ltd
* @license GNU/GPLv2, see http://www.gnu.org/licenses/gpl-2.0.html
* @link http://www.jevents.net
*/
defined( 'JPATH_BASE' ) or die( 'Direct Access to this location is not allowed.' );
jimport('joomla.filesystem.path');
/*
// JevDate test
jimport("joomla.utilities.date");
$date = new JevDate("1.30pm 12 March 2011", new DateTimeZone('America/New_York'));
echo $date->format("Y-m-d H:i:s")."<br/>";
echo "<hr/>";
$date->add(new DateInterval('P1D'));
echo $date->format("Y-m-d H:i:s")."<br/>";
echo "<hr/>";
$date = new JevDate("1.30pm 12 March 2011", new DateTimeZone('UTC'));
echo $date->format("Y-m-d H:i:s")."<br/>";
echo "<hr/>";
$date->add(new DateInterval('P1D'));
echo $date->format("Y-m-d H:i:s")."<br/>";
echo "<hr/>";
$date = new JevDate("1.30pm 12 March 2011", new DateTimeZone('America/New_York'));
echo $date->format("Y-m-d H:i:s")."<br/>";
echo "<hr/>";
$date->modify("+1 day");
echo $date->format("Y-m-d H:i:s")."<br/>";
echo "<hr/>";
*/
// For development performance testing only
/*
$db =& JFactory::getDBO();
$db->setQuery("SET SESSION query_cache_type = OFF");
$db->query();
$cfg = & JEVConfig::getInstance();
$cfg->set('jev_debug', 1);
*/
include_once(JPATH_COMPONENT.DS."jevents.defines.php");
$isMobile = false;
jimport("joomla.environment.browser");
$browser = JBrowser::getInstance();
$registry =& JRegistry::getInstance("jevents");
// In Joomla 1.6 JComponentHelper::getParams(JEV_COM_COMPONENT) is a clone so the menu params do not propagate so we force this here!
if (JVersion::isCompatible("1.6.0")){
$newparams = JFactory::getApplication('site')->getParams();
// Because the application sets a default page title,
// we need to get it from the menu item itself
$menu = JFactory::getApplication()->getMenu()->getActive();
if ($menu) {
$newparams->def('page_heading', $newparams->get('page_title', $menu->title));
}
else {
$params = JComponentHelper::getParams(JEV_COM_COMPONENT);
$newparams->def('page_heading', $params->get('page_title')) ;
}
$component =& JComponentHelper::getComponent(JEV_COM_COMPONENT);
$component->params =& $newparams;
$isMobile = $browser->isMobile();
// Joomla isMobile method doesn't identify all android phones
if (!$isMobile && isset($_SERVER['HTTP_USER_AGENT']) && stripos($_SERVER['HTTP_USER_AGENT'], 'android') !== false) {
$isMobile = true;
}
}
else {
$isMobile = $browser->_mobile;
}
$params =& JComponentHelper::getParams(JEV_COM_COMPONENT);
if ($isMobile || strpos(JFactory::getApplication()->getTemplate(), 'mobile_')===0 || (class_exists("T3Common") && class_exists("T3Parameter") && T3Common::mobile_device_detect()) || JRequest::getVar("jEV","")=="smartphone"){
JRequest::setVar("jevsmartphone",1);
if (JFolder::exists(JEV_VIEWS."/smartphone")){
JRequest::setVar("jEV","smartphone");
}
$params->set('iconicwidth',485);
$params->set('extpluswidth',485);
$params->set('ruthinwidth',485);
}
// See http://www.php.net/manual/en/timezones.php
$tz=$params->get("icaltimezonelive","");
if ($tz!="" && is_callable("date_default_timezone_set")){
$timezone= date_default_timezone_get();
date_default_timezone_set($tz);
$registry->setValue("jevents.timezone",$timezone);
}
if (!JVersion::isCompatible("1.6.0")){
// Multi-category events only supported in Joomla 2.5 + so disable elsewhere
$params->set('multicategory',0);
}
// Must also load backend language files
$lang =& JFactory::getLanguage();
$lang->load(JEV_COM_COMPONENT, JPATH_ADMINISTRATOR);
// Load Site specific language overrides
$lang->load(JEV_COM_COMPONENT, JPATH_THEMES.DS.JFactory::getApplication()->getTemplate());
// disable Zend php4 compatability mode
@ini_set("zend.ze1_compatibility_mode","Off");
// Split task into command and task
$cmd = JRequest::getCmd('task', false);
if (!$cmd) {
$view = JRequest::getCmd('view', false);
$layout = JRequest::getCmd('layout', "show");
if ($view && $layout){
$cmd = $view.'.'.$layout;
}
else $cmd = "month.calendar";
}
if (strpos($cmd, '.') != false) {
// We have a defined controller/task pair -- lets split them out
list($controllerName, $task) = explode('.', $cmd);
// Define the controller name and path
$controllerName = strtolower($controllerName);
$controllerPath = JPATH_COMPONENT.DS.'controllers'.DS.$controllerName.'.php';
//$controllerName = "Front".$controllerName;
// If the controller file path exists, include it ... else lets die with a 500 error
if (file_exists($controllerPath)) {
require_once($controllerPath);
} else {
JFactory::getApplication()->enqueueMessage('Invalid Controller - '.$controllerName );
$cmd = "month.calendar";
list($controllerName, $task) = explode('.', $cmd);
$controllerPath = JPATH_COMPONENT.DS.'controllers'.DS.$controllerName.'.php';
require_once($controllerPath);
}
} else {
// Base controller, just set the task
$controllerName = null;
$task = $cmd;
}
// Make the task available later
JRequest::setVar("jevtask",$cmd);
JRequest::setVar("jevcmd",$cmd);
// Are all Jevents pages apart from crawler, rss and details pages to be redirected for search engines?
if (in_array($cmd, array("year.listevents","month.calendar","week.listevents","day.listevents","cat.listevents","search.form",
"search.results","admin.listevents","jevent.edit","icalevent.edit","icalevent.publish","icalevent.unpublish",
"icalevent.editcopy","icalrepeat.edit","jevent.delete","icalevent.delete","icalrepeat.delete","icalrepeat.deletefuture")))
{
$browser = JBrowser::getInstance();
if ($params->get("redirectrobots", 0) && ($browser->isRobot() || strpos ($browser->getAgentString(), "bingbot")!==false))
{
// redirect to crawler menu item
$Itemid = $params->get("robotmenuitem", 0);
JFactory::getApplication()->redirect(JRoute::_("index.php?option=com_jevents&task=crawler.listevents&Itemid=$Itemid"));
}
}
JPluginHelper::importPlugin("jevents");
// Make sure the view specific language file is loaded
JEV_CommonFunctions::loadJEventsViewLang();
// Set the name for the controller and instantiate it
$controllerClass = ucfirst($controllerName).'Controller';
if (class_exists($controllerClass)) {
$controller = new $controllerClass();
} else {
JFactory::getApplication()->enqueueMessage('Invalid Controller Class - '.$controllerClass );
$cmd = "month.calendar";
list($controllerName, $task) = explode('.', $cmd);
JRequest::setVar("jevtask",$cmd);
JRequest::setVar("jevcmd",$cmd);
$controllerClass = ucfirst($controllerName).'Controller';
$controllerPath = JPATH_COMPONENT.DS.'controllers'.DS.$controllerName.'.php';
require_once($controllerPath);
$controller = new $controllerClass();
}
// create live bookmark if requested
$cfg = & JEVConfig::getInstance();
if ($cfg->get('com_rss_live_bookmarks')) {
$Itemid = JRequest::getInt('Itemid', 0);
$rssmodid = $cfg->get('com_rss_modid', 0);
// do not use JRoute since this creates .rss link which normal sef can't deal with
$rssLink = 'index.php?option='.JEV_COM_COMPONENT.'&task=modlatest.rss&format=feed&type=rss&Itemid='.$Itemid.'&modid='.$rssmodid;
$rssLink = JUri::root().$rssLink;
if (JVersion::isCompatible("1.6.0")){
if (method_exists(JFactory::getDocument(),"addHeadLink")){
$attribs = array('type' => 'application/rss+xml', 'title' => 'RSS 2.0');
JFactory::getDocument()->addHeadLink($rssLink, 'alternate', 'rel', $attribs);
}
}
else {
$rss = '<link href="' .$rssLink .'" rel="alternate" type="application/rss+xml" title="JEvents - RSS 2.0 Feed" />'. "\n";
JFactory::getApplication()->addCustomHeadTag( $rss );
}
$rssLink = 'index.php?option='.JEV_COM_COMPONENT.'&task=modlatest.rss&format=feed&type=atom&Itemid='.$Itemid.'&modid='.$rssmodid;
$rssLink = JUri::root().$rssLink;
//$rssLink = JRoute::_($rssLink);
if (JVersion::isCompatible("1.6.0")){
if (method_exists(JFactory::getDocument(),"addHeadLink")){
$attribs = array('type' => 'application/atom+xml', 'title' => 'Atom 1.0');
JFactory::getDocument()->addHeadLink($rssLink, 'alternate', 'rel', $attribs);
}
}
else {
$rss = '<link href="' .$rssLink .'" rel="alternate" type="application/rss+xml" title="JEvents - Atom Feed" />'. "\n";
JFactory::getApplication()->addCustomHeadTag( $rss );
}
}
// Add reference for constructor in registry - unfortunately there is no add by reference method
// we rely on php efficiency to not create a copy
$registry =& JRegistry::getInstance("jevents");
$registry->setValue("jevents.controller",$controller);
// record what is running - used by the filters
$registry->setValue("jevents.activeprocess","component");
// Stop viewing ALL events - it could take VAST amounts of memory
if ($cfg->get('blockall', 0) && ( JRequest::getInt("limit" , -1) == 0 || JRequest::getInt("limit" , -1) >100 )){
JRequest::setVar("limit",100);
}
// Perform the Request task
$controller->execute($task);
// Must reset the timezone back!!
if ($tz && is_callable("date_default_timezone_set")){
date_default_timezone_set($timezone);
}
// Redirect if set by the controller
$controller->redirect();
| gpl-2.0 |
jshorty/chickadee | db/migrate/20160409215248_add_index_to_user_birds.rb | 111 | class AddIndexToUserBirds < ActiveRecord::Migration
def change
add_index :user_birds, :user_id
end
end
| gpl-2.0 |
nao-pon/xpWiki | html/common/fckxpwiki/plugins/TableEx/fckplugin.js | 8023 | //
// guiedit - PukiWiki Plugin
//
// License:
// GNU General Public License Version 2 or later (GPL)
// http://www.gnu.org/licenses/gpl.html
//
// Copyright (C) 2006-2007 garand
// PukiWiki : Copyright (C) 2001-2006 PukiWiki Developers Team
// FCKeditor : Copyright (C) 2003-2007 Frederico Caldeira Knabben
//
///////////////////////////////////////////////////////////
// コマンド
// テーブル プロパティ
FCKCommands.GetCommand('Table').Url = FCKPlugins.Items['TableEx'].Path + 'Table.html';
FCKCommands.GetCommand('Table').Width = 260;
FCKCommands.GetCommand('Table').Height = 160;
FCKCommands.GetCommand('Table').GetState = function() {
// Disabled if not WYSIWYG.
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG || ! FCK.EditorWindow )
return FCK_TRISTATE_DISABLED ;
var tags = new Array('H2', 'H3', 'H4', 'H5', 'H6', 'PRE', 'TABLE');
for (i = 0; i < tags.length; i++) {
if (FCKSelection.HasAncestorNode(tags[i])) {
return FCK_TRISTATE_DISABLED;
}
}
var oElement = FCKSelection.GetSelectedElement();
if (oElement && oElement.tagName.Equals('IMG', 'HR', 'DIV', 'SPAN')) {
return FCK_TRISTATE_DISABLED;
}
return FCK_TRISTATE_OFF;
}
// セル プロパティ
FCKCommands.RegisterCommand('TableCellProp',
new FCKDialogCommand('TableCellEx', FCKLang.CellProperties,
FCKPlugins.Items['TableEx'].Path + 'TableCell.html', 380, 200
)
);
// 列 プロパティ
FCKCommands.RegisterCommand('TableCol',
new FCKDialogCommand('TableCol', FCKLang.TableColDlgTitle,
FCKPlugins.Items['TableEx'].Path + 'TableCol.html', 380, 180
)
);
// セルの挿入
FCKCommands.GetCommand('TableInsertCellBefore').Execute = function() {
TableInsertCell(true);
}
FCKCommands.GetCommand('TableInsertCellAfter').Execute = function() {
TableInsertCell(false);
}
function TableInsertCell(insertBefore) {
FCKUndo.SaveUndoStep();
var oCell = FCKSelection.MoveToAncestorNode('TD') || FCKSelection.MoveToAncestorNode('TH');
oCell = FCKTableHandler.InsertCell(oCell, insertBefore);
oCell.className = 'style_td';
FCKUndo.SaveUndoStep();
}
// 列削除
FCKCommands.GetCommand('TableDeleteColumns').Execute = function() {
var oCell = FCKSelection.MoveToAncestorNode('TD') || FCKSelection.MoveToAncestorNode('TH');
if (!oCell) {
return;
}
FCKUndo.SaveUndoStep();
var oTable = FCKTools.GetElementAscensor(oCell, 'TABLE');
var aTableMap = FCKTableHandler._CreateTableMap(oTable);
var nColIndex = FCKTableHandler._GetCellIndexSpan(aTableMap, oCell.parentNode.rowIndex, oCell);
FCKTableHandler.DeleteColumns();
var aColGroups = oTable.getElementsByTagName('COLGROUP');
var aCols;
if (!aColGroups.length) {
return;
}
for (i = 0; i < aColGroups.length; i++) {
aCols = aColGroups[i].getElementsByTagName('COL');
aColGroups[i].removeChild(aCols[nColIndex]);
}
FCKUndo.SaveUndoStep();
}
// セルを左右に分割
FCKCommands.RegisterCommand('TableSplitCellRightLeft', {
Execute : function() {
var cells = FCKTableHandler.GetSelectedCells();
if ( cells.length != 1 )
return ;
FCKUndo.SaveUndoStep();
FCKTableHandler.HorizontalSplitCell();
var refBase = cells[0].parentNode.parentNode;
var tag = cells[0].nodeName;
var elems = refBase.getElementsByTagName(tag);
var name = 'style_' + cells[0].nodeName.toLowerCase();
for (var i=0; i<elems.length; i++) {
if (! elems[i].className) {
elems[i].className = name;
}
}
FCKUndo.SaveUndoStep();
},
GetState : function() { return FCK_TRISTATE_OFF; }
})
// セルを上下に分割
FCKCommands.RegisterCommand('TableSplitCellTopBottom', {
Execute : function() {
var cells = FCKTableHandler.GetSelectedCells();
if ( cells.length != 1 )
return ;
FCKUndo.SaveUndoStep();
FCKTableHandler.VerticalSplitCell();
var refBase = cells[0].parentNode.parentNode;
var tag = cells[0].nodeName;
var elems = refBase.getElementsByTagName(tag);
var name = 'style_' + cells[0].nodeName.toLowerCase();
for (var i=0; i<elems.length; i++) {
if (! elems[i].className) {
elems[i].className = name;
}
}
FCKUndo.SaveUndoStep();
},
GetState : function() { return FCK_TRISTATE_OFF; }
})
// FCKeditorのバグ対策 ([Firefox]セル結合でリンクを含むセルが消える)
FCKCommands.RegisterCommand('TableMergeGecko', {
Execute : function() {
var cells = FCKTableHandler.GetSelectedCells();
for (var i=0; i<cells.length; i++) {
var elems = cells[i].getElementsByTagName('a');
for (var i2=0; i2<elems.length; i2++) {
if (! elems[i2].className) {
elems[i2].setAttribute('_moz_dirty', '');
}
}
}
FCKUndo.SaveUndoStep();
FCKTableHandler.MergeCells();
FCKUndo.SaveUndoStep();
},
GetState : function() { return FCK_TRISTATE_OFF; }
})
// セル 見出し/通常 反転
FCKCommands.RegisterCommand('TableCellHeadToggle', {
Execute : function() {
var aCells = FCKTableHandler.GetSelectedCells();
FCKUndo.SaveUndoStep();
for (var i=0; i<aCells.length; i++) {
var tag = (aCells[i].tagName.toLowerCase() == 'td')? 'TH' : 'TD';
// タグの置換
oElement = FCK.EditorDocument.createElement(tag);
oElement.className = (tag == 'TH') ? 'style_th' : 'style_td';
oElement.innerHTML = aCells[i].innerHTML;
oElement.colSpan = aCells[i].colSpan;
oElement.rowSpan = aCells[i].rowSpan;
oElement.setAttribute('style', aCells[i].getAttribute('style'));
aCells[i] = aCells[i].parentNode.replaceChild(oElement, aCells[i]);
}
FCKUndo.SaveUndoStep();
},
GetState : function() { return FCK_TRISTATE_OFF; }
})
///////////////////////////////////////////////////////////
// ツールバー
FCK.Events.AttachEvent('OnSelectionChange', function () { FCKToolbarItems.GetItem('Table').RefreshState() });
///////////////////////////////////////////////////////////
// コンテキストメニュー
FCK.ContextMenu.RegisterListener( {
AddItems : function(menu, tag, tagName) {
var bIsTable = (tagName == 'TABLE');
var bIsCell = (!bIsTable && FCKSelection.HasAncestorNode('TABLE'));
if (bIsCell) {
menu.AddSeparator();
var oItem = menu.AddItem('Cell', FCKLang.CellCM);
oItem.AddItem('TableCellHeadToggle', FCKLang.TableCellHeadToggle, 39);
oItem.AddItem('TableInsertCellBefore', FCKLang.InsertCellBefore, 69);
oItem.AddItem('TableInsertCellAfter', FCKLang.InsertCellAfter, 58);
oItem.AddItem('TableDeleteCells', FCKLang.DeleteCells, 59);
if ( FCKBrowserInfo.IsGecko ) {
oItem.AddItem( 'TableMergeGecko' , FCKLang.MergeCells, 60,
FCKCommands.GetCommand( 'TableMergeCells' ).GetState() == FCK_TRISTATE_DISABLED ) ;
}
else {
oItem.AddItem('TableMergeRight', FCKLang.MergeRight, 60);
oItem.AddItem('TableMergeDown', FCKLang.MergeDown, 60);
}
oItem.AddItem('TableSplitCellRightLeft', FCKLang.HorizontalSplitCell, 61, FCKCommands.GetCommand( 'TableHorizontalSplitCell' ).GetState() == FCK_TRISTATE_DISABLED );
oItem.AddItem('TableSplitCellTopBottom', FCKLang.VerticalSplitCell, 61, FCKCommands.GetCommand( 'TableVerticalSplitCell' ).GetState() == FCK_TRISTATE_DISABLED);
oItem.AddSeparator();
oItem.AddItem('TableCellProp', FCKLang.CellProperties, 57);
menu.AddSeparator();
oItem = menu.AddItem('Row', FCKLang.RowCM);
oItem.AddItem('TableInsertRowBefore', FCKLang.InsertRowBefore, 70);
oItem.AddItem('TableInsertRowAfter', FCKLang.InsertRowAfter, 62);
oItem.AddItem('TableDeleteRows', FCKLang.DeleteRows, 63);
menu.AddSeparator();
oItem = menu.AddItem('Column', FCKLang.TableColMenu);
oItem.AddItem('TableInsertColumnBefore', FCKLang.InsertColumnBefore, 71);
oItem.AddItem('TableInsertColumnAfter', FCKLang.InsertColumnAfter, 64);
oItem.AddItem('TableDeleteColumns', FCKLang.DeleteColumns, 65);
oItem.AddSeparator();
oItem.AddItem('TableCol', FCKLang.TableColDlgTitle);
}
if (bIsTable || bIsCell) {
menu.AddSeparator();
menu.AddItem('TableDelete', FCKLang.TableDelete);
menu.AddItem('Table', FCKLang.TableProperties, 39);
}
}}
);
| gpl-2.0 |
george5613/libertv | libtorrent.svn/include/libtorrent/invariant_check.hpp | 1482 | // Copyright Daniel Wallin 2004. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef TORRENT_INVARIANT_ACCESS_HPP_INCLUDED
#define TORRENT_INVARIANT_ACCESS_HPP_INCLUDED
#include <cassert>
namespace libtorrent
{
class invariant_access
{
public:
template<class T>
static void check_invariant(T const& self)
{
self.check_invariant();
}
};
template<class T>
void check_invariant(T const& x)
{
invariant_access::check_invariant(x);
}
struct invariant_checker {};
template<class T>
struct invariant_checker_impl : invariant_checker
{
invariant_checker_impl(T const& self_)
: self(self_)
{
try
{
check_invariant(self);
}
catch (...)
{
assert(false);
}
}
~invariant_checker_impl()
{
try
{
check_invariant(self);
}
catch (...)
{
assert(false);
}
}
T const& self;
};
template<class T>
invariant_checker_impl<T> make_invariant_checker(T const& x)
{
return invariant_checker_impl<T>(x);
}
}
#ifndef NDEBUG
#define INVARIANT_CHECK \
invariant_checker const& _invariant_check = make_invariant_checker(*this); \
(void)_invariant_check; \
do {} while (false)
#else
#define INVARIANT_CHECK do {} while (false)
#endif
#endif // TORRENT_INVARIANT_ACCESS_HPP_INCLUDED
| gpl-2.0 |
Lasica/RebeliaProgramowalnychZaskroncow | src/shared/Map.hpp | 908 | #ifndef WORLD_HPP
#define WORLD_HPP
#include <iostream>
#include <cstdio>
#include <vector>
typedef char MapUnit;
class Map {
public:
Map(): width(10), height(10), baseMapUnit_('.') { map_resize(width,height);}
void map_resize(int x, int y) {
if(x > 20) x = 20;
if(y > 20) y = 20;
if(x < 1) x = 1;
if(y < 1) y = 1;
field_.resize(y);
for(int i=0; i < y; ++i) {
field_[i].resize(x, baseMapUnit_);
}
width = x;
height = y;
}
void set_base_map_unit(const MapUnit &a) { baseMapUnit_ = a; }
void set_field(const int &x, const int &y, const MapUnit &character) {
if(x >=0 && x < width && y >=0 && y < height) {
field_[y][x] = character;
}
}
//private:
std::vector<std::vector<MapUnit>> field_; //map[y][x]
int width;
int height;
MapUnit baseMapUnit_;
};
#endif
| gpl-2.0 |
yinheark/yincart2 | lib/yincart/cart/_helpers/_kiwi_helper.php | 388 | <?php
namespace kiwi;
exit("This file should not be included, only analyzed by your IDE");
/**
* @method static \yincart\cart\models\ShoppingCart getShoppingCart()
* @method static \yincart\cart\models\Cart getCart()
* @method static string|\yincart\cart\models\ShoppingCart getShoppingCartClass()
* @method static string|\yincart\cart\models\Cart getCartClass()
*/
class Kiwi
{
} | gpl-2.0 |