Chronicle 4 branch.

This commit is contained in:
MobiusDev
2017-07-19 21:24:06 +00:00
parent 9a69bec286
commit 3a0bf3539a
13496 changed files with 641683 additions and 0 deletions

View File

@@ -0,0 +1,120 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.logging.Logger;
import com.l2jmobius.Config;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.model.L2ArmorSet;
import javolution.util.FastMap;
/**
* @author Luno
*/
public class ArmorSetsTable
{
private static Logger _log = Logger.getLogger(ArmorSetsTable.class.getName());
private static ArmorSetsTable _instance;
private final FastMap<Integer, L2ArmorSet> _armorSets;
public static ArmorSetsTable getInstance()
{
if (_instance == null)
{
_instance = new ArmorSetsTable();
}
return _instance;
}
private ArmorSetsTable()
{
_armorSets = new FastMap<>();
loadData();
}
private void loadData()
{
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT chest, legs, head, gloves, feet, skill_id, shield, shield_skill_id FROM armorsets");
ResultSet rset = statement.executeQuery())
{
while (rset.next())
{
final int chest = rset.getInt("chest");
final int legs = rset.getInt("legs");
final int head = rset.getInt("head");
final int gloves = rset.getInt("gloves");
final int feet = rset.getInt("feet");
final int skill_id = rset.getInt("skill_id");
final int shield = rset.getInt("shield");
final int shield_skill_id = rset.getInt("shield_skill_id");
_armorSets.put(chest, new L2ArmorSet(chest, legs, head, gloves, feet, skill_id, shield, shield_skill_id));
}
_log.config("ArmorSetsTable: Loaded " + _armorSets.size() + " armor sets.");
}
catch (final Exception e)
{
_log.severe("ArmorSetsTable: Error reading ArmorSets table: " + e);
}
if (Config.CUSTOM_ARMORSETS_TABLE)
{
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT chest, legs, head, gloves, feet, skill_id, shield, shield_skill_id FROM custom_armorsets");
ResultSet rset = statement.executeQuery())
{
final int cSets = _armorSets.size();
while (rset.next())
{
final int chest = rset.getInt("chest");
final int legs = rset.getInt("legs");
final int head = rset.getInt("head");
final int gloves = rset.getInt("gloves");
final int feet = rset.getInt("feet");
final int skill_id = rset.getInt("skill_id");
final int shield = rset.getInt("shield");
final int shield_skill_id = rset.getInt("shield_skill_id");
_armorSets.put(chest, new L2ArmorSet(chest, legs, head, gloves, feet, skill_id, shield, shield_skill_id));
}
_log.config("ArmorSetsTable: Loaded " + (_armorSets.size() - cSets) + " custom armor sets.");
}
catch (final Exception e)
{
_log.severe("ArmorSetsTable: Error reading Custom ArmorSets table: " + e);
}
}
}
public boolean setExists(int chestId)
{
return _armorSets.containsKey(chestId);
}
public L2ArmorSet getSet(int chestId)
{
return _armorSets.get(chestId);
}
}

View File

@@ -0,0 +1,88 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Logger;
import com.l2jmobius.L2DatabaseFactory;
/**
* This class ...
* @version $Revision: 1.3.2.2.2.1 $ $Date: 2005/03/27 15:29:18 $
*/
public class CharNameTable
{
private static Logger _log = Logger.getLogger(CharNameTable.class.getName());
private static CharNameTable _instance;
public static CharNameTable getInstance()
{
if (_instance == null)
{
_instance = new CharNameTable();
}
return _instance;
}
public boolean doesCharNameExist(String name)
{
boolean result = true;
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT account_name FROM characters WHERE char_name=?"))
{
statement.setString(1, name);
try (ResultSet rset = statement.executeQuery())
{
result = rset.next();
}
}
catch (final SQLException e)
{
_log.warning("could not check existing charname:" + e.getMessage());
}
return result;
}
public int accountCharNumber(String account)
{
int number = 0;
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT COUNT(char_name) FROM characters WHERE account_name=?"))
{
statement.setString(1, account);
try (ResultSet rset = statement.executeQuery())
{
while (rset.next())
{
number = rset.getInt(1);
}
}
}
catch (final SQLException e)
{
_log.warning("could not check existing char number:" + e.getMessage());
}
return number;
}
}

View File

@@ -0,0 +1,300 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.logging.Logger;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.model.base.ClassId;
import com.l2jmobius.gameserver.templates.L2PcTemplate;
import com.l2jmobius.gameserver.templates.StatsSet;
import javolution.util.FastMap;
/**
* This class ...
* @version $Revision: 1.6.2.1.2.10 $ $Date: 2005/03/29 14:00:54 $
*/
public class CharTemplateTable
{
private static Logger _log = Logger.getLogger(CharTemplateTable.class.getName());
private static CharTemplateTable _instance;
public static final String[] charClasses =
{
"Human Fighter",
"Warrior",
"Gladiator",
"Warlord",
"Human Knight",
"Paladin",
"Dark Avenger",
"Rogue",
"Treasure Hunter",
"Hawkeye",
"Human Mystic",
"Human Wizard",
"Sorcerer",
"Necromancer",
"Warlock",
"Cleric",
"Bishop",
"Prophet",
"Elven Fighter",
"Elven Knight",
"Temple Knight",
"Swordsinger",
"Elven Scout",
"Plainswalker",
"Silver Ranger",
"Elven Mystic",
"Elven Wizard",
"Spellsinger",
"Elemental Summoner",
"Elven Oracle",
"Elven Elder",
"Dark Fighter",
"Palus Knight",
"Shillien Knight",
"Bladedancer",
"Assassin",
"Abyss Walker",
"Phantom Ranger",
"Dark Elven Mystic",
"Dark Elven Wizard",
"Spellhowler",
"Phantom Summoner",
"Shillien Oracle",
"Shillien Elder",
"Orc Fighter",
"Orc Raider",
"Destroyer",
"Orc Monk",
"Tyrant",
"Orc Mystic",
"Orc Shaman",
"Overlord",
"Warcryer",
"Dwarven Fighter",
"Dwarven Scavenger",
"Bounty Hunter",
"Dwarven Artisan",
"Warsmith",
"dummyEntry1",
"dummyEntry2",
"dummyEntry3",
"dummyEntry4",
"dummyEntry5",
"dummyEntry6",
"dummyEntry7",
"dummyEntry8",
"dummyEntry9",
"dummyEntry10",
"dummyEntry11",
"dummyEntry12",
"dummyEntry13",
"dummyEntry14",
"dummyEntry15",
"dummyEntry16",
"dummyEntry17",
"dummyEntry18",
"dummyEntry19",
"dummyEntry20",
"dummyEntry21",
"dummyEntry22",
"dummyEntry23",
"dummyEntry24",
"dummyEntry25",
"dummyEntry26",
"dummyEntry27",
"dummyEntry28",
"dummyEntry29",
"dummyEntry30",
"Duelist",
"Dreadnought",
"Phoenix Knight",
"Hell Knight",
"Sagittarius",
"Adventurer",
"Archmage",
"Soultaker",
"Arcana Lord",
"Cardinal",
"Hierophant",
"Eva Templar",
"Sword Muse",
"Wind Rider",
"Moonlight Sentinel",
"Mystic Muse",
"Elemental Master",
"Eva's Saint",
"Shillien Templar",
"Spectral Dancer",
"Ghost Hunter",
"Ghost Sentinel",
"Storm Screamer",
"Spectral Master",
"Shillien Saint",
"Titan",
"Grand Khavatari",
"Dominator",
"Doomcryer",
"Fortune Seeker",
"Maestro"
};
private final Map<Integer, L2PcTemplate> _templates;
public static CharTemplateTable getInstance()
{
if (_instance == null)
{
_instance = new CharTemplateTable();
}
return _instance;
}
private CharTemplateTable()
{
_templates = new FastMap<>();
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT * FROM class_list, char_templates, lvlupgain" + " WHERE class_list.id = char_templates.classId" + " AND class_list.id = lvlupgain.classId" + " ORDER BY class_list.id");
ResultSet rset = statement.executeQuery())
{
while (rset.next())
{
final StatsSet set = new StatsSet();
set.set("classId", rset.getInt("id"));
set.set("className", rset.getString("className"));
set.set("raceId", rset.getInt("raceId"));
set.set("baseSTR", rset.getInt("STR"));
set.set("baseCON", rset.getInt("CON"));
set.set("baseDEX", rset.getInt("DEX"));
set.set("baseINT", rset.getInt("_INT"));
set.set("baseWIT", rset.getInt("WIT"));
set.set("baseMEN", rset.getInt("MEN"));
set.set("baseHpMax", rset.getFloat("defaultHpBase"));
set.set("lvlHpAdd", rset.getFloat("defaultHpAdd"));
set.set("lvlHpMod", rset.getFloat("defaultHpMod"));
set.set("baseMpMax", rset.getFloat("defaultMpBase"));
set.set("baseCpMax", rset.getFloat("defaultCpBase"));
set.set("lvlCpAdd", rset.getFloat("defaultCpAdd"));
set.set("lvlCpMod", rset.getFloat("defaultCpMod"));
set.set("lvlMpAdd", rset.getFloat("defaultMpAdd"));
set.set("lvlMpMod", rset.getFloat("defaultMpMod"));
set.set("baseHpReg", 1.5);
set.set("baseMpReg", 0.9);
set.set("basePAtk", rset.getInt("p_atk"));
set.set("basePDef", rset.getInt("p_def"));
set.set("baseMAtk", rset.getInt("m_atk"));
set.set("baseMDef", rset.getInt("char_templates.m_def"));
set.set("classBaseLevel", rset.getInt("class_lvl"));
set.set("basePAtkSpd", rset.getInt("p_spd"));
set.set("baseMAtkSpd", rset.getInt("char_templates.m_spd"));
set.set("baseCritRate", rset.getInt("char_templates.critical") / 10);
set.set("baseRunSpd", rset.getInt("move_spd"));
set.set("baseWalkSpd", 0);
set.set("baseShldDef", 0);
set.set("baseShldRate", 0);
set.set("baseAtkRange", 40);
set.set("spawnX", rset.getInt("x"));
set.set("spawnY", rset.getInt("y"));
set.set("spawnZ", rset.getInt("z"));
L2PcTemplate ct;
set.set("collision_radius", rset.getDouble("m_col_r"));
set.set("collision_height", rset.getDouble("m_col_h"));
set.set("collision_radius_female", rset.getDouble("f_col_r"));
set.set("collision_height_female", rset.getDouble("f_col_h"));
ct = new L2PcTemplate(set);
// 5 items must go here
for (int x = 1; x < 6; x++)
{
if (rset.getInt("items" + x) != 0)
{
ct.addItem(rset.getInt("items" + x));
}
}
_templates.put(ct.classId.getId(), ct);
}
}
catch (final SQLException e)
{
_log.warning("error while loading char templates " + e.getMessage());
}
_log.config("CharTemplateTable: Loaded " + _templates.size() + " Character Templates.");
}
public L2PcTemplate getTemplate(ClassId classId)
{
return getTemplate(classId.getId());
}
public L2PcTemplate getTemplate(int classId)
{
return _templates.get(classId);
}
public static final String getClassNameById(int classId)
{
return charClasses[classId];
}
public static final int getClassIdByName(String className)
{
int currId = 1;
for (final String name : charClasses)
{
if (name.equalsIgnoreCase(className))
{
break;
}
currId++;
}
return currId;
}
}

View File

@@ -0,0 +1,421 @@
/*
* 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.
*
* 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.
*
* http://www.gnu.org/copyleft/gpl.html
*/
package com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;
import java.util.logging.Logger;
import com.l2jmobius.Config;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.ThreadPoolManager;
import com.l2jmobius.gameserver.idfactory.IdFactory;
import com.l2jmobius.gameserver.instancemanager.AuctionManager;
import com.l2jmobius.gameserver.instancemanager.ClanHallManager;
import com.l2jmobius.gameserver.instancemanager.SiegeManager;
import com.l2jmobius.gameserver.model.L2Clan;
import com.l2jmobius.gameserver.model.L2ClanMember;
import com.l2jmobius.gameserver.model.actor.instance.L2PcInstance;
import com.l2jmobius.gameserver.model.entity.Siege;
import com.l2jmobius.gameserver.network.serverpackets.PledgeShowInfoUpdate;
import com.l2jmobius.gameserver.network.serverpackets.PledgeShowMemberListAll;
import com.l2jmobius.gameserver.network.serverpackets.SystemMessage;
import com.l2jmobius.gameserver.network.serverpackets.UserInfo;
import com.l2jmobius.gameserver.util.Util;
import javolution.util.FastMap;
/**
* This class ...
* @version $Revision: 1.11.2.5.2.5 $ $Date: 2005/03/27 15:29:18 $
*/
public class ClanTable
{
private static Logger _log = Logger.getLogger(ClanTable.class.getName());
private static ClanTable _instance;
private final Map<Integer, L2Clan> _clans;
public static ClanTable getInstance()
{
if (_instance == null)
{
_instance = new ClanTable();
}
return _instance;
}
public L2Clan[] getClans()
{
return _clans.values().toArray(new L2Clan[_clans.size()]);
}
private ClanTable()
{
_clans = new FastMap<>();
L2Clan clan;
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT clan_id FROM clan_data");
ResultSet result = statement.executeQuery())
{
// Count the clans
int clanCount = 0;
while (result.next())
{
_clans.put(Integer.parseInt(result.getString("clan_id")), new L2Clan(Integer.parseInt(result.getString("clan_id"))));
clan = getClan(Integer.parseInt(result.getString("clan_id")));
if (clan.getDissolvingExpiryTime() != 0)
{
if (clan.getDissolvingExpiryTime() < System.currentTimeMillis())
{
destroyClan(clan.getClanId());
}
else
{
scheduleRemoveClan(clan.getClanId());
}
}
clanCount++;
}
_log.config("Restored " + clanCount + " clans from the database.");
}
catch (final Exception e)
{
_log.warning("data error on ClanTable: " + e);
e.printStackTrace();
}
}
/**
* @param clanId
* @return
*/
public L2Clan getClan(int clanId)
{
final L2Clan clan = _clans.get(new Integer(clanId));
return clan;
}
public L2Clan getClanByName(String clanName)
{
for (final L2Clan clan : getClans())
{
if (clan.getName().equalsIgnoreCase(clanName))
{
return clan;
}
}
return null;
}
public L2Clan createClan(L2PcInstance player, String clanName)
{
if (player == null)
{
return null;
}
if (Config.DEBUG)
{
_log.fine(player.getObjectId() + "(" + player.getName() + ") requested a clan creation.");
}
if (player.getLevel() < 10)
{
player.sendPacket(new SystemMessage(SystemMessage.FAILED_TO_CREATE_CLAN));
return null;
}
if (player.getClanId() != 0)
{
player.sendPacket(new SystemMessage(SystemMessage.FAILED_TO_CREATE_CLAN));
return null;
}
if (player.getClanCreateExpiryTime() > System.currentTimeMillis())
{
player.sendPacket(new SystemMessage(SystemMessage.YOU_MUST_WAIT_XX_DAYS_BEFORE_CREATING_A_NEW_CLAN));
return null;
}
if (!Util.isAlphaNumeric(clanName) || (clanName.length() < 2))
{
player.sendPacket(new SystemMessage(SystemMessage.CLAN_NAME_INCORRECT));
return null;
}
if (clanName.length() > 16)
{
player.sendPacket(new SystemMessage(SystemMessage.CLAN_NAME_TOO_LONG));
return null;
}
if (getClanByName(clanName) != null)
{
player.sendMessage("Clan name already exists.");
return null;
}
final L2ClanMember leader = new L2ClanMember(player.getName(), player.getLevel(), player.getClassId().getId(), player.getObjectId());
final L2Clan clan = new L2Clan(IdFactory.getInstance().getNextId(), clanName, leader);
leader.setPlayerInstance(player);
clan.store();
player.setClan(clan);
player.setClanPrivileges(L2Clan.CP_ALL);
if (Config.DEBUG)
{
_log.fine("New clan created: " + clan.getClanId() + " " + clan.getName());
}
_clans.put(new Integer(clan.getClanId()), clan);
// should be update packet only
player.sendPacket(new PledgeShowInfoUpdate(clan));
player.sendPacket(new PledgeShowMemberListAll(clan, player));
player.sendPacket(new UserInfo(player));
player.sendPacket(new SystemMessage(SystemMessage.CLAN_CREATED));
return clan;
}
public void destroyClan(int clanId)
{
final L2Clan clan = getClan(clanId);
if (clan == null)
{
return;
}
clan.broadcastToOnlineMembers(new SystemMessage(193));
if (AuctionManager.getInstance().getAuction(clan.getAuctionBiddedAt()) != null)
{
AuctionManager.getInstance().getAuction(clan.getAuctionBiddedAt()).cancelBid(clan.getClanId());
}
if (clan.getHasHideout() != 0)
{
ClanHallManager.getInstance().getClanHallByOwner(clan).setOwner(null);
}
final int castleId = clan.getHasCastle();
if (castleId == 0)
{
for (final Siege siege : SiegeManager.getInstance().getSieges())
{
siege.removeSiegeClan(clanId);
}
}
final L2ClanMember leaderMember = clan.getLeader();
if (leaderMember == null)
{
clan.getWarehouse().destroyAllItems("ClanRemove", null, null);
}
else
{
clan.getWarehouse().destroyAllItems("ClanRemove", clan.getLeader().getPlayerInstance(), null);
}
for (final L2ClanMember member : clan.getMembers())
{
clan.removeClanMember(member.getObjectId(), 0);
}
_clans.remove(clanId);
IdFactory.getInstance().releaseId(clanId);
try (Connection con = L2DatabaseFactory.getInstance().getConnection())
{
try (PreparedStatement statement = con.prepareStatement("UPDATE characters SET clanid = 0, clan_privs = 0 WHERE clanid=?"))
{
statement.setInt(1, clanId);
statement.execute();
}
try (PreparedStatement statement = con.prepareStatement("DELETE FROM clan_data WHERE clan_id=?"))
{
statement.setInt(1, clanId);
statement.execute();
}
try (PreparedStatement statement = con.prepareStatement("DELETE FROM clan_wars WHERE clan1=? OR clan2=?"))
{
statement.setInt(1, clanId);
statement.setInt(2, clanId);
statement.execute();
}
if (castleId != 0)
{
try (PreparedStatement statement = con.prepareStatement("UPDATE castle SET taxPercent = 0 WHERE id = ?"))
{
statement.setInt(1, castleId);
statement.execute();
}
}
}
catch (final Exception e)
{
_log.warning("could not dissolve clan:" + e);
}
}
public boolean isAllyExists(String allyName)
{
for (final L2Clan clan : getClans())
{
if ((clan.getAllyName() != null) && clan.getAllyName().equalsIgnoreCase(allyName))
{
return true;
}
}
return false;
}
public void storeclanswars(int clanId1, int clanId2)
{
final L2Clan clan1 = ClanTable.getInstance().getClan(clanId1);
final L2Clan clan2 = ClanTable.getInstance().getClan(clanId2);
clan1.setEnemyClan(clan2);
clan1.broadcastClanStatus();
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("REPLACE INTO clan_wars (clan1, clan2, wantspeace1, wantspeace2) VALUES(?,?,?,?)"))
{
statement.setInt(1, clanId1);
statement.setInt(2, clanId2);
statement.setInt(3, 0);
statement.setInt(4, 0);
statement.execute();
}
catch (final Exception e)
{
_log.warning("could not store clans wars data:" + e);
}
SystemMessage msg = new SystemMessage(1562);
msg.addString(clan2.getName());
clan1.broadcastToOnlineMembers(msg);
// clan1 declared clan war.
msg = new SystemMessage(1561);
msg.addString(clan1.getName());
clan2.broadcastToOnlineMembers(msg);
}
public void deleteclanswars(int clanId1, int clanId2)
{
final L2Clan clan1 = ClanTable.getInstance().getClan(clanId1);
final L2Clan clan2 = ClanTable.getInstance().getClan(clanId2);
clan1.deleteEnemyClan(clan2);
clan1.broadcastClanStatus();
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("DELETE FROM clan_wars WHERE clan1=? AND clan2=?"))
{
statement.setInt(1, clanId1);
statement.setInt(2, clanId2);
statement.execute();
}
catch (final Exception e)
{
_log.warning("could not restore clans wars data:" + e);
}
SystemMessage msg = new SystemMessage(1567);
msg.addString(clan2.getName());
clan1.broadcastToOnlineMembers(msg);
msg = new SystemMessage(1566);
msg.addString(clan1.getName());
clan2.broadcastToOnlineMembers(msg);
}
public void CheckSurrender(L2Clan clan1, L2Clan clan2)
{
int count = 0;
for (final L2ClanMember player : clan1.getMembers())
{
if ((player != null) && (player.getPlayerInstance().getWantsPeace() == 1))
{
count++;
}
}
if (count == (clan1.getMembers().length - 1))
{
clan1.deleteEnemyClan(clan2);
clan2.deleteEnemyClan(clan1);
deleteclanswars(clan1.getClanId(), clan2.getClanId());
}
}
public void scheduleRemoveClan(final int clanId)
{
ThreadPoolManager.getInstance().scheduleGeneral(() ->
{
if (getClan(clanId) == null)
{
return;
}
if (getClan(clanId).getDissolvingExpiryTime() != 0)
{
destroyClan(clanId);
}
}, getClan(clanId).getDissolvingExpiryTime() - System.currentTimeMillis());
}
}

View File

@@ -0,0 +1,378 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import com.l2jmobius.Config;
import com.l2jmobius.gameserver.idfactory.IdFactory;
import com.l2jmobius.gameserver.instancemanager.ClanHallManager;
import com.l2jmobius.gameserver.model.actor.instance.L2DoorInstance;
import com.l2jmobius.gameserver.model.entity.ClanHall;
import com.l2jmobius.gameserver.pathfinding.AbstractNodeLoc;
import com.l2jmobius.gameserver.templates.L2CharTemplate;
import com.l2jmobius.gameserver.templates.StatsSet;
import javolution.util.FastMap;
public class DoorTable
{
private static Logger _log = Logger.getLogger(DoorTable.class.getName());
private Map<Integer, L2DoorInstance> _staticItems;
private static DoorTable _instance;
public static DoorTable getInstance()
{
if (_instance == null)
{
_instance = new DoorTable();
}
return _instance;
}
public DoorTable()
{
_staticItems = new FastMap<>();
}
public void reloadAll()
{
respawn();
}
public void respawn()
{
_staticItems = null;
_instance = null;
_instance = new DoorTable();
}
public void parseData()
{
final File doorData = new File(Config.DATAPACK_ROOT, "data/door.csv");
try (FileReader fr = new FileReader(doorData);
BufferedReader br = new BufferedReader(fr);
LineNumberReader lnr = new LineNumberReader(br))
{
String line = null;
_log.warning("Searching clan halls doors:");
while ((line = lnr.readLine()) != null)
{
if ((line.trim().length() == 0) || line.startsWith("#"))
{
continue;
}
final L2DoorInstance door = parseList(line);
putDoor(door);
door.spawnMe(door.getX(), door.getY(), door.getZ());
final ClanHall clanhall = ClanHallManager.getInstance().getNearbyClanHall(door.getX(), door.getY(), 500);
if (clanhall != null)
{
clanhall.getDoors().add(door);
door.setClanHall(clanhall);
if (Config.DEBUG)
{
_log.warning("door " + door.getDoorName() + " attached to ch " + clanhall.getName());
}
}
}
_log.config("DoorTable: Loaded " + _staticItems.size() + " Door Templates.");
}
catch (final FileNotFoundException e)
{
_initialized = false;
_log.warning("door.csv is missing in data folder");
}
catch (final IOException e)
{
_initialized = false;
_log.warning("error while creating door table " + e);
}
}
public static L2DoorInstance parseList(String line)
{
final StringTokenizer st = new StringTokenizer(line, ";");
final String name = st.nextToken();
final int id = Integer.parseInt(st.nextToken());
final int x = Integer.parseInt(st.nextToken());
final int y = Integer.parseInt(st.nextToken());
final int z = Integer.parseInt(st.nextToken());
final int rangeXMin = Integer.parseInt(st.nextToken());
final int rangeYMin = Integer.parseInt(st.nextToken());
final int rangeZMin = Integer.parseInt(st.nextToken());
final int rangeXMax = Integer.parseInt(st.nextToken());
final int rangeYMax = Integer.parseInt(st.nextToken());
final int rangeZMax = Integer.parseInt(st.nextToken());
final int hp = Integer.parseInt(st.nextToken());
final int pdef = Integer.parseInt(st.nextToken());
final int mdef = Integer.parseInt(st.nextToken());
boolean unlockable = false;
if (st.hasMoreTokens())
{
unlockable = Boolean.parseBoolean(st.nextToken());
}
if (rangeXMin > rangeXMax)
{
_log.severe("Error in door data, XMin > XMax, ID:" + id);
}
if (rangeYMin > rangeYMax)
{
_log.severe("Error in door data, YMin > YMax, ID:" + id);
}
if (rangeZMin > rangeZMax)
{
_log.severe("Error in door data, ZMin > ZMax, ID:" + id);
}
int collisionRadius; // (max) radius for movement checks
if ((rangeXMax - rangeXMin) > (rangeYMax - rangeYMin))
{
collisionRadius = rangeYMax - rangeYMin;
}
else
{
collisionRadius = rangeXMax - rangeXMin;
}
final StatsSet npcDat = new StatsSet();
npcDat.set("npcId", id);
npcDat.set("level", 0);
npcDat.set("jClass", "door");
npcDat.set("baseSTR", 0);
npcDat.set("baseCON", 0);
npcDat.set("baseDEX", 0);
npcDat.set("baseINT", 0);
npcDat.set("baseWIT", 0);
npcDat.set("baseMEN", 0);
npcDat.set("baseShldDef", 0);
npcDat.set("baseShldRate", 0);
npcDat.set("baseAccCombat", 38);
npcDat.set("baseEvasRate", 38);
npcDat.set("baseCritRate", 38);
npcDat.set("collision_radius", collisionRadius);
npcDat.set("collision_height", rangeZMax - rangeZMin);
npcDat.set("sex", "male");
npcDat.set("type", "");
npcDat.set("baseAtkRange", 0);
npcDat.set("baseMpMax", 0);
npcDat.set("baseCpMax", 0);
npcDat.set("rewardExp", 0);
npcDat.set("rewardSp", 0);
npcDat.set("basePAtk", 0);
npcDat.set("baseMAtk", 0);
npcDat.set("basePAtkSpd", 0);
npcDat.set("aggroRange", 0);
npcDat.set("baseMAtkSpd", 0);
npcDat.set("rhand", 0);
npcDat.set("lhand", 0);
npcDat.set("armor", 0);
npcDat.set("baseWalkSpd", 0);
npcDat.set("baseRunSpd", 0);
npcDat.set("name", name);
npcDat.set("baseHpMax", hp);
npcDat.set("baseHpReg", 3.e-3f);
npcDat.set("baseMpReg", 3.e-3f);
npcDat.set("basePDef", pdef);
npcDat.set("baseMDef", mdef);
final L2CharTemplate template = new L2CharTemplate(npcDat);
final L2DoorInstance door = new L2DoorInstance(IdFactory.getInstance().getNextId(), template, id, name, unlockable);
door.setRange(rangeXMin, rangeYMin, rangeZMin, rangeXMax, rangeYMax, rangeZMax);
try
{
door.setMapRegion(MapRegionTable.getInstance().getMapRegion(x, y));
}
catch (final Exception e)
{
_log.severe("Error in door data, ID:" + id);
}
door.setCurrentHpMp(door.getMaxHp(), door.getMaxMp());
door.setOpen(1);
door.setXYZInvisible(x, y, z);
door.setMapRegion(MapRegionTable.getInstance().getMapRegion(x, y));
return door;
}
private boolean _initialized = true;
public boolean isInitialized()
{
return _initialized;
}
public L2DoorInstance getDoor(Integer id)
{
return _staticItems.get(id);
}
public void putDoor(L2DoorInstance door)
{
_staticItems.put(door.getDoorId(), door);
}
public L2DoorInstance[] getDoors()
{
final L2DoorInstance[] _allTemplates = _staticItems.values().toArray(new L2DoorInstance[_staticItems.size()]);
return _allTemplates;
}
/**
* Performs a check and sets up a scheduled task for those doors that require auto opening/closing.
*/
public void checkAutoOpen()
{
for (final L2DoorInstance doorInst : getDoors())
{
if (doorInst.isUnlockable())
{
continue;
}
// Garden of Eva (every 7 minutes)
if (doorInst.getDoorName().startsWith("goe"))
{
doorInst.setAutoActionDelay(420000);
}
else if (doorInst.getDoorName().startsWith("aden_tower"))
{
doorInst.setAutoActionDelay(300000);
}
else if (doorInst.getDoorName().startsWith("pirate_isle"))
{
doorInst.setAutoActionDelay(300000);
}
else if (doorInst.getDoorName().startsWith("cruma"))
{
doorInst.setAutoActionDelay(1200000);
}
}
}
public boolean checkIfDoorsBetween(AbstractNodeLoc start, AbstractNodeLoc end)
{
return checkIfDoorsBetween(start.getX(), start.getY(), start.getZ(), end.getX(), end.getY(), end.getZ());
}
public boolean checkIfDoorsBetween(int x, int y, int z, int tx, int ty, int tz)
{
int region;
try
{
region = MapRegionTable.getInstance().getMapRegion(x, y);
}
catch (final Exception e)
{
return false;
}
// there are quite many doors, maybe they should be splitted
for (final L2DoorInstance doorInst : getDoors())
{
if (doorInst.getMapRegion() != region)
{
continue;
}
if (doorInst.getXMax() == 0)
{
continue;
}
// line segment goes through box
// first basic checks to stop most calculations short
// phase 1, x
if (((x <= doorInst.getXMax()) && (tx >= doorInst.getXMin())) || ((tx <= doorInst.getXMax()) && (x >= doorInst.getXMin())))
{
// phase 2, y
if (((y <= doorInst.getYMax()) && (ty >= doorInst.getYMin())) || ((ty <= doorInst.getYMax()) && (y >= doorInst.getYMin())))
{
// phase 3, basically only z remains but now we calculate it with another formula (by rage)
// in some cases the direct line check (only) in the beginning isn't sufficient,
// when char z changes a lot along the path
if ((doorInst.getCurrentHp() > 0) && (doorInst.getOpen() != 0))
{
final int px1 = doorInst.getXMin();
final int py1 = doorInst.getYMin();
final int pz1 = doorInst.getZMin();
final int px2 = doorInst.getXMax();
final int py2 = doorInst.getYMax();
final int pz2 = doorInst.getZMax();
final int l = tx - x;
final int m = ty - y;
final int n = tz - z;
int dk;
if ((dk = ((doorInst.getA() * l) + (doorInst.getB() * m) + (doorInst.getC() * n))) == 0)
{
continue; // Parallel
}
final float p = (float) ((doorInst.getA() * x) + (doorInst.getB() * y) + (doorInst.getC() * z) + doorInst.getD()) / (float) dk;
final int fx = (int) (x - (l * p));
final int fy = (int) (y - (m * p));
final int fz = (int) (z - (n * p));
if (((Math.min(x, tx) <= fx) && (fx <= Math.max(x, tx))) && ((Math.min(y, ty) <= fy) && (fy <= Math.max(y, ty))) && ((Math.min(z, tz) <= fz) && (fz <= Math.max(z, tz))))
{
if ((((fx >= px1) && (fx <= px2)) || ((fx >= px2) && (fx <= px1))) && (((fy >= py1) && (fy <= py2)) || ((fy >= py2) && (fy <= py1))) && (((fz >= pz1) && (fz <= pz2)) || ((fz >= pz2) && (fz <= pz1))))
{
return true; // Door between
}
}
}
}
}
}
return false;
}
}

View File

@@ -0,0 +1,179 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.io.File;
import java.util.Scanner;
import com.l2jmobius.Config;
import com.l2jmobius.gameserver.model.L2ExtractableItem;
import com.l2jmobius.gameserver.model.L2ExtractableProductItem;
import javolution.util.FastList;
import javolution.util.FastMap;
/**
* @author FBIagent
*/
public class ExtractableItemsData
{
private final FastMap<Integer, L2ExtractableItem> _items;
private static ExtractableItemsData _instance = null;
public static ExtractableItemsData getInstance()
{
if (_instance == null)
{
_instance = new ExtractableItemsData();
}
return _instance;
}
public ExtractableItemsData()
{
_items = new FastMap<>();
try (Scanner s = new Scanner(new File(Config.DATAPACK_ROOT + "/data/extractable_items.csv")))
{
int lineCount = 0;
while (s.hasNextLine())
{
lineCount++;
final String line = s.nextLine();
if (line.startsWith("#"))
{
continue;
}
if (line.isEmpty())
{
continue;
}
final String[] lineSplit = line.split(";");
boolean ok = true;
int itemID = 0;
try
{
itemID = Integer.parseInt(lineSplit[0]);
}
catch (final Exception e)
{
System.out.println("Extractable items data: Error in line " + lineCount + " -> invalid item id or wrong seperator after item id!");
System.out.println(" " + line);
ok = false;
}
if (!ok)
{
continue;
}
final FastList<L2ExtractableProductItem> product_temp = new FastList<>();
for (int i = 0; i < (lineSplit.length - 1); i++)
{
ok = true;
final String[] lineSplit2 = lineSplit[i + 1].split(",");
if (lineSplit2.length != 3)
{
System.out.println("Extractable items data: Error in line " + lineCount + " -> wrong seperator!");
System.out.println(" " + line);
ok = false;
}
if (!ok)
{
continue;
}
int production = 0, amount = 0, chance = 0;
try
{
production = Integer.parseInt(lineSplit2[0]);
amount = Integer.parseInt(lineSplit2[1]);
chance = Integer.parseInt(lineSplit2[2]);
}
catch (final Exception e)
{
System.out.println("Extractable items data: Error in line " + lineCount + " -> incomplete/invalid production data or wrong seperator!");
System.out.println(" " + line);
ok = false;
}
if (!ok)
{
continue;
}
final L2ExtractableProductItem product = new L2ExtractableProductItem(production, amount, chance);
product_temp.add(product);
}
int fullChances = 0;
for (final L2ExtractableProductItem Pi : product_temp)
{
fullChances += Pi.getChance();
}
if (fullChances > 100)
{
System.out.println("Extractable items data: Error in line " + lineCount + " -> all chances together are more then 100!");
System.out.println(" " + line);
continue;
}
final L2ExtractableItem product = new L2ExtractableItem(itemID, product_temp);
_items.put(itemID, product);
}
System.out.println("Extractable items data: Loaded " + _items.size() + " extractable items!");
}
catch (final Exception e)
{
System.out.println("Extractable items data: Cannot find '" + Config.DATAPACK_ROOT + "/data/extractable_items.csv'");
}
}
public L2ExtractableItem getExtractableItem(int itemID)
{
return _items.get(itemID);
}
public int[] itemIDs()
{
final int size = _items.size();
final int[] result = new int[size];
int i = 0;
for (final L2ExtractableItem ei : _items.values())
{
result[i] = ei.getItemId();
i++;
}
return result;
}
}

View File

@@ -0,0 +1,142 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.model.FishData;
import javolution.util.FastList;
/**
* @author -Nemesiss-
*/
public class FishTable
{
private static Logger _log = Logger.getLogger(SkillTreeTable.class.getName());
private static final FishTable _instance = new FishTable();
private static List<FishData> _Fishs;
private static List<FishData> _Fishs_Newbie;
public static FishTable getInstance()
{
return _instance;
}
private FishTable()
{
// Create table that contains all fish data
int count = 0;
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT id, level, name, hp, hpregen, fish_type, fish_group, fish_guts, guts_check_time, wait_time, combat_time FROM fish ORDER BY id");
ResultSet Fishes = statement.executeQuery())
{
_Fishs_Newbie = new FastList<>();
_Fishs = new FastList<>();
FishData fish;
while (Fishes.next())
{
final int id = Fishes.getInt("id");
final int lvl = Fishes.getInt("level");
final String name = Fishes.getString("name");
final int hp = Fishes.getInt("hp");
final int hpreg = Fishes.getInt("hpregen");
final int type = Fishes.getInt("fish_type");
final int group = Fishes.getInt("fish_group");
final int fish_guts = Fishes.getInt("fish_guts");
final int guts_check_time = Fishes.getInt("guts_check_time");
final int wait_time = Fishes.getInt("wait_time");
final int combat_time = Fishes.getInt("combat_time");
fish = new FishData(id, lvl, name, hp, hpreg, type, group, fish_guts, guts_check_time, wait_time, combat_time);
if (fish.getGroup() == 0)
{
_Fishs_Newbie.add(fish);
}
else
{
_Fishs.add(fish);
}
}
count = _Fishs_Newbie.size() + _Fishs.size();
}
catch (final Exception e)
{
_log.log(Level.SEVERE, "error while creating fishes table" + e);
}
_log.config("FishTable: Loaded " + count + " Fishes.");
}
/**
* @param lvl
* @param type
* @param group
* @return List of Fish that can be fished
*/
public List<FishData> getfish(int lvl, int type, int group)
{
final List<FishData> result = new FastList<>();
List<FishData> _Fishing = null;
if (group == 0)
{
_Fishing = _Fishs_Newbie;
}
else
{
_Fishing = _Fishs;
}
if ((_Fishing == null) || _Fishing.isEmpty())
{
// the fish list is empty
_log.warning("Fish are not defined!");
return null;
}
for (final FishData f : _Fishing)
{
if (f.getLevel() != lvl)
{
continue;
}
if (f.getType() != type)
{
continue;
}
result.add(f);
}
if (result.size() == 0)
{
_log.warning("Cant Find Any Fish!? - Lvl: " + lvl + " Type: " + type);
}
return result;
}
}

View File

@@ -0,0 +1,184 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.util.logging.Logger;
import com.l2jmobius.Config;
import com.l2jmobius.gameserver.model.actor.instance.L2PcInstance;
import com.l2jmobius.gameserver.network.serverpackets.L2GameServerPacket;
import com.l2jmobius.gameserver.network.serverpackets.SystemMessage;
import javolution.util.FastList;
import javolution.util.FastMap;
/**
* This class stores references to all online game masters. (access level > 100)
* @version $Revision: 1.2.2.1.2.7 $ $Date: 2005/04/05 19:41:24 $
*/
public class GmListTable
{
private static Logger _log = Logger.getLogger(GmListTable.class.getName());
private static GmListTable _instance;
/** List(L2PcInstance>) containing all the GM in game */
private final FastMap<L2PcInstance, Boolean> _gmList;
public static GmListTable getInstance()
{
if (_instance == null)
{
_instance = new GmListTable();
}
return _instance;
}
public FastList<L2PcInstance> getAllGms(boolean includeHidden)
{
final FastList<L2PcInstance> tmpGmList = new FastList<>();
for (FastMap.Entry<L2PcInstance, Boolean> n = _gmList.head(), end = _gmList.tail(); (n = n.getNext()) != end;)
{
if (includeHidden || !n.getValue())
{
tmpGmList.add(n.getKey());
}
}
return tmpGmList;
}
public FastList<String> getAllGmNames(boolean includeHidden)
{
final FastList<String> tmpGmList = new FastList<>();
for (FastMap.Entry<L2PcInstance, Boolean> n = _gmList.head(), end = _gmList.tail(); (n = n.getNext()) != end;)
{
if (!n.getValue())
{
tmpGmList.add(n.getKey().getName());
}
else if (includeHidden)
{
tmpGmList.add(n.getKey().getName() + " (invis)");
}
}
return tmpGmList;
}
private GmListTable()
{
_gmList = new FastMap<L2PcInstance, Boolean>().shared();
}
/**
* Add a L2PcInstance player to the Set _gmList
* @param player
* @param hidden
*/
public void addGm(L2PcInstance player, boolean hidden)
{
if (Config.DEBUG)
{
_log.fine("added gm: " + player.getName());
}
_gmList.put(player, hidden);
}
public void deleteGm(L2PcInstance player)
{
if (Config.DEBUG)
{
_log.fine("deleted gm: " + player.getName());
}
_gmList.remove(player);
}
/**
* GM will be displayed on clients gmlist
* @param player
*/
public void showGm(L2PcInstance player)
{
final FastMap.Entry<L2PcInstance, Boolean> gm = _gmList.getEntry(player);
if (gm != null)
{
gm.setValue(false);
}
}
/**
* GM will no longer be displayed on clients gmlist
* @param player
*/
public void hideGm(L2PcInstance player)
{
final FastMap.Entry<L2PcInstance, Boolean> gm = _gmList.getEntry(player);
if (gm != null)
{
gm.setValue(true);
}
}
public boolean isGmOnline(boolean includeHidden)
{
for (FastMap.Entry<L2PcInstance, Boolean> n = _gmList.head(), end = _gmList.tail(); (n = n.getNext()) != end;)
{
if (includeHidden || !n.getValue())
{
return true;
}
}
return false;
}
public void sendListToPlayer(L2PcInstance player)
{
if (!isGmOnline(player.isGM()))
{
player.sendPacket(new SystemMessage(SystemMessage.NO_GM_PROVIDING_SERVICE_NOW)); // There are not any GMs that are providing customer service currently.
}
else
{
SystemMessage sm = new SystemMessage(SystemMessage.GM_LIST);
player.sendPacket(sm);
for (final String name : getAllGmNames(player.isGM()))
{
sm = new SystemMessage(SystemMessage.GM_S1);
sm.addString(name);
player.sendPacket(sm);
}
}
}
public static void broadcastToGMs(L2GameServerPacket packet)
{
for (final L2PcInstance gm : getInstance().getAllGms(true))
{
gm.sendPacket(packet);
}
}
public static void broadcastMessageToGMs(String message)
{
for (final L2PcInstance gm : getInstance().getAllGms(true))
{
gm.sendPacket(SystemMessage.sendString(message));
}
}
}

View File

@@ -0,0 +1,230 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.logging.Logger;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.templates.L2HelperBuff;
import com.l2jmobius.gameserver.templates.StatsSet;
import javolution.util.FastList;
/**
* This class represents the Newbie Helper Buff list Author: Ayor
*/
public class HelperBuffTable
{
private static Logger _log = Logger.getLogger(HennaTable.class.getName());
private static HelperBuffTable _instance;
/** The table containing all Buff of the Newbie Helper */
private final List<L2HelperBuff> _helperBuff;
private final boolean _initialized = true;
/**
* The player level since Newbie Helper can give the fisrt buff <BR>
* Used to generate message : "Come back here when you have reached level ...")
*/
private int _magicClassLowestLevel = 100;
private int _physicClassLowestLevel = 100;
/**
* The player level above which Newbie Helper won't give any buff <BR>
* Used to generate message : "Only novice character of level ... or less can receive my support magic.")
*/
private int _magicClassHighestLevel = 1;
private int _physicClassHighestLevel = 1;
public static HelperBuffTable getInstance()
{
if (_instance == null)
{
_instance = new HelperBuffTable();
}
return _instance;
}
/**
* Create and Load the Newbie Helper Buff list from SQL Table helper_buff_list
*/
private HelperBuffTable()
{
_helperBuff = new FastList<>();
RestoreHelperBuffData();
}
/**
* Read and Load the Newbie Helper Buff list from SQL Table helper_buff_list
*/
private void RestoreHelperBuffData()
{
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT * FROM helper_buff_list");
ResultSet helperbuffdata = statement.executeQuery())
{
fillHelperBuffTable(helperbuffdata);
}
catch (final Exception e)
{
_log.severe("Table helper_buff_list not found : Update your DataPack" + e);
e.printStackTrace();
}
}
/**
* Load the Newbie Helper Buff list from SQL Table helper_buff_list
* @param HelperBuffData
* @throws Exception
*/
private void fillHelperBuffTable(ResultSet HelperBuffData) throws Exception
{
while (HelperBuffData.next())
{
final StatsSet helperBuffDat = new StatsSet();
final int id = HelperBuffData.getInt("id");
helperBuffDat.set("id", id);
helperBuffDat.set("skillID", HelperBuffData.getInt("skill_id"));
helperBuffDat.set("skillLevel", HelperBuffData.getInt("skill_level"));
helperBuffDat.set("lowerLevel", HelperBuffData.getInt("lower_level"));
helperBuffDat.set("upperLevel", HelperBuffData.getInt("upper_level"));
helperBuffDat.set("isMagicClass", HelperBuffData.getString("is_magic_class"));
// Calulate the range level in wich player must be to obtain buff from Newbie Helper
if ("false".equals(HelperBuffData.getString("is_magic_class")))
{
if (HelperBuffData.getInt("lower_level") < _physicClassLowestLevel)
{
_physicClassLowestLevel = HelperBuffData.getInt("lower_level");
}
if (HelperBuffData.getInt("upper_level") > _physicClassHighestLevel)
{
_physicClassHighestLevel = HelperBuffData.getInt("upper_level");
}
}
else
{
if (HelperBuffData.getInt("lower_level") < _magicClassLowestLevel)
{
_magicClassLowestLevel = HelperBuffData.getInt("lower_level");
}
if (HelperBuffData.getInt("upper_level") > _magicClassHighestLevel)
{
_magicClassHighestLevel = HelperBuffData.getInt("upper_level");
}
}
// Add this Helper Buff to the Helper Buff List
final L2HelperBuff template = new L2HelperBuff(helperBuffDat);
_helperBuff.add(template);
}
_log.config("Helper Buff Table: Loaded " + _helperBuff.size() + " Templates.");
}
public boolean isInitialized()
{
return _initialized;
}
public L2HelperBuff getHelperBuffTableItem(int id)
{
return _helperBuff.get(id);
}
/**
* Return the Helper Buff List
* @return
*/
public List<L2HelperBuff> getHelperBuffTable()
{
return _helperBuff;
}
/**
* @return Returns the magicClassHighestLevel.
*/
public int getMagicClassHighestLevel()
{
return _magicClassHighestLevel;
}
/**
* @param magicClassHighestLevel The magicClassHighestLevel to set.
*/
public void setMagicClassHighestLevel(int magicClassHighestLevel)
{
_magicClassHighestLevel = magicClassHighestLevel;
}
/**
* @return Returns the magicClassLowestLevel.
*/
public int getMagicClassLowestLevel()
{
return _magicClassLowestLevel;
}
/**
* @param magicClassLowestLevel The magicClassLowestLevel to set.
*/
public void setMagicClassLowestLevel(int magicClassLowestLevel)
{
_magicClassLowestLevel = magicClassLowestLevel;
}
/**
* @return Returns the physicClassHighestLevel.
*/
public int getPhysicClassHighestLevel()
{
return _physicClassHighestLevel;
}
/**
* @param physicClassHighestLevel The physicClassHighestLevel to set.
*/
public void setPhysicClassHighestLevel(int physicClassHighestLevel)
{
_physicClassHighestLevel = physicClassHighestLevel;
}
/**
* @return Returns the physicClassLowestLevel.
*/
public int getPhysicClassLowestLevel()
{
return _physicClassLowestLevel;
}
/**
* @param physicClassLowestLevel The physicClassLowestLevel to set.
*/
public void setPhysicClassLowestLevel(int physicClassLowestLevel)
{
_physicClassLowestLevel = physicClassLowestLevel;
}
}

View File

@@ -0,0 +1,112 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;
import java.util.logging.Logger;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.templates.L2Henna;
import com.l2jmobius.gameserver.templates.StatsSet;
import javolution.util.FastMap;
/**
* This class ...
* @version $Revision$ $Date$
*/
public class HennaTable
{
private static Logger _log = Logger.getLogger(HennaTable.class.getName());
private static HennaTable _instance;
private final Map<Integer, L2Henna> _henna;
private final boolean _initialized = true;
public static HennaTable getInstance()
{
if (_instance == null)
{
_instance = new HennaTable();
}
return _instance;
}
private HennaTable()
{
_henna = new FastMap<>();
RestoreHennaData();
}
/**
*
*/
private void RestoreHennaData()
{
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT symbol_id, symbol_name, dye_id, dye_amount, price, stat_INT, stat_STR, stat_CON, stat_MEN, stat_DEX, stat_WIT FROM henna");
ResultSet hennadata = statement.executeQuery())
{
fillHennaTable(hennadata);
}
catch (final Exception e)
{
_log.severe("error while creating henna table " + e);
e.printStackTrace();
}
}
private void fillHennaTable(ResultSet HennaData) throws Exception
{
while (HennaData.next())
{
final StatsSet hennaDat = new StatsSet();
final int id = HennaData.getInt("symbol_id");
hennaDat.set("symbol_id", id);
// hennaDat.set("symbol_name", HennaData.getString("symbol_name"));
hennaDat.set("dye", HennaData.getInt("dye_id"));
hennaDat.set("price", HennaData.getInt("price"));
// amount of dye required
hennaDat.set("amount", HennaData.getInt("dye_amount"));
hennaDat.set("stat_INT", HennaData.getInt("stat_INT"));
hennaDat.set("stat_STR", HennaData.getInt("stat_STR"));
hennaDat.set("stat_CON", HennaData.getInt("stat_CON"));
hennaDat.set("stat_MEN", HennaData.getInt("stat_MEN"));
hennaDat.set("stat_DEX", HennaData.getInt("stat_DEX"));
hennaDat.set("stat_WIT", HennaData.getInt("stat_WIT"));
final L2Henna template = new L2Henna(hennaDat);
_henna.put(id, template);
}
_log.config("HennaTable: Loaded " + _henna.size() + " Templates.");
}
public boolean isInitialized()
{
return _initialized;
}
public L2Henna getTemplate(int id)
{
return _henna.get(id);
}
}

View File

@@ -0,0 +1,136 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.model.L2HennaInstance;
import com.l2jmobius.gameserver.model.base.ClassId;
import com.l2jmobius.gameserver.templates.L2Henna;
import javolution.util.FastList;
import javolution.util.FastMap;
/**
* This class ...
* @version $Revision$ $Date$
*/
public class HennaTreeTable
{
private static Logger _log = Logger.getLogger(HennaTreeTable.class.getName());
private static final HennaTreeTable _instance = new HennaTreeTable();
private final Map<ClassId, List<L2HennaInstance>> _hennaTrees;
private final boolean _initialized = true;
public static HennaTreeTable getInstance()
{
return _instance;
}
private HennaTreeTable()
{
_hennaTrees = new FastMap<>();
int classId = 0;
int count = 0;
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT class_name, id, parent_id FROM class_list ORDER BY id");
ResultSet classlist = statement.executeQuery())
{
List<L2HennaInstance> list;
while (classlist.next())
{
list = new FastList<>();
classId = classlist.getInt("id");
try (PreparedStatement statement2 = con.prepareStatement("SELECT class_id, symbol_id FROM henna_trees where class_id=? ORDER BY symbol_id"))
{
statement2.setInt(1, classId);
try (ResultSet hennatree = statement2.executeQuery())
{
while (hennatree.next())
{
final int id = hennatree.getInt("symbol_id");
final L2Henna template = HennaTable.getInstance().getTemplate(id);
if (template == null)
{
continue;
}
final L2HennaInstance temp = new L2HennaInstance(template);
temp.setSymbolId(id);
temp.setItemIdDye(template.getDyeId());
temp.setAmountDyeRequire(template.getAmountDyeRequire());
temp.setPrice(template.getPrice());
temp.setStatINT(template.getStatINT());
temp.setStatSTR(template.getStatSTR());
temp.setStatCON(template.getStatCON());
temp.setStatMEN(template.getStatMEN());
temp.setStatDEX(template.getStatDEX());
temp.setStatWIT(template.getStatWIT());
list.add(temp);
}
}
}
_hennaTrees.put(ClassId.values()[classId], list);
count += list.size();
_log.fine("Henna Tree for Class: " + classId + " has " + list.size() + " Henna Templates.");
}
}
catch (final Exception e)
{
_log.warning("error while creating henna tree for classId " + classId + " " + e);
e.printStackTrace();
}
_log.config("HennaTreeTable: Loaded " + count + " Henna Tree Templates.");
}
public L2HennaInstance[] getAvailableHenna(ClassId classId)
{
final List<L2HennaInstance> result = new FastList<>();
final List<L2HennaInstance> henna = _hennaTrees.get(classId);
if (henna == null)
{
// the hennatree for this class is undefined, so we give an empty list
_log.warning("Hennatree for class " + classId + " is not defined!");
return new L2HennaInstance[0];
}
for (int i = 0; i < henna.size(); i++)
{
final L2HennaInstance temp = henna.get(i);
result.add(temp);
}
return result.toArray(new L2HennaInstance[result.size()]);
}
public boolean isInitialized()
{
return _initialized;
}
}

View File

@@ -0,0 +1,878 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import com.l2jmobius.Config;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.Item;
import com.l2jmobius.gameserver.ThreadPoolManager;
import com.l2jmobius.gameserver.idfactory.IdFactory;
import com.l2jmobius.gameserver.model.L2Attackable;
import com.l2jmobius.gameserver.model.L2ItemInstance;
import com.l2jmobius.gameserver.model.L2ItemInstance.ItemLocation;
import com.l2jmobius.gameserver.model.L2Object;
import com.l2jmobius.gameserver.model.L2PetDataTable;
import com.l2jmobius.gameserver.model.L2World;
import com.l2jmobius.gameserver.model.actor.instance.L2PcInstance;
import com.l2jmobius.gameserver.skills.SkillsEngine;
import com.l2jmobius.gameserver.templates.L2Armor;
import com.l2jmobius.gameserver.templates.L2ArmorType;
import com.l2jmobius.gameserver.templates.L2EtcItem;
import com.l2jmobius.gameserver.templates.L2EtcItemType;
import com.l2jmobius.gameserver.templates.L2Item;
import com.l2jmobius.gameserver.templates.L2Weapon;
import com.l2jmobius.gameserver.templates.L2WeaponType;
import com.l2jmobius.gameserver.templates.StatsSet;
import javolution.util.FastMap;
/**
* This class ...
* @version $Revision: 1.9.2.6.2.9 $ $Date: 2005/04/02 15:57:34 $
*/
public class ItemTable
{
private static Logger _log = Logger.getLogger(ItemTable.class.getName());
private static Logger _logItems = Logger.getLogger("item");
private static final Map<String, Integer> _materials = new FastMap<>();
private static final Map<String, Integer> _crystalTypes = new FastMap<>();
private static final Map<String, L2WeaponType> _weaponTypes = new FastMap<>();
private static final Map<String, L2ArmorType> _armorTypes = new FastMap<>();
private static final Map<String, Integer> _slots = new FastMap<>();
private L2Item[] _allTemplates;
private final Map<Integer, L2EtcItem> _etcItems;
private final Map<Integer, L2Armor> _armors;
private final Map<Integer, L2Weapon> _weapons;
private final boolean _initialized = true;
static
{
_materials.put("paper", L2Item.MATERIAL_PAPER);
_materials.put("wood", L2Item.MATERIAL_WOOD);
_materials.put("liquid", L2Item.MATERIAL_LIQUID);
_materials.put("cloth", L2Item.MATERIAL_CLOTH);
_materials.put("leather", L2Item.MATERIAL_LEATHER);
_materials.put("horn", L2Item.MATERIAL_HORN);
_materials.put("bone", L2Item.MATERIAL_BONE);
_materials.put("bronze", L2Item.MATERIAL_BRONZE);
_materials.put("fine_steel", L2Item.MATERIAL_FINE_STEEL);
_materials.put("cotton", L2Item.MATERIAL_FINE_STEEL);
_materials.put("mithril", L2Item.MATERIAL_MITHRIL);
_materials.put("silver", L2Item.MATERIAL_SILVER);
_materials.put("gold", L2Item.MATERIAL_GOLD);
_materials.put("adamantaite", L2Item.MATERIAL_ADAMANTAITE);
_materials.put("steel", L2Item.MATERIAL_STEEL);
_materials.put("oriharukon", L2Item.MATERIAL_ORIHARUKON);
_materials.put("blood_steel", L2Item.MATERIAL_BLOOD_STEEL);
_materials.put("crystal", L2Item.MATERIAL_CRYSTAL);
_materials.put("damascus", L2Item.MATERIAL_DAMASCUS);
_materials.put("chrysolite", L2Item.MATERIAL_CHRYSOLITE);
_materials.put("scale_of_dragon", L2Item.MATERIAL_SCALE_OF_DRAGON);
_materials.put("dyestuff", L2Item.MATERIAL_DYESTUFF);
_materials.put("cobweb", L2Item.MATERIAL_COBWEB);
_materials.put("seed", L2Item.MATERIAL_SEED);
_crystalTypes.put("s", L2Item.CRYSTAL_S);
_crystalTypes.put("a", L2Item.CRYSTAL_A);
_crystalTypes.put("b", L2Item.CRYSTAL_B);
_crystalTypes.put("c", L2Item.CRYSTAL_C);
_crystalTypes.put("d", L2Item.CRYSTAL_D);
_crystalTypes.put("none", L2Item.CRYSTAL_NONE);
_weaponTypes.put("blunt", L2WeaponType.BLUNT);
_weaponTypes.put("bow", L2WeaponType.BOW);
_weaponTypes.put("dagger", L2WeaponType.DAGGER);
_weaponTypes.put("dual", L2WeaponType.DUAL);
_weaponTypes.put("dualfist", L2WeaponType.DUALFIST);
_weaponTypes.put("etc", L2WeaponType.ETC);
_weaponTypes.put("fist", L2WeaponType.FIST);
_weaponTypes.put("none", L2WeaponType.NONE); // these are shields !
_weaponTypes.put("pole", L2WeaponType.POLE);
_weaponTypes.put("sword", L2WeaponType.SWORD);
_weaponTypes.put("bigsword", L2WeaponType.BIGSWORD); // Two-Handed Swords
_weaponTypes.put("pet", L2WeaponType.PET); // Pet Weapon
_weaponTypes.put("rod", L2WeaponType.ROD); // Fishing Rods
_weaponTypes.put("bigblunt", L2WeaponType.BIGBLUNT); // Two handed blunt
_armorTypes.put("none", L2ArmorType.NONE);
_armorTypes.put("light", L2ArmorType.LIGHT);
_armorTypes.put("heavy", L2ArmorType.HEAVY);
_armorTypes.put("magic", L2ArmorType.MAGIC);
_armorTypes.put("pet", L2ArmorType.PET);
_slots.put("chest", L2Item.SLOT_CHEST);
_slots.put("fullarmor", L2Item.SLOT_FULL_ARMOR);
_slots.put("head", L2Item.SLOT_HEAD);
_slots.put("hair", L2Item.SLOT_HAIR);
_slots.put("underwear", L2Item.SLOT_UNDERWEAR);
_slots.put("back", L2Item.SLOT_BACK);
_slots.put("neck", L2Item.SLOT_NECK);
_slots.put("legs", L2Item.SLOT_LEGS);
_slots.put("feet", L2Item.SLOT_FEET);
_slots.put("gloves", L2Item.SLOT_GLOVES);
_slots.put("chest,legs", L2Item.SLOT_CHEST | L2Item.SLOT_LEGS);
_slots.put("rhand", L2Item.SLOT_R_HAND);
_slots.put("lhand", L2Item.SLOT_L_HAND);
_slots.put("lrhand", L2Item.SLOT_LR_HAND);
_slots.put("rear,lear", L2Item.SLOT_R_EAR | L2Item.SLOT_L_EAR);
_slots.put("rfinger,lfinger", L2Item.SLOT_R_FINGER | L2Item.SLOT_L_FINGER);
_slots.put("none", L2Item.SLOT_NONE);
_slots.put("wolf", L2Item.SLOT_WOLF); // for wolf
_slots.put("hatchling", L2Item.SLOT_HATCHLING); // for hatchling
_slots.put("strider", L2Item.SLOT_STRIDER); // for strider
}
private static ItemTable _instance;
/** Table of SQL request in order to obtain items from tables [etcitem], [armor], [weapon] */
private static final String[] SQL_ITEM_SELECTS =
{
"SELECT item_id, name, crystallizable, item_type, weight, consume_type, material, crystal_type, price, crystal_count, sellable, dropable, destroyable, tradeable FROM etcitem",
"SELECT item_id, name, bodypart, crystallizable, armor_type, weight, material, crystal_type, avoid_modify, p_def, m_def, mp_bonus, price, crystal_count, sellable, dropable, destroyable, tradeable, item_skill_id, item_skill_lvl FROM armor",
"SELECT item_id, name, bodypart, crystallizable, weight, soulshots, spiritshots, material, crystal_type, p_dam, rnd_dam, weaponType, critical, hit_modify, avoid_modify, shield_def, shield_def_rate, atk_speed, mp_consume," + " m_dam, price, crystal_count, sellable, dropable, destroyable, tradeable, item_skill_id, item_skill_lvl, onCast_skill_id, onCast_skill_lvl, onCast_skill_chance, onCrit_skill_id, onCrit_skill_lvl, onCrit_skill_chance FROM weapon"
};
/** Table of SQL request in order to obtain items from tables [custom_etcitem], [custom_armor], [custom_weapon] */
private static final String[] SQL_CUSTOM_ITEM_SELECTS =
{
"SELECT item_id, name, crystallizable, item_type, weight, consume_type, material, crystal_type, price, crystal_count, sellable, dropable, destroyable, tradeable FROM custom_etcitem",
"SELECT item_id, name, bodypart, crystallizable, armor_type, weight, material, crystal_type, avoid_modify, p_def, m_def, mp_bonus, price, crystal_count, sellable, dropable, destroyable, tradeable, item_skill_id, item_skill_lvl FROM custom_armor",
"SELECT item_id, name, bodypart, crystallizable, weight, soulshots, spiritshots, material, crystal_type, p_dam, rnd_dam, weaponType, critical, hit_modify, avoid_modify, shield_def, shield_def_rate, atk_speed, mp_consume," + " m_dam, price, crystal_count, sellable, dropable, destroyable, tradeable, item_skill_id, item_skill_lvl, onCast_skill_id, onCast_skill_lvl, onCast_skill_chance, onCrit_skill_id, onCrit_skill_lvl, onCrit_skill_chance FROM custom_weapon"
};
/** List of etcItem */
private static final Map<Integer, Item> itemData = new FastMap<>();
/** List of weapons */
private static final Map<Integer, Item> weaponData = new FastMap<>();
/** List of armor */
private static final Map<Integer, Item> armorData = new FastMap<>();
/**
* Returns instance of ItemTable
* @return ItemTable
*/
public static ItemTable getInstance()
{
if (_instance == null)
{
_instance = new ItemTable();
}
return _instance;
}
/**
* Returns a new object Item
* @return
*/
public Item newItem()
{
return new Item();
}
/**
* Constructor.
*/
public ItemTable()
{
_etcItems = new FastMap<>();
_armors = new FastMap<>();
_weapons = new FastMap<>();
try (Connection con = L2DatabaseFactory.getInstance().getConnection())
{
for (final String selectQuery : SQL_ITEM_SELECTS)
{
try (PreparedStatement statement = con.prepareStatement(selectQuery);
ResultSet rset = statement.executeQuery())
{
// Add item in correct FastMap
while (rset.next())
{
if (selectQuery.endsWith("etcitem"))
{
final Item newItem = readItem(rset);
itemData.put(newItem.id, newItem);
}
else if (selectQuery.endsWith("armor"))
{
final Item newItem = readArmor(rset);
armorData.put(newItem.id, newItem);
}
else if (selectQuery.endsWith("weapon"))
{
final Item newItem = readWeapon(rset);
weaponData.put(newItem.id, newItem);
}
}
}
}
}
catch (final Exception e)
{
_log.log(Level.WARNING, "data error on item: ", e);
}
if (Config.CUSTOM_ITEM_TABLES)
{
try (Connection con = L2DatabaseFactory.getInstance().getConnection())
{
for (final String selectQuery : SQL_CUSTOM_ITEM_SELECTS)
{
try (PreparedStatement statement = con.prepareStatement(selectQuery);
ResultSet rset = statement.executeQuery())
{
// Add item in correct FastMap
while (rset.next())
{
if (selectQuery.endsWith("etcitem"))
{
final Item newItem = readItem(rset);
if (itemData.containsKey(newItem.id))
{
itemData.remove(newItem.id);
}
itemData.put(newItem.id, newItem);
}
else if (selectQuery.endsWith("armor"))
{
final Item newItem = readArmor(rset);
if (armorData.containsKey(newItem.id))
{
armorData.remove(newItem.id);
}
armorData.put(newItem.id, newItem);
}
else if (selectQuery.endsWith("weapon"))
{
final Item newItem = readWeapon(rset);
if (weaponData.containsKey(newItem.id))
{
weaponData.remove(newItem.id);
}
weaponData.put(newItem.id, newItem);
}
}
}
}
}
catch (final Exception e)
{
_log.log(Level.WARNING, "data error on custom item: ", e);
}
}
for (final L2Armor armor : SkillsEngine.getInstance().loadArmors(armorData))
{
_armors.put(armor.getItemId(), armor);
}
_log.config("ItemTable: Loaded " + _armors.size() + " Armors.");
for (final L2EtcItem item : SkillsEngine.getInstance().loadItems(itemData))
{
_etcItems.put(item.getItemId(), item);
}
_log.config("ItemTable: Loaded " + _etcItems.size() + " Items.");
for (final L2Weapon weapon : SkillsEngine.getInstance().loadWeapons(weaponData))
{
_weapons.put(weapon.getItemId(), weapon);
}
_log.config("ItemTable: Loaded " + _weapons.size() + " Weapons.");
buildFastLookupTable();
}
/**
* Returns object Item from the record of the database
* @param rset : ResultSet designating a record of the [weapon] table of database
* @return Item : object created from the database record
* @throws SQLException
*/
private Item readWeapon(ResultSet rset) throws SQLException
{
final Item item = new Item();
item.set = new StatsSet();
item.type = _weaponTypes.get(rset.getString("weaponType"));
item.id = rset.getInt("item_id");
item.name = rset.getString("name");
item.set.set("item_id", item.id);
item.set.set("name", item.name);
// lets see if this is a shield
if (item.type == L2WeaponType.NONE)
{
item.set.set("type1", L2Item.TYPE1_SHIELD_ARMOR);
item.set.set("type2", L2Item.TYPE2_SHIELD_ARMOR);
}
else
{
item.set.set("type1", L2Item.TYPE1_WEAPON_RING_EARRING_NECKLACE);
item.set.set("type2", L2Item.TYPE2_WEAPON);
}
item.set.set("bodypart", _slots.get(rset.getString("bodypart")));
item.set.set("material", _materials.get(rset.getString("material")));
item.set.set("crystal_type", _crystalTypes.get(rset.getString("crystal_type")));
item.set.set("crystallizable", Boolean.valueOf(rset.getString("crystallizable")).booleanValue());
item.set.set("weight", rset.getInt("weight"));
item.set.set("soulshots", rset.getInt("soulshots"));
item.set.set("spiritshots", rset.getInt("spiritshots"));
item.set.set("p_dam", rset.getInt("p_dam"));
item.set.set("rnd_dam", rset.getInt("rnd_dam"));
item.set.set("critical", rset.getInt("critical"));
item.set.set("hit_modify", rset.getDouble("hit_modify"));
item.set.set("avoid_modify", rset.getInt("avoid_modify"));
item.set.set("shield_def", rset.getInt("shield_def"));
item.set.set("shield_def_rate", rset.getInt("shield_def_rate"));
item.set.set("atk_speed", rset.getInt("atk_speed"));
item.set.set("mp_consume", rset.getInt("mp_consume"));
item.set.set("m_dam", rset.getInt("m_dam"));
item.set.set("price", rset.getInt("price"));
item.set.set("crystal_count", rset.getInt("crystal_count"));
item.set.set("sellable", Boolean.valueOf(rset.getString("sellable")));
item.set.set("dropable", Boolean.valueOf(rset.getString("dropable")));
item.set.set("destroyable", Boolean.valueOf(rset.getString("destroyable")));
item.set.set("tradeable", Boolean.valueOf(rset.getString("tradeable")));
item.set.set("item_skill_id", rset.getInt("item_skill_id"));
item.set.set("item_skill_lvl", rset.getInt("item_skill_lvl"));
item.set.set("onCast_skill_id", rset.getInt("onCast_skill_id"));
item.set.set("onCast_skill_lvl", rset.getInt("onCast_skill_lvl"));
item.set.set("onCast_skill_chance", rset.getInt("onCast_skill_chance"));
item.set.set("onCrit_skill_id", rset.getInt("onCrit_skill_id"));
item.set.set("onCrit_skill_lvl", rset.getInt("onCrit_skill_lvl"));
item.set.set("onCrit_skill_chance", rset.getInt("onCrit_skill_chance"));
if (item.type == L2WeaponType.PET)
{
item.set.set("type1", L2Item.TYPE1_WEAPON_RING_EARRING_NECKLACE);
if (item.set.getInteger("bodypart") == L2Item.SLOT_WOLF)
{
item.set.set("type2", L2Item.TYPE2_PET_WOLF);
}
else if (item.set.getInteger("bodypart") == L2Item.SLOT_HATCHLING)
{
item.set.set("type2", L2Item.TYPE2_PET_HATCHLING);
}
else
{
item.set.set("type2", L2Item.TYPE2_PET_STRIDER);
}
item.set.set("bodypart", L2Item.SLOT_R_HAND);
}
return item;
}
/**
* Returns object Item from the record of the database
* @param rset : ResultSet designating a record of the [armor] table of database
* @return Item : object created from the database record
* @throws SQLException
*/
private Item readArmor(ResultSet rset) throws SQLException
{
final Item item = new Item();
item.set = new StatsSet();
item.type = _armorTypes.get(rset.getString("armor_type"));
item.id = rset.getInt("item_id");
item.name = rset.getString("name");
item.set.set("item_id", item.id);
item.set.set("name", item.name);
final int bodypart = _slots.get(rset.getString("bodypart"));
item.set.set("bodypart", bodypart);
item.set.set("crystallizable", Boolean.valueOf(rset.getString("crystallizable")));
item.set.set("crystal_count", rset.getInt("crystal_count"));
item.set.set("sellable", Boolean.valueOf(rset.getString("sellable")));
item.set.set("dropable", Boolean.valueOf(rset.getString("dropable")));
item.set.set("destroyable", Boolean.valueOf(rset.getString("destroyable")));
item.set.set("tradeable", Boolean.valueOf(rset.getString("tradeable")));
if ((bodypart == L2Item.SLOT_NECK) || (bodypart == L2Item.SLOT_HAIR) || ((bodypart & L2Item.SLOT_L_EAR) != 0) || ((bodypart & L2Item.SLOT_L_FINGER) != 0))
{
item.set.set("type1", L2Item.TYPE1_WEAPON_RING_EARRING_NECKLACE);
item.set.set("type2", L2Item.TYPE2_ACCESSORY);
}
else
{
item.set.set("type1", L2Item.TYPE1_SHIELD_ARMOR);
item.set.set("type2", L2Item.TYPE2_SHIELD_ARMOR);
}
item.set.set("weight", rset.getInt("weight"));
item.set.set("material", _materials.get(rset.getString("material")));
item.set.set("crystal_type", _crystalTypes.get(rset.getString("crystal_type")));
item.set.set("avoid_modify", rset.getInt("avoid_modify"));
item.set.set("p_def", rset.getInt("p_def"));
item.set.set("m_def", rset.getInt("m_def"));
item.set.set("mp_bonus", rset.getInt("mp_bonus"));
item.set.set("price", rset.getInt("price"));
item.set.set("item_skill_id", rset.getInt("item_skill_id"));
item.set.set("item_skill_lvl", rset.getInt("item_skill_lvl"));
if (item.type == L2ArmorType.PET)
{
if (bodypart == L2Item.SLOT_NECK)
{
item.set.set("type1", L2Item.TYPE1_WEAPON_RING_EARRING_NECKLACE);
item.set.set("type2", L2Item.TYPE2_ACCESSORY);
item.set.set("bodypart", L2Item.SLOT_NECK);
}
else
{
item.set.set("type1", L2Item.TYPE1_SHIELD_ARMOR);
switch (item.set.getInteger("bodypart"))
{
case L2Item.SLOT_WOLF:
item.set.set("type2", L2Item.TYPE2_PET_WOLF);
break;
case L2Item.SLOT_HATCHLING:
item.set.set("type2", L2Item.TYPE2_PET_HATCHLING);
break;
default:
item.set.set("type2", L2Item.TYPE2_PET_STRIDER);
break;
}
item.set.set("bodypart", L2Item.SLOT_CHEST);
}
}
return item;
}
/**
* Returns object Item from the record of the database
* @param rset : ResultSet designating a record of the [etcitem] table of database
* @return Item : object created from the database record
* @throws SQLException
*/
private Item readItem(ResultSet rset) throws SQLException
{
final Item item = new Item();
item.set = new StatsSet();
item.id = rset.getInt("item_id");
item.set.set("item_id", item.id);
item.set.set("crystallizable", Boolean.valueOf(rset.getString("crystallizable")));
item.set.set("type1", L2Item.TYPE1_ITEM_QUESTITEM_ADENA);
item.set.set("type2", L2Item.TYPE2_OTHER);
item.set.set("bodypart", 0);
item.set.set("crystal_count", rset.getInt("crystal_count"));
item.set.set("sellable", Boolean.valueOf(rset.getString("sellable")));
item.set.set("dropable", Boolean.valueOf(rset.getString("dropable")));
item.set.set("destroyable", Boolean.valueOf(rset.getString("destroyable")));
item.set.set("tradeable", Boolean.valueOf(rset.getString("tradeable")));
final String itemType = rset.getString("item_type");
if (itemType.equals("none"))
{
item.type = L2EtcItemType.OTHER; // only for default
}
else if (itemType.equals("castle_guard"))
{
item.type = L2EtcItemType.SCROLL; // dummy
}
else if (itemType.equals("material"))
{
item.type = L2EtcItemType.MATERIAL;
}
else if (itemType.equals("pet_collar"))
{
item.type = L2EtcItemType.PET_COLLAR;
}
else if (itemType.equals("potion"))
{
item.type = L2EtcItemType.POTION;
}
else if (itemType.equals("recipe"))
{
item.type = L2EtcItemType.RECEIPE;
}
else if (itemType.equals("scroll"))
{
item.type = L2EtcItemType.SCROLL;
}
else if (itemType.equals("seed"))
{
item.type = L2EtcItemType.SEED;
}
else if (itemType.equals("shot"))
{
item.type = L2EtcItemType.SHOT;
}
else if (itemType.equals("spellbook"))
{
item.type = L2EtcItemType.SPELLBOOK; // Spellbook, Amulet, Blueprint
}
else if (itemType.equals("arrow"))
{
item.type = L2EtcItemType.ARROW;
item.set.set("bodypart", L2Item.SLOT_L_HAND);
}
else if (itemType.equals("quest"))
{
item.type = L2EtcItemType.QUEST;
item.set.set("type2", L2Item.TYPE2_QUEST);
}
else if (itemType.equals("lure"))
{
item.type = L2EtcItemType.OTHER;
item.set.set("bodypart", L2Item.SLOT_L_HAND);
}
else
{
_log.fine("unknown etcitem type:" + itemType);
item.type = L2EtcItemType.OTHER;
}
final String consume = rset.getString("consume_type");
if (consume.equals("asset"))
{
item.type = L2EtcItemType.MONEY;
item.set.set("stackable", true);
item.set.set("type2", L2Item.TYPE2_MONEY);
}
else if (consume.equals("stackable"))
{
item.set.set("stackable", true);
}
else
{
item.set.set("stackable", false);
}
final int material = _materials.get(rset.getString("material"));
item.set.set("material", material);
final int crystal = _crystalTypes.get(rset.getString("crystal_type"));
item.set.set("crystal_type", crystal);
final int weight = rset.getInt("weight");
item.set.set("weight", weight);
item.name = rset.getString("name");
item.set.set("name", item.name);
item.set.set("price", rset.getInt("price"));
return item;
}
/**
* Returns if ItemTable initialized
* @return boolean
*/
public boolean isInitialized()
{
return _initialized;
}
/**
* Builds a variable in which all items are putting in in function of their ID.
*/
private void buildFastLookupTable()
{
int highestId = 0;
// Get highest ID of item in armor FastMap, then in weapon FastMap, and finally in etcitem FastMap
for (final Integer id : _armors.keySet())
{
final L2Armor item = _armors.get(id);
if (item.getItemId() > highestId)
{
highestId = item.getItemId();
}
}
for (final Integer id : _weapons.keySet())
{
final L2Weapon item = _weapons.get(id);
if (item.getItemId() > highestId)
{
highestId = item.getItemId();
}
}
for (final Integer id : _etcItems.keySet())
{
final L2EtcItem item = _etcItems.get(id);
if (item.getItemId() > highestId)
{
highestId = item.getItemId();
}
}
// Create a FastLookUp Table called _allTemplates of size : value of the highest item ID
if (Config.DEBUG)
{
_log.fine("highest item id used:" + highestId);
}
_allTemplates = new L2Item[highestId + 1];
// Insert armor item in Fast Look Up Table
for (final Integer id : _armors.keySet())
{
final L2Armor item = _armors.get(id);
assert _allTemplates[id.intValue()] == null;
_allTemplates[id.intValue()] = item;
}
// Insert weapon item in Fast Look Up Table
for (final Integer id : _weapons.keySet())
{
final L2Weapon item = _weapons.get(id);
assert _allTemplates[id.intValue()] == null;
_allTemplates[id.intValue()] = item;
}
// Insert etcItem item in Fast Look Up Table
for (final Integer id : _etcItems.keySet())
{
final L2EtcItem item = _etcItems.get(id);
assert _allTemplates[id.intValue()] == null;
_allTemplates[id.intValue()] = item;
}
}
/**
* Returns the item corresponding to the item ID
* @param id : int designating the item
* @return L2Item
*/
public L2Item getTemplate(int id)
{
if (id > _allTemplates.length)
{
return null;
}
return _allTemplates[id];
}
/**
* Create the L2ItemInstance corresponding to the Item Identifier and quantitiy add logs the activity.<BR>
* <BR>
* <B><U> Actions</U> :</B><BR>
* <BR>
* <li>Create and Init the L2ItemInstance corresponding to the Item Identifier and quantity</li>
* <li>Add the L2ItemInstance object to _allObjects of L2world</li>
* <li>Logs Item creation according to log settings</li><BR>
* <BR>
* @param process : String Identifier of process triggering this action
* @param itemId : int Item Identifier of the item to be created
* @param count : int Quantity of items to be created for stackable items
* @param actor : L2PcInstance Player requesting the item creation
* @param reference : L2Object Object referencing current action like NPC selling item or previous item in transformation
* @return L2ItemInstance corresponding to the new item
*/
public L2ItemInstance createItem(String process, int itemId, int count, L2PcInstance actor, L2Object reference)
{
// Create and Init the L2ItemInstance corresponding to the Item Identifier
final L2ItemInstance item = new L2ItemInstance(IdFactory.getInstance().getNextId(), itemId);
if (process.equalsIgnoreCase("loot"))
{
ScheduledFuture<?> itemLootShedule;
if ((reference != null) && (reference instanceof L2Attackable) && ((L2Attackable) reference).isRaid() && !Config.AUTO_LOOT_RAIDS)
{
item.setOwnerId(actor.getObjectId());
itemLootShedule = ThreadPoolManager.getInstance().scheduleGeneral(new resetOwner(item), 15000);
item.setItemLootSchedule(itemLootShedule);
}
else if (!Config.AUTO_LOOT)
{
item.setOwnerId(actor.getObjectId());
itemLootShedule = ThreadPoolManager.getInstance().scheduleGeneral(new resetOwner(item), 15000);
item.setItemLootSchedule(itemLootShedule);
}
}
if (Config.DEBUG)
{
_log.fine("ItemTable: Item created oid:" + item.getObjectId() + " itemid:" + itemId);
}
// Add the L2ItemInstance object to _allObjects of L2world
L2World.getInstance().storeObject(item);
// Set Item parameters
if (item.isStackable() && (count > 1))
{
item.setCount(count);
}
if (Config.LOG_ITEMS)
{
final LogRecord record = new LogRecord(Level.INFO, "CREATE:" + process);
record.setLoggerName("item");
record.setParameters(new Object[]
{
item,
actor,
reference
});
_logItems.log(record);
}
return item;
}
public L2ItemInstance createItem(String process, int itemId, int count, L2PcInstance actor)
{
return createItem(process, itemId, count, actor, null);
}
/**
* Returns a dummy (fr = factice) item.<BR>
* <BR>
* <U><I>Concept :</I></U><BR>
* Dummy item is created by setting the ID of the object in the world at null value
* @param itemId : int designating the item
* @return L2ItemInstance designating the dummy item created
*/
public L2ItemInstance createDummyItem(int itemId)
{
final L2Item item = getTemplate(itemId);
if (item == null)
{
return null;
}
L2ItemInstance temp = new L2ItemInstance(0, item);
try
{
temp = new L2ItemInstance(0, itemId);
}
catch (final ArrayIndexOutOfBoundsException e)
{
// this can happen if the item templates were not initialized
}
if (temp.getItem() == null)
{
_log.warning("ItemTable: Item Template missing for Id: " + itemId);
}
return temp;
}
/**
* Destroys the L2ItemInstance.<BR>
* <BR>
* <B><U> Actions</U> :</B><BR>
* <BR>
* <li>Sets L2ItemInstance parameters to be unusable</li>
* <li>Removes the L2ItemInstance object to _allObjects of L2world</li>
* <li>Logs Item deletion according to log settings</li><BR>
* <BR>
* @param process : String Identifier of process triggering this action
* @param item : int Item Identifier of the item to be created
* @param actor : L2PcInstance Player requesting the item destroy
* @param reference : L2Object Object referencing current action like NPC selling item or previous item in transformation
*/
public void destroyItem(String process, L2ItemInstance item, L2PcInstance actor, L2Object reference)
{
synchronized (item)
{
item.setCount(0);
item.setOwnerId(0);
item.setLocation(ItemLocation.VOID);
item.setLastChange(L2ItemInstance.REMOVED);
L2World.getInstance().removeObject(item);
IdFactory.getInstance().releaseId(item.getObjectId());
if (Config.LOG_ITEMS)
{
final LogRecord record = new LogRecord(Level.INFO, "DELETE:" + process);
record.setLoggerName("item");
record.setParameters(new Object[]
{
item,
actor,
reference
});
_logItems.log(record);
}
// if it's a pet control item, delete the pet as well
if (L2PetDataTable.isPetItem(item.getItemId()))
{
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("DELETE FROM pets WHERE item_obj_id=?"))
{
// Delete the pet in db
statement.setInt(1, item.getObjectId());
statement.execute();
}
catch (final Exception e)
{
_log.log(Level.WARNING, "could not delete pet objectid:", e);
}
}
}
}
public void reload()
{
synchronized (_instance)
{
_instance = null;
_instance = new ItemTable();
}
}
protected class resetOwner implements Runnable
{
L2ItemInstance _item;
public resetOwner(L2ItemInstance item)
{
_item = item;
}
@Override
public void run()
{
_item.setOwnerId(0);
_item.setItemLootSchedule(null);
}
}
}

View File

@@ -0,0 +1,115 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;
import java.util.logging.Logger;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.model.L2LvlupData;
import com.l2jmobius.gameserver.model.base.ClassId;
import javolution.util.FastMap;
/**
* This class ...
* @author NightMarez
* @version $Revision: 1.3.2.4.2.3 $ $Date: 2005/03/27 15:29:18 $
*/
public class LevelUpData
{
private static final String SELECT_ALL = "SELECT classid, defaulthpbase, defaulthpadd, defaulthpmod, defaultcpbase, defaultcpadd, defaultcpmod, defaultmpbase, defaultmpadd, defaultmpmod, class_lvl FROM lvlupgain";
private static final String CLASS_LVL = "class_lvl";
private static final String MP_MOD = "defaultmpmod";
private static final String MP_ADD = "defaultmpadd";
private static final String MP_BASE = "defaultmpbase";
private static final String HP_MOD = "defaulthpmod";
private static final String HP_ADD = "defaulthpadd";
private static final String HP_BASE = "defaulthpbase";
private static final String CP_MOD = "defaultcpmod";
private static final String CP_ADD = "defaultcpadd";
private static final String CP_BASE = "defaultcpbase";
private static final String CLASS_ID = "classid";
private static Logger _log = Logger.getLogger(LevelUpData.class.getName());
private static LevelUpData _instance;
private final Map<Integer, L2LvlupData> _lvltable;
public static LevelUpData getInstance()
{
if (_instance == null)
{
_instance = new LevelUpData();
}
return _instance;
}
private LevelUpData()
{
_lvltable = new FastMap<>();
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement(SELECT_ALL);
ResultSet rset = statement.executeQuery())
{
L2LvlupData lvlDat;
while (rset.next())
{
lvlDat = new L2LvlupData();
lvlDat.set_classid(rset.getInt(CLASS_ID));
lvlDat.set_classLvl(rset.getInt(CLASS_LVL));
lvlDat.set_classHpBase(rset.getFloat(HP_BASE));
lvlDat.set_classHpAdd(rset.getFloat(HP_ADD));
lvlDat.set_classHpModifier(rset.getFloat(HP_MOD));
lvlDat.set_classCpBase(rset.getFloat(CP_BASE));
lvlDat.set_classCpAdd(rset.getFloat(CP_ADD));
lvlDat.set_classCpModifier(rset.getFloat(CP_MOD));
lvlDat.set_classMpBase(rset.getFloat(MP_BASE));
lvlDat.set_classMpAdd(rset.getFloat(MP_ADD));
lvlDat.set_classMpModifier(rset.getFloat(MP_MOD));
_lvltable.put(new Integer(lvlDat.get_classid()), lvlDat);
}
_log.config("LevelUpData: Loaded " + _lvltable.size() + " Character Level Up Templates.");
}
catch (final Exception e)
{
_log.warning("error while creating Lvl up data table " + e);
}
}
/**
* @param classId
* @return
*/
public L2LvlupData getTemplate(int classId)
{
return _lvltable.get(classId);
}
public L2LvlupData getTemplate(ClassId classId)
{
return _lvltable.get(classId.getId());
}
}

View File

@@ -0,0 +1,352 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.logging.Logger;
import com.l2jmobius.Config;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.instancemanager.ArenaManager;
import com.l2jmobius.gameserver.instancemanager.CastleManager;
import com.l2jmobius.gameserver.instancemanager.ClanHallManager;
import com.l2jmobius.gameserver.instancemanager.SiegeManager;
import com.l2jmobius.gameserver.instancemanager.TownManager;
import com.l2jmobius.gameserver.model.L2Character;
import com.l2jmobius.gameserver.model.Location;
import com.l2jmobius.gameserver.model.actor.instance.L2NpcInstance;
import com.l2jmobius.gameserver.model.actor.instance.L2PcInstance;
import com.l2jmobius.gameserver.model.entity.Castle;
import com.l2jmobius.gameserver.model.entity.ClanHall;
import com.l2jmobius.gameserver.model.entity.Siege;
import com.l2jmobius.gameserver.model.zone.type.L2ArenaZone;
import com.l2jmobius.gameserver.model.zone.type.L2ClanHallZone;
/**
* This class ...
*/
public class MapRegionTable
{
private static Logger _log = Logger.getLogger(MapRegionTable.class.getName());
private static MapRegionTable _instance;
private final int[][] _regions = new int[19][21];
public static enum TeleportWhereType
{
Castle,
ClanHall,
SiegeFlag,
Town
}
public static MapRegionTable getInstance()
{
if (_instance == null)
{
_instance = new MapRegionTable();
}
return _instance;
}
private MapRegionTable()
{
int count2 = 0;
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT region, sec0, sec1, sec2, sec3, sec4, sec5, sec6, sec7, sec8, sec9, sec10 FROM mapregion");
ResultSet rset = statement.executeQuery())
{
int region;
while (rset.next())
{
region = rset.getInt(1);
for (int j = 0; j < 11; j++)
{
_regions[j][region] = rset.getInt(j + 2);
count2++;
}
}
if (Config.DEBUG)
{
_log.fine(count2 + " mapregion loaded");
}
}
catch (final Exception e)
{
_log.warning("error while creating map region data: " + e);
}
}
public final int getMapRegion(int posX, int posY)
{
return _regions[getMapRegionX(posX)][getMapRegionY(posY)];
}
public final int getMapRegionX(int posX)
{
return (posX >> 15) + 4;// + centerTileX;
}
public final int getMapRegionY(int posY)
{
return (posY >> 15) + 10;// + centerTileX;
}
public int getAreaCastle(L2Character activeChar)
{
final int area = getClosestTownNumber(activeChar);
int castle;
switch (area)
{
case 0:
castle = 1;
break;
case 1:
castle = 4;
break;
case 2:
castle = 4;
break;
case 5:
castle = 1;
break;
case 6:
castle = 1;
break;
case 7:
castle = 2;
break;
case 8:
castle = 3;
break;
case 9:
castle = 4;
break;
case 10:
castle = 5;
break;
case 11:
castle = 5;
break;
case 12:
castle = 3;
break;
case 13:
castle = 6;
break;
case 15:
castle = 7;
break;
case 16:
castle = 2;
break;
default:
castle = 5;
break;
}
return castle;
}
public int getClosestTownNumber(L2Character activeChar)
{
return getMapRegion(activeChar.getX(), activeChar.getY());
}
public String getClosestTownName(L2Character activeChar)
{
final int nearestTownId = getMapRegion(activeChar.getX(), activeChar.getY());
String nearestTown;
switch (nearestTownId)
{
case 0:
nearestTown = "Talking Island Village";
break;
case 1:
nearestTown = "Elven Village";
break;
case 2:
nearestTown = "Dark Elven Village";
break;
case 3:
nearestTown = "Orc Village";
break;
case 4:
nearestTown = "Dwarven Village";
break;
case 5:
nearestTown = "Gludio Castle Town";
break;
case 6:
nearestTown = "Gludin Village";
break;
case 7:
nearestTown = "Dion Castle Town";
break;
case 8:
nearestTown = "Giran Castle Town";
break;
case 9:
nearestTown = "Oren Castle Town";
break;
case 10:
nearestTown = "Aden Castle Town";
break;
case 11:
nearestTown = "Hunters Village";
break;
case 12:
nearestTown = "Giran Harbor";
break;
case 13:
nearestTown = "Innadril Castle Town";
break;
case 14:
nearestTown = "Rune Castle Town";
break;
case 15:
nearestTown = "Goddard Castle Town";
break;
case 16:
nearestTown = "Floran Village";
break;
default:
nearestTown = "Aden Castle Town";
break;
}
return nearestTown;
}
public Location getTeleToLocation(L2Character activeChar, TeleportWhereType teleportWhere)
{
// int[] coord;
if (activeChar instanceof L2PcInstance)
{
final L2PcInstance player = ((L2PcInstance) activeChar);
// If in Monster Derby Track
if (player.isInsideZone(L2Character.ZONE_MONSTERTRACK))
{
return new Location(12661, 181687, -3560);
}
Castle castle = null;
ClanHall clanhall = null;
if (player.getClan() != null)
{
// If teleport to clan hall
if (teleportWhere == TeleportWhereType.ClanHall)
{
clanhall = ClanHallManager.getInstance().getClanHallByOwner(player.getClan());
if (clanhall != null)
{
final L2ClanHallZone zone = clanhall.getZone();
if (zone != null)
{
return zone.getSpawnLoc();
}
}
}
if (teleportWhere == TeleportWhereType.Castle)
{
castle = CastleManager.getInstance().getCastleByOwner(player.getClan());
if (castle != null)
{
return castle.getZone().getSpawnLoc();
}
castle = CastleManager.getInstance().getCastle(player);
if ((castle != null) && (castle.getCastleId() > 0))
{
// If teleport to castle
if (castle.getSiege().getIsInProgress() && (castle.getSiege().getDefenderClan(player.getClan()) != null))
{
return castle.getZone().getSpawnLoc();
}
}
}
if (teleportWhere == TeleportWhereType.SiegeFlag)
{
final Siege siege = SiegeManager.getInstance().getSiege(player);
if (siege != null)
{
// Check if player's clan is attacker
final List<L2NpcInstance> flags = siege.getFlag(player.getClan());
if ((flags != null) && !flags.isEmpty())
{
// Spawn to flag - Need more work to get player to the nearest flag
final L2NpcInstance flag = flags.get(0);
return new Location(flag.getX(), flag.getY(), flag.getZ());
}
}
}
}
// Karma player land out of city
if (player.getKarma() > 0)
{
try
{
return TownManager.getInstance().getClosestTown(activeChar).getChaoticSpawnLoc();
}
catch (final Exception e)
{
return new Location(17817, 170079, -3530);
}
}
// Checking if in arena
final L2ArenaZone arena = ArenaManager.getInstance().getArena(player);
if (arena != null)
{
return arena.getSpawnLoc();
}
}
// Get the nearest town
try
{
return TownManager.getInstance().getClosestTown(activeChar).getSpawnLoc();
}
catch (final NullPointerException e)
{
// port to the Talking Island if no closest town found
return new Location(-84176, 243382, -3126);
}
}
}

View File

@@ -0,0 +1,55 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import com.l2jmobius.gameserver.model.L2Skill;
/**
* @author -Nemesiss-
*/
public class NobleSkillTable
{
private static NobleSkillTable _instance;
private static L2Skill[] _NobleSkills;
private NobleSkillTable()
{
_NobleSkills = new L2Skill[8];
_NobleSkills[0] = SkillTable.getInstance().getInfo(1323, 1);
_NobleSkills[1] = SkillTable.getInstance().getInfo(325, 1);
_NobleSkills[2] = SkillTable.getInstance().getInfo(326, 1);
_NobleSkills[3] = SkillTable.getInstance().getInfo(327, 1);
_NobleSkills[4] = SkillTable.getInstance().getInfo(1324, 1);
_NobleSkills[5] = SkillTable.getInstance().getInfo(1325, 1);
_NobleSkills[6] = SkillTable.getInstance().getInfo(1326, 1);
_NobleSkills[7] = SkillTable.getInstance().getInfo(1327, 1);
}
public static NobleSkillTable getInstance()
{
if (_instance == null)
{
_instance = new NobleSkillTable();
}
return _instance;
}
public L2Skill[] GetNobleSkills()
{
return _NobleSkills;
}
}

View File

@@ -0,0 +1,104 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;
import com.l2jmobius.L2DatabaseFactory;
import javolution.util.FastMap;
public class NpcBufferTable
{
private static NpcBufferTable _instance = null;
private final Map<Integer, Integer> _skillId = new FastMap<>();
private final Map<Integer, Integer> _skillLevels = new FastMap<>();
private final Map<Integer, Integer> _skillFeeIds = new FastMap<>();
private final Map<Integer, Integer> _skillFeeAmounts = new FastMap<>();
public void addSkill(int skillId, int skillLevel, int skillFeeId, int skillFeeAmount, int buffGroup)
{
_skillId.put(buffGroup, skillId);
_skillLevels.put(buffGroup, skillLevel);
_skillFeeIds.put(buffGroup, skillFeeId);
_skillFeeAmounts.put(buffGroup, skillFeeAmount);
}
public int[] getSkillGroupInfo(int buffGroup)
{
final Integer skillId = _skillId.get(buffGroup);
final Integer skillLevel = _skillLevels.get(buffGroup);
final Integer skillFeeId = _skillFeeIds.get(buffGroup);
final Integer skillFeeAmount = _skillFeeAmounts.get(buffGroup);
if ((skillId == null) || (skillLevel == null) || (skillFeeId == null) || (skillFeeAmount == null))
{
return null;
}
return new int[]
{
skillId,
skillLevel,
skillFeeId,
skillFeeAmount
};
}
private NpcBufferTable()
{
int skillCount = 0;
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT skill_id, skill_level, skill_fee_id, skill_fee_amount, buff_group FROM npc_buffer order by id");
ResultSet rset = statement.executeQuery())
{
while (rset.next())
{
final int skillId = rset.getInt("skill_id");
final int skillLevel = rset.getInt("skill_level");
final int skillFeeId = rset.getInt("skill_fee_id");
final int skillFeeAmount = rset.getInt("skill_fee_amount");
final int buffGroup = rset.getInt("buff_group");
addSkill(skillId, skillLevel, skillFeeId, skillFeeAmount, buffGroup);
skillCount++;
}
}
catch (final Exception e)
{
System.out.println("NpcBufferTable: Error reading npc_buffer table: " + e);
}
System.out.println("NpcBufferTable: Loaded " + skillCount + " skills.");
}
public static NpcBufferTable getInstance()
{
if (_instance == null)
{
_instance = new NpcBufferTable();
}
return _instance;
}
}

View File

@@ -0,0 +1,847 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import com.l2jmobius.Config;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.model.L2DropCategory;
import com.l2jmobius.gameserver.model.L2DropData;
import com.l2jmobius.gameserver.model.L2MinionData;
import com.l2jmobius.gameserver.model.L2Skill;
import com.l2jmobius.gameserver.model.base.ClassId;
import com.l2jmobius.gameserver.skills.Stats;
import com.l2jmobius.gameserver.templates.L2NpcTemplate;
import com.l2jmobius.gameserver.templates.StatsSet;
import javolution.util.FastList;
import javolution.util.FastMap;
/**
* This class ...
* @version $Revision: 1.8.2.6.2.9 $ $Date: 2005/04/06 16:13:25 $
*/
public class NpcTable
{
private static Logger _log = Logger.getLogger(NpcTable.class.getName());
private static NpcTable _instance;
private final Map<Integer, L2NpcTemplate> _npcs;
private boolean _initialized = false;
public static NpcTable getInstance()
{
if (_instance == null)
{
_instance = new NpcTable();
}
return _instance;
}
private NpcTable()
{
_npcs = new FastMap<>();
restoreNpcData();
}
private void restoreNpcData()
{
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT " + L2DatabaseFactory.getInstance().safetyString(new String[]
{
"id",
"idTemplate",
"name",
"serverSideName",
"title",
"serverSideTitle",
"class",
"collision_radius",
"collision_height",
"level",
"sex",
"type",
"attackrange",
"hp",
"mp",
"hpreg",
"mpreg",
"str",
"con",
"dex",
"int",
"wit",
"men",
"exp",
"sp",
"patk",
"pdef",
"matk",
"mdef",
"atkspd",
"aggro",
"matkspd",
"rhand",
"lhand",
"armor",
"walkspd",
"runspd",
"faction_id",
"faction_range",
"isUndead",
"absorb_level",
"ss",
"bss",
"ss_rate",
"AI"
}) + " FROM npc");
ResultSet npcdata = statement.executeQuery())
{
fillNpcTable(npcdata, false);
}
catch (final Exception e)
{
_log.severe("NPCTable: Error creating NPC table: " + e);
}
if (Config.CUSTOM_NPC_TABLE)
{
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT " + L2DatabaseFactory.getInstance().safetyString(new String[]
{
"id",
"idTemplate",
"name",
"serverSideName",
"title",
"serverSideTitle",
"class",
"collision_radius",
"collision_height",
"level",
"sex",
"type",
"attackrange",
"hp",
"mp",
"hpreg",
"mpreg",
"str",
"con",
"dex",
"int",
"wit",
"men",
"exp",
"sp",
"patk",
"pdef",
"matk",
"mdef",
"atkspd",
"aggro",
"matkspd",
"rhand",
"lhand",
"armor",
"walkspd",
"runspd",
"faction_id",
"faction_range",
"isUndead",
"absorb_level",
"ss",
"bss",
"ss_rate",
"AI"
}) + " FROM custom_npc");
ResultSet npcdata = statement.executeQuery())
{
fillNpcTable(npcdata, true);
}
catch (final Exception e)
{
_log.severe("NPCTable: Error creating Custom NPC table: " + e);
}
}
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT npcid, skillid, level FROM npcskills");
ResultSet npcskills = statement.executeQuery())
{
L2NpcTemplate npcDat = null;
L2Skill npcSkill = null;
while (npcskills.next())
{
final int mobId = npcskills.getInt("npcid");
npcDat = _npcs.get(mobId);
if (npcDat == null)
{
continue;
}
final int skillId = npcskills.getInt("skillid");
final int level = npcskills.getInt("level");
if (npcDat.race == 0)
{
if ((skillId >= 4290) && (skillId <= 4302))
{
npcDat.setRace(skillId);
continue;
}
}
npcSkill = SkillTable.getInstance().getInfo(skillId, level);
if (npcSkill == null)
{
continue;
}
npcDat.addSkill(npcSkill);
}
}
catch (final Exception e)
{
_log.severe("NPCTable: Error reading NPC skills table: " + e);
}
if (Config.CUSTOM_NPC_SKILLS_TABLE)
{
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT npcid, skillid, level FROM custom_npcskills");
ResultSet npcskills = statement.executeQuery())
{
L2NpcTemplate npcDat = null;
L2Skill npcSkill = null;
while (npcskills.next())
{
final int mobId = npcskills.getInt("npcid");
npcDat = _npcs.get(mobId);
if (npcDat == null)
{
continue;
}
final int skillId = npcskills.getInt("skillid");
final int level = npcskills.getInt("level");
if (npcDat.race == 0)
{
if ((skillId >= 4290) && (skillId <= 4302))
{
npcDat.setRace(skillId);
continue;
}
}
npcSkill = SkillTable.getInstance().getInfo(skillId, level);
if (npcSkill == null)
{
continue;
}
npcDat.addSkill(npcSkill);
}
}
catch (final Exception e)
{
_log.severe("NPCTable: Error reading Custom NPC skills table: " + e);
}
}
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement2 = con.prepareStatement("SELECT " + L2DatabaseFactory.getInstance().safetyString(new String[]
{
"mobId",
"itemId",
"min",
"max",
"category",
"chance"
}) + " FROM droplist ORDER BY mobId, chance DESC");
ResultSet dropData = statement2.executeQuery())
{
L2DropData dropDat = null;
L2NpcTemplate npcDat = null;
while (dropData.next())
{
final int mobId = dropData.getInt("mobId");
npcDat = _npcs.get(mobId);
if (npcDat == null)
{
_log.severe("NPCTable: No npc correlating with id : " + mobId);
continue;
}
dropDat = new L2DropData();
dropDat.setItemId(dropData.getInt("itemId"));
dropDat.setMinDrop(dropData.getInt("min"));
dropDat.setMaxDrop(dropData.getInt("max"));
dropDat.setChance(dropData.getInt("chance"));
final int category = dropData.getInt("category");
npcDat.addDropData(dropDat, category);
}
}
catch (final Exception e)
{
_log.severe("NPCTable: Error reading NPC drop data: " + e);
}
if (Config.CUSTOM_DROPLIST_TABLE)
{
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement2 = con.prepareStatement("SELECT " + L2DatabaseFactory.getInstance().safetyString(new String[]
{
"mobId",
"itemId",
"min",
"max",
"category",
"chance"
}) + " FROM custom_droplist ORDER BY mobId, chance DESC");
ResultSet dropData = statement2.executeQuery())
{
L2DropData dropDat = null;
L2NpcTemplate npcDat = null;
int cCount = 0;
while (dropData.next())
{
final int mobId = dropData.getInt("mobId");
npcDat = _npcs.get(mobId);
if (npcDat == null)
{
_log.severe("NPCTable: No custom npc correlating with id : " + mobId);
continue;
}
dropDat = new L2DropData();
dropDat.setItemId(dropData.getInt("itemId"));
dropDat.setMinDrop(dropData.getInt("min"));
dropDat.setMaxDrop(dropData.getInt("max"));
dropDat.setChance(dropData.getInt("chance"));
final int category = dropData.getInt("category");
npcDat.addDropData(dropDat, category);
cCount++;
}
_log.info("CustomDropList : Added " + cCount + " drops to custom droplist");
}
catch (final Exception e)
{
_log.severe("NPCTable: Error reading Custom NPC drop data: " + e);
}
}
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement3 = con.prepareStatement("SELECT " + L2DatabaseFactory.getInstance().safetyString(new String[]
{
"npc_id",
"class_id"
}) + " FROM skill_learn");
ResultSet learndata = statement3.executeQuery())
{
while (learndata.next())
{
final int npcId = learndata.getInt("npc_id");
final int classId = learndata.getInt("class_id");
final L2NpcTemplate npc = getTemplate(npcId);
if (npc == null)
{
_log.warning("NPCTable: Error getting NPC template ID " + npcId + " while trying to load skill trainer data.");
continue;
}
npc.addTeachInfo(ClassId.values()[classId]);
}
}
catch (final Exception e)
{
_log.severe("NPCTable: Error reading NPC trainer data: " + e);
}
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement4 = con.prepareStatement("SELECT " + L2DatabaseFactory.getInstance().safetyString(new String[]
{
"boss_id",
"minion_id",
"amount_min",
"amount_max"
}) + " FROM minions");
ResultSet minionData = statement4.executeQuery())
{
L2MinionData minionDat = null;
L2NpcTemplate npcDat = null;
int cnt = 0;
while (minionData.next())
{
final int raidId = minionData.getInt("boss_id");
npcDat = _npcs.get(raidId);
minionDat = new L2MinionData();
minionDat.setMinionId(minionData.getInt("minion_id"));
minionDat.setAmountMin(minionData.getInt("amount_min"));
minionDat.setAmountMax(minionData.getInt("amount_max"));
npcDat.addRaidData(minionDat);
cnt++;
}
_log.config("NpcTable: Loaded " + cnt + " Minions.");
}
catch (final Exception e)
{
_log.severe("Error loading minion data: " + e);
}
_initialized = true;
}
private void fillNpcTable(ResultSet NpcData, boolean customData) throws Exception
{
int count = 0;
while (NpcData.next())
{
final StatsSet npcDat = new StatsSet();
final int id = NpcData.getInt("id");
if (Config.ASSERT)
{
assert id < 1000000;
}
npcDat.set("npcId", id);
npcDat.set("idTemplate", NpcData.getInt("idTemplate"));
final int level = NpcData.getInt("level");
npcDat.set("level", level);
npcDat.set("jClass", NpcData.getString("class"));
npcDat.set("baseShldDef", 0);
npcDat.set("baseShldRate", 0);
npcDat.set("baseCritRate", 38);
npcDat.set("name", NpcData.getString("name"));
npcDat.set("serverSideName", NpcData.getBoolean("serverSideName"));
// npcDat.set("name", "");
npcDat.set("title", NpcData.getString("title"));
npcDat.set("serverSideTitle", NpcData.getBoolean("serverSideTitle"));
npcDat.set("collision_radius", NpcData.getDouble("collision_radius"));
npcDat.set("collision_height", NpcData.getDouble("collision_height"));
npcDat.set("sex", NpcData.getString("sex"));
npcDat.set("type", NpcData.getString("type"));
npcDat.set("baseAtkRange", NpcData.getInt("attackrange"));
npcDat.set("rewardExp", NpcData.getInt("exp"));
npcDat.set("rewardSp", NpcData.getInt("sp"));
npcDat.set("basePAtkSpd", NpcData.getInt("atkspd"));
npcDat.set("baseMAtkSpd", NpcData.getInt("matkspd"));
npcDat.set("aggroRange", NpcData.getInt("aggro"));
npcDat.set("rhand", NpcData.getInt("rhand"));
npcDat.set("lhand", NpcData.getInt("lhand"));
npcDat.set("armor", NpcData.getInt("armor"));
npcDat.set("baseWalkSpd", NpcData.getInt("walkspd"));
npcDat.set("baseRunSpd", NpcData.getInt("runspd"));
// constants, until we have stats in DB
npcDat.set("baseSTR", NpcData.getInt("str"));
npcDat.set("baseCON", NpcData.getInt("con"));
npcDat.set("baseDEX", NpcData.getInt("dex"));
npcDat.set("baseINT", NpcData.getInt("int"));
npcDat.set("baseWIT", NpcData.getInt("wit"));
npcDat.set("baseMEN", NpcData.getInt("men"));
npcDat.set("baseHpMax", NpcData.getInt("hp"));
npcDat.set("baseCpMax", 0);
npcDat.set("baseMpMax", NpcData.getInt("mp"));
npcDat.set("baseHpReg", NpcData.getFloat("hpreg") > 0 ? NpcData.getFloat("hpreg") : 1.5 + ((level - 1) / 10));
npcDat.set("baseMpReg", NpcData.getFloat("mpreg") > 0 ? NpcData.getFloat("mpreg") : 0.9 + (0.3 * ((level - 1) / 10)));
npcDat.set("basePAtk", NpcData.getInt("patk"));
npcDat.set("basePDef", NpcData.getInt("pdef"));
npcDat.set("baseMAtk", NpcData.getInt("matk"));
npcDat.set("baseMDef", NpcData.getInt("mdef"));
npcDat.set("factionId", NpcData.getString("faction_id"));
npcDat.set("factionRange", NpcData.getInt("faction_range"));
npcDat.set("isUndead", NpcData.getString("isUndead"));
npcDat.set("absorb_level", NpcData.getString("absorb_level"));
npcDat.set("ss", NpcData.getInt("ss"));
npcDat.set("bss", NpcData.getInt("bss"));
npcDat.set("ssRate", NpcData.getInt("ss_rate"));
npcDat.set("AI", NpcData.getString("AI"));
final L2NpcTemplate template = new L2NpcTemplate(npcDat);
template.addVulnerability(Stats.BOW_WPN_VULN, 1);
template.addVulnerability(Stats.BLUNT_WPN_VULN, 1);
template.addVulnerability(Stats.DAGGER_WPN_VULN, 1);
final L2NpcTemplate oldTemplate = getTemplate(id);
if (oldTemplate != null)
{
// add quest events to the new template
if (oldTemplate.questEvents != null)
{
template.questEvents = oldTemplate.questEvents;
}
}
_npcs.put(id, template);
count++;
}
if (count > 0)
{
if (!customData)
{
_log.config("NpcTable: (Re)Loaded " + count + " NPC template(s).");
}
else
{
_log.config("NpcTable: (Re)Loaded " + count + " custom NPC template(s).");
}
}
}
public void reloadNpc(int id)
{
try (Connection con = L2DatabaseFactory.getInstance().getConnection())
{
// save a copy of the old data
final L2NpcTemplate old = getTemplate(id);
final Map<Integer, L2Skill> skills = new FastMap<>();
if (old.getSkills() != null)
{
skills.putAll(old.getSkills());
}
final FastList<L2DropCategory> categories = new FastList<>();
if (old.getDropData() != null)
{
categories.addAll(old.getDropData());
}
ClassId[] classIds = null;
if (old.getTeachInfo() != null)
{
classIds = old.getTeachInfo().clone();
}
final List<L2MinionData> minions = new FastList<>();
if (old.getMinionData() != null)
{
minions.addAll(old.getMinionData());
}
// reload the NPC base data
try (PreparedStatement st = con.prepareStatement("SELECT " + L2DatabaseFactory.getInstance().safetyString(new String[]
{
"id",
"idTemplate",
"name",
"serverSideName",
"title",
"serverSideTitle",
"class",
"collision_radius",
"collision_height",
"level",
"sex",
"type",
"attackrange",
"hp",
"mp",
"hpreg",
"mpreg",
"str",
"con",
"dex",
"int",
"wit",
"men",
"exp",
"sp",
"patk",
"pdef",
"matk",
"mdef",
"atkspd",
"aggro",
"matkspd",
"rhand",
"lhand",
"armor",
"walkspd",
"runspd",
"faction_id",
"faction_range",
"isUndead",
"absorb_level",
"ss",
"bss",
"ss_rate",
"AI"
}) + " FROM npc WHERE id=?"))
{
st.setInt(1, id);
try (ResultSet rs = st.executeQuery())
{
fillNpcTable(rs, false);
}
}
if (Config.CUSTOM_NPC_TABLE) // reload certain NPCs
{
try (PreparedStatement st = con.prepareStatement("SELECT " + L2DatabaseFactory.getInstance().safetyString(new String[]
{
"id",
"idTemplate",
"name",
"serverSideName",
"title",
"serverSideTitle",
"class",
"collision_radius",
"collision_height",
"level",
"sex",
"type",
"attackrange",
"hp",
"mp",
"hpreg",
"mpreg",
"str",
"con",
"dex",
"int",
"wit",
"men",
"exp",
"sp",
"patk",
"pdef",
"matk",
"mdef",
"atkspd",
"aggro",
"matkspd",
"rhand",
"lhand",
"armor",
"walkspd",
"runspd",
"faction_id",
"faction_range",
"isUndead",
"absorb_level",
"ss",
"bss",
"ss_rate",
"AI"
}) + " FROM custom_npc WHERE id=?"))
{
st.setInt(1, id);
try (ResultSet rs = st.executeQuery())
{
fillNpcTable(rs, true);
}
}
}
// restore additional data from saved copy
final L2NpcTemplate created = getTemplate(id);
// set race
created.setRace(old.race);
for (final L2Skill skill : skills.values())
{
created.addSkill(skill);
}
if (classIds != null)
{
for (final ClassId classId : classIds)
{
created.addTeachInfo(classId);
}
}
for (final L2MinionData minion : minions)
{
created.addRaidData(minion);
}
}
catch (final Exception e)
{
_log.warning("NPCTable: Could not reload data for NPC " + id + ": " + e);
}
}
// just wrapper
public void reloadAllNpc()
{
restoreNpcData();
}
public void saveNpc(StatsSet npc)
{
String query = "";
try (Connection con = L2DatabaseFactory.getInstance().getConnection())
{
final Map<String, Object> set = npc.getSet();
String name = "";
String values = "";
for (final Object obj : set.keySet())
{
name = (String) obj;
if (name.equalsIgnoreCase("npcId"))
{
continue;
}
if (!values.isEmpty())
{
values += ", ";
}
values += name + " = '" + set.get(name) + "'";
}
int updated = 0;
if (Config.CUSTOM_NPC_TABLE)
{
query = "UPDATE custom_npc SET " + values + " WHERE id = ?";
try (PreparedStatement statement = con.prepareStatement(query))
{
statement.setInt(1, npc.getInteger("npcId"));
updated = statement.executeUpdate();
}
}
if (updated == 0)
{
query = "UPDATE npc SET " + values + " WHERE id = ?";
try (PreparedStatement statement = con.prepareStatement(query))
{
statement.setInt(1, npc.getInteger("npcId"));
statement.executeUpdate();
}
}
}
catch (final Exception e)
{
_log.warning("NPCTable: Could not store new NPC data in database: " + e);
}
}
public boolean isInitialized()
{
return _initialized;
}
public void replaceTemplate(L2NpcTemplate npc)
{
_npcs.put(npc.npcId, npc);
}
public L2NpcTemplate getTemplate(int id)
{
return _npcs.get(id);
}
public L2NpcTemplate getTemplateByName(String name)
{
for (final L2NpcTemplate npcTemplate : _npcs.values())
{
if (npcTemplate.name.equalsIgnoreCase(name))
{
return npcTemplate;
}
}
return null;
}
public L2NpcTemplate[] getAllOfLevel(int lvl)
{
final List<L2NpcTemplate> list = new FastList<>();
for (final L2NpcTemplate t : _npcs.values())
{
if (t.level == lvl)
{
list.add(t);
}
}
return list.toArray(new L2NpcTemplate[list.size()]);
}
public L2NpcTemplate[] getAllMonstersOfLevel(int lvl)
{
final List<L2NpcTemplate> list = new FastList<>();
for (final L2NpcTemplate t : _npcs.values())
{
if ((t.level == lvl) && "L2Monster".equals(t.type))
{
list.add(t);
}
}
return list.toArray(new L2NpcTemplate[list.size()]);
}
public L2NpcTemplate[] getAllNpcStartingWith(String letter)
{
final List<L2NpcTemplate> list = new FastList<>();
for (final L2NpcTemplate t : _npcs.values())
{
if (t.name.startsWith(letter) && "L2Npc".equals(t.type))
{
list.add(t);
}
}
return list.toArray(new L2NpcTemplate[list.size()]);
}
}

View File

@@ -0,0 +1,104 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.logging.Logger;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.model.L2NpcWalkerNode;
import javolution.util.FastList;
/**
* Main Table to Load Npc Walkers Routes and Chat SQL Table.<br>
* @author Rayan RPG for L2Emu Project
* @since 927
*/
public class NpcWalkerRoutesTable
{
private static Logger _log = Logger.getLogger(NpcWalkerRoutesTable.class.getName());
private static NpcWalkerRoutesTable _instance;
private final FastList<L2NpcWalkerNode> _routes = new FastList<>();
public static NpcWalkerRoutesTable getInstance()
{
if (_instance == null)
{
_instance = new NpcWalkerRoutesTable();
_log.info("Initializing Walker Routes Table.");
}
return _instance;
}
private NpcWalkerRoutesTable()
{
load();
}
public void load()
{
_routes.clear();
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT route_id, npc_id, move_point, chatText, move_x, move_y, move_z, delay, running FROM walker_routes ORDER By move_point ASC");
ResultSet rset = statement.executeQuery())
{
L2NpcWalkerNode route;
while (rset.next())
{
route = new L2NpcWalkerNode();
route.setRouteId(rset.getInt("route_id"));
route.setNpcId(rset.getInt("npc_id"));
route.setMovePoint(rset.getString("move_point"));
route.setChatText(rset.getString("chatText"));
route.setMoveX(rset.getInt("move_x"));
route.setMoveY(rset.getInt("move_y"));
route.setMoveZ(rset.getInt("move_z"));
route.setDelay(rset.getInt("delay"));
route.setRunning(rset.getBoolean("running"));
_routes.add(route);
}
_log.info("WalkerRoutesTable: Loaded " + _routes.size() + " Npc Walker Routes.");
}
catch (final Exception e)
{
_log.warning("WalkerRoutesTable: Error while loading Npc Walkers Routes: " + e.getMessage());
}
}
public FastList<L2NpcWalkerNode> getRouteForNpc(int id)
{
final FastList<L2NpcWalkerNode> _return = new FastList<>();
for (FastList.Node<L2NpcWalkerNode> n = _routes.head(), end = _routes.tail(); (n = n.getNext()) != end;)
{
if (n.getValue().getNpcId() == id)
{
_return.add(n.getValue());
}
}
return _return;
}
}

View File

@@ -0,0 +1,265 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.l2jmobius.Config;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.LoginServerThread;
import com.l2jmobius.gameserver.model.L2ManufactureItem;
import com.l2jmobius.gameserver.model.L2ManufactureList;
import com.l2jmobius.gameserver.model.L2World;
import com.l2jmobius.gameserver.model.TradeList.TradeItem;
import com.l2jmobius.gameserver.model.actor.instance.L2PcInstance;
import com.l2jmobius.gameserver.network.L2GameClient;
import com.l2jmobius.gameserver.network.L2GameClient.GameClientState;
public class OfflineTradersTable
{
private static Logger _log = Logger.getLogger(OfflineTradersTable.class.getName());
// SQL DEFINITIONS
private static final String SAVE_OFFLINE_STATUS = "INSERT INTO character_offline_trade (`char_id`,`time`,`type`,`title`) VALUES (?,?,?,?)";
private static final String SAVE_ITEMS = "INSERT INTO character_offline_trade_items (`char_id`,`item`,`count`,`price`) VALUES (?,?,?,?)";
private static final String CLEAR_OFFLINE_TABLE = "DELETE FROM character_offline_trade";
private static final String CLEAR_OFFLINE_TABLE_ITEMS = "DELETE FROM character_offline_trade_items";
private static final String LOAD_OFFLINE_STATUS = "SELECT * FROM character_offline_trade";
private static final String LOAD_OFFLINE_ITEMS = "SELECT * FROM character_offline_trade_items WHERE char_id = ?";
public static void storeOffliners()
{
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement stm1 = con.prepareStatement(CLEAR_OFFLINE_TABLE);
PreparedStatement stm2 = con.prepareStatement(CLEAR_OFFLINE_TABLE_ITEMS);
PreparedStatement stm3 = con.prepareStatement(SAVE_OFFLINE_STATUS);
PreparedStatement stm_items = con.prepareStatement(SAVE_ITEMS))
{
stm1.execute();
stm2.execute();
con.setAutoCommit(false); // avoid halfway done
for (final L2PcInstance pc : L2World.getInstance().getAllPlayers())
{
try
{
if (pc.inOfflineMode())
{
stm3.setInt(1, pc.getObjectId()); // Char Id
stm3.setLong(2, pc.getOfflineStartTime());
stm3.setInt(3, pc.getPrivateStoreType()); // store type
String title = null;
switch (pc.getPrivateStoreType())
{
case L2PcInstance.STORE_PRIVATE_BUY:
if (!Config.OFFLINE_TRADE_ENABLE)
{
continue;
}
title = pc.getBuyList().getTitle();
for (final TradeItem i : pc.getBuyList().getItems())
{
stm_items.setInt(1, pc.getObjectId());
stm_items.setInt(2, i.getItem().getItemId());
stm_items.setInt(3, i.getCount());
stm_items.setInt(4, i.getPrice());
stm_items.executeUpdate();
stm_items.clearParameters();
}
break;
case L2PcInstance.STORE_PRIVATE_SELL:
case L2PcInstance.STORE_PRIVATE_PACKAGE_SELL:
if (!Config.OFFLINE_TRADE_ENABLE)
{
continue;
}
title = pc.getSellList().getTitle();
for (final TradeItem i : pc.getSellList().getItems())
{
stm_items.setInt(1, pc.getObjectId());
stm_items.setInt(2, i.getObjectId());
stm_items.setInt(3, i.getCount());
stm_items.setInt(4, i.getPrice());
stm_items.executeUpdate();
stm_items.clearParameters();
}
break;
case L2PcInstance.STORE_PRIVATE_MANUFACTURE:
if (!Config.OFFLINE_CRAFT_ENABLE)
{
continue;
}
title = pc.getCreateList().getStoreName();
for (final L2ManufactureItem i : pc.getCreateList().getList())
{
stm_items.setInt(1, pc.getObjectId());
stm_items.setInt(2, i.getRecipeId());
stm_items.setInt(3, 0);
stm_items.setInt(4, i.getCost());
stm_items.executeUpdate();
stm_items.clearParameters();
}
}
stm3.setString(4, title);
stm3.executeUpdate();
stm3.clearParameters();
con.commit(); // flush
}
}
catch (final Exception e)
{
_log.log(Level.WARNING, "OfflineTradersTable[storeTradeItems()]: Error while saving offline trader: " + pc.getObjectId() + " " + e, e);
}
}
_log.info("Offline traders stored.");
}
catch (final Exception e)
{
_log.log(Level.WARNING, "OfflineTradersTable[storeTradeItems()]: Error while saving offline traders: " + e, e);
}
}
public static void restoreOfflineTraders()
{
_log.info("Loading offline traders...");
int nTraders = 0;
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement stm = con.prepareStatement(LOAD_OFFLINE_STATUS);
ResultSet rs = stm.executeQuery())
{
while (rs.next())
{
final long time = rs.getLong("time");
if (Config.OFFLINE_MAX_DAYS > 0)
{
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time);
cal.add(Calendar.DAY_OF_YEAR, Config.OFFLINE_MAX_DAYS);
if (cal.getTimeInMillis() <= System.currentTimeMillis())
{
continue;
}
}
final int type = rs.getInt("type");
if (type == L2PcInstance.STORE_PRIVATE_NONE)
{
continue;
}
L2PcInstance player = null;
try
{
final L2GameClient client = new L2GameClient(null);
client.setDetached(true);
player = L2PcInstance.load(rs.getInt("char_id"));
client.setActiveChar(player);
client.setAccountName(player.getAccountName());
client.setState(GameClientState.IN_GAME);
player.setClient(client);
player.setOfflineStartTime(time);
player.spawnMe(player.getX(), player.getY(), player.getZ());
LoginServerThread.getInstance().addGameServerLogin(player.getAccountName(), client);
try (PreparedStatement stm_items = con.prepareStatement(LOAD_OFFLINE_ITEMS))
{
stm_items.setInt(1, player.getObjectId());
try (ResultSet items = stm_items.executeQuery())
{
switch (type)
{
case L2PcInstance.STORE_PRIVATE_BUY:
while (items.next())
{
if (player.getBuyList().addItemByItemId(items.getInt(2), items.getInt(3), items.getInt(4)) == null)
{
throw new NullPointerException();
}
}
player.getBuyList().setTitle(rs.getString("title"));
break;
case L2PcInstance.STORE_PRIVATE_SELL:
case L2PcInstance.STORE_PRIVATE_PACKAGE_SELL:
while (items.next())
{
if (player.getSellList().addItem(items.getInt(2), items.getInt(3), items.getInt(4)) == null)
{
throw new NullPointerException();
}
}
player.getSellList().setTitle(rs.getString("title"));
player.getSellList().setPackaged(type == L2PcInstance.STORE_PRIVATE_PACKAGE_SELL);
break;
case L2PcInstance.STORE_PRIVATE_MANUFACTURE:
final L2ManufactureList createList = new L2ManufactureList();
while (items.next())
{
createList.add(new L2ManufactureItem(items.getInt(2), items.getInt(4)));
}
player.setCreateList(createList);
player.getCreateList().setStoreName(rs.getString("title"));
break;
}
}
}
player.sitDown();
player.setInOfflineMode();
if (Config.OFFLINE_SET_NAME_COLOR)
{
player.getAppearance().setNameColor(Config.OFFLINE_NAME_COLOR);
}
player.setPrivateStoreType(type);
player.setOnlineStatus(true);
player.restoreEffects();
player.broadcastUserInfo();
nTraders++;
}
catch (final Exception e)
{
_log.log(Level.WARNING, "OfflineTradersTable[loadOffliners()]: Error loading trader: " + player, e);
if (player != null)
{
player.logout();
}
}
}
_log.info("Loaded: " + nTraders + " offline trader(s)");
try (Statement stm1 = con.createStatement())
{
stm1.execute(CLEAR_OFFLINE_TABLE);
stm1.execute(CLEAR_OFFLINE_TABLE_ITEMS);
}
}
catch (final Exception e)
{
_log.log(Level.WARNING, "OfflineTradersTable[loadOffliners()]: Error while loading offline traders: ", e);
}
}
}

View File

@@ -0,0 +1,120 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import com.l2jmobius.Config;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.model.L2PetDataTable;
public class PetNameTable
{
private static Logger _log = Logger.getLogger(PetNameTable.class.getName());
private static PetNameTable _instance;
public static PetNameTable getInstance()
{
if (_instance == null)
{
_instance = new PetNameTable();
}
return _instance;
}
public boolean doesPetNameExist(String name, int petNpcId)
{
boolean result = true;
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT name FROM pets p, items i WHERE p.item_obj_id = i.object_id AND name=? AND i.item_id IN (?)"))
{
statement.setString(1, name);
String cond = "";
for (final int it : L2PetDataTable.getPetItemsAsNpc(petNpcId))
{
if (!cond.isEmpty())
{
cond += ", ";
}
cond += it;
}
statement.setString(2, cond);
try (ResultSet rset = statement.executeQuery())
{
result = rset.next();
}
}
catch (final SQLException e)
{
_log.warning("could not check existing petname:" + e.getMessage());
}
return result;
}
public boolean isValidPetName(String name)
{
boolean result = true;
if (!isAlphaNumeric(name))
{
return result;
}
Pattern pattern;
try
{
pattern = Pattern.compile(Config.PET_NAME_TEMPLATE);
}
catch (final PatternSyntaxException e) // case of illegal pattern
{
_log.warning("ERROR : Pet name pattern of config is wrong!");
pattern = Pattern.compile(".*");
}
final Matcher regexp = pattern.matcher(name);
if (!regexp.matches())
{
result = false;
}
return result;
}
private boolean isAlphaNumeric(String text)
{
boolean result = true;
final char[] chars = text.toCharArray();
for (int i = 0; i < chars.length; i++)
{
if (!Character.isLetterOrDigit(chars[i]))
{
result = false;
break;
}
}
return result;
}
}

View File

@@ -0,0 +1,81 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;
import java.util.logging.Logger;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.model.L2Skill;
import javolution.util.FastMap;
public class SkillSpellbookTable
{
private static Logger _log = Logger.getLogger(SkillTreeTable.class.getName());
private static SkillSpellbookTable _instance;
private static Map<Integer, Integer> _skillSpellbooks;
public static SkillSpellbookTable getInstance()
{
if (_instance == null)
{
_instance = new SkillSpellbookTable();
}
return _instance;
}
private SkillSpellbookTable()
{
_skillSpellbooks = new FastMap<>();
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT skill_id, item_id FROM skill_spellbooks");
ResultSet spbooks = statement.executeQuery())
{
while (spbooks.next())
{
_skillSpellbooks.put(spbooks.getInt("skill_id"), spbooks.getInt("item_id"));
}
_log.config("SkillSpellbookTable: Loaded " + _skillSpellbooks.size() + " Spellbooks.");
}
catch (final Exception e)
{
_log.warning("Error while loading spellbook data: " + e);
}
}
public int getBookForSkill(int skillId)
{
if (!_skillSpellbooks.containsKey(skillId))
{
return -1;
}
return _skillSpellbooks.get(skillId);
}
public int getBookForSkill(L2Skill skill)
{
return getBookForSkill(skill.getId());
}
}

View File

@@ -0,0 +1,143 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.util.HashMap;
import java.util.Map;
import com.l2jmobius.gameserver.model.L2Skill;
import com.l2jmobius.gameserver.skills.SkillsEngine;
import com.l2jmobius.gameserver.templates.L2WeaponType;
import gnu.trove.map.hash.TIntIntHashMap;
/**
*
*/
public class SkillTable
{
private static SkillTable _instance;
private final Map<Integer, L2Skill> _skills;
private final TIntIntHashMap _skillMaxLevel;
public static SkillTable getInstance()
{
if (_instance == null)
{
_instance = new SkillTable();
}
return _instance;
}
private SkillTable()
{
_skills = new HashMap<>();
_skillMaxLevel = new TIntIntHashMap();
reload();
}
public void reload()
{
_skills.clear();
SkillsEngine.getInstance().loadAllSkills(_skills);
_skillMaxLevel.clear();
for (final L2Skill skill : _skills.values())
{
final int skillLvl = skill.getLevel();
if (skillLvl > 99)
{
continue;
}
final int skillId = skill.getId();
final int maxLvl = _skillMaxLevel.get(skillId);
if (skillLvl > maxLvl)
{
_skillMaxLevel.put(skillId, skillLvl);
}
}
}
/**
* Provides the skill hash
* @param skill The L2Skill to be hashed
* @return getSkillHashCode(skill.getId(), skill.getLevel())
*/
public static int getSkillHashCode(L2Skill skill)
{
return getSkillHashCode(skill.getId(), skill.getLevel());
}
/**
* Centralized method for easier change of the hashing sys
* @param skillId The Skill Id
* @param skillLevel The Skill Level
* @return The Skill hash number
*/
public static int getSkillHashCode(int skillId, int skillLevel)
{
return (skillId * 256) + skillLevel;
}
public final L2Skill getInfo(final int skillId, final int level)
{
return _skills.get(getSkillHashCode(skillId, level));
}
public final int getMaxLevel(final int skillId)
{
return _skillMaxLevel.get(skillId);
}
private static final L2WeaponType[] weaponDbMasks =
{
L2WeaponType.ETC,
L2WeaponType.BOW,
L2WeaponType.POLE,
L2WeaponType.DUALFIST,
L2WeaponType.DUAL,
L2WeaponType.BLUNT,
L2WeaponType.SWORD,
L2WeaponType.DAGGER,
L2WeaponType.BIGSWORD,
L2WeaponType.ROD,
L2WeaponType.BIGBLUNT
};
public int calcWeaponsAllowed(int mask)
{
if (mask == 0)
{
return 0;
}
int weaponsAllowed = 0;
for (int i = 0; i < weaponDbMasks.length; i++)
{
if ((mask & (1 << i)) != 0)
{
weaponsAllowed |= weaponDbMasks[i].mask();
}
}
return weaponsAllowed;
}
}

View File

@@ -0,0 +1,761 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.model.L2EnchantSkillLearn;
import com.l2jmobius.gameserver.model.L2Skill;
import com.l2jmobius.gameserver.model.L2SkillLearn;
import com.l2jmobius.gameserver.model.actor.instance.L2PcInstance;
import com.l2jmobius.gameserver.model.base.ClassId;
import gnu.trove.map.hash.TIntObjectHashMap;
import javolution.util.FastList;
import javolution.util.FastMap;
/**
* This class ...
* @version $Revision: 1.13.2.2.2.8 $ $Date: 2005/04/06 16:13:25 $
*/
public class SkillTreeTable
{
private static Logger _log = Logger.getLogger(SkillTreeTable.class.getName());
private static SkillTreeTable _instance;
private Map<ClassId, Map<Integer, L2SkillLearn>> _skillTrees;
private List<L2SkillLearn> _fishingSkillTrees; // all common skills (teached by Fisherman)
private List<L2SkillLearn> _expandDwarfCraftSkillTrees; // list of special skill for dwarf (expand dwarf craft) learned by class teacher
private Map<Integer, L2EnchantSkillLearn> _enchantSkillTrees; // enchant skill list
// checker, sorted arrays of hashcodes
private TIntObjectHashMap<int[]> _skillsByClassIdHashCodes; // occupation skills
private int[] _allSkillsHashCodes; // fishing, and special
private boolean _loading = true;
public static SkillTreeTable getInstance()
{
if (_instance == null)
{
_instance = new SkillTreeTable();
}
return _instance;
}
/**
* Return the minimum level needed to have this Expertise.<BR>
* <BR>
* @param grade The grade level searched
* @return
*/
public int getExpertiseLevel(int grade)
{
if (grade <= 0)
{
return 0;
}
// since expertise comes at same level for all classes we use paladin for now
final Map<Integer, L2SkillLearn> learnMap = getSkillTrees().get(ClassId.paladin);
final int skillHashCode = SkillTable.getSkillHashCode(239, grade);
if (learnMap.containsKey(skillHashCode))
{
return learnMap.get(skillHashCode).getMinLevel();
}
_log.severe("Expertise not found for grade " + grade);
return 0;
}
/**
* Each class receives new skill on certain levels, this methods allow the retrieval of the minimun character level of given class required to learn a given skill
* @param skillId The iD of the skill
* @param classId The classId of the character
* @param skillLvl The SkillLvl
* @return The min level
*/
public int getMinSkillLevel(int skillId, ClassId classId, int skillLvl)
{
final Map<Integer, L2SkillLearn> map = getSkillTrees().get(classId);
final int skillHashCode = SkillTable.getSkillHashCode(skillId, skillLvl);
if (map.containsKey(skillHashCode))
{
return map.get(skillHashCode).getMinLevel();
}
return 0;
}
public int getMinSkillLevel(int skillId, int skillLvl)
{
final int skillHashCode = SkillTable.getSkillHashCode(skillId, skillLvl);
// Look on all classes for this skill (takes the first one found)
for (final Map<Integer, L2SkillLearn> map : getSkillTrees().values())
{
// checks if the current class has this skill
if (map.containsKey(skillHashCode))
{
return map.get(skillHashCode).getMinLevel();
}
}
return 0;
}
private SkillTreeTable()
{
_loading = true;
int classId = 0;
int count = 0;
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT * FROM class_list ORDER BY id");
ResultSet classlist = statement.executeQuery())
{
Map<Integer, L2SkillLearn> map;
int parentClassId;
L2SkillLearn skillLearn;
while (classlist.next())
{
map = new FastMap<>();
parentClassId = classlist.getInt("parent_id");
classId = classlist.getInt("id");
if (parentClassId != -1)
{
final Map<Integer, L2SkillLearn> parentMap = getSkillTrees().get(ClassId.values()[parentClassId]);
map.putAll(parentMap);
}
try (PreparedStatement statement2 = con.prepareStatement("SELECT class_id, skill_id, level, name, sp, min_level FROM skill_trees where class_id=? ORDER BY skill_id, level"))
{
statement2.setInt(1, classId);
try (ResultSet skilltree = statement2.executeQuery())
{
int prevSkillId = -1;
while (skilltree.next())
{
final int id = skilltree.getInt("skill_id");
final int lvl = skilltree.getInt("level");
final String name = skilltree.getString("name");
final int minLvl = skilltree.getInt("min_level");
final int cost = skilltree.getInt("sp");
if (prevSkillId != id)
{
prevSkillId = id;
}
skillLearn = new L2SkillLearn(id, lvl, minLvl, name, cost, 0, 0);
map.put(SkillTable.getSkillHashCode(id, lvl), skillLearn);
}
}
}
getSkillTrees().put(ClassId.values()[classId], map);
count += map.size();
_log.fine("SkillTreeTable: skill tree for class " + classId + " has " + map.size() + " skills");
}
}
catch (final Exception e)
{
_log.severe("Error while creating skill tree (Class ID " + classId + "):" + e);
}
_log.config("SkillTreeTable: Loaded " + count + " skills.");
// Skill tree for fishing skill (from Fisherman)
int count2 = 0;
int count3 = 0;
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT skill_id, level, name, sp, min_level, costid, cost, isfordwarf FROM fishing_skill_trees ORDER BY skill_id, level");
ResultSet skilltree2 = statement.executeQuery())
{
_fishingSkillTrees = new FastList<>();
_expandDwarfCraftSkillTrees = new FastList<>();
int prevSkillId = -1;
while (skilltree2.next())
{
final int id = skilltree2.getInt("skill_id");
final int lvl = skilltree2.getInt("level");
final String name = skilltree2.getString("name");
final int minLvl = skilltree2.getInt("min_level");
final int cost = skilltree2.getInt("sp");
final int costId = skilltree2.getInt("costid");
final int costCount = skilltree2.getInt("cost");
final int isDwarven = skilltree2.getInt("isfordwarf");
if (prevSkillId != id)
{
prevSkillId = id;
}
final L2SkillLearn skill = new L2SkillLearn(id, lvl, minLvl, name, cost, costId, costCount);
if (isDwarven == 0)
{
_fishingSkillTrees.add(skill);
}
else
{
_expandDwarfCraftSkillTrees.add(skill);
}
}
count2 = _fishingSkillTrees.size();
count3 = _expandDwarfCraftSkillTrees.size();
}
catch (final Exception e)
{
_log.severe("Error while creating fishing skill table: " + e);
}
int count4 = 0;
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT skill_id, level, name, base_lvl, sp, min_skill_lvl, exp, success_rate76, success_rate77, success_rate78 FROM enchant_skill_trees ORDER BY skill_id, level");
ResultSet skilltree3 = statement.executeQuery())
{
_enchantSkillTrees = new FastMap<>();
int prevSkillId = -1;
while (skilltree3.next())
{
final int id = skilltree3.getInt("skill_id");
final int lvl = skilltree3.getInt("level");
final String name = skilltree3.getString("name");
final int baseLvl = skilltree3.getInt("base_lvl");
final int minSkillLvl = skilltree3.getInt("min_skill_lvl");
final int sp = skilltree3.getInt("sp");
final int exp = skilltree3.getInt("exp");
final byte rate76 = skilltree3.getByte("success_rate76");
final byte rate77 = skilltree3.getByte("success_rate77");
final byte rate78 = skilltree3.getByte("success_rate78");
if (prevSkillId != id)
{
prevSkillId = id;
}
final L2EnchantSkillLearn skill = new L2EnchantSkillLearn(id, lvl, minSkillLvl, baseLvl, name, sp, exp, rate76, rate77, rate78);
_enchantSkillTrees.put(SkillTable.getSkillHashCode(id, lvl), skill);
}
count4 = _enchantSkillTrees.size();
}
catch (final Exception e)
{
_log.severe("Error while creating enchant skill table: " + e);
}
generateCheckArrays();
_log.config("FishingSkillTreeTable: Loaded " + count2 + " general skills.");
_log.config("FishingSkillTreeTable: Loaded " + count3 + " dwarven skills.");
_log.config("EnchantSkillTreeTable: Loaded " + count4 + " enchant skills.");
_loading = false;
}
private void generateCheckArrays()
{
int i;
int[] array;
// class-specific skills
Map<Integer, L2SkillLearn> tempMap;
final TIntObjectHashMap<int[]> result = new TIntObjectHashMap<>(_skillTrees.keySet().size());
for (final ClassId cls : _skillTrees.keySet())
{
i = 0;
tempMap = _skillTrees.get(cls);
array = new int[tempMap.size()];
for (final int h : tempMap.keySet())
{
array[i++] = h;
}
Arrays.sort(array);
result.put(cls.ordinal(), array);
}
_skillsByClassIdHashCodes = result;
// skills available for all classes and races
final FastList<Integer> list = FastList.newInstance();
for (final L2SkillLearn s : _fishingSkillTrees)
{
list.add(SkillTable.getSkillHashCode(s.getId(), s.getLevel()));
}
for (final L2SkillLearn s : _expandDwarfCraftSkillTrees)
{
list.add(SkillTable.getSkillHashCode(s.getId(), s.getLevel()));
}
i = 0;
array = new int[list.size()];
for (final int s : list)
{
array[i++] = s;
}
Arrays.sort(array);
_allSkillsHashCodes = array;
FastList.recycle(list);
}
private Map<ClassId, Map<Integer, L2SkillLearn>> getSkillTrees()
{
if (_skillTrees == null)
{
_skillTrees = new FastMap<>();
}
return _skillTrees;
}
public L2SkillLearn[] getMaxAvailableSkills(L2PcInstance cha, ClassId classId)
{
final Map<Integer, L2SkillLearn> result = new FastMap<>();
final Collection<L2SkillLearn> skills = getSkillTrees().get(classId).values();
if (skills == null)
{
// the skilltree for this class is undefined, so we give an empty list
_log.warning("Skilltree for class " + classId + " is not defined !");
return new L2SkillLearn[0];
}
final L2Skill[] oldSkills = cha.getAllSkills();
for (final L2SkillLearn temp : skills)
{
if (temp.getMinLevel() <= cha.getLevel())
{
boolean knownSkill = false;
for (int j = 0; (j < oldSkills.length) && !knownSkill; j++)
{
if (oldSkills[j].getId() == temp.getId())
{
knownSkill = true;
if (oldSkills[j].getLevel() < temp.getLevel())
{
// this is the next level of a skill that we know
result.put(temp.getId(), temp);
}
}
}
if (!knownSkill)
{
// this is a new skill
result.put(temp.getId(), temp);
}
}
}
return result.values().toArray(new L2SkillLearn[result.size()]);
}
public L2SkillLearn[] getAvailableSkills(L2PcInstance cha, ClassId classId)
{
final List<L2SkillLearn> result = new FastList<>();
final Collection<L2SkillLearn> skills = getSkillTrees().get(classId).values();
if (skills == null)
{
// the skilltree for this class is undefined, so we give an empty list
_log.warning("Skilltree for class " + classId + " is not defined !");
return new L2SkillLearn[0];
}
final L2Skill[] oldSkills = cha.getAllSkills();
for (final L2SkillLearn temp : skills)
{
if (temp.getMinLevel() <= cha.getLevel())
{
boolean knownSkill = false;
for (int j = 0; (j < oldSkills.length) && !knownSkill; j++)
{
if (oldSkills[j].getId() == temp.getId())
{
knownSkill = true;
if (oldSkills[j].getLevel() == (temp.getLevel() - 1))
{
// this is the next level of a skill that we know
result.add(temp);
}
}
}
if (!knownSkill && (temp.getLevel() == 1))
{
// this is a new skill
result.add(temp);
}
}
}
return result.toArray(new L2SkillLearn[result.size()]);
}
public L2SkillLearn[] getAvailableSkills(L2PcInstance cha)
{
final List<L2SkillLearn> result = new FastList<>();
final List<L2SkillLearn> skills = new FastList<>();
skills.addAll(_fishingSkillTrees);
// if (skills == null)
// {
// // the skilltree for this class is undefined, so we give an empty list
// _log.warning("Skilltree for fishing is not defined !");
// return new L2SkillLearn[0];
// }
if (cha.hasDwarvenCraft() && (_expandDwarfCraftSkillTrees != null))
{
skills.addAll(_expandDwarfCraftSkillTrees);
}
final L2Skill[] oldSkills = cha.getAllSkills();
for (final L2SkillLearn temp : skills)
{
if (temp.getMinLevel() <= cha.getLevel())
{
boolean knownSkill = false;
for (int j = 0; (j < oldSkills.length) && !knownSkill; j++)
{
if (oldSkills[j].getId() == temp.getId())
{
knownSkill = true;
if (oldSkills[j].getLevel() == (temp.getLevel() - 1))
{
// this is the next level of a skill that we know
result.add(temp);
}
}
}
if (!knownSkill && (temp.getLevel() == 1))
{
// this is a new skill
result.add(temp);
}
}
}
return result.toArray(new L2SkillLearn[result.size()]);
}
public L2EnchantSkillLearn[] getAvailableEnchantSkills(L2PcInstance cha)
{
final List<L2EnchantSkillLearn> result = new FastList<>();
final Map<Integer, L2EnchantSkillLearn> skills = new FastMap<>();
skills.putAll(_enchantSkillTrees);
// if (skills == null)
// {
// // the skilltree for this class is undefined, so we give an empty list
// _log.warning("Skilltree for enchanting is not defined !");
// return new L2EnchantSkillLearn[0];
// }
final L2Skill[] oldSkills = cha.getAllSkills();
for (final L2EnchantSkillLearn temp : skills.values())
{
if (cha.getLevel() >= 76)
{
boolean knownSkill = false;
for (int j = 0; (j < oldSkills.length) && !knownSkill; j++)
{
if (oldSkills[j].getId() == temp.getId())
{
knownSkill = true;
if (oldSkills[j].getLevel() == temp.getMinSkillLevel())
{
// this is the next level of a skill that we know
result.add(temp);
}
}
}
}
}
return result.toArray(new L2EnchantSkillLearn[result.size()]);
}
/**
* Returns all allowed skills for a given class.
* @param classId
* @return all allowed skills for a given class.
*/
public Collection<L2SkillLearn> getAllowedSkills(ClassId classId)
{
return getSkillTrees().get(classId).values();
}
public int getMinLevelForNewSkill(L2PcInstance cha, ClassId classId)
{
int minLevel = 0;
final Collection<L2SkillLearn> skills = getSkillTrees().get(classId).values();
if (skills == null)
{
// the skilltree for this class is undefined, so we give an empty list
_log.warning("Skilltree for class " + classId + " is not defined !");
return minLevel;
}
for (final L2SkillLearn temp : skills)
{
if ((temp.getMinLevel() > cha.getLevel()) && (temp.getSpCost() != 0))
{
if ((minLevel == 0) || (temp.getMinLevel() < minLevel))
{
minLevel = temp.getMinLevel();
}
}
}
return minLevel;
}
public int getMinLevelForNewSkill(L2PcInstance cha)
{
int minLevel = 0;
final List<L2SkillLearn> skills = new FastList<>();
skills.addAll(_fishingSkillTrees);
// if (skills == null)
// {
// // the skilltree for this class is undefined, so we give an empty list
// _log.warning("SkillTree for fishing is not defined!");
// return minLevel;
// }
if (cha.hasDwarvenCraft() && (_expandDwarfCraftSkillTrees != null))
{
skills.addAll(_expandDwarfCraftSkillTrees);
}
for (final L2SkillLearn s : skills)
{
if (s.getMinLevel() > cha.getLevel())
{
if ((minLevel == 0) || (s.getMinLevel() < minLevel))
{
minLevel = s.getMinLevel();
}
}
}
return minLevel;
}
public int getSkillCost(L2PcInstance player, L2Skill skill)
{
int skillCost = 100000000;
final ClassId classId = player.getSkillLearningClassId();
final int skillHashCode = SkillTable.getSkillHashCode(skill);
if (getSkillTrees().get(classId).containsKey(skillHashCode))
{
final L2SkillLearn skillLearn = getSkillTrees().get(classId).get(skillHashCode);
if (skillLearn.getMinLevel() <= player.getLevel())
{
skillCost = skillLearn.getSpCost();
if (!player.getClassId().equalsOrChildOf(classId))
{
if (skill.getCrossLearnAdd() < 0)
{
return skillCost;
}
skillCost += skill.getCrossLearnAdd();
skillCost *= skill.getCrossLearnMul();
}
if ((classId.getRace() != player.getRace()) && !player.isSubClassActive())
{
skillCost *= skill.getCrossLearnRace();
}
if (classId.isMage() != player.getClassId().isMage())
{
skillCost *= skill.getCrossLearnProf();
}
}
}
return skillCost;
}
public int getSkillSpCost(L2PcInstance player, L2Skill skill)
{
int skillCost = 100000000;
final L2EnchantSkillLearn[] enchantSkillLearnList = getAvailableEnchantSkills(player);
for (final L2EnchantSkillLearn enchantSkillLearn : enchantSkillLearnList)
{
if (enchantSkillLearn.getId() != skill.getId())
{
continue;
}
if (enchantSkillLearn.getLevel() != skill.getLevel())
{
continue;
}
if (player.getLevel() < 76)
{
continue;
}
skillCost = enchantSkillLearn.getSpCost();
}
return skillCost;
}
public int getSkillExpCost(L2PcInstance player, L2Skill skill)
{
int skillCost = 100000000;
final L2EnchantSkillLearn[] enchantSkillLearnList = getAvailableEnchantSkills(player);
for (final L2EnchantSkillLearn enchantSkillLearn : enchantSkillLearnList)
{
if (enchantSkillLearn.getId() != skill.getId())
{
continue;
}
if (enchantSkillLearn.getLevel() != skill.getLevel())
{
continue;
}
if (player.getLevel() < 76)
{
continue;
}
skillCost = enchantSkillLearn.getExp();
}
return skillCost;
}
public byte getSkillRate(L2PcInstance player, L2Skill skill)
{
final L2EnchantSkillLearn[] enchantSkillLearnList = getAvailableEnchantSkills(player);
for (final L2EnchantSkillLearn enchantSkillLearn : enchantSkillLearnList)
{
if (enchantSkillLearn.getId() != skill.getId())
{
continue;
}
if (enchantSkillLearn.getLevel() != skill.getLevel())
{
continue;
}
return enchantSkillLearn.getRate(player);
}
return 0;
}
public boolean isSkillAllowed(L2PcInstance player, L2Skill skill)
{
if (player.isGM())
{
return true;
}
if (_loading)
{
return true;
}
int level = skill.getLevel();
final int maxLvl = SkillTable.getInstance().getMaxLevel(skill.getId());
int hashCode = SkillTable.getSkillHashCode(skill.getId(), level);
if (_enchantSkillTrees.get(hashCode) != null)
{
level = _enchantSkillTrees.get(hashCode).getBaseLevel();
}
hashCode = SkillTable.getSkillHashCode(skill.getId(), Math.min(level, maxLvl));
if (Arrays.binarySearch(_skillsByClassIdHashCodes.get(player.getClassId().ordinal()), hashCode) >= 0)
{
return true;
}
if (Arrays.binarySearch(_allSkillsHashCodes, hashCode) >= 0)
{
return true;
}
return false;
}
}

View File

@@ -0,0 +1,325 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;
import java.util.logging.Logger;
import com.l2jmobius.Config;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.instancemanager.DayNightSpawnManager;
import com.l2jmobius.gameserver.model.L2Spawn;
import com.l2jmobius.gameserver.model.actor.instance.L2PcInstance;
import com.l2jmobius.gameserver.templates.L2NpcTemplate;
import javolution.util.FastMap;
/**
* This class ...
* @author Nightmare
* @version $Revision: 1.5.2.6.2.7 $ $Date: 2005/03/27 15:29:18 $
*/
public class SpawnTable
{
private static Logger _log = Logger.getLogger(SpawnTable.class.getName());
private static final SpawnTable _instance = new SpawnTable();
private final Map<Integer, L2Spawn> _spawntable = new FastMap<Integer, L2Spawn>().shared();
private int _npcSpawnCount;
private int _customSpawnCount;
private int _highestId;
public static SpawnTable getInstance()
{
return _instance;
}
private SpawnTable()
{
if (!Config.ALT_DEV_NO_SPAWNS)
{
fillSpawnTable();
}
}
public Map<Integer, L2Spawn> getSpawnTable()
{
return _spawntable;
}
private void fillSpawnTable()
{
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT id, count, npc_templateid, locx, locy, locz, heading, respawn_delay, loc_id, periodOfDay FROM spawnlist ORDER BY id");
ResultSet rset = statement.executeQuery())
{
L2Spawn spawnDat;
L2NpcTemplate template1;
while (rset.next())
{
template1 = NpcTable.getInstance().getTemplate(rset.getInt("npc_templateid"));
if (template1 != null)
{
if (template1.type.equalsIgnoreCase("L2SiegeGuard"))
{
// Don't spawn
}
else if (template1.type.equalsIgnoreCase("L2RaidBoss"))
{
// Don't spawn raidboss
}
else if (!Config.ALLOW_CLASS_MASTERS && template1.type.equals("L2ClassMaster"))
{
// Don't spawn class masters
}
else
{
spawnDat = new L2Spawn(template1);
spawnDat.setId(rset.getInt("id"));
spawnDat.setAmount(rset.getInt("count"));
spawnDat.setLocx(rset.getInt("locx"));
spawnDat.setLocy(rset.getInt("locy"));
spawnDat.setLocz(rset.getInt("locz"));
spawnDat.setHeading(rset.getInt("heading"));
spawnDat.setRespawnDelay(rset.getInt("respawn_delay"));
final int loc_id = rset.getInt("loc_id");
spawnDat.setLocation(loc_id);
switch (rset.getInt("periodOfDay"))
{
case 0: // default
_npcSpawnCount += spawnDat.init();
break;
case 1: // Day
DayNightSpawnManager.getInstance().addDayCreature(spawnDat);
_npcSpawnCount++;
break;
case 2: // Night
DayNightSpawnManager.getInstance().addNightCreature(spawnDat);
_npcSpawnCount++;
break;
}
_spawntable.put(spawnDat.getId(), spawnDat);
if (spawnDat.getId() > _highestId)
{
_highestId = spawnDat.getId();
}
}
}
else
{
_log.warning("SpawnTable: Data missing in NPC table for ID: " + rset.getInt("npc_templateid") + ".");
}
}
}
catch (final Exception e)
{
// problem with initializing spawn, go to next one
_log.warning("SpawnTable: Spawn could not be initialized: " + e);
}
_log.config("SpawnTable: Loaded " + _spawntable.size() + " Npc Spawn Locations.");
if (Config.CUSTOM_SPAWNLIST_TABLE)
{
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT id, count, npc_templateid, locx, locy, locz, heading, respawn_delay, loc_id, periodOfDay FROM custom_spawnlist ORDER BY id");
ResultSet rset = statement.executeQuery())
{
L2Spawn spawnDat;
L2NpcTemplate template1;
while (rset.next())
{
template1 = NpcTable.getInstance().getTemplate(rset.getInt("npc_templateid"));
if (template1 != null)
{
if (template1.type.equalsIgnoreCase("L2SiegeGuard"))
{
// Don't spawn
}
else if (template1.type.equalsIgnoreCase("L2RaidBoss"))
{
// Don't spawn raidboss
}
else if (!Config.ALLOW_CLASS_MASTERS && template1.type.equals("L2ClassMaster"))
{
// Don't spawn class masters
}
else
{
spawnDat = new L2Spawn(template1);
spawnDat.setId(rset.getInt("id"));
spawnDat.setAmount(rset.getInt("count"));
spawnDat.setLocx(rset.getInt("locx"));
spawnDat.setLocy(rset.getInt("locy"));
spawnDat.setLocz(rset.getInt("locz"));
spawnDat.setHeading(rset.getInt("heading"));
spawnDat.setRespawnDelay(rset.getInt("respawn_delay"));
spawnDat.setCustom(true);
final int loc_id = rset.getInt("loc_id");
spawnDat.setLocation(loc_id);
switch (rset.getInt("periodOfDay"))
{
case 0: // default
_customSpawnCount += spawnDat.init();
break;
case 1: // Day
DayNightSpawnManager.getInstance().addDayCreature(spawnDat);
_customSpawnCount++;
break;
case 2: // Night
DayNightSpawnManager.getInstance().addNightCreature(spawnDat);
_customSpawnCount++;
break;
}
_spawntable.put(spawnDat.getId(), spawnDat);
if (spawnDat.getId() > _highestId)
{
_highestId = spawnDat.getId();
}
}
}
else
{
_log.warning("SpawnTable: Data missing in Custom NPC table for ID: " + rset.getInt("npc_templateid") + ".");
}
}
}
catch (final Exception e)
{
// problem with initializing custom spawn, go to next one
_log.warning("SpawnTable: Custom spawn could not be initialized: " + e);
}
_log.config("CustomSpawnTable: Loaded " + _customSpawnCount + " Custom Npc Spawn Locations.");
}
if (Config.DEBUG)
{
_log.fine("SpawnTable: Spawning completed, total number of NPCs in the world: " + (_npcSpawnCount + _customSpawnCount));
}
}
public L2Spawn getTemplate(int id)
{
return _spawntable.get(id);
}
public void addNewSpawn(L2Spawn spawn, boolean storeInDb)
{
_highestId++;
spawn.setId(_highestId);
_spawntable.put(_highestId, spawn);
if (storeInDb)
{
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("INSERT INTO " + (spawn.isCustom() ? "custom_spawnlist" : "spawnlist") + " (id,count,npc_templateid,locx,locy,locz,heading,respawn_delay,loc_id) values(?,?,?,?,?,?,?,?,?)"))
{
statement.setInt(1, spawn.getId());
statement.setInt(2, spawn.getAmount());
statement.setInt(3, spawn.getNpcid());
statement.setInt(4, spawn.getLocx());
statement.setInt(5, spawn.getLocy());
statement.setInt(6, spawn.getLocz());
statement.setInt(7, spawn.getHeading());
statement.setInt(8, spawn.getRespawnDelay() / 1000);
statement.setInt(9, spawn.getLocation());
statement.execute();
}
catch (final Exception e)
{
// problem with storing spawn
_log.warning("SpawnTable: Could not store spawn in the DB:" + e);
}
}
}
public void deleteSpawn(L2Spawn spawn, boolean updateDb)
{
if (_spawntable.remove(spawn.getId()) == null)
{
return;
}
if (updateDb)
{
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("DELETE FROM " + (spawn.isCustom() ? "custom_spawnlist" : "spawnlist") + " WHERE id=?"))
{
statement.setInt(1, spawn.getId());
statement.execute();
}
catch (final Exception e)
{
// problem with deleting spawn
_log.warning("SpawnTable: Spawn " + spawn.getId() + " could not be removed from DB: " + e);
}
}
}
// just wrapper
public void reloadAll()
{
fillSpawnTable();
}
/**
* Get all the spawn of a NPC<BR>
* <BR>
* @param activeChar
* @param npcId : ID of the NPC to find.
* @param teleportIndex
*/
public void findNPCInstances(L2PcInstance activeChar, int npcId, int teleportIndex)
{
int index = 0;
for (final L2Spawn spawn : _spawntable.values())
{
if (npcId == spawn.getNpcid())
{
index++;
if (teleportIndex > -1)
{
if (teleportIndex == index)
{
activeChar.teleToLocation(spawn.getLocx(), spawn.getLocy(), spawn.getLocz(), true);
}
}
else
{
activeChar.sendMessage(index + " - " + spawn.getTemplate().name + " (" + spawn.getId() + "): " + spawn.getLocx() + " " + spawn.getLocy() + " " + spawn.getLocz());
}
}
}
if (index == 0)
{
activeChar.sendMessage("No current spawns found.");
}
}
}

View File

@@ -0,0 +1,110 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.LineNumberReader;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import com.l2jmobius.Config;
import com.l2jmobius.gameserver.idfactory.IdFactory;
import com.l2jmobius.gameserver.model.actor.instance.L2StaticObjectInstance;
import javolution.util.FastMap;
public class StaticObjects
{
private static Logger _log = Logger.getLogger(StaticObjects.class.getName());
private static StaticObjects _instance;
private final Map<Integer, L2StaticObjectInstance> _staticObjects;
public static StaticObjects getInstance()
{
if (_instance == null)
{
_instance = new StaticObjects();
}
return _instance;
}
public StaticObjects()
{
_staticObjects = new FastMap<>();
parseData();
_log.config("StaticObject: Loaded " + _staticObjects.size() + " StaticObject Templates.");
}
private void parseData()
{
final File objectData = new File(Config.DATAPACK_ROOT, "data/staticobjects.csv");
try (FileReader fr = new FileReader(objectData);
BufferedReader br = new BufferedReader(fr);
LineNumberReader lnr = new LineNumberReader(br))
{
String line = null;
while ((line = lnr.readLine()) != null)
{
if ((line.trim().length() == 0) || line.startsWith("#"))
{
continue;
}
final L2StaticObjectInstance obj = parse(line);
_staticObjects.put(obj.getStaticObjectId(), obj);
}
}
catch (final FileNotFoundException e)
{
_log.warning("staticobjects.csv is missing in data folder");
}
catch (final Exception e)
{
_log.warning("error while creating StaticObjects table " + e);
}
}
public static L2StaticObjectInstance parse(String line)
{
final StringTokenizer st = new StringTokenizer(line, ";");
st.nextToken(); // Pass over static object name (not used in server)
final int id = Integer.parseInt(st.nextToken());
final int x = Integer.parseInt(st.nextToken());
final int y = Integer.parseInt(st.nextToken());
final int z = Integer.parseInt(st.nextToken());
final int type = Integer.parseInt(st.nextToken());
final String texture = st.nextToken();
final int map_x = Integer.parseInt(st.nextToken());
final int map_y = Integer.parseInt(st.nextToken());
final L2StaticObjectInstance obj = new L2StaticObjectInstance(IdFactory.getInstance().getNextId());
obj.setType(type);
obj.setStaticObjectId(id);
obj.setXYZ(x, y, z);
obj.setMap(texture, map_x, map_y);
obj.spawnMe();
return obj;
}
}

View File

@@ -0,0 +1,120 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.io.File;
import java.util.Scanner;
import com.l2jmobius.Config;
import com.l2jmobius.gameserver.model.L2SummonItem;
import javolution.util.FastMap;
/**
* @author FBIagent
*/
public class SummonItemsData
{
private final FastMap<Integer, L2SummonItem> _summonitems;
private static SummonItemsData _instance;
public static SummonItemsData getInstance()
{
if (_instance == null)
{
_instance = new SummonItemsData();
}
return _instance;
}
public SummonItemsData()
{
_summonitems = new FastMap<>();
try (Scanner s = new Scanner(new File(Config.DATAPACK_ROOT + "/data/summon_items.csv")))
{
int lineCount = 0;
while (s.hasNextLine())
{
lineCount++;
final String line = s.nextLine();
if (line.startsWith("#"))
{
continue;
}
else if (line.isEmpty())
{
continue;
}
final String[] lineSplit = line.split(";");
boolean ok = true;
int itemID = 0, npcID = 0;
byte summonType = 0;
try
{
itemID = Integer.parseInt(lineSplit[0]);
npcID = Integer.parseInt(lineSplit[1]);
summonType = Byte.parseByte(lineSplit[2]);
}
catch (final Exception e)
{
System.out.println("Summon items data: Error in line " + lineCount + " -> incomplete/invalid data or wrong seperator!");
System.out.println(" " + line);
ok = false;
}
if (!ok)
{
continue;
}
final L2SummonItem summonitem = new L2SummonItem(itemID, npcID, summonType);
_summonitems.put(itemID, summonitem);
}
System.out.println("Summon items data: Loaded " + _summonitems.size() + " summon items.");
}
catch (final Exception e)
{
System.out.println("Summon items data: Cannot find '" + Config.DATAPACK_ROOT + "/data/summon_items.csv'");
}
}
public L2SummonItem getSummonItem(int itemId)
{
return _summonitems.get(itemId);
}
public int[] itemIDs()
{
final int size = _summonitems.size();
final int[] result = new int[size];
int i = 0;
for (final L2SummonItem si : _summonitems.values())
{
result[i] = si.getItemId();
i++;
}
return result;
}
}

View File

@@ -0,0 +1,128 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;
import java.util.logging.Logger;
import com.l2jmobius.Config;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.model.L2TeleportLocation;
import javolution.util.FastMap;
/**
* This class ...
* @version $Revision: 1.3.2.2.2.3 $ $Date: 2005/03/27 15:29:18 $
*/
public class TeleportLocationTable
{
private static Logger _log = Logger.getLogger(TeleportLocationTable.class.getName());
private static TeleportLocationTable _instance;
private Map<Integer, L2TeleportLocation> _teleports;
public static TeleportLocationTable getInstance()
{
if (_instance == null)
{
_instance = new TeleportLocationTable();
}
return _instance;
}
private TeleportLocationTable()
{
reloadAll();
}
public void reloadAll()
{
_teleports = new FastMap<>();
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT Description, id, loc_x, loc_y, loc_z, price, fornoble FROM teleport");
ResultSet rset = statement.executeQuery())
{
L2TeleportLocation teleport;
while (rset.next())
{
teleport = new L2TeleportLocation();
teleport.setTeleId(rset.getInt("id"));
teleport.setLocX(rset.getInt("loc_x"));
teleport.setLocY(rset.getInt("loc_y"));
teleport.setLocZ(rset.getInt("loc_z"));
teleport.setPrice(rset.getInt("price"));
teleport.setIsForNoble(rset.getInt("fornoble") == 1);
_teleports.put(teleport.getTeleId(), teleport);
}
_log.config("TeleportLocationTable: Loaded " + _teleports.size() + " Teleport Location Templates.");
}
catch (final Exception e)
{
_log.warning("error while creating teleport table " + e);
}
if (Config.CUSTOM_TELEPORT_TABLE)
{
try (Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("SELECT Description, id, loc_x, loc_y, loc_z, price, fornoble FROM custom_teleport");
ResultSet rset = statement.executeQuery())
{
L2TeleportLocation teleport;
final int _cTeleCount = _teleports.size();
while (rset.next())
{
teleport = new L2TeleportLocation();
teleport.setTeleId(rset.getInt("id"));
teleport.setLocX(rset.getInt("loc_x"));
teleport.setLocY(rset.getInt("loc_y"));
teleport.setLocZ(rset.getInt("loc_z"));
teleport.setPrice(rset.getInt("price"));
teleport.setIsForNoble(rset.getInt("fornoble") == 1);
_teleports.put(teleport.getTeleId(), teleport);
}
_log.config("TeleportLocationTable: Loaded " + (_teleports.size() - _cTeleCount) + " Custom Teleport Location Templates.");
}
catch (final Exception e)
{
_log.warning("error while creating custom teleport table " + e);
}
}
}
/**
* @param id
* @return
*/
public L2TeleportLocation getTemplate(int id)
{
return _teleports.get(id);
}
}

View File

@@ -0,0 +1,421 @@
/*
* This file is part of the L2J Mobius project.
*
* 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.
*
* 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 com.l2jmobius.gameserver.datatables;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import com.l2jmobius.Config;
import com.l2jmobius.L2DatabaseFactory;
import com.l2jmobius.gameserver.instancemanager.ArenaManager;
import com.l2jmobius.gameserver.instancemanager.GrandBossManager;
import com.l2jmobius.gameserver.instancemanager.OlympiadStadiumManager;
import com.l2jmobius.gameserver.instancemanager.TownManager;
import com.l2jmobius.gameserver.model.L2World;
import com.l2jmobius.gameserver.model.L2WorldRegion;
import com.l2jmobius.gameserver.model.zone.L2ZoneSpawn;
import com.l2jmobius.gameserver.model.zone.L2ZoneType;
import com.l2jmobius.gameserver.model.zone.form.ZoneCuboid;
import com.l2jmobius.gameserver.model.zone.form.ZoneNPoly;
import com.l2jmobius.gameserver.model.zone.type.L2ArenaZone;
import com.l2jmobius.gameserver.model.zone.type.L2BossZone;
import com.l2jmobius.gameserver.model.zone.type.L2CastleTeleportZone;
import com.l2jmobius.gameserver.model.zone.type.L2ClanHallZone;
import com.l2jmobius.gameserver.model.zone.type.L2DamageZone;
import com.l2jmobius.gameserver.model.zone.type.L2DerbyTrackZone;
import com.l2jmobius.gameserver.model.zone.type.L2EffectZone;
import com.l2jmobius.gameserver.model.zone.type.L2FishingZone;
import com.l2jmobius.gameserver.model.zone.type.L2JailZone;
import com.l2jmobius.gameserver.model.zone.type.L2MotherTreeZone;
import com.l2jmobius.gameserver.model.zone.type.L2NoHqZone;
import com.l2jmobius.gameserver.model.zone.type.L2NoLandingZone;
import com.l2jmobius.gameserver.model.zone.type.L2NoStoreZone;
import com.l2jmobius.gameserver.model.zone.type.L2OlympiadStadiumZone;
import com.l2jmobius.gameserver.model.zone.type.L2PeaceZone;
import com.l2jmobius.gameserver.model.zone.type.L2SiegeZone;
import com.l2jmobius.gameserver.model.zone.type.L2TownZone;
import com.l2jmobius.gameserver.model.zone.type.L2WaterZone;
import javolution.util.FastList;
/**
* This class manages all zone data.
* @author durgus
*/
public class ZoneTable
{
private static final Logger _log = Logger.getLogger(ZoneTable.class.getName());
// =========================================================
private static ZoneTable _instance;
public static final ZoneTable getInstance()
{
if (_instance == null)
{
_instance = new ZoneTable();
}
return _instance;
}
// =========================================================
// Data Field
// =========================================================
// Constructor
public ZoneTable()
{
_log.info("Loading zones");
load();
}
// =========================================================
// Method - Private
private final void load()
{
int zoneCount = 0;
// Get the world regions
final L2WorldRegion[][] worldRegions = L2World.getInstance().getAllWorldRegions();
// Get an sql connection here
try (Connection con = L2DatabaseFactory.getInstance().getConnection())
{
// Load the zone xml
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setIgnoringComments(true);
final File file = new File(Config.DATAPACK_ROOT + "/data/zones/zone.xml");
if (!file.exists())
{
if (Config.DEBUG)
{
_log.info("The zone.xml file is missing.");
}
return;
}
final Document doc = factory.newDocumentBuilder().parse(file);
for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling())
{
if ("list".equalsIgnoreCase(n.getNodeName()))
{
for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling())
{
if ("zone".equalsIgnoreCase(d.getNodeName()))
{
NamedNodeMap attrs = d.getAttributes();
final int zoneId = Integer.parseInt(attrs.getNamedItem("id").getNodeValue());
final int minZ = Integer.parseInt(attrs.getNamedItem("minZ").getNodeValue());
final int maxZ = Integer.parseInt(attrs.getNamedItem("maxZ").getNodeValue());
final String zoneType = attrs.getNamedItem("type").getNodeValue();
final String zoneShape = attrs.getNamedItem("shape").getNodeValue();
// Create the zone
L2ZoneType temp = null;
if (zoneType.equals("FishingZone"))
{
temp = new L2FishingZone(zoneId);
}
else if (zoneType.equals("ClanHallZone"))
{
temp = new L2ClanHallZone(zoneId);
}
else if (zoneType.equals("PeaceZone"))
{
temp = new L2PeaceZone(zoneId);
}
else if (zoneType.equals("Town"))
{
temp = new L2TownZone(zoneId);
}
else if (zoneType.equals("OlympiadStadium"))
{
temp = new L2OlympiadStadiumZone(zoneId);
}
else if (zoneType.equals("SiegeZone"))
{
temp = new L2SiegeZone(zoneId);
}
else if (zoneType.equals("DamageZone"))
{
temp = new L2DamageZone(zoneId);
}
else if (zoneType.equals("Arena"))
{
temp = new L2ArenaZone(zoneId);
}
else if (zoneType.equals("MotherTree"))
{
temp = new L2MotherTreeZone(zoneId);
}
else if (zoneType.equals("EffectZone"))
{
temp = new L2EffectZone(zoneId);
}
else if (zoneType.equals("NoLandingZone"))
{
temp = new L2NoLandingZone(zoneId);
}
else if (zoneType.equals("JailZone"))
{
temp = new L2JailZone(zoneId);
}
else if (zoneType.equals("DerbyTrackZone"))
{
temp = new L2DerbyTrackZone(zoneId);
}
else if (zoneType.equals("WaterZone"))
{
temp = new L2WaterZone(zoneId);
}
else if (zoneType.equals("CastleTeleportZone"))
{
temp = new L2CastleTeleportZone(zoneId);
}
else if (zoneType.equals("NoHqZone"))
{
temp = new L2NoHqZone(zoneId);
}
else if (zoneType.equals("BossZone"))
{
temp = new L2BossZone(zoneId);
}
else if (zoneType.equals("NoStoreZone"))
{
temp = new L2NoStoreZone(zoneId);
}
// Check for unknown type
if (temp == null)
{
_log.warning("ZoneTable: No such zone type: " + zoneType);
continue;
}
// Get the zone shape from sql
try (PreparedStatement statement = con.prepareStatement("SELECT x,y FROM zone_vertices WHERE id=? ORDER BY 'order' ASC "))
{
// Set the correct query
statement.setInt(1, zoneId);
try (ResultSet rset = statement.executeQuery())
{
// Create this zone. Parsing for cuboids is a bit different than for other polygons
// cuboids need exactly 2 points to be defined. Other polygons need at least 3 (one per vertex)
if (zoneShape.equals("Cuboid"))
{
final int[] x =
{
0,
0
};
final int[] y =
{
0,
0
};
boolean successfulLoad = true;
for (int i = 0; i < 2; i++)
{
if (rset.next())
{
x[i] = rset.getInt("x");
y[i] = rset.getInt("y");
}
else
{
_log.warning("ZoneTable: Missing cuboid vertex in sql data for zone: " + zoneId);
successfulLoad = false;
break;
}
}
if (successfulLoad)
{
temp.setZone(zoneId, new ZoneCuboid(x[0], x[1], y[0], y[1], minZ, maxZ));
}
else
{
continue;
}
}
else if (zoneShape.equals("NPoly"))
{
final FastList<Integer> fl_x = new FastList<>(), fl_y = new FastList<>();
// Load the rest
while (rset.next())
{
fl_x.add(rset.getInt("x"));
fl_y.add(rset.getInt("y"));
}
// An nPoly needs to have at least 3 vertices
if ((fl_x.size() == fl_y.size()) && (fl_x.size() > 2))
{
// Create arrays
final int[] aX = new int[fl_x.size()];
final int[] aY = new int[fl_y.size()];
// This runs only at server startup so dont complain :>
for (int i = 0; i < fl_x.size(); i++)
{
aX[i] = fl_x.get(i);
aY[i] = fl_y.get(i);
}
// Create the zone
temp.setZone(zoneId, new ZoneNPoly(aX, aY, minZ, maxZ));
}
else
{
_log.warning("ZoneTable: Bad sql data for zone: " + zoneId);
continue;
}
}
else
{
_log.warning("ZoneTable: Unknown shape: " + zoneShape);
continue;
}
}
}
catch (final Exception e)
{
_log.warning("ZoneTable: Failed to load zone coordinates: " + e);
}
// Check for additional parameters
for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling())
{
if ("stat".equalsIgnoreCase(cd.getNodeName()))
{
attrs = cd.getAttributes();
final String name = attrs.getNamedItem("name").getNodeValue();
final String val = attrs.getNamedItem("val").getNodeValue();
temp.setParameter(name, val);
}
else if ("spawn".equalsIgnoreCase(cd.getNodeName()) && (temp instanceof L2ZoneSpawn))
{
attrs = cd.getAttributes();
final int spawnX = Integer.parseInt(attrs.getNamedItem("X").getNodeValue());
final int spawnY = Integer.parseInt(attrs.getNamedItem("Y").getNodeValue());
final int spawnZ = Integer.parseInt(attrs.getNamedItem("Z").getNodeValue());
final Node val = attrs.getNamedItem("isChaotic");
if ((val != null) && Boolean.parseBoolean(val.getNodeValue()))
{
((L2ZoneSpawn) temp).addChaoticSpawn(spawnX, spawnY, spawnZ);
}
else
{
((L2ZoneSpawn) temp).addSpawn(spawnX, spawnY, spawnZ);
}
}
}
// Register the zone into any world region it intersects with...
// currently 11136 test for each zone :>
int ax, ay, bx, by;
for (int x = 0; x < worldRegions.length; x++)
{
for (int y = 0; y < worldRegions[x].length; y++)
{
ax = (x - L2World.OFFSET_X) << L2World.SHIFT_BY;
bx = ((x + 1) - L2World.OFFSET_X) << L2World.SHIFT_BY;
ay = (y - L2World.OFFSET_Y) << L2World.SHIFT_BY;
by = ((y + 1) - L2World.OFFSET_Y) << L2World.SHIFT_BY;
if (temp.getZone().intersectsRectangle(ax, bx, ay, by))
{
if (Config.DEBUG)
{
_log.info("Zone (" + zoneId + ") added to: " + x + " " + y);
}
worldRegions[x][y].addZone(temp);
}
}
}
// Special managers for arenas, towns...
if (temp instanceof L2ArenaZone)
{
ArenaManager.getInstance().addArena((L2ArenaZone) temp);
}
else if (temp instanceof L2TownZone)
{
TownManager.getInstance().addTown((L2TownZone) temp);
}
else if (temp instanceof L2OlympiadStadiumZone)
{
OlympiadStadiumManager.getInstance().addStadium((L2OlympiadStadiumZone) temp);
}
else if (temp instanceof L2BossZone)
{
GrandBossManager.getInstance().addZone((L2BossZone) temp);
}
// Increase the counter
zoneCount++;
}
}
}
}
}
catch (final Exception e)
{
_log.log(Level.SEVERE, "Error while loading zones.", e);
return;
}
GrandBossManager.getInstance().initZones();
_log.info("Loaded " + zoneCount + " zones.");
}
public FastList<L2ZoneType> getZones(int x, int y)
{
final L2WorldRegion region = L2World.getInstance().getRegion(x, y);
final FastList<L2ZoneType> temp = new FastList<>();
for (final L2ZoneType zone : region.getZones())
{
if (zone.isInsideZone(x, y))
{
temp.add(zone);
}
}
return temp;
}
}