Formatted all code.

Removed unused imports.
Addressed all warnings.
Made all fields in Player class private (added getters and setters where needed).
Removed dead code.
This commit is contained in:
CodeForFame 2011-06-25 00:44:53 -05:00
parent 3880d8869a
commit d7e4583d3b
235 changed files with 26292 additions and 22671 deletions

View File

@ -94,9 +94,9 @@ public class Config {
SAVE_INTERVAL = Integer.parseInt(props.getProperty("save-interval"));
DATE_FORMAT = props.getProperty("date-format");
ALERT_CONFIG = props.getProperty("alert-config");
COMMAND_CONFIG = props.getProperty("command-config");
COMMAND_CONFIG = props.getProperty("command-config");
props.clear();

View File

@ -1,7 +1,5 @@
package org.moparscape.msc.config;
import org.moparscape.msc.gs.Instance;
/**
* Holds all important, commonly tweaked variables.
*

File diff suppressed because it is too large Load Diff

View File

@ -14,23 +14,23 @@ import org.moparscape.msc.gs.plugins.dependencies.PluginHandler;
*/
public class Instance {
public static Server getServer() {
return World.getWorld().getServer();
}
public static Server getServer() {
return World.getWorld().getServer();
}
public static World getWorld() {
return World.getWorld();
}
public static World getWorld() {
return World.getWorld();
}
public static DelayedEventHandler getDelayedEventHandler() {
return getWorld().getDelayedEventHandler();
}
public static DelayedEventHandler getDelayedEventHandler() {
return getWorld().getDelayedEventHandler();
}
public static PluginHandler getPluginHandler() {
return PluginHandler.getPluginHandler();
}
public static ReportHandlerQueries getReport() {
return DBConnection.getReport();
}
public static PluginHandler getPluginHandler() {
return PluginHandler.getPluginHandler();
}
public static ReportHandlerQueries getReport() {
return DBConnection.getReport();
}
}

View File

@ -12,7 +12,6 @@ import org.apache.mina.transport.socket.nio.SocketAcceptor;
import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;
import org.apache.mina.transport.socket.nio.SocketSessionConfig;
import org.moparscape.msc.config.Config;
import org.moparscape.msc.config.Constants;
import org.moparscape.msc.gs.connection.RSCConnectionHandler;
import org.moparscape.msc.gs.connection.filter.ConnectionFilter;
import org.moparscape.msc.gs.core.GameEngine;
@ -40,7 +39,7 @@ public class Server {
configFile = f.getName();
}
}
Config.initConfig(configFile);
world = Instance.getWorld();
world.wl.loadObjects();

View File

@ -8,49 +8,52 @@ import org.moparscape.msc.gs.model.Player;
import org.moparscape.msc.gs.tools.DataConversions;
import org.moparscape.msc.gs.util.StatefulEntityCollection;
public class GameObjectPositionPacketBuilder {
private Player playerToUpdate;
private Player playerToUpdate;
public RSCPacket getPacket() {
StatefulEntityCollection<GameObject> watchedObjects = playerToUpdate.getWatchedObjects();
if (watchedObjects.changed()) {
Collection<GameObject> newObjects = watchedObjects.getNewEntities();
Collection<GameObject> knownObjets = watchedObjects.getKnownEntities();
RSCPacketBuilder packet = new RSCPacketBuilder();
packet.setID(27);
for (GameObject o : knownObjets) {
if (o.getType() != 0) {
continue;
public RSCPacket getPacket() {
StatefulEntityCollection<GameObject> watchedObjects = playerToUpdate
.getWatchedObjects();
if (watchedObjects.changed()) {
Collection<GameObject> newObjects = watchedObjects.getNewEntities();
Collection<GameObject> knownObjets = watchedObjects
.getKnownEntities();
RSCPacketBuilder packet = new RSCPacketBuilder();
packet.setID(27);
for (GameObject o : knownObjets) {
if (o.getType() != 0) {
continue;
}
// We should remove ones miles away differently I think
if (watchedObjects.isRemoving(o)) {
byte[] offsets = DataConversions.getObjectPositionOffsets(
o.getLocation(), playerToUpdate.getLocation());
packet.addShort(60000);
packet.addByte(offsets[0]);
packet.addByte(offsets[1]);
packet.addByte((byte) o.getDirection());
}
}
for (GameObject o : newObjects) {
if (o.getType() != 0) {
continue;
}
byte[] offsets = DataConversions.getObjectPositionOffsets(
o.getLocation(), playerToUpdate.getLocation());
packet.addShort(o.getID());
packet.addByte(offsets[0]);
packet.addByte(offsets[1]);
packet.addByte((byte) o.getDirection());
}
return packet.toPacket();
}
// We should remove ones miles away differently I think
if (watchedObjects.isRemoving(o)) {
byte[] offsets = DataConversions.getObjectPositionOffsets(o.getLocation(), playerToUpdate.getLocation());
packet.addShort(60000);
packet.addByte(offsets[0]);
packet.addByte(offsets[1]);
packet.addByte((byte) o.getDirection());
}
}
for (GameObject o : newObjects) {
if (o.getType() != 0) {
continue;
}
byte[] offsets = DataConversions.getObjectPositionOffsets(o.getLocation(), playerToUpdate.getLocation());
packet.addShort(o.getID());
packet.addByte(offsets[0]);
packet.addByte(offsets[1]);
packet.addByte((byte) o.getDirection());
}
return packet.toPacket();
return null;
}
return null;
}
/**
* Sets the player to update
*/
public void setPlayer(Player p) {
playerToUpdate = p;
}
/**
* Sets the player to update
*/
public void setPlayer(Player p) {
playerToUpdate = p;
}
}

View File

@ -8,49 +8,51 @@ import org.moparscape.msc.gs.model.Player;
import org.moparscape.msc.gs.tools.DataConversions;
import org.moparscape.msc.gs.util.StatefulEntityCollection;
public class ItemPositionPacketBuilder {
private Player playerToUpdate;
private Player playerToUpdate;
public RSCPacket getPacket() {
StatefulEntityCollection<Item> watchedItems = playerToUpdate.getWatchedItems();
if (watchedItems.changed()) {
Collection<Item> newItems = watchedItems.getNewEntities();
Collection<Item> knownItems = watchedItems.getKnownEntities();
RSCPacketBuilder packet = new RSCPacketBuilder();
packet.setID(109);
public RSCPacket getPacket() {
StatefulEntityCollection<Item> watchedItems = playerToUpdate
.getWatchedItems();
if (watchedItems.changed()) {
Collection<Item> newItems = watchedItems.getNewEntities();
Collection<Item> knownItems = watchedItems.getKnownEntities();
RSCPacketBuilder packet = new RSCPacketBuilder();
packet.setID(109);
for (Item i : knownItems) {
// nextTo
if (watchedItems.isRemoving(i)) {
byte[] offsets = DataConversions.getObjectPositionOffsets(i.getLocation(), playerToUpdate.getLocation());
// if(it's miles away) {
// packet.addByte((byte)255);
// packet.addByte((byte)sectionX);
// packet.addByte((byte)sectionY);
// }
// else {
packet.addShort(i.getID() + 32768);
packet.addByte(offsets[0]);
packet.addByte(offsets[1]);
// }
for (Item i : knownItems) {
// nextTo
if (watchedItems.isRemoving(i)) {
byte[] offsets = DataConversions.getObjectPositionOffsets(
i.getLocation(), playerToUpdate.getLocation());
// if(it's miles away) {
// packet.addByte((byte)255);
// packet.addByte((byte)sectionX);
// packet.addByte((byte)sectionY);
// }
// else {
packet.addShort(i.getID() + 32768);
packet.addByte(offsets[0]);
packet.addByte(offsets[1]);
// }
}
}
for (Item i : newItems) {
byte[] offsets = DataConversions.getObjectPositionOffsets(
i.getLocation(), playerToUpdate.getLocation());
packet.addShort(i.getID());
packet.addByte(offsets[0]);
packet.addByte(offsets[1]);
}
return packet.toPacket();
}
}
for (Item i : newItems) {
byte[] offsets = DataConversions.getObjectPositionOffsets(i.getLocation(), playerToUpdate.getLocation());
packet.addShort(i.getID());
packet.addByte(offsets[0]);
packet.addByte(offsets[1]);
}
return packet.toPacket();
return null;
}
return null;
}
/**
* Sets the player to update
*/
public void setPlayer(Player p) {
playerToUpdate = p;
}
/**
* Sets the player to update
*/
public void setPlayer(Player p) {
playerToUpdate = p;
}
}

View File

@ -6,59 +6,60 @@ import org.moparscape.msc.gs.phandler.PacketHandler;
import org.moparscape.msc.gs.tools.DataConversions;
public class LSPacketBuilder extends StaticPacketBuilder {
/**
* ID of the packet
*/
private int pID = 0;
/**
* UID of the packet
*/
private long uID = 0;
/**
* ID of the packet
*/
private int pID = 0;
/**
* UID of the packet
*/
private long uID = 0;
/**
* Sets the handler for this packet.
*
* @param handler
* The handler of the packet
*/
public LSPacketBuilder setHandler(LoginConnector connector, PacketHandler handler) {
uID = DataConversions.getRandom().nextLong();
connector.setHandler(uID, handler);
return this;
}
/**
* Sets the handler for this packet.
*
* @param handler
* The handler of the packet
*/
public LSPacketBuilder setHandler(LoginConnector connector,
PacketHandler handler) {
uID = DataConversions.getRandom().nextLong();
connector.setHandler(uID, handler);
return this;
}
/**
* Sets the ID for this packet.
*
* @param id
* The ID of the packet
*/
public LSPacketBuilder setID(int pID) {
this.pID = pID;
return this;
}
/**
* Sets the ID for this packet.
*
* @param id
* The ID of the packet
*/
public LSPacketBuilder setID(int pID) {
this.pID = pID;
return this;
}
/**
* Sets the uID for this packet.
*
* @param id
* The uID of the packet
*/
public LSPacketBuilder setUID(long uID) {
this.uID = uID;
return this;
}
/**
* Sets the uID for this packet.
*
* @param id
* The uID of the packet
*/
public LSPacketBuilder setUID(long uID) {
this.uID = uID;
return this;
}
/**
* Returns a <code>LSPacket</code> object for the data contained in this
* builder.
*
* @return A <code>LSPacket</code> object
*/
public LSPacket toPacket() {
byte[] data = new byte[curLength];
System.arraycopy(payload, 0, data, 0, curLength);
return new LSPacket(null, pID, uID, data, bare);
}
/**
* Returns a <code>LSPacket</code> object for the data contained in this
* builder.
*
* @return A <code>LSPacket</code> object
*/
public LSPacket toPacket() {
byte[] data = new byte[curLength];
System.arraycopy(payload, 0, data, 0, curLength);
return new LSPacket(null, pID, uID, data, bare);
}
}

View File

@ -8,54 +8,52 @@ import org.moparscape.msc.gs.model.Player;
import org.moparscape.msc.gs.tools.DataConversions;
import org.moparscape.msc.gs.util.StatefulEntityCollection;
public class NpcPositionPacketBuilder {
private Player playerToUpdate;
private Player playerToUpdate;
public RSCPacket getPacket() {
StatefulEntityCollection<Npc> watchedNpcs = playerToUpdate.getWatchedNpcs();
Collection<Npc> newNpcs = watchedNpcs.getNewEntities();
Collection<Npc> knownNpcs = watchedNpcs.getKnownEntities();
RSCPacketBuilder packet = new RSCPacketBuilder();
packet.setID(77);
packet.addBits(knownNpcs.size(), 8);
for (Npc n : knownNpcs) {
packet.addBits(n.getIndex(), 16);
if (watchedNpcs.isRemoving(n)) {
packet.addBits(1, 1);
packet.addBits(1, 1);
packet.addBits(12, 4);
}
else if (n.hasMoved()) {
packet.addBits(1, 1);
packet.addBits(0, 1);
packet.addBits(n.getSprite(), 3);
}
else if (n.spriteChanged()) {
packet.addBits(1, 1);
packet.addBits(1, 1);
packet.addBits(n.getSprite(), 4);
}
else {
packet.addBits(0, 1);
}
}
for (Npc n : newNpcs) {
byte[] offsets = DataConversions.getMobPositionOffsets(n.getLocation(), playerToUpdate.getLocation());
packet.addBits(n.getIndex(), 16);
packet.addBits(offsets[0], 5);
packet.addBits(offsets[1], 5);
packet.addBits(n.getSprite(), 4);
packet.addBits(n.getID(), 10);
public RSCPacket getPacket() {
StatefulEntityCollection<Npc> watchedNpcs = playerToUpdate
.getWatchedNpcs();
Collection<Npc> newNpcs = watchedNpcs.getNewEntities();
Collection<Npc> knownNpcs = watchedNpcs.getKnownEntities();
RSCPacketBuilder packet = new RSCPacketBuilder();
packet.setID(77);
packet.addBits(knownNpcs.size(), 8);
for (Npc n : knownNpcs) {
packet.addBits(n.getIndex(), 16);
if (watchedNpcs.isRemoving(n)) {
packet.addBits(1, 1);
packet.addBits(1, 1);
packet.addBits(12, 4);
} else if (n.hasMoved()) {
packet.addBits(1, 1);
packet.addBits(0, 1);
packet.addBits(n.getSprite(), 3);
} else if (n.spriteChanged()) {
packet.addBits(1, 1);
packet.addBits(1, 1);
packet.addBits(n.getSprite(), 4);
} else {
packet.addBits(0, 1);
}
}
return packet.toPacket();
}
for (Npc n : newNpcs) {
byte[] offsets = DataConversions.getMobPositionOffsets(
n.getLocation(), playerToUpdate.getLocation());
packet.addBits(n.getIndex(), 16);
packet.addBits(offsets[0], 5);
packet.addBits(offsets[1], 5);
packet.addBits(n.getSprite(), 4);
packet.addBits(n.getID(), 10);
}
return packet.toPacket();
}
/**
* Sets the player to update
*/
public void setPlayer(Player p) {
playerToUpdate = p;
}
/**
* Sets the player to update
*/
public void setPlayer(Player p) {
playerToUpdate = p;
}
}

View File

@ -8,66 +8,70 @@ import org.moparscape.msc.gs.model.ChatMessage;
import org.moparscape.msc.gs.model.Npc;
import org.moparscape.msc.gs.model.Player;
public class NpcUpdatePacketBuilder {
private Player playerToUpdate;
private Player playerToUpdate;
public RSCPacket getPacket() {
List<Npc> npcsNeedingHitsUpdate = playerToUpdate.getNpcsRequiringHitsUpdate();
List<ChatMessage> npcMessagesNeedingDisplayed = playerToUpdate.getNpcMessagesNeedingDisplayed();
public RSCPacket getPacket() {
List<Npc> npcsNeedingHitsUpdate = playerToUpdate
.getNpcsRequiringHitsUpdate();
List<ChatMessage> npcMessagesNeedingDisplayed = playerToUpdate
.getNpcMessagesNeedingDisplayed();
int updateSize = npcMessagesNeedingDisplayed.size() + npcsNeedingHitsUpdate.size();
if (updateSize > 0) {
try {
RSCPacketBuilder updates = new RSCPacketBuilder();
updates.setID(190);
updates.addShort(updateSize);
for (ChatMessage cm : npcMessagesNeedingDisplayed) {
int updateSize = npcMessagesNeedingDisplayed.size()
+ npcsNeedingHitsUpdate.size();
if (updateSize > 0) {
try {
RSCPacketBuilder updates = new RSCPacketBuilder();
updates.setID(190);
updates.addShort(updateSize);
for (ChatMessage cm : npcMessagesNeedingDisplayed) {
updates.addShort(cm.getSender().getIndex());
updates.addByte((byte) 1);
updates.addShort(cm.getRecipient().getIndex());
updates.addByte((byte) cm.getLength());
updates.addBytes(cm.getMessage());
// show text above heads of players around
if (cm.getRecipient() != null && cm.getRecipient() instanceof Player) {
RSCPacketBuilder updatez = new RSCPacketBuilder();
updatez.setID(190);
updatez.addShort(1);
updatez.addShort(cm.getSender().getIndex());
updatez.addByte((byte) 1);
updatez.addShort(-1);
updatez.addByte((byte) cm.getLength());
updatez.addBytes(cm.getMessage());
for (Player pl : playerToUpdate.getViewArea().getPlayersInView()) {
if (pl.equals(playerToUpdate) || pl == playerToUpdate)
continue;
pl.getActionSender().addPacket(updatez.toPacket());
}
}
}
for (Npc n : npcsNeedingHitsUpdate) {
updates.addShort(n.getIndex());
updates.addByte((byte) 2);
updates.addByte((byte) n.getLastDamage());
updates.addByte((byte) n.getHits());
updates.addByte((byte) n.getDef().getHits());
}
return updates.toPacket();
}
catch(ConcurrentModificationException e) {
return null;
/**
* Should fix the GS packet queue from piling up
*/
}
if (cm.getRecipient() != null
&& cm.getRecipient() instanceof Player) {
RSCPacketBuilder updatez = new RSCPacketBuilder();
updatez.setID(190);
updatez.addShort(1);
updatez.addShort(cm.getSender().getIndex());
updatez.addByte((byte) 1);
updatez.addShort(-1);
updatez.addByte((byte) cm.getLength());
updatez.addBytes(cm.getMessage());
for (Player pl : playerToUpdate.getViewArea()
.getPlayersInView()) {
if (pl.equals(playerToUpdate)
|| pl == playerToUpdate)
continue;
pl.getActionSender().addPacket(updatez.toPacket());
}
}
}
for (Npc n : npcsNeedingHitsUpdate) {
updates.addShort(n.getIndex());
updates.addByte((byte) 2);
updates.addByte((byte) n.getLastDamage());
updates.addByte((byte) n.getHits());
updates.addByte((byte) n.getDef().getHits());
}
return updates.toPacket();
} catch (ConcurrentModificationException e) {
return null;
/**
* Should fix the GS packet queue from piling up
*/
}
}
return null;
}
return null;
}
/**
* Sets the player to update
*/
public void setPlayer(Player p) {
playerToUpdate = p;
}
/**
* Sets the player to update
*/
public void setPlayer(Player p) {
playerToUpdate = p;
}
}

View File

@ -7,13 +7,13 @@ import org.moparscape.msc.gs.model.Player;
import org.moparscape.msc.gs.tools.DataConversions;
import org.moparscape.msc.gs.util.StatefulEntityCollection;
public class PlayerPositionPacketBuilder {
private Player playerToUpdate;
public RSCPacket getPacket() {
StatefulEntityCollection<Player> watchedPlayers = playerToUpdate.getWatchedPlayers();
StatefulEntityCollection<Player> watchedPlayers = playerToUpdate
.getWatchedPlayers();
Collection<Player> newPlayers = watchedPlayers.getNewEntities();
Collection<Player> knownPlayers = watchedPlayers.getKnownEntities();
RSCPacketBuilder packet = new RSCPacketBuilder();
@ -43,7 +43,8 @@ public class PlayerPositionPacketBuilder {
}
}
for (Player p : newPlayers) {
byte[] offsets = DataConversions.getMobPositionOffsets(p.getLocation(), playerToUpdate.getLocation());
byte[] offsets = DataConversions.getMobPositionOffsets(
p.getLocation(), playerToUpdate.getLocation());
packet.addBits(p.getIndex(), 16);
packet.addBits(offsets[0], 5);
packet.addBits(offsets[1], 5);
@ -51,7 +52,6 @@ public class PlayerPositionPacketBuilder {
packet.addBits(0, 1);
}
RSCPacket pkt = packet.toPacket();
Player p = playerToUpdate;
return pkt;
}

View File

@ -11,20 +11,28 @@ import org.moparscape.msc.gs.model.Player;
import org.moparscape.msc.gs.model.PlayerAppearance;
import org.moparscape.msc.gs.model.Projectile;
public class PlayerUpdatePacketBuilder {
private Player playerToUpdate;
public RSCPacket getPacket() {
List<Bubble> bubblesNeedingDisplayed = playerToUpdate.getBubblesNeedingDisplayed();
List<ChatMessage> chatMessagesNeedingDisplayed = playerToUpdate.getChatMessagesNeedingDisplayed();
List<Player> playersNeedingHitsUpdate = playerToUpdate.getPlayersRequiringHitsUpdate();
List<Bubble> bubblesNeedingDisplayed = playerToUpdate
.getBubblesNeedingDisplayed();
List<ChatMessage> chatMessagesNeedingDisplayed = playerToUpdate
.getChatMessagesNeedingDisplayed();
List<Player> playersNeedingHitsUpdate = playerToUpdate
.getPlayersRequiringHitsUpdate();
List<Projectile> projectilesNeedingDisplayed = playerToUpdate.getProjectilesNeedingDisplayed();
List<Player> playersNeedingAppearanceUpdate = playerToUpdate.getPlayersRequiringAppearanceUpdate();
List<Projectile> projectilesNeedingDisplayed = playerToUpdate
.getProjectilesNeedingDisplayed();
List<Player> playersNeedingAppearanceUpdate = playerToUpdate
.getPlayersRequiringAppearanceUpdate();
int updateSize = bubblesNeedingDisplayed.size() + chatMessagesNeedingDisplayed.size() + playersNeedingHitsUpdate.size() + projectilesNeedingDisplayed.size() + playersNeedingAppearanceUpdate.size();
int updateSize = bubblesNeedingDisplayed.size()
+ chatMessagesNeedingDisplayed.size()
+ playersNeedingHitsUpdate.size()
+ projectilesNeedingDisplayed.size()
+ playersNeedingAppearanceUpdate.size();
if (updateSize > 0) {
RSCPacketBuilder updates = new RSCPacketBuilder();
updates.setID(53);
@ -89,7 +97,8 @@ public class PlayerUpdatePacketBuilder {
updates.addByte(appearance.getSkinColour());
updates.addByte((byte) p.getCombatLevel());
updates.addByte((byte) (p.isSkulled() ? 1 : 0));
updates.addByte((byte) (p.isAdmin() ? 3 : (p.isMod() ? 2 : (p.isPMod() ? 1 : 0))));
updates.addByte((byte) (p.isAdmin() ? 3 : (p.isMod() ? 2 : (p
.isPMod() ? 1 : 0))));
}
return updates.toPacket();
}

View File

@ -3,32 +3,32 @@ package org.moparscape.msc.gs.builders;
import org.moparscape.msc.gs.connection.RSCPacket;
public class RSCPacketBuilder extends StaticPacketBuilder {
/**
* ID of the packet
*/
private int pID = 0;
/**
* ID of the packet
*/
private int pID = 0;
/**
* Sets the ID for this packet.
*
* @param id
* The ID of the packet
*/
public RSCPacketBuilder setID(int pID) {
this.pID = pID;
return this;
}
/**
* Sets the ID for this packet.
*
* @param id
* The ID of the packet
*/
public RSCPacketBuilder setID(int pID) {
this.pID = pID;
return this;
}
/**
* Returns a <code>RSCPacket</code> object for the data contained in this
* builder.
*
* @return A <code>RSCPacket</code> object
*/
public RSCPacket toPacket() {
byte[] data = new byte[curLength];
System.arraycopy(payload, 0, data, 0, curLength);
return new RSCPacket(null, pID, data, bare);
}
/**
* Returns a <code>RSCPacket</code> object for the data contained in this
* builder.
*
* @return A <code>RSCPacket</code> object
*/
public RSCPacket toPacket() {
byte[] data = new byte[curLength];
System.arraycopy(payload, 0, data, 0, curLength);
return new RSCPacket(null, pID, data, bare);
}
}

View File

@ -8,247 +8,252 @@ import org.moparscape.msc.gs.util.Logger;
* <code>RSCPacket</code> objects.
*/
public class StaticPacketBuilder {
/**
* Bitmasks for <code>addBits()</code>
*/
protected static int bitmasks[] = { 0, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f, 0xff, 0x1ff, 0x3ff, 0x7ff, 0xfff, 0x1fff, 0x3fff, 0x7fff, 0xffff, 0x1ffff, 0x3ffff, 0x7ffff, 0xfffff, 0x1fffff, 0x3fffff, 0x7fffff, 0xffffff, 0x1ffffff, 0x3ffffff, 0x7ffffff, 0xfffffff, 0x1fffffff, 0x3fffffff, 0x7fffffff, -1 };
/**
* Default capacity
*/
protected static final int DEFAULT_SIZE = 32;
/**
* Whether this packet does not use the standard packet header
*/
protected boolean bare = false;
/**
* Current index into the buffer by bits
*/
protected int bitPosition = 0;
/**
* Current number of bytes used in the buffer
*/
protected int curLength;
/**
* Bitmasks for <code>addBits()</code>
*/
protected static int bitmasks[] = { 0, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f,
0x7f, 0xff, 0x1ff, 0x3ff, 0x7ff, 0xfff, 0x1fff, 0x3fff, 0x7fff,
0xffff, 0x1ffff, 0x3ffff, 0x7ffff, 0xfffff, 0x1fffff, 0x3fffff,
0x7fffff, 0xffffff, 0x1ffffff, 0x3ffffff, 0x7ffffff, 0xfffffff,
0x1fffffff, 0x3fffffff, 0x7fffffff, -1 };
/**
* Default capacity
*/
protected static final int DEFAULT_SIZE = 32;
/**
* Whether this packet does not use the standard packet header
*/
protected boolean bare = false;
/**
* Current index into the buffer by bits
*/
protected int bitPosition = 0;
/**
* Current number of bytes used in the buffer
*/
protected int curLength;
/**
* The payload buffer
*/
protected byte[] payload;
/**
* The payload buffer
*/
protected byte[] payload;
/**
* Constructs a packet builder with no data and an initial capacity of
* <code>DEFAULT_SIZE</code>.
*
* @see DEFAULT_SIZE
*/
public StaticPacketBuilder() {
this(DEFAULT_SIZE);
}
/**
* Constructs a packet builder with no data and an initial capacity of
* <code>capacity</code>.
*
* @param capacity
* The initial capacity of the buffer
*/
public StaticPacketBuilder(int capacity) {
payload = new byte[capacity];
}
/**
* TODO needs a proper description.
*/
public StaticPacketBuilder addBits(int value, int numBits) {
int bytePos = bitPosition >> 3;
int bitOffset = 8 - (bitPosition & 7);
bitPosition += numBits;
curLength = (bitPosition + 7) / 8;
ensureCapacity(curLength);
for (; numBits > bitOffset; bitOffset = 8) {
payload[bytePos] &= ~bitmasks[bitOffset]; // mask out the desired
// area
payload[bytePos++] |= (value >> (numBits - bitOffset)) & bitmasks[bitOffset];
numBits -= bitOffset;
/**
* Constructs a packet builder with no data and an initial capacity of
* <code>DEFAULT_SIZE</code>.
*
* @see DEFAULT_SIZE
*/
public StaticPacketBuilder() {
this(DEFAULT_SIZE);
}
if (numBits == bitOffset) {
payload[bytePos] &= ~bitmasks[bitOffset];
payload[bytePos] |= value & bitmasks[bitOffset];
} else {
payload[bytePos] &= ~(bitmasks[numBits] << (bitOffset - numBits));
payload[bytePos] |= (value & bitmasks[numBits]) << (bitOffset - numBits);
/**
* Constructs a packet builder with no data and an initial capacity of
* <code>capacity</code>.
*
* @param capacity
* The initial capacity of the buffer
*/
public StaticPacketBuilder(int capacity) {
payload = new byte[capacity];
}
return this;
}
/**
* Adds a <code>byte</code> to the data buffer. The size of this packet will
* grow by one byte.
*
* @param val
* The <code>byte</code> value to add
* @return A reference to this object
*/
public StaticPacketBuilder addByte(byte val) {
return addByte(val, true);
}
/**
* TODO needs a proper description.
*/
public StaticPacketBuilder addBits(int value, int numBits) {
int bytePos = bitPosition >> 3;
int bitOffset = 8 - (bitPosition & 7);
bitPosition += numBits;
curLength = (bitPosition + 7) / 8;
ensureCapacity(curLength);
for (; numBits > bitOffset; bitOffset = 8) {
payload[bytePos] &= ~bitmasks[bitOffset]; // mask out the desired
// area
payload[bytePos++] |= (value >> (numBits - bitOffset))
& bitmasks[bitOffset];
/**
* Adds a <code>byte</code> to the data buffer. The size of this packet will
* grow by one byte.
*
* @param val
* The <code>byte</code> value to add
* @param checkCapacity
* Whether the buffer capacity should be checked
* @return A reference to this object
*/
private StaticPacketBuilder addByte(byte val, boolean checkCapacity) {
if (checkCapacity)
ensureCapacity(curLength + 1);
payload[curLength++] = val;
return this;
}
/**
* Adds the contents of <code>byte</code> array <code>data</code> to the
* packet. The size of this packet will grow by the length of the provided
* array.
*
* @param data
* The bytes to add to this packet
* @return A reference to this object
*/
public StaticPacketBuilder addBytes(byte[] data) {
return addBytes(data, 0, data.length);
}
/**
* Adds the contents of <code>byte</code> array <code>data</code>, starting
* at index <code>offset</code>. The size of this packet will grow by
* <code>len</code> bytes.
*
* @param data
* The bytes to add to this packet
* @param offset
* The index of the first byte to append
* @param len
* The number of bytes to append
* @return A reference to this object
*/
public StaticPacketBuilder addBytes(byte[] data, int offset, int len) {
int newLength = curLength + len;
ensureCapacity(newLength);
System.arraycopy(data, offset, payload, curLength, len);
curLength = newLength;
return this;
}
/**
* Adds a <code>int</code> to the data stream. The size of this packet will
* grow by four bytes.
*
* @param val
* The <code>int</code> value to add
* @return A reference to this object
*/
public StaticPacketBuilder addInt(int val) {
ensureCapacity(curLength + 4);
addByte((byte) (val >> 24), false);
addByte((byte) (val >> 16), false);
addByte((byte) (val >> 8), false);
addByte((byte) val, false);
return this;
}
/**
* Adds a <code>long</code> to the data stream. The size of this packet will
* grow by eight bytes.
*
* @param val
* The <code>long</code> value to add
* @return A reference to this object
*/
public StaticPacketBuilder addLong(long val) {
addInt((int) (val >> 32));
addInt((int) (val & -1L));
return this;
}
/**
* Adds a <code>short</code> to the data stream. The size of this packet
* will grow by two bytes.
*
* @param val
* The <code>short</code> value to add
* @return A reference to this object
*/
public StaticPacketBuilder addShort(int val) {
ensureCapacity(curLength + 2);
addByte((byte) (val >> 8), false);
addByte((byte) val, false);
return this;
}
/**
* Ensures that the buffer is at least <code>minimumBytes</code> bytes.
*
* @param minimumCapacity
* The size needed
*/
private void ensureCapacity(int minimumCapacity) {
if (minimumCapacity >= payload.length)
expandCapacity(minimumCapacity);
}
/**
* Expands the buffer to the specified size.
*
* @param minimumCapacity
* The minimum capacity to which to expand
* @see java.lang.AbstractStringBuilder#expandCapacity(int)
*/
private void expandCapacity(int minimumCapacity) {
int newCapacity = (payload.length + 1) * 2;
if (newCapacity < 0) {
newCapacity = Integer.MAX_VALUE;
} else if (minimumCapacity > newCapacity) {
newCapacity = minimumCapacity;
numBits -= bitOffset;
}
if (numBits == bitOffset) {
payload[bytePos] &= ~bitmasks[bitOffset];
payload[bytePos] |= value & bitmasks[bitOffset];
} else {
payload[bytePos] &= ~(bitmasks[numBits] << (bitOffset - numBits));
payload[bytePos] |= (value & bitmasks[numBits]) << (bitOffset - numBits);
}
return this;
}
int oldLength = curLength;
if (oldLength > payload.length) {
oldLength = payload.length;
}
byte[] newPayload = new byte[newCapacity];
try {
System.arraycopy(payload, 0, newPayload, 0, oldLength);
} catch (Exception e) {
Logger.error(e);
}
payload = newPayload;
}
/**
* Sets this packet as bare. A bare packet will contain only the payload
* data, rather than having the standard packet header prepended.
*
* @param bare
* Whether this packet is to be sent bare
*/
public StaticPacketBuilder setBare(boolean bare) {
this.bare = bare;
return this;
}
/**
* Adds a <code>byte</code> to the data buffer. The size of this packet will
* grow by one byte.
*
* @param val
* The <code>byte</code> value to add
* @return A reference to this object
*/
public StaticPacketBuilder addByte(byte val) {
return addByte(val, true);
}
/**
* Returns a <code>Packet</code> object for the data contained in this
* builder.
*
* @return A <code>Packet</code> object
*/
public Packet toPacket() {
byte[] data = new byte[curLength];
System.arraycopy(payload, 0, data, 0, curLength);
/**
* Adds a <code>byte</code> to the data buffer. The size of this packet will
* grow by one byte.
*
* @param val
* The <code>byte</code> value to add
* @param checkCapacity
* Whether the buffer capacity should be checked
* @return A reference to this object
*/
private StaticPacketBuilder addByte(byte val, boolean checkCapacity) {
if (checkCapacity)
ensureCapacity(curLength + 1);
payload[curLength++] = val;
return this;
}
/**
* Adds the contents of <code>byte</code> array <code>data</code> to the
* packet. The size of this packet will grow by the length of the provided
* array.
*
* @param data
* The bytes to add to this packet
* @return A reference to this object
*/
public StaticPacketBuilder addBytes(byte[] data) {
return addBytes(data, 0, data.length);
}
/**
* Adds the contents of <code>byte</code> array <code>data</code>, starting
* at index <code>offset</code>. The size of this packet will grow by
* <code>len</code> bytes.
*
* @param data
* The bytes to add to this packet
* @param offset
* The index of the first byte to append
* @param len
* The number of bytes to append
* @return A reference to this object
*/
public StaticPacketBuilder addBytes(byte[] data, int offset, int len) {
int newLength = curLength + len;
ensureCapacity(newLength);
System.arraycopy(data, offset, payload, curLength, len);
curLength = newLength;
return this;
}
/**
* Adds a <code>int</code> to the data stream. The size of this packet will
* grow by four bytes.
*
* @param val
* The <code>int</code> value to add
* @return A reference to this object
*/
public StaticPacketBuilder addInt(int val) {
ensureCapacity(curLength + 4);
addByte((byte) (val >> 24), false);
addByte((byte) (val >> 16), false);
addByte((byte) (val >> 8), false);
addByte((byte) val, false);
return this;
}
/**
* Adds a <code>long</code> to the data stream. The size of this packet will
* grow by eight bytes.
*
* @param val
* The <code>long</code> value to add
* @return A reference to this object
*/
public StaticPacketBuilder addLong(long val) {
addInt((int) (val >> 32));
addInt((int) (val & -1L));
return this;
}
/**
* Adds a <code>short</code> to the data stream. The size of this packet
* will grow by two bytes.
*
* @param val
* The <code>short</code> value to add
* @return A reference to this object
*/
public StaticPacketBuilder addShort(int val) {
ensureCapacity(curLength + 2);
addByte((byte) (val >> 8), false);
addByte((byte) val, false);
return this;
}
/**
* Ensures that the buffer is at least <code>minimumBytes</code> bytes.
*
* @param minimumCapacity
* The size needed
*/
private void ensureCapacity(int minimumCapacity) {
if (minimumCapacity >= payload.length)
expandCapacity(minimumCapacity);
}
/**
* Expands the buffer to the specified size.
*
* @param minimumCapacity
* The minimum capacity to which to expand
* @see java.lang.AbstractStringBuilder#expandCapacity(int)
*/
private void expandCapacity(int minimumCapacity) {
int newCapacity = (payload.length + 1) * 2;
if (newCapacity < 0) {
newCapacity = Integer.MAX_VALUE;
} else if (minimumCapacity > newCapacity) {
newCapacity = minimumCapacity;
}
int oldLength = curLength;
if (oldLength > payload.length) {
oldLength = payload.length;
}
byte[] newPayload = new byte[newCapacity];
try {
System.arraycopy(payload, 0, newPayload, 0, oldLength);
} catch (Exception e) {
Logger.error(e);
}
payload = newPayload;
}
/**
* Sets this packet as bare. A bare packet will contain only the payload
* data, rather than having the standard packet header prepended.
*
* @param bare
* Whether this packet is to be sent bare
*/
public StaticPacketBuilder setBare(boolean bare) {
this.bare = bare;
return this;
}
/**
* Returns a <code>Packet</code> object for the data contained in this
* builder.
*
* @return A <code>Packet</code> object
*/
public Packet toPacket() {
byte[] data = new byte[curLength];
System.arraycopy(payload, 0, data, 0, curLength);
return new Packet(null, data, bare);
}
}
}

View File

@ -8,49 +8,52 @@ import org.moparscape.msc.gs.model.Player;
import org.moparscape.msc.gs.tools.DataConversions;
import org.moparscape.msc.gs.util.StatefulEntityCollection;
public class WallObjectPositionPacketBuilder {
private Player playerToUpdate;
private Player playerToUpdate;
public RSCPacket getPacket() {
StatefulEntityCollection<GameObject> watchedObjects = playerToUpdate.getWatchedObjects();
if (watchedObjects.changed()) {
Collection<GameObject> newObjects = watchedObjects.getNewEntities();
Collection<GameObject> knownObjets = watchedObjects.getKnownEntities();
RSCPacketBuilder packet = new RSCPacketBuilder();
packet.setID(95);
for (GameObject o : knownObjets) {
if (o.getType() != 1) {
continue;
public RSCPacket getPacket() {
StatefulEntityCollection<GameObject> watchedObjects = playerToUpdate
.getWatchedObjects();
if (watchedObjects.changed()) {
Collection<GameObject> newObjects = watchedObjects.getNewEntities();
Collection<GameObject> knownObjets = watchedObjects
.getKnownEntities();
RSCPacketBuilder packet = new RSCPacketBuilder();
packet.setID(95);
for (GameObject o : knownObjets) {
if (o.getType() != 1) {
continue;
}
// We should remove ones miles away differently I think
if (watchedObjects.isRemoving(o)) {
byte[] offsets = DataConversions.getObjectPositionOffsets(
o.getLocation(), playerToUpdate.getLocation());
packet.addShort(60000);
packet.addByte(offsets[0]);
packet.addByte(offsets[1]);
packet.addByte((byte) o.getDirection());
}
}
for (GameObject o : newObjects) {
if (o.getType() != 1) {
continue;
}
byte[] offsets = DataConversions.getObjectPositionOffsets(
o.getLocation(), playerToUpdate.getLocation());
packet.addShort(o.getID());
packet.addByte(offsets[0]);
packet.addByte(offsets[1]);
packet.addByte((byte) o.getDirection());
}
return packet.toPacket();
}
// We should remove ones miles away differently I think
if (watchedObjects.isRemoving(o)) {
byte[] offsets = DataConversions.getObjectPositionOffsets(o.getLocation(), playerToUpdate.getLocation());
packet.addShort(60000);
packet.addByte(offsets[0]);
packet.addByte(offsets[1]);
packet.addByte((byte) o.getDirection());
}
}
for (GameObject o : newObjects) {
if (o.getType() != 1) {
continue;
}
byte[] offsets = DataConversions.getObjectPositionOffsets(o.getLocation(), playerToUpdate.getLocation());
packet.addShort(o.getID());
packet.addByte(offsets[0]);
packet.addByte(offsets[1]);
packet.addByte((byte) o.getDirection());
}
return packet.toPacket();
return null;
}
return null;
}
/**
* Sets the player to update
*/
public void setPlayer(Player p) {
playerToUpdate = p;
}
/**
* Sets the player to update
*/
public void setPlayer(Player p) {
playerToUpdate = p;
}
}

View File

@ -20,7 +20,6 @@ import org.moparscape.msc.gs.tools.DataConversions;
import org.moparscape.msc.gs.util.EntityList;
import org.moparscape.msc.gs.util.Logger;
public class MiscPacketBuilder {
/**
* Connector instance
@ -184,11 +183,10 @@ public class MiscPacketBuilder {
+ DataConversions.hashToUsername(user));
int world = p.readShort();
Point location = Point.location(p.readShort(), p
.readShort());
Point location = Point.location(p.readShort(),
p.readShort());
long loginDate = p.readLong();
int lastMoved = (int) ((GameEngine.getTime() - p
.readLong()) / 1000);
int lastMoved = (int) ((GameEngine.getTime() - p.readLong()) / 1000);
boolean chatBlock = p.readByte() == 1;
int fatigue = p.readShort();
String state = p.readString();
@ -208,8 +206,7 @@ public class MiscPacketBuilder {
+ "@whi@. Fatigue is at @or1@" + fatigue
+ "@whi@.", false);
} else {
mod
.getActionSender()
mod.getActionSender()
.sendMessage(
"Invalid player, maybe they aren't currently online?");
}
@ -251,8 +248,8 @@ public class MiscPacketBuilder {
s.addLong(to);
s.addInt(item);
s.addLong(amount);
s.addInt(x);
s.addInt(y);
s.addInt(x);
s.addInt(y);
s.addInt(type);
s.addLong((GameEngine.getTime() / 1000));
packets.add(s.toPacket());

View File

@ -16,16 +16,14 @@ public class SavePacketBuilder {
private Player player;
public LSPacket getPacket() {
LSPacketBuilder packet = new LSPacketBuilder();
packet.setID(20);
packet.addLong(player.getUsernameHash());
packet.addInt(player.getOwner());
packet
.addLong(player.getLastLogin() == 0L
&& player.isChangingAppearance() ? 0 : player
.getCurrentLogin());
packet.addLong(player.getLastLogin() == 0L
&& player.isChangingAppearance() ? 0 : player.getCurrentLogin());
packet.addLong(DataConversions.IPToLong(player.getCurrentIP()));
packet.addShort(player.getCombatLevel());
packet.addShort(player.getSkillTotal());
@ -66,6 +64,7 @@ public class SavePacketBuilder {
}
packet.addShort(player.getQuestPoints());
@SuppressWarnings("unchecked")
java.util.HashMap<Integer, Integer> questStage = (java.util.HashMap<Integer, Integer>) player
.getQuestStages().clone();
@ -76,7 +75,7 @@ public class SavePacketBuilder {
packet.addShort(i);
packet.addShort(questStage.get(i));
}
packet.addLong(player.getEventCD());
packet.addLong(player.getEventCD());
return packet.toPacket();
}

View File

@ -8,30 +8,30 @@ import org.apache.mina.filter.codec.ProtocolEncoder;
* Provides access to the protocol encoders and decoders for the LS protocol.
*/
public class LSCodecFactory implements ProtocolCodecFactory {
/**
* The protocol decoder in use
*/
private static ProtocolDecoder decoder = new LSProtocolDecoder();
/**
* The protocol encoder in use
*/
private static ProtocolEncoder encoder = new LSProtocolEncoder();
/**
* The protocol decoder in use
*/
private static ProtocolDecoder decoder = new LSProtocolDecoder();
/**
* The protocol encoder in use
*/
private static ProtocolEncoder encoder = new LSProtocolEncoder();
/**
* Provides the decoder to use to format outgoing data.
*
* @return A protocol decoder
*/
public ProtocolDecoder getDecoder() {
return decoder;
}
/**
* Provides the decoder to use to format outgoing data.
*
* @return A protocol decoder
*/
public ProtocolDecoder getDecoder() {
return decoder;
}
/**
* Provides the encoder to use to parse incoming data.
*
* @return A protocol encoder
*/
public ProtocolEncoder getEncoder() {
return encoder;
}
/**
* Provides the encoder to use to parse incoming data.
*
* @return A protocol encoder
*/
public ProtocolEncoder getEncoder() {
return encoder;
}
}

View File

@ -9,106 +9,106 @@ import org.moparscape.msc.gs.Server;
import org.moparscape.msc.gs.core.LoginConnector;
import org.moparscape.msc.gs.util.Logger;
/**
* Handles the protocol events fired from MINA.
*/
public class LSConnectionHandler implements IoHandler {
/**
* A reference to the login connector
*/
private LoginConnector connector;
/**
* A reference to the login connector
*/
private LoginConnector connector;
/**
* Creates a new connection handler for the given login connector.
*
* @param connector
* The connector in use
*/
public LSConnectionHandler(LoginConnector connector) {
this.connector = connector;
}
/**
* Invoked whenever an exception is thrown by MINA or this IoHandler.
*
* @param session
* The associated session
* @param cause
* The exception thrown
*/
public void exceptionCaught(IoSession session, Throwable cause) {
}
/**
* Invoked whenever a packet is ready to be added to the queue.
*
* @param session
* The IO session on which the packet was received
* @param message
* The packet
*/
public void messageReceived(IoSession session, Object message) {
if (session.isClosing()) {
return;
/**
* Creates a new connection handler for the given login connector.
*
* @param connector
* The connector in use
*/
public LSConnectionHandler(LoginConnector connector) {
this.connector = connector;
}
LSPacket p = (LSPacket) message;
connector.getPacketQueue().add(p);
}
/**
* Invoked whenever a packet is sent.
*
* @param session
* The associated session
* @param message
* The packet sent
*/
public void messageSent(IoSession session, Object message) {
}
/**
* Invoked whenever an IO session is closed. This must handle unregistering
* the disconnecting player from the engine.
*
* @param session
* The IO session which has been closed
*/
public void sessionClosed(IoSession session) {
Server server = Instance.getServer();
if (server != null && server.running()) {
Logger.error(new Exception("Lost connection the login server!"));
/**
* Invoked whenever an exception is thrown by MINA or this IoHandler.
*
* @param session
* The associated session
* @param cause
* The exception thrown
*/
public void exceptionCaught(IoSession session, Throwable cause) {
}
}
/**
* Invoked whenever an IO session is created.
*
* @param session
* The session opened
*/
public void sessionCreated(IoSession session) {
session.getFilterChain().addFirst("protocolFilter", new ProtocolCodecFilter(new LSCodecFactory()));
// Logger.event("Connection to LOGIN_SERVER created");
}
/**
* Invoked whenever a packet is ready to be added to the queue.
*
* @param session
* The IO session on which the packet was received
* @param message
* The packet
*/
public void messageReceived(IoSession session, Object message) {
if (session.isClosing()) {
return;
}
LSPacket p = (LSPacket) message;
connector.getPacketQueue().add(p);
}
/**
* Invoked when the idle status of a session changes.
*
* @param session
* The session in question
* @param status
* The new idle status
*/
public void sessionIdle(IoSession session, IdleStatus status) {
}
/**
* Invoked whenever a packet is sent.
*
* @param session
* The associated session
* @param message
* The packet sent
*/
public void messageSent(IoSession session, Object message) {
}
/**
* Invoked when a new session is opened.
*
* @param session
* The session opened
*/
public void sessionOpened(IoSession session) {
}
/**
* Invoked whenever an IO session is closed. This must handle unregistering
* the disconnecting player from the engine.
*
* @param session
* The IO session which has been closed
*/
public void sessionClosed(IoSession session) {
Server server = Instance.getServer();
if (server != null && server.running()) {
Logger.error(new Exception("Lost connection the login server!"));
}
}
/**
* Invoked whenever an IO session is created.
*
* @param session
* The session opened
*/
public void sessionCreated(IoSession session) {
session.getFilterChain().addFirst("protocolFilter",
new ProtocolCodecFilter(new LSCodecFactory()));
// Logger.event("Connection to LOGIN_SERVER created");
}
/**
* Invoked when the idle status of a session changes.
*
* @param session
* The session in question
* @param status
* The new idle status
*/
public void sessionIdle(IoSession session, IdleStatus status) {
}
/**
* Invoked when a new session is opened.
*
* @param session
* The session opened
*/
public void sessionOpened(IoSession session) {
}
}

View File

@ -6,50 +6,51 @@ import org.apache.mina.common.IoSession;
* An immutable packet object.
*/
public final class LSPacket extends Packet {
/**
* The ID of the packet
*/
private int pID;
/**
* The uID of the packet
*/
private long uID;
/**
* The ID of the packet
*/
private int pID;
/**
* The uID of the packet
*/
private long uID;
public LSPacket(IoSession session, int pID, long uID, byte[] pData) {
this(session, pID, uID, pData, false);
}
public LSPacket(IoSession session, int pID, long uID, byte[] pData) {
this(session, pID, uID, pData, false);
}
public LSPacket(IoSession session, int pID, long uID, byte[] pData, boolean bare) {
super(session, pData, bare);
this.pID = pID;
this.uID = uID;
}
public LSPacket(IoSession session, int pID, long uID, byte[] pData,
boolean bare) {
super(session, pData, bare);
this.pID = pID;
this.uID = uID;
}
/**
* Returns the packet ID.
*
* @return The packet ID
*/
public int getID() {
return pID;
}
/**
* Returns the packet ID.
*
* @return The packet ID
*/
public int getID() {
return pID;
}
/**
* Returns the unique ID.
*
* @return The unique ID
*/
public long getUID() {
return uID;
}
/**
* Returns the unique ID.
*
* @return The unique ID
*/
public long getUID() {
return uID;
}
/**
* Returns this packet in string form.
*
* @return A <code>String</code> representing this packet
*/
public String toString() {
return super.toString() + " pid = " + pID + " uid = " + uID;
}
/**
* Returns this packet in string form.
*
* @return A <code>String</code> representing this packet
*/
public String toString() {
return super.toString() + " pid = " + pID + " uid = " + uID;
}
}

View File

@ -10,48 +10,49 @@ import org.apache.mina.filter.codec.ProtocolDecoderOutput;
* outputs it as a <code>LSPacket</code> object.
*/
public class LSProtocolDecoder extends CumulativeProtocolDecoder {
/**
* Releases the buffer used by the given session.
*
* @param session
* The session for which to release the buffer
* @throws Exception
* if failed to dispose all resources
*/
public void dispose(IoSession session) throws Exception {
super.dispose(session);
}
/**
* Parses the data in the provided byte buffer and writes it to
* <code>out</code> as a <code>LSPacket</code>.
*
* @param session
* The IoSession the data was read from
* @param in
* The buffer
* @param out
* The decoder output stream to which to write the
* <code>LSPacket</code>
* @return Whether enough data was available to create a packet
*/
protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) {
if (in.remaining() >= 13) {
int length = in.getInt();
if (length <= in.remaining()) {
byte[] payload = new byte[length - 9];
int id = in.getUnsigned();
long uid = in.getLong();
in.get(payload);
out.write(new LSPacket(session, id, uid, payload));
return true;
} else {
in.rewind();
return false;
}
/**
* Releases the buffer used by the given session.
*
* @param session
* The session for which to release the buffer
* @throws Exception
* if failed to dispose all resources
*/
public void dispose(IoSession session) throws Exception {
super.dispose(session);
}
/**
* Parses the data in the provided byte buffer and writes it to
* <code>out</code> as a <code>LSPacket</code>.
*
* @param session
* The IoSession the data was read from
* @param in
* The buffer
* @param out
* The decoder output stream to which to write the
* <code>LSPacket</code>
* @return Whether enough data was available to create a packet
*/
protected boolean doDecode(IoSession session, ByteBuffer in,
ProtocolDecoderOutput out) {
if (in.remaining() >= 13) {
int length = in.getInt();
if (length <= in.remaining()) {
byte[] payload = new byte[length - 9];
int id = in.getUnsigned();
long uid = in.getLong();
in.get(payload);
out.write(new LSPacket(session, id, uid, payload));
return true;
} else {
in.rewind();
return false;
}
}
return false;
}
return false;
}
}

View File

@ -6,54 +6,55 @@ import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.moparscape.msc.gs.util.Logger;
/**
* Encodes the high level <code>LSPacket</code> class into the proper protocol
* data required for transmission.
*/
public class LSProtocolEncoder implements ProtocolEncoder {
/**
* Releases all resources used by this encoder.
*
* @param session
* The IO session
*/
public void dispose(IoSession session) {
}
/**
* Converts a <code>LSPacket</code> object into the raw data needed for
* transmission.
*
* @param session
* The IO session associated with the packet
* @param message
* A <code>LSPacket</code> to encode
* @param out
* The output stream to which to write the data
*/
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) {
if (!(message instanceof LSPacket)) {
Logger.error(new Exception("Wrong packet type! " + message.toString()));
return;
/**
* Releases all resources used by this encoder.
*
* @param session
* The IO session
*/
public void dispose(IoSession session) {
}
LSPacket p = (LSPacket) message;
byte[] data = p.getData();
int packetLength = data.length;
ByteBuffer buffer;
if (!p.isBare()) {
buffer = ByteBuffer.allocate(data.length + 13);
packetLength += 9;
buffer.putInt(packetLength);
buffer.put((byte) p.getID());
buffer.putLong(p.getUID());
/**
* Converts a <code>LSPacket</code> object into the raw data needed for
* transmission.
*
* @param session
* The IO session associated with the packet
* @param message
* A <code>LSPacket</code> to encode
* @param out
* The output stream to which to write the data
*/
public void encode(IoSession session, Object message,
ProtocolEncoderOutput out) {
if (!(message instanceof LSPacket)) {
Logger.error(new Exception("Wrong packet type! "
+ message.toString()));
return;
}
LSPacket p = (LSPacket) message;
byte[] data = p.getData();
int packetLength = data.length;
ByteBuffer buffer;
if (!p.isBare()) {
buffer = ByteBuffer.allocate(data.length + 13);
packetLength += 9;
} else {
buffer = ByteBuffer.allocate(data.length);
buffer.putInt(packetLength);
buffer.put((byte) p.getID());
buffer.putLong(p.getUID());
} else {
buffer = ByteBuffer.allocate(data.length);
}
buffer.put(data, 0, data.length);
buffer.flip();
out.write(buffer);
}
buffer.put(data, 0, data.length);
buffer.flip();
out.write(buffer);
}
}

View File

@ -6,253 +6,262 @@ import org.apache.mina.common.IoSession;
import org.moparscape.msc.gs.core.GameEngine;
import org.moparscape.msc.gs.util.Logger;
/**
* An immutable packet object.
*/
public class Packet {
/**
* Whether this packet is without the standard packet header
*/
protected boolean bare;
/**
* The current index into the payload buffer for reading
*/
protected int caret = 0;
/**
* The payload
*/
protected byte[] pData;
/**
* The length of the payload
*/
protected int pLength;
/**
* The associated IO session
*/
protected IoSession session;
/**
* The time this packet was created
*/
protected long time;
/**
* Whether this packet is without the standard packet header
*/
protected boolean bare;
/**
* The current index into the payload buffer for reading
*/
protected int caret = 0;
/**
* The payload
*/
protected byte[] pData;
/**
* The length of the payload
*/
protected int pLength;
/**
* The associated IO session
*/
protected IoSession session;
/**
* The time this packet was created
*/
protected long time;
/**
* Creates a new packet with the specified parameters. The packet is
* considered not to be a bare packet.
*
* @param session
* The session to associate with the packet
* @param pData
* The payload the packet
*/
public Packet(IoSession session, byte[] pData) {
this(session, pData, false);
}
/**
* Creates a new packet with the specified parameters.
*
* @param session
* The session to associate with the packet
* @param pData
* The payload of the packet
* @param bare
* Whether this packet is bare, which means that it does not
* include the standard packet header
*/
public Packet(IoSession session, byte[] pData, boolean bare) {
this.session = session;
this.pData = pData;
this.pLength = pData.length;
this.bare = bare;
time = GameEngine.getTime();
}
/**
* Returns the time the packet was created.
*
* @ return the time the packet was created
*/
public long getCreated() {
return time;
}
/**
* Returns the entire payload data of this packet.
*
* @return The payload <code>byte</code> array
*/
public byte[] getData() {
return pData;
}
/**
* Returns the length of the payload of this packet.
*
* @return The length of the packet's payload
*/
public int getLength() {
return pLength;
}
/**
* Returns the remaining payload data of this packet.
*
* @return The payload <code>byte</code> array
*/
public byte[] getRemainingData() {
byte[] data = new byte[pLength - caret];
for (int i = 0; i < data.length; i++) {
data[i] = pData[i + caret];
/**
* Creates a new packet with the specified parameters. The packet is
* considered not to be a bare packet.
*
* @param session
* The session to associate with the packet
* @param pData
* The payload the packet
*/
public Packet(IoSession session, byte[] pData) {
this(session, pData, false);
}
caret += data.length;
return data;
}
/**
* Returns the IO session associated with the packet, if any.
*
* @return The <code>IoSession</code> object, or <code>null</code> if none.
*/
public IoSession getSession() {
return session;
}
/**
* Checks if this packet is considered to be a bare packet, which means that
* it does not include the standard packet header (ID and length values).
*
* @return Whether this packet is a bare packet
*/
public boolean isBare() {
return bare;
}
public String printData() {
if (pLength == 0) {
return "";
/**
* Creates a new packet with the specified parameters.
*
* @param session
* The session to associate with the packet
* @param pData
* The payload of the packet
* @param bare
* Whether this packet is bare, which means that it does not
* include the standard packet header
*/
public Packet(IoSession session, byte[] pData, boolean bare) {
this.session = session;
this.pData = pData;
this.pLength = pData.length;
this.bare = bare;
time = GameEngine.getTime();
}
String data = "";
for (int i = 0; i < pLength; i++) {
data += " " + pData[i];
/**
* Returns the time the packet was created.
*
* @ return the time the packet was created
*/
public long getCreated() {
return time;
}
return data.substring(1);
}
/**
* Reads the next <code>byte</code> from the payload.
*
* @return A <code>byte</code>
*/
public byte readByte() {
return pData[caret++];
}
/**
* Returns length of payload data of this packet.
*
* @return The payload <code>byte</code> array
*/
public byte[] readBytes(int length) {
byte[] data = new byte[length];
try {
for (int i = 0; i < length; i++) {
data[i] = pData[i + caret];
}
} catch (Exception e) {
Logger.error(e.getMessage());
/**
* Returns the entire payload data of this packet.
*
* @return The payload <code>byte</code> array
*/
public byte[] getData() {
return pData;
}
caret += length;
return data;
}
/**
* Reads the next <code>int</code> from the payload.
*
* @return An <code>int</code>
*/
public int readInt() {
try {
return ((pData[caret++] & 0xff) << 24) | ((pData[caret++] & 0xff) << 16) | ((pData[caret++] & 0xff) << 8) | (pData[caret++] & 0xff);
} catch (Exception e) {
Logger.error(e.getMessage());
return 0;
/**
* Returns the length of the payload of this packet.
*
* @return The length of the packet's payload
*/
public int getLength() {
return pLength;
}
}
/**
* Reads the next <code>long</code> from the payload.
*
* @return A <code>long</code>
*/
public long readLong() {
try {
return (long) ((long) (pData[caret++] & 0xff) << 56) | ((long) (pData[caret++] & 0xff) << 48) | ((long) (pData[caret++] & 0xff) << 40) | ((long) (pData[caret++] & 0xff) << 32) | ((long) (pData[caret++] & 0xff) << 24) | ((long) (pData[caret++] & 0xff) << 16) | ((long) (pData[caret++] & 0xff) << 8) | ((long) (pData[caret++] & 0xff));
} catch (Exception e) {
Logger.error(e.getMessage());
return 0;
/**
* Returns the remaining payload data of this packet.
*
* @return The payload <code>byte</code> array
*/
public byte[] getRemainingData() {
byte[] data = new byte[pLength - caret];
for (int i = 0; i < data.length; i++) {
data[i] = pData[i + caret];
}
caret += data.length;
return data;
}
}
/**
* Reads the next <code>short</code> from the payload.
*
* @return A <code>short</code>
*/
public short readShort() {
try {
return (short) ((short) ((pData[caret++] & 0xff) << 8) | (short) (pData[caret++] & 0xff));
} catch (Exception e) {
// Logger.error(e.getMessage());
return 0;
/**
* Returns the IO session associated with the packet, if any.
*
* @return The <code>IoSession</code> object, or <code>null</code> if none.
*/
public IoSession getSession() {
return session;
}
}
/**
* Reads the string which is formed by the unread portion of the payload.
*
* @return A <code>String</code>
*/
public String readString() {
return readString(pLength - caret);
}
/**
* Checks if this packet is considered to be a bare packet, which means that
* it does not include the standard packet header (ID and length values).
*
* @return Whether this packet is a bare packet
*/
public boolean isBare() {
return bare;
}
/**
* Reads a string of the specified length from the payload.
*
* @param length
* The length of the string to be read
* @return A <code>String</code>
*/
public String readString(int length) {
public String printData() {
if (pLength == 0) {
return "";
}
String data = "";
for (int i = 0; i < pLength; i++) {
data += " " + pData[i];
}
return data.substring(1);
}
/**
* Reads the next <code>byte</code> from the payload.
*
* @return A <code>byte</code>
*/
public byte readByte() {
return pData[caret++];
}
/**
* Returns length of payload data of this packet.
*
* @return The payload <code>byte</code> array
*/
public byte[] readBytes(int length) {
byte[] data = new byte[length];
try {
for (int i = 0; i < length; i++) {
data[i] = pData[i + caret];
}
} catch (Exception e) {
Logger.error(e.getMessage());
}
caret += length;
return data;
}
/**
* Reads the next <code>int</code> from the payload.
*
* @return An <code>int</code>
*/
public int readInt() {
try {
return ((pData[caret++] & 0xff) << 24)
| ((pData[caret++] & 0xff) << 16)
| ((pData[caret++] & 0xff) << 8) | (pData[caret++] & 0xff);
} catch (Exception e) {
Logger.error(e.getMessage());
return 0;
}
}
/**
* Reads the next <code>long</code> from the payload.
*
* @return A <code>long</code>
*/
public long readLong() {
try {
return (long) ((long) (pData[caret++] & 0xff) << 56)
| ((long) (pData[caret++] & 0xff) << 48)
| ((long) (pData[caret++] & 0xff) << 40)
| ((long) (pData[caret++] & 0xff) << 32)
| ((long) (pData[caret++] & 0xff) << 24)
| ((long) (pData[caret++] & 0xff) << 16)
| ((long) (pData[caret++] & 0xff) << 8)
| ((long) (pData[caret++] & 0xff));
} catch (Exception e) {
Logger.error(e.getMessage());
return 0;
}
}
/**
* Reads the next <code>short</code> from the payload.
*
* @return A <code>short</code>
*/
public short readShort() {
try {
return (short) ((short) ((pData[caret++] & 0xff) << 8) | (short) (pData[caret++] & 0xff));
} catch (Exception e) {
// Logger.error(e.getMessage());
return 0;
}
}
/**
* Reads the string which is formed by the unread portion of the payload.
*
* @return A <code>String</code>
*/
public String readString() {
return readString(pLength - caret);
}
/**
* Reads a string of the specified length from the payload.
*
* @param length
* The length of the string to be read
* @return A <code>String</code>
*/
public String readString(int length) {
String rv = new String(pData, caret, length);
caret += length;
return rv;
}
}
public int remaining() {
return pData.length - caret;
}
public int remaining() {
return pData.length - caret;
}
/**
* Skips the specified number of bytes in the payload.
*
* @param x
* The number of bytes to be skipped
*/
public void skip(int x) {
caret += x;
}
/**
* Skips the specified number of bytes in the payload.
*
* @param x
* The number of bytes to be skipped
*/
public void skip(int x) {
caret += x;
}
/**
* Returns this packet in string form.
*
* @return A <code>String</code> representing this packet
*/
public String toString() {
String origin = session == null ? "this" : ((InetSocketAddress) session.getRemoteAddress()).getAddress().getHostAddress();
return "origin = " + origin + " length = " + pLength;
}
/**
* Returns this packet in string form.
*
* @return A <code>String</code> representing this packet
*/
public String toString() {
String origin = session == null ? "this" : ((InetSocketAddress) session
.getRemoteAddress()).getAddress().getHostAddress();
return "origin = " + origin + " length = " + pLength;
}
}

View File

@ -7,38 +7,39 @@ import java.util.List;
* Synchronized packet queue
*/
public class PacketQueue<T extends Packet> {
/**
* The list of packets in the queue
*/
private ArrayList<T> packets = new ArrayList<T>();
/**
* The list of packets in the queue
*/
private ArrayList<T> packets = new ArrayList<T>();
/**
* Adds a packet to the queue
*/
public void add(T p) {
//Logging.debug("[DEBUG] Packet Q: " + packets.size());
synchronized (packets) {
packets.add(p);
/**
* Adds a packet to the queue
*/
public void add(T p) {
// Logging.debug("[DEBUG] Packet Q: " + packets.size());
synchronized (packets) {
packets.add(p);
}
}
}
/**
* Returns the packets currently in the list and removes them from the
* backing store
*/
public List<T> getPackets() {
List<T> tmpList;
synchronized (packets) {
tmpList = (List<T>) packets.clone();
packets.clear();
/**
* Returns the packets currently in the list and removes them from the
* backing store
*/
@SuppressWarnings("unchecked")
public List<T> getPackets() {
List<T> tmpList;
synchronized (packets) {
tmpList = (List<T>) packets.clone();
packets.clear();
}
return tmpList;
}
return tmpList;
}
/**
* Returns if there is packets to process
*/
public boolean hasPackets() {
return !packets.isEmpty();
}
/**
* Returns if there is packets to process
*/
public boolean hasPackets() {
return !packets.isEmpty();
}
}

View File

@ -8,30 +8,30 @@ import org.apache.mina.filter.codec.ProtocolEncoder;
* Provides access to the protocol encoders and decoders for the RSC protocol.
*/
public class RSCCodecFactory implements ProtocolCodecFactory {
/**
* The protocol decoder in use
*/
private static ProtocolDecoder decoder = new RSCProtocolDecoder();
/**
* The protocol encoder in use
*/
private static ProtocolEncoder encoder = new RSCProtocolEncoder();
/**
* The protocol decoder in use
*/
private static ProtocolDecoder decoder = new RSCProtocolDecoder();
/**
* The protocol encoder in use
*/
private static ProtocolEncoder encoder = new RSCProtocolEncoder();
/**
* Provides the decoder to use to format outgoing data.
*
* @return A protocol decoder
*/
public ProtocolDecoder getDecoder() {
return decoder;
}
/**
* Provides the decoder to use to format outgoing data.
*
* @return A protocol decoder
*/
public ProtocolDecoder getDecoder() {
return decoder;
}
/**
* Provides the encoder to use to parse incoming data.
*
* @return A protocol encoder
*/
public ProtocolEncoder getEncoder() {
return encoder;
}
/**
* Provides the encoder to use to parse incoming data.
*
* @return A protocol encoder
*/
public ProtocolEncoder getEncoder() {
return encoder;
}
}

View File

@ -1,302 +1,220 @@
package org.moparscape.msc.gs.connection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Map;
import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoHandler;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.moparscape.msc.config.Constants;
import org.moparscape.msc.gs.Instance;
import org.moparscape.msc.gs.core.GameEngine;
import org.moparscape.msc.gs.model.Player;
import org.moparscape.msc.gs.model.World;
import org.moparscape.msc.gs.util.Logger;
/**
* Handles the protocol events fired from MINA.
*/
public class RSCConnectionHandler implements IoHandler {
/**
* World instance
*/
// sudo
private static final World world = Instance.getWorld();
private long allowedInterval;
/*
private int attackers = 0;
private Map<InetAddress, Long> clients;
private Set<InetAddress> connectedAddresses;
private Map<InetAddress, Integer> counts;
private long lastAttack = 0;
*/
/**
* A reference to the game engine's packet queue
*/
private PacketQueue<RSCPacket> packets;
private Map<InetAddress, Integer> written;
/**
* Creates a new connection handler for the given engine.
*
* @param engine
* The engine in use
*/
public RSCConnectionHandler(GameEngine engine) {
packets = (PacketQueue<RSCPacket>) engine.getPacketQueue();
this.allowedInterval = allowedInterval;
/*
clients = Collections.synchronizedMap(new HashMap<InetAddress, Long>());
counts = Collections.synchronizedMap(new HashMap<InetAddress, Integer>());
written = Collections.synchronizedMap(new HashMap<InetAddress, Integer>());
connectedAddresses = new HashSet<InetAddress>();
*/
}
/*
public void connectionOk(IoSession io) {
counts.remove(getAddress(io));
}
public void delayClient(IoSession session, int delay) {
long d = System.currentTimeMillis() - delay;
clients.put(getAddress(session), d);
}
*/
/**
* Invoked whenever an exception is thrown by MINA or this IoHandler.
*
* @param session
* The associated session
* @param cause
* The exception thrown
*/
public void exceptionCaught(IoSession session, Throwable cause) {
Player p = (Player) session.getAttachment();
// if(p.getUsername().equalsIgnoreCase("xent")) {
// }
if(p != null)
p.getActionSender().sendLogout();
session.close();
/*
* Logging.debug("---MINA Error from: " + p.getUsername() +
* " -------"); cause.printStackTrace();Logging.debug(
* "------------------------------------------------------------");
/**
* World instance
*/
cause.printStackTrace();
}
private InetAddress getAddress(IoSession io) {
return ((InetSocketAddress) io.getRemoteAddress()).getAddress();
}
/**
* Method responsible for deciding if a connection is OK to continue
*
* @param session
* The new session that will be verified
* @return True if the session meets the criteria, otherwise false (if
* false, adds to a IPSec filter & writes IP to log.
*/
/*
public boolean isConnectionOk(IoSession session) {
final InetAddress addr = getAddress(session);
final String ip = addr.toString().replaceAll("/", "");
// ip = ip.replaceAll("/","");
long now = System.currentTimeMillis();
int c = 0;
if (counts.containsKey(addr) && clients.containsKey(addr)) {
try {
c = counts.get(addr);
} catch (Exception e) {
Logging.debug("Error: " + e);
}
if (c >= 5) {
if (!written.containsKey(addr)) {
attackers++;
// if(now - lastAttack > 60000)
// {
// for(Player p : world.getPlayers())
// {
// p.save();
// p.getActionSender().sendLogout();
// }
// Instance.getServer().getLoginConnector().getActionSender().saveProfiles();
// }
try {
/*
* Logging.debug("ATTACKER IP: " + ip);
* BufferedWriter bf2 = new BufferedWriter(new
* FileWriter( "ddos.log", true));
* bf2.write("sudo /sbin/route add " +
* addr.getHostAddress() + " gw 127.0.0.1");
* bf2.newLine(); bf2.close();
* /
written.put(addr, 1);
Instance.getDelayedEventHandler().add(new DelayedEvent(null, 3600000) {
public void run() {
written.remove(addr);
counts.remove(addr);
try {
Runtime.getRuntime().exec("sudo /sbin/route delete " + ip);
} catch (Exception err) {
Logging.debug(err);
}
}
});
try {
Runtime.getRuntime().exec("sudo /sbin/route add " + ip + " gw 127.0.0.1");
} catch (Exception err) {
Logging.debug(err);
}
// try { Runtime.getRuntime().exec(ip + ".bat"); }
// catch (Exception err) { Logging.debug(err); }
lastAttack = now;
} catch (Exception e) {
System.err.println(e);
}
}
return false;
}
}
if (clients.containsKey(addr)) {
long lastConnTime = clients.get(addr);
if (now - lastConnTime < 2000) {
if (!counts.containsKey(addr))
counts.put(addr, 0);
else
c = counts.get(addr) + 1;
counts.put(addr, c);
return false;
} else {
clients.put(addr, now);
if (counts.containsKey(addr))
counts.remove(addr);
return true;
}
} else {
clients.put(addr, now);
return true;
}
}
*/
/**
* Invoked whenever a packet is ready to be added to the queue.
*
* @param session
* The IO session on which the packet was received
* @param message
* The packet
*/
public void messageReceived(IoSession session, Object message) {
Player player = (Player) session.getAttachment();
if (session.isClosing() || player.destroyed()) {
return;
}
RSCPacket p = (RSCPacket) message;
/* if(p.getID() == 57 || p.getID() == 73 || p.getID() == 40 || p.getID()
== 51 || p.getID() == 128 || p.getID() == 206 || p.getID() == 71 ||
p.getID() == 55)*/
if(p.getID() == 55)
player.addInterval();
player.addPacket(p);
packets.add(p);
}
/**
* Invoked whenever a packet is sent.
*
* @param session
* The associated session
* @param message
* The packet sent
*/
public void messageSent(IoSession session, Object message) {
}
/**
* Invoked whenever an IO session is closed. This must handle unregistering
* the disconnecting player from the engine.
*
* @param session
* The IO session which has been closed
*/
public void sessionClosed(IoSession session) {
Player player = (Player) session.getAttachment();
if (!player.destroyed()) {
player.destroy(false);
}
}
public void sessionCreated(IoSession session) {
/*
if (!isConnectionOk(session)) {
session.close();
return;
} else {
connectionOk(session);
*
* private int attackers = 0;
*
* private Map<InetAddress, Long> clients; private Set<InetAddress>
* connectedAddresses; private Map<InetAddress, Integer> counts; private
* long lastAttack = 0;
*/
/**
* A reference to the game engine's packet queue
*/
private PacketQueue<RSCPacket> packets;
/**
* Creates a new connection handler for the given engine.
*
* @param engine
* The engine in use
*/
public RSCConnectionHandler(GameEngine engine) {
packets = (PacketQueue<RSCPacket>) engine.getPacketQueue();
/*
* clients = Collections.synchronizedMap(new HashMap<InetAddress,
* Long>()); counts = Collections.synchronizedMap(new
* HashMap<InetAddress, Integer>()); written =
* Collections.synchronizedMap(new HashMap<InetAddress, Integer>());
* connectedAddresses = new HashSet<InetAddress>();
*/
}
*/
session.getFilterChain().addFirst("protocolFilter", new ProtocolCodecFilter(new RSCCodecFactory()));
// Logger.event("Connection from: " +
// ((InetSocketAddress)session.getRemoteAddress()).getAddress().getHostAddress());
Logger.println("Connection from: " + ((InetSocketAddress) session.getRemoteAddress()).getAddress().getHostAddress());
}
/**
* Invoked when the idle status of a session changes.
*
* @param session
* The session in question
* @param status
* The new idle status
*/
public void sessionIdle(IoSession session, IdleStatus status) {
Player player = (Player) session.getAttachment();
if (!player.destroyed()) {
player.destroy(false);
/*
* public void connectionOk(IoSession io) { counts.remove(getAddress(io)); }
*
* public void delayClient(IoSession session, int delay) { long d =
* System.currentTimeMillis() - delay; clients.put(getAddress(session), d);
* }
*/
/**
* Invoked whenever an exception is thrown by MINA or this IoHandler.
*
* @param session
* The associated session
* @param cause
* The exception thrown
*/
public void exceptionCaught(IoSession session, Throwable cause) {
Player p = (Player) session.getAttachment();
// if(p.getUsername().equalsIgnoreCase("xent")) {
// }
if (p != null)
p.getActionSender().sendLogout();
session.close();
/*
* Logging.debug("---MINA Error from: " + p.getUsername() + " -------");
* cause.printStackTrace();Logging.debug(
* "------------------------------------------------------------");
*/
cause.printStackTrace();
}
session.close();
}
/**
* Invoked when a new session is opened.
*
* @param session
* The session opened
*/
public void sessionOpened(IoSession session) {
Constants.GameServer.ACCEPTED_CONNECTIONS++;
session.setAttachment(new Player(session));
session.setIdleTime(IdleStatus.BOTH_IDLE, 30);
session.setWriteTimeout(30);
}
/**
* Method responsible for deciding if a connection is OK to continue
*
* @param session
* The new session that will be verified
* @return True if the session meets the criteria, otherwise false (if
* false, adds to a IPSec filter & writes IP to log.
*/
/*
* public boolean isConnectionOk(IoSession session) { final InetAddress addr
* = getAddress(session); final String ip = addr.toString().replaceAll("/",
* ""); // ip = ip.replaceAll("/",""); long now =
* System.currentTimeMillis(); int c = 0; if (counts.containsKey(addr) &&
* clients.containsKey(addr)) { try { c = counts.get(addr); } catch
* (Exception e) { Logging.debug("Error: " + e); } if (c >= 5) { if
* (!written.containsKey(addr)) { attackers++; // if(now - lastAttack >
* 60000) // { // for(Player p : world.getPlayers()) // { // p.save(); //
* p.getActionSender().sendLogout(); // } //
* Instance.getServer().getLoginConnector
* ().getActionSender().saveProfiles(); // } try { /*
* Logging.debug("ATTACKER IP: " + ip); BufferedWriter bf2 = new
* BufferedWriter(new FileWriter( "ddos.log", true));
* bf2.write("sudo /sbin/route add " + addr.getHostAddress() +
* " gw 127.0.0.1"); bf2.newLine(); bf2.close(); / written.put(addr, 1);
* Instance.getDelayedEventHandler().add(new DelayedEvent(null, 3600000) {
* public void run() { written.remove(addr); counts.remove(addr); try {
* Runtime.getRuntime().exec("sudo /sbin/route delete " + ip); } catch
* (Exception err) { Logging.debug(err); } } }); try {
* Runtime.getRuntime().exec("sudo /sbin/route add " + ip +
* " gw 127.0.0.1"); } catch (Exception err) { Logging.debug(err); }
*
* // try { Runtime.getRuntime().exec(ip + ".bat"); } // catch (Exception
* err) { Logging.debug(err); } lastAttack = now; } catch (Exception e) {
* System.err.println(e); } } return false; } } if
* (clients.containsKey(addr)) { long lastConnTime = clients.get(addr); if
* (now - lastConnTime < 2000) { if (!counts.containsKey(addr))
* counts.put(addr, 0); else c = counts.get(addr) + 1; counts.put(addr, c);
* return false; } else { clients.put(addr, now); if
* (counts.containsKey(addr)) counts.remove(addr); return true; } } else {
* clients.put(addr, now); return true; } }
*/
/**
* Invoked whenever a packet is ready to be added to the queue.
*
* @param session
* The IO session on which the packet was received
* @param message
* The packet
*/
public void messageReceived(IoSession session, Object message) {
Player player = (Player) session.getAttachment();
if (session.isClosing() || player.destroyed()) {
return;
}
RSCPacket p = (RSCPacket) message;
/**
* Sets the interval between connections from a client. This value is
* measured in milliseconds.
*
* @param allowedInterval
* The number of milliseconds a client is allowed to wait before
* making another successful connection
*/
public void setAllowedInterval(long allowedInterval) {
this.allowedInterval = allowedInterval;
}
/*
* if(p.getID() == 57 || p.getID() == 73 || p.getID() == 40 || p.getID()
* == 51 || p.getID() == 128 || p.getID() == 206 || p.getID() == 71 ||
* p.getID() == 55)
*/
if (p.getID() == 55)
player.addInterval();
player.addPacket(p);
packets.add(p);
}
/**
* Invoked whenever a packet is sent.
*
* @param session
* The associated session
* @param message
* The packet sent
*/
public void messageSent(IoSession session, Object message) {
}
/**
* Invoked whenever an IO session is closed. This must handle unregistering
* the disconnecting player from the engine.
*
* @param session
* The IO session which has been closed
*/
public void sessionClosed(IoSession session) {
Player player = (Player) session.getAttachment();
if (!player.destroyed()) {
player.destroy(false);
}
}
public void sessionCreated(IoSession session) {
/*
* if (!isConnectionOk(session)) { session.close(); return; } else {
* connectionOk(session); }
*/
session.getFilterChain().addFirst("protocolFilter",
new ProtocolCodecFilter(new RSCCodecFactory()));
// Logger.event("Connection from: " +
// ((InetSocketAddress)session.getRemoteAddress()).getAddress().getHostAddress());
Logger.println("Connection from: "
+ ((InetSocketAddress) session.getRemoteAddress()).getAddress()
.getHostAddress());
}
/**
* Invoked when the idle status of a session changes.
*
* @param session
* The session in question
* @param status
* The new idle status
*/
public void sessionIdle(IoSession session, IdleStatus status) {
Player player = (Player) session.getAttachment();
if (!player.destroyed()) {
player.destroy(false);
}
session.close();
}
/**
* Invoked when a new session is opened.
*
* @param session
* The session opened
*/
public void sessionOpened(IoSession session) {
Constants.GameServer.ACCEPTED_CONNECTIONS++;
session.setAttachment(new Player(session));
session.setIdleTime(IdleStatus.BOTH_IDLE, 30);
session.setWriteTimeout(30);
}
}

View File

@ -6,36 +6,36 @@ import org.apache.mina.common.IoSession;
* An immutable packet object.
*/
public final class RSCPacket extends Packet {
/**
* The ID of the packet
*/
private int pID;
/**
* The ID of the packet
*/
private int pID;
public RSCPacket(IoSession session, int pID, byte[] pData) {
this(session, pID, pData, false);
}
public RSCPacket(IoSession session, int pID, byte[] pData) {
this(session, pID, pData, false);
}
public RSCPacket(IoSession session, int pID, byte[] pData, boolean bare) {
super(session, pData, bare);
this.pID = pID;
}
public RSCPacket(IoSession session, int pID, byte[] pData, boolean bare) {
super(session, pData, bare);
this.pID = pID;
}
/**
* Returns the packet ID.
*
* @return The packet ID
*/
public int getID() {
return pID;
}
/**
* Returns the packet ID.
*
* @return The packet ID
*/
public int getID() {
return pID;
}
/**
* Returns this packet in string form.
*
* @return A <code>String</code> representing this packet
*/
public String toString() {
return super.toString() + " pid = " + pID;
}
/**
* Returns this packet in string form.
*
* @return A <code>String</code> representing this packet
*/
public String toString() {
return super.toString() + " pid = " + pID;
}
}

View File

@ -6,64 +6,65 @@ import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.moparscape.msc.gs.util.Logger;
/**
* A decoder for the RSC protocol. Parses the incoming data from an IoSession
* and outputs it as a <code>RSCPacket</code> object.
*/
public class RSCProtocolDecoder extends CumulativeProtocolDecoder {
/**
* Releases the buffer used by the given session.
*
* @param session
* The session for which to release the buffer
* @throws Exception
* if failed to dispose all resources
*/
public void dispose(IoSession session) throws Exception {
super.dispose(session);
}
/**
* Parses the data in the provided byte buffer and writes it to
* <code>out</code> as a <code>RSCPacket</code>.
*
* @param session
* The IoSession the data was read from
* @param in
* The buffer
* @param out
* The decoder output stream to which to write the
* <code>RSCPacket</code>
* @return Whether enough data was available to create a packet
*/
protected synchronized boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) {
try {
if (in.remaining() >= 2) {
byte[] buf = new byte[] { in.get(), in.get() };
int length = ((short) ((buf[0] & 0xff) << 8) | (short) (buf[1] & 0xff));
// Logger.log("len="+length);
if (length <= in.remaining()) {
if (length - 1 < 0) {
Logger.println("Negative array length! id=" + in.getUnsigned() + ",len=" + length);
session.close();
return true;
}
byte[] payload = new byte[length - 1];
int id = in.get() & 0xff;
in.get(payload);
RSCPacket p = new RSCPacket(session, id, payload);
out.write(p);
return true;
} else {
in.rewind();
return false;
}
}
} catch (Exception e) {
e.printStackTrace();
/**
* Releases the buffer used by the given session.
*
* @param session
* The session for which to release the buffer
* @throws Exception
* if failed to dispose all resources
*/
public void dispose(IoSession session) throws Exception {
super.dispose(session);
}
/**
* Parses the data in the provided byte buffer and writes it to
* <code>out</code> as a <code>RSCPacket</code>.
*
* @param session
* The IoSession the data was read from
* @param in
* The buffer
* @param out
* The decoder output stream to which to write the
* <code>RSCPacket</code>
* @return Whether enough data was available to create a packet
*/
protected synchronized boolean doDecode(IoSession session, ByteBuffer in,
ProtocolDecoderOutput out) {
try {
if (in.remaining() >= 2) {
byte[] buf = new byte[] { in.get(), in.get() };
int length = ((short) ((buf[0] & 0xff) << 8) | (short) (buf[1] & 0xff));
// Logger.log("len="+length);
if (length <= in.remaining()) {
if (length - 1 < 0) {
Logger.println("Negative array length! id="
+ in.getUnsigned() + ",len=" + length);
session.close();
return true;
}
byte[] payload = new byte[length - 1];
int id = in.get() & 0xff;
in.get(payload);
RSCPacket p = new RSCPacket(session, id, payload);
out.write(p);
return true;
} else {
in.rewind();
return false;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
return false;
}
}

View File

@ -4,81 +4,81 @@ import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.moparscape.msc.gs.model.Player;
import org.moparscape.msc.gs.util.Logger;
/**
* Encodes the high level <code>RSCPacket</code> class into the proper protocol
* data required for transmission.
*/
public class RSCProtocolEncoder implements ProtocolEncoder {
/**
* Releases all resources used by this encoder.
*
* @param session
* The IO session
*/
public void dispose(IoSession session) {
}
/**
* Converts a <code>RSCPacket</code> object into the raw data needed for
* transmission.
*
* @param session
* The IO session associated with the packet
* @param message
* A <code>RSCPacket</code> to encode
* @param out
* The output stream to which to write the data
*/
public synchronized void encode(IoSession session, Object message, ProtocolEncoderOutput out) {
if (!(message instanceof RSCPacket)) {
Logger.error(new Exception("Wrong packet type! " + message.toString()));
return;
/**
* Releases all resources used by this encoder.
*
* @param session
* The IO session
*/
public void dispose(IoSession session) {
}
try {
RSCPacket p = (RSCPacket) message;
byte[] data = p.getData();
int dataLength = data.length;
ByteBuffer buffer;
// byte[] debug = new byte[dataLength + 4];
if (!p.isBare()) {
buffer = ByteBuffer.allocate(dataLength + 3);
byte[] outlen = { (byte) (dataLength >> 8), (byte) (dataLength) };
buffer.put(outlen);
// debug[0] = outlen[0]; debug[1] = outlen[1];
int id = p.getID();
// debug[2] = (byte)offset; debug[3] = (byte)id;
buffer.put((byte) id);
} else {
buffer = ByteBuffer.allocate(dataLength);
}
// System.arraycopy(data, 0, debug, 4, dataLength);
// Logging.debug(java.util.Arrays.toString(data));
buffer.put(data, 0, dataLength);
buffer.flip();
out.write(buffer);
return;
/*
* byte[] data = p.getData(); int packetLength = data.length; int
* dataLength = data.length; ByteBuffer buffer; if (!p.isBare()) {
* buffer = ByteBuffer.allocate(dataLength + 3); packetLength++; if
* (data.length >= 160) { buffer.put((byte) (160 + (packetLength /
* 256))); buffer.put((byte) (packetLength & 0xff)); } else {
* buffer.put((byte) (packetLength)); if (dataLength > 0) {
* dataLength--; buffer.put((byte) data[dataLength]); } }
* buffer.put((byte) p.getID()); } else { buffer =
* ByteBuffer.allocate(dataLength); } buffer.put(data, 0,
* dataLength); buffer.flip();
*
* out.write(buffer);
*/
/**
* Converts a <code>RSCPacket</code> object into the raw data needed for
* transmission.
*
* @param session
* The IO session associated with the packet
* @param message
* A <code>RSCPacket</code> to encode
* @param out
* The output stream to which to write the data
*/
public synchronized void encode(IoSession session, Object message,
ProtocolEncoderOutput out) {
if (!(message instanceof RSCPacket)) {
Logger.error(new Exception("Wrong packet type! "
+ message.toString()));
return;
}
try {
RSCPacket p = (RSCPacket) message;
byte[] data = p.getData();
int dataLength = data.length;
ByteBuffer buffer;
// byte[] debug = new byte[dataLength + 4];
if (!p.isBare()) {
buffer = ByteBuffer.allocate(dataLength + 3);
byte[] outlen = { (byte) (dataLength >> 8), (byte) (dataLength) };
buffer.put(outlen);
// debug[0] = outlen[0]; debug[1] = outlen[1];
int id = p.getID();
// debug[2] = (byte)offset; debug[3] = (byte)id;
buffer.put((byte) id);
} else {
buffer = ByteBuffer.allocate(dataLength);
}
// System.arraycopy(data, 0, debug, 4, dataLength);
// Logging.debug(java.util.Arrays.toString(data));
buffer.put(data, 0, dataLength);
buffer.flip();
out.write(buffer);
return;
} catch (Exception e) {
e.printStackTrace();
/*
* byte[] data = p.getData(); int packetLength = data.length; int
* dataLength = data.length; ByteBuffer buffer; if (!p.isBare()) {
* buffer = ByteBuffer.allocate(dataLength + 3); packetLength++; if
* (data.length >= 160) { buffer.put((byte) (160 + (packetLength /
* 256))); buffer.put((byte) (packetLength & 0xff)); } else {
* buffer.put((byte) (packetLength)); if (dataLength > 0) {
* dataLength--; buffer.put((byte) data[dataLength]); } }
* buffer.put((byte) p.getID()); } else { buffer =
* ByteBuffer.allocate(dataLength); } buffer.put(data, 0,
* dataLength); buffer.flip();
*
* out.write(buffer);
*/
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

View File

@ -18,7 +18,8 @@ public class ConnectionFilter extends BlacklistFilter {
final InetSocketAddress a = (InetSocketAddress) sa;
final Integer val = connections.get(a);
System.out.println(val);
final Integer retVal = connections.put(a, val == null ? 1 : val + 1);
final Integer retVal = connections
.put(a, val == null ? 1 : val + 1);
if (retVal != null && retVal > BLOCK_THRESHOLD) {
block(a.getAddress());
}
@ -33,7 +34,8 @@ public class ConnectionFilter extends BlacklistFilter {
final InetSocketAddress a = (InetSocketAddress) sa;
final Integer val = connections.get(a);
System.out.println(val);
final Integer retVal = connections.put(a, val == null ? 1 : val + 1);
final Integer retVal = connections
.put(a, val == null ? 1 : val + 1);
if (retVal != null && retVal - 1 <= BLOCK_THRESHOLD) {
unblock(a.getAddress());
}

View File

@ -23,7 +23,6 @@ import org.moparscape.msc.gs.util.Logger;
import org.moparscape.msc.gs.util.Processor;
import org.moparscape.msc.gs.util.WorkGroup;
public final class ClientUpdater implements Processor {
public static int pktcount = 0;
@ -39,11 +38,12 @@ public final class ClientUpdater implements Processor {
private EntityList<Player> players = world.getPlayers();
private WorkGroup<Player> clientInformerGroup = null;
public ClientUpdater() {
world.setClientUpdater(this);
this.clientInformerGroup = new WorkGroup<Player>(this);
}
/**
* Sends queued packets to each player
*/
@ -64,6 +64,7 @@ public final class ClientUpdater implements Processor {
e.printStackTrace();
}
}
/**
* Update player/npc appearances, game objects, items, wall objects, ping
*/
@ -92,13 +93,14 @@ public final class ClientUpdater implements Processor {
for (Npc n : npcs) {
n.setAppearnceChanged(false);
}
}
public static boolean threaded = false;
public volatile boolean updatingCollections;
public void doMajor() {
Long delay;
Long now = System.currentTimeMillis();
@ -106,66 +108,74 @@ public final class ClientUpdater implements Processor {
updateNpcPositions();
delay = System.currentTimeMillis() - now;
if(delay > 299) Logger.println("updateNpcPositions() is taking longer than it should, exactly " + delay + "ms");
if (delay > 299)
Logger.println("updateNpcPositions() is taking longer than it should, exactly "
+ delay + "ms");
now = System.currentTimeMillis();
updatePlayersPositions();
delay = System.currentTimeMillis() - now;
if(delay > 299) Logger.println("updatePlayersPositions() is taking longer than it should, exactly " + delay + "ms");
if (delay > 299)
Logger.println("updatePlayersPositions() is taking longer than it should, exactly "
+ delay + "ms");
now = System.currentTimeMillis();
updateMessageQueues();
delay = System.currentTimeMillis() - now;
if(delay > 299) Logger.println("updateMessageQueues() is taking longer than it should, exactly " + delay + "ms");
if (delay > 299)
Logger.println("updateMessageQueues() is taking longer than it should, exactly "
+ delay + "ms");
now = System.currentTimeMillis();
updateOffers();
if(threaded) {
if (threaded) {
try {
clientInformerGroup.processWorkload(players);
} catch(InterruptedException ie) {
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
else {
} else {
for (Player p : players) {
//Logging.debug("Process for player " + p.getUsername() + " | threaded: " + threaded);
// Logging.debug("Process for player " + p.getUsername() +
// " | threaded: " + threaded);
updateTimeouts(p);
updatePlayerPositions(p);
updateNpcPositions(p);
updateGameObjects(p);
updateWallObjects(p);
updateItems(p);
p.setFirstMajorUpdateSent(true);
}
updateCollections();
}
}
public void process(Player p) {
//Logging.debug("Process for player " + p.getUsername() + " | threaded: " + threaded);
// Logging.debug("Process for player " + p.getUsername() +
// " | threaded: " + threaded);
updateTimeouts(p);
updatePlayerPositions(p); // Must be done before updating any objects/items/npcs!
updatePlayerPositions(p); // Must be done before updating any
// objects/items/npcs!
updateNpcPositions(p);
updateGameObjects(p);
updateWallObjects(p);
updateItems(p);
p.setFirstMajorUpdateSent(true);
}
}
/**
* Updates collections, new becomes known, removing is removed etc.
@ -183,19 +193,19 @@ public final class ClientUpdater implements Processor {
p.getWatchedItems().update();
p.getWatchedNpcs().update();
//p.clearProjectilesNeedingDisplayed();
//p.clearPlayersNeedingHitsUpdate();
//p.clearNpcsNeedingHitsUpdate();
//p.clearChatMessagesNeedingDisplayed();
//p.clearNpcMessagesNeedingDisplayed();
//p.clearBubblesNeedingDisplayed();
// p.clearProjectilesNeedingDisplayed();
// p.clearPlayersNeedingHitsUpdate();
// p.clearNpcsNeedingHitsUpdate();
// p.clearChatMessagesNeedingDisplayed();
// p.clearNpcMessagesNeedingDisplayed();
// p.clearBubblesNeedingDisplayed();
p.resetSpriteChanged();
//p.setAppearnceChanged(false);
// p.setAppearnceChanged(false);
}
for (Npc n : npcs) {
n.resetSpriteChanged();
//n.setAppearnceChanged(false);
// n.setAppearnceChanged(false);
}
updatingCollections = false;
}
@ -208,7 +218,7 @@ public final class ClientUpdater implements Processor {
RSCPacket temp = gameObjectPositionBuilder.getPacket();
if (temp != null) {
p.getActionSender().addPacket(temp);
//p.getSession().write(temp);
// p.getSession().write(temp);
}
}
@ -220,7 +230,7 @@ public final class ClientUpdater implements Processor {
RSCPacket temp = itemPositionBuilder.getPacket();
if (temp != null) {
p.getActionSender().addPacket(temp);
//p.getSession().write(temp);
// p.getSession().write(temp);
}
}
@ -233,33 +243,43 @@ public final class ClientUpdater implements Processor {
if (message == null || !sender.loggedIn()) {
continue;
}
String s = DataConversions.byteToString(message.getMessage(), 0, message.getMessage().length);
String s = DataConversions.byteToString(message.getMessage(), 0,
message.getMessage().length);
s = s.toLowerCase();
String k = s;
s = s.replace(" ", "");
s = s.replace(".", "");
if (s.contains("#adm#") || s.contains("#mod#") || s.contains("#pmd#")) {
sender.getActionSender().sendMessage("@red@Your last message was not sent out due to an illegal string");
return;
}
if(sender.isMuted()) {
sender.getActionSender().sendMessage("You are muted, you cannot send messages");
if (s.contains("#adm#") || s.contains("#mod#")
|| s.contains("#pmd#")) {
sender.getActionSender()
.sendMessage(
"@red@Your last message was not sent out due to an illegal string");
return;
}
}
if (sender.isMuted()) {
sender.getActionSender().sendMessage(
"You are muted, you cannot send messages");
return;
}
List<Player> recievers = sender.getViewArea().getPlayersInView();
ArrayList<String> recieverUsernames = new ArrayList<String>();
for(Player p : recievers)
for (Player p : recievers)
recieverUsernames.add(p.getUsername());
world.addEntryToSnapshots(new Chatlog(sender.getUsername(), k, recieverUsernames));
world.addEntryToSnapshots(new Chatlog(sender.getUsername(), k,
recieverUsernames));
for (Player recipient : recievers) {
if (sender.getIndex() == recipient.getIndex() || !recipient.loggedIn()) {
if (sender.getIndex() == recipient.getIndex()
|| !recipient.loggedIn()) {
continue;
}
if (recipient.getPrivacySetting(0) && !recipient.isFriendsWith(sender.getUsernameHash()) && !sender.isPMod()) {
if (recipient.getPrivacySetting(0)
&& !recipient.isFriendsWith(sender.getUsernameHash())
&& !sender.isPMod()) {
continue;
}
if (recipient.isIgnoring(sender.getUsernameHash()) && !sender.isPMod()) {
if (recipient.isIgnoring(sender.getUsernameHash())
&& !sender.isPMod()) {
continue;
}
recipient.informOfChatMessage(message);
@ -276,7 +296,7 @@ public final class ClientUpdater implements Processor {
RSCPacket temp = npcApperanceBuilder.getPacket();
if (temp != null) {
p.getActionSender().addPacket(temp);
//p.getSession().write(temp);
// p.getSession().write(temp);
}
}
@ -301,7 +321,7 @@ public final class ClientUpdater implements Processor {
RSCPacket temp = npcPositionPacketBuilder.getPacket();
if (temp != null) {
p.getActionSender().addPacket(temp);
//p.getSession().write(temp);
// p.getSession().write(temp);
}
}
@ -338,7 +358,7 @@ public final class ClientUpdater implements Processor {
RSCPacket temp = playerApperanceBuilder.getPacket();
if (temp != null) {
p.getActionSender().addPacket(temp);
//p.getSession().write(temp);
// p.getSession().write(temp);
}
}
@ -351,7 +371,7 @@ public final class ClientUpdater implements Processor {
RSCPacket temp = playerPositionBuilder.getPacket();
if (temp != null) {
p.getActionSender().addPacket(temp);
//p.getSession().write(temp);
// p.getSession().write(temp);
}
}
@ -392,7 +412,9 @@ public final class ClientUpdater implements Processor {
p.destroy(false);
}
} else if (curTime - p.getLastMoved() >= 900000) {
p.getActionSender().sendMessage("@cya@You have not moved for 15 mins, please move to a new area to avoid logout.");
p.getActionSender()
.sendMessage(
"@cya@You have not moved for 15 mins, please move to a new area to avoid logout.");
p.warnToMove();
}
}
@ -404,9 +426,8 @@ public final class ClientUpdater implements Processor {
wallObjectPositionPacketBuilder.setPlayer(p);
RSCPacket temp = wallObjectPositionPacketBuilder.getPacket();
if (temp != null) {
//p.getSession().write(temp);
// p.getSession().write(temp);
p.getActionSender().addPacket(temp);
}
}
}

View File

@ -9,77 +9,77 @@ import org.moparscape.msc.gs.model.Player;
import org.moparscape.msc.gs.model.World;
import org.moparscape.msc.gs.util.Logger;
public final class DelayedEventHandler {
private static World world = Instance.getWorld();
private ArrayList<DelayedEvent> events = new ArrayList<DelayedEvent>();
private ArrayList<DelayedEvent> toAdd = new ArrayList<DelayedEvent>();
private static World world = Instance.getWorld();
private ArrayList<DelayedEvent> events = new ArrayList<DelayedEvent>();
private ArrayList<DelayedEvent> toAdd = new ArrayList<DelayedEvent>();
public DelayedEventHandler() {
world.setDelayedEventHandler(this);
}
public DelayedEventHandler() {
world.setDelayedEventHandler(this);
}
public void add(DelayedEvent event) {
public void add(DelayedEvent event) {
if (!events.contains(event)) {
toAdd.add(event);
toAdd.add(event);
}
}
public boolean contains(DelayedEvent event) {
return events.contains(event);
}
public void doEvents() {
try {
if (toAdd.size() > 0) {
events.addAll(toAdd);
toAdd.clear();
}
Iterator<DelayedEvent> iterator = events.iterator();
while (iterator.hasNext()) {
DelayedEvent event = iterator.next();
if (event == null) {
iterator.remove();
continue;
}
if (event.shouldRun()) {
event.run();
event.updateLastRun();
}
if (event.shouldRemove()) {
iterator.remove();
}
}
} catch (Exception e) {
e.printStackTrace();
Logger.println("Error @ doEvents(): " + e);
}
}
public ArrayList<DelayedEvent> getEvents() {
return events;
}
public void remove(DelayedEvent event) {
events.remove(event);
}
public void removePlayersEvents(Player player) {
try {
Iterator<DelayedEvent> iterator = events.iterator();
while (iterator.hasNext()) {
DelayedEvent event = iterator.next();
if (event.belongsTo(player)) {
iterator.remove();
}
}
} catch (Exception e) {
Logger.println("Error @ removePlayer, IP address:" + player.getCurrentIP() + " Name: " + player.getUsername());
e.printStackTrace();
}
}
public boolean contains(DelayedEvent event) {
return events.contains(event);
}
public void doEvents() {
try {
if (toAdd.size() > 0) {
events.addAll(toAdd);
toAdd.clear();
}
Iterator<DelayedEvent> iterator = events.iterator();
while (iterator.hasNext()) {
DelayedEvent event = iterator.next();
if (event == null) {
iterator.remove();
continue;
}
if (event.shouldRun()) {
event.run();
event.updateLastRun();
}
if (event.shouldRemove()) {
iterator.remove();
}
}
} catch (Exception e) {
e.printStackTrace();
Logger.println("Error @ doEvents(): " + e);
}
}
public ArrayList<DelayedEvent> getEvents() {
return events;
}
public void remove(DelayedEvent event) {
events.remove(event);
}
public void removePlayersEvents(Player player) {
try {
Iterator<DelayedEvent> iterator = events.iterator();
while (iterator.hasNext()) {
DelayedEvent event = iterator.next();
if (event.belongsTo(player)) {
iterator.remove();
}
}
} catch (Exception e) {
Logger.println("Error @ removePlayer, IP address:"
+ player.getCurrentIP() + " Name: " + player.getUsername());
e.printStackTrace();
}
}
}

View File

@ -5,31 +5,19 @@ import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import org.apache.mina.common.IoSession;
import org.moparscape.msc.config.Config;
import org.moparscape.msc.config.Constants;
import org.moparscape.msc.config.Formulae;
import org.moparscape.msc.gs.Instance;
import org.moparscape.msc.gs.connection.PacketQueue;
import org.moparscape.msc.gs.connection.RSCPacket;
import org.moparscape.msc.gs.connection.filter.OSLevelBlocking;
import org.moparscape.msc.gs.event.DelayedEvent;
import org.moparscape.msc.gs.event.MiniEvent;
import org.moparscape.msc.gs.model.ActiveTile;
import org.moparscape.msc.gs.model.Item;
import org.moparscape.msc.gs.model.Npc;
import org.moparscape.msc.gs.model.Player;
import org.moparscape.msc.gs.model.Point;
import org.moparscape.msc.gs.model.Shop;
import org.moparscape.msc.gs.model.World;
import org.moparscape.msc.gs.model.snapshot.Snapshot;
@ -37,7 +25,6 @@ import org.moparscape.msc.gs.phandler.PacketHandler;
import org.moparscape.msc.gs.phandler.PacketHandlerDef;
import org.moparscape.msc.gs.plugins.dependencies.NpcAI;
import org.moparscape.msc.gs.tools.Captcha;
import org.moparscape.msc.gs.tools.DataConversions;
import org.moparscape.msc.gs.util.Logger;
import org.moparscape.msc.gs.util.PersistenceManager;
@ -128,10 +115,10 @@ public final class GameEngine extends Thread {
* getAddress(session); String ip = addr.toString(); ip =
* ip.replaceAll("/",""); long now = System.currentTimeMillis(); int c = 0;
* if(counts.containsKey(addr) && clients.containsKey(addr)) { try { c =
* counts.get(addr); } catch(Exception e) { Logging.debug("Error: " +
* e); } if(c >= 10) { if(!written.containsKey(addr)) { try {
* Logging.debug("Dummy packet flooder IP: " + ip); BufferedWriter bf2
* = new BufferedWriter(new FileWriter("dummy.log", true));
* counts.get(addr); } catch(Exception e) { Logging.debug("Error: " + e); }
* if(c >= 10) { if(!written.containsKey(addr)) { try {
* Logging.debug("Dummy packet flooder IP: " + ip); BufferedWriter bf2 = new
* BufferedWriter(new FileWriter("dummy.log", true));
* bf2.write("sudo /sbin/route add " + addr.getHostAddress() +
* " gw 127.0.0.1"); bf2.newLine(); bf2.close(); written.put(addr, 1); }
* catch(Exception e) { System.err.println(e);} } } } if
@ -204,7 +191,7 @@ public final class GameEngine extends Thread {
private void processEvents() {
eventHandler.doEvents();
}
public DelayedEventHandler getEventHandler() {
return eventHandler;
}
@ -309,9 +296,11 @@ public final class GameEngine extends Thread {
}
time = System.currentTimeMillis();
eventHandler.add(new DelayedEvent(null, Config.GARBAGE_COLLECT_INTERVAL) { // Ran every
// 50*2
// minutes
eventHandler
.add(new DelayedEvent(null, Config.GARBAGE_COLLECT_INTERVAL) { // Ran
// every
// 50*2
// minutes
@Override
public void run() {
new Thread(new Runnable() {

View File

@ -20,216 +20,223 @@ import org.moparscape.msc.gs.phandler.PacketHandlerDef;
import org.moparscape.msc.gs.util.Logger;
import org.moparscape.msc.gs.util.PersistenceManager;
public class LoginConnector {
/**
* A packet builder
*/
private MiscPacketBuilder actionSender = new MiscPacketBuilder(this);
/**
* Connection attempts
*/
private int connectionAttempts = 0;
/**
* Connection Handler
*/
private IoHandler connectionHandler = new LSConnectionHandler(this);
/**
* The mapping of packet IDs to their handler
*/
private TreeMap<Integer, PacketHandler> packetHandlers = new TreeMap<Integer, PacketHandler>();
/**
* The packet queue to be processed
*/
private PacketQueue<LSPacket> packetQueue;
/**
* World registered
*/
private boolean registered = false;
/**
* Should we be running?
*/
private boolean running = true;
/**
* IoSession
*/
private IoSession session;
/**
* The mapping of packet UIDs to their handler
*/
private TreeMap<Long, PacketHandler> uniqueHandlers = new TreeMap<Long, PacketHandler>();
/**
* A packet builder
*/
private MiscPacketBuilder actionSender = new MiscPacketBuilder(this);
/**
* Connection attempts
*/
private int connectionAttempts = 0;
/**
* Connection Handler
*/
private IoHandler connectionHandler = new LSConnectionHandler(this);
/**
* The mapping of packet IDs to their handler
*/
private TreeMap<Integer, PacketHandler> packetHandlers = new TreeMap<Integer, PacketHandler>();
/**
* The packet queue to be processed
*/
private PacketQueue<LSPacket> packetQueue;
/**
* World registered
*/
private boolean registered = false;
/**
* Should we be running?
*/
private boolean running = true;
/**
* IoSession
*/
private IoSession session;
/**
* The mapping of packet UIDs to their handler
*/
private TreeMap<Long, PacketHandler> uniqueHandlers = new TreeMap<Long, PacketHandler>();
public int getConnectionAttempts() {
return connectionAttempts;
}
public void setConnectionAttempts(int connectionAttempts) {
this.connectionAttempts = connectionAttempts;
}
public IoHandler getConnectionHandler() {
return connectionHandler;
}
public void setConnectionHandler(IoHandler connectionHandler) {
this.connectionHandler = connectionHandler;
}
public TreeMap<Integer, PacketHandler> getPacketHandlers() {
return packetHandlers;
}
public void setPacketHandlers(TreeMap<Integer, PacketHandler> packetHandlers) {
this.packetHandlers = packetHandlers;
}
public boolean isRunning() {
return running;
}
public void setRunning(boolean running) {
this.running = running;
}
public TreeMap<Long, PacketHandler> getUniqueHandlers() {
return uniqueHandlers;
}
public void setUniqueHandlers(TreeMap<Long, PacketHandler> uniqueHandlers) {
this.uniqueHandlers = uniqueHandlers;
}
public void setActionSender(MiscPacketBuilder actionSender) {
this.actionSender = actionSender;
}
public void setPacketQueue(PacketQueue<LSPacket> packetQueue) {
this.packetQueue = packetQueue;
}
public void setSession(IoSession session) {
this.session = session;
}
public LoginConnector() {
packetQueue = new PacketQueue<LSPacket>();
loadPacketHandlers();
reconnect();
}
public MiscPacketBuilder getActionSender() {
return actionSender;
}
public PacketQueue getPacketQueue() {
return packetQueue;
}
public IoSession getSession() {
return session;
}
public boolean isRegistered() {
return registered;
}
public void kill() {
running = false;
Logger.print("Unregistering world (" + Config.SERVER_NUM + ") with LS");
actionSender.unregisterWorld();
}
private void loadPacketHandlers() {
PacketHandlerDef[] handlerDefs = (PacketHandlerDef[]) PersistenceManager.load("LSPacketHandlers.xml");
for (PacketHandlerDef handlerDef : handlerDefs) {
try {
String className = handlerDef.getClassName();
Class c = Class.forName(className);
if (c != null) {
PacketHandler handler = (PacketHandler) c.newInstance();
for (int packetID : handlerDef.getAssociatedPackets()) {
packetHandlers.put(packetID, handler);
}
}
} catch (Exception e) {
Logger.error(e);
}
public int getConnectionAttempts() {
return connectionAttempts;
}
}
public void processIncomingPackets() {
for (LSPacket p : packetQueue.getPackets()) {
PacketHandler handler;
if (((handler = uniqueHandlers.get(p.getUID())) != null) || ((handler = packetHandlers.get(p.getID())) != null)) {
public void setConnectionAttempts(int connectionAttempts) {
this.connectionAttempts = connectionAttempts;
}
public IoHandler getConnectionHandler() {
return connectionHandler;
}
public void setConnectionHandler(IoHandler connectionHandler) {
this.connectionHandler = connectionHandler;
}
public TreeMap<Integer, PacketHandler> getPacketHandlers() {
return packetHandlers;
}
public void setPacketHandlers(TreeMap<Integer, PacketHandler> packetHandlers) {
this.packetHandlers = packetHandlers;
}
public boolean isRunning() {
return running;
}
public void setRunning(boolean running) {
this.running = running;
}
public TreeMap<Long, PacketHandler> getUniqueHandlers() {
return uniqueHandlers;
}
public void setUniqueHandlers(TreeMap<Long, PacketHandler> uniqueHandlers) {
this.uniqueHandlers = uniqueHandlers;
}
public void setActionSender(MiscPacketBuilder actionSender) {
this.actionSender = actionSender;
}
public void setPacketQueue(PacketQueue<LSPacket> packetQueue) {
this.packetQueue = packetQueue;
}
public void setSession(IoSession session) {
this.session = session;
}
public LoginConnector() {
packetQueue = new PacketQueue<LSPacket>();
loadPacketHandlers();
reconnect();
}
public MiscPacketBuilder getActionSender() {
return actionSender;
}
public PacketQueue<LSPacket> getPacketQueue() {
return packetQueue;
}
public IoSession getSession() {
return session;
}
public boolean isRegistered() {
return registered;
}
public void kill() {
running = false;
Logger.print("Unregistering world (" + Config.SERVER_NUM + ") with LS");
actionSender.unregisterWorld();
}
private void loadPacketHandlers() {
PacketHandlerDef[] handlerDefs = (PacketHandlerDef[]) PersistenceManager
.load("LSPacketHandlers.xml");
for (PacketHandlerDef handlerDef : handlerDefs) {
try {
String className = handlerDef.getClassName();
Class<?> c = Class.forName(className);
if (c != null) {
PacketHandler handler = (PacketHandler) c.newInstance();
for (int packetID : handlerDef.getAssociatedPackets()) {
packetHandlers.put(packetID, handler);
}
}
} catch (Exception e) {
Logger.error(e);
}
}
}
public void processIncomingPackets() {
for (LSPacket p : packetQueue.getPackets()) {
PacketHandler handler;
if (((handler = uniqueHandlers.get(p.getUID())) != null)
|| ((handler = packetHandlers.get(p.getID())) != null)) {
try {
handler.handlePacket(p, session);
uniqueHandlers.remove(p.getUID());
} catch (Exception e) {
Logger.error("Exception with p[" + p.getID()
+ "] from LOGIN_SERVER: " + e.getMessage());
}
} else {
Logger.error("Unhandled packet from LS: " + p.getID());
}
}
}
public boolean reconnect() {
try {
handler.handlePacket(p, session);
uniqueHandlers.remove(p.getUID());
Logger.println("Attempting to connect to LS");
SocketConnector conn = new SocketConnector();
SocketConnectorConfig config = new SocketConnectorConfig();
((SocketSessionConfig) config.getSessionConfig())
.setKeepAlive(true);
((SocketSessionConfig) config.getSessionConfig())
.setTcpNoDelay(true);
ConnectFuture future = conn.connect(new InetSocketAddress(
Config.LS_IP, Config.LS_PORT), connectionHandler, config);
future.join(3000);
if (future.isConnected()) {
session = future.getSession();
Logger.println("Registering world (" + Config.SERVER_NUM
+ ") with LS");
actionSender.registerWorld();
connectionAttempts = 0;
return true;
}
if (connectionAttempts++ >= 100) {
Logger.println("Unable to connect to LS, giving up after "
+ connectionAttempts + " tries");
System.exit(1);
return false;
}
return reconnect();
} catch (Exception e) {
Logger.error("Exception with p[" + p.getID() + "] from LOGIN_SERVER: " + e.getMessage());
Logger.println("Error connecting to LS: " + e.getMessage());
return false;
}
} else {
Logger.error("Unhandled packet from LS: " + p.getID());
}
}
}
public boolean reconnect() {
try {
Logger.println("Attempting to connect to LS");
SocketConnector conn = new SocketConnector();
SocketConnectorConfig config = new SocketConnectorConfig();
((SocketSessionConfig) config.getSessionConfig()).setKeepAlive(true);
((SocketSessionConfig) config.getSessionConfig()).setTcpNoDelay(true);
ConnectFuture future = conn.connect(new InetSocketAddress(Config.LS_IP, Config.LS_PORT), connectionHandler, config);
future.join(3000);
if (future.isConnected()) {
session = future.getSession();
Logger.println("Registering world (" + Config.SERVER_NUM + ") with LS");
actionSender.registerWorld();
connectionAttempts = 0;
return true;
}
if (connectionAttempts++ >= 100) {
Logger.println("Unable to connect to LS, giving up after " + connectionAttempts + " tries");
System.exit(1);
return false;
}
return reconnect();
} catch (Exception e) {
Logger.println("Error connecting to LS: " + e.getMessage());
return false;
public boolean running() {
return running;
}
}
public boolean running() {
return running;
}
public synchronized void sendQueuedPackets() {
try {
List<LSPacket> packets = actionSender.getPackets();
for (LSPacket packet : packets) {
session.write(packet);
}
actionSender.clearPackets();
} catch (Exception e) {
Logger.println("Stack processInc: ");
e.printStackTrace();
public synchronized void sendQueuedPackets() {
try {
List<LSPacket> packets = actionSender.getPackets();
for (LSPacket packet : packets) {
session.write(packet);
}
actionSender.clearPackets();
} catch (Exception e) {
Logger.println("Stack processInc: ");
e.printStackTrace();
}
}
}
public void setHandler(long uID, PacketHandler handler) {
uniqueHandlers.put(uID, handler);
}
public void setRegistered(boolean registered) {
if (registered) {
this.registered = true;
Logger.print("World successfully registered with LS");
} else {
Logger.error(new Exception("Error registering world"));
public void setHandler(long uID, PacketHandler handler) {
uniqueHandlers.put(uID, handler);
}
public void setRegistered(boolean registered) {
if (registered) {
this.registered = true;
Logger.print("World successfully registered with LS");
} else {
Logger.error(new Exception("Error registering world"));
}
}
}
}

View File

@ -1,7 +1,5 @@
package org.moparscape.msc.gs.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
@ -10,14 +8,11 @@ import java.sql.Statement;
import org.moparscape.msc.config.Config;
import org.moparscape.msc.gs.util.Logger;
/**
* Used to interact with the database.
*/
public class DBConnection {
/**
* The database connection in use
*/
@ -30,18 +25,19 @@ public class DBConnection {
* Report2Database handleing logic
*/
private static ReportHandlerQueries reportDB = new ReportHandlerQueries();
/**
* Getter for reportDB
*
* @return reportDB
*/
public static ReportHandlerQueries getReport() {
return reportDB;
}
static
{
static {
testForDriver();
}
}
/**
* Tests we have a mysql Driver
@ -49,8 +45,7 @@ public class DBConnection {
private static void testForDriver() {
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException cnfe) {
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
}
@ -59,25 +54,27 @@ public class DBConnection {
* Instantiates a new database connection
*/
public DBConnection() {
if(!createConnection()) {
if (!createConnection()) {
new Exception("Unable to connect to MySQL").printStackTrace();
System.exit(1);
}
else {
} else {
Logger.println("Database connection achieved.");
}
}
public void initilizePreparedStatements(DBConnection db) {
reportDB.initilizePreparedStatements(db);
}
public boolean createConnection() {
try {
con = DriverManager.getConnection("jdbc:mysql://" + Config.MYSQL_HOST + "/" + Config.MYSQL_DB, Config.MYSQL_USER, Config.MYSQL_PASS);
con = DriverManager.getConnection("jdbc:mysql://"
+ Config.MYSQL_HOST + "/" + Config.MYSQL_DB,
Config.MYSQL_USER, Config.MYSQL_PASS);
statement = con.createStatement();
statement.setEscapeProcessing(true);
return isConnected();
}
catch(SQLException e) {
} catch (SQLException e) {
e.printStackTrace();
return false;
}
@ -87,52 +84,43 @@ public class DBConnection {
try {
statement.executeQuery("SELECT CURRENT_DATE");
return true;
}
catch(SQLException e) {
} catch (SQLException e) {
return false;
}
}
public Connection getConnection() {
return con;
}
/*
public synchronized int updateUserStats(String user, int messages, int modes, int kicks, int kicked, long lastTimeSpoken, int joins, int parts, String randomstring, int moderatedchan) throws SQLException {
existingRecord.setString(1, user);
existingRecord.execute();
if(existingRecord.getResultSet().next()) { // Existing
existingUserQuery.setInt(1, messages);
existingUserQuery.setInt(2, modes);
existingUserQuery.setInt(3, kicks);
existingUserQuery.setInt(4, kicked);
existingUserQuery.setLong(5, lastTimeSpoken);
existingUserQuery.setInt(6, joins);
existingUserQuery.setInt(7, parts);
existingUserQuery.setString(8, randomstring);
existingUserQuery.setInt(9, moderatedchan);
existingUserQuery.setString(10, user);
return existingUserQuery.executeUpdate();
}
else { // New record
newUserQuery.setString(1, user);
newUserQuery.setInt(2, messages);
newUserQuery.setInt(3, modes);
newUserQuery.setInt(4, kicks);
newUserQuery.setInt(5, kicked);
newUserQuery.setLong(6, lastTimeSpoken);
newUserQuery.setInt(7, joins);
newUserQuery.setInt(8, parts);
newUserQuery.setString(9, randomstring);
newUserQuery.setInt(10, moderatedchan);
return newUserQuery.executeUpdate();
}
}
*/
/*
* public synchronized int updateUserStats(String user, int messages, int
* modes, int kicks, int kicked, long lastTimeSpoken, int joins, int parts,
* String randomstring, int moderatedchan) throws SQLException {
* existingRecord.setString(1, user); existingRecord.execute();
* if(existingRecord.getResultSet().next()) { // Existing
* existingUserQuery.setInt(1, messages); existingUserQuery.setInt(2,
* modes); existingUserQuery.setInt(3, kicks); existingUserQuery.setInt(4,
* kicked); existingUserQuery.setLong(5, lastTimeSpoken);
* existingUserQuery.setInt(6, joins); existingUserQuery.setInt(7, parts);
* existingUserQuery.setString(8, randomstring); existingUserQuery.setInt(9,
* moderatedchan); existingUserQuery.setString(10, user); return
* existingUserQuery.executeUpdate(); } else { // New record
* newUserQuery.setString(1, user); newUserQuery.setInt(2, messages);
* newUserQuery.setInt(3, modes); newUserQuery.setInt(4, kicks);
* newUserQuery.setInt(5, kicked); newUserQuery.setLong(6, lastTimeSpoken);
* newUserQuery.setInt(7, joins); newUserQuery.setInt(8, parts);
* newUserQuery.setString(9, randomstring); newUserQuery.setInt(10,
* moderatedchan); return newUserQuery.executeUpdate(); }
*
* }
*/
/**
* Closes the database conection.
*
* @throws SQLException if there was an error when closing the connection
*
* @throws SQLException
* if there was an error when closing the connection
*/
public void close() throws SQLException {
con.close();

View File

@ -13,80 +13,94 @@ import org.moparscape.msc.gs.model.snapshot.Chatlog;
import org.moparscape.msc.gs.model.snapshot.Snapshot;
import org.moparscape.msc.gs.util.Logger;
public class ReportHandlerQueries {
/**
* Inserts a new row into "msc2_reports" table
*/
private PreparedStatement insertNewReportRow;
private PreparedStatement insertNewDupeDataRow;
/**
* Initilizes prepared statements, if failed, shuts down the server.
*/
public void initilizePreparedStatements(DBConnection db) {
try {
insertNewReportRow = db.getConnection().prepareStatement("INSERT INTO `msc2_reports` (`from`, `about`, `time`, `reason`, `snapshot_from`,`snapshot_about`,`chatlogs`, `from_x`, `from_y`, `about_x`, `about_y`) VALUES(?,?,?,?,?,?,?,?,?,?,?)");
insertNewDupeDataRow = db.getConnection().prepareStatement("INSERT INTO `dupe_data` (`user`, `userhash`, `string`, `time`) VALUES(?,?,?,?);");
insertNewReportRow = db
.getConnection()
.prepareStatement(
"INSERT INTO `msc2_reports` (`from`, `about`, `time`, `reason`, `snapshot_from`,`snapshot_about`,`chatlogs`, `from_x`, `from_y`, `about_x`, `about_y`) VALUES(?,?,?,?,?,?,?,?,?,?,?)");
insertNewDupeDataRow = db
.getConnection()
.prepareStatement(
"INSERT INTO `dupe_data` (`user`, `userhash`, `string`, `time`) VALUES(?,?,?,?);");
} catch (SQLException e) {
e.printStackTrace();
Logger.error(e);
}
}
/**
* Submits a report to the database
*
* Chatlogs, snapshots, locations etc are generated inside this method.
*
* @param from Players usernameHash (who reported)
* @param about Players usernameHash (who got reported)
* @param reason What type of a report is this
* @param from
* Players usernameHash (who reported)
* @param about
* Players usernameHash (who got reported)
* @param reason
* What type of a report is this
*/
public synchronized void submitRepot(long from, long about, byte reason, Player from2) {
long time = GameEngine.getTime()/1000;
String f = org.moparscape.msc.gs.tools.DataConversions.hashToUsername(from);
String a = org.moparscape.msc.gs.tools.DataConversions.hashToUsername(about);
public synchronized void submitRepot(long from, long about, byte reason,
Player from2) {
long time = GameEngine.getTime() / 1000;
String f = org.moparscape.msc.gs.tools.DataConversions
.hashToUsername(from);
String a = org.moparscape.msc.gs.tools.DataConversions
.hashToUsername(about);
Player about2 = World.getWorld().getPlayer(about);
int player2X;
int player2Y;
if(about2 == null) {
if (about2 == null) {
player2X = 0;
player2Y = 0;
}
else {
} else {
player2X = about2.getX();
player2Y = about2.getY();
}
StringBuilder snapshot_from = new StringBuilder();
StringBuilder snapshot_about = new StringBuilder();
StringBuilder chatlog = new StringBuilder();
Iterator<Snapshot> i = Instance.getWorld().getSnapshots().descendingIterator();
Iterator<Snapshot> i = Instance.getWorld().getSnapshots()
.descendingIterator();
while (i.hasNext()) {
Snapshot s = i.next();
if(s instanceof Chatlog) {
Chatlog cl = (Chatlog)s;
if (s instanceof Chatlog) {
Chatlog cl = (Chatlog) s;
if (cl.getRecievers().contains(a) || cl.getOwner().equals(a)) {
chatlog.append((cl.getTimestamp()/1000) + " <" + cl.getOwner() + "> " + cl.getMessage() + "\n");
chatlog.append((cl.getTimestamp() / 1000) + " <"
+ cl.getOwner() + "> " + cl.getMessage() + "\n");
}
}
else if (s instanceof Activity) {
Activity ac = (Activity)s;
if(ac.getOwner().equals(f)) {
snapshot_from.append((ac.getTimestamp()/1000) + " " + ac.getActivity() + "\n");
}
else if(ac.getOwner().equals(a)) {
snapshot_about.append((ac.getTimestamp()/1000) + " " + ac.getActivity() + "\n");
} else if (s instanceof Activity) {
Activity ac = (Activity) s;
if (ac.getOwner().equals(f)) {
snapshot_from.append((ac.getTimestamp() / 1000) + " "
+ ac.getActivity() + "\n");
} else if (ac.getOwner().equals(a)) {
snapshot_about.append((ac.getTimestamp() / 1000) + " "
+ ac.getActivity() + "\n");
}
}
}
try {
insertNewReportRow.setLong(1, from);
insertNewReportRow.setLong(2, about);
insertNewReportRow.setLong(3, time);
insertNewReportRow.setLong(2, about);
insertNewReportRow.setLong(3, time);
insertNewReportRow.setInt(4, reason);
insertNewReportRow.setString(5, snapshot_from.toString());
insertNewReportRow.setString(6, snapshot_about.toString());
@ -99,36 +113,39 @@ public class ReportHandlerQueries {
} catch (SQLException e) {
e.printStackTrace();
Logger.error(e);
}
}
}
public synchronized void submitDupeData(String username, Long hash) {
StringBuilder data = new StringBuilder();
Iterator<Snapshot> i = Instance.getWorld().getSnapshots().descendingIterator();
Iterator<Snapshot> i = Instance.getWorld().getSnapshots()
.descendingIterator();
while (i.hasNext()) {
Snapshot s = i.next();
if(s instanceof Chatlog) {
Chatlog cl = (Chatlog)s;
if (cl.getRecievers().contains(username) || cl.getOwner().equals(username)) {
data.append((cl.getTimestamp()/1000) + " <" + cl.getOwner() + "> " + cl.getMessage() + "\n");
if (s instanceof Chatlog) {
Chatlog cl = (Chatlog) s;
if (cl.getRecievers().contains(username)
|| cl.getOwner().equals(username)) {
data.append((cl.getTimestamp() / 1000) + " <"
+ cl.getOwner() + "> " + cl.getMessage() + "\n");
}
}
else if (s instanceof Activity) {
Activity ac = (Activity)s;
if(ac.getOwner().equals(username)) {
data.append((ac.getTimestamp()/1000) + " " + ac.getActivity() + "\n");
} else if (s instanceof Activity) {
Activity ac = (Activity) s;
if (ac.getOwner().equals(username)) {
data.append((ac.getTimestamp() / 1000) + " "
+ ac.getActivity() + "\n");
}
}
}
try {
insertNewDupeDataRow.setString(1, username);
insertNewDupeDataRow.setLong(2, hash);
insertNewDupeDataRow.setString(3, data.toString());
insertNewDupeDataRow.setLong(4,GameEngine.getTime());
insertNewDupeDataRow.setLong(2, hash);
insertNewDupeDataRow.setString(3, data.toString());
insertNewDupeDataRow.setLong(4, GameEngine.getTime());
insertNewDupeDataRow.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
Logger.error(e);
}
}
}
}

View File

@ -7,78 +7,80 @@ import org.moparscape.msc.gs.model.Player;
import org.moparscape.msc.gs.model.World;
public abstract class DelayedEvent {
public static final World world = Instance.getWorld();
protected int delay = 500;
protected final DelayedEventHandler handler = Instance.getWorld().getDelayedEventHandler();
private long lastRun = GameEngine.getTime();
protected Player owner;
protected boolean matchRunning = true;
public Object[] args = null;
public static final World world = Instance.getWorld();
protected int delay = 500;
protected final DelayedEventHandler handler = Instance.getWorld()
.getDelayedEventHandler();
private long lastRun = GameEngine.getTime();
protected Player owner;
protected boolean matchRunning = true;
public Object[] args = null;
// f2p
public DelayedEvent(Player owner, int delay) {
this.owner = owner;
this.delay = delay;
}
// f2p
public DelayedEvent(Player owner, int delay) {
this.owner = owner;
this.delay = delay;
}
public DelayedEvent(Player owner, int delay, Object[] arg) {
args = arg;
this.owner = owner;
this.delay = delay;
}
public DelayedEvent(Player owner, int delay, Object[] arg) {
args = arg;
this.owner = owner;
this.delay = delay;
}
public boolean belongsTo(Player player) {
return owner != null && owner.equals(player);
}
public boolean belongsTo(Player player) {
return owner != null && owner.equals(player);
}
public int getDelay() {
return delay;
}
public int getDelay() {
return delay;
}
public Object getIdentifier() {
return null;
}
public Object getIdentifier() {
return null;
}
public Player getOwner() {
return owner;
}
public Player getOwner() {
return owner;
}
public boolean hasOwner() {
return owner != null;
}
public boolean hasOwner() {
return owner != null;
}
public boolean is(DelayedEvent e) {
return (e.getIdentifier() != null && e.getIdentifier().equals(getIdentifier()));
}
public boolean is(DelayedEvent e) {
return (e.getIdentifier() != null && e.getIdentifier().equals(
getIdentifier()));
}
public abstract void run();
public abstract void run();
public void setDelay(int delay) {
this.delay = delay;
}
public void setDelay(int delay) {
this.delay = delay;
}
public void setLastRun(long time) {
lastRun = time;
}
public void setLastRun(long time) {
lastRun = time;
}
public final boolean shouldRemove() {
return !matchRunning;
}
public final boolean shouldRemove() {
return !matchRunning;
}
public final boolean shouldRun() {
return matchRunning && GameEngine.getTime() - lastRun >= delay;
}
public final boolean shouldRun() {
return matchRunning && GameEngine.getTime() - lastRun >= delay;
}
public final void stop() {
matchRunning = false;
}
public final void stop() {
matchRunning = false;
}
public int timeTillNextRun() {
int time = (int) (delay - (GameEngine.getTime() - lastRun));
return time < 0 ? 0 : time;
}
public int timeTillNextRun() {
int time = (int) (delay - (GameEngine.getTime() - lastRun));
return time < 0 ? 0 : time;
}
public final void updateLastRun() {
lastRun = GameEngine.getTime();
}
public final void updateLastRun() {
lastRun = GameEngine.getTime();
}
}

View File

@ -5,28 +5,28 @@ import org.moparscape.msc.gs.model.Npc;
import org.moparscape.msc.gs.model.Player;
public abstract class DelayedQuestChat extends DelayedEvent {
public int curIndex;
public String[] messages;
public Npc npc;
public Player owner;
public int curIndex;
public String[] messages;
public Npc npc;
public Player owner;
public DelayedQuestChat(Npc npc, Player owner, String[] messages) {
super(null, 2200);
this.owner = owner;
this.npc = npc;
this.messages = messages;
curIndex = 0;
}
public abstract void finished();
public void run() {
owner.informOfNpcMessage(new ChatMessage(npc, messages[curIndex], owner));
curIndex++;
if (curIndex == messages.length) {
finished();
stop();
return;
public DelayedQuestChat(Npc npc, Player owner, String[] messages) {
super(null, 2200);
this.owner = owner;
this.npc = npc;
this.messages = messages;
curIndex = 0;
}
public abstract void finished();
public void run() {
owner.informOfNpcMessage(new ChatMessage(npc, messages[curIndex], owner));
curIndex++;
if (curIndex == messages.length) {
finished();
stop();
return;
}
}
}
}

View File

@ -7,98 +7,101 @@ import org.moparscape.msc.gs.model.Player;
import org.moparscape.msc.gs.states.CombatState;
import org.moparscape.msc.gs.tools.DataConversions;
public class DuelEvent extends DelayedEvent {
private Player affectedPlayer;
private int hits;
private Player affectedPlayer;
private int hits;
public DuelEvent(Player owner, Player affectedPlayer) {
super(owner, 1300);
this.affectedPlayer = affectedPlayer;
hits = 0;
}
public boolean equals(Object o) {
if (o instanceof DuelEvent) {
DuelEvent e = (DuelEvent) o;
return e.belongsTo(owner) && e.getAffectedPlayer().equals(affectedPlayer);
public DuelEvent(Player owner, Player affectedPlayer) {
super(owner, 1300);
this.affectedPlayer = affectedPlayer;
hits = 0;
}
return false;
}
public Player getAffectedPlayer() {
return affectedPlayer;
}
public void run() {
if (!owner.loggedIn() || !affectedPlayer.loggedIn()) {
owner.resetCombat(CombatState.ERROR);
affectedPlayer.resetCombat(CombatState.ERROR);
return;
}
Player attacker, opponent;
if (hits++ % 2 == 0) {
attacker = owner;
opponent = affectedPlayer;
} else {
attacker = affectedPlayer;
opponent = owner;
}
if (opponent.getHits() <= 0) {
attacker.resetCombat(CombatState.WON);
opponent.resetCombat(CombatState.LOST);
return;
}
attacker.incHitsMade();
attacker.setLastMoved();
int damage = (attacker instanceof Player && opponent instanceof Player ? Formulae.calcFightHit(attacker, opponent) : Formulae.calcFightHitWithNPC(attacker, opponent));
opponent.setLastDamage(damage);
int newHp = opponent.getHits() - damage;
opponent.setHits(newHp);
ArrayList<Player> playersToInform = new ArrayList<Player>();
playersToInform.addAll(opponent.getViewArea().getPlayersInView());
playersToInform.addAll(attacker.getViewArea().getPlayersInView());
for (Player p : playersToInform) {
p.informOfModifiedHits(opponent);
}
String combatSound = damage > 0 ? "combat1b" : "combat1a";
opponent.getActionSender().sendStat(3);
opponent.getActionSender().sendSound(combatSound);
attacker.getActionSender().sendSound(combatSound);
if (newHp <= 0) {
opponent.killedBy(attacker, true);
int exp = DataConversions.roundUp(Formulae.combatExperience(opponent) / 4D);
switch (attacker.getCombatStyle()) {
case 0:
for (int x = 0; x < 3; x++) {
attacker.incExp(x, exp, true);
attacker.getActionSender().sendStat(x);
public boolean equals(Object o) {
if (o instanceof DuelEvent) {
DuelEvent e = (DuelEvent) o;
return e.belongsTo(owner)
&& e.getAffectedPlayer().equals(affectedPlayer);
}
return false;
}
public Player getAffectedPlayer() {
return affectedPlayer;
}
public void run() {
if (!owner.loggedIn() || !affectedPlayer.loggedIn()) {
owner.resetCombat(CombatState.ERROR);
affectedPlayer.resetCombat(CombatState.ERROR);
return;
}
Player attacker, opponent;
if (hits++ % 2 == 0) {
attacker = owner;
opponent = affectedPlayer;
} else {
attacker = affectedPlayer;
opponent = owner;
}
if (opponent.getHits() <= 0) {
attacker.resetCombat(CombatState.WON);
opponent.resetCombat(CombatState.LOST);
return;
}
attacker.incHitsMade();
attacker.setLastMoved();
int damage = (attacker instanceof Player && opponent instanceof Player ? Formulae
.calcFightHit(attacker, opponent) : Formulae
.calcFightHitWithNPC(attacker, opponent));
opponent.setLastDamage(damage);
int newHp = opponent.getHits() - damage;
opponent.setHits(newHp);
ArrayList<Player> playersToInform = new ArrayList<Player>();
playersToInform.addAll(opponent.getViewArea().getPlayersInView());
playersToInform.addAll(attacker.getViewArea().getPlayersInView());
for (Player p : playersToInform) {
p.informOfModifiedHits(opponent);
}
String combatSound = damage > 0 ? "combat1b" : "combat1a";
opponent.getActionSender().sendStat(3);
opponent.getActionSender().sendSound(combatSound);
attacker.getActionSender().sendSound(combatSound);
if (newHp <= 0) {
opponent.killedBy(attacker, true);
int exp = DataConversions.roundUp(Formulae
.combatExperience(opponent) / 4D);
switch (attacker.getCombatStyle()) {
case 0:
for (int x = 0; x < 3; x++) {
attacker.incExp(x, exp, true);
attacker.getActionSender().sendStat(x);
}
break;
case 1:
attacker.incExp(2, exp * 3, true);
attacker.getActionSender().sendStat(2);
break;
case 2:
attacker.incExp(0, exp * 3, true);
attacker.getActionSender().sendStat(0);
break;
case 3:
attacker.incExp(1, exp * 3, true);
attacker.getActionSender().sendStat(1);
break;
}
attacker.incExp(3, exp, true);
attacker.getActionSender().sendStat(3);
attacker.resetCombat(CombatState.WON);
opponent.resetCombat(CombatState.LOST);
attacker.resetDueling();
opponent.resetDueling();
}
break;
case 1:
attacker.incExp(2, exp * 3, true);
attacker.getActionSender().sendStat(2);
break;
case 2:
attacker.incExp(0, exp * 3, true);
attacker.getActionSender().sendStat(0);
break;
case 3:
attacker.incExp(1, exp * 3, true);
attacker.getActionSender().sendStat(1);
break;
}
attacker.incExp(3, exp, true);
attacker.getActionSender().sendStat(3);
attacker.resetCombat(CombatState.WON);
opponent.resetCombat(CombatState.LOST);
attacker.resetDueling();
opponent.resetDueling();
}
}
}

View File

@ -9,7 +9,6 @@ import org.moparscape.msc.gs.model.Mob;
import org.moparscape.msc.gs.model.Npc;
import org.moparscape.msc.gs.model.Path;
import org.moparscape.msc.gs.model.Player;
import org.moparscape.msc.gs.model.World;
import org.moparscape.msc.gs.model.mini.Damage;
import org.moparscape.msc.gs.states.CombatState;
import org.moparscape.msc.gs.tools.DataConversions;
@ -83,20 +82,12 @@ public class FightEvent extends DelayedEvent {
if (attacker.getHits() <= 0) {
n.resetCombat(CombatState.ERROR);
}
if (n == null) {
Player p = (Player) opponent;
p.resetCombat(CombatState.ERROR);
}
}
if (opponent instanceof Npc) {
Npc n = (Npc) opponent;
if (opponent.getHits() <= 0) {
n.resetCombat(CombatState.ERROR);
}
if (n == null) {
Player p = (Player) attacker;
p.resetCombat(CombatState.ERROR);
}
}
if (opponent instanceof Player && attacker instanceof Player) {
if (((Player) opponent).isSleeping()) {

View File

@ -4,18 +4,18 @@ import org.moparscape.msc.gs.model.Player;
public abstract class MiniEvent extends SingleEvent {
public MiniEvent(Player owner) {
super(owner, 500);
}
public MiniEvent(Player owner) {
super(owner, 500);
}
public MiniEvent(Player owner, int delay) {
super(owner, delay);
}
public MiniEvent(Player owner, int delay) {
super(owner, delay);
}
public MiniEvent(Player owner, int delay, Object[] arg) {
super(owner, delay, arg);
}
public MiniEvent(Player owner, int delay, Object[] arg) {
super(owner, delay, arg);
}
public abstract void action();
public abstract void action();
}

View File

@ -6,34 +6,34 @@ import org.moparscape.msc.gs.model.GameObject;
import org.moparscape.msc.gs.model.World;
public class ObjectRemover extends DelayedEvent {
public static final World world = Instance.getWorld();
private GameObject object;
public static final World world = Instance.getWorld();
private GameObject object;
public ObjectRemover(GameObject object, int delay) {
super(null, delay);
this.object = object;
}
public boolean equals(Object o) {
if (o instanceof ObjectRemover) {
return ((ObjectRemover) o).getObject().equals(getObject());
public ObjectRemover(GameObject object, int delay) {
super(null, delay);
this.object = object;
}
return false;
}
public GameObject getObject() {
return object;
}
public void run() {
ActiveTile tile = world.getTile(object.getLocation());
if (!tile.hasGameObject() || !tile.getGameObject().equals(object)) {
super.matchRunning = false;
return;
public boolean equals(Object o) {
if (o instanceof ObjectRemover) {
return ((ObjectRemover) o).getObject().equals(getObject());
}
return false;
}
public GameObject getObject() {
return object;
}
public void run() {
ActiveTile tile = world.getTile(object.getLocation());
if (!tile.hasGameObject() || !tile.getGameObject().equals(object)) {
super.matchRunning = false;
return;
}
tile.remove(object);
world.unregisterGameObject(object);
super.matchRunning = false;
}
tile.remove(object);
world.unregisterGameObject(object);
super.matchRunning = false;
}
}

View File

@ -17,266 +17,295 @@ import org.moparscape.msc.gs.model.mini.Damage;
import org.moparscape.msc.gs.states.Action;
import org.moparscape.msc.gs.tools.DataConversions;
public class RangeEvent extends DelayedEvent {
private Mob affectedMob;
public int[][] allowedArrows = { { 189, 11, 638 }, // Shortbow
{ 188, 11, 638 }, // Longbow
{ 649, 11, 638 }, // Oak Shortbow
{ 648, 11, 638, 640 }, // Oak Longbow
{ 651, 11, 638, 640 }, // Willow Shortbow
{ 650, 11, 638, 640, 642 }, // Willow Longbow
{ 653, 11, 638, 640, 642 }, // Maple Shortbow
{ 652, 11, 638, 640, 642, 644 }, // Maple Longbow
{ 655, 11, 638, 640, 642, 644 }, // Yew Shortbow
{ 654, 11, 638, 640, 642, 644, 646 }, // Yew Longbow
{ 657, 11, 638, 640, 642, 644, 646 }, // Magic Shortbow
{ 656, 11, 638, 640, 642, 644, 646 } // Magic Longbow
};
private Mob affectedMob;
public int[][] allowedArrows = { { 189, 11, 638 }, // Shortbow
{ 188, 11, 638 }, // Longbow
{ 649, 11, 638 }, // Oak Shortbow
{ 648, 11, 638, 640 }, // Oak Longbow
{ 651, 11, 638, 640 }, // Willow Shortbow
{ 650, 11, 638, 640, 642 }, // Willow Longbow
{ 653, 11, 638, 640, 642 }, // Maple Shortbow
{ 652, 11, 638, 640, 642, 644 }, // Maple Longbow
{ 655, 11, 638, 640, 642, 644 }, // Yew Shortbow
{ 654, 11, 638, 640, 642, 644, 646 }, // Yew Longbow
{ 657, 11, 638, 640, 642, 644, 646 }, // Magic Shortbow
{ 656, 11, 638, 640, 642, 644, 646 } // Magic Longbow
};
private boolean firstRun = true;
private boolean firstRun = true;
public RangeEvent(Player owner, Mob affectedMob) {
super(owner, 2000);
this.affectedMob = affectedMob;
}
public boolean equals(Object o) {
if (o instanceof RangeEvent) {
RangeEvent e = (RangeEvent) o;
return e.belongsTo(owner);
public RangeEvent(Player owner, Mob affectedMob) {
super(owner, 2000);
this.affectedMob = affectedMob;
}
return false;
}
public Mob getAffectedMob() {
return affectedMob;
}
private Item getArrows(int id) {
for (Item i : world.getTile(affectedMob.getLocation()).getItems()) {
if (i.getID() == id && i.visibleTo(owner) && !i.isRemoved()) {
return i;
}
}
return null;
}
public void run() {
int bowID = owner.getRangeEquip();
if (!owner.loggedIn() || (affectedMob instanceof Player && !((Player) affectedMob).loggedIn()) || affectedMob.getHits() <= 0 || !owner.checkAttack(affectedMob, true) || bowID < 0) {
owner.resetRange();
return;
}
if (owner.withinRange(affectedMob, 5)) {
if (owner.isFollowing()) {
owner.resetFollowing();
}
if (!owner.finishedPath()) {
owner.resetPath();
}
} else {
owner.setFollowing(affectedMob);
return;
}
if (!new PathGenerator(owner.getX(), owner.getY(), affectedMob.getX(), affectedMob.getY()).isValid()) {
owner.getActionSender().sendMessage("I can't get a clear shot from here");
owner.resetPath();
return;
}
boolean xbow = DataConversions.inArray(Formulae.xbowIDs, bowID);
int arrowID = -1;
for (int aID : (xbow ? Formulae.boltIDs : Formulae.arrowIDs)) {
int slot = owner.getInventory().getLastIndexById(aID);
if (slot < 0) {
continue;
}
InvItem arrow = owner.getInventory().get(slot);
if (arrow == null) { // This shouldn't happen
continue;
}
arrowID = aID;
if(owner.getLocation().inWilderness() && Config.f2pWildy) {
if(arrowID != 11 && arrowID != 190) {
owner.getActionSender().sendMessage("You may not use P2P (Member Item) Arrows in the F2P Wilderness");
owner.resetRange();
return;
public boolean equals(Object o) {
if (o instanceof RangeEvent) {
RangeEvent e = (RangeEvent) o;
return e.belongsTo(owner);
}
}
int newAmount = arrow.getAmount() - 1;
if (!xbow && arrowID > 0) {
int temp = -1;
return false;
}
for (int i = 0; i < allowedArrows.length; i++)
if (allowedArrows[i][0] == owner.getRangeEquip())
temp = i;
public Mob getAffectedMob() {
return affectedMob;
}
boolean canFire = false;
for (int i = 0; i < allowedArrows[temp].length; i++)
if (allowedArrows[temp][i] == aID)
canFire = true;
if (!canFire) {
owner.getActionSender().sendMessage("Your arrows are too powerful for your Bow.");
owner.resetRange();
return;
private Item getArrows(int id) {
for (Item i : world.getTile(affectedMob.getLocation()).getItems()) {
if (i.getID() == id && i.visibleTo(owner) && !i.isRemoved()) {
return i;
}
}
}
if (newAmount <= 0) {
owner.getInventory().remove(slot);
owner.getActionSender().sendInventory();
} else {
arrow.setAmount(newAmount);
owner.getActionSender().sendUpdateItem(slot);
}
break;
}
if (arrowID < 0) {
owner.getActionSender().sendMessage("You have run out of " + (xbow ? "bolts" : "arrows"));
owner.resetRange();
return;
}
if (affectedMob.isPrayerActivated(13)) {
if(!owner.shouldRangePass()) {
owner.getActionSender().sendMessage("Your missile got blocked");
return;
}
}
// if(owner.getRangeEquip())
int damage = Formulae.calcRangeHit(owner.getCurStat(4), owner.getRangePoints(), affectedMob.getArmourPoints(), arrowID);
if (affectedMob instanceof Npc) {
Npc npc = (Npc) affectedMob;
if(damage > 1 && npc.getID() == 477)
damage = damage / 2;
}
if (!Formulae.looseArrow(damage)) {
Item arrows = getArrows(arrowID);
if (arrows == null) {
world.registerItem(new Item(arrowID, affectedMob.getX(), affectedMob.getY(), 1, owner));
} else {
arrows.setAmount(arrows.getAmount() + 1);
}
}
if (firstRun) {
firstRun = false;
if (affectedMob instanceof Player) {
if(((Player)affectedMob).isSleeping()) {
((Player)affectedMob).getActionSender().sendWakeUp(false);
}
((Player) affectedMob).getActionSender().sendMessage(owner.getUsername() + " is shooting at you!");
}
}
if(affectedMob instanceof Npc && ((Npc)affectedMob).isScripted()) {
Instance.getPluginHandler().getNpcAIHandler(affectedMob.getID()).onRangedAttack(owner, (Npc) affectedMob);
}
if (affectedMob instanceof Npc) {
Npc npc = (Npc) affectedMob;
npc.getSyndicate().addDamage(owner, damage, Damage.RANGE_DAMAGE);
}
Projectile projectile = new Projectile(owner, affectedMob, 2);
ArrayList<Player> playersToInform = new ArrayList<Player>();
playersToInform.addAll(owner.getViewArea().getPlayersInView());
playersToInform.addAll(affectedMob.getViewArea().getPlayersInView());
for (Player p : playersToInform) {
p.informOfProjectile(projectile);
return null;
}
if (GameEngine.getTime() - affectedMob.lastTimeShot > 500) {
affectedMob.lastTimeShot = GameEngine.getTime();
affectedMob.setLastDamage(damage);
int newHp = affectedMob.getHits() - damage;
affectedMob.setHits(newHp);
if (affectedMob instanceof Npc && newHp > 0) {
Npc n = (Npc) affectedMob;
double max = n.getDef().hits;
double cur = n.getHits();
int percent = (int) ((cur / max) * 100);
if (n.isScripted())
Instance.getPluginHandler().getNpcAIHandler(n.getID()).onHealthPercentage(n, percent);
}
for (Player p : playersToInform) {
p.informOfModifiedHits(affectedMob);
}
if (affectedMob instanceof Player) {
Player affectedPlayer = (Player) affectedMob;
affectedPlayer.getActionSender().sendStat(3);
}
owner.getActionSender().sendSound("shoot");
owner.setArrowFired();
if (newHp <= 0) {
affectedMob.killedBy(owner, false);
owner.resetRange();
if (owner instanceof Player) {
Player attackerPlayer = (Player) owner;
if (affectedMob instanceof Npc) {
Npc npc = (Npc) affectedMob;
npc.getSyndicate().distributeExp(npc);
}
}
} else {
if (owner instanceof Player && affectedMob instanceof Npc) // We're ranging an NPC, so make it chase the player.
{
final Npc npc = (Npc) affectedMob;
final Player player = (Player) owner;
if (npc.isBusy() || npc.getChasing() != null)
public void run() {
int bowID = owner.getRangeEquip();
if (!owner.loggedIn()
|| (affectedMob instanceof Player && !((Player) affectedMob)
.loggedIn()) || affectedMob.getHits() <= 0
|| !owner.checkAttack(affectedMob, true) || bowID < 0) {
owner.resetRange();
return;
npc.resetPath();
npc.setChasing(player);
// Radius is 0 to prevent wallhacking by NPCs. Easiest
// method I
// can come up with for now.
Instance.getDelayedEventHandler().add(new WalkMobToMobEvent(affectedMob, owner, 0) {
public void arrived() {
if (affectedMob.isBusy() || player.isBusy()) {
npc.setChasing(null);
return;
}
npc.resetPath();
player.setBusy(true);
player.resetPath();
player.resetAll();
if (npc.isScripted())
Instance.getPluginHandler().getNpcAIHandler(npc.getID()).onNpcAttack(npc, player);
player.setStatus(Action.FIGHTING_MOB);
player.getActionSender().sendSound("underattack");
player.getActionSender().sendMessage("You are under attack!");
npc.setLocation(player.getLocation(), true);
for (Player p : npc.getViewArea().getPlayersInView())
p.removeWatchedNpc(npc);
player.setBusy(true);
player.setSprite(9);
player.setOpponent(npc);
player.setCombatTimer();
npc.setBusy(true);
npc.setSprite(8);
npc.setOpponent(player);
npc.setCombatTimer();
npc.setChasing(null);
FightEvent fighting = new FightEvent(player, npc, true);
fighting.setLastRun(0);
Instance.getDelayedEventHandler().add(fighting);
}
public void failed() {
npc.setChasing(null);
}
});
}
}
if (owner.withinRange(affectedMob, 5)) {
if (owner.isFollowing()) {
owner.resetFollowing();
}
if (!owner.finishedPath()) {
owner.resetPath();
}
} else {
owner.setFollowing(affectedMob);
return;
}
if (!new PathGenerator(owner.getX(), owner.getY(), affectedMob.getX(),
affectedMob.getY()).isValid()) {
owner.getActionSender().sendMessage(
"I can't get a clear shot from here");
owner.resetPath();
return;
}
boolean xbow = DataConversions.inArray(Formulae.xbowIDs, bowID);
int arrowID = -1;
for (int aID : (xbow ? Formulae.boltIDs : Formulae.arrowIDs)) {
int slot = owner.getInventory().getLastIndexById(aID);
if (slot < 0) {
continue;
}
InvItem arrow = owner.getInventory().get(slot);
if (arrow == null) { // This shouldn't happen
continue;
}
arrowID = aID;
if (owner.getLocation().inWilderness() && Config.f2pWildy) {
if (arrowID != 11 && arrowID != 190) {
owner.getActionSender()
.sendMessage(
"You may not use P2P (Member Item) Arrows in the F2P Wilderness");
owner.resetRange();
return;
}
}
int newAmount = arrow.getAmount() - 1;
if (!xbow && arrowID > 0) {
int temp = -1;
for (int i = 0; i < allowedArrows.length; i++)
if (allowedArrows[i][0] == owner.getRangeEquip())
temp = i;
boolean canFire = false;
for (int i = 0; i < allowedArrows[temp].length; i++)
if (allowedArrows[temp][i] == aID)
canFire = true;
if (!canFire) {
owner.getActionSender().sendMessage(
"Your arrows are too powerful for your Bow.");
owner.resetRange();
return;
}
}
if (newAmount <= 0) {
owner.getInventory().remove(slot);
owner.getActionSender().sendInventory();
} else {
arrow.setAmount(newAmount);
owner.getActionSender().sendUpdateItem(slot);
}
break;
}
if (arrowID < 0) {
owner.getActionSender().sendMessage(
"You have run out of " + (xbow ? "bolts" : "arrows"));
owner.resetRange();
return;
}
if (affectedMob.isPrayerActivated(13)) {
if (!owner.shouldRangePass()) {
owner.getActionSender().sendMessage("Your missile got blocked");
return;
}
}
// if(owner.getRangeEquip())
int damage = Formulae.calcRangeHit(owner.getCurStat(4),
owner.getRangePoints(), affectedMob.getArmourPoints(), arrowID);
if (affectedMob instanceof Npc) {
Npc npc = (Npc) affectedMob;
if (damage > 1 && npc.getID() == 477)
damage = damage / 2;
}
if (!Formulae.looseArrow(damage)) {
Item arrows = getArrows(arrowID);
if (arrows == null) {
world.registerItem(new Item(arrowID, affectedMob.getX(),
affectedMob.getY(), 1, owner));
} else {
arrows.setAmount(arrows.getAmount() + 1);
}
}
if (firstRun) {
firstRun = false;
if (affectedMob instanceof Player) {
if (((Player) affectedMob).isSleeping()) {
((Player) affectedMob).getActionSender().sendWakeUp(false);
}
((Player) affectedMob).getActionSender().sendMessage(
owner.getUsername() + " is shooting at you!");
}
}
if (affectedMob instanceof Npc && ((Npc) affectedMob).isScripted()) {
Instance.getPluginHandler().getNpcAIHandler(affectedMob.getID())
.onRangedAttack(owner, (Npc) affectedMob);
}
if (affectedMob instanceof Npc) {
Npc npc = (Npc) affectedMob;
npc.getSyndicate().addDamage(owner, damage, Damage.RANGE_DAMAGE);
}
Projectile projectile = new Projectile(owner, affectedMob, 2);
ArrayList<Player> playersToInform = new ArrayList<Player>();
playersToInform.addAll(owner.getViewArea().getPlayersInView());
playersToInform.addAll(affectedMob.getViewArea().getPlayersInView());
for (Player p : playersToInform) {
p.informOfProjectile(projectile);
}
if (GameEngine.getTime() - affectedMob.lastTimeShot > 500) {
affectedMob.lastTimeShot = GameEngine.getTime();
affectedMob.setLastDamage(damage);
int newHp = affectedMob.getHits() - damage;
affectedMob.setHits(newHp);
if (affectedMob instanceof Npc && newHp > 0) {
Npc n = (Npc) affectedMob;
double max = n.getDef().hits;
double cur = n.getHits();
int percent = (int) ((cur / max) * 100);
if (n.isScripted())
Instance.getPluginHandler().getNpcAIHandler(n.getID())
.onHealthPercentage(n, percent);
}
for (Player p : playersToInform) {
p.informOfModifiedHits(affectedMob);
}
if (affectedMob instanceof Player) {
Player affectedPlayer = (Player) affectedMob;
affectedPlayer.getActionSender().sendStat(3);
}
owner.getActionSender().sendSound("shoot");
owner.setArrowFired();
if (newHp <= 0) {
affectedMob.killedBy(owner, false);
owner.resetRange();
if (owner instanceof Player) {
if (affectedMob instanceof Npc) {
Npc npc = (Npc) affectedMob;
npc.getSyndicate().distributeExp(npc);
}
}
} else {
if (owner instanceof Player && affectedMob instanceof Npc) // We're
// ranging
// an
// NPC,
// so
// make
// it
// chase
// the
// player.
{
final Npc npc = (Npc) affectedMob;
final Player player = (Player) owner;
if (npc.isBusy() || npc.getChasing() != null)
return;
npc.resetPath();
npc.setChasing(player);
// Radius is 0 to prevent wallhacking by NPCs. Easiest
// method I
// can come up with for now.
Instance.getDelayedEventHandler().add(
new WalkMobToMobEvent(affectedMob, owner, 0) {
public void arrived() {
if (affectedMob.isBusy() || player.isBusy()) {
npc.setChasing(null);
return;
}
npc.resetPath();
player.setBusy(true);
player.resetPath();
player.resetAll();
if (npc.isScripted())
Instance.getPluginHandler()
.getNpcAIHandler(npc.getID())
.onNpcAttack(npc, player);
player.setStatus(Action.FIGHTING_MOB);
player.getActionSender().sendSound(
"underattack");
player.getActionSender().sendMessage(
"You are under attack!");
npc.setLocation(player.getLocation(), true);
for (Player p : npc.getViewArea()
.getPlayersInView())
p.removeWatchedNpc(npc);
player.setBusy(true);
player.setSprite(9);
player.setOpponent(npc);
player.setCombatTimer();
npc.setBusy(true);
npc.setSprite(8);
npc.setOpponent(player);
npc.setCombatTimer();
npc.setChasing(null);
FightEvent fighting = new FightEvent(
player, npc, true);
fighting.setLastRun(0);
Instance.getDelayedEventHandler().add(
fighting);
}
public void failed() {
npc.setChasing(null);
}
});
}
}
}
}
}
}

View File

@ -4,10 +4,10 @@ import org.moparscape.msc.gs.model.Player;
public abstract class ShortEvent extends SingleEvent {
public ShortEvent(Player owner) {
super(owner, 1500);
}
public ShortEvent(Player owner) {
super(owner, 1500);
}
public abstract void action();
public abstract void action();
}

View File

@ -4,19 +4,19 @@ import org.moparscape.msc.gs.model.Player;
public abstract class SingleEvent extends DelayedEvent {
public SingleEvent(Player owner, int delay) {
super(owner, delay);
}
public SingleEvent(Player owner, int delay) {
super(owner, delay);
}
public SingleEvent(Player owner, int delay, Object[] arg) {
super(owner, delay, arg);
}
public SingleEvent(Player owner, int delay, Object[] arg) {
super(owner, delay, arg);
}
public abstract void action();
public abstract void action();
public void run() {
action();
super.matchRunning = false;
}
public void run() {
action();
super.matchRunning = false;
}
}

View File

@ -7,87 +7,95 @@ import org.moparscape.msc.gs.model.Npc;
import org.moparscape.msc.gs.model.Path;
public abstract class WalkMobToMobEvent extends DelayedEvent {
protected Mob affectedMob;
private NPCLoc loc = null;
protected Mob owner;
private int radius;
private long startTime = 0L;
protected Mob affectedMob;
private NPCLoc loc = null;
protected Mob owner;
private int radius;
private long startTime = 0L;
public WalkMobToMobEvent(Mob owner, Mob affectedMob, int radius) {
super(null, 500);
public WalkMobToMobEvent(Mob owner, Mob affectedMob, int radius) {
super(null, 500);
if (owner.isRemoved()) {
super.matchRunning = false;
return;
}
if (owner instanceof Npc) {
Npc npc = (Npc) owner;
loc = npc.getLoc();
if (affectedMob.getX() < (loc.minX() - 4) || affectedMob.getX() > (loc.maxX() + 4) || affectedMob.getY() < (loc.minY() - 4) || affectedMob.getY() > (loc.maxY() + 4)) {
super.matchRunning = false;
return;
}
}
this.owner = owner;
owner.setPath(new Path(owner.getX(), owner.getY(), affectedMob.getX(), affectedMob.getY()));
this.affectedMob = affectedMob;
this.radius = radius;
if (owner.withinRange(affectedMob, radius)) {
arrived();
super.matchRunning = false;
return;
}
startTime = GameEngine.getTime();
}
public abstract void arrived();
public void failed() {
}
public Mob getAffectedMob() {
return affectedMob;
}
public final void run() {
if (owner.isRemoved()) {
super.matchRunning = false;
return;
}
if (owner.withinRange(affectedMob, radius))
arrived();
else if (owner.hasMoved())
return; // We're still moving
else {
if (GameEngine.getTime() - startTime <= 10000) // Make NPCs
// give a 10
// second
// chase
{
if (loc != null) {
if (affectedMob.getX() < (loc.minX() - 4) || affectedMob.getX() > (loc.maxX() + 4) || affectedMob.getY() < (loc.minY() - 4) || affectedMob.getY() > (loc.maxY() + 4)) {
if (owner.isRemoved()) {
super.matchRunning = false;
failed();
return;
}
}
if (owner.isBusy())
return;
if (owner instanceof Npc) {
Npc npc = (Npc) owner;
loc = npc.getLoc();
owner.setPath(new Path(owner.getX(), owner.getY(), affectedMob.getX(), affectedMob.getY()));
return;
} else
failed();
if (affectedMob.getX() < (loc.minX() - 4)
|| affectedMob.getX() > (loc.maxX() + 4)
|| affectedMob.getY() < (loc.minY() - 4)
|| affectedMob.getY() > (loc.maxY() + 4)) {
super.matchRunning = false;
return;
}
}
this.owner = owner;
owner.setPath(new Path(owner.getX(), owner.getY(), affectedMob.getX(),
affectedMob.getY()));
this.affectedMob = affectedMob;
this.radius = radius;
if (owner.withinRange(affectedMob, radius)) {
arrived();
super.matchRunning = false;
return;
}
startTime = GameEngine.getTime();
}
super.matchRunning = false;
}
public abstract void arrived();
public void failed() {
}
public Mob getAffectedMob() {
return affectedMob;
}
public final void run() {
if (owner.isRemoved()) {
super.matchRunning = false;
return;
}
if (owner.withinRange(affectedMob, radius))
arrived();
else if (owner.hasMoved())
return; // We're still moving
else {
if (GameEngine.getTime() - startTime <= 10000) // Make NPCs
// give a 10
// second
// chase
{
if (loc != null) {
if (affectedMob.getX() < (loc.minX() - 4)
|| affectedMob.getX() > (loc.maxX() + 4)
|| affectedMob.getY() < (loc.minY() - 4)
|| affectedMob.getY() > (loc.maxY() + 4)) {
super.matchRunning = false;
failed();
return;
}
}
if (owner.isBusy())
return;
owner.setPath(new Path(owner.getX(), owner.getY(), affectedMob
.getX(), affectedMob.getY()));
return;
} else
failed();
}
super.matchRunning = false;
}
}

View File

@ -4,37 +4,37 @@ import org.moparscape.msc.gs.model.Mob;
import org.moparscape.msc.gs.model.Player;
public abstract class WalkToMobEvent extends DelayedEvent {
protected Mob affectedMob;
private int radius;
protected Mob affectedMob;
private int radius;
public WalkToMobEvent(Player owner, Mob affectedMob, int radius) {
super(owner, 600);
this.affectedMob = affectedMob;
this.radius = radius;
if (owner.withinRange(affectedMob, radius)) {
arrived();
super.matchRunning = false;
public WalkToMobEvent(Player owner, Mob affectedMob, int radius) {
super(owner, 600);
this.affectedMob = affectedMob;
this.radius = radius;
if (owner.withinRange(affectedMob, radius)) {
arrived();
super.matchRunning = false;
}
}
}
public abstract void arrived();
public abstract void arrived();
public void failed() {
} // Not abstract as isn't required
public void failed() {
} // Not abstract as isn't required
public Mob getAffectedMob() {
return affectedMob;
}
public final void run() {
if (owner.withinRange(affectedMob, radius)) {
arrived();
} else if (owner.hasMoved()) {
return; // We're still moving
} else {
failed();
public Mob getAffectedMob() {
return affectedMob;
}
public final void run() {
if (owner.withinRange(affectedMob, radius)) {
arrived();
} else if (owner.hasMoved()) {
return; // We're still moving
} else {
failed();
}
super.matchRunning = false;
}
super.matchRunning = false;
}
}

View File

@ -4,32 +4,32 @@ import org.moparscape.msc.gs.model.GameObject;
import org.moparscape.msc.gs.model.Player;
public abstract class WalkToObjectEvent extends DelayedEvent {
protected GameObject object;
private boolean stop;
protected GameObject object;
private boolean stop;
public WalkToObjectEvent(Player owner, GameObject object, boolean stop) {
super(owner, 601);
this.object = object;
this.stop = stop;
if (stop && owner.atObject(object)) {
owner.resetPath();
arrived();
super.matchRunning = false;
public WalkToObjectEvent(Player owner, GameObject object, boolean stop) {
super(owner, 601);
this.object = object;
this.stop = stop;
if (stop && owner.atObject(object)) {
owner.resetPath();
arrived();
super.matchRunning = false;
}
}
}
public abstract void arrived();
public abstract void arrived();
public final void run() {
if (stop && owner.atObject(object)) {
owner.resetPath();
arrived();
} else if (owner.hasMoved()) {
return; // We're still moving
} else if (owner.atObject(object)) {
arrived();
public final void run() {
if (stop && owner.atObject(object)) {
owner.resetPath();
arrived();
} else if (owner.hasMoved()) {
return; // We're still moving
} else if (owner.atObject(object)) {
arrived();
}
super.matchRunning = false;
}
super.matchRunning = false;
}
}

View File

@ -4,81 +4,81 @@ package org.moparscape.msc.gs.external;
* Defines an agility course
*/
public class AgilityCourseDef {
/**
* Ending object ID
*/
public int endID;
/**
* Ending object x
*/
public int endX;
/**
* Ending object y
*/
public int endY;
/**
* The exp reward for completing this course
*/
public int exp;
/**
* This course's name
*/
public String name;
/**
* Starting object x
*/
public int startX;
/**
* Starting object y
*/
public int startY;
/**
* Ending object ID
*/
public int endID;
/**
* Ending object x
*/
public int endX;
/**
* Ending object y
*/
public int endY;
/**
* The exp reward for completing this course
*/
public int exp;
/**
* This course's name
*/
public String name;
/**
* Starting object x
*/
public int startX;
/**
* Starting object y
*/
public int startY;
/**
* @return the end ID
*/
public int getEndID() {
return endID;
}
/**
* @return the end ID
*/
public int getEndID() {
return endID;
}
/**
* @return the end x
*/
public int getEndX() {
return endX;
}
/**
* @return the end x
*/
public int getEndX() {
return endX;
}
/**
* @return the end y
*/
public int getEndY() {
return endY;
}
/**
* @return the end y
*/
public int getEndY() {
return endY;
}
/**
* @return the exp reward
*/
public int getExp() {
return exp;
}
/**
* @return the exp reward
*/
public int getExp() {
return exp;
}
/**
* @return this course's name
*/
public String getName() {
return name;
}
/**
* @return this course's name
*/
public String getName() {
return name;
}
/**
* @return the starting object x
*/
public int getStartX() {
return startX;
}
/**
* @return the starting object x
*/
public int getStartX() {
return startX;
}
/**
* @return the starting object y
*/
public int getStartY() {
return startY;
}
/**
* @return the starting object y
*/
public int getStartY() {
return startY;
}
}

View File

@ -4,125 +4,125 @@ package org.moparscape.msc.gs.external;
* Defines an agility course object
*/
public class AgilityDef {
/**
* Can you fail this obstacle?
*/
public boolean canFail;
/**
* The xp you get for doing this obstacle safely
*/
public int exp;
/**
* The fail x coord
*/
public int failX;
/**
* The fail y coord
*/
public int failY;
/**
* What message does this object spew to the client?
*/
public String message;
/**
* What order this object is in the obstacle course
*/
public int order;
/**
* Required level
*/
public int reqLevel;
/**
* Tele x coord
*/
public int toX;
/**
* Tele y coord
*/
public int toY;
/**
* The x coord
*/
public int x;
/**
* The y coord
*/
public int y;
/**
* Can you fail this obstacle?
*/
public boolean canFail;
/**
* The xp you get for doing this obstacle safely
*/
public int exp;
/**
* The fail x coord
*/
public int failX;
/**
* The fail y coord
*/
public int failY;
/**
* What message does this object spew to the client?
*/
public String message;
/**
* What order this object is in the obstacle course
*/
public int order;
/**
* Required level
*/
public int reqLevel;
/**
* Tele x coord
*/
public int toX;
/**
* Tele y coord
*/
public int toY;
/**
* The x coord
*/
public int x;
/**
* The y coord
*/
public int y;
/**
* @return if you can fail this def
*/
public boolean canFail() {
return canFail;
}
/**
* @return if you can fail this def
*/
public boolean canFail() {
return canFail;
}
/**
* @return the xp you get for doing this agility object
*/
public int getExp() {
return exp;
}
/**
* @return the xp you get for doing this agility object
*/
public int getExp() {
return exp;
}
/**
* @return the fail x coord we go to if we fail
*/
public int getFailX() {
return failX;
}
/**
* @return the fail x coord we go to if we fail
*/
public int getFailX() {
return failX;
}
/**
* @return the fail y coord we go to if we fail
*/
public int getFailY() {
return failY;
}
/**
* @return the fail y coord we go to if we fail
*/
public int getFailY() {
return failY;
}
/**
* @return the object's message
*/
public String getMessage() {
return message;
}
/**
* @return the object's message
*/
public String getMessage() {
return message;
}
/**
* @return the order of this agility object
*/
public int getOrder() {
return order;
}
/**
* @return the order of this agility object
*/
public int getOrder() {
return order;
}
/**
* @return this def's required level
*/
public int getReqLevel() {
return reqLevel;
}
/**
* @return this def's required level
*/
public int getReqLevel() {
return reqLevel;
}
/**
* @return this def's tele x
*/
public int getToX() {
return toX;
}
/**
* @return this def's tele x
*/
public int getToX() {
return toX;
}
/**
* @return this def's tele y
*/
public int getToY() {
return toY;
}
/**
* @return this def's tele y
*/
public int getToY() {
return toY;
}
/**
* @return this def's x coord
*/
public int getX() {
return x;
}
/**
* @return this def's x coord
*/
public int getX() {
return x;
}
/**
* @return this def's y coord
*/
public int getY() {
return y;
}
/**
* @return this def's y coord
*/
public int getY() {
return y;
}
}

View File

@ -1,28 +1,28 @@
package org.moparscape.msc.gs.external;
public class CertDef {
/**
* The ID of the certificate
*/
public int certID;
/**
* The ID of the assosiated item
*/
public int itemID;
/**
* The name of the item this cert is for
*/
public String name;
/**
* The ID of the certificate
*/
public int certID;
/**
* The ID of the assosiated item
*/
public int itemID;
/**
* The name of the item this cert is for
*/
public String name;
public int getCertID() {
return certID;
}
public int getCertID() {
return certID;
}
public int getItemID() {
return itemID;
}
public int getItemID() {
return itemID;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
}

View File

@ -1,38 +1,38 @@
package org.moparscape.msc.gs.external;
public class CerterDef {
/**
* Certs this stall can deal with
*/
private CertDef[] certs;
/**
* Type of stall
*/
private String type;
/**
* Certs this stall can deal with
*/
private CertDef[] certs;
/**
* Type of stall
*/
private String type;
public int getCertID(int index) {
if (index < 0 || index >= certs.length) {
return -1;
public int getCertID(int index) {
if (index < 0 || index >= certs.length) {
return -1;
}
return certs[index].getCertID();
}
return certs[index].getCertID();
}
public String[] getCertNames() {
String[] names = new String[certs.length];
for (int i = 0; i < certs.length; i++) {
names[i] = certs[i].getName();
public String[] getCertNames() {
String[] names = new String[certs.length];
for (int i = 0; i < certs.length; i++) {
names[i] = certs[i].getName();
}
return names;
}
return names;
}
public int getItemID(int index) {
if (index < 0 || index >= certs.length) {
return -1;
public int getItemID(int index) {
if (index < 0 || index >= certs.length) {
return -1;
}
return certs[index].getItemID();
}
return certs[index].getItemID();
}
public String getType() {
return type;
}
public String getType() {
return type;
}
}

View File

@ -5,52 +5,52 @@ package org.moparscape.msc.gs.external;
*/
public class DoorDef extends EntityDef {
/**
* The first command of the door
*/
public String command1;
/**
* The second command of the door
*/
public String command2;
/**
* The doors type.
*/
public int doorType;
public int modelVar1;
/**
* The first command of the door
*/
public String command1;
/**
* The second command of the door
*/
public String command2;
/**
* The doors type.
*/
public int doorType;
public int modelVar1;
public int modelVar2;
public int modelVar3;
/**
* Unknown
*/
public int unknown;
public int modelVar2;
public int modelVar3;
/**
* Unknown
*/
public int unknown;
public String getCommand1() {
return command1.toLowerCase();
}
public String getCommand1() {
return command1.toLowerCase();
}
public String getCommand2() {
return command2.toLowerCase();
}
public String getCommand2() {
return command2.toLowerCase();
}
public int getDoorType() {
return doorType;
}
public int getDoorType() {
return doorType;
}
public int getModelVar1() {
return modelVar1;
}
public int getModelVar1() {
return modelVar1;
}
public int getModelVar2() {
return modelVar2;
}
public int getModelVar2() {
return modelVar2;
}
public int getModelVar3() {
return modelVar3;
}
public int getModelVar3() {
return modelVar3;
}
public int getUnknown() {
return unknown;
}
public int getUnknown() {
return unknown;
}
}

View File

@ -6,26 +6,26 @@ package org.moparscape.msc.gs.external;
*/
public abstract class EntityDef {
/**
* The description of the entity
*/
public String description;
/**
* The name of the entity
*/
public String name;
/**
* The description of the entity
*/
public String description;
/**
* The name of the entity
*/
public String name;
/**
* Returns the description of the entity
*/
public String getDescription() {
return description;
}
/**
* Returns the description of the entity
*/
public String getDescription() {
return description;
}
/**
* Returns the name of the entity
*/
public String getName() {
return name;
}
/**
* Returns the name of the entity
*/
public String getName() {
return name;
}
}

View File

@ -7,7 +7,6 @@ import org.moparscape.msc.gs.model.Point;
import org.moparscape.msc.gs.model.TelePoint;
import org.moparscape.msc.gs.util.PersistenceManager;
/**
* This class handles the loading of entities from the conf files, and provides
* methods for relaying these entities to the user.
@ -15,405 +14,435 @@ import org.moparscape.msc.gs.util.PersistenceManager;
@SuppressWarnings("unchecked")
public class EntityHandler {
private static HashMap<Integer, AgilityCourseDef> agilityCourses;
private static HashMap<Integer, AgilityDef> agilityObjects;
private static HashMap<Integer, ItemArrowHeadDef> arrowHeads;
private static HashMap<Integer, ItemBowStringDef> bowString;
private static HashMap<Integer, CerterDef> certers;
private static HashMap<Integer, ItemDartTipDef> dartTips;
private static HashMap<Integer, AgilityCourseDef> agilityCourses;
private static HashMap<Integer, AgilityDef> agilityObjects;
private static HashMap<Integer, ItemArrowHeadDef> arrowHeads;
private static HashMap<Integer, ItemBowStringDef> bowString;
private static HashMap<Integer, CerterDef> certers;
private static HashMap<Integer, ItemDartTipDef> dartTips;
private static DoorDef[] doors;
private static HashMap<Integer, FiremakingDef> firemaking;
private static GameObjectDef[] gameObjects;
private static HashMap<Integer, ItemGemDef> gems;
private static ItemHerbSecond[] herbSeconds;
private static HashMap<Integer, int[]> itemAffectedTypes;
private static HashMap<Integer, ItemCookingDef> itemCooking;
private static ItemCraftingDef[] itemCrafting;
private static HashMap<Integer, Integer> itemEdibleHeals;
private static HashMap<Integer, ItemHerbDef> itemHerb;
private static ItemDef[] items;
private static HashMap<Integer, ItemSmeltingDef> itemSmelting;
private static ItemSmithingDef[] itemSmithing;
private static HashMap<Integer, ItemUnIdentHerbDef> itemUnIdentHerb;
private static HashMap<Integer, ItemWieldableDef> itemWieldable;
private static List[] keyChestLoots;
private static HashMap<Integer, ItemLogCutDef> logCut;
private static DoorDef[] doors;
private static HashMap<Integer, FiremakingDef> firemaking;
private static GameObjectDef[] gameObjects;
private static HashMap<Integer, ItemGemDef> gems;
private static ItemHerbSecond[] herbSeconds;
private static HashMap<Integer, int[]> itemAffectedTypes;
private static HashMap<Integer, ItemCookingDef> itemCooking;
private static ItemCraftingDef[] itemCrafting;
private static HashMap<Integer, Integer> itemEdibleHeals;
private static HashMap<Integer, ItemHerbDef> itemHerb;
private static ItemDef[] items;
private static HashMap<Integer, ItemSmeltingDef> itemSmelting;
private static ItemSmithingDef[] itemSmithing;
private static HashMap<Integer, ItemUnIdentHerbDef> itemUnIdentHerb;
private static HashMap<Integer, ItemWieldableDef> itemWieldable;
private static List<?>[] keyChestLoots;
private static HashMap<Integer, ItemLogCutDef> logCut;
private static NPCDef[] npcs;
private static HashMap<Integer, ObjectFishingDef[]> objectFishing;
private static NPCDef[] npcs;
private static HashMap<Integer, ObjectFishingDef[]> objectFishing;
private static HashMap<Integer, ObjectMiningDef> objectMining;
private static HashMap<Point, TelePoint> objectTelePoints;
private static HashMap<Integer, ObjectWoodcuttingDef> objectWoodcutting;
private static PrayerDef[] prayers;
private static HashMap<Integer, Integer> spellAggressiveLvl;
private static SpellDef[] spells;
private static TileDef[] tiles;
private static HashMap<Integer, ObjectMiningDef> objectMining;
private static HashMap<Point, TelePoint> objectTelePoints;
private static HashMap<Integer, ObjectWoodcuttingDef> objectWoodcutting;
private static PrayerDef[] prayers;
private static HashMap<Integer, Integer> spellAggressiveLvl;
private static SpellDef[] spells;
private static TileDef[] tiles;
static {
static {
doors = (DoorDef[]) PersistenceManager.load("defs/DoorDef.xml.gz");
gameObjects = (GameObjectDef[]) PersistenceManager.load("defs/GameObjectDef.xml.gz");
gameObjects = (GameObjectDef[]) PersistenceManager
.load("defs/GameObjectDef.xml.gz");
npcs = (NPCDef[]) PersistenceManager.load("defs/NPCDef.xml.gz");
for (NPCDef n : npcs) {
if (n.isAttackable()) {
n.respawnTime -= (n.respawnTime / 3);
}
for (NPCDef n : npcs) {
if (n.isAttackable()) {
n.respawnTime -= (n.respawnTime / 3);
}
prayers = (PrayerDef[]) PersistenceManager.load("defs/PrayerDef.xml.gz");
}
prayers = (PrayerDef[]) PersistenceManager
.load("defs/PrayerDef.xml.gz");
items = (ItemDef[]) PersistenceManager.load("defs/ItemDef.xml.gz");
spells = (SpellDef[]) PersistenceManager.load("defs/SpellDef.xml.gz");
tiles = (TileDef[]) PersistenceManager.load("defs/TileDef.xml.gz");
keyChestLoots = (List[]) PersistenceManager.load("defs/extras/KeyChestLoot.xml.gz");
herbSeconds = (ItemHerbSecond[]) PersistenceManager.load("defs/extras/ItemHerbSecond.xml.gz");
dartTips = (HashMap<Integer, ItemDartTipDef>) PersistenceManager.load("defs/extras/ItemDartTipDef.xml.gz");
gems = (HashMap<Integer, ItemGemDef>) PersistenceManager.load("defs/extras/ItemGemDef.xml.gz");
logCut = (HashMap<Integer, ItemLogCutDef>) PersistenceManager.load("defs/extras/ItemLogCutDef.xml.gz");
bowString = (HashMap<Integer, ItemBowStringDef>) PersistenceManager.load("defs/extras/ItemBowStringDef.xml.gz");
arrowHeads = (HashMap<Integer, ItemArrowHeadDef>) PersistenceManager.load("defs/extras/ItemArrowHeadDef.xml.gz");
firemaking = (HashMap<Integer, FiremakingDef>) PersistenceManager.load("defs/extras/FiremakingDef.xml.gz");
itemAffectedTypes = (HashMap<Integer, int[]>) PersistenceManager.load("defs/extras/ItemAffectedTypes.xml.gz");
itemWieldable = (HashMap<Integer, ItemWieldableDef>) PersistenceManager.load("defs/extras/ItemWieldableDef.xml.gz");
itemUnIdentHerb = (HashMap<Integer, ItemUnIdentHerbDef>) PersistenceManager.load("defs/extras/ItemUnIdentHerbDef.xml.gz");
itemHerb = (HashMap<Integer, ItemHerbDef>) PersistenceManager.load("defs/extras/ItemHerbDef.xml.gz");
itemEdibleHeals = (HashMap<Integer, Integer>) PersistenceManager.load("defs/extras/ItemEdibleHeals.xml.gz");
itemCooking = (HashMap<Integer, ItemCookingDef>) PersistenceManager.load("defs/extras/ItemCookingDef.xml.gz");
itemSmelting = (HashMap<Integer, ItemSmeltingDef>) PersistenceManager.load("defs/extras/ItemSmeltingDef.xml.gz");
itemSmithing = (ItemSmithingDef[]) PersistenceManager.load("defs/extras/ItemSmithingDef.xml.gz");
itemCrafting = (ItemCraftingDef[]) PersistenceManager.load("defs/extras/ItemCraftingDef.xml.gz");
objectMining = (HashMap<Integer, ObjectMiningDef>) PersistenceManager.load("defs/extras/ObjectMining.xml.gz");
objectWoodcutting = (HashMap<Integer, ObjectWoodcuttingDef>) PersistenceManager.load("defs/extras/ObjectWoodcutting.xml.gz");
objectFishing = (HashMap<Integer, ObjectFishingDef[]>) PersistenceManager.load("defs/extras/ObjectFishing.xml.gz");
spellAggressiveLvl = (HashMap<Integer, Integer>) PersistenceManager.load("defs/extras/SpellAggressiveLvl.xml.gz");
objectTelePoints = (HashMap<Point, TelePoint>) PersistenceManager.load("locs/extras/ObjectTelePoints.xml.gz");
certers = (HashMap<Integer, CerterDef>) PersistenceManager.load("defs/extras/NpcCerters.xml.gz");
agilityObjects = (HashMap<Integer, AgilityDef>) PersistenceManager.load("defs/extras/AgilityDef.xml.gz");
agilityCourses = (HashMap<Integer, AgilityCourseDef>) PersistenceManager.load("defs/extras/AgilityCourseDef.xml.gz");
}
keyChestLoots = (List[]) PersistenceManager
.load("defs/extras/KeyChestLoot.xml.gz");
herbSeconds = (ItemHerbSecond[]) PersistenceManager
.load("defs/extras/ItemHerbSecond.xml.gz");
dartTips = (HashMap<Integer, ItemDartTipDef>) PersistenceManager
.load("defs/extras/ItemDartTipDef.xml.gz");
gems = (HashMap<Integer, ItemGemDef>) PersistenceManager
.load("defs/extras/ItemGemDef.xml.gz");
logCut = (HashMap<Integer, ItemLogCutDef>) PersistenceManager
.load("defs/extras/ItemLogCutDef.xml.gz");
bowString = (HashMap<Integer, ItemBowStringDef>) PersistenceManager
.load("defs/extras/ItemBowStringDef.xml.gz");
arrowHeads = (HashMap<Integer, ItemArrowHeadDef>) PersistenceManager
.load("defs/extras/ItemArrowHeadDef.xml.gz");
firemaking = (HashMap<Integer, FiremakingDef>) PersistenceManager
.load("defs/extras/FiremakingDef.xml.gz");
itemAffectedTypes = (HashMap<Integer, int[]>) PersistenceManager
.load("defs/extras/ItemAffectedTypes.xml.gz");
itemWieldable = (HashMap<Integer, ItemWieldableDef>) PersistenceManager
.load("defs/extras/ItemWieldableDef.xml.gz");
itemUnIdentHerb = (HashMap<Integer, ItemUnIdentHerbDef>) PersistenceManager
.load("defs/extras/ItemUnIdentHerbDef.xml.gz");
itemHerb = (HashMap<Integer, ItemHerbDef>) PersistenceManager
.load("defs/extras/ItemHerbDef.xml.gz");
itemEdibleHeals = (HashMap<Integer, Integer>) PersistenceManager
.load("defs/extras/ItemEdibleHeals.xml.gz");
itemCooking = (HashMap<Integer, ItemCookingDef>) PersistenceManager
.load("defs/extras/ItemCookingDef.xml.gz");
itemSmelting = (HashMap<Integer, ItemSmeltingDef>) PersistenceManager
.load("defs/extras/ItemSmeltingDef.xml.gz");
itemSmithing = (ItemSmithingDef[]) PersistenceManager
.load("defs/extras/ItemSmithingDef.xml.gz");
itemCrafting = (ItemCraftingDef[]) PersistenceManager
.load("defs/extras/ItemCraftingDef.xml.gz");
objectMining = (HashMap<Integer, ObjectMiningDef>) PersistenceManager
.load("defs/extras/ObjectMining.xml.gz");
objectWoodcutting = (HashMap<Integer, ObjectWoodcuttingDef>) PersistenceManager
.load("defs/extras/ObjectWoodcutting.xml.gz");
objectFishing = (HashMap<Integer, ObjectFishingDef[]>) PersistenceManager
.load("defs/extras/ObjectFishing.xml.gz");
spellAggressiveLvl = (HashMap<Integer, Integer>) PersistenceManager
.load("defs/extras/SpellAggressiveLvl.xml.gz");
objectTelePoints = (HashMap<Point, TelePoint>) PersistenceManager
.load("locs/extras/ObjectTelePoints.xml.gz");
certers = (HashMap<Integer, CerterDef>) PersistenceManager
.load("defs/extras/NpcCerters.xml.gz");
agilityObjects = (HashMap<Integer, AgilityDef>) PersistenceManager
.load("defs/extras/AgilityDef.xml.gz");
agilityCourses = (HashMap<Integer, AgilityCourseDef>) PersistenceManager
.load("defs/extras/AgilityCourseDef.xml.gz");
}
/**
* @param id
* the agility courses's start ID
* @return the AgilityCourseDef with the given start ID
*/
public static AgilityCourseDef getAgilityCourseDef(int id) {
return agilityCourses.get(id);
}
/**
* @param id
* the agility courses's start ID
* @return the AgilityCourseDef with the given start ID
*/
public static AgilityCourseDef getAgilityCourseDef(int id) {
return agilityCourses.get(id);
}
/**
* @param id
* the agility object's ID
* @return the AgilityDef with the given object ID
*/
public static AgilityDef getAgilityDef(int id) {
return agilityObjects.get(id);
}
/**
* @param id
* the agility object's ID
* @return the AgilityDef with the given object ID
*/
public static AgilityDef getAgilityDef(int id) {
return agilityObjects.get(id);
}
/**
* @param id
* the npcs ID
* @return the CerterDef for the given npc
*/
public static CerterDef getCerterDef(int id) {
return certers.get(id);
}
/**
* @param id
* the npcs ID
* @return the CerterDef for the given npc
*/
public static CerterDef getCerterDef(int id) {
return certers.get(id);
}
/**
* @return the ItemCraftingDef for the requested item
*/
public static ItemCraftingDef getCraftingDef(int id) {
/**
* @return the ItemCraftingDef for the requested item
*/
public static ItemCraftingDef getCraftingDef(int id) {
if (id < 0 || id >= itemCrafting.length) {
return null;
return null;
}
return itemCrafting[id];
}
/**
* @param id
* the entities ID
* @return the DoorDef with the given ID
*/
public static DoorDef getDoorDef(int id) {
if (id < 0 || id >= doors.length) {
return null;
}
return doors[id];
}
/**
* @return the FiremakingDef for the given log
*/
public static FiremakingDef getFiremakingDef(int id) {
return firemaking.get(id);
}
/**
* @param id
* the entities ID
* @return the DoorDef with the given ID
*/
public static DoorDef getDoorDef(int id) {
if (id < 0 || id >= doors.length) {
return null;
}
return doors[id];
}
/**
* @param id
* the entities ID
* @return the GameObjectDef with the given ID
*/
public static GameObjectDef getGameObjectDef(int id) {
/**
* @return the FiremakingDef for the given log
*/
public static FiremakingDef getFiremakingDef(int id) {
return firemaking.get(id);
}
/**
* @param id
* the entities ID
* @return the GameObjectDef with the given ID
*/
public static GameObjectDef getGameObjectDef(int id) {
if (id < 0 || id >= gameObjects.length) {
return null;
return null;
}
return gameObjects[id];
}
}
/**
* @param the
* items type
* @return the types of items affected
*/
public static int[] getItemAffectedTypes(int type) {
return itemAffectedTypes.get(type);
}
/**
* @param the
* items type
* @return the types of items affected
*/
public static int[] getItemAffectedTypes(int type) {
return itemAffectedTypes.get(type);
}
/**
* @return the ItemArrowHeadDef for the given arrow
*/
public static ItemArrowHeadDef getItemArrowHeadDef(int id) {
return arrowHeads.get(id);
}
/**
* @return the ItemArrowHeadDef for the given arrow
*/
public static ItemArrowHeadDef getItemArrowHeadDef(int id) {
return arrowHeads.get(id);
}
/**
* @return the ItemBowStringDef for the given bow
*/
public static ItemBowStringDef getItemBowStringDef(int id) {
return bowString.get(id);
}
/**
* @return the ItemBowStringDef for the given bow
*/
public static ItemBowStringDef getItemBowStringDef(int id) {
return bowString.get(id);
}
/**
* @param id
* the entities ID
* @return the ItemCookingDef with the given ID
*/
public static ItemCookingDef getItemCookingDef(int id) {
return itemCooking.get(id);
}
/**
* @param id
* the entities ID
* @return the ItemCookingDef with the given ID
*/
public static ItemCookingDef getItemCookingDef(int id) {
return itemCooking.get(id);
}
/**
* @return the ItemDartTipDef for the given tip
*/
public static ItemDartTipDef getItemDartTipDef(int id) {
return dartTips.get(id);
}
/**
* @return the ItemDartTipDef for the given tip
*/
public static ItemDartTipDef getItemDartTipDef(int id) {
return dartTips.get(id);
}
/**
* @param id
* the entities ID
* @return the ItemDef with the given ID
*/
public static ItemDef getItemDef(int id) {
/**
* @param id
* the entities ID
* @return the ItemDef with the given ID
*/
public static ItemDef getItemDef(int id) {
if (id < 0 || id >= items.length) {
return null;
return null;
}
return items[id];
}
}
/**
* @param the
* items id
* @return the amount eating the item should heal
*/
public static int getItemEdibleHeals(int id) {
/**
* @param the
* items id
* @return the amount eating the item should heal
*/
public static int getItemEdibleHeals(int id) {
Integer heals = itemEdibleHeals.get(id);
if (heals != null) {
return heals.intValue();
return heals.intValue();
}
return 0;
}
}
/**
* @return the ItemGemDef for the given gem
*/
public static ItemGemDef getItemGemDef(int id) {
return gems.get(id);
}
/**
* @return the ItemGemDef for the given gem
*/
public static ItemGemDef getItemGemDef(int id) {
return gems.get(id);
}
/**
* @param id
* the entities ID
* @return the ItemHerbDef with the given ID
*/
public static ItemHerbDef getItemHerbDef(int id) {
return itemHerb.get(id);
}
/**
* @param id
* the entities ID
* @return the ItemHerbDef with the given ID
*/
public static ItemHerbDef getItemHerbDef(int id) {
return itemHerb.get(id);
}
/**
* @return the ItemHerbSecond for the given second ingredient
*/
public static ItemHerbSecond getItemHerbSecond(int secondID, int unfinishedID) {
/**
* @return the ItemHerbSecond for the given second ingredient
*/
public static ItemHerbSecond getItemHerbSecond(int secondID,
int unfinishedID) {
for (ItemHerbSecond def : herbSeconds) {
if (def.getSecondID() == secondID && def.getUnfinishedID() == unfinishedID) {
return def;
}
if (def.getSecondID() == secondID
&& def.getUnfinishedID() == unfinishedID) {
return def;
}
}
return null;
}
}
/**
* @return the ItemLogCutDef for the given log
*/
public static ItemLogCutDef getItemLogCutDef(int id) {
return logCut.get(id);
}
/**
* @return the ItemLogCutDef for the given log
*/
public static ItemLogCutDef getItemLogCutDef(int id) {
return logCut.get(id);
}
/**
* @param id
* the entities ID
* @return the ItemSmeltingDef with the given ID
*/
public static ItemSmeltingDef getItemSmeltingDef(int id) {
return itemSmelting.get(id);
}
/**
* @param id
* the entities ID
* @return the ItemSmeltingDef with the given ID
*/
public static ItemSmeltingDef getItemSmeltingDef(int id) {
return itemSmelting.get(id);
}
/**
* @param id
* the entities ID
* @return the ItemUnIdentHerbDef with the given ID
*/
public static ItemUnIdentHerbDef getItemUnIdentHerbDef(int id) {
return itemUnIdentHerb.get(id);
}
/**
* @param id
* the entities ID
* @return the ItemUnIdentHerbDef with the given ID
*/
public static ItemUnIdentHerbDef getItemUnIdentHerbDef(int id) {
return itemUnIdentHerb.get(id);
}
/**
* @param id
* the entities ID
* @return the ItemWieldableDef with the given ID
*/
public static ItemWieldableDef getItemWieldableDef(int id) {
return itemWieldable.get(id);
}
/**
* @param id
* the entities ID
* @return the ItemWieldableDef with the given ID
*/
public static ItemWieldableDef getItemWieldableDef(int id) {
return itemWieldable.get(id);
}
public static List[] getKeyChestLoots() {
return keyChestLoots;
}
public static List<?>[] getKeyChestLoots() {
return keyChestLoots;
}
/**
* @param id
* the entities ID
* @return the NPCDef with the given ID
*/
public static NPCDef getNpcDef(int id) {
/**
* @param id
* the entities ID
* @return the NPCDef with the given ID
*/
public static NPCDef getNpcDef(int id) {
if (id < 0 || id >= npcs.length) {
return null;
return null;
}
return npcs[id];
}
}
/**
* @param id
* the entities ID
* @return the ObjectFishingDef with the given ID
*/
public static ObjectFishingDef getObjectFishingDef(int id, int click) {
/**
* @param id
* the entities ID
* @return the ObjectFishingDef with the given ID
*/
public static ObjectFishingDef getObjectFishingDef(int id, int click) {
ObjectFishingDef[] defs = objectFishing.get(id);
if (defs == null) {
return null;
return null;
}
return defs[click];
}
/**
* @param id
* the entities ID
* @return the ObjectMiningDef with the given ID
*/
public static ObjectMiningDef getObjectMiningDef(int id) {
return objectMining.get(id);
}
/**
* @param the
* point we are currently at
* @return the point we should be teleported to
*/
public static Point getObjectTelePoint(Point location, String command) {
TelePoint point = objectTelePoints.get(location);
if (point == null) {
return null;
}
if (command == null || point.getCommand().equalsIgnoreCase(command)) {
return point;
}
return null;
}
/**
* @param id
* the entities ID
* @return the ObjectWoodcuttingDef with the given ID
*/
public static ObjectWoodcuttingDef getObjectWoodcuttingDef(int id) {
return objectWoodcutting.get(id);
}
/**
* @param id
* the entities ID
* @return the PrayerDef with the given ID
*/
public static PrayerDef getPrayerDef(int id) {
if (id < 0 || id >= prayers.length) {
return null;
/**
* @param id
* the entities ID
* @return the ObjectMiningDef with the given ID
*/
public static ObjectMiningDef getObjectMiningDef(int id) {
return objectMining.get(id);
}
return prayers[id];
}
/**
* @return the ItemSmithingDef for the requested item
*/
public static ItemSmithingDef getSmithingDef(int id) {
if (id < 0 || id >= itemSmithing.length) {
return null;
/**
* @param the
* point we are currently at
* @return the point we should be teleported to
*/
public static Point getObjectTelePoint(Point location, String command) {
TelePoint point = objectTelePoints.get(location);
if (point == null) {
return null;
}
if (command == null || point.getCommand().equalsIgnoreCase(command)) {
return point;
}
return null;
}
return itemSmithing[id];
}
/**
* @return the ItemSmithingDef for the requested item
*/
public static ItemSmithingDef getSmithingDefbyID(int itemID) {
for(ItemSmithingDef i : itemSmithing) {
if(i.itemID == itemID)
return i;
}
return null;
}
/**
* @param the
* spells id
* @return the lvl of the spell (for calculating what it hits)
*/
public static int getSpellAggressiveLvl(int id) {
Integer lvl = spellAggressiveLvl.get(id);
if (lvl != null) {
return lvl.intValue();
/**
* @param id
* the entities ID
* @return the ObjectWoodcuttingDef with the given ID
*/
public static ObjectWoodcuttingDef getObjectWoodcuttingDef(int id) {
return objectWoodcutting.get(id);
}
return 0;
}
/**
* @param id
* the entities ID
* @return the SpellDef with the given ID
*/
public static SpellDef getSpellDef(int id) {
if (id < 0 || id >= spells.length) {
return null;
/**
* @param id
* the entities ID
* @return the PrayerDef with the given ID
*/
public static PrayerDef getPrayerDef(int id) {
if (id < 0 || id >= prayers.length) {
return null;
}
return prayers[id];
}
return spells[id];
}
/**
* @param id
* the entities ID
* @return the TileDef with the given ID
*/
public static TileDef getTileDef(int id) {
if (id < 0 || id >= tiles.length) {
return null;
/**
* @return the ItemSmithingDef for the requested item
*/
public static ItemSmithingDef getSmithingDef(int id) {
if (id < 0 || id >= itemSmithing.length) {
return null;
}
return itemSmithing[id];
}
/**
* @return the ItemSmithingDef for the requested item
*/
public static ItemSmithingDef getSmithingDefbyID(int itemID) {
for (ItemSmithingDef i : itemSmithing) {
if (i.itemID == itemID)
return i;
}
return null;
}
/**
* @param the
* spells id
* @return the lvl of the spell (for calculating what it hits)
*/
public static int getSpellAggressiveLvl(int id) {
Integer lvl = spellAggressiveLvl.get(id);
if (lvl != null) {
return lvl.intValue();
}
return 0;
}
/**
* @param id
* the entities ID
* @return the SpellDef with the given ID
*/
public static SpellDef getSpellDef(int id) {
if (id < 0 || id >= spells.length) {
return null;
}
return spells[id];
}
/**
* @param id
* the entities ID
* @return the TileDef with the given ID
*/
public static TileDef getTileDef(int id) {
if (id < 0 || id >= tiles.length) {
return null;
}
return tiles[id];
}
return tiles[id];
}
}

View File

@ -1,28 +1,28 @@
package org.moparscape.msc.gs.external;
public class FiremakingDef {
/**
* The exp given by these logs
*/
public int exp;
/**
* How many ms the fire should last for
*/
public int length;
/**
* The firemaking level required to light these logs
*/
public int level;
/**
* The exp given by these logs
*/
public int exp;
/**
* How many ms the fire should last for
*/
public int length;
/**
* The firemaking level required to light these logs
*/
public int level;
public int getExp() {
return exp;
}
public int getExp() {
return exp;
}
public int getLength() {
return length * 1000;
}
public int getLength() {
return length * 1000;
}
public int getRequiredLevel() {
return level;
}
public int getRequiredLevel() {
return level;
}
}

View File

@ -5,59 +5,59 @@ package org.moparscape.msc.gs.external;
*/
public class GameObjectDef extends EntityDef {
/**
* The first command of the object
*/
public String command1;
/**
* The second command of the object
*/
public String command2;
/**
* Can't figure out what this one is for, either.
*/
public int groundItemVar;
/**
* The height of the object
*/
public int height;
public String objectModel;
/**
* The object type. Can't figure out the significance of it. Item type 2 & 3
* seem to be special
*/
public int type;
/**
* The first command of the object
*/
public String command1;
/**
* The second command of the object
*/
public String command2;
/**
* Can't figure out what this one is for, either.
*/
public int groundItemVar;
/**
* The height of the object
*/
public int height;
public String objectModel;
/**
* The object type. Can't figure out the significance of it. Item type 2 & 3
* seem to be special
*/
public int type;
/**
* The width of the object
*/
public int width;
/**
* The width of the object
*/
public int width;
public String getCommand1() {
return command1.toLowerCase();
}
public String getCommand1() {
return command1.toLowerCase();
}
public String getCommand2() {
return command2.toLowerCase();
}
public String getCommand2() {
return command2.toLowerCase();
}
public int getGroundItemVar() {
return groundItemVar;
}
public int getGroundItemVar() {
return groundItemVar;
}
public int getHeight() {
return height;
}
public int getHeight() {
return height;
}
public String getObjectModel() {
return objectModel;
}
public String getObjectModel() {
return objectModel;
}
public int getType() {
return type;
}
public int getType() {
return type;
}
public int getWidth() {
return width;
}
public int getWidth() {
return width;
}
}

View File

@ -1,52 +1,52 @@
package org.moparscape.msc.gs.external;
public class GameObjectLoc {
/**
* The direction it faces
*/
public int direction;
/**
* The id of the gameObject
*/
public int id;
/**
* Type of object - 0: Object, 1: WallObject
*/
public int type;
/**
* The objects x coord
*/
public int x;
/**
* The objects y coord
*/
public int y;
/**
* The direction it faces
*/
public int direction;
/**
* The id of the gameObject
*/
public int id;
/**
* Type of object - 0: Object, 1: WallObject
*/
public int type;
/**
* The objects x coord
*/
public int x;
/**
* The objects y coord
*/
public int y;
public GameObjectLoc(int id, int x, int y, int direction, int type) {
this.id = id;
this.x = x;
this.y = y;
this.direction = direction;
this.type = type;
}
public GameObjectLoc(int id, int x, int y, int direction, int type) {
this.id = id;
this.x = x;
this.y = y;
this.direction = direction;
this.type = type;
}
public int getDirection() {
return direction;
}
public int getDirection() {
return direction;
}
public int getId() {
return id;
}
public int getId() {
return id;
}
public int getType() {
return type;
}
public int getType() {
return type;
}
public int getX() {
return x;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getY() {
return y;
}
}

View File

@ -5,28 +5,28 @@ package org.moparscape.msc.gs.external;
*/
public class ItemArrowHeadDef {
/**
* The ID of the arrow created
*/
public int arrowID;
/**
* The exp given by attaching this arrow head
*/
public double exp;
/**
* The level required to attach this head to an arrow
*/
public int requiredLvl;
/**
* The ID of the arrow created
*/
public int arrowID;
/**
* The exp given by attaching this arrow head
*/
public double exp;
/**
* The level required to attach this head to an arrow
*/
public int requiredLvl;
public int getArrowID() {
return arrowID;
}
public int getArrowID() {
return arrowID;
}
public double getExp() {
return exp;
}
public double getExp() {
return exp;
}
public int getReqLevel() {
return requiredLvl;
}
public int getReqLevel() {
return requiredLvl;
}
}

View File

@ -5,28 +5,28 @@ package org.moparscape.msc.gs.external;
*/
public class ItemBowStringDef {
/**
* The ID of the bow created
*/
public int bowID;
/**
* The exp given by attaching this bow string
*/
public int exp;
/**
* The level required to attach this bow string
*/
public int requiredLvl;
/**
* The ID of the bow created
*/
public int bowID;
/**
* The exp given by attaching this bow string
*/
public int exp;
/**
* The level required to attach this bow string
*/
public int requiredLvl;
public int getBowID() {
return bowID;
}
public int getBowID() {
return bowID;
}
public int getExp() {
return exp;
}
public int getExp() {
return exp;
}
public int getReqLevel() {
return requiredLvl;
}
public int getReqLevel() {
return requiredLvl;
}
}

View File

@ -5,37 +5,37 @@ package org.moparscape.msc.gs.external;
*/
public class ItemCookingDef {
/**
* The id of the burned version
*/
public int burnedId;
/**
* The id of the cooked version
*/
public int cookedId;
/**
* The exp cooking this item gives
*/
public int exp;
/**
* The level required to cook this
*/
public int requiredLvl;
/**
* The id of the burned version
*/
public int burnedId;
/**
* The id of the cooked version
*/
public int cookedId;
/**
* The exp cooking this item gives
*/
public int exp;
/**
* The level required to cook this
*/
public int requiredLvl;
public int getBurnedId() {
return burnedId;
}
public int getBurnedId() {
return burnedId;
}
public int getCookedId() {
return cookedId;
}
public int getCookedId() {
return cookedId;
}
public int getExp() {
return exp;
}
public int getExp() {
return exp;
}
public int getReqLevel() {
return requiredLvl;
}
public int getReqLevel() {
return requiredLvl;
}
}

View File

@ -1,28 +1,28 @@
package org.moparscape.msc.gs.external;
public class ItemCraftingDef {
/**
* The exp given
*/
public int exp;
/**
* The ID of the item produced
*/
public int itemID;
/**
* The crafting level required to make this item
*/
public int requiredLvl;
/**
* The exp given
*/
public int exp;
/**
* The ID of the item produced
*/
public int itemID;
/**
* The crafting level required to make this item
*/
public int requiredLvl;
public int getExp() {
return exp;
}
public int getExp() {
return exp;
}
public int getItemID() {
return itemID;
}
public int getItemID() {
return itemID;
}
public int getReqLevel() {
return requiredLvl;
}
public int getReqLevel() {
return requiredLvl;
}
}

View File

@ -5,28 +5,28 @@ package org.moparscape.msc.gs.external;
*/
public class ItemDartTipDef {
/**
* The ID of the arrow created
*/
public int dartID;
/**
* The exp given by attaching this arrow head
*/
public double exp;
/**
* The level required to attach this head to an arrow
*/
public int requiredLvl;
/**
* The ID of the arrow created
*/
public int dartID;
/**
* The exp given by attaching this arrow head
*/
public double exp;
/**
* The level required to attach this head to an arrow
*/
public int requiredLvl;
public int getDartID() {
return dartID;
}
public int getDartID() {
return dartID;
}
public double getExp() {
return exp;
}
public double getExp() {
return exp;
}
public int getReqLevel() {
return requiredLvl;
}
public int getReqLevel() {
return requiredLvl;
}
}

View File

@ -4,72 +4,72 @@ package org.moparscape.msc.gs.external;
* The definition wrapper for items
*/
public class ItemDef extends EntityDef {
/**
* The base price of the object
*/
public int basePrice;
/**
* The command of the object
*/
public String command;
/**
* PictureMask
*/
public int mask;
/**
* Is this item a member's item?
*/
public boolean members;
/**
* The sprite id
*/
public int sprite;
/**
* Whether the item is stackable or not
*/
public boolean stackable;
/**
* Is this item tradeable?
*/
public boolean trade;
/**
* Whether the item is wieldable or not
*/
public int wieldable;
/**
* The base price of the object
*/
public int basePrice;
/**
* The command of the object
*/
public String command;
/**
* PictureMask
*/
public int mask;
/**
* Is this item a member's item?
*/
public boolean members;
/**
* The sprite id
*/
public int sprite;
/**
* Whether the item is stackable or not
*/
public boolean stackable;
/**
* Is this item tradeable?
*/
public boolean trade;
/**
* Whether the item is wieldable or not
*/
public int wieldable;
public boolean canTrade() {
return trade;
}
public boolean canTrade() {
return trade;
}
public int getBasePrice() {
return basePrice;
}
public int getBasePrice() {
return basePrice;
}
public String getCommand() {
return command;
}
public String getCommand() {
return command;
}
public String getCommandType() {
return wieldable == 16 ? "Wield" : "Wear";
}
public String getCommandType() {
return wieldable == 16 ? "Wield" : "Wear";
}
public int getPictureMask() {
return mask;
}
public int getPictureMask() {
return mask;
}
public int getSprite() {
return sprite;
}
public int getSprite() {
return sprite;
}
public boolean isMembers() {
return members;
}
public boolean isMembers() {
return members;
}
public boolean isStackable() {
return stackable;
}
public boolean isStackable() {
return stackable;
}
public boolean isWieldable() {
return wieldable > 0;
}
public boolean isWieldable() {
return wieldable > 0;
}
}

View File

@ -1,25 +1,25 @@
package org.moparscape.msc.gs.external;
public class ItemDropDef {
public int amount;
public int id;
public int weight;
public int amount;
public int id;
public int weight;
public ItemDropDef(int id, int amount, int weight) {
this.id = id;
this.amount = amount;
this.weight = weight;
}
public ItemDropDef(int id, int amount, int weight) {
this.id = id;
this.amount = amount;
this.weight = weight;
}
public int getAmount() {
return amount;
}
public int getAmount() {
return amount;
}
public int getID() {
return id;
}
public int getID() {
return id;
}
public int getWeight() {
return weight;
}
public int getWeight() {
return weight;
}
}

View File

@ -5,28 +5,28 @@ package org.moparscape.msc.gs.external;
*/
public class ItemGemDef {
/**
* The exp given by attaching this bow string
*/
public int exp;
/**
* The ID of the gem
*/
public int gemID;
/**
* The level required to attach this bow string
*/
public int requiredLvl;
/**
* The exp given by attaching this bow string
*/
public int exp;
/**
* The ID of the gem
*/
public int gemID;
/**
* The level required to attach this bow string
*/
public int requiredLvl;
public int getExp() {
return exp;
}
public int getExp() {
return exp;
}
public int getGemID() {
return gemID;
}
public int getGemID() {
return gemID;
}
public int getReqLevel() {
return requiredLvl;
}
public int getReqLevel() {
return requiredLvl;
}
}

View File

@ -5,29 +5,29 @@ package org.moparscape.msc.gs.external;
*/
public class ItemHerbDef {
/**
* The exp smelting this item gives
*/
public int exp;
/**
* The id of the related potion
*/
public int potionId;
/**
* The level required to make this
*/
public int requiredLvl;
/**
* The exp smelting this item gives
*/
public int exp;
/**
* The id of the related potion
*/
public int potionId;
/**
* The level required to make this
*/
public int requiredLvl;
public int getExp() {
return exp;
}
public int getExp() {
return exp;
}
public int getPotionId() {
return potionId;
}
public int getPotionId() {
return potionId;
}
public int getReqLevel() {
return requiredLvl;
}
public int getReqLevel() {
return requiredLvl;
}
}

View File

@ -5,44 +5,44 @@ package org.moparscape.msc.gs.external;
*/
public class ItemHerbSecond {
/**
* The exp given completing this potion
*/
public int exp;
/**
* The ID of the potion created
*/
public int potionID;
/**
* The level required to complete this potion
*/
public int requiredLvl;
/**
* The ID of the second ingredient
*/
public int secondID;
/**
* The ID of the unfinished potion required
*/
public int unfinishedID;
/**
* The exp given completing this potion
*/
public int exp;
/**
* The ID of the potion created
*/
public int potionID;
/**
* The level required to complete this potion
*/
public int requiredLvl;
/**
* The ID of the second ingredient
*/
public int secondID;
/**
* The ID of the unfinished potion required
*/
public int unfinishedID;
public int getExp() {
return exp;
}
public int getExp() {
return exp;
}
public int getPotionID() {
return potionID;
}
public int getPotionID() {
return potionID;
}
public int getReqLevel() {
return requiredLvl;
}
public int getReqLevel() {
return requiredLvl;
}
public int getSecondID() {
return secondID;
}
public int getSecondID() {
return secondID;
}
public int getUnfinishedID() {
return unfinishedID;
}
public int getUnfinishedID() {
return unfinishedID;
}
}

View File

@ -1,44 +1,44 @@
package org.moparscape.msc.gs.external;
public class ItemLoc {
/**
* Amount of item (stackables)
*/
public int amount;
/**
* The id of the gameObject
*/
public int id;
/**
* How long the item takes to spawn
*/
public int respawnTime;
/**
* The objects x coord
*/
public int x;
/**
* The objects y coord
*/
public int y;
/**
* Amount of item (stackables)
*/
public int amount;
/**
* The id of the gameObject
*/
public int id;
/**
* How long the item takes to spawn
*/
public int respawnTime;
/**
* The objects x coord
*/
public int x;
/**
* The objects y coord
*/
public int y;
public int getAmount() {
return amount;
}
public int getAmount() {
return amount;
}
public int getId() {
return id;
}
public int getId() {
return id;
}
public int getRespawnTime() {
return respawnTime;
}
public int getRespawnTime() {
return respawnTime;
}
public int getX() {
return x;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getY() {
return y;
}
}

View File

@ -5,51 +5,51 @@ package org.moparscape.msc.gs.external;
*/
public class ItemLogCutDef {
public int longbowExp;
public int longbowID;
public int longbowLvl;
public int longbowExp;
public int longbowID;
public int longbowLvl;
public int shaftAmount;
public int shaftLvl;
public int shortbowExp;
public int shaftAmount;
public int shaftLvl;
public int shortbowExp;
public int shortbowID;
public int shortbowLvl;
public int shortbowID;
public int shortbowLvl;
public int getLongbowExp() {
return longbowExp;
}
public int getLongbowExp() {
return longbowExp;
}
public int getLongbowID() {
return longbowID;
}
public int getLongbowID() {
return longbowID;
}
public int getLongbowLvl() {
return longbowLvl;
}
public int getLongbowLvl() {
return longbowLvl;
}
public int getShaftAmount() {
return shaftAmount;
}
public int getShaftAmount() {
return shaftAmount;
}
public int getShaftExp() {
return shaftAmount;
}
public int getShaftExp() {
return shaftAmount;
}
public int getShaftLvl() {
return shaftLvl;
}
public int getShaftLvl() {
return shaftLvl;
}
public int getShortbowExp() {
return shortbowExp;
}
public int getShortbowExp() {
return shortbowExp;
}
public int getShortbowID() {
return shortbowID;
}
public int getShortbowID() {
return shortbowID;
}
public int getShortbowLvl() {
return shortbowLvl;
}
public int getShortbowLvl() {
return shortbowLvl;
}
}

View File

@ -5,37 +5,37 @@ package org.moparscape.msc.gs.external;
*/
public class ItemSmeltingDef {
/**
* The id of the related bar
*/
public int barId;
/**
* The exp smelting this item gives
*/
public int exp;
/**
* The ores required in addition to this one
*/
public ReqOreDef[] reqOres;
/**
* The level required to smelt this
*/
public int requiredLvl;
/**
* The id of the related bar
*/
public int barId;
/**
* The exp smelting this item gives
*/
public int exp;
/**
* The ores required in addition to this one
*/
public ReqOreDef[] reqOres;
/**
* The level required to smelt this
*/
public int requiredLvl;
public int getBarId() {
return barId;
}
public int getBarId() {
return barId;
}
public int getExp() {
return exp;
}
public int getExp() {
return exp;
}
public int getReqLevel() {
return requiredLvl;
}
public int getReqLevel() {
return requiredLvl;
}
public ReqOreDef[] getReqOres() {
return reqOres;
}
public ReqOreDef[] getReqOres() {
return reqOres;
}
}

View File

@ -1,36 +1,36 @@
package org.moparscape.msc.gs.external;
public class ItemSmithingDef {
/**
* The amount of the item produced
*/
public int amount;
/**
* How many bars are required
*/
public int bars;
/**
* The ID of the item produced
*/
public int itemID;
/**
* The smithing level required to make this item
*/
public int level;
/**
* The amount of the item produced
*/
public int amount;
/**
* How many bars are required
*/
public int bars;
/**
* The ID of the item produced
*/
public int itemID;
/**
* The smithing level required to make this item
*/
public int level;
public int getAmount() {
return amount;
}
public int getAmount() {
return amount;
}
public int getItemID() {
return itemID;
}
public int getItemID() {
return itemID;
}
public int getRequiredBars() {
return bars;
}
public int getRequiredBars() {
return bars;
}
public int getRequiredLevel() {
return level;
}
public int getRequiredLevel() {
return level;
}
}

View File

@ -5,29 +5,29 @@ package org.moparscape.msc.gs.external;
*/
public class ItemUnIdentHerbDef {
/**
* How much experience identifying gives
*/
public int exp;
/**
* The id of the herb this turns into
*/
private int newId;
/**
* Herblaw level required to identify
*/
public int requiredLvl;
/**
* How much experience identifying gives
*/
public int exp;
/**
* The id of the herb this turns into
*/
private int newId;
/**
* Herblaw level required to identify
*/
public int requiredLvl;
public int getExp() {
return exp;
}
public int getExp() {
return exp;
}
public int getLevelRequired() {
return requiredLvl;
}
public int getLevelRequired() {
return requiredLvl;
}
public int getNewId() {
return newId;
}
public int getNewId() {
return newId;
}
}

View File

@ -1,108 +1,108 @@
package org.moparscape.msc.gs.external;
import java.util.HashMap;
import java.util.Set;
import java.util.Map.Entry;
import java.util.Set;
/**
* The definition wrapper for items
*/
public class ItemWieldableDef {
/**
* How many armour points should be given
*/
public int armourPoints;
/**
* If the item can only be worn by females (used for female plates)
*/
private boolean femaleOnly;
/**
* How many magic points should be given
*/
public int magicPoints;
/**
* How many prayer points should be given
*/
public int prayerPoints;
/**
* How many range points should be given
*/
public int rangePoints;
/**
* The level of each stat required to wield
*/
public HashMap<Integer, Integer> requiredStats;
/**
* Sprite Id of the item
*/
public int sprite;
/**
* Type of item
*/
public int type;
/**
* How many weapon aim points should be given
*/
public int weaponAimPoints;
/**
* How many weapon power points should be given
*/
public int weaponPowerPoints;
/**
* Body position the item is drawn on
*/
private int wieldPos;
/**
* How many armour points should be given
*/
public int armourPoints;
/**
* If the item can only be worn by females (used for female plates)
*/
private boolean femaleOnly;
/**
* How many magic points should be given
*/
public int magicPoints;
/**
* How many prayer points should be given
*/
public int prayerPoints;
/**
* How many range points should be given
*/
public int rangePoints;
/**
* The level of each stat required to wield
*/
public HashMap<Integer, Integer> requiredStats;
/**
* Sprite Id of the item
*/
public int sprite;
/**
* Type of item
*/
public int type;
/**
* How many weapon aim points should be given
*/
public int weaponAimPoints;
/**
* How many weapon power points should be given
*/
public int weaponPowerPoints;
/**
* Body position the item is drawn on
*/
private int wieldPos;
public boolean femaleOnly() {
return femaleOnly;
}
public int[] getAffectedTypes() {
int[] affectedTypes = EntityHandler.getItemAffectedTypes(type);
if (affectedTypes != null) {
return affectedTypes;
public boolean femaleOnly() {
return femaleOnly;
}
return new int[0];
}
public int getArmourPoints() {
return armourPoints;
}
public int[] getAffectedTypes() {
int[] affectedTypes = EntityHandler.getItemAffectedTypes(type);
if (affectedTypes != null) {
return affectedTypes;
}
return new int[0];
}
public int getMagicPoints() {
return magicPoints;
}
public int getArmourPoints() {
return armourPoints;
}
public int getPrayerPoints() {
return prayerPoints;
}
public int getMagicPoints() {
return magicPoints;
}
public int getRangePoints() {
return rangePoints;
}
public int getPrayerPoints() {
return prayerPoints;
}
public int getSprite() {
return sprite;
}
public int getRangePoints() {
return rangePoints;
}
public Set<Entry<Integer, Integer>> getStatsRequired() {
return requiredStats.entrySet();
}
public int getSprite() {
return sprite;
}
public int getType() {
return type;
}
public Set<Entry<Integer, Integer>> getStatsRequired() {
return requiredStats.entrySet();
}
public int getWeaponAimPoints() {
return weaponAimPoints;
}
public int getType() {
return type;
}
public int getWeaponPowerPoints() {
return weaponPowerPoints;
}
public int getWeaponAimPoints() {
return weaponAimPoints;
}
public int getWieldPos() {
return wieldPos;
}
public int getWeaponPowerPoints() {
return weaponPowerPoints;
}
public int getWieldPos() {
return wieldPos;
}
}

View File

@ -4,148 +4,148 @@ package org.moparscape.msc.gs.external;
* The definition wrapper for npcs
*/
public class NPCDef extends EntityDef {
/**
* Whether the npc is aggressive
*/
public boolean aggressive;
/**
* The attack lvl
*/
public int attack;
/**
* Whether the npc is attackable
*/
public boolean attackable;
/**
* Colour of our legs
*/
public int bottomColour;
/**
* Something to do with the camera
*/
public int camera1, camera2;
/**
* The primary command
*/
public String command;
/**
* The def lvl
*/
public int defense;
/**
* Possible drops
*/
public ItemDropDef[] drops;
/**
* Colour of our hair
*/
public int hairColour;
/**
* The hit points
*/
public int hits;
/**
* How long the npc takes to respawn
*/
public int respawnTime;
/**
* Skin colour
*/
public int skinColour;
/**
* Sprites used to make up this npc
*/
public int[] sprites;
/**
* The strength lvl
*/
public int strength;
/**
* Colour of our top
*/
public int topColour;
/**
* Something to do with models
*/
public int walkModel, combatModel, combatSprite;
/**
* Whether the npc is aggressive
*/
public boolean aggressive;
/**
* The attack lvl
*/
public int attack;
/**
* Whether the npc is attackable
*/
public boolean attackable;
/**
* Colour of our legs
*/
public int bottomColour;
/**
* Something to do with the camera
*/
public int camera1, camera2;
/**
* The primary command
*/
public String command;
/**
* The def lvl
*/
public int defense;
/**
* Possible drops
*/
public ItemDropDef[] drops;
/**
* Colour of our hair
*/
public int hairColour;
/**
* The hit points
*/
public int hits;
/**
* How long the npc takes to respawn
*/
public int respawnTime;
/**
* Skin colour
*/
public int skinColour;
/**
* Sprites used to make up this npc
*/
public int[] sprites;
/**
* The strength lvl
*/
public int strength;
/**
* Colour of our top
*/
public int topColour;
/**
* Something to do with models
*/
public int walkModel, combatModel, combatSprite;
public int getAtt() {
return attack;
}
public int getAtt() {
return attack;
}
public int getBottomColour() {
return bottomColour;
}
public int getBottomColour() {
return bottomColour;
}
public int getCamera1() {
return camera1;
}
public int getCamera1() {
return camera1;
}
public int getCamera2() {
return camera2;
}
public int getCamera2() {
return camera2;
}
public int getCombatModel() {
return combatModel;
}
public int getCombatModel() {
return combatModel;
}
public int getCombatSprite() {
return combatSprite;
}
public int getCombatSprite() {
return combatSprite;
}
public String getCommand() {
return command;
}
public String getCommand() {
return command;
}
public int getDef() {
return defense;
}
public int getDef() {
return defense;
}
public ItemDropDef[] getDrops() {
return drops;
}
public ItemDropDef[] getDrops() {
return drops;
}
public int getHairColour() {
return hairColour;
}
public int getHairColour() {
return hairColour;
}
public int getHits() {
return hits;
}
public int getHits() {
return hits;
}
public int getSkinColour() {
return skinColour;
}
public int getSkinColour() {
return skinColour;
}
public int getSprite(int index) {
return sprites[index];
}
public int getSprite(int index) {
return sprites[index];
}
public int[] getStats() {
return new int[] { attack, defense, strength };
}
public int[] getStats() {
return new int[] { attack, defense, strength };
}
public int getStr() {
return strength;
}
public int getStr() {
return strength;
}
public int getTopColour() {
return topColour;
}
public int getTopColour() {
return topColour;
}
public int getWalkModel() {
return walkModel;
}
public int getWalkModel() {
return walkModel;
}
public boolean isAggressive() {
return attackable && aggressive;
}
public boolean isAggressive() {
return attackable && aggressive;
}
public boolean isAttackable() {
return attackable;
}
public boolean isAttackable() {
return attackable;
}
public int respawnTime() {
return respawnTime;
}
public int respawnTime() {
return respawnTime;
}
}

View File

@ -1,70 +1,71 @@
package org.moparscape.msc.gs.external;
public class NPCLoc {
/**
* The id of the Npc
*/
public int id;
/**
* The Npcs max x coord
*/
public int maxX;
/**
* The Npcs max y coord
*/
public int maxY;
/**
* The Npcs min x coord
*/
public int minX;
/**
* The Npcs min y coord
*/
public int minY;
/**
* The Npcs x coord
*/
public int startX;
/**
* The Npcs y coord
*/
public int startY;
/**
* The id of the Npc
*/
public int id;
/**
* The Npcs max x coord
*/
public int maxX;
/**
* The Npcs max y coord
*/
public int maxY;
/**
* The Npcs min x coord
*/
public int minX;
/**
* The Npcs min y coord
*/
public int minY;
/**
* The Npcs x coord
*/
public int startX;
/**
* The Npcs y coord
*/
public int startY;
public NPCLoc(int id, int startX, int startY, int minX, int maxX, int minY, int maxY) {
this.id = id;
this.startX = startX;
this.startY = startY;
this.minX = minX;
this.maxX = maxX;
this.minY = minY;
this.maxY = maxY;
}
public NPCLoc(int id, int startX, int startY, int minX, int maxX, int minY,
int maxY) {
this.id = id;
this.startX = startX;
this.startY = startY;
this.minX = minX;
this.maxX = maxX;
this.minY = minY;
this.maxY = maxY;
}
public int getId() {
return id;
}
public int getId() {
return id;
}
public int maxX() {
return maxX;
}
public int maxX() {
return maxX;
}
public int maxY() {
return maxY;
}
public int maxY() {
return maxY;
}
public int minX() {
return minX;
}
public int minX() {
return minX;
}
public int minY() {
return minY;
}
public int minY() {
return minY;
}
public int startX() {
return startX;
}
public int startX() {
return startX;
}
public int startY() {
return startY;
}
public int startY() {
return startY;
}
}

View File

@ -5,29 +5,29 @@ package org.moparscape.msc.gs.external;
*/
public class ObjectFishDef {
/**
* How much experience this fish should give
*/
public int exp;
/**
* The id of the fish
*/
public int fishId;
/**
* The fishing level required to fish
*/
public int requiredLevel;
/**
* How much experience this fish should give
*/
public int exp;
/**
* The id of the fish
*/
public int fishId;
/**
* The fishing level required to fish
*/
public int requiredLevel;
public int getExp() {
return exp;
}
public int getExp() {
return exp;
}
public int getId() {
return fishId;
}
public int getId() {
return fishId;
}
public int getReqLevel() {
return requiredLevel;
}
public int getReqLevel() {
return requiredLevel;
}
}

View File

@ -5,39 +5,39 @@ package org.moparscape.msc.gs.external;
*/
public class ObjectFishingDef {
/**
* The If of any bait required to go with the net
*/
public int baitId;
/**
* The fish that can be caught here
*/
public ObjectFishDef[] defs;
/**
* The Id of the net required to fish with
*/
public int netId;
/**
* The If of any bait required to go with the net
*/
public int baitId;
/**
* The fish that can be caught here
*/
public ObjectFishDef[] defs;
/**
* The Id of the net required to fish with
*/
public int netId;
public int getBaitId() {
return baitId;
}
public ObjectFishDef[] getFishDefs() {
return defs;
}
public int getNetId() {
return netId;
}
public int getReqLevel() {
int requiredLevel = 99;
for (ObjectFishDef def : defs) {
if (def.getReqLevel() < requiredLevel) {
requiredLevel = def.getReqLevel();
}
public int getBaitId() {
return baitId;
}
public ObjectFishDef[] getFishDefs() {
return defs;
}
public int getNetId() {
return netId;
}
public int getReqLevel() {
int requiredLevel = 99;
for (ObjectFishDef def : defs) {
if (def.getReqLevel() < requiredLevel) {
requiredLevel = def.getReqLevel();
}
}
return requiredLevel;
}
return requiredLevel;
}
}

View File

@ -5,37 +5,37 @@ package org.moparscape.msc.gs.external;
*/
public class ObjectMiningDef {
/**
* How much experience identifying gives
*/
public int exp;
/**
* The id of the ore this turns into
*/
private int oreId;
/**
* Herblaw level required to identify
*/
public int requiredLvl;
/**
* How long the rock takes to respawn afterwards
*/
public int respawnTime;
/**
* How much experience identifying gives
*/
public int exp;
/**
* The id of the ore this turns into
*/
private int oreId;
/**
* Herblaw level required to identify
*/
public int requiredLvl;
/**
* How long the rock takes to respawn afterwards
*/
public int respawnTime;
public int getExp() {
return exp;
}
public int getExp() {
return exp;
}
public int getOreId() {
return oreId;
}
public int getOreId() {
return oreId;
}
public int getReqLevel() {
return requiredLvl;
}
public int getReqLevel() {
return requiredLvl;
}
public int getRespawnTime() {
return respawnTime;
}
public int getRespawnTime() {
return respawnTime;
}
}

View File

@ -5,45 +5,45 @@ package org.moparscape.msc.gs.external;
*/
public class ObjectWoodcuttingDef {
/**
* How much experience identifying gives
*/
public int exp;
/**
* Percent chance the tree will be felled
*/
public int fell;
/**
* The id of the ore this turns into
*/
private int logId;
/**
* Herblaw level required to identify
*/
public int requiredLvl;
/**
* How long the tree takes to respawn afterwards
*/
public int respawnTime;
/**
* How much experience identifying gives
*/
public int exp;
/**
* Percent chance the tree will be felled
*/
public int fell;
/**
* The id of the ore this turns into
*/
private int logId;
/**
* Herblaw level required to identify
*/
public int requiredLvl;
/**
* How long the tree takes to respawn afterwards
*/
public int respawnTime;
public int getExp() {
return exp;
}
public int getExp() {
return exp;
}
public int getFell() {
return fell;
}
public int getFell() {
return fell;
}
public int getLogId() {
return logId;
}
public int getLogId() {
return logId;
}
public int getReqLevel() {
return requiredLvl;
}
public int getReqLevel() {
return requiredLvl;
}
public int getRespawnTime() {
return respawnTime;
}
public int getRespawnTime() {
return respawnTime;
}
}

View File

@ -5,20 +5,20 @@ package org.moparscape.msc.gs.external;
*/
public class PrayerDef extends EntityDef {
/**
* The drain rate of the prayer (perhaps points per min?)
*/
public int drainRate;
/**
* The level required to use the prayer
*/
public int reqLevel;
/**
* The drain rate of the prayer (perhaps points per min?)
*/
public int drainRate;
/**
* The level required to use the prayer
*/
public int reqLevel;
public int getDrainRate() {
return drainRate;
}
public int getDrainRate() {
return drainRate;
}
public int getReqLevel() {
return reqLevel;
}
public int getReqLevel() {
return reqLevel;
}
}

View File

@ -5,21 +5,21 @@ package org.moparscape.msc.gs.external;
*/
public class ReqOreDef {
/**
* The amount of the ore required
*/
public int amount;
/**
* The id of the ore
*/
public int oreId;
/**
* The amount of the ore required
*/
public int amount;
/**
* The id of the ore
*/
public int oreId;
public int getAmount() {
return amount;
}
public int getAmount() {
return amount;
}
public int getId() {
return oreId;
}
public int getId() {
return oreId;
}
}

View File

@ -1,52 +1,52 @@
package org.moparscape.msc.gs.external;
import java.util.HashMap;
import java.util.Set;
import java.util.Map.Entry;
import java.util.Set;
/**
* The definition wrapper for spells
*/
public class SpellDef extends EntityDef {
/**
* The amount of experience given by this spell
*/
public int exp;
/**
* The level required to use the spell
*/
public int reqLevel;
/**
* The number of each type of rune (item id) required
*/
public HashMap<Integer, Integer> requiredRunes;
/**
* The number of different runes needed for the spell
*/
public int runeCount;
/**
* The type of the spell
*/
public int type;
/**
* The amount of experience given by this spell
*/
public int exp;
/**
* The level required to use the spell
*/
public int reqLevel;
/**
* The number of each type of rune (item id) required
*/
public HashMap<Integer, Integer> requiredRunes;
/**
* The number of different runes needed for the spell
*/
public int runeCount;
/**
* The type of the spell
*/
public int type;
public int getExp() {
return exp;
}
public int getExp() {
return exp;
}
public int getReqLevel() {
return reqLevel;
}
public int getReqLevel() {
return reqLevel;
}
public int getRuneCount() {
return runeCount;
}
public int getRuneCount() {
return runeCount;
}
public Set<Entry<Integer, Integer>> getRunesRequired() {
return requiredRunes.entrySet();
}
public Set<Entry<Integer, Integer>> getRunesRequired() {
return requiredRunes.entrySet();
}
public int getSpellType() {
return type;
}
public int getSpellType() {
return type;
}
}

View File

@ -1,19 +1,19 @@
package org.moparscape.msc.gs.external;
public class TileDef {
public int colour;
public int objectType;
public int unknown;
public int colour;
public int objectType;
public int unknown;
public int getColour() {
return colour;
}
public int getColour() {
return colour;
}
public int getObjectType() {
return objectType;
}
public int getObjectType() {
return objectType;
}
public int getUnknown() {
return unknown;
}
public int getUnknown() {
return unknown;
}
}

View File

@ -24,144 +24,171 @@ import org.moparscape.msc.gs.tools.DataConversions;
import org.moparscape.msc.gs.util.Logger;
import org.moparscape.msc.gs.util.PersistenceManager;
public class WorldLoader {
private ZipFile tileArchive;
private ZipFile tileArchive;
// private ZipOutputStream out;
// private ZipOutputStream out;
private void loadSection(int sectionX, int sectionY, int height, World world, int bigX, int bigY) {
//Logging.debug(1);
Sector s = null;
try {
String filename = "h" + height + "x" + sectionX + "y" + sectionY;
ZipEntry e = tileArchive.getEntry(filename);
if (e == null) {
throw new Exception("Missing tile: " + filename);
}
ByteBuffer data = DataConversions.streamToBuffer(new BufferedInputStream(tileArchive.getInputStream(e)));
s = Sector.unpack(data);
// s = modifyAndSave(filename, s, bigX, bigY);
} catch (Exception e) {
Logger.error(e);
private void loadSection(int sectionX, int sectionY, int height,
World world, int bigX, int bigY) {
// Logging.debug(1);
Sector s = null;
try {
String filename = "h" + height + "x" + sectionX + "y" + sectionY;
ZipEntry e = tileArchive.getEntry(filename);
if (e == null) {
throw new Exception("Missing tile: " + filename);
}
ByteBuffer data = DataConversions
.streamToBuffer(new BufferedInputStream(tileArchive
.getInputStream(e)));
s = Sector.unpack(data);
// s = modifyAndSave(filename, s, bigX, bigY);
} catch (Exception e) {
Logger.error(e);
}
// Logging.debug(2);
for (int y = 0; y < Sector.HEIGHT; y++) {
for (int x = 0; x < Sector.WIDTH; x++) {
int bx = bigX + x;
int by = bigY + y;
if (!world.withinWorld(bx, by)) {
continue;
}
world.getTileValue(bx, by).overlay = s.getTile(x, y).groundOverlay;
world.getTileValue(bx, by).diagWallVal = s.getTile(x, y).diagonalWalls;
world.getTileValue(bx, by).horizontalWallVal = s.getTile(x, y).horizontalWall;
world.getTileValue(bx, by).verticalWallVal = s.getTile(x, y).verticalWall;
world.getTileValue(bx, by).elevation = s.getTile(x, y).groundElevation;
/** start of shit **/
if ((s.getTile(x, y).groundOverlay & 0xff) == 250) {
s.getTile(x, y).groundOverlay = (byte) 2;
}
/** break in shit **/
int groundOverlay = s.getTile(x, y).groundOverlay & 0xFF;
if (groundOverlay > 0
&& EntityHandler.getTileDef(groundOverlay - 1)
.getObjectType() != 0) {
world.getTileValue(bx, by).mapValue |= 0x40; // 64
}
int verticalWall = s.getTile(x, y).verticalWall & 0xFF;
if (verticalWall > 0
&& EntityHandler.getDoorDef(verticalWall - 1)
.getUnknown() == 0
&& EntityHandler.getDoorDef(verticalWall - 1)
.getDoorType() != 0) {
world.getTileValue(bx, by).mapValue |= 1; // 1
world.getTileValue(bx, by - 1).mapValue |= 4; // 4
}
int horizontalWall = s.getTile(x, y).horizontalWall & 0xFF;
if (horizontalWall > 0
&& EntityHandler.getDoorDef(horizontalWall - 1)
.getUnknown() == 0
&& EntityHandler.getDoorDef(horizontalWall - 1)
.getDoorType() != 0) {
world.getTileValue(bx, by).mapValue |= 2; // 2
world.getTileValue(bx - 1, by).mapValue |= 8; // 8
}
int diagonalWalls = s.getTile(x, y).diagonalWalls;
if (diagonalWalls > 0
&& diagonalWalls < 12000
&& EntityHandler.getDoorDef(diagonalWalls - 1)
.getUnknown() == 0
&& EntityHandler.getDoorDef(diagonalWalls - 1)
.getDoorType() != 0) {
world.getTileValue(bx, by).mapValue |= 0x20; // 32
}
if (diagonalWalls > 12000
&& diagonalWalls < 24000
&& EntityHandler.getDoorDef(diagonalWalls - 12001)
.getUnknown() == 0
&& EntityHandler.getDoorDef(diagonalWalls - 12001)
.getDoorType() != 0) {
world.getTileValue(bx, by).mapValue |= 0x10; // 16
}
/** end of shit **/
}
}
// Logging.debug(3);
}
//Logging.debug(2);
for (int y = 0; y < Sector.HEIGHT; y++) {
for (int x = 0; x < Sector.WIDTH; x++) {
int bx = bigX + x;
int by = bigY + y;
if (!world.withinWorld(bx, by)) {
continue;
}
world.getTileValue(bx, by).overlay = s.getTile(x, y).groundOverlay;
world.getTileValue(bx, by).diagWallVal = s.getTile(x, y).diagonalWalls;
world.getTileValue(bx, by).horizontalWallVal = s.getTile(x, y).horizontalWall;
world.getTileValue(bx, by).verticalWallVal = s.getTile(x, y).verticalWall;
world.getTileValue(bx, by).elevation = s.getTile(x, y).groundElevation;
/** start of shit **/
if ((s.getTile(x, y).groundOverlay & 0xff) == 250) {
s.getTile(x, y).groundOverlay = (byte) 2;
}
/** break in shit **/
int groundOverlay = s.getTile(x, y).groundOverlay & 0xFF;
if (groundOverlay > 0 && EntityHandler.getTileDef(groundOverlay - 1).getObjectType() != 0) {
world.getTileValue(bx, by).mapValue |= 0x40; // 64
}
int verticalWall = s.getTile(x, y).verticalWall & 0xFF;
if (verticalWall > 0 && EntityHandler.getDoorDef(verticalWall - 1).getUnknown() == 0 && EntityHandler.getDoorDef(verticalWall - 1).getDoorType() != 0) {
world.getTileValue(bx, by).mapValue |= 1; // 1
world.getTileValue(bx, by - 1).mapValue |= 4; // 4
}
/*
* private Sector modifyAndSave(String filename, Sector s, int bigX, int
* bigY) { for(int y = 0;y < Sector.HEIGHT;y++) { for(int x = 0;x <
* Sector.WIDTH;x++) { int bx = bigX + x; int by = bigY + y;
* if(!Instance.getWorld().withinWorld(bx, by)) { continue; } } } try {
* out.putNextEntry(new ZipEntry(filename));
*
* byte[] data = s.pack().array(); out.write(data);
*
* out.closeEntry(); } catch(Exception e) { e.printStackTrace(); } return s;
* }
*/
int horizontalWall = s.getTile(x, y).horizontalWall & 0xFF;
if (horizontalWall > 0 && EntityHandler.getDoorDef(horizontalWall - 1).getUnknown() == 0 && EntityHandler.getDoorDef(horizontalWall - 1).getDoorType() != 0) {
world.getTileValue(bx, by).mapValue |= 2; // 2
world.getTileValue(bx - 1, by).mapValue |= 8; // 8
}
int diagonalWalls = s.getTile(x, y).diagonalWalls;
if (diagonalWalls > 0 && diagonalWalls < 12000 && EntityHandler.getDoorDef(diagonalWalls - 1).getUnknown() == 0 && EntityHandler.getDoorDef(diagonalWalls - 1).getDoorType() != 0) {
world.getTileValue(bx, by).mapValue |= 0x20; // 32
}
if (diagonalWalls > 12000 && diagonalWalls < 24000 && EntityHandler.getDoorDef(diagonalWalls - 12001).getUnknown() == 0 && EntityHandler.getDoorDef(diagonalWalls - 12001).getDoorType() != 0) {
world.getTileValue(bx, by).mapValue |= 0x10; // 16
}
/** end of shit **/
}
}
//Logging.debug(3);
}
/*
* private Sector modifyAndSave(String filename, Sector s, int bigX, int
* bigY) { for(int y = 0;y < Sector.HEIGHT;y++) { for(int x = 0;x <
* Sector.WIDTH;x++) { int bx = bigX + x; int by = bigY + y;
* if(!Instance.getWorld().withinWorld(bx, by)) { continue; } } } try {
* out.putNextEntry(new ZipEntry(filename));
*
* byte[] data = s.pack().array(); out.write(data);
*
* out.closeEntry(); } catch(Exception e) { e.printStackTrace(); } return s;
* }
*/
@SuppressWarnings("unchecked")
@SuppressWarnings("unchecked")
public void loadWorld(World world) {
try {
tileArchive = new ZipFile(new File(Config.CONF_DIR, "data/Landscape.rscd"));
// out = new ZipOutputStream(new FileOutputStream(new
// File(Config.CONF_DIR, "data/new_Landscape.rscd")));
// out.setLevel(9);
} catch (Exception e) {
Logger.error(e);
}
long now = System.currentTimeMillis();
for (int lvl = 0; lvl < 4; lvl++) {
int wildX = 2304;
int wildY = 1776 - (lvl * 944);
for (int sx = 0; sx < 1000; sx += 48) {
for (int sy = 0; sy < 1000; sy += 48) {
int x = (sx + wildX) / 48;
int y = (sy + (lvl * 944) + wildY) / 48;
loadSection(x, y, lvl, world, sx, sy + (944 * lvl));
try {
tileArchive = new ZipFile(new File(Config.CONF_DIR,
"data/Landscape.rscd"));
// out = new ZipOutputStream(new FileOutputStream(new
// File(Config.CONF_DIR, "data/new_Landscape.rscd")));
// out.setLevel(9);
} catch (Exception e) {
Logger.error(e);
}
}
long now = System.currentTimeMillis();
for (int lvl = 0; lvl < 4; lvl++) {
int wildX = 2304;
int wildY = 1776 - (lvl * 944);
for (int sx = 0; sx < 1000; sx += 48) {
for (int sy = 0; sy < 1000; sy += 48) {
int x = (sx + wildX) / 48;
int y = (sy + (lvl * 944) + wildY) / 48;
loadSection(x, y, lvl, world, sx, sy + (944 * lvl));
}
}
}
Logger.error((System.currentTimeMillis() - now) / 1000 + "s to parse");
// try { out.close(); } catch(Exception e) { Logger.error(e); }
for (Shop shop : (List<Shop>) PersistenceManager
.load("locs/Shops.xml.gz")) {
world.registerShop(shop);
}
System.gc();
}
Logger.error((System.currentTimeMillis() - now)/1000 + "s to parse");
// try { out.close(); } catch(Exception e) { Logger.error(e); }
for (Shop shop : (List<Shop>) PersistenceManager.load("locs/Shops.xml.gz")) {
world.registerShop(shop);
@SuppressWarnings("unchecked")
public void loadObjects() {
World world = Instance.getWorld();
for (GameObjectLoc gameObject : (List<GameObjectLoc>) PersistenceManager
.load("locs/GameObjectLoc.xml.gz")) {
if (Config.f2pWildy && Formulae.isP2P(true, gameObject))
continue;
if (Formulae.isP2P(gameObject) && !World.isMembers())
continue;
world.registerGameObject(new GameObject(gameObject));
}
for (ItemLoc item : (List<ItemLoc>) PersistenceManager
.load("locs/ItemLoc.xml.gz")) {
if (Config.f2pWildy && Formulae.isP2P(true, item))
continue;
if (Formulae.isP2P(item) && !World.isMembers())
continue;
world.registerItem(new Item(item));
}// ember
for (NPCLoc npc : (List<NPCLoc>) PersistenceManager
.load("locs/NpcLoc.xml.gz")) {
if (Config.f2pWildy && Formulae.isP2P(true, npc))
continue;
if (Formulae.isP2P(npc) && !World.isMembers())
continue;
world.registerNpc(new Npc(npc));
}
}
System.gc();
}
@SuppressWarnings("unchecked")
public void loadObjects() {
World world = Instance.getWorld();
for (GameObjectLoc gameObject : (List<GameObjectLoc>) PersistenceManager.load("locs/GameObjectLoc.xml.gz")) {
if(Config.f2pWildy && Formulae.isP2P(true, gameObject))
continue;
if (Formulae.isP2P(gameObject) && !World.isMembers())
continue;
world.registerGameObject(new GameObject(gameObject));
}
for (ItemLoc item : (List<ItemLoc>) PersistenceManager.load("locs/ItemLoc.xml.gz")) {
if(Config.f2pWildy && Formulae.isP2P(true, item))
continue;
if (Formulae.isP2P(item) && !World.isMembers())
continue;
world.registerItem(new Item(item));
}// ember
for (NPCLoc npc : (List<NPCLoc>) PersistenceManager.load("locs/NpcLoc.xml.gz")) {
if(Config.f2pWildy && Formulae.isP2P(true, npc))
continue;
if (Formulae.isP2P(npc) && !World.isMembers())
continue;
world.registerNpc(new Npc(npc));
}
}
}

View File

@ -7,7 +7,6 @@ import org.moparscape.msc.config.Formulae;
import org.moparscape.msc.gs.Instance;
import org.moparscape.msc.gs.tools.DataConversions;
public class ActiveTile {
/**
@ -42,7 +41,9 @@ public class ActiveTile {
this.x = x;
this.y = y;
}
public boolean remove = false;
/**
* Add an entity to the tile
*/
@ -108,38 +109,46 @@ public class ActiveTile {
}
public boolean specificArea() {
boolean t = DataConversions.inPointArray(Formulae.noremoveTiles, new Point(this.getX(), this.getY()));
boolean t = DataConversions.inPointArray(Formulae.noremoveTiles,
new Point(this.getX(), this.getY()));
return t;
}
/**
* Remove an entity from the tile
*/
public void remove(Entity entity) {
if (entity instanceof Player) {
players.remove(entity);
if (!this.hasGameObject() && !this.hasItems() && !this.hasNpcs() && !this.hasPlayers() && !this.specificArea()) {
if (!this.hasGameObject() && !this.hasItems() && !this.hasNpcs()
&& !this.hasPlayers() && !this.specificArea()) {
Instance.getWorld().tiles[this.getX()][this.getY()] = null;
}
} else if (entity instanceof Npc) {
npcs.remove(entity);
if (!this.hasGameObject() && !this.hasItems() && !this.hasNpcs() && !this.hasPlayers() && !this.specificArea()) {
if (!this.hasGameObject() && !this.hasItems() && !this.hasNpcs()
&& !this.hasPlayers() && !this.specificArea()) {
Instance.getWorld().tiles[this.getX()][this.getY()] = null;
}
} else if (entity instanceof Item) {
items.remove(entity);
if (!this.hasGameObject() && !this.hasItems() && !this.hasNpcs() && !this.hasPlayers() && !this.specificArea()) {
if (!this.hasGameObject() && !this.hasItems() && !this.hasNpcs()
&& !this.hasPlayers() && !this.specificArea()) {
Instance.getWorld().tiles[this.getX()][this.getY()] = null;
}
} else if (entity instanceof GameObject) {
object = null;
if (!this.hasGameObject() && !this.hasItems() && !this.hasNpcs() && !this.hasPlayers() && !remove) {
if (!this.hasGameObject() && !this.hasItems() && !this.hasNpcs()
&& !this.hasPlayers() && !remove) {
Instance.getWorld().tiles[this.getX()][this.getY()] = null;
}
}
}
public void cleanItself() {
if (!this.hasGameObject() && !this.hasItems() && !this.hasNpcs() && !this.hasPlayers() && !this.specificArea()) {
if (!this.hasGameObject() && !this.hasItems() && !this.hasNpcs()
&& !this.hasPlayers() && !this.specificArea()) {
Instance.getWorld().tiles[this.getX()][this.getY()] = null;
}
}

View File

@ -6,141 +6,142 @@ import java.util.List;
import java.util.ListIterator;
public class Bank {
/**
* The maximum size of a bank
*/
public static final int MAX_SIZE = 192;
private ArrayList<InvItem> list = new ArrayList<InvItem>();
/**
* The maximum size of a bank
*/
public static final int MAX_SIZE = 192;
private ArrayList<InvItem> list = new ArrayList<InvItem>();
public Bank() {
}
public int add(InvItem item) {
if (item.getAmount() <= 0) {
return -1;
}
for (int index = 0; index < list.size(); index++) {
if (item.equals(list.get(index))) {
list.get(index).setAmount(list.get(index).getAmount() + item.getAmount());
return index;
}
}
list.add(item);
return list.size() - 2;
}
public boolean canHold(ArrayList<InvItem> items) {
return (MAX_SIZE - list.size()) >= getRequiredSlots(items);
}
public boolean canHold(InvItem item) {
return (MAX_SIZE - list.size()) >= getRequiredSlots(item);
}
public boolean contains(InvItem i) {
return list.contains(i);
}
public int countId(int id) {
for (InvItem i : list) {
if (i.getID() == id) {
return i.getAmount();
}
}
return 0;
}
public boolean full() {
return list.size() >= MAX_SIZE;
}
public InvItem get(int index) {
if (index < 0 || index >= list.size()) {
return null;
}
return list.get(index);
}
public InvItem get(InvItem item) {
for (InvItem i : list) {
if (item.equals(i)) {
return i;
}
}
return null;
}
public int getFirstIndexById(int id) {
for (int index = 0; index < list.size(); index++) {
if (list.get(index).getID() == id) {
return index;
}
}
return -1;
}
public ArrayList<InvItem> getItems() {
return list;
}
public int getRequiredSlots(InvItem item) {
return (list.contains(item) ? 0 : 1);
}
public int getRequiredSlots(List<InvItem> items) {
int requiredSlots = 0;
for (InvItem item : items) {
if (list.contains(item)) {
continue;
}
requiredSlots++;
}
return requiredSlots;
}
public boolean hasItemId(int id) {
for (InvItem i : list) {
if (i.getID() == id)
return true;
public Bank() {
}
return false;
}
public ListIterator<InvItem> iterator() {
return list.listIterator();
}
public void remove(int index) {
InvItem item = get(index);
if (item == null) {
return;
}
remove(item.getID(), item.getAmount());
}
public int remove(int id, int amount) {
Iterator<InvItem> iterator = list.iterator();
for (int index = 0; iterator.hasNext(); index++) {
InvItem i = iterator.next();
if (id == i.getID()) {
if (amount < i.getAmount()) {
i.setAmount(i.getAmount() - amount);
} else {
iterator.remove();
public int add(InvItem item) {
if (item.getAmount() <= 0) {
return -1;
}
return index;
}
for (int index = 0; index < list.size(); index++) {
if (item.equals(list.get(index))) {
list.get(index).setAmount(
list.get(index).getAmount() + item.getAmount());
return index;
}
}
list.add(item);
return list.size() - 2;
}
return -1;
}
public int remove(InvItem item) {
return remove(item.getID(), item.getAmount());
}
public boolean canHold(ArrayList<InvItem> items) {
return (MAX_SIZE - list.size()) >= getRequiredSlots(items);
}
public int size() {
return list.size();
}
public boolean canHold(InvItem item) {
return (MAX_SIZE - list.size()) >= getRequiredSlots(item);
}
public boolean contains(InvItem i) {
return list.contains(i);
}
public int countId(int id) {
for (InvItem i : list) {
if (i.getID() == id) {
return i.getAmount();
}
}
return 0;
}
public boolean full() {
return list.size() >= MAX_SIZE;
}
public InvItem get(int index) {
if (index < 0 || index >= list.size()) {
return null;
}
return list.get(index);
}
public InvItem get(InvItem item) {
for (InvItem i : list) {
if (item.equals(i)) {
return i;
}
}
return null;
}
public int getFirstIndexById(int id) {
for (int index = 0; index < list.size(); index++) {
if (list.get(index).getID() == id) {
return index;
}
}
return -1;
}
public ArrayList<InvItem> getItems() {
return list;
}
public int getRequiredSlots(InvItem item) {
return (list.contains(item) ? 0 : 1);
}
public int getRequiredSlots(List<InvItem> items) {
int requiredSlots = 0;
for (InvItem item : items) {
if (list.contains(item)) {
continue;
}
requiredSlots++;
}
return requiredSlots;
}
public boolean hasItemId(int id) {
for (InvItem i : list) {
if (i.getID() == id)
return true;
}
return false;
}
public ListIterator<InvItem> iterator() {
return list.listIterator();
}
public void remove(int index) {
InvItem item = get(index);
if (item == null) {
return;
}
remove(item.getID(), item.getAmount());
}
public int remove(int id, int amount) {
Iterator<InvItem> iterator = list.iterator();
for (int index = 0; iterator.hasNext(); index++) {
InvItem i = iterator.next();
if (id == i.getID()) {
if (amount < i.getAmount()) {
i.setAmount(i.getAmount() - amount);
} else {
iterator.remove();
}
return index;
}
}
return -1;
}
public int remove(InvItem item) {
return remove(item.getID(), item.getAmount());
}
public int size() {
return list.size();
}
}

View File

@ -1,26 +1,26 @@
package org.moparscape.msc.gs.model;
public class Bubble {
/**
* What to draw in it
*/
private int itemID;
/**
* Who the bubble belongs to
*/
private Player owner;
/**
* What to draw in it
*/
private int itemID;
/**
* Who the bubble belongs to
*/
private Player owner;
public Bubble(Player owner, int itemID) {
this.owner = owner;
this.itemID = itemID;
}
public Bubble(Player owner, int itemID) {
this.owner = owner;
this.itemID = itemID;
}
public int getID() {
return itemID;
}
public int getID() {
return itemID;
}
public Player getOwner() {
return owner;
}
public Player getOwner() {
return owner;
}
}

View File

@ -3,44 +3,44 @@ package org.moparscape.msc.gs.model;
import org.moparscape.msc.gs.tools.DataConversions;
public class ChatMessage {
/**
* The message it self, in byte format
*/
private byte[] message;
/**
* Who the message is for
*/
private Mob recipient = null;
/**
* Who sent the message
*/
private Mob sender;
/**
* The message it self, in byte format
*/
private byte[] message;
/**
* Who the message is for
*/
private Mob recipient = null;
/**
* Who sent the message
*/
private Mob sender;
public ChatMessage(Mob sender, byte[] message) {
this.sender = sender;
this.message = message;
}
public ChatMessage(Mob sender, byte[] message) {
this.sender = sender;
this.message = message;
}
public ChatMessage(Mob sender, String message, Mob recipient) {
this.sender = sender;
this.message = DataConversions.stringToByteArray(message);
this.recipient = recipient;
}
public ChatMessage(Mob sender, String message, Mob recipient) {
this.sender = sender;
this.message = DataConversions.stringToByteArray(message);
this.recipient = recipient;
}
public int getLength() {
return message.length;
}
public int getLength() {
return message.length;
}
public byte[] getMessage() {
return message;
}
public byte[] getMessage() {
return message;
}
public Mob getRecipient() {
return recipient;
}
public Mob getRecipient() {
return recipient;
}
public Mob getSender() {
return sender;
}
public Mob getSender() {
return sender;
}
}

View File

@ -1,211 +1,225 @@
package org.moparscape.msc.gs.model;
import org.moparscape.msc.config.Config;
import org.moparscape.msc.config.Constants;
import org.moparscape.msc.config.Formulae;
import org.moparscape.msc.gs.Instance;
public class Entity {
/**
* World instance
*/
public static final World world = Instance.getWorld();
/**
* World instance
*/
public static final World world = Instance.getWorld();
protected int id;
protected int id;
protected int index;
protected int index;
protected Point location;
protected Point location;
public final int getID() {
return id;
}
public final int getIndex() {
return index;
}
public final Point getLocation() {
return location;
}
public final int getX() {
return location.getX();
}
public final int getY() {
return location.getY();
}
private boolean isBlocking(Entity e, int x, int y, int bit) {
return isMapBlocking(e, x, y, (byte) bit) || isObjectBlocking(e, x, y, (byte) bit);
}
private boolean isMapBlocking(Entity e, int x, int y, byte bit) {
byte val = world.getTileValue(x, y).mapValue;
if ((val & bit) != 0) { // There is a wall in the way
return true;
}
if ((val & 16) != 0) { // There is a diagonal wall here: \
return true;
}
if ((val & 32) != 0) { // There is a diagonal wall here: /
return true;
}
if ((val & 64) != 0 && (e instanceof Npc || e instanceof Player || (e instanceof Item && !((Item) e).isOn(x, y)) || (e instanceof GameObject && !((GameObject) e).isOn(x, y)))) { // There
// is
// an
// object
// here,
// doesn't
// block items (ontop of it) or the
// object itself though
return true;
}
return false;
}
private boolean isObjectBlocking(Entity e, int x, int y, byte bit) {
byte val = world.getTileValue(x, y).objectValue;
if ((val & bit) != 0 && !Formulae.doorAtFacing(e, x, y, Formulae.bitToDoorDir(bit)) && !Formulae.objectAtFacing(e, x, y, Formulae.bitToObjectDir(bit))) { // There
// is
// a
// wall
// in
// the
// way
return true;
}
if ((val & 16) != 0 && !Formulae.doorAtFacing(e, x, y, 2) && !Formulae.objectAtFacing(e, x, y, 3)) { // There
// is
// a
// diagonal wall
// here: \
return true;
}
if ((val & 32) != 0 && !Formulae.doorAtFacing(e, x, y, 3) && !Formulae.objectAtFacing(e, x, y, 1)) { // There
// is
// a
// diagonal wall
// here: /
return true;
}
if ((val & 64) != 0 && (e instanceof Npc || e instanceof Player || (e instanceof Item && !((Item) e).isOn(x, y)) || (e instanceof GameObject && !((GameObject) e).isOn(x, y)))) { // There
// is
// an
// object
// here,
// doesn't
// block items (ontop of it) or the
// object itself though
return true;
}
return false;
}
public int[] nextStep(int myX, int myY, Entity e) {
if (myX == e.getX() && myY == e.getY()) {
return new int[] { myX, myY };
}
int newX = myX, newY = myY;
boolean myXBlocked = false, myYBlocked = false, newXBlocked = false, newYBlocked = false;
if (myX > e.getX()) {
myXBlocked = isBlocking(e, myX - 1, myY, 8); // Check right tiles
// left wall
newX = myX - 1;
} else if (myX < e.getX()) {
myXBlocked = isBlocking(e, myX + 1, myY, 2); // Check left tiles
// right wall
newX = myX + 1;
public final int getID() {
return id;
}
if (myY > e.getY()) {
myYBlocked = isBlocking(e, myX, myY - 1, 4); // Check top tiles
// bottom wall
newY = myY - 1;
} else if (myY < e.getY()) {
myYBlocked = isBlocking(e, myX, myY + 1, 1); // Check bottom tiles
// top wall
newY = myY + 1;
public final int getIndex() {
return index;
}
// If both directions are blocked OR we are going straight and the
// direction is blocked
if ((myXBlocked && myYBlocked) || (myXBlocked && myY == newY) || (myYBlocked && myX == newX)) {
return null;
public final Point getLocation() {
return location;
}
if (newX > myX) {
newXBlocked = isBlocking(e, newX, newY, 2); // Check dest tiles
// right wall
} else if (newX < myX) {
newXBlocked = isBlocking(e, newX, newY, 8); // Check dest tiles left
// wall
public final int getX() {
return location.getX();
}
if (newY > myY) {
newYBlocked = isBlocking(e, newX, newY, 1); // Check dest tiles top
// wall
} else if (newY < myY) {
newYBlocked = isBlocking(e, newX, newY, 4); // Check dest tiles
// bottom wall
public final int getY() {
return location.getY();
}
// If both directions are blocked OR we are going straight and the
// direction is blocked
if ((newXBlocked && newYBlocked) || (newXBlocked && myY == newY) || (myYBlocked && myX == newX)) {
return null;
private boolean isBlocking(Entity e, int x, int y, int bit) {
return isMapBlocking(e, x, y, (byte) bit)
|| isObjectBlocking(e, x, y, (byte) bit);
}
// If only one direction is blocked, but it blocks both tiles
if ((myXBlocked && newXBlocked) || (myYBlocked && newYBlocked)) {
return null;
}
return new int[] { newX, newY };
}
public final boolean nextTo(Entity e) {
int[] currentCoords = { getX(), getY() };
while (currentCoords[0] != e.getX() || currentCoords[1] != e.getY()) {
currentCoords = nextStep(currentCoords[0], currentCoords[1], e);
if (currentCoords == null) {
return false;
}
}
return true;
}
public final void setID(int newid) {
id = newid;
}
public final void setIndex(int newIndex) {
index = newIndex;
}
public void setLocation(Point p) {
if(this instanceof Player && location != null && Config.f2pWildy) {
Player pl = (Player)this;
if(pl != null && getX() > 0 && getY() > 0) {
if(!Point.inWilderness(getX(), getY()) && Point.inWilderness(p.getX(), p.getY())) {
pl.p2pWildy();
private boolean isMapBlocking(Entity e, int x, int y, byte bit) {
byte val = world.getTileValue(x, y).mapValue;
if ((val & bit) != 0) { // There is a wall in the way
return true;
}
}
if ((val & 16) != 0) { // There is a diagonal wall here: \
return true;
}
if ((val & 32) != 0) { // There is a diagonal wall here: /
return true;
}
if ((val & 64) != 0
&& (e instanceof Npc || e instanceof Player
|| (e instanceof Item && !((Item) e).isOn(x, y)) || (e instanceof GameObject && !((GameObject) e)
.isOn(x, y)))) { // There
// is
// an
// object
// here,
// doesn't
// block items (ontop of it) or the
// object itself though
return true;
}
return false;
}
world.setLocation(this, location, p);
location = p;
}
public final boolean withinRange(Entity e, int radius) {
return withinRange(e.getLocation(), radius);
}
private boolean isObjectBlocking(Entity e, int x, int y, byte bit) {
byte val = world.getTileValue(x, y).objectValue;
if ((val & bit) != 0
&& !Formulae.doorAtFacing(e, x, y, Formulae.bitToDoorDir(bit))
&& !Formulae.objectAtFacing(e, x, y,
Formulae.bitToObjectDir(bit))) { // There
// is
// a
// wall
// in
// the
// way
return true;
}
if ((val & 16) != 0 && !Formulae.doorAtFacing(e, x, y, 2)
&& !Formulae.objectAtFacing(e, x, y, 3)) { // There
// is
// a
// diagonal wall
// here: \
return true;
}
if ((val & 32) != 0 && !Formulae.doorAtFacing(e, x, y, 3)
&& !Formulae.objectAtFacing(e, x, y, 1)) { // There
// is
// a
// diagonal wall
// here: /
return true;
}
if ((val & 64) != 0
&& (e instanceof Npc || e instanceof Player
|| (e instanceof Item && !((Item) e).isOn(x, y)) || (e instanceof GameObject && !((GameObject) e)
.isOn(x, y)))) { // There
// is
// an
// object
// here,
// doesn't
// block items (ontop of it) or the
// object itself though
return true;
}
return false;
}
public final boolean withinRange(Point p, int radius) {
int xDiff = Math.abs(location.getX() - p.getX());
int yDiff = Math.abs(location.getY() - p.getY());
return xDiff <= radius && yDiff <= radius;
}
public int[] nextStep(int myX, int myY, Entity e) {
if (myX == e.getX() && myY == e.getY()) {
return new int[] { myX, myY };
}
int newX = myX, newY = myY;
boolean myXBlocked = false, myYBlocked = false, newXBlocked = false, newYBlocked = false;
if (myX > e.getX()) {
myXBlocked = isBlocking(e, myX - 1, myY, 8); // Check right tiles
// left wall
newX = myX - 1;
} else if (myX < e.getX()) {
myXBlocked = isBlocking(e, myX + 1, myY, 2); // Check left tiles
// right wall
newX = myX + 1;
}
if (myY > e.getY()) {
myYBlocked = isBlocking(e, myX, myY - 1, 4); // Check top tiles
// bottom wall
newY = myY - 1;
} else if (myY < e.getY()) {
myYBlocked = isBlocking(e, myX, myY + 1, 1); // Check bottom tiles
// top wall
newY = myY + 1;
}
// If both directions are blocked OR we are going straight and the
// direction is blocked
if ((myXBlocked && myYBlocked) || (myXBlocked && myY == newY)
|| (myYBlocked && myX == newX)) {
return null;
}
if (newX > myX) {
newXBlocked = isBlocking(e, newX, newY, 2); // Check dest tiles
// right wall
} else if (newX < myX) {
newXBlocked = isBlocking(e, newX, newY, 8); // Check dest tiles left
// wall
}
if (newY > myY) {
newYBlocked = isBlocking(e, newX, newY, 1); // Check dest tiles top
// wall
} else if (newY < myY) {
newYBlocked = isBlocking(e, newX, newY, 4); // Check dest tiles
// bottom wall
}
// If both directions are blocked OR we are going straight and the
// direction is blocked
if ((newXBlocked && newYBlocked) || (newXBlocked && myY == newY)
|| (myYBlocked && myX == newX)) {
return null;
}
// If only one direction is blocked, but it blocks both tiles
if ((myXBlocked && newXBlocked) || (myYBlocked && newYBlocked)) {
return null;
}
return new int[] { newX, newY };
}
public final boolean nextTo(Entity e) {
int[] currentCoords = { getX(), getY() };
while (currentCoords[0] != e.getX() || currentCoords[1] != e.getY()) {
currentCoords = nextStep(currentCoords[0], currentCoords[1], e);
if (currentCoords == null) {
return false;
}
}
return true;
}
public final void setID(int newid) {
id = newid;
}
public final void setIndex(int newIndex) {
index = newIndex;
}
public void setLocation(Point p) {
if (this instanceof Player && location != null && Config.f2pWildy) {
Player pl = (Player) this;
if (pl != null && getX() > 0 && getY() > 0) {
if (!Point.inWilderness(getX(), getY())
&& Point.inWilderness(p.getX(), p.getY())) {
pl.p2pWildy();
}
}
}
world.setLocation(this, location, p);
location = p;
}
public final boolean withinRange(Entity e, int radius) {
return withinRange(e.getLocation(), radius);
}
public final boolean withinRange(Point p, int radius) {
int xDiff = Math.abs(location.getX() - p.getX());
int yDiff = Math.abs(location.getY() - p.getY());
return xDiff <= radius && yDiff <= radius;
}
}

View File

@ -6,118 +6,125 @@ import org.moparscape.msc.gs.external.GameObjectDef;
import org.moparscape.msc.gs.external.GameObjectLoc;
public class GameObject extends Entity {
/**
* Returns the ID of an item contained in the object.
*
* @author Konijn
*/
private int containsItem = -1;
/**
* The direction the object points in
*/
private int direction;
/**
* Location definition of the object
*/
private GameObjectLoc loc = null;
/**
* Set when the item has been destroyed to alert players
*/
private boolean removed = false;
/**
* Returns the ID of an item contained in the object.
*
* @author Konijn
*/
private int containsItem = -1;
/**
* The direction the object points in
*/
private int direction;
/**
* Location definition of the object
*/
private GameObjectLoc loc = null;
/**
* Set when the item has been destroyed to alert players
*/
private boolean removed = false;
/**
* The type of object
*/
private int type;
/**
* The type of object
*/
private int type;
public GameObject(GameObjectLoc loc) {
direction = loc.direction;
type = loc.type;
this.loc = loc;
super.setID(loc.id);
super.setLocation(Point.location(loc.x, loc.y));
}
public GameObject(Point location, int id, int direction, int type) {
this(new GameObjectLoc(id, location.getX(), location.getY(), direction, type));
}
public int containsItem() {
return containsItem;
}
public void containsItem(int item) {
containsItem = item;
}
public boolean equals(Object o) {
if (o instanceof GameObject) {
GameObject go = (GameObject) o;
return go.getLocation().equals(getLocation()) && go.getID() == getID() && go.getDirection() == getDirection() && go.getType() == getType();
public GameObject(GameObjectLoc loc) {
direction = loc.direction;
type = loc.type;
this.loc = loc;
super.setID(loc.id);
super.setLocation(Point.location(loc.x, loc.y));
}
return false;
}
public int getDirection() {
return direction;
}
public DoorDef getDoorDef() {
return EntityHandler.getDoorDef(super.getID());
}
public GameObjectDef getGameObjectDef() {
return EntityHandler.getGameObjectDef(super.getID());
}
public GameObjectLoc getLoc() {
return loc;
}
public int getType() {
return type;
}
public boolean isOn(int x, int y) {
int width, height;
if (type == 1) {
width = height = 1;
} else if (direction == 0 || direction == 4) {
width = getGameObjectDef().getWidth();
height = getGameObjectDef().getHeight();
} else {
height = getGameObjectDef().getWidth();
width = getGameObjectDef().getHeight();
public GameObject(Point location, int id, int direction, int type) {
this(new GameObjectLoc(id, location.getX(), location.getY(), direction,
type));
}
if (type == 0) { // Object
return x >= getX() && x <= (getX() + width) && y >= getY() && y <= (getY() + height);
} else { // Door
return x == getX() && y == getY();
public int containsItem() {
return containsItem;
}
}
public boolean isRemoved() {
return removed;
}
public void containsItem(int item) {
containsItem = item;
}
public boolean isTelePoint() {
return EntityHandler.getObjectTelePoint(getLocation(), null) != null;
}
public boolean equals(Object o) {
if (o instanceof GameObject) {
GameObject go = (GameObject) o;
return go.getLocation().equals(getLocation())
&& go.getID() == getID()
&& go.getDirection() == getDirection()
&& go.getType() == getType();
}
return false;
}
public void remove() {
removed = true;
}
public int getDirection() {
return direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
public DoorDef getDoorDef() {
return EntityHandler.getDoorDef(super.getID());
}
public void setType(int type) {
this.type = type;
}
public GameObjectDef getGameObjectDef() {
return EntityHandler.getGameObjectDef(super.getID());
}
public String toString() {
return (type == 0 ? "GameObject" : "WallObject") + ":id = " + id + "; dir = " + direction + "; location = " + location.toString() + ";";
}
public GameObjectLoc getLoc() {
return loc;
}
public int getType() {
return type;
}
public boolean isOn(int x, int y) {
int width, height;
if (type == 1) {
width = height = 1;
} else if (direction == 0 || direction == 4) {
width = getGameObjectDef().getWidth();
height = getGameObjectDef().getHeight();
} else {
height = getGameObjectDef().getWidth();
width = getGameObjectDef().getHeight();
}
if (type == 0) { // Object
return x >= getX() && x <= (getX() + width) && y >= getY()
&& y <= (getY() + height);
} else { // Door
return x == getX() && y == getY();
}
}
public boolean isRemoved() {
return removed;
}
public boolean isTelePoint() {
return EntityHandler.getObjectTelePoint(getLocation(), null) != null;
}
public void remove() {
removed = true;
}
public void setDirection(int direction) {
this.direction = direction;
}
public void setType(int type) {
this.type = type;
}
public String toString() {
return (type == 0 ? "GameObject" : "WallObject") + ":id = " + id
+ "; dir = " + direction + "; location = "
+ location.toString() + ";";
}
}

View File

@ -9,101 +9,101 @@ import org.moparscape.msc.gs.external.ItemWieldableDef;
public class InvItem extends Entity implements Comparable<InvItem> {
private int amount;
private boolean wielded = false;
private int amount;
private boolean wielded = false;
public InvItem(int id) {
setID(id);
setAmount(1);
}
public InvItem(int id, int amount) {
setID(id);
setAmount(amount);
}
public int compareTo(InvItem item) {
if (item.getDef().isStackable()) {
return -1;
public InvItem(int id) {
setID(id);
setAmount(1);
}
if (getDef().isStackable()) {
return 1;
public InvItem(int id, int amount) {
setID(id);
setAmount(amount);
}
return item.getDef().getBasePrice() - getDef().getBasePrice();
}
public int eatingHeals() {
if (!isEdible()) {
return 0;
public int compareTo(InvItem item) {
if (item.getDef().isStackable()) {
return -1;
}
if (getDef().isStackable()) {
return 1;
}
return item.getDef().getBasePrice() - getDef().getBasePrice();
}
return EntityHandler.getItemEdibleHeals(id);
}
public boolean equals(Object o) {
if (o instanceof InvItem) {
InvItem item = (InvItem) o;
return item.getID() == getID();
public int eatingHeals() {
if (!isEdible()) {
return 0;
}
return EntityHandler.getItemEdibleHeals(id);
}
return false;
}
public int getAmount() {
return amount;
}
public ItemCookingDef getCookingDef() {
return EntityHandler.getItemCookingDef(id);
}
public ItemDef getDef() {
return EntityHandler.getItemDef(id);
}
public ItemSmeltingDef getSmeltingDef() {
return EntityHandler.getItemSmeltingDef(id);
}
public ItemUnIdentHerbDef getUnIdentHerbDef() {
return EntityHandler.getItemUnIdentHerbDef(id);
}
public ItemWieldableDef getWieldableDef() {
return EntityHandler.getItemWieldableDef(id);
}
public boolean isEdible() {
return EntityHandler.getItemEdibleHeals(id) > 0;
}
public boolean isWieldable() {
return EntityHandler.getItemWieldableDef(id) != null;
}
public boolean isWielded() {
return wielded;
}
public void setAmount(int amount) {
if (amount < 0) {
amount = 0;
public boolean equals(Object o) {
if (o instanceof InvItem) {
InvItem item = (InvItem) o;
return item.getID() == getID();
}
return false;
}
this.amount = amount;
}
public void setWield(boolean wielded) {
this.wielded = wielded;
}
public int getAmount() {
return amount;
}
public boolean wieldingAffectsItem(InvItem i) {
if (!i.isWieldable() || !isWieldable()) {
return false;
public ItemCookingDef getCookingDef() {
return EntityHandler.getItemCookingDef(id);
}
for (int affected : getWieldableDef().getAffectedTypes()) {
if (i.getWieldableDef().getType() == affected) {
return true;
}
public ItemDef getDef() {
return EntityHandler.getItemDef(id);
}
public ItemSmeltingDef getSmeltingDef() {
return EntityHandler.getItemSmeltingDef(id);
}
public ItemUnIdentHerbDef getUnIdentHerbDef() {
return EntityHandler.getItemUnIdentHerbDef(id);
}
public ItemWieldableDef getWieldableDef() {
return EntityHandler.getItemWieldableDef(id);
}
public boolean isEdible() {
return EntityHandler.getItemEdibleHeals(id) > 0;
}
public boolean isWieldable() {
return EntityHandler.getItemWieldableDef(id) != null;
}
public boolean isWielded() {
return wielded;
}
public void setAmount(int amount) {
if (amount < 0) {
amount = 0;
}
this.amount = amount;
}
public void setWield(boolean wielded) {
this.wielded = wielded;
}
public boolean wieldingAffectsItem(InvItem i) {
if (!i.isWieldable() || !isWieldable()) {
return false;
}
for (int affected : getWieldableDef().getAffectedTypes()) {
if (i.getWieldableDef().getType() == affected) {
return true;
}
}
return false;
}
return false;
}
}

View File

@ -7,191 +7,197 @@ import java.util.ListIterator;
import org.moparscape.msc.gs.Instance;
public class Inventory {
/**
* The maximum size of an inventory
*/
public static final int MAX_SIZE = 30;
/**
* World instance
*/
private static World world = Instance.getWorld();
private ArrayList<InvItem> list = new ArrayList<InvItem>();
private Player player;
/**
* The maximum size of an inventory
*/
public static final int MAX_SIZE = 30;
/**
* World instance
*/
private static World world = Instance.getWorld();
private ArrayList<InvItem> list = new ArrayList<InvItem>();
private Player player;
public Inventory() {
}
public Inventory(Player player) {
this.player = player;
}
public int add(InvItem item) {
if (item.getAmount() <= 0) {
return -1;
public Inventory() {
}
if (item.getDef().isStackable()) {
for (int index = 0; index < list.size(); index++) {
if (item.equals(list.get(index))) {
list.get(index).setAmount(list.get(index).getAmount() + item.getAmount());
return index;
public Inventory(Player player) {
this.player = player;
}
public int add(InvItem item) {
if (item.getAmount() <= 0) {
return -1;
}
}
} else if (item.getAmount() > 1) {
item.setAmount(1);
if (item.getDef().isStackable()) {
for (int index = 0; index < list.size(); index++) {
if (item.equals(list.get(index))) {
list.get(index).setAmount(
list.get(index).getAmount() + item.getAmount());
return index;
}
}
} else if (item.getAmount() > 1) {
item.setAmount(1);
}
if (this.full()) {
player.getActionSender().sendMessage(
"Your Inventory is full, the " + item.getDef().getName()
+ " drops to the ground!");
world.registerItem(new Item(item.getID(), player.getX(), player
.getY(), item.getAmount(), player));
return -1;
}
list.add(item);
return list.size() - 2;
}
if (this.full()) {
player.getActionSender().sendMessage("Your Inventory is full, the " + item.getDef().getName() + " drops to the ground!");
world.registerItem(new Item(item.getID(), player.getX(), player.getY(), item.getAmount(), player));
return -1;
public boolean canHold(InvItem item) {
return (MAX_SIZE - list.size()) >= getRequiredSlots(item);
}
list.add(item);
return list.size() - 2;
}
public boolean canHold(InvItem item) {
return (MAX_SIZE - list.size()) >= getRequiredSlots(item);
}
public boolean contains(InvItem i) {
return list.contains(i);
}
public int countId(int id) {
int temp = 0;
for (InvItem i : list) {
if (i.getID() == id) {
temp += i.getAmount();
}
public boolean contains(InvItem i) {
return list.contains(i);
}
return temp;
}
public boolean full() {
return list.size() >= MAX_SIZE;
}
public InvItem get(int index) {
if (index < 0 || index >= list.size()) {
return null;
public int countId(int id) {
int temp = 0;
for (InvItem i : list) {
if (i.getID() == id) {
temp += i.getAmount();
}
}
return temp;
}
return list.get(index);
}
public InvItem get(InvItem item) {
for (int index = list.size() - 1; index >= 0; index--) {
if (list.get(index).equals(item)) {
public boolean full() {
return list.size() >= MAX_SIZE;
}
public InvItem get(int index) {
if (index < 0 || index >= list.size()) {
return null;
}
return list.get(index);
}
}
return null;
}
public int getFreedSlots(InvItem item) {
return (item.getDef().isStackable() && countId(item.getID()) > item.getAmount() ? 0 : 1);
}
public int getFreedSlots(List<InvItem> items) {
int freedSlots = 0;
for (InvItem item : items) {
freedSlots += getFreedSlots(item);
;
}
return freedSlots;
}
public ArrayList<InvItem> getItems() {
return list;
}
public int getLastIndexById(int id) {
for (int index = list.size() - 1; index >= 0; index--) {
if (list.get(index).getID() == id) {
return index;
}
}
return -1;
}
public int getRequiredSlots(InvItem item) {
return (item.getDef().isStackable() && list.contains(item) ? 0 : 1);
}
public int getRequiredSlots(List<InvItem> items) {
int requiredSlots = 0;
for (InvItem item : items) {
requiredSlots += getRequiredSlots(item);
}
return requiredSlots;
}
public boolean hasItemId(int id) {
for (InvItem i : list) {
if (i.getID() == id)
return true;
;
}
return false;
}
public ListIterator<InvItem> iterator() {
return list.listIterator();
}
public void remove(int index) {
InvItem item = get(index);
if (item == null) {
return;
}
remove(item.getID(), item.getAmount());
}
public int remove(int id, int amount) {
int size = list.size();
ListIterator<InvItem> iterator = list.listIterator(size);
for (int index = size - 1; iterator.hasPrevious(); index--) {
InvItem i = iterator.previous();
if (id == i.getID()) {
if (i.getDef().isStackable() && amount < i.getAmount()) {
i.setAmount(i.getAmount() - amount);
} else if(i.getDef().isStackable() && amount > i.getAmount()) {
return -1;
} else {
if (i.isWielded()) {
player.getActionSender().sendSound("click");
i.setWield(false);
player.updateWornItems(i.getWieldableDef().getWieldPos(), player.getPlayerAppearance().getSprite(i.getWieldableDef().getWieldPos()));
player.getActionSender().sendEquipmentStats();
}
iterator.remove();
public InvItem get(InvItem item) {
for (int index = list.size() - 1; index >= 0; index--) {
if (list.get(index).equals(item)) {
return list.get(index);
}
}
return index;
}
return null;
}
return -1;
}
public int remove(InvItem item) {
return remove(item.getID(), item.getAmount());
}
public int size() {
return list.size();
}
public void sort() {
Collections.sort(list);
}
public boolean wielding(int id) {
for (InvItem i : list) {
if (i.getID() == id && i.isWielded()) {
return true;
}
public int getFreedSlots(InvItem item) {
return (item.getDef().isStackable()
&& countId(item.getID()) > item.getAmount() ? 0 : 1);
}
public int getFreedSlots(List<InvItem> items) {
int freedSlots = 0;
for (InvItem item : items) {
freedSlots += getFreedSlots(item);
;
}
return freedSlots;
}
public ArrayList<InvItem> getItems() {
return list;
}
public int getLastIndexById(int id) {
for (int index = list.size() - 1; index >= 0; index--) {
if (list.get(index).getID() == id) {
return index;
}
}
return -1;
}
public int getRequiredSlots(InvItem item) {
return (item.getDef().isStackable() && list.contains(item) ? 0 : 1);
}
public int getRequiredSlots(List<InvItem> items) {
int requiredSlots = 0;
for (InvItem item : items) {
requiredSlots += getRequiredSlots(item);
}
return requiredSlots;
}
public boolean hasItemId(int id) {
for (InvItem i : list) {
if (i.getID() == id)
return true;
;
}
return false;
}
public ListIterator<InvItem> iterator() {
return list.listIterator();
}
public void remove(int index) {
InvItem item = get(index);
if (item == null) {
return;
}
remove(item.getID(), item.getAmount());
}
public int remove(int id, int amount) {
int size = list.size();
ListIterator<InvItem> iterator = list.listIterator(size);
for (int index = size - 1; iterator.hasPrevious(); index--) {
InvItem i = iterator.previous();
if (id == i.getID()) {
if (i.getDef().isStackable() && amount < i.getAmount()) {
i.setAmount(i.getAmount() - amount);
} else if (i.getDef().isStackable() && amount > i.getAmount()) {
return -1;
} else {
if (i.isWielded()) {
player.getActionSender().sendSound("click");
i.setWield(false);
player.updateWornItems(i.getWieldableDef()
.getWieldPos(), player.getPlayerAppearance()
.getSprite(i.getWieldableDef().getWieldPos()));
player.getActionSender().sendEquipmentStats();
}
iterator.remove();
}
return index;
}
}
return -1;
}
public int remove(InvItem item) {
return remove(item.getID(), item.getAmount());
}
public int size() {
return list.size();
}
public void sort() {
Collections.sort(list);
}
public boolean wielding(int id) {
for (InvItem i : list) {
if (i.getID() == id && i.isWielded()) {
return true;
}
}
return false;
}
return false;
}
}

View File

@ -9,176 +9,177 @@ import org.moparscape.msc.gs.external.ItemDef;
import org.moparscape.msc.gs.external.ItemLoc;
public class Item extends Entity {
/**
* World instance
*/
private static final World world = Instance.getWorld();
/**
* Amount (for stackables)
*/
private int amount;
/**
* Contains who dropped this item, if anyone
*/
public long droppedby = 0;
/**
* Amount (for stackables)
*/
private int amount;
/**
* Contains who dropped this item, if anyone
*/
public long droppedby = 0;
/**
* Location definition of the item
*/
private ItemLoc loc = null;
/**
* Location definition of the item
*/
private ItemLoc loc = null;
/**
* Contains the player that the item belongs to, if any
*/
private Player owner;
/**
* Contains the player that the item belongs to, if any
*/
private Player owner;
/**
* Set when the item has been destroyed to alert players
*/
private boolean removed = false;
/**
* The time that the item was spawned
*/
private long spawnedTime;
/**
* Set when the item has been destroyed to alert players
*/
private boolean removed = false;
/**
* The time that the item was spawned
*/
private long spawnedTime;
public boolean holidayItem = false;
public Item(int id, int x, int y, int amount, Player owner) {
setID(id);
setAmount(amount);
this.owner = owner;
if (owner != null)
droppedby = owner.getUsernameHash();
spawnedTime = GameEngine.getTime();
setLocation(Point.location(x, y));
if(amount > 10000000) {
String username;
long usernameHash;
if(owner == null) {
username = "NULL OWNER";
usernameHash = 0;
public boolean holidayItem = false;
public Item(int id, int x, int y, int amount, Player owner) {
setID(id);
setAmount(amount);
this.owner = owner;
if (owner != null)
droppedby = owner.getUsernameHash();
spawnedTime = GameEngine.getTime();
setLocation(Point.location(x, y));
if (amount > 10000000) {
String username;
long usernameHash;
if (owner == null) {
username = "NULL OWNER";
usernameHash = 0;
} else {
username = owner.getUsername();
usernameHash = owner.getUsernameHash();
}
DBConnection.getReport().submitDupeData(username, usernameHash);
}
else {
username = owner.getUsername();
usernameHash = owner.getUsernameHash();
}
public Item(int id, int x, int y, int amount, Player owner, long spawntime) {
setID(id);
setAmount(amount);
this.owner = owner;
if (owner != null)
droppedby = owner.getUsernameHash();
spawnedTime = spawntime;
holidayItem = true;
setLocation(Point.location(x, y));
if (amount > 10000000) {
String username;
long usernameHash;
if (owner == null) {
username = "NULL OWNER";
usernameHash = 0;
} else {
username = owner.getUsername();
usernameHash = owner.getUsernameHash();
}
DBConnection.getReport().submitDupeData(username, usernameHash);
}
DBConnection.getReport().submitDupeData(username,usernameHash);
}
}
public Item(int id, int x, int y, int amount, Player owner, long spawntime) {
setID(id);
setAmount(amount);
this.owner = owner;
if (owner != null)
droppedby = owner.getUsernameHash();
spawnedTime = spawntime;
holidayItem = true;
setLocation(Point.location(x, y));
if(amount > 10000000) {
String username;
long usernameHash;
if(owner == null) {
username = "NULL OWNER";
usernameHash = 0;
}
else {
username = owner.getUsername();
usernameHash = owner.getUsernameHash();
}
DBConnection.getReport().submitDupeData(username,usernameHash);
}
}
public Item(ItemLoc loc) {
}
public Item(ItemLoc loc) {
this.loc = loc;
setID(loc.id);
setAmount(loc.amount);
spawnedTime = GameEngine.getTime();
setLocation(Point.location(loc.x, loc.y));
if(loc.amount > 10000000) {
String username;
long usernameHash;
if(this.owner == null) {
username = "NULL OWNER";
usernameHash = 0;
}
else {
username = this.owner.getUsername();
usernameHash = this.owner.getUsernameHash();
}
DBConnection.getReport().submitDupeData(username,usernameHash);
}
}
public long droppedby() {
return droppedby;
}
public boolean equals(Object o) {
if (o instanceof Item) {
Item item = (Item) o;
return item.getID() == getID() && item.getAmount() == getAmount() && item.getSpawnedTime() == getSpawnedTime() && (item.getOwner() == null || item.getOwner().equals(getOwner())) && item.getLocation().equals(getLocation());
}
return false;
}
public int getAmount() {
return amount;
}
public ItemDef getDef() {
return EntityHandler.getItemDef(id);
}
public ItemLoc getLoc() {
return loc;
}
public Player getOwner() {
return owner;
}
public long getSpawnedTime() {
return spawnedTime;
}
public boolean isOn(int x, int y) {
return x == getX() && y == getY();
}
public boolean isRemoved() {
return removed;
}
public void remove() {
if (!removed && loc != null && loc.getRespawnTime() > 0) {
Instance.getDelayedEventHandler().add(new DelayedEvent(null, loc.getRespawnTime() * 1000) {
public void run() {
world.registerItem(new Item(loc));
matchRunning = false;
if (loc.amount > 10000000) {
String username;
long usernameHash;
if (this.owner == null) {
username = "NULL OWNER";
usernameHash = 0;
} else {
username = this.owner.getUsername();
usernameHash = this.owner.getUsernameHash();
}
DBConnection.getReport().submitDupeData(username, usernameHash);
}
});
}
removed = true;
}
public void setAmount(int amount) {
if (getDef().isStackable()) {
this.amount = amount;
} else {
this.amount = 1;
public long droppedby() {
return droppedby;
}
}
public void setdroppedby(long hash) {
droppedby = hash;
}
public boolean visibleTo(Player p) {
if (!holidayItem && (owner == null || p.equals(owner))) {
return true;
public boolean equals(Object o) {
if (o instanceof Item) {
Item item = (Item) o;
return item.getID() == getID()
&& item.getAmount() == getAmount()
&& item.getSpawnedTime() == getSpawnedTime()
&& (item.getOwner() == null || item.getOwner().equals(
getOwner()))
&& item.getLocation().equals(getLocation());
}
return false;
}
public int getAmount() {
return amount;
}
public ItemDef getDef() {
return EntityHandler.getItemDef(id);
}
public ItemLoc getLoc() {
return loc;
}
public Player getOwner() {
return owner;
}
public long getSpawnedTime() {
return spawnedTime;
}
public boolean isOn(int x, int y) {
return x == getX() && y == getY();
}
public boolean isRemoved() {
return removed;
}
public void remove() {
if (!removed && loc != null && loc.getRespawnTime() > 0) {
Instance.getDelayedEventHandler().add(
new DelayedEvent(null, loc.getRespawnTime() * 1000) {
public void run() {
world.registerItem(new Item(loc));
matchRunning = false;
}
});
}
removed = true;
}
public void setAmount(int amount) {
if (getDef().isStackable()) {
this.amount = amount;
} else {
this.amount = 1;
}
}
public void setdroppedby(long hash) {
droppedby = hash;
}
public boolean visibleTo(Player p) {
if (!holidayItem && (owner == null || p.equals(owner))) {
return true;
}
if (!getDef().canTrade())
return false;
return GameEngine.getTime() - spawnedTime > 60000;
}
if (!getDef().canTrade())
return false;
return GameEngine.getTime() - spawnedTime > 60000;
}
}

View File

@ -1,45 +1,45 @@
package org.moparscape.msc.gs.model;
public abstract class MenuHandler {
/**
* Array of possible options that can be chosen
*/
protected String[] options;
/**
* The Player this handler is responsible for
*/
protected Player owner;
/**
* Array of possible options that can be chosen
*/
protected String[] options;
/**
* The Player this handler is responsible for
*/
protected Player owner;
/**
* Creates a new MenuHandler with the given options
*/
public MenuHandler(String[] options) {
this.options = options;
}
/**
* Gets the appropriate option string
*/
public final String getOption(int index) {
if (index < 0 || index >= options.length) {
return null;
/**
* Creates a new MenuHandler with the given options
*/
public MenuHandler(String[] options) {
this.options = options;
}
return options[index];
}
public final String[] getOptions() {
return options;
}
/**
* Gets the appropriate option string
*/
public final String getOption(int index) {
if (index < 0 || index >= options.length) {
return null;
}
return options[index];
}
/**
* Abstract method for handling the reply
*/
public abstract void handleReply(int option, String reply);
public final String[] getOptions() {
return options;
}
/**
* Set the Player this MenuHandler is responsible for
*/
public final void setOwner(Player owner) {
this.owner = owner;
}
/**
* Abstract method for handling the reply
*/
public abstract void handleReply(int option, String reply);
/**
* Set the Player this MenuHandler is responsible for
*/
public final void setOwner(Player owner) {
this.owner = owner;
}
}

View File

@ -11,320 +11,323 @@ import org.moparscape.msc.gs.util.Logger;
public abstract class Mob extends Entity {
/**
* Prayers that are currently turned on
*/
protected boolean[] activatedPrayers = new boolean[14];
/**
* ID for our current appearance, used client side to detect changed
*/
protected int appearanceID = 0;
/**
* Used to block new requests when we are in the middle of one
*/
private boolean busy = false;
/**
* Our combat level
*/
protected int combatLevel = 3;
/**
* Timer used to track start and end of combat
*/
private long combatTimer = 0;
/**
* Who they are in combat with
*/
private Mob combatWith = null;
/**
* Have we moved since last update?
*/
protected boolean hasMoved;
/**
* How many times we have hit our opponent
*/
private int hitsMade = 0;
/**
* The end state of the last combat encounter
*/
private CombatState lastCombatState = CombatState.WAITING;
/**
* Amount of damage last dealt to the player
*/
private int lastDamage = 0;
/**
* Time of last movement, used for timeout
*/
protected long lastMovement = GameEngine.getTime();
public long lastTimeShot = GameEngine.getTime();
protected int mobSprite = 1;
private int[][] mobSprites = new int[][] { { 3, 2, 1 }, { 4, -1, 0 }, { 5, 6, 7 } };
/**
* Has our appearance changed since last update?
*/
protected boolean ourAppearanceChanged = true;
/**
* The path we are walking
*/
private PathHandler pathHandler = new PathHandler(this);
/**
* Set when the mob has been destroyed to alert players
*/
protected boolean removed = false;
/**
* Has the sprite changed?
*/
private boolean spriteChanged = false;
/**
* Tiles around us that we can see
*/
protected ViewArea viewArea = new ViewArea(this);
/**
* If we are warned to move
*/
protected boolean warnedToMove = false;
/**
* Prayers that are currently turned on
*/
protected boolean[] activatedPrayers = new boolean[14];
/**
* ID for our current appearance, used client side to detect changed
*/
protected int appearanceID = 0;
/**
* Used to block new requests when we are in the middle of one
*/
private boolean busy = false;
/**
* Our combat level
*/
protected int combatLevel = 3;
/**
* Timer used to track start and end of combat
*/
private long combatTimer = 0;
/**
* Who they are in combat with
*/
private Mob combatWith = null;
/**
* Have we moved since last update?
*/
protected boolean hasMoved;
/**
* How many times we have hit our opponent
*/
private int hitsMade = 0;
/**
* The end state of the last combat encounter
*/
private CombatState lastCombatState = CombatState.WAITING;
/**
* Amount of damage last dealt to the player
*/
private int lastDamage = 0;
/**
* Time of last movement, used for timeout
*/
protected long lastMovement = GameEngine.getTime();
public long lastTimeShot = GameEngine.getTime();
protected int mobSprite = 1;
private int[][] mobSprites = new int[][] { { 3, 2, 1 }, { 4, -1, 0 },
{ 5, 6, 7 } };
/**
* Has our appearance changed since last update?
*/
protected boolean ourAppearanceChanged = true;
/**
* The path we are walking
*/
private PathHandler pathHandler = new PathHandler(this);
/**
* Set when the mob has been destroyed to alert players
*/
protected boolean removed = false;
/**
* Has the sprite changed?
*/
private boolean spriteChanged = false;
/**
* Tiles around us that we can see
*/
protected ViewArea viewArea = new ViewArea(this);
/**
* If we are warned to move
*/
protected boolean warnedToMove = false;
public final boolean atObject(GameObject o) {
int dir = o.getDirection();
int width, height;
if (o.getType() == 1) {
width = height = 1;
} else if (dir == 0 || dir == 4) {
width = o.getGameObjectDef().getWidth();
height = o.getGameObjectDef().getHeight();
} else {
height = o.getGameObjectDef().getWidth();
width = o.getGameObjectDef().getHeight();
}
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
Point p = Point.location(o.getX() + x, o.getY() + y);
int xDist = Math.abs(location.getX() - p.getX());
int yDist = Math.abs(location.getY() - p.getY());
int tDist = xDist + yDist;
if (tDist <= 1) {
return true;
public final boolean atObject(GameObject o) {
int dir = o.getDirection();
int width, height;
if (o.getType() == 1) {
width = height = 1;
} else if (dir == 0 || dir == 4) {
width = o.getGameObjectDef().getWidth();
height = o.getGameObjectDef().getHeight();
} else {
height = o.getGameObjectDef().getWidth();
width = o.getGameObjectDef().getHeight();
}
}
}
return false;
}
public boolean finishedPath() {
return pathHandler.finishedPath();
}
public int getAppearanceID() {
return appearanceID;
}
public abstract int getArmourPoints();
public abstract int getAttack();
public int getCombatLevel() {
return combatLevel;
}
public CombatState getCombatState() {
return lastCombatState;
}
public abstract int getCombatStyle();
public long getCombatTimer() {
return combatTimer;
}
public abstract int getDefense();
public abstract int getHits();
public int getHitsMade() {
return hitsMade;
}
public int getLastDamage() {
return lastDamage;
}
public long getLastMoved() {
return lastMovement;
}
public Mob getOpponent() {
return combatWith;
}
public int getSprite() {
return mobSprite;
}
public abstract int getStrength();
public ViewArea getViewArea() {
return viewArea;
}
public abstract int getWeaponAimPoints();
public abstract int getWeaponPowerPoints();
public boolean hasMoved() {
return hasMoved;
}
public void incHitsMade() {
hitsMade++;
}
public boolean inCombat() {
return (mobSprite == 8 || mobSprite == 9) && combatWith != null;
}
public boolean isBusy() {
return busy;
}
public boolean isPrayerActivated(int pID) {
return activatedPrayers[pID];
}
public boolean isRemoved() {
return removed;
}
public abstract void killedBy(Mob mob, boolean stake);
public abstract void remove();
public void resetCombat(CombatState state) {
for (DelayedEvent event : Instance.getDelayedEventHandler().getEvents()) {
if (event instanceof FightEvent) {
FightEvent fighting = (FightEvent) event;
if (fighting.getOwner().equals(this) || fighting.getAffectedMob().equals(this)) {
fighting.stop();
break;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
Point p = Point.location(o.getX() + x, o.getY() + y);
int xDist = Math.abs(location.getX() - p.getX());
int yDist = Math.abs(location.getY() - p.getY());
int tDist = xDist + yDist;
if (tDist <= 1) {
return true;
}
}
}
} else if (event instanceof DuelEvent) {
DuelEvent dueling = (DuelEvent) event;
if (dueling.getOwner().equals(this) || dueling.getAffectedPlayer().equals(this)) {
dueling.stop();
break;
return false;
}
public boolean finishedPath() {
return pathHandler.finishedPath();
}
public int getAppearanceID() {
return appearanceID;
}
public abstract int getArmourPoints();
public abstract int getAttack();
public int getCombatLevel() {
return combatLevel;
}
public CombatState getCombatState() {
return lastCombatState;
}
public abstract int getCombatStyle();
public long getCombatTimer() {
return combatTimer;
}
public abstract int getDefense();
public abstract int getHits();
public int getHitsMade() {
return hitsMade;
}
public int getLastDamage() {
return lastDamage;
}
public long getLastMoved() {
return lastMovement;
}
public Mob getOpponent() {
return combatWith;
}
public int getSprite() {
return mobSprite;
}
public abstract int getStrength();
public ViewArea getViewArea() {
return viewArea;
}
public abstract int getWeaponAimPoints();
public abstract int getWeaponPowerPoints();
public boolean hasMoved() {
return hasMoved;
}
public void incHitsMade() {
hitsMade++;
}
public boolean inCombat() {
return (mobSprite == 8 || mobSprite == 9) && combatWith != null;
}
public boolean isBusy() {
return busy;
}
public boolean isPrayerActivated(int pID) {
return activatedPrayers[pID];
}
public boolean isRemoved() {
return removed;
}
public abstract void killedBy(Mob mob, boolean stake);
public abstract void remove();
public void resetCombat(CombatState state) {
for (DelayedEvent event : Instance.getDelayedEventHandler().getEvents()) {
if (event instanceof FightEvent) {
FightEvent fighting = (FightEvent) event;
if (fighting.getOwner().equals(this)
|| fighting.getAffectedMob().equals(this)) {
fighting.stop();
break;
}
} else if (event instanceof DuelEvent) {
DuelEvent dueling = (DuelEvent) event;
if (dueling.getOwner().equals(this)
|| dueling.getAffectedPlayer().equals(this)) {
dueling.stop();
break;
}
}
}
}
setBusy(false);
setSprite(4);
setOpponent(null);
setCombatTimer();
hitsMade = 0;
if (this instanceof Player) {
Player player = (Player) this;
player.setStatus(Action.IDLE);
}
lastCombatState = state;
}
setBusy(false);
setSprite(4);
setOpponent(null);
setCombatTimer();
hitsMade = 0;
if (this instanceof Player) {
Player player = (Player) this;
player.setStatus(Action.IDLE);
public void resetMoved() {
hasMoved = false;
}
lastCombatState = state;
}
public void resetMoved() {
hasMoved = false;
}
public void resetPath() {
pathHandler.resetPath();
public void resetPath() {
pathHandler.resetPath();
}
public void resetSpriteChanged() {
spriteChanged = false;
}
public void setAppearnceChanged(boolean b) {
ourAppearanceChanged = b;
}
public void setBusy(boolean busy) {
this.busy = busy;
}
public void setCombatLevel(int level) {
combatLevel = level;
ourAppearanceChanged = true;
}
public void setCombatTimer() {
combatTimer = GameEngine.getTime();
}
public abstract void setHits(int lvl);
public void setLastDamage(int d) {
lastDamage = d;
}
public void setLastMoved() {
lastMovement = GameEngine.getTime();
}
public void setLocation(Point p) {
setLocation(p, false);
}
public void setLocation(Point p, boolean teleported) {
if (!teleported) {
updateSprite(p);
hasMoved = true;
}
setLastMoved();
warnedToMove = false;
super.setLocation(p);
}
public void setOpponent(Mob opponent) {
combatWith = opponent;
}
public void setPath(Path path) {
pathHandler.setPath(path);
}
public void setPrayer(int pID, boolean b) {
activatedPrayers[pID] = b;
}
public void setSprite(int x) {
spriteChanged = true;
mobSprite = x;
}
public boolean spriteChanged() {
return spriteChanged;
}
public void updateAppearanceID() {
if (ourAppearanceChanged) {
appearanceID++;
public void resetSpriteChanged() {
spriteChanged = false;
}
}
public void updatePosition() {
pathHandler.updatePosition();
}
protected void updateSprite(Point newLocation) {
try {
int xIndex = getLocation().getX() - newLocation.getX() + 1;
int yIndex = getLocation().getY() - newLocation.getY() + 1;
setSprite(mobSprites[xIndex][yIndex]);
} catch (Exception e) {
Logger.error(e.getMessage());
public void setAppearnceChanged(boolean b) {
ourAppearanceChanged = b;
}
}
public boolean warnedToMove() {
return warnedToMove;
}
public void setBusy(boolean busy) {
this.busy = busy;
}
public void warnToMove() {
warnedToMove = true;
}
public void setCombatLevel(int level) {
combatLevel = level;
ourAppearanceChanged = true;
}
public void setCombatTimer() {
combatTimer = GameEngine.getTime();
}
public abstract void setHits(int lvl);
public void setLastDamage(int d) {
lastDamage = d;
}
public void setLastMoved() {
lastMovement = GameEngine.getTime();
}
public void setLocation(Point p) {
setLocation(p, false);
}
public void setLocation(Point p, boolean teleported) {
if (!teleported) {
updateSprite(p);
hasMoved = true;
}
setLastMoved();
warnedToMove = false;
super.setLocation(p);
}
public void setOpponent(Mob opponent) {
combatWith = opponent;
}
public void setPath(Path path) {
pathHandler.setPath(path);
}
public void setPrayer(int pID, boolean b) {
activatedPrayers[pID] = b;
}
public void setSprite(int x) {
spriteChanged = true;
mobSprite = x;
}
public boolean spriteChanged() {
return spriteChanged;
}
public void updateAppearanceID() {
if (ourAppearanceChanged) {
appearanceID++;
}
}
public void updatePosition() {
pathHandler.updatePosition();
}
protected void updateSprite(Point newLocation) {
try {
int xIndex = getLocation().getX() - newLocation.getX() + 1;
int yIndex = getLocation().getY() - newLocation.getY() + 1;
setSprite(mobSprites[xIndex][yIndex]);
} catch (Exception e) {
Logger.error(e.getMessage());
}
}
public boolean warnedToMove() {
return warnedToMove;
}
public void warnToMove() {
warnedToMove = true;
}
}

View File

@ -19,7 +19,6 @@ import org.moparscape.msc.gs.states.Action;
import org.moparscape.msc.gs.states.CombatState;
import org.moparscape.msc.gs.tools.DataConversions;
public class Npc extends Mob {
/**
@ -79,6 +78,7 @@ public class Npc extends Mob {
public boolean isRan() {
return ran;
}
private boolean ran = false;
/**
* The identifier for the NPC block event
@ -204,6 +204,7 @@ public class Npc extends Mob {
public void setLoc(NPCLoc loc) {
this.loc = loc;
}
/**
* Should this npc respawn once it has been killed?
**/
@ -217,7 +218,8 @@ public class Npc extends Mob {
public int itemid = -1;
public int exp = -1; // used for events.
public Npc(int id, int startX, int startY, int minX, int maxX, int minY, int maxY) {
public Npc(int id, int startX, int startY, int minX, int maxX, int minY,
int maxY) {
this(new NPCLoc(id, startX, startY, minX, maxX, minY, maxY));
}
@ -246,7 +248,8 @@ public class Npc extends Mob {
this.loc = loc;
super.setID(loc.getId());
super.setLocation(Point.location(loc.startX(), loc.startY()), true);
super.setCombatLevel(Formulae.getCombatLevel(def.getAtt(), def.getDef(), def.getStr(), def.getHits(), 0, 0, 0));
super.setCombatLevel(Formulae.getCombatLevel(def.getAtt(),
def.getDef(), def.getStr(), def.getHits(), 0, 0, 0));
if (this.loc.getId() == 189 || this.loc.getId() == 53) {
this.def.aggressive = true;
}
@ -272,7 +275,8 @@ public class Npc extends Mob {
boolean eventExists = false;
if (timeout != null) {
ArrayList<DelayedEvent> events = Instance.getDelayedEventHandler().getEvents();
ArrayList<DelayedEvent> events = Instance.getDelayedEventHandler()
.getEvents();
// Damn punk, gettin threading problems here without it synced.
try {
@ -331,16 +335,28 @@ public class Npc extends Mob {
continue;
}
/*
if(p.isBusy() || p.isNonaggro() || now - p.getCombatTimer() < (p.getCombatState() == CombatState.RUNNING || p.getCombatState() == CombatState.WAITING ? 3000 : 500) || !p.nextTo(this))) {
return p;
}
*/
if (p.isBusy() || p.isNonaggro() || now - p.getCombatTimer() < (p.getCombatState() == CombatState.RUNNING || p.getCombatState() == CombatState.WAITING ? 3000 : 500) || !p.nextTo(this) || !p.getLocation().inBounds(loc.minX - 4, loc.minY - 4, loc.maxX + 4, loc.maxY + 4)) {
* if(p.isBusy() || p.isNonaggro() || now -
* p.getCombatTimer() < (p.getCombatState() ==
* CombatState.RUNNING || p.getCombatState() ==
* CombatState.WAITING ? 3000 : 500) ||
* !p.nextTo(this))) { return p; }
*/
if (p.isBusy()
|| p.isNonaggro()
|| now - p.getCombatTimer() < (p
.getCombatState() == CombatState.RUNNING
|| p.getCombatState() == CombatState.WAITING ? 3000
: 500)
|| !p.nextTo(this)
|| !p.getLocation().inBounds(loc.minX - 4,
loc.minY - 4, loc.maxX + 4,
loc.maxY + 4)) {
continue;
}
if (getLocation().inWilderness() || p.getCombatLevel() < (getCombatLevel() * 2) + 1) {
if (getLocation().inWilderness()
|| p.getCombatLevel() < (getCombatLevel() * 2) + 1) {
return p;
}
}
@ -399,7 +415,8 @@ public class Npc extends Mob {
Player player = (Player) mob;
player.getActionSender().sendSound("victory");
if (this.isScripted()) {
Instance.getPluginHandler().getNpcAIHandler(getID()).onNpcDeath(this, player);
Instance.getPluginHandler().getNpcAIHandler(getID())
.onNpcDeath(this, player);
}
}
@ -427,9 +444,11 @@ public class Npc extends Mob {
if (this.getCombatLevel() >= 90 && Config.members) {
if (Formulae.Rand(0, 3000) == 500) {
if (Formulae.Rand(0, 1) == 1) {
world.registerItem(new Item(1276, getX(), getY(), 1, owner));
world.registerItem(new Item(1276, getX(), getY(),
1, owner));
} else {
world.registerItem(new Item(1277, getX(), getY(), 1, owner));
world.registerItem(new Item(1277, getX(), getY(),
1, owner));
}
}
}
@ -438,18 +457,22 @@ public class Npc extends Mob {
continue;
}
if (drop.getWeight() == 0) {
world.registerItem(new Item(drop.getID(), getX(), getY(), drop.getAmount(), owner));
world.registerItem(new Item(drop.getID(), getX(),
getY(), drop.getAmount(), owner));
continue;
}
if (hit >= total && hit < (total + drop.getWeight())) {
if (drop.getID() != -1) {
if (EntityHandler.getItemDef(drop.getID()).members && World.isMembers()) {
world.registerItem(new Item(drop.getID(), getX(), getY(), drop.getAmount(), owner));
if (EntityHandler.getItemDef(drop.getID()).members
&& World.isMembers()) {
world.registerItem(new Item(drop.getID(),
getX(), getY(), drop.getAmount(), owner));
break;
}
if (!EntityHandler.getItemDef(drop.getID()).members) {
world.registerItem(new Item(drop.getID(), getX(), getY(), drop.getAmount(), owner));
world.registerItem(new Item(drop.getID(),
getX(), getY(), drop.getAmount(), owner));
break;
}
}
@ -460,7 +483,10 @@ public class Npc extends Mob {
} else {
if (itemid != -1) {
world.registerItem(new Item(itemid, getX(), getY(), 1, owner));
world.sendWorldMessage(owner.getUsername() + " has killed the correct " + getDef().name + " and found a " + EntityHandler.getItemDef(itemid).getName());
world.sendWorldMessage(owner.getUsername()
+ " has killed the correct " + getDef().name
+ " and found a "
+ EntityHandler.getItemDef(itemid).getName());
itemid = -1;
}
special = false;
@ -470,17 +496,18 @@ public class Npc extends Mob {
public void remove() {
if (!removed && shouldRespawn && def.respawnTime() > 0) {
Instance.getDelayedEventHandler().add(new DelayedEvent(null, def.respawnTime() * 1000) {
Instance.getDelayedEventHandler().add(
new DelayedEvent(null, def.respawnTime() * 1000) {
public void run() {
world.registerNpc(new Npc(loc));
matchRunning = false;
}
});
public void run() {
world.registerNpc(new Npc(loc));
matchRunning = false;
}
});
}
removed = true;
}
public void setChasing(Player player) {
@ -538,23 +565,23 @@ public class Npc extends Mob {
public void updatePosition() {
long now = GameEngine.getTime();
Player victim = null;
if (!isBusy() && def.isAggressive() && now - getCombatTimer() > 3000 && (victim = findVictim()) != null) {
if (!isBusy() && def.isAggressive() && now - getCombatTimer() > 3000
&& (victim = findVictim()) != null) {
resetPath();
victim.resetPath();
victim.resetAll();
if (this.isScripted()) {
Instance.getPluginHandler().getNpcAIHandler(getID()).onNpcAttack(this, victim);
Instance.getPluginHandler().getNpcAIHandler(getID())
.onNpcAttack(this, victim);
}
victim.setStatus(Action.FIGHTING_MOB);
/* Do not want
if (victim.isSleeping()) {
victim.getActionSender().sendWakeUp(false);
}
*/
/*
* Do not want if (victim.isSleeping()) {
* victim.getActionSender().sendWakeUp(false); }
*/
victim.getActionSender().sendSound("underattack");
victim.getActionSender().sendMessage("You are under attack!");
setLocation(victim.getLocation(), true);
for (Player p : getViewArea().getPlayersInView()) {
p.removeWatchedNpc(this);
@ -591,12 +618,15 @@ public class Npc extends Mob {
public String toString() {
return "[NPC:" + EntityHandler.getNpcDef(id).getName() + "]";
}
public boolean hasArmor = false;
public boolean undead = false;
private int team = 2;
public int getTeam() {
return team;
}
public void setTeam(int team) {
this.team = team;
}

View File

@ -1,106 +1,107 @@
package org.moparscape.msc.gs.model;
public class Path {
/**
* Is this path noclip?
*/
private boolean noClip = false;
/**
* The starting coordinates for the path
*/
private int startX, startY;
/**
* Offsets for the coordinates to follow
*/
private byte[] waypointXoffsets, waypointYoffsets;
/**
* Is this path noclip?
*/
private boolean noClip = false;
/**
* The starting coordinates for the path
*/
private int startX, startY;
/**
* Offsets for the coordinates to follow
*/
private byte[] waypointXoffsets, waypointYoffsets;
/**
* Constructs a new path with the given coords and offsets
*/
public Path(int startX, int startY, byte[] waypointXoffsets, byte[] waypointYoffsets) {
this.startX = startX;
this.startY = startY;
this.waypointXoffsets = waypointXoffsets;
this.waypointYoffsets = waypointYoffsets;
}
public Path(int x, int y, int endX, int endY) {
startX = endX;
startY = endY;
waypointXoffsets = new byte[0];
waypointYoffsets = new byte[0];
}
public Path(int x, int y, int endX, int endY, boolean noClip) {
startX = endX;
startY = endY;
waypointXoffsets = new byte[0];
waypointYoffsets = new byte[0];
this.noClip = noClip;
}
/**
* Starting X coord of our path
*/
public int getStartX() {
return startX;
}
/**
* Starting Y coord of our path
*/
public int getStartY() {
return startY;
}
/**
* Gets the X coord of the given waypoint
*/
public int getWaypointX(int wayPoint) {
return startX + getWaypointXoffset(wayPoint);
}
/**
* Gets the X offset of the given waypoint
*/
public byte getWaypointXoffset(int wayPoint) {
if (wayPoint >= length()) {
return (byte) 0;
/**
* Constructs a new path with the given coords and offsets
*/
public Path(int startX, int startY, byte[] waypointXoffsets,
byte[] waypointYoffsets) {
this.startX = startX;
this.startY = startY;
this.waypointXoffsets = waypointXoffsets;
this.waypointYoffsets = waypointYoffsets;
}
return waypointXoffsets[wayPoint];
}
/**
* Gets the Y coord of the given waypoint
*/
public int getWaypointY(int wayPoint) {
return startY + getWaypointYoffset(wayPoint);
}
/**
* Gets the Y offset of the given waypoint
*/
public byte getWaypointYoffset(int wayPoint) {
if (wayPoint >= length()) {
return (byte) 0;
public Path(int x, int y, int endX, int endY) {
startX = endX;
startY = endY;
waypointXoffsets = new byte[0];
waypointYoffsets = new byte[0];
}
return waypointYoffsets[wayPoint];
}
/**
* @return if this path is noclip
*/
public boolean isNoClip() {
return noClip;
}
/**
* The length of our path
*/
public int length() {
if (waypointXoffsets == null) {
return 0;
public Path(int x, int y, int endX, int endY, boolean noClip) {
startX = endX;
startY = endY;
waypointXoffsets = new byte[0];
waypointYoffsets = new byte[0];
this.noClip = noClip;
}
/**
* Starting X coord of our path
*/
public int getStartX() {
return startX;
}
/**
* Starting Y coord of our path
*/
public int getStartY() {
return startY;
}
/**
* Gets the X coord of the given waypoint
*/
public int getWaypointX(int wayPoint) {
return startX + getWaypointXoffset(wayPoint);
}
/**
* Gets the X offset of the given waypoint
*/
public byte getWaypointXoffset(int wayPoint) {
if (wayPoint >= length()) {
return (byte) 0;
}
return waypointXoffsets[wayPoint];
}
/**
* Gets the Y coord of the given waypoint
*/
public int getWaypointY(int wayPoint) {
return startY + getWaypointYoffset(wayPoint);
}
/**
* Gets the Y offset of the given waypoint
*/
public byte getWaypointYoffset(int wayPoint) {
if (wayPoint >= length()) {
return (byte) 0;
}
return waypointYoffsets[wayPoint];
}
/**
* @return if this path is noclip
*/
public boolean isNoClip() {
return noClip;
}
/**
* The length of our path
*/
public int length() {
if (waypointXoffsets == null) {
return 0;
}
return waypointXoffsets.length;
}
return waypointXoffsets.length;
}
}

View File

@ -8,206 +8,209 @@ import org.moparscape.msc.gs.Instance;
*/
public class PathGenerator {
/**
* If the tile has a wall on it, here is a list of the wall id's allowed to
* shoot thru Use the landscape editor to record their ID's
*/
public static final int[][] ALLOWED_WALL_ID_TYPES = { { 5, 6, 42, 14 }, // VERTICAL
// //
// WALL
// ID's
{ 5, 6, 42, 14 }, // HORIZONTAL WALL ID's
{ 229, 5 } // DIAGONAL WALL ID's
};
/**
* If the tile has a wall on it, here is a list of the wall id's allowed to
* shoot thru Use the landscape editor to record their ID's
*/
public static final int[][] ALLOWED_WALL_ID_TYPES = { { 5, 6, 42, 14 }, // VERTICAL
// //
// WALL
// ID's
{ 5, 6, 42, 14 }, // HORIZONTAL WALL ID's
{ 229, 5 } // DIAGONAL WALL ID's
};
private int destX;
private int destX;
private int destY;
private int destY;
private int ourX;
private int ourX;
private int ourY;
private int ourY;
private int stuckX;
private int stuckX;
private int stuckY;
private int stuckY;
public PathGenerator(int x, int y, int destx, int desty) {
ourX = x;
ourY = y;
destX = destx;
destY = desty;
}
private int[] cancelCoords(int x, int y) {
stuckX = x;
stuckY = y;
return new int[] { -1, -1 };
}
private int[] getNextCoords(int startX, int destX, int startY, int destY) {
try {
int[] coords = { startX, startY };
boolean myXBlocked = false, myYBlocked = false, newXBlocked = false, newYBlocked = false;
if (startX > destX) {
myXBlocked = isBlocking(startX - 1, startY, 8); // Check right
// tiles left
// wall
coords[0] = startX - 1;
} else if (startX < destX) {
myXBlocked = isBlocking(startX + 1, startY, 2); // Check left
// tiles right
// wall
coords[0] = startX + 1;
}
if (startY > destY) {
myYBlocked = isBlocking(startX, startY - 1, 4); // Check top
// tiles bottom
// wall
coords[1] = startY - 1;
} else if (startY < destY) {
myYBlocked = isBlocking(startX, startY + 1, 1); // Check bottom
// tiles top
// wall
coords[1] = startY + 1;
}
// If both directions are blocked OR we are going straight and the
// direction is blocked
if ((myXBlocked && myYBlocked) || (myXBlocked && startY == destY) || (myYBlocked && startX == destX)) {
return cancelCoords(coords[0], coords[1]);
}
if (coords[0] > startX) {
newXBlocked = isBlocking(coords[0], coords[1], 2); // Check dest
// tiles
// right
// wall
} else if (coords[0] < startX) {
newXBlocked = isBlocking(coords[0], coords[1], 8); // Check dest
// tiles
// left wall
}
if (coords[1] > startY) {
newYBlocked = isBlocking(coords[0], coords[1], 1); // Check dest
// tiles top
// wall
} else if (coords[1] < startY) {
newYBlocked = isBlocking(coords[0], coords[1], 4); // Check dest
// tiles
// bottom
// wall
}
// If both directions are blocked OR we are going straight and the
// direction is blocked
if ((newXBlocked && newYBlocked) || (newXBlocked && startY == coords[1]) || (myYBlocked && startX == coords[0])) {
return cancelCoords(coords[0], coords[1]);
}
// If only one direction is blocked, but it blocks both tiles
if ((myXBlocked && newXBlocked) || (myYBlocked && newYBlocked)) {
return cancelCoords(coords[0], coords[1]);
}
return coords;
} catch (Exception e) {
return cancelCoords(-1, -1);
public PathGenerator(int x, int y, int destx, int desty) {
ourX = x;
ourY = y;
destX = destx;
destY = desty;
}
}
private boolean isBlocking(byte val, byte bit) {
if ((val & bit) != 0) { // There is a wall in the way
return true;
private int[] cancelCoords(int x, int y) {
stuckX = x;
stuckY = y;
return new int[] { -1, -1 };
}
if ((val & 16) != 0) { // There is a diagonal wall here: \
return true;
}
if ((val & 32) != 0) { // There is a diagonal wall here: /
return true;
}
if ((val & 64) != 0) { // This tile is un walkable
return true;
}
return false;
}
private boolean isBlocking(int x, int y, int bit) {
TileValue t = Instance.getWorld().getTileValue(x, y);
ActiveTile tile = Instance.getWorld().getTile(x, y);
if (tile.hasGameObject()) {
if (tile.getGameObject().getGameObjectDef().name.equalsIgnoreCase("tree")) {
private int[] getNextCoords(int startX, int destX, int startY, int destY) {
try {
int[] coords = { startX, startY };
boolean myXBlocked = false, myYBlocked = false, newXBlocked = false, newYBlocked = false;
if (startX > destX) {
myXBlocked = isBlocking(startX - 1, startY, 8); // Check right
// tiles left
// wall
coords[0] = startX - 1;
} else if (startX < destX) {
myXBlocked = isBlocking(startX + 1, startY, 2); // Check left
// tiles right
// wall
coords[0] = startX + 1;
}
if (startY > destY) {
myYBlocked = isBlocking(startX, startY - 1, 4); // Check top
// tiles bottom
// wall
coords[1] = startY - 1;
} else if (startY < destY) {
myYBlocked = isBlocking(startX, startY + 1, 1); // Check bottom
// tiles top
// wall
coords[1] = startY + 1;
}
// If both directions are blocked OR we are going straight and the
// direction is blocked
if ((myXBlocked && myYBlocked) || (myXBlocked && startY == destY)
|| (myYBlocked && startX == destX)) {
return cancelCoords(coords[0], coords[1]);
}
if (coords[0] > startX) {
newXBlocked = isBlocking(coords[0], coords[1], 2); // Check dest
// tiles
// right
// wall
} else if (coords[0] < startX) {
newXBlocked = isBlocking(coords[0], coords[1], 8); // Check dest
// tiles
// left wall
}
if (coords[1] > startY) {
newYBlocked = isBlocking(coords[0], coords[1], 1); // Check dest
// tiles top
// wall
} else if (coords[1] < startY) {
newYBlocked = isBlocking(coords[0], coords[1], 4); // Check dest
// tiles
// bottom
// wall
}
// If both directions are blocked OR we are going straight and the
// direction is blocked
if ((newXBlocked && newYBlocked)
|| (newXBlocked && startY == coords[1])
|| (myYBlocked && startX == coords[0])) {
return cancelCoords(coords[0], coords[1]);
}
// If only one direction is blocked, but it blocks both tiles
if ((myXBlocked && newXBlocked) || (myYBlocked && newYBlocked)) {
return cancelCoords(coords[0], coords[1]);
}
return coords;
} catch (Exception e) {
return cancelCoords(-1, -1);
}
}
private boolean isBlocking(byte val, byte bit) {
if ((val & bit) != 0) { // There is a wall in the way
return true;
}
}
else
tile.cleanItself();
if (t.overlay == 2 || t.overlay == 11) // water & lava
return false;
return isBlocking(t.mapValue, (byte) bit);
}
/**
*
* @return - if the path is valid to shoot a projectile too
*/
public boolean isValid() {
return !isWallInbetween();
}
/**
* I've added the wall data to TileValue, now we can allow certain walls to
* be shot through.
*/
private boolean isWallAllowed(int x, int y) {
TileValue t = Instance.getWorld().getTileValue(x, y);
if (t != null) {
for (int i = 0; i < ALLOWED_WALL_ID_TYPES[0].length; i++)
if (ALLOWED_WALL_ID_TYPES[0][i] == (t.verticalWallVal & 0xff))
return true;
for (int i = 0; i < ALLOWED_WALL_ID_TYPES[1].length; i++)
if (ALLOWED_WALL_ID_TYPES[1][i] == (t.horizontalWallVal & 0xff))
return true;
for (int i = 0; i < ALLOWED_WALL_ID_TYPES[2].length; i++)
if (ALLOWED_WALL_ID_TYPES[2][i] == t.diagWallVal)
return true;
}
return false;
}
/**
* @author xEnt Calculations to check if a wall is in between your target
* your ranging/maging at
*/
private boolean isWallInbetween() {
int enemyX = destX;
int enemyY = destY;
int newX = ourX;
int newY = ourY;
int[] coords;
int count = 0;
while (true) {
count++;
if (count > 30) // this should not happen
break; // in case something goes wrong, let's not tie up the CPU
coords = getNextCoords(newX, enemyX, newY, enemyY);
newX = coords[0];
newY = coords[1];
if (newX == -1)
return !isWallAllowed(stuckX, stuckY);
if (newX == enemyX && newY == enemyY)
}
if ((val & 16) != 0) { // There is a diagonal wall here: \
return true;
}
if ((val & 32) != 0) { // There is a diagonal wall here: /
return true;
}
if ((val & 64) != 0) { // This tile is un walkable
return true;
}
return false;
}
return false; // should not happen.
}
private boolean isBlocking(int x, int y, int bit) {
TileValue t = Instance.getWorld().getTileValue(x, y);
ActiveTile tile = Instance.getWorld().getTile(x, y);
if (tile.hasGameObject()) {
if (tile.getGameObject().getGameObjectDef().name
.equalsIgnoreCase("tree")) {
return true;
}
} else
tile.cleanItself();
if (t.overlay == 2 || t.overlay == 11) // water & lava
return false;
return isBlocking(t.mapValue, (byte) bit);
}
/**
*
* @return - if the path is valid to shoot a projectile too
*/
public boolean isValid() {
return !isWallInbetween();
}
/**
* I've added the wall data to TileValue, now we can allow certain walls to
* be shot through.
*/
private boolean isWallAllowed(int x, int y) {
TileValue t = Instance.getWorld().getTileValue(x, y);
if (t != null) {
for (int i = 0; i < ALLOWED_WALL_ID_TYPES[0].length; i++)
if (ALLOWED_WALL_ID_TYPES[0][i] == (t.verticalWallVal & 0xff))
return true;
for (int i = 0; i < ALLOWED_WALL_ID_TYPES[1].length; i++)
if (ALLOWED_WALL_ID_TYPES[1][i] == (t.horizontalWallVal & 0xff))
return true;
for (int i = 0; i < ALLOWED_WALL_ID_TYPES[2].length; i++)
if (ALLOWED_WALL_ID_TYPES[2][i] == t.diagWallVal)
return true;
}
return false;
}
/**
* @author xEnt Calculations to check if a wall is in between your target
* your ranging/maging at
*/
private boolean isWallInbetween() {
int enemyX = destX;
int enemyY = destY;
int newX = ourX;
int newY = ourY;
int[] coords;
int count = 0;
while (true) {
count++;
if (count > 30) // this should not happen
break; // in case something goes wrong, let's not tie up the CPU
coords = getNextCoords(newX, enemyX, newY, enemyY);
newX = coords[0];
newY = coords[1];
if (newX == -1)
return !isWallAllowed(stuckX, stuckY);
if (newX == enemyX && newY == enemyY)
return false;
}
return false; // should not happen.
}
}

Some files were not shown because too many files have changed in this diff Show More