Browse Source

Reformat and bonus code removal.

master
MagicBot 2 years ago
parent
commit
566522befb
  1. 393
      src/engine/ai/MobileFSM.java
  2. 121
      src/engine/ai/MobileFSMManager.java
  3. 954
      src/engine/ai/utilities/CombatUtilities.java
  4. 374
      src/engine/ai/utilities/MovementUtilities.java
  5. 1
      src/engine/ai/utilities/PowerUtilities.java

393
src/engine/ai/MobileFSM.java

@ -6,6 +6,7 @@
// Magicbane Emulator Project © 2013 - 2022 // Magicbane Emulator Project © 2013 - 2022
// www.magicbane.com // www.magicbane.com
package engine.ai; package engine.ai;
import engine.Enum; import engine.Enum;
import engine.Enum.DispatchChannel; import engine.Enum.DispatchChannel;
import engine.InterestManagement.WorldGrid; import engine.InterestManagement.WorldGrid;
@ -22,12 +23,15 @@ import engine.objects.*;
import engine.powers.ActionsBase; import engine.powers.ActionsBase;
import engine.powers.PowersBase; import engine.powers.PowersBase;
import engine.server.MBServerStatics; import engine.server.MBServerStatics;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
import static engine.math.FastMath.sqr; import static engine.math.FastMath.sqr;
public class MobileFSM { public class MobileFSM {
private static void AttackTarget(Mob mob, AbstractWorldObject target) { private static void AttackTarget(Mob mob, AbstractWorldObject target) {
if (mob == null) if (mob == null)
@ -42,11 +46,11 @@ public class MobileFSM {
case PlayerCharacter: case PlayerCharacter:
PlayerCharacter targetPlayer = (PlayerCharacter) target; PlayerCharacter targetPlayer = (PlayerCharacter) target;
if (canCast(mob)) { if (canCast(mob)) {
if (!MobCast(mob)) if (canCast(mob) && !MobCast(mob))
AttackPlayer(mob, targetPlayer); AttackPlayer(mob, targetPlayer);
} else { } else
AttackPlayer(mob, targetPlayer); AttackPlayer(mob, targetPlayer);
}
break; break;
case Building: case Building:
Building targetBuilding = (Building) target; Building targetBuilding = (Building) target;
@ -58,79 +62,117 @@ public class MobileFSM {
break; break;
} }
} }
public static void AttackPlayer(Mob mob, PlayerCharacter target) { public static void AttackPlayer(Mob mob, PlayerCharacter target) {
if (mob.getMobBase().getSeeInvis() < target.getHidden() || !target.isAlive()) { if (mob.getMobBase().getSeeInvis() < target.getHidden() || !target.isAlive()) {
mob.setCombatTarget(null); mob.setCombatTarget(null);
return; return;
} }
if (mob.BehaviourType.callsForHelp) if (mob.BehaviourType.callsForHelp)
MobCallForHelp(mob); MobCallForHelp(mob);
if (!MovementUtilities.inRangeDropAggro(mob, target)) { if (!MovementUtilities.inRangeDropAggro(mob, target)) {
mob.setCombatTarget(null); mob.setCombatTarget(null);
return; return;
} }
if (CombatUtilities.inRangeToAttack(mob,mob.getCombatTarget())) { if (CombatUtilities.inRangeToAttack(mob, mob.getCombatTarget())) {
//no weapons, default mob attack speed 3 seconds. //no weapons, default mob attack speed 3 seconds.
if (System.currentTimeMillis() < mob.getLastAttackTime()) if (System.currentTimeMillis() < mob.getLastAttackTime())
return; return;
// ranged mobs cant attack while running. skip until they finally stop. // ranged mobs cant attack while running. skip until they finally stop.
if (mob.isMoving()) if (mob.isMoving())
return; return;
// add timer for last attack. // add timer for last attack.
ItemBase mainHand = mob.getWeaponItemBase(true); ItemBase mainHand = mob.getWeaponItemBase(true);
ItemBase offHand = mob.getWeaponItemBase(false); ItemBase offHand = mob.getWeaponItemBase(false);
if (mainHand == null && offHand == null) { if (mainHand == null && offHand == null) {
CombatUtilities.combatCycle(mob, target, true, null); CombatUtilities.combatCycle(mob, target, true, null);
int delay = 3000; int delay = 3000;
if (mob.isSiege()) if (mob.isSiege())
delay = 11000; delay = 11000;
mob.setLastAttackTime(System.currentTimeMillis() + delay); mob.setLastAttackTime(System.currentTimeMillis() + delay);
} else if (mob.getWeaponItemBase(true) != null) { } else if (mob.getWeaponItemBase(true) != null) {
int delay = 3000; int delay = 3000;
if (mob.isSiege()) if (mob.isSiege())
delay = 11000; delay = 11000;
CombatUtilities.combatCycle(mob, target, true, mob.getWeaponItemBase(true)); CombatUtilities.combatCycle(mob, target, true, mob.getWeaponItemBase(true));
mob.setLastAttackTime(System.currentTimeMillis() + delay); mob.setLastAttackTime(System.currentTimeMillis() + delay);
} else if (mob.getWeaponItemBase(false) != null) { } else if (mob.getWeaponItemBase(false) != null) {
int attackDelay = 3000; int attackDelay = 3000;
if (mob.isSiege()) if (mob.isSiege())
attackDelay = 11000; attackDelay = 11000;
CombatUtilities.combatCycle(mob, target, false, mob.getWeaponItemBase(false)); CombatUtilities.combatCycle(mob, target, false, mob.getWeaponItemBase(false));
mob.setLastAttackTime(System.currentTimeMillis() + attackDelay); mob.setLastAttackTime(System.currentTimeMillis() + attackDelay);
} }
} }
} }
public static void AttackBuilding(Mob mob, Building target) { public static void AttackBuilding(Mob mob, Building target) {
if (target.getRank() == -1 || !target.isVulnerable() || BuildingManager.getBuildingFromCache(target.getObjectUUID()) == null) { if (target.getRank() == -1 || !target.isVulnerable() || BuildingManager.getBuildingFromCache(target.getObjectUUID()) == null) {
mob.setCombatTarget(null); mob.setCombatTarget(null);
return; return;
} }
City playercity = ZoneManager.getCityAtLocation(mob.getLoc()); City playercity = ZoneManager.getCityAtLocation(mob.getLoc());
if (playercity != null) if (playercity != null)
for (Mob guard : playercity.getParent().zoneMobSet) for (Mob guard : playercity.getParent().zoneMobSet)
if (guard.BehaviourType != null && guard.BehaviourType.ordinal() == Enum.MobBehaviourType.GuardCaptain.ordinal()) if (guard.BehaviourType != null && guard.BehaviourType.ordinal() == Enum.MobBehaviourType.GuardCaptain.ordinal())
if (guard.getCombatTarget() == null && !guard.getGuild().equals(mob.getGuild())) if (guard.getCombatTarget() == null && !guard.getGuild().equals(mob.getGuild()))
guard.setCombatTarget(mob); guard.setCombatTarget(mob);
if (mob.isSiege()) if (mob.isSiege())
MovementManager.sendRWSSMsg(mob); MovementManager.sendRWSSMsg(mob);
ItemBase mainHand = mob.getWeaponItemBase(true); ItemBase mainHand = mob.getWeaponItemBase(true);
ItemBase offHand = mob.getWeaponItemBase(false); ItemBase offHand = mob.getWeaponItemBase(false);
if (mainHand == null && offHand == null) { if (mainHand == null && offHand == null) {
CombatUtilities.combatCycle(mob, target, true, null); CombatUtilities.combatCycle(mob, target, true, null);
int delay = 3000; int delay = 3000;
if (mob.isSiege()) if (mob.isSiege())
delay = 15000; delay = 15000;
mob.setLastAttackTime(System.currentTimeMillis() + delay); mob.setLastAttackTime(System.currentTimeMillis() + delay);
} else if (mob.getWeaponItemBase(true) != null) { } else if (mob.getWeaponItemBase(true) != null) {
int attackDelay = 3000; int attackDelay = 3000;
if (mob.isSiege()) if (mob.isSiege())
attackDelay = 15000; attackDelay = 15000;
CombatUtilities.combatCycle(mob, target, true, mob.getWeaponItemBase(true)); CombatUtilities.combatCycle(mob, target, true, mob.getWeaponItemBase(true));
mob.setLastAttackTime(System.currentTimeMillis() + attackDelay); mob.setLastAttackTime(System.currentTimeMillis() + attackDelay);
} else if (mob.getWeaponItemBase(false) != null) { } else if (mob.getWeaponItemBase(false) != null) {
int attackDelay = 3000; int attackDelay = 3000;
if (mob.isSiege()) if (mob.isSiege())
attackDelay = 15000; attackDelay = 15000;
CombatUtilities.combatCycle(mob, target, false, mob.getWeaponItemBase(false)); CombatUtilities.combatCycle(mob, target, false, mob.getWeaponItemBase(false));
mob.setLastAttackTime(System.currentTimeMillis() + attackDelay); mob.setLastAttackTime(System.currentTimeMillis() + attackDelay);
} }
@ -140,67 +182,91 @@ public class MobileFSM {
DispatchMessage.dispatchMsgToInterestArea(mob, ppm, DispatchChannel.SECONDARY, MBServerStatics.CHARACTER_LOAD_RANGE, false, false); DispatchMessage.dispatchMsgToInterestArea(mob, ppm, DispatchChannel.SECONDARY, MBServerStatics.CHARACTER_LOAD_RANGE, false, false);
} }
} }
public static void AttackMob(Mob mob, Mob target) { public static void AttackMob(Mob mob, Mob target) {
if (mob.getRange() >= 30 && mob.isMoving()) if (mob.getRange() >= 30 && mob.isMoving())
return; return;
//no weapons, default mob attack speed 3 seconds. //no weapons, default mob attack speed 3 seconds.
ItemBase mainHand = mob.getWeaponItemBase(true); ItemBase mainHand = mob.getWeaponItemBase(true);
ItemBase offHand = mob.getWeaponItemBase(false); ItemBase offHand = mob.getWeaponItemBase(false);
if (mainHand == null && offHand == null) { if (mainHand == null && offHand == null) {
CombatUtilities.combatCycle(mob, target, true, null); CombatUtilities.combatCycle(mob, target, true, null);
int delay = 3000; int delay = 3000;
if (mob.isSiege()) if (mob.isSiege())
delay = 11000; delay = 11000;
mob.setLastAttackTime(System.currentTimeMillis() + delay); mob.setLastAttackTime(System.currentTimeMillis() + delay);
} else if (mob.getWeaponItemBase(true) != null) { } else if (mob.getWeaponItemBase(true) != null) {
int attackDelay = 3000; int attackDelay = 3000;
if (mob.isSiege()) if (mob.isSiege())
attackDelay = 11000; attackDelay = 11000;
CombatUtilities.combatCycle(mob, target, true, mob.getWeaponItemBase(true)); CombatUtilities.combatCycle(mob, target, true, mob.getWeaponItemBase(true));
mob.setLastAttackTime(System.currentTimeMillis() + attackDelay); mob.setLastAttackTime(System.currentTimeMillis() + attackDelay);
} else if (mob.getWeaponItemBase(false) != null) { } else if (mob.getWeaponItemBase(false) != null) {
int attackDelay = 3000; int attackDelay = 3000;
if (mob.isSiege()) if (mob.isSiege())
attackDelay = 11000; attackDelay = 11000;
CombatUtilities.combatCycle(mob, target, false, mob.getWeaponItemBase(false)); CombatUtilities.combatCycle(mob, target, false, mob.getWeaponItemBase(false));
mob.setLastAttackTime(System.currentTimeMillis() + attackDelay); mob.setLastAttackTime(System.currentTimeMillis() + attackDelay);
} }
} }
private static void Patrol(Mob mob) { private static void Patrol(Mob mob) {
//make sure mob is out of combat stance //make sure mob is out of combat stance
if(mob.stopPatrolTime == 0) { if (mob.stopPatrolTime == 0)
mob.stopPatrolTime = System.currentTimeMillis(); mob.stopPatrolTime = System.currentTimeMillis();
}
if(mob.isMoving() == true){ if (mob.isMoving() == true) {
mob.stopPatrolTime = System.currentTimeMillis(); mob.stopPatrolTime = System.currentTimeMillis();
return; return;
} }
if (mob.isCombat() && mob.getCombatTarget() == null) { if (mob.isCombat() && mob.getCombatTarget() == null) {
mob.setCombat(false); mob.setCombat(false);
UpdateStateMsg rwss = new UpdateStateMsg(); UpdateStateMsg rwss = new UpdateStateMsg();
rwss.setPlayer(mob); rwss.setPlayer(mob);
DispatchMessage.sendToAllInRange(mob, rwss); DispatchMessage.sendToAllInRange(mob, rwss);
} }
//early exit while waiting to patrol again
if (mob.stopPatrolTime + (MBServerStatics.AI_PATROL_DIVISOR * 1000) > System.currentTimeMillis()) if (mob.stopPatrolTime + (MBServerStatics.AI_PATROL_DIVISOR * 1000) > System.currentTimeMillis())
//early exit while waiting to patrol again
return; return;
//guard captains inherit barracks patrol points dynamically //guard captains inherit barracks patrol points dynamically
if (mob.BehaviourType.ordinal() == Enum.MobBehaviourType.GuardCaptain.ordinal()) { if (mob.BehaviourType.ordinal() == Enum.MobBehaviourType.GuardCaptain.ordinal()) {
Building barracks = mob.building; Building barracks = mob.building;
if (barracks != null && barracks.patrolPoints != null && !barracks.getPatrolPoints().isEmpty()) { if (barracks != null && barracks.patrolPoints != null && !barracks.getPatrolPoints().isEmpty()) {
mob.patrolPoints = barracks.patrolPoints; mob.patrolPoints = barracks.patrolPoints;
} else{ } else {
randomGuardPatrolPoint(mob); randomGuardPatrolPoint(mob);
return; return;
} }
} }
if (mob.lastPatrolPointIndex > mob.patrolPoints.size() - 1) {
mob.lastPatrolPointIndex = 0; if (mob.lastPatrolPointIndex > mob.patrolPoints.size() - 1)
} mob.lastPatrolPointIndex = 0;
mob.destination = mob.patrolPoints.get(mob.lastPatrolPointIndex); mob.destination = mob.patrolPoints.get(mob.lastPatrolPointIndex);
mob.lastPatrolPointIndex += 1; mob.lastPatrolPointIndex += 1;
MovementUtilities.aiMove(mob, mob.destination, true); MovementUtilities.aiMove(mob, mob.destination, true);
if(mob.BehaviourType.ordinal() == Enum.MobBehaviourType.GuardCaptain.ordinal()){
if (mob.BehaviourType.ordinal() == Enum.MobBehaviourType.GuardCaptain.ordinal()) {
for (Entry<Mob, Integer> minion : mob.siegeMinionMap.entrySet()) { for (Entry<Mob, Integer> minion : mob.siegeMinionMap.entrySet()) {
//make sure mob is out of combat stance //make sure mob is out of combat stance
if (minion.getKey().despawned == false) { if (minion.getKey().despawned == false) {
@ -215,117 +281,162 @@ public class MobileFSM {
minion.getKey().updateLocation(); minion.getKey().updateLocation();
Vector3fImmutable formationPatrolPoint = new Vector3fImmutable(mob.destination.x + minionOffset.x, mob.destination.y, mob.destination.z + minionOffset.z); Vector3fImmutable formationPatrolPoint = new Vector3fImmutable(mob.destination.x + minionOffset.x, mob.destination.y, mob.destination.z + minionOffset.z);
MovementUtilities.aiMove(minion.getKey(), formationPatrolPoint, true); MovementUtilities.aiMove(minion.getKey(), formationPatrolPoint, true);
MovementUtilities.moveToLocation(minion.getKey(),formationPatrolPoint,0); MovementUtilities.moveToLocation(minion.getKey(), formationPatrolPoint, 0);
} }
} }
} }
} }
} }
public static boolean canCast(Mob mob) { public static boolean canCast(Mob mob) {
// Performs validation to determine if a // Performs validation to determine if a
// mobile in the proper state to cast. // mobile in the proper state to cast.
if (mob == null) if (mob == null)
return false; return false;
if (mob.mobPowers.isEmpty()) if (mob.mobPowers.isEmpty())
return false; return false;
if(ThreadLocalRandom.current().nextInt(100) > 50)
if (ThreadLocalRandom.current().nextInt(100) > 50)
return false; return false;
if (mob.nextCastTime == 0) if (mob.nextCastTime == 0)
mob.nextCastTime = System.currentTimeMillis(); mob.nextCastTime = System.currentTimeMillis();
return mob.nextCastTime <= System.currentTimeMillis(); return mob.nextCastTime <= System.currentTimeMillis();
} }
public static boolean MobCast(Mob mob) { public static boolean MobCast(Mob mob) {
// Method picks a random spell from a mobile's list of powers // Method picks a random spell from a mobile's list of powers
// and casts it on the current target (or itself). Validation // and casts it on the current target (or itself). Validation
// (including empty lists) is done previously within canCast(); // (including empty lists) is done previously within canCast();
ArrayList<Integer> powerTokens; ArrayList<Integer> powerTokens;
ArrayList<Integer> purgeTokens; ArrayList<Integer> purgeTokens;
PlayerCharacter target = (PlayerCharacter) mob.getCombatTarget(); PlayerCharacter target = (PlayerCharacter) mob.getCombatTarget();
if (mob.BehaviourType.callsForHelp) if (mob.BehaviourType.callsForHelp)
MobCallForHelp(mob); MobCallForHelp(mob);
// Generate a list of tokens from the mob powers for this mobile. // Generate a list of tokens from the mob powers for this mobile.
powerTokens = new ArrayList<>(mob.mobPowers.keySet()); powerTokens = new ArrayList<>(mob.mobPowers.keySet());
purgeTokens = new ArrayList<>(); purgeTokens = new ArrayList<>();
// If player has this effect on them currently then remove // If player has this effect on them currently then remove
// this token from our list. // this token from our list.
for (int powerToken : powerTokens) { for (int powerToken : powerTokens) {
PowersBase powerBase = PowersManager.getPowerByToken(powerToken); PowersBase powerBase = PowersManager.getPowerByToken(powerToken);
for (ActionsBase actionBase : powerBase.getActions()) { for (ActionsBase actionBase : powerBase.getActions()) {
String stackType = actionBase.stackType; String stackType = actionBase.stackType;
if (target.getEffects() != null && target.getEffects().containsKey(stackType)) if (target.getEffects() != null && target.getEffects().containsKey(stackType))
purgeTokens.add(powerToken); purgeTokens.add(powerToken);
} }
} }
powerTokens.removeAll(purgeTokens); powerTokens.removeAll(purgeTokens);
// Sanity check // Sanity check
if (powerTokens.isEmpty()) if (powerTokens.isEmpty())
return false; return false;
// Pick random spell from our list of powers // Pick random spell from our list of powers
int powerToken = powerTokens.get(ThreadLocalRandom.current().nextInt(powerTokens.size())); int powerToken = powerTokens.get(ThreadLocalRandom.current().nextInt(powerTokens.size()));
int powerRank = mob.mobPowers.get(powerToken); int powerRank = mob.mobPowers.get(powerToken);
PowersBase mobPower = PowersManager.getPowerByToken(powerToken); PowersBase mobPower = PowersManager.getPowerByToken(powerToken);
// Cast the spell // Cast the spell
if (CombatUtilities.inRange2D(mob, mob.getCombatTarget(), mobPower.getRange())) { if (CombatUtilities.inRange2D(mob, mob.getCombatTarget(), mobPower.getRange())) {
PowersManager.useMobPower(mob, (AbstractCharacter) mob.getCombatTarget(), mobPower, powerRank); PowersManager.useMobPower(mob, (AbstractCharacter) mob.getCombatTarget(), mobPower, powerRank);
PerformActionMsg msg; PerformActionMsg msg;
if (!mobPower.isHarmful() || mobPower.targetSelf) if (!mobPower.isHarmful() || mobPower.targetSelf)
msg = PowersManager.createPowerMsg(mobPower, powerRank, mob, mob); msg = PowersManager.createPowerMsg(mobPower, powerRank, mob, mob);
else else
msg = PowersManager.createPowerMsg(mobPower, powerRank, mob, target); msg = PowersManager.createPowerMsg(mobPower, powerRank, mob, target);
msg.setUnknown04(2); msg.setUnknown04(2);
PowersManager.finishUseMobPower(msg, mob, 0, 0); PowersManager.finishUseMobPower(msg, mob, 0, 0);
mob.nextCastTime = System.currentTimeMillis() + (MBServerStatics.AI_POWER_DIVISOR * 1000); mob.nextCastTime = System.currentTimeMillis() + (MBServerStatics.AI_POWER_DIVISOR * 1000);
return true; return true;
} }
return false; return false;
} }
public static void MobCallForHelp(Mob mob) { public static void MobCallForHelp(Mob mob) {
boolean callGotResponse = false; boolean callGotResponse = false;
if (mob.nextCallForHelp == 0) {
if (mob.nextCallForHelp == 0)
mob.nextCallForHelp = System.currentTimeMillis(); mob.nextCallForHelp = System.currentTimeMillis();
}
if (mob.nextCallForHelp < System.currentTimeMillis()) if (mob.nextCallForHelp < System.currentTimeMillis())
return; return;
//mob sends call for help message //mob sends call for help message
ChatManager.chatSayInfo(null, mob.getName() + " calls for help!"); ChatManager.chatSayInfo(null, mob.getName() + " calls for help!");
Zone mobCamp = mob.getParentZone(); Zone mobCamp = mob.getParentZone();
for (Mob helper : mobCamp.zoneMobSet) { for (Mob helper : mobCamp.zoneMobSet) {
if (helper.BehaviourType.respondsToCallForHelp && helper.BehaviourType.BehaviourHelperType.equals(mob.BehaviourType)) { if (helper.BehaviourType.respondsToCallForHelp && helper.BehaviourType.BehaviourHelperType.equals(mob.BehaviourType)) {
helper.setCombatTarget(mob.getCombatTarget()); helper.setCombatTarget(mob.getCombatTarget());
callGotResponse = true; callGotResponse = true;
} }
} }
//wait 60 seconds to call for help again
if (callGotResponse) if (callGotResponse)
//wait 60 seconds to call for help again
mob.nextCallForHelp = System.currentTimeMillis() + 60000; mob.nextCallForHelp = System.currentTimeMillis() + 60000;
} }
public static void DetermineAction(Mob mob) { public static void DetermineAction(Mob mob) {
if (mob == null) if (mob == null)
return; return;
if(mob.despawned == true || mob.isAlive() == false) {
if (mob.despawned == true || mob.isAlive() == false) {
if (mob.BehaviourType.ordinal() == Enum.MobBehaviourType.GuardMinion.ordinal()) { if (mob.BehaviourType.ordinal() == Enum.MobBehaviourType.GuardMinion.ordinal()) {
//minions don't respawn while guard captain is dead
if (mob.npcOwner.isAlive() == false || ((Mob) mob.npcOwner).despawned == true) { if (mob.npcOwner.isAlive() == false || ((Mob) mob.npcOwner).despawned == true) {
//minions don't respawn while guard captain is dead mob.deathTime = System.currentTimeMillis();
mob.deathTime = System.currentTimeMillis(); return;
return;
} }
} }
CheckForRespawn(mob); CheckForRespawn(mob);
return; return;
} }
//no players loaded, no need to proceed
if (mob.playerAgroMap.isEmpty() && mob.isPlayerGuard == false) if (mob.playerAgroMap.isEmpty() && mob.isPlayerGuard == false)
//no players loaded, no need to proceed
return; return;
if (mob.isCombat() && mob.getCombatTarget() == null) { if (mob.isCombat() && mob.getCombatTarget() == null) {
mob.setCombat(false); mob.setCombat(false);
UpdateStateMsg rwss = new UpdateStateMsg(); UpdateStateMsg rwss = new UpdateStateMsg();
rwss.setPlayer(mob); rwss.setPlayer(mob);
DispatchMessage.sendToAllInRange(mob, rwss); DispatchMessage.sendToAllInRange(mob, rwss);
} }
mob.updateLocation(); mob.updateLocation();
CheckToSendMobHome(mob); CheckToSendMobHome(mob);
switch (mob.BehaviourType) { switch (mob.BehaviourType) {
case GuardCaptain: case GuardCaptain:
GuardCaptainLogic(mob); GuardCaptainLogic(mob);
@ -347,81 +458,110 @@ public class MobileFSM {
break; break;
} }
} }
private static void CheckForAggro(Mob aiAgent) { private static void CheckForAggro(Mob aiAgent) {
//looks for and sets mobs combatTarget //looks for and sets mobs combatTarget
if (!aiAgent.isAlive()) if (!aiAgent.isAlive())
return; return;
ConcurrentHashMap<Integer, Boolean> loadedPlayers = aiAgent.playerAgroMap; ConcurrentHashMap<Integer, Boolean> loadedPlayers = aiAgent.playerAgroMap;
for (Entry playerEntry : loadedPlayers.entrySet()) { for (Entry playerEntry : loadedPlayers.entrySet()) {
int playerID = (int) playerEntry.getKey(); int playerID = (int) playerEntry.getKey();
PlayerCharacter loadedPlayer = PlayerCharacter.getFromCache(playerID); PlayerCharacter loadedPlayer = PlayerCharacter.getFromCache(playerID);
//Player is null, let's remove them from the list. //Player is null, let's remove them from the list.
if (loadedPlayer == null) { if (loadedPlayer == null) {
loadedPlayers.remove(playerID); loadedPlayers.remove(playerID);
continue; continue;
} }
//Player is Dead, Mob no longer needs to attempt to aggro. Remove them from aggro map. //Player is Dead, Mob no longer needs to attempt to aggro. Remove them from aggro map.
if (!loadedPlayer.isAlive()) { if (!loadedPlayer.isAlive()) {
loadedPlayers.remove(playerID); loadedPlayers.remove(playerID);
continue; continue;
} }
//Can't see target, skip aggro. //Can't see target, skip aggro.
if (!aiAgent.canSee(loadedPlayer)) if (!aiAgent.canSee(loadedPlayer))
continue; continue;
// No aggro for this race type // No aggro for this race type
if (aiAgent.notEnemy.contains(loadedPlayer.getRace().getRaceType().getMonsterType())) if (aiAgent.notEnemy.contains(loadedPlayer.getRace().getRaceType().getMonsterType()))
continue; continue;
if (MovementUtilities.inRangeToAggro(aiAgent, loadedPlayer)) { if (MovementUtilities.inRangeToAggro(aiAgent, loadedPlayer)) {
aiAgent.setCombatTarget(loadedPlayer); aiAgent.setCombatTarget(loadedPlayer);
return; return;
} }
} }
} }
private static void CheckMobMovement(Mob mob) { private static void CheckMobMovement(Mob mob) {
if (!MovementUtilities.canMove(mob)) if (!MovementUtilities.canMove(mob))
return; return;
switch(mob.BehaviourType){
switch (mob.BehaviourType) {
case Pet1: case Pet1:
//mob no longer has its owner loaded, translocate pet to owner
if (!mob.playerAgroMap.containsKey(mob.getOwner().getObjectUUID())) { if (!mob.playerAgroMap.containsKey(mob.getOwner().getObjectUUID())) {
//mob no longer has its owner loaded, translocate pet to owner
MovementManager.translocate(mob, mob.getOwner().getLoc(), null); MovementManager.translocate(mob, mob.getOwner().getLoc(), null);
return; return;
} }
//move back to owner
if (mob.getCombatTarget() == null) { if (mob.getCombatTarget() == null) {
//move back to owner //move back to owner
if (CombatUtilities.inRange2D(mob, mob.getOwner(), 6)) if (CombatUtilities.inRange2D(mob, mob.getOwner(), 6))
return; return;
mob.destination = mob.getOwner().getLoc(); mob.destination = mob.getOwner().getLoc();
MovementUtilities.moveToLocation(mob, mob.destination, 5); MovementUtilities.moveToLocation(mob, mob.destination, 5);
} else } else
chaseTarget(mob); chaseTarget(mob);
break; break;
case GuardMinion: case GuardMinion:
if (!mob.npcOwner.isAlive() || ((Mob)mob.npcOwner).despawned) if (!mob.npcOwner.isAlive() || ((Mob) mob.npcOwner).despawned)
randomGuardPatrolPoint(mob); randomGuardPatrolPoint(mob);
else{ else {
if(mob.getCombatTarget() != null){ if (mob.getCombatTarget() != null)
chaseTarget(mob); chaseTarget(mob);
}
} }
break; break;
default: default:
if (mob.getCombatTarget() == null) { if (mob.getCombatTarget() == null)
Patrol(mob); Patrol(mob);
}else { else
chaseTarget(mob); chaseTarget(mob);
}
break; break;
} }
} }
private static void CheckForRespawn(Mob aiAgent) { private static void CheckForRespawn(Mob aiAgent) {
if (aiAgent.deathTime == 0) { if (aiAgent.deathTime == 0) {
aiAgent.setDeathTime(System.currentTimeMillis()); aiAgent.setDeathTime(System.currentTimeMillis());
return; return;
} }
//handles checking for respawn of dead mobs even when no players have mob loaded //handles checking for respawn of dead mobs even when no players have mob loaded
//Despawn Timer with Loot currently in inventory. //Despawn Timer with Loot currently in inventory.
if (!aiAgent.despawned) { if (!aiAgent.despawned) {
if (aiAgent.getCharItemManager().getInventoryCount() > 0) { if (aiAgent.getCharItemManager().getInventoryCount() > 0) {
if (System.currentTimeMillis() > aiAgent.deathTime + MBServerStatics.DESPAWN_TIMER_WITH_LOOT) { if (System.currentTimeMillis() > aiAgent.deathTime + MBServerStatics.DESPAWN_TIMER_WITH_LOOT) {
aiAgent.despawn(); aiAgent.despawn();
@ -429,12 +569,15 @@ public class MobileFSM {
} }
//No items in inventory. //No items in inventory.
} else { } else {
//Mob's Loot has been looted. //Mob's Loot has been looted.
if (aiAgent.isHasLoot()) { if (aiAgent.isHasLoot()) {
if (System.currentTimeMillis() > aiAgent.deathTime + MBServerStatics.DESPAWN_TIMER_ONCE_LOOTED) { if (System.currentTimeMillis() > aiAgent.deathTime + MBServerStatics.DESPAWN_TIMER_ONCE_LOOTED) {
aiAgent.despawn(); aiAgent.despawn();
aiAgent.deathTime = System.currentTimeMillis(); aiAgent.deathTime = System.currentTimeMillis();
} }
//Mob never had Loot. //Mob never had Loot.
} else { } else {
if (System.currentTimeMillis() > aiAgent.deathTime + MBServerStatics.DESPAWN_TIMER) { if (System.currentTimeMillis() > aiAgent.deathTime + MBServerStatics.DESPAWN_TIMER) {
@ -447,10 +590,14 @@ public class MobileFSM {
aiAgent.respawn(); aiAgent.respawn();
} }
} }
public static void CheckForAttack(Mob mob) { public static void CheckForAttack(Mob mob) {
//checks if mob can attack based on attack timer and range //checks if mob can attack based on attack timer and range
if (mob.isAlive() == false) if (mob.isAlive() == false)
return; return;
if (MovementUtilities.inRangeDropAggro(mob, (PlayerCharacter) mob.getCombatTarget()) == false) { if (MovementUtilities.inRangeDropAggro(mob, (PlayerCharacter) mob.getCombatTarget()) == false) {
mob.setCombatTarget(null); mob.setCombatTarget(null);
if (mob.isCombat()) { if (mob.isCombat()) {
@ -470,34 +617,42 @@ public class MobileFSM {
if (System.currentTimeMillis() > mob.getLastAttackTime()) if (System.currentTimeMillis() > mob.getLastAttackTime())
AttackTarget(mob, mob.getCombatTarget()); AttackTarget(mob, mob.getCombatTarget());
} }
private static void CheckToSendMobHome(Mob mob) { private static void CheckToSendMobHome(Mob mob) {
if (mob.isPlayerGuard() && !mob.despawned) { if (mob.isPlayerGuard() && !mob.despawned) {
City current = ZoneManager.getCityAtLocation(mob.getLoc()); City current = ZoneManager.getCityAtLocation(mob.getLoc());
if (current == null || current.equals(mob.getGuild().getOwnedCity()) == false || mob.playerAgroMap.isEmpty()) { if (current == null || current.equals(mob.getGuild().getOwnedCity()) == false || mob.playerAgroMap.isEmpty()) {
PowersBase recall = PowersManager.getPowerByToken(-1994153779); PowersBase recall = PowersManager.getPowerByToken(-1994153779);
PowersManager.useMobPower(mob, mob, recall, 40); PowersManager.useMobPower(mob, mob, recall, 40);
mob.setCombatTarget(null); mob.setCombatTarget(null);
if(mob.BehaviourType.ordinal() == Enum.MobBehaviourType.GuardCaptain.ordinal() && mob.isAlive()){
//guard captain pulls his minions home with him //guard captain pulls his minions home with him
if (mob.BehaviourType.ordinal() == Enum.MobBehaviourType.GuardCaptain.ordinal() && mob.isAlive()) {
for (Entry<Mob, Integer> minion : mob.siegeMinionMap.entrySet()) { for (Entry<Mob, Integer> minion : mob.siegeMinionMap.entrySet()) {
PowersManager.useMobPower(minion.getKey(), minion.getKey(), recall, 40); PowersManager.useMobPower(minion.getKey(), minion.getKey(), recall, 40);
minion.getKey().setCombatTarget(null); minion.getKey().setCombatTarget(null);
} }
} }
} }
} } else if (MovementUtilities.inRangeOfBindLocation(mob) == false) {
else if(MovementUtilities.inRangeOfBindLocation(mob) == false) {
PowersBase recall = PowersManager.getPowerByToken(-1994153779); PowersBase recall = PowersManager.getPowerByToken(-1994153779);
PowersManager.useMobPower(mob, mob, recall, 40); PowersManager.useMobPower(mob, mob, recall, 40);
mob.setCombatTarget(null); mob.setCombatTarget(null);
} }
} }
private static void chaseTarget(Mob mob) { private static void chaseTarget(Mob mob) {
mob.updateMovementState(); mob.updateMovementState();
if(mob.playerAgroMap.containsKey(mob.getCombatTarget().getObjectUUID()) == false){
if (mob.playerAgroMap.containsKey(mob.getCombatTarget().getObjectUUID()) == false) {
mob.setCombatTarget(null); mob.setCombatTarget(null);
return; return;
} }
if (CombatUtilities.inRange2D(mob, mob.getCombatTarget(), mob.getRange()) == false) { if (CombatUtilities.inRange2D(mob, mob.getCombatTarget(), mob.getRange()) == false) {
if (mob.getRange() > 15) { if (mob.getRange() > 15) {
mob.destination = mob.getCombatTarget().getLoc(); mob.destination = mob.getCombatTarget().getLoc();
@ -508,179 +663,263 @@ public class MobileFSM {
} }
} }
} }
private static void SafeGuardAggro(Mob mob) { private static void SafeGuardAggro(Mob mob) {
HashSet<AbstractWorldObject> awoList = WorldGrid.getObjectsInRangePartial(mob, 100, MBServerStatics.MASK_MOB); HashSet<AbstractWorldObject> awoList = WorldGrid.getObjectsInRangePartial(mob, 100, MBServerStatics.MASK_MOB);
for (AbstractWorldObject awoMob : awoList) { for (AbstractWorldObject awoMob : awoList) {
//dont scan self. //dont scan self.
if (mob.equals(awoMob)) if (mob.equals(awoMob))
continue; continue;
Mob aggroMob = (Mob) awoMob; Mob aggroMob = (Mob) awoMob;
//dont attack other guards //dont attack other guards
if (aggroMob.isGuard()) if (aggroMob.isGuard())
continue; continue;
if (mob.getLoc().distanceSquared2D(aggroMob.getLoc()) > sqr(50)) if (mob.getLoc().distanceSquared2D(aggroMob.getLoc()) > sqr(50))
continue; continue;
mob.setCombatTarget(aggroMob); mob.setCombatTarget(aggroMob);
} }
} }
public static void GuardCaptainLogic(Mob mob) { public static void GuardCaptainLogic(Mob mob) {
if (mob.getCombatTarget() == null) if (mob.getCombatTarget() == null)
CheckForPlayerGuardAggro(mob); CheckForPlayerGuardAggro(mob);
CheckMobMovement(mob); CheckMobMovement(mob);
if (mob.getCombatTarget() != null) if (mob.getCombatTarget() != null)
CheckForAttack(mob); CheckForAttack(mob);
} }
public static void GuardMinionLogic(Mob mob) { public static void GuardMinionLogic(Mob mob) {
if (!mob.npcOwner.isAlive() && mob.getCombatTarget() == null) {
if (!mob.npcOwner.isAlive() && mob.getCombatTarget() == null)
CheckForPlayerGuardAggro(mob); CheckForPlayerGuardAggro(mob);
}
if(mob.npcOwner.getCombatTarget() != null) if (mob.npcOwner.getCombatTarget() != null)
mob.setCombatTarget(mob.npcOwner.getCombatTarget()); mob.setCombatTarget(mob.npcOwner.getCombatTarget());
else else
mob.setCombatTarget(null); mob.setCombatTarget(null);
CheckMobMovement(mob); CheckMobMovement(mob);
if (mob.getCombatTarget() != null) if (mob.getCombatTarget() != null)
CheckForAttack(mob); CheckForAttack(mob);
} }
public static void GuardWallArcherLogic(Mob mob) { public static void GuardWallArcherLogic(Mob mob) {
if (mob.getCombatTarget() == null) if (mob.getCombatTarget() == null)
CheckForPlayerGuardAggro(mob); CheckForPlayerGuardAggro(mob);
else else
CheckForAttack(mob); CheckForAttack(mob);
} }
private static void PetLogic(Mob mob) { private static void PetLogic(Mob mob) {
if (mob.getCombatTarget() != null && !mob.getCombatTarget().isAlive()) if (mob.getCombatTarget() != null && !mob.getCombatTarget().isAlive())
mob.setCombatTarget(null); mob.setCombatTarget(null);
if (MovementUtilities.canMove(mob) && mob.BehaviourType.canRoam) if (MovementUtilities.canMove(mob) && mob.BehaviourType.canRoam)
CheckMobMovement(mob); CheckMobMovement(mob);
if (mob.getCombatTarget() != null) if (mob.getCombatTarget() != null)
CheckForAttack(mob); CheckForAttack(mob);
} }
private static void HamletGuardLogic(Mob mob) { private static void HamletGuardLogic(Mob mob) {
//safehold guard
if (mob.getCombatTarget() == null) { if (mob.getCombatTarget() == null) {
//safehold guard
SafeGuardAggro(mob); SafeGuardAggro(mob);
if (mob.getCombatTarget() != null) if (mob.getCombatTarget() != null)
CheckForAttack(mob); CheckForAttack(mob);
} }
} }
private static void DefaultLogic(Mob mob) { private static void DefaultLogic(Mob mob) {
//check for players that can be aggroed if mob is agressive and has no target
// check for players that can be aggroed if mob is agressive and has no target
if (mob.BehaviourType.isAgressive) { if (mob.BehaviourType.isAgressive) {
AbstractWorldObject newTarget = ChangeTargetFromHateValue(mob); AbstractWorldObject newTarget = ChangeTargetFromHateValue(mob);
if (newTarget != null) { if (newTarget != null) {
mob.setCombatTarget(newTarget); mob.setCombatTarget(newTarget);
} else { } else {
if (mob.getCombatTarget() == null) { if (mob.getCombatTarget() == null) {
if (mob.BehaviourType == Enum.MobBehaviourType.HamletGuard) if (mob.BehaviourType == Enum.MobBehaviourType.HamletGuard)
//safehold guard SafeGuardAggro(mob); // safehold guard
SafeGuardAggro(mob);
else else
//normal aggro CheckForAggro(mob); // normal aggro
CheckForAggro(mob);
} }
} }
} }
//check if mob can move for patrol or moving to target //check if mob can move for patrol or moving to target
if (mob.BehaviourType.canRoam) if (mob.BehaviourType.canRoam)
CheckMobMovement(mob); CheckMobMovement(mob);
//check if mob can attack if it isn't wimpy //check if mob can attack if it isn't wimpy
if (!mob.BehaviourType.isWimpy && !mob.isMoving() && mob.combatTarget != null) if (!mob.BehaviourType.isWimpy && !mob.isMoving() && mob.combatTarget != null)
CheckForAttack(mob); CheckForAttack(mob);
if(mob.combatTarget != null){
if (mob.combatTarget != null) {
CheckForAttack(mob); CheckForAttack(mob);
} }
} }
public static void CheckForPlayerGuardAggro(Mob mob) { public static void CheckForPlayerGuardAggro(Mob mob) {
//looks for and sets mobs combatTarget //looks for and sets mobs combatTarget
if (!mob.isAlive()) if (!mob.isAlive())
return; return;
ConcurrentHashMap<Integer, Boolean> loadedPlayers = mob.playerAgroMap; ConcurrentHashMap<Integer, Boolean> loadedPlayers = mob.playerAgroMap;
for (Entry playerEntry : loadedPlayers.entrySet()) { for (Entry playerEntry : loadedPlayers.entrySet()) {
int playerID = (int) playerEntry.getKey(); int playerID = (int) playerEntry.getKey();
PlayerCharacter loadedPlayer = PlayerCharacter.getFromCache(playerID); PlayerCharacter loadedPlayer = PlayerCharacter.getFromCache(playerID);
//Player is null, let's remove them from the list. //Player is null, let's remove them from the list.
if (loadedPlayer == null) { if (loadedPlayer == null) {
loadedPlayers.remove(playerID); loadedPlayers.remove(playerID);
continue; continue;
} }
//Player is Dead, Mob no longer needs to attempt to aggro. Remove them from aggro map. //Player is Dead, Mob no longer needs to attempt to aggro. Remove them from aggro map.
if (!loadedPlayer.isAlive()) { if (!loadedPlayer.isAlive()) {
loadedPlayers.remove(playerID); loadedPlayers.remove(playerID);
continue; continue;
} }
//Can't see target, skip aggro. //Can't see target, skip aggro.
if (!mob.canSee(loadedPlayer)) if (!mob.canSee(loadedPlayer))
continue; continue;
// No aggro for this player // No aggro for this player
if (GuardCanAggro(mob, loadedPlayer) == false) if (GuardCanAggro(mob, loadedPlayer) == false)
continue; continue;
if (MovementUtilities.inRangeToAggro(mob, loadedPlayer)) { if (MovementUtilities.inRangeToAggro(mob, loadedPlayer)) {
mob.setCombatTarget(loadedPlayer); mob.setCombatTarget(loadedPlayer);
return; return;
} }
} }
} }
public static Boolean GuardCanAggro(Mob mob, PlayerCharacter target) { public static Boolean GuardCanAggro(Mob mob, PlayerCharacter target) {
if (mob.getGuild().getNation().equals(target.getGuild().getNation())) if (mob.getGuild().getNation().equals(target.getGuild().getNation()))
return false; return false;
if (mob.BehaviourType.ordinal() == Enum.MobBehaviourType.GuardMinion.ordinal()) { if (mob.BehaviourType.ordinal() == Enum.MobBehaviourType.GuardMinion.ordinal()) {
if(((Mob)mob.npcOwner).building.getCity().cityOutlaws.contains(target.getObjectUUID()) == true){
if (((Mob) mob.npcOwner).building.getCity().cityOutlaws.contains(target.getObjectUUID()) == true)
return true; return true;
}
} else if(mob.building.getCity().cityOutlaws.contains(target.getObjectUUID()) == true){ } else if (mob.building.getCity().cityOutlaws.contains(target.getObjectUUID()) == true) {
return true; return true;
} }
//first check condemn list for aggro allowed (allies button is checked) //first check condemn list for aggro allowed (allies button is checked)
if (ZoneManager.getCityAtLocation(mob.getLoc()).getTOL().reverseKOS) { if (ZoneManager.getCityAtLocation(mob.getLoc()).getTOL().reverseKOS) {
for (Entry<Integer, Condemned> entry : ZoneManager.getCityAtLocation(mob.getLoc()).getTOL().getCondemned().entrySet()) { for (Entry<Integer, Condemned> entry : ZoneManager.getCityAtLocation(mob.getLoc()).getTOL().getCondemned().entrySet()) {
//target is listed individually
if (entry.getValue().getPlayerUID() == target.getObjectUUID() && entry.getValue().isActive()) if (entry.getValue().getPlayerUID() == target.getObjectUUID() && entry.getValue().isActive())
//target is listed individually
return false; return false;
//target's guild is listed
if (Guild.getGuild(entry.getValue().getGuildUID()) == target.getGuild()) if (Guild.getGuild(entry.getValue().getGuildUID()) == target.getGuild())
//target's guild is listed
return false; return false;
//target's nation is listed
if (Guild.getGuild(entry.getValue().getGuildUID()) == target.getGuild().getNation()) if (Guild.getGuild(entry.getValue().getGuildUID()) == target.getGuild().getNation())
//target's nation is listed
return false; return false;
} }
return true; return true;
} else{ } else {
//allies button is not checked //allies button is not checked
for (Entry<Integer, Condemned> entry : ZoneManager.getCityAtLocation(mob.getLoc()).getTOL().getCondemned().entrySet()) { for (Entry<Integer, Condemned> entry : ZoneManager.getCityAtLocation(mob.getLoc()).getTOL().getCondemned().entrySet()) {
//target is listed individually
if (entry.getValue().getPlayerUID() == target.getObjectUUID() && entry.getValue().isActive()) if (entry.getValue().getPlayerUID() == target.getObjectUUID() && entry.getValue().isActive())
//target is listed individually
return true; return true;
//target's guild is listed
if (Guild.getGuild(entry.getValue().getGuildUID()) == target.getGuild()) if (Guild.getGuild(entry.getValue().getGuildUID()) == target.getGuild())
//target's guild is listed
return true; return true;
//target's nation is listed
if (Guild.getGuild(entry.getValue().getGuildUID()) == target.getGuild().getNation()) if (Guild.getGuild(entry.getValue().getGuildUID()) == target.getGuild().getNation())
//target's nation is listed
return true; return true;
} }
} }
return false; return false;
} }
public static void randomGuardPatrolPoint(Mob mob){
public static void randomGuardPatrolPoint(Mob mob) {
//early exit for a mob who is already moving to a patrol point
//while mob moving, update lastPatrolTime so that when they stop moving the 10 second timer can begin
if (mob.isMoving() == true) { if (mob.isMoving() == true) {
//early exit for a mob who is already moving to a patrol point
//while mob moving, update lastPatrolTime so that when they stop moving the 10 second timer can begin
mob.stopPatrolTime = System.currentTimeMillis(); mob.stopPatrolTime = System.currentTimeMillis();
return; return;
} }
//wait between 10 and 15 seconds after reaching patrol point before moving //wait between 10 and 15 seconds after reaching patrol point before moving
int patrolDelay = ThreadLocalRandom.current().nextInt(10000) + 5000; int patrolDelay = ThreadLocalRandom.current().nextInt(10000) + 5000;
//early exit while waiting to patrol again
if (mob.stopPatrolTime + patrolDelay > System.currentTimeMillis()) if (mob.stopPatrolTime + patrolDelay > System.currentTimeMillis())
//early exit while waiting to patrol again
return; return;
float xPoint = ThreadLocalRandom.current().nextInt(400) - 200; float xPoint = ThreadLocalRandom.current().nextInt(400) - 200;
float zPoint = ThreadLocalRandom.current().nextInt(400) - 200; float zPoint = ThreadLocalRandom.current().nextInt(400) - 200;
Vector3fImmutable TreePos = mob.getGuild().getOwnedCity().getLoc(); Vector3fImmutable TreePos = mob.getGuild().getOwnedCity().getLoc();
mob.destination = new Vector3fImmutable(TreePos.x + xPoint,TreePos.y,TreePos.z + zPoint);
mob.destination = new Vector3fImmutable(TreePos.x + xPoint, TreePos.y, TreePos.z + zPoint);
MovementUtilities.aiMove(mob, mob.destination, true); MovementUtilities.aiMove(mob, mob.destination, true);
if(mob.BehaviourType.ordinal() == Enum.MobBehaviourType.GuardCaptain.ordinal()){
if (mob.BehaviourType.ordinal() == Enum.MobBehaviourType.GuardCaptain.ordinal()) {
for (Entry<Mob, Integer> minion : mob.siegeMinionMap.entrySet()) { for (Entry<Mob, Integer> minion : mob.siegeMinionMap.entrySet()) {
//make sure mob is out of combat stance //make sure mob is out of combat stance
if (minion.getKey().despawned == false) { if (minion.getKey().despawned == false) {
if (minion.getKey().isCombat() && minion.getKey().getCombatTarget() == null) { if (minion.getKey().isCombat() && minion.getKey().getCombatTarget() == null) {
minion.getKey().setCombat(false); minion.getKey().setCombat(false);
@ -698,18 +937,24 @@ public class MobileFSM {
} }
} }
} }
public static AbstractWorldObject ChangeTargetFromHateValue(Mob mob){
public static AbstractWorldObject ChangeTargetFromHateValue(Mob mob) {
float CurrentHateValue = 0; float CurrentHateValue = 0;
if(mob.getCombatTarget() != null && mob.getCombatTarget().getObjectType().equals(Enum.GameObjectType.PlayerCharacter)){
CurrentHateValue = ((PlayerCharacter)mob.getCombatTarget()).getHateValue(); if (mob.getCombatTarget() != null && mob.getCombatTarget().getObjectType().equals(Enum.GameObjectType.PlayerCharacter))
} CurrentHateValue = ((PlayerCharacter) mob.getCombatTarget()).getHateValue();
AbstractWorldObject mostHatedTarget = null; AbstractWorldObject mostHatedTarget = null;
for (Entry playerEntry : mob.playerAgroMap.entrySet()) { for (Entry playerEntry : mob.playerAgroMap.entrySet()) {
PlayerCharacter potentialTarget = PlayerCharacter.getFromCache((int)playerEntry.getKey());
if(potentialTarget.equals(mob.getCombatTarget())){ PlayerCharacter potentialTarget = PlayerCharacter.getFromCache((int) playerEntry.getKey());
if (potentialTarget.equals(mob.getCombatTarget()))
continue; continue;
}
if(potentialTarget != null && potentialTarget.getHateValue() > CurrentHateValue){ if (potentialTarget != null && potentialTarget.getHateValue() > CurrentHateValue) {
CurrentHateValue = potentialTarget.getHateValue(); CurrentHateValue = potentialTarget.getHateValue();
mostHatedTarget = potentialTarget; mostHatedTarget = potentialTarget;
} }

121
src/engine/ai/MobileFSMManager.java

@ -8,6 +8,7 @@
package engine.ai; package engine.ai;
import engine.gameManager.SessionManager; import engine.gameManager.SessionManager;
import engine.gameManager.ZoneManager; import engine.gameManager.ZoneManager;
import engine.objects.Mob; import engine.objects.Mob;
@ -22,90 +23,84 @@ import java.time.Instant;
public class MobileFSMManager { public class MobileFSMManager {
private static final MobileFSMManager INSTANCE = new MobileFSMManager(); private static final MobileFSMManager INSTANCE = new MobileFSMManager();
public static Duration executionTime = Duration.ofNanos(1);
private volatile boolean alive; public static Duration executionMax = Duration.ofNanos(1);
private long timeOfKill = -1; private volatile boolean alive;
private long timeOfKill = -1;
public static Duration executionTime = Duration.ofNanos(1);
public static Duration executionMax = Duration.ofNanos(1);
private MobileFSMManager() {
Runnable worker = new Runnable() { private MobileFSMManager() {
@Override
public void run() {
execution();
}
};
alive = true; Runnable worker = new Runnable() {
@Override
public void run() {
execution();
}
};
Thread t = new Thread(worker, "MobileFSMManager"); alive = true;
t.start();
}
public static MobileFSMManager getInstance() { Thread t = new Thread(worker, "MobileFSMManager");
return INSTANCE; t.start();
} }
/** public static MobileFSMManager getInstance() {
* Stops the MobileFSMManager return INSTANCE;
*/ }
public void shutdown() {
if (alive) {
alive = false;
timeOfKill = System.currentTimeMillis();
}
}
/**
* Stops the MobileFSMManager
*/
public void shutdown() {
if (alive) {
alive = false;
timeOfKill = System.currentTimeMillis();
}
}
public long getTimeOfKill() {
return this.timeOfKill;
}
public boolean isAlive() { public boolean isAlive() {
return this.alive; return this.alive;
} }
private void execution() { private void execution() {
//Load zone threshold once. //Load zone threshold once.
long mobPulse = System.currentTimeMillis() + MBServerStatics.AI_PULSE_MOB_THRESHOLD; long mobPulse = System.currentTimeMillis() + MBServerStatics.AI_PULSE_MOB_THRESHOLD;
Instant startTime; Instant startTime;
while (alive) { while (alive) {
ThreadUtils.sleep(1); ThreadUtils.sleep(1);
if (System.currentTimeMillis() > mobPulse) { if (System.currentTimeMillis() > mobPulse) {
startTime = Instant.now(); startTime = Instant.now();
for (Zone zone : ZoneManager.getAllZones()) { for (Zone zone : ZoneManager.getAllZones()) {
for (Mob mob : zone.zoneMobSet) { for (Mob mob : zone.zoneMobSet) {
try { try {
if (mob != null && SessionManager.getActivePlayerCharacterCount() > 0) if (mob != null && SessionManager.getActivePlayerCharacterCount() > 0)
MobileFSM.DetermineAction(mob); MobileFSM.DetermineAction(mob);
} catch (Exception e) { } catch (Exception e) {
Logger.error("Mob: " + mob.getName() + " UUID: " + mob.getObjectUUID() + " ERROR: " + e); Logger.error("Mob: " + mob.getName() + " UUID: " + mob.getObjectUUID() + " ERROR: " + e);
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
this.executionTime = Duration.between(startTime, Instant.now()); executionTime = Duration.between(startTime, Instant.now());
if (executionTime.compareTo(executionMax) > 0) if (executionTime.compareTo(executionMax) > 0)
executionMax = executionTime; executionMax = executionTime;
mobPulse = System.currentTimeMillis() + MBServerStatics.AI_PULSE_MOB_THRESHOLD; mobPulse = System.currentTimeMillis() + MBServerStatics.AI_PULSE_MOB_THRESHOLD;
} }
} }
} }
} }

954
src/engine/ai/utilities/CombatUtilities.java

@ -7,7 +7,6 @@
// www.magicbane.com // www.magicbane.com
package engine.ai.utilities; package engine.ai.utilities;
import engine.Enum.*; import engine.Enum.*;
@ -27,479 +26,482 @@ import static java.lang.Math.pow;
public class CombatUtilities { public class CombatUtilities {
public static boolean inRangeToAttack(Mob agent,AbstractWorldObject target){ public static boolean inRangeToAttack(Mob agent, AbstractWorldObject target) {
if (Float.isNaN(agent.getLoc().x)) if (Float.isNaN(agent.getLoc().x))
return false; return false;
try{ try {
Vector3fImmutable sl = agent.getLoc(); Vector3fImmutable sl = agent.getLoc();
Vector3fImmutable tl = target.getLoc(); Vector3fImmutable tl = target.getLoc();
//add Hitbox's to range. //add Hitbox's to range.
float range = agent.getRange(); float range = agent.getRange();
range += CombatManager.calcHitBox(target) + CombatManager.calcHitBox(agent); range += CombatManager.calcHitBox(target) + CombatManager.calcHitBox(agent);
//if (target instanceof AbstractCharacter)
// if (((AbstractCharacter)target).isMoving()) return !(sl.distanceSquared(tl) > sqr(range));
// range+= 5; } catch (Exception e) {
Logger.error(e.toString());
return !(sl.distanceSquared(tl) > sqr(range)); return false;
}catch(Exception e){ }
Logger.error( e.toString());
return false; }
}
public static boolean inRange2D(AbstractWorldObject entity1, AbstractWorldObject entity2, double range) {
} return entity1.getLoc().distance2D(entity2.getLoc()) < range;
public static boolean inRangeToAttack2D(Mob agent,AbstractWorldObject target){ }
if (Float.isNaN(agent.getLoc().x)) public static void swingIsBlock(Mob agent, AbstractWorldObject target, int animation) {
return false;
if (!target.isAlive())
try{ return;
Vector3fImmutable sl = agent.getLoc();
Vector3fImmutable tl = target.getLoc(); TargetedActionMsg msg = new TargetedActionMsg(agent, animation, target, MBServerStatics.COMBAT_SEND_BLOCK);
//add Hitbox's to range. if (target.getObjectType() == GameObjectType.PlayerCharacter)
float range = agent.getRange(); DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true, false);
range += CombatManager.calcHitBox(target) + CombatManager.calcHitBox(agent); else
//if (target instanceof AbstractCharacter) DispatchMessage.sendToAllInRange(agent, msg);
// if (((AbstractCharacter)target).isMoving())
// range+= 5; }
return !(sl.distanceSquared2D(tl) > sqr(range)); public static void swingIsParry(Mob agent, AbstractWorldObject target, int animation) {
}catch(Exception e){
Logger.error( e.toString()); if (!target.isAlive())
return false; return;
}
TargetedActionMsg msg = new TargetedActionMsg(agent, animation, target, MBServerStatics.COMBAT_SEND_PARRY);
}
public static boolean inRange2D(AbstractWorldObject entity1, AbstractWorldObject entity2, double range){ if (target.getObjectType() == GameObjectType.PlayerCharacter)
return entity1.getLoc().distance2D(entity2.getLoc()) < range; DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true, false);
} else
public static void swingIsBlock(Mob agent,AbstractWorldObject target, int animation) { DispatchMessage.sendToAllInRange(agent, msg);
if (!target.isAlive()) }
return;
public static void swingIsDodge(Mob agent, AbstractWorldObject target, int animation) {
TargetedActionMsg msg = new TargetedActionMsg(agent,animation, target, MBServerStatics.COMBAT_SEND_BLOCK);
if (!target.isAlive())
if (target.getObjectType() == GameObjectType.PlayerCharacter) return;
DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true,false);
else TargetedActionMsg msg = new TargetedActionMsg(agent, animation, target, MBServerStatics.COMBAT_SEND_DODGE);
DispatchMessage.sendToAllInRange(agent,msg);
if (target.getObjectType() == GameObjectType.PlayerCharacter)
} DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true, false);
public static void swingIsParry(Mob agent,AbstractWorldObject target, int animation) { else
DispatchMessage.sendToAllInRange(agent, msg);
if (!target.isAlive()) }
return;
public static void swingIsDamage(Mob agent, AbstractWorldObject target, float damage, int animation) {
TargetedActionMsg msg = new TargetedActionMsg(agent,animation, target, MBServerStatics.COMBAT_SEND_PARRY); if (agent.isSiege() == true) {
damage = ThreadLocalRandom.current().nextInt(1000) + 1500;
if (target.getObjectType() == GameObjectType.PlayerCharacter) }
DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true,false); float trueDamage = damage;
else
DispatchMessage.sendToAllInRange(agent,msg); if (!target.isAlive())
return;
}
public static void swingIsDodge(Mob agent,AbstractWorldObject target, int animation) { if (AbstractWorldObject.IsAbstractCharacter(target))
trueDamage = ((AbstractCharacter) target).modifyHealth(-damage, agent, false);
if (!target.isAlive()) else if (target.getObjectType() == GameObjectType.Building)
return; trueDamage = ((Building) target).modifyHealth(-damage, agent);
TargetedActionMsg msg = new TargetedActionMsg(agent,animation, target, MBServerStatics.COMBAT_SEND_DODGE); //Don't send 0 damage kay thanx.
if (target.getObjectType() == GameObjectType.PlayerCharacter) if (trueDamage == 0)
DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true,false); return;
else
DispatchMessage.sendToAllInRange(agent,msg); TargetedActionMsg msg = new TargetedActionMsg(agent, target, damage, animation);
}
public static void swingIsDamage(Mob agent, AbstractWorldObject target, float damage, int animation){ if (target.getObjectType() == GameObjectType.PlayerCharacter)
if(agent.isSiege() == true){ DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true, false);
damage = ThreadLocalRandom.current().nextInt(1000) + 1500; else
} DispatchMessage.sendToAllInRange(agent, msg);
float trueDamage = damage;
//target = agent.getCombatTarget(); //check damage shields
if (!target.isAlive()) if (AbstractWorldObject.IsAbstractCharacter(target) && target.isAlive() && target.getObjectType() != GameObjectType.Mob)
return; CombatManager.handleDamageShields(agent, (AbstractCharacter) target, damage);
}
if (AbstractWorldObject.IsAbstractCharacter(target))
trueDamage = ((AbstractCharacter) target).modifyHealth(-damage, agent, false); public static boolean canSwing(Mob agent) {
else if (target.getObjectType() == GameObjectType.Building) return (agent.isAlive() && !agent.getBonuses().getBool(ModType.Stunned, SourceType.None));
trueDamage = ((Building) target).modifyHealth(-damage, agent); }
//Don't send 0 damage kay thanx. public static void swingIsMiss(Mob agent, AbstractWorldObject target, int animation) {
if (trueDamage == 0) TargetedActionMsg msg = new TargetedActionMsg(agent, target, 0f, animation);
return;
if (target.getObjectType() == GameObjectType.PlayerCharacter)
TargetedActionMsg msg = new TargetedActionMsg(agent,target, damage, animation); DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true, false);
else
if (target.getObjectType() == GameObjectType.PlayerCharacter) DispatchMessage.sendToAllInRange(agent, msg);
DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true,false);
else }
DispatchMessage.sendToAllInRange(agent,msg);
public static boolean triggerDefense(Mob agent, AbstractWorldObject target) {
//check damage shields int defenseScore = 0;
if(AbstractWorldObject.IsAbstractCharacter(target) && target.isAlive() && target.getObjectType() != GameObjectType.Mob) int attackScore = agent.getAtrHandOne();
CombatManager.handleDamageShields(agent,(AbstractCharacter)target, damage); switch (target.getObjectType()) {
} case PlayerCharacter:
public static boolean canSwing(Mob agent) { defenseScore = ((AbstractCharacter) target).getDefenseRating();
return (agent.isAlive() && !agent.getBonuses().getBool(ModType.Stunned, SourceType.None)); break;
} case Mob:
public static void swingIsMiss(Mob agent,AbstractWorldObject target, int animation) {
Mob mob = (Mob) target;
TargetedActionMsg msg = new TargetedActionMsg(agent,target, 0f, animation); if (mob.isSiege())
defenseScore = attackScore;
if (target.getObjectType() == GameObjectType.PlayerCharacter) break;
DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true,false); case Building:
else return false;
DispatchMessage.sendToAllInRange(agent,msg); }
} int hitChance;
public static boolean triggerDefense(Mob agent, AbstractWorldObject target) { if (attackScore > defenseScore || defenseScore == 0)
int defenseScore = 0; hitChance = 94;
int attackScore = agent.getAtrHandOne(); else if (attackScore == defenseScore && target.getObjectType() == GameObjectType.Mob)
switch (target.getObjectType()) { hitChance = 10;
case PlayerCharacter: else {
defenseScore = ((AbstractCharacter) target).getDefenseRating(); float dif = attackScore / defenseScore;
break; if (dif <= 0.8f)
case Mob: hitChance = 4;
else
Mob mob = (Mob)target; hitChance = ((int) (450 * (dif - 0.8f)) + 4);
if (mob.isSiege()) if (target.getObjectType() == GameObjectType.Building)
defenseScore = attackScore; hitChance = 100;
break; }
case Building: return ThreadLocalRandom.current().nextInt(100) > hitChance;
return false; }
}
public static boolean triggerBlock(Mob agent, AbstractWorldObject ac) {
return triggerPassive(agent, ac, "Block");
}
int hitChance;
if (attackScore > defenseScore || defenseScore == 0) public static boolean triggerParry(Mob agent, AbstractWorldObject ac) {
hitChance = 94; return triggerPassive(agent, ac, "Parry");
else if (attackScore == defenseScore && target.getObjectType() == GameObjectType.Mob) }
hitChance = 10;
else { public static boolean triggerDodge(Mob agent, AbstractWorldObject ac) {
float dif = attackScore / defenseScore; return triggerPassive(agent, ac, "Dodge");
if (dif <= 0.8f) }
hitChance = 4;
else public static boolean triggerPassive(Mob agent, AbstractWorldObject ac, String type) {
hitChance = ((int)(450 * (dif - 0.8f)) + 4); float chance = 0;
if (target.getObjectType() == GameObjectType.Building) if (AbstractWorldObject.IsAbstractCharacter(ac))
hitChance = 100; chance = ((AbstractCharacter) ac).getPassiveChance(type, agent.getLevel(), true);
}
return ThreadLocalRandom.current().nextInt(100) > hitChance; if (chance > 75f)
} chance = 75f;
public static boolean triggerBlock(Mob agent,AbstractWorldObject ac) { if (agent.isSiege() && AbstractWorldObject.IsAbstractCharacter(ac))
return triggerPassive(agent,ac, "Block"); chance = 100;
}
public static boolean triggerParry(Mob agent,AbstractWorldObject ac) { return ThreadLocalRandom.current().nextInt(100) < chance;
return triggerPassive(agent,ac, "Parry"); }
}
public static boolean triggerDodge(Mob agent,AbstractWorldObject ac) { public static void combatCycle(Mob agent, AbstractWorldObject target, boolean mainHand, ItemBase wb) {
return triggerPassive(agent,ac, "Dodge");
} if (!agent.isAlive() || !target.isAlive())
public static boolean triggerPassive(Mob agent,AbstractWorldObject ac, String type) { return;
float chance = 0;
if (AbstractWorldObject.IsAbstractCharacter(ac)) if (target.getObjectType() == GameObjectType.PlayerCharacter)
chance = ((AbstractCharacter)ac).getPassiveChance(type, agent.getLevel(), true); if (!((PlayerCharacter) target).isActive())
return;
if (chance > 75f)
chance = 75f; int anim = 75;
if (agent.isSiege() && AbstractWorldObject.IsAbstractCharacter(ac)) float speed;
chance = 100;
if (mainHand)
return ThreadLocalRandom.current().nextInt(100) < chance; speed = agent.getSpeedHandOne();
} else
public static void combatCycle(Mob agent,AbstractWorldObject target, boolean mainHand, ItemBase wb) { speed = agent.getSpeedHandTwo();
if (!agent.isAlive() || !target.isAlive()) return; DamageType dt = DamageType.Crush;
if (target.getObjectType() == GameObjectType.PlayerCharacter) if (agent.isSiege())
if (!((PlayerCharacter)target).isActive()) dt = DamageType.Siege;
return; if (wb != null) {
anim = CombatManager.getSwingAnimation(wb, null, mainHand);
int anim = 75; dt = wb.getDamageType();
float speed = 30f; } else if (!mainHand)
if (mainHand) return;
speed = agent.getSpeedHandOne();
else Resists res = null;
speed = agent.getSpeedHandTwo(); PlayerBonuses bonus = null;
DamageType dt = DamageType.Crush;
if (agent.isSiege()) switch (target.getObjectType()) {
dt = DamageType.Siege; case Building:
if (wb != null) { res = ((Building) target).getResists();
anim = CombatManager.getSwingAnimation(wb, null,mainHand); break;
dt = wb.getDamageType(); case PlayerCharacter:
} else if (!mainHand) res = ((PlayerCharacter) target).getResists();
return; bonus = ((PlayerCharacter) target).getBonuses();
Resists res = null; break;
PlayerBonuses bonus = null; case Mob:
switch(target.getObjectType()){ Mob mob = (Mob) target;
case Building: res = mob.getResists();
res = ((Building)target).getResists(); bonus = ((Mob) target).getBonuses();
break; break;
case PlayerCharacter: }
res = ((PlayerCharacter)target).getResists();
bonus = ((PlayerCharacter)target).getBonuses(); //must not be immune to all or immune to attack
break;
case Mob: if (bonus != null && !bonus.getBool(ModType.NoMod, SourceType.ImmuneToAttack))
Mob mob = (Mob)target; if (res != null && (res.immuneToAll() || res.immuneToAttacks() || res.immuneTo(dt)))
res = mob.getResists(); return;
bonus = ((Mob)target).getBonuses();
break; int passiveAnim = CombatManager.getSwingAnimation(wb, null, mainHand);
} if (canSwing(agent)) {
if (triggerDefense(agent, target)) {
//must not be immune to all or immune to attack swingIsMiss(agent, target, passiveAnim);
return;
if (bonus != null && !bonus.getBool(ModType.NoMod, SourceType.ImmuneToAttack)) } else if (triggerDodge(agent, target)) {
if (res != null &&(res.immuneToAll() || res.immuneToAttacks() || res.immuneTo(dt))) swingIsDodge(agent, target, passiveAnim);
return; return;
} else if (triggerParry(agent, target)) {
int passiveAnim = CombatManager.getSwingAnimation(wb, null,mainHand); swingIsParry(agent, target, passiveAnim);
if(canSwing(agent)) {
if(triggerDefense(agent,target)) { return;
swingIsMiss(agent, target, passiveAnim); } else if (triggerBlock(agent, target)) {
return; swingIsBlock(agent, target, passiveAnim);
} return;
else if(triggerDodge(agent,target)) { }
swingIsDodge(agent, target, passiveAnim); if (agent.getEquip().get(1) != null && agent.getEquip().get(2) != null && agent.getEquip().get(2).getItemBase().isShield() == false) {
return; //mob is duel wielding and should conduct an attack for each hand
} ItemBase weapon1 = agent.getEquip().get(1).getItemBase();
else if (triggerParry(agent, target)){ double range1 = getMaxDmg(weapon1.getMinDamage(), agent, weapon1) - getMinDmg(weapon1.getMinDamage(), agent, weapon1);
swingIsParry(agent, target, passiveAnim); double damage1 = getMinDmg(weapon1.getMinDamage(), agent, weapon1) + ((ThreadLocalRandom.current().nextFloat() * range1) + (ThreadLocalRandom.current().nextFloat() * range1)) / 2;
swingIsDamage(agent, target, (float) damage1, CombatManager.getSwingAnimation(weapon1, null, true));
return; ItemBase weapon2 = agent.getEquip().get(2).getItemBase();
} double range2 = getMaxDmg(weapon2.getMinDamage(), agent, weapon2) - getMinDmg(weapon2.getMinDamage(), agent, weapon2);
else if(triggerBlock(agent,target)) { double damage2 = getMinDmg(weapon2.getMinDamage(), agent, weapon2) + ((ThreadLocalRandom.current().nextFloat() * range2) + (ThreadLocalRandom.current().nextFloat() * range2)) / 2;
swingIsBlock(agent, target, passiveAnim); swingIsDamage(agent, target, (float) damage2, CombatManager.getSwingAnimation(weapon1, null, false));
return; } else {
} swingIsDamage(agent, target, determineDamage(agent), anim);
if(agent.getEquip().get(1) != null && agent.getEquip().get(2) != null && agent.getEquip().get(2).getItemBase().isShield() == false){ }
//mob is duel wielding and should conduct an attack for each hand
ItemBase weapon1 = agent.getEquip().get(1).getItemBase(); if (agent.getWeaponPower() != null)
double range1 = getMaxDmg(weapon1.getMinDamage(),agent,weapon1) - getMinDmg(weapon1.getMinDamage(),agent,weapon1); agent.getWeaponPower().attack(target, MBServerStatics.ONE_MINUTE);
double damage1 = getMinDmg(weapon1.getMinDamage(),agent,weapon1) + ((ThreadLocalRandom.current().nextFloat() * range1) + (ThreadLocalRandom.current().nextFloat() * range1)) / 2; }
swingIsDamage(agent,target, (float) damage1, CombatManager.getSwingAnimation(weapon1, null,true));
ItemBase weapon2 = agent.getEquip().get(2).getItemBase(); if (target.getObjectType().equals(GameObjectType.PlayerCharacter)) {
double range2 = getMaxDmg(weapon2.getMinDamage(),agent,weapon2) - getMinDmg(weapon2.getMinDamage(),agent,weapon2); PlayerCharacter player = (PlayerCharacter) target;
double damage2 = getMinDmg(weapon2.getMinDamage(),agent,weapon2) + ((ThreadLocalRandom.current().nextFloat() * range2) + (ThreadLocalRandom.current().nextFloat() * range2)) / 2;
swingIsDamage(agent,target, (float) damage2, CombatManager.getSwingAnimation(weapon1, null,false)); if (player.getDebug(64))
} else{ ChatManager.chatSayInfo(player, "Debug Combat: Mob UUID " + agent.getObjectUUID() + " || Building ID = " + agent.getBuildingID() + " || Floor = " + agent.getInFloorID() + " || Level = " + agent.getInBuilding());//combat debug
swingIsDamage(agent,target, determineDamage(agent), anim); }
}
//SIEGE MONSTERS DO NOT ATTACK GUARDSs
if (agent.getWeaponPower() != null) if (target.getObjectType() == GameObjectType.Mob)
agent.getWeaponPower().attack(target, MBServerStatics.ONE_MINUTE); if (((Mob) target).isSiege())
} return;
if (target.getObjectType().equals(GameObjectType.PlayerCharacter)){ //handle the retaliate
PlayerCharacter player = (PlayerCharacter)target;
if (player.getDebug(64)){ if (AbstractWorldObject.IsAbstractCharacter(target))
ChatManager.chatSayInfo(player, "Debug Combat: Mob UUID " + agent.getObjectUUID() + " || Building ID = " + agent.getBuildingID() + " || Floor = " + agent.getInFloorID() + " || Level = " + agent.getInBuilding() );//combat debug CombatManager.handleRetaliate((AbstractCharacter) target, agent);
}
} if (target.getObjectType() == GameObjectType.Mob) {
Mob targetMob = (Mob) target;
//SIEGE MONSTERS DO NOT ATTACK GUARDSs if (targetMob.isSiege())
if (target.getObjectType() == GameObjectType.Mob) return;
if (((Mob)target).isSiege()) }
return;
}
//handle the retaliate
public static float determineDamage(Mob agent) {
if (AbstractWorldObject.IsAbstractCharacter(target))
CombatManager.handleRetaliate((AbstractCharacter)target, agent); //early exit for null
if (target.getObjectType() == GameObjectType.Mob){ if (agent == null)
Mob targetMob = (Mob)target; return 0;
if (targetMob.isSiege())
return; AbstractWorldObject target = agent.getCombatTarget();
}
if (target == null)
return 0;
}
public static float determineDamage(Mob agent) { float damage = 0;
if(agent == null){
//early exit for null DamageType dt = getDamageType(agent);
return 0; if (agent.isSummonedPet() == true || agent.isPet() == true || agent.isNecroPet() == true) {
} damage = calculatePetDamage(agent);
AbstractWorldObject target = agent.getCombatTarget(); } else if (agent.isPlayerGuard() == true) {
if(target == null){ //damage = calculateGuardDamage(agent);
//early exit for null target damage = calculateMobDamage(agent);
return 0; } else if (agent.getLevel() > 80) {
} damage = calculateEpicDamage(agent);
float damage = 0; } else {
DamageType dt = getDamageType(agent); damage = calculateMobDamage(agent);
if(agent.isSummonedPet() == true || agent.isPet() == true || agent.isNecroPet() == true) { }
damage = calculatePetDamage(agent); if (AbstractWorldObject.IsAbstractCharacter(target)) {
}else if(agent.isPlayerGuard() == true){ if (((AbstractCharacter) target).isSit()) {
//damage = calculateGuardDamage(agent); damage *= 2.5f; //increase damage if sitting
damage = calculateMobDamage(agent); }
}else if (agent.getLevel() > 80) { return (int) (((AbstractCharacter) target).getResists().getResistedDamage(agent, (AbstractCharacter) target, dt, damage, 0));
damage = calculateEpicDamage(agent); }
} else{ if (target.getObjectType() == GameObjectType.Building) {
damage = calculateMobDamage(agent); Building building = (Building) target;
} Resists resists = building.getResists();
if (AbstractWorldObject.IsAbstractCharacter(target)) { return (int) ((damage * (1 - (resists.getResist(dt, 0) / 100))));
if (((AbstractCharacter) target).isSit()) { }
damage *= 2.5f; //increase damage if sitting return damage;
} }
return (int) (((AbstractCharacter) target).getResists().getResistedDamage(agent, (AbstractCharacter) target, dt, damage, 0));
} public static DamageType getDamageType(Mob agent) {
if (target.getObjectType() == GameObjectType.Building) { DamageType dt = DamageType.Crush;
Building building = (Building) target; if (agent.getEquip().get(1) != null) {
Resists resists = building.getResists(); return agent.getEquip().get(1).getItemBase().getDamageType();
return (int) ((damage * (1 - (resists.getResist(dt, 0) / 100)))); }
} if (agent.getEquip().get(2) != null && agent.getEquip().get(2).getItemBase().isShield() == false) {
return damage; return agent.getEquip().get(2).getItemBase().getDamageType();
} }
public static DamageType getDamageType(Mob agent){ return dt;
DamageType dt = DamageType.Crush; }
if(agent.getEquip().get(1) != null ){
return agent.getEquip().get(1).getItemBase().getDamageType(); public static int calculatePetDamage(Mob agent) {
} //damage calc for pet
if(agent.getEquip().get(2) != null && agent.getEquip().get(2).getItemBase().isShield() == false){ float range;
return agent.getEquip().get(2).getItemBase().getDamageType(); float damage;
} float min = 40;
return dt; float max = 60;
} AbstractWorldObject target = agent.getCombatTarget();
public static int calculatePetDamage(Mob agent) { float dmgMultiplier = 1 + agent.getBonuses().getFloatPercentAll(ModType.MeleeDamageModifier, SourceType.None);
//damage calc for pet double minDmg = getMinDmg(min, agent, null);
float range; double maxDmg = getMaxDmg(max, agent, null);
float damage; dmgMultiplier += agent.getLevel() / 10;
float min = 40; range = (float) (maxDmg - minDmg);
float max = 60; damage = min + ((ThreadLocalRandom.current().nextFloat() * range) + (ThreadLocalRandom.current().nextFloat() * range)) / 2;
AbstractWorldObject target = agent.getCombatTarget(); return (int) (damage * dmgMultiplier);
float dmgMultiplier = 1 + agent.getBonuses().getFloatPercentAll(ModType.MeleeDamageModifier, SourceType.None); }
float str = agent.getStatStrCurrent();
float dex = agent.getStatDexCurrent(); public static int calculateGuardDamage(Mob agent) {
double minDmg = getMinDmg(min,agent, null); //damage calc for guard
double maxDmg = getMaxDmg(max,agent, null); ItemBase weapon = agent.getEquip().get(1).getItemBase();
dmgMultiplier += agent.getLevel() / 10; AbstractWorldObject target = agent.getCombatTarget();
range = (float) (maxDmg - minDmg);
damage = min + ((ThreadLocalRandom.current().nextFloat() * range) + (ThreadLocalRandom.current().nextFloat() * range)) / 2; float dmgMultiplier = 1 + agent.getBonuses().getFloatPercentAll(ModType.MeleeDamageModifier, SourceType.None);
return (int) (damage * dmgMultiplier);
} double minDmg = weapon.getMinDamage();
public static int calculateGuardDamage(Mob agent){ double maxDmg = weapon.getMaxDamage();
//damage calc for guard double min = getMinDmg(minDmg, agent, weapon);
ItemBase weapon = agent.getEquip().get(1).getItemBase(); double max = getMaxDmg(maxDmg, agent, weapon);
AbstractWorldObject target = agent.getCombatTarget();
float dmgMultiplier = 1 + agent.getBonuses().getFloatPercentAll(ModType.MeleeDamageModifier, SourceType.None); DamageType dt = weapon.getDamageType();
double minDmg = weapon.getMinDamage();
double maxDmg = weapon.getMaxDamage(); double range = max - min;
float str = agent.getStatStrCurrent(); double damage = min + ((ThreadLocalRandom.current().nextFloat() * range) + (ThreadLocalRandom.current().nextFloat() * range)) / 2;
float dex = agent.getStatDexCurrent();
double min = getMinDmg(minDmg,agent, weapon); if (AbstractWorldObject.IsAbstractCharacter(target))
double max = getMaxDmg(maxDmg,agent, weapon); if (((AbstractCharacter) target).isSit())
DamageType dt = weapon.getDamageType(); damage *= 2.5f; //increase damage if sitting
double range = max - min; if (AbstractWorldObject.IsAbstractCharacter(target))
double damage = min + ((ThreadLocalRandom.current().nextFloat() * range) + (ThreadLocalRandom.current().nextFloat() * range)) / 2; return (int) (((AbstractCharacter) target).getResists().getResistedDamage(agent, (AbstractCharacter) target, dt, (float) damage, 0) * dmgMultiplier);
if (AbstractWorldObject.IsAbstractCharacter(target)) return 0;
if (((AbstractCharacter) target).isSit()) }
damage *= 2.5f; //increase damage if sitting
if (AbstractWorldObject.IsAbstractCharacter(target)) public static int calculateEpicDamage(Mob agent) {
return (int) (((AbstractCharacter) target).getResists().getResistedDamage((AbstractCharacter) agent, (AbstractCharacter) target, dt, (float) damage, 0) * dmgMultiplier); //handle r8 mob damage
return 0; DamageType dt = DamageType.Crush;
} AbstractWorldObject target = agent.getCombatTarget();
public static int calculateEpicDamage(Mob agent){ float dmgMultiplier = 1 + agent.getBonuses().getFloatPercentAll(ModType.MeleeDamageModifier, SourceType.None);
//handle r8 mob damage if (agent.getEquip().get(1).getItemBase() != null) {
DamageType dt = DamageType.Crush; dt = agent.getEquip().get(1).getItemBase().getDamageType();
AbstractWorldObject target = agent.getCombatTarget(); } else if (agent.getEquip().get(2).getItemBase() != null && agent.getEquip().get(2).getItemBase().isShield() == false) {
float dmgMultiplier = 1 + agent.getBonuses().getFloatPercentAll(ModType.MeleeDamageModifier, SourceType.None); dt = agent.getEquip().get(2).getItemBase().getDamageType();
if (agent.getEquip().get(1).getItemBase() != null) { }
dt = agent.getEquip().get(1).getItemBase().getDamageType(); double min = agent.getMobBase().getMinDmg();
} else if(agent.getEquip().get(2).getItemBase() != null && agent.getEquip().get(2).getItemBase().isShield() == false){ double max = agent.getMobBase().getMaxDmg();
dt = agent.getEquip().get(2).getItemBase().getDamageType(); double range = max - min;
} double damage = min + ((ThreadLocalRandom.current().nextFloat() * range) + (ThreadLocalRandom.current().nextFloat() * range)) / 2;
double min = agent.getMobBase().getMinDmg(); return (int) (((AbstractCharacter) target).getResists().getResistedDamage(agent, (AbstractCharacter) target, dt, (float) damage, 0) * dmgMultiplier);
double max = agent.getMobBase().getMaxDmg(); }
double range = max - min;
double damage = min + ((ThreadLocalRandom.current().nextFloat() * range) + (ThreadLocalRandom.current().nextFloat() * range)) / 2; public static int calculateMobDamage(Mob agent) {
return (int) (((AbstractCharacter) target).getResists().getResistedDamage((AbstractCharacter) agent, (AbstractCharacter) target, dt, (float) damage, 0) * dmgMultiplier); ItemBase weapon = null;
} double minDmg;
public static int calculateMobDamage(Mob agent){ double maxDmg;
ItemBase weapon = null; DamageType dt;
double minDmg;
double maxDmg; //main hand or offhand damage
DamageType dt;
if(agent.getEquip().get(1) != null){ if (agent.getEquip().get(1) != null)
//mainhand damage weapon = agent.getEquip().get(1).getItemBase();
weapon = agent.getEquip().get(1).getItemBase(); else if (agent.getEquip().get(2) != null)
} else if(agent.getEquip().get(2) != null){ weapon = agent.getEquip().get(2).getItemBase();
//offhand damage
weapon = agent.getEquip().get(2).getItemBase(); if (weapon != null) {
} minDmg = getMinDmg(weapon.getMinDamage(), agent, weapon);
if(weapon != null){ maxDmg = getMaxDmg(weapon.getMaxDamage(), agent, weapon);
minDmg = getMinDmg(weapon.getMinDamage(),agent,weapon); dt = weapon.getDamageType();
maxDmg = getMaxDmg(weapon.getMaxDamage(),agent, weapon); } else {
dt = weapon.getDamageType(); minDmg = agent.getMobBase().getDamageMin();
}else{ maxDmg = agent.getMobBase().getDamageMax();
minDmg = agent.getMobBase().getDamageMin(); dt = DamageType.Crush;
maxDmg = agent.getMobBase().getDamageMax(); }
dt = DamageType.Crush;
} AbstractWorldObject target = agent.getCombatTarget();
AbstractWorldObject target = agent.getCombatTarget();
float dmgMultiplier = 1 + agent.getBonuses().getFloatPercentAll(ModType.MeleeDamageModifier, SourceType.None); float dmgMultiplier = 1 + agent.getBonuses().getFloatPercentAll(ModType.MeleeDamageModifier, SourceType.None);
double range = maxDmg - minDmg; double range = maxDmg - minDmg;
double damage = minDmg + ((ThreadLocalRandom.current().nextFloat() * range) + (ThreadLocalRandom.current().nextFloat() * range)) / 2; double damage = minDmg + ((ThreadLocalRandom.current().nextFloat() * range) + (ThreadLocalRandom.current().nextFloat() * range)) / 2;
if (AbstractWorldObject.IsAbstractCharacter(target))
if (((AbstractCharacter) target).isSit()) if (AbstractWorldObject.IsAbstractCharacter(target))
damage *= 2.5f; //increase damage if sitting if (((AbstractCharacter) target).isSit())
if (AbstractWorldObject.IsAbstractCharacter(target)) damage *= 2.5f; //increase damage if sitting
return (int) (((AbstractCharacter) target).getResists().getResistedDamage((AbstractCharacter) agent, (AbstractCharacter) target, dt, (float) damage, 0) * dmgMultiplier); if (AbstractWorldObject.IsAbstractCharacter(target))
return 0; return (int) (((AbstractCharacter) target).getResists().getResistedDamage(agent, (AbstractCharacter) target, dt, (float) damage, 0) * dmgMultiplier);
} return 0;
public static double getMinDmg(double min, Mob agent, ItemBase weapon){ }
int primary = agent.getStatStrCurrent();
int secondary = agent.getStatDexCurrent(); public static double getMinDmg(double min, Mob agent, ItemBase weapon) {
int focusLevel = 0;
int masteryLevel = 0; int primary = agent.getStatStrCurrent();
if(weapon != null) { int secondary = agent.getStatDexCurrent();
if (weapon.isStrBased() == true) { int focusLevel = 0;
primary = agent.getStatStrCurrent(); int masteryLevel = 0;
secondary = agent.getStatDexCurrent();
} else { if (weapon != null) {
primary = agent.getStatDexCurrent(); if (weapon.isStrBased() == true) {
secondary = agent.getStatStrCurrent(); primary = agent.getStatStrCurrent();
if (agent.getSkills().containsKey(weapon.getSkillRequired())) { secondary = agent.getStatDexCurrent();
focusLevel = (int) agent.getSkills().get(weapon.getSkillRequired()).getModifiedAmount(); } else {
} primary = agent.getStatDexCurrent();
if (agent.getSkills().containsKey(weapon.getMastery())) { secondary = agent.getStatStrCurrent();
masteryLevel = (int) agent.getSkills().get(weapon.getMastery()).getModifiedAmount(); if (agent.getSkills().containsKey(weapon.getSkillRequired())) {
} focusLevel = (int) agent.getSkills().get(weapon.getSkillRequired()).getModifiedAmount();
} }
} if (agent.getSkills().containsKey(weapon.getMastery())) {
return min * (pow(0.0048*primary +.049*(primary-0.75),0.5) + pow(0.0066*secondary + 0.064*(secondary-0.75),0.5) + + 0.01*(focusLevel + masteryLevel)); masteryLevel = (int) agent.getSkills().get(weapon.getMastery()).getModifiedAmount();
} }
public static double getMaxDmg(double max, Mob agent, ItemBase weapon){ }
int primary = agent.getStatStrCurrent(); }
int secondary = agent.getStatDexCurrent(); return min * (pow(0.0048 * primary + .049 * (primary - 0.75), 0.5) + pow(0.0066 * secondary + 0.064 * (secondary - 0.75), 0.5) + +0.01 * (focusLevel + masteryLevel));
int focusLevel = 0; }
int masteryLevel = 0;
if (weapon != null) { public static double getMaxDmg(double max, Mob agent, ItemBase weapon) {
if(weapon.isStrBased() == true){
primary = agent.getStatStrCurrent(); int primary = agent.getStatStrCurrent();
secondary = agent.getStatDexCurrent(); int secondary = agent.getStatDexCurrent();
} int focusLevel = 0;
else{ int masteryLevel = 0;
primary = agent.getStatDexCurrent();
secondary = agent.getStatStrCurrent(); if (weapon != null) {
}
if (weapon.isStrBased() == true) {
if(agent.getSkills().containsKey(weapon.getSkillRequired())) { primary = agent.getStatStrCurrent();
focusLevel = (int) agent.getSkills().get(weapon.getSkillRequired()).getModifiedAmount(); secondary = agent.getStatDexCurrent();
} } else {
if(agent.getSkills().containsKey(weapon.getSkillRequired())) { primary = agent.getStatDexCurrent();
masteryLevel = (int) agent.getSkills().get(weapon.getMastery()).getModifiedAmount(); secondary = agent.getStatStrCurrent();
} }
}
return max * (pow(0.0124*primary + 0.118*(primary -0.75),0.5) + pow(0.0022*secondary + 0.028*(secondary-0.75),0.5) + 0.0075*(focusLevel + masteryLevel)); if (agent.getSkills().containsKey(weapon.getSkillRequired()))
} focusLevel = (int) agent.getSkills().get(weapon.getSkillRequired()).getModifiedAmount();
public static boolean RunAIRandom(){
int random = ThreadLocalRandom.current().nextInt(4); if (agent.getSkills().containsKey(weapon.getSkillRequired()))
masteryLevel = (int) agent.getSkills().get(weapon.getMastery()).getModifiedAmount();
return random == 0;
} }
return max * (pow(0.0124 * primary + 0.118 * (primary - 0.75), 0.5) + pow(0.0022 * secondary + 0.028 * (secondary - 0.75), 0.5) + 0.0075 * (focusLevel + masteryLevel));
}
} }

374
src/engine/ai/utilities/MovementUtilities.java

@ -7,7 +7,6 @@
// www.magicbane.com // www.magicbane.com
package engine.ai.utilities; package engine.ai.utilities;
import engine.Enum; import engine.Enum;
@ -30,179 +29,176 @@ import static engine.math.FastMath.sqrt;
public class MovementUtilities { public class MovementUtilities {
public static boolean inRangeOfBindLocation(Mob agent){ public static boolean inRangeOfBindLocation(Mob agent) {
if (agent.isPlayerGuard()) {
if (agent.isPlayerGuard()){
Mob guardCaptain = null;
Mob guardCaptain = null; if (agent.getContract() != null)
if (agent.getContract() != null) guardCaptain = agent;
guardCaptain = agent; else
else guardCaptain = (Mob) agent.npcOwner;
guardCaptain = (Mob) agent.npcOwner;
if (guardCaptain != null) {
if (guardCaptain != null){
Building barracks = guardCaptain.building; Building barracks = guardCaptain.building;
if (barracks != null){
City city = barracks.getCity();
if (city != null){
Building tol = city.getTOL();
//Guards recall distance = 814.
if (tol != null){
if (agent.getLoc().distanceSquared2D(tol.getLoc()) > sqr(Enum.CityBoundsType.ZONE.extents)) {
return false;
}
}
}
}
}
return true;
}
Vector3fImmutable sl = new Vector3fImmutable(agent.getLoc().getX(), 0, agent.getLoc().getZ()); if (barracks != null) {
Vector3fImmutable tl = new Vector3fImmutable(agent.getTrueBindLoc().x,0,agent.getTrueBindLoc().z); City city = barracks.getCity();
if (city != null) {
Building tol = city.getTOL();
//Guards recall distance = 814.
if (tol != null) {
return !(agent.getLoc().distanceSquared2D(tol.getLoc()) > sqr(Enum.CityBoundsType.ZONE.extents));
}
}
}
}
float distanceSquaredToTarget = sl.distanceSquared2D(tl); //distance to center of target return true;
float zoneRange = 250; }
if (agent.getParentZone() != null){ Vector3fImmutable sl = new Vector3fImmutable(agent.getLoc().getX(), 0, agent.getLoc().getZ());
if (agent.getParentZone().getBounds() != null) Vector3fImmutable tl = new Vector3fImmutable(agent.getTrueBindLoc().x, 0, agent.getTrueBindLoc().z);
zoneRange = agent.getParentZone().getBounds().getHalfExtents().x * 2;
}
if (zoneRange > 300) float distanceSquaredToTarget = sl.distanceSquared2D(tl); //distance to center of target
zoneRange = 300; float zoneRange = 250;
if (agent.getSpawnRadius() > zoneRange)
zoneRange = agent.getSpawnRadius();
return distanceSquaredToTarget < sqr(MBServerStatics.AI_DROP_AGGRO_RANGE + zoneRange); if (agent.getParentZone() != null) {
if (agent.getParentZone().getBounds() != null)
zoneRange = agent.getParentZone().getBounds().getHalfExtents().x * 2;
}
} if (zoneRange > 300)
zoneRange = 300;
public static boolean inRangeToAggro(Mob agent,PlayerCharacter target){ if (agent.getSpawnRadius() > zoneRange)
zoneRange = agent.getSpawnRadius();
Vector3fImmutable sl = agent.getLoc();
Vector3fImmutable tl =target.getLoc();
float distanceSquaredToTarget = sl.distanceSquared2D(tl) - sqr(agent.calcHitBox() + target.calcHitBox()); //distance to center of target return distanceSquaredToTarget < sqr(MBServerStatics.AI_DROP_AGGRO_RANGE + zoneRange);
float range = MBServerStatics.AI_BASE_AGGRO_RANGE;
if (agent.isPlayerGuard()) }
range = 150;
return distanceSquaredToTarget < sqr(range); public static boolean inRangeToAggro(Mob agent, PlayerCharacter target) {
} Vector3fImmutable sl = agent.getLoc();
Vector3fImmutable tl = target.getLoc();
public static boolean inRangeDropAggro(Mob agent,PlayerCharacter target){ float distanceSquaredToTarget = sl.distanceSquared2D(tl) - sqr(agent.calcHitBox() + target.calcHitBox()); //distance to center of target
float range = MBServerStatics.AI_BASE_AGGRO_RANGE;
Vector3fImmutable sl = agent.getLoc(); if (agent.isPlayerGuard())
Vector3fImmutable tl = target.getLoc(); range = 150;
float distanceSquaredToTarget = sl.distanceSquared2D(tl) - sqr(agent.calcHitBox() + target.calcHitBox()); //distance to center of target return distanceSquaredToTarget < sqr(range);
float range = agent.getRange() + 150; }
if (range > 200) public static boolean inRangeDropAggro(Mob agent, PlayerCharacter target) {
range = 200;
Vector3fImmutable sl = agent.getLoc();
Vector3fImmutable tl = target.getLoc();
return distanceSquaredToTarget < sqr(range); float distanceSquaredToTarget = sl.distanceSquared2D(tl) - sqr(agent.calcHitBox() + target.calcHitBox()); //distance to center of target
} float range = agent.getRange() + 150;
public static Vector3fImmutable GetMoveLocation(Mob aiAgent, AbstractCharacter aggroTarget){ if (range > 200)
range = 200;
// Player isnt moving and neither is mob. Just return
// the mobile's current location. Ain't goin nowhere!
// *** Refactor: Check to ensure methods calling us
// all don't sent move messages when not moving.
if ((aggroTarget.isMoving() == false)) return distanceSquaredToTarget < sqr(range);
return aggroTarget.getLoc();
if (aggroTarget.getEndLoc().x != 0){ }
float aggroTargetDistanceSquared = aggroTarget.getLoc().distanceSquared2D(aggroTarget.getEndLoc()); public static Vector3fImmutable GetMoveLocation(Mob aiAgent, AbstractCharacter aggroTarget) {
float aiAgentDistanceSquared = aiAgent.getLoc().distanceSquared2D(aggroTarget.getEndLoc());
if (aiAgentDistanceSquared >= aggroTargetDistanceSquared) // Player isnt moving and neither is mob. Just return
return aggroTarget.getEndLoc(); // the mobile's current location. Ain't goin nowhere!
else{ // *** Refactor: Check to ensure methods calling us
float distanceToMove = sqrt(aggroTargetDistanceSquared + aiAgentDistanceSquared) *.5f; // all don't sent move messages when not moving.
return aggroTarget.getFaceDir().scaleAdd(distanceToMove, aggroTarget.getLoc()); if ((aggroTarget.isMoving() == false))
return aggroTarget.getLoc();
} if (aggroTarget.getEndLoc().x != 0) {
}
// One of us is moving so let's calculate our destination loc for this float aggroTargetDistanceSquared = aggroTarget.getLoc().distanceSquared2D(aggroTarget.getEndLoc());
// simulation frame. We will simply project our position onto the float aiAgentDistanceSquared = aiAgent.getLoc().distanceSquared2D(aggroTarget.getEndLoc());
// character's movement vector and return the closest point.
return aiAgent.getLoc().ClosestPointOnLine(aggroTarget.getLoc(), aggroTarget.getEndLoc()); if (aiAgentDistanceSquared >= aggroTargetDistanceSquared)
} return aggroTarget.getEndLoc();
else {
float distanceToMove = sqrt(aggroTargetDistanceSquared + aiAgentDistanceSquared) * .5f;
public static void moveToLocation(Mob agent,Vector3fImmutable newLocation, float offset){ return aggroTarget.getFaceDir().scaleAdd(distanceToMove, aggroTarget.getLoc());
try {
//don't move farther than 30 units from player.
if (offset > 30)
offset = 30;
Vector3fImmutable newLoc = Vector3fImmutable.getRandomPointInCircle(newLocation, offset);
}
}
agent.setFaceDir(newLoc.subtract2D(agent.getLoc()).normalize()); // One of us is moving so let's calculate our destination loc for this
// simulation frame. We will simply project our position onto the
aiMove(agent,newLoc,false); // character's movement vector and return the closest point.
} catch (Exception e) {
Logger.error( e.toString());
}
}
return aiAgent.getLoc().ClosestPointOnLine(aggroTarget.getLoc(), aggroTarget.getEndLoc());
}
public static void moveToLocation(Mob agent, Vector3fImmutable newLocation, float offset) {
try {
public static boolean canMove(Mob agent) { //don't move farther than 30 units from player.
if (agent.getMobBase() != null && Enum.MobFlagType.SENTINEL.elementOf(agent.getMobBase().getFlags())) if (offset > 30)
return false; offset = 30;
Vector3fImmutable newLoc = Vector3fImmutable.getRandomPointInCircle(newLocation, offset);
return (agent.isAlive() && !agent.getBonuses().getBool(ModType.Stunned,SourceType.None) && !agent.getBonuses().getBool(ModType.CannotMove, SourceType.None));
}
public static Vector3fImmutable randomPatrolLocation(Mob agent,Vector3fImmutable center, float radius){ agent.setFaceDir(newLoc.subtract2D(agent.getLoc()).normalize());
//Determing where I want to move. aiMove(agent, newLoc, false);
return new Vector3fImmutable((center.x - radius) + ((ThreadLocalRandom.current().nextFloat()+.1f*2)*radius), } catch (Exception e) {
center.y, Logger.error(e.toString());
(center.z - radius) + ((ThreadLocalRandom.current().nextFloat()+.1f *2)*radius)); }
} }
public static Long estimateMovementTime(Mob agent) {
if(agent.getEndLoc().x == 0 && agent.getEndLoc().y == 0)
return 0L;
return (long) ((agent.getLoc().distance2D(agent.getEndLoc())*1000)/agent.getSpeed());
}
public static void aiMove(Mob agent,Vector3fImmutable vect, boolean isWalking) { public static boolean canMove(Mob agent) {
if (agent.getMobBase() != null && Enum.MobFlagType.SENTINEL.elementOf(agent.getMobBase().getFlags()))
return false;
//update our walk/run state. return (agent.isAlive() && !agent.getBonuses().getBool(ModType.Stunned, SourceType.None) && !agent.getBonuses().getBool(ModType.CannotMove, SourceType.None));
if (isWalking && !agent.isWalk()){ }
agent.setWalkMode(true);
MovementManager.sendRWSSMsg(agent);
}else if(!isWalking && agent.isWalk()){
agent.setWalkMode(false);
MovementManager.sendRWSSMsg(agent);
}
MoveToPointMsg msg = new MoveToPointMsg(); public static Vector3fImmutable randomPatrolLocation(Mob agent, Vector3fImmutable center, float radius) {
//Determing where I want to move.
return new Vector3fImmutable((center.x - radius) + ((ThreadLocalRandom.current().nextFloat() + .1f * 2) * radius),
center.y,
(center.z - radius) + ((ThreadLocalRandom.current().nextFloat() + .1f * 2) * radius));
}
public static Long estimateMovementTime(Mob agent) {
if (agent.getEndLoc().x == 0 && agent.getEndLoc().y == 0)
return 0L;
return (long) ((agent.getLoc().distance2D(agent.getEndLoc()) * 1000) / agent.getSpeed());
}
public static void aiMove(Mob agent, Vector3fImmutable vect, boolean isWalking) {
//update our walk/run state.
if (isWalking && !agent.isWalk()) {
agent.setWalkMode(true);
MovementManager.sendRWSSMsg(agent);
} else if (!isWalking && agent.isWalk()) {
agent.setWalkMode(false);
MovementManager.sendRWSSMsg(agent);
}
MoveToPointMsg msg = new MoveToPointMsg();
// Regions currentRegion = Mob.InsideBuildingRegion(agent); // Regions currentRegion = Mob.InsideBuildingRegion(agent);
@ -225,9 +221,8 @@ public class MovementUtilities {
// agent.setLastRegion(currentRegion); // agent.setLastRegion(currentRegion);
Vector3fImmutable startLoc = null;
Vector3fImmutable startLoc = null; Vector3fImmutable endLoc = null;
Vector3fImmutable endLoc = null;
// if (agent.getLastRegion() != null){ // if (agent.getLastRegion() != null){
// Building inBuilding = Building.getBuildingFromCache(agent.getInBuildingID()); // Building inBuilding = Building.getBuildingFromCache(agent.getInBuildingID());
@ -241,63 +236,60 @@ public class MovementUtilities {
// startLoc = agent.getLoc(); // startLoc = agent.getLoc();
// endLoc = vect; // endLoc = vect;
// } // }
startLoc = agent.getLoc(); startLoc = agent.getLoc();
endLoc = vect; endLoc = vect;
msg.setSourceType(GameObjectType.Mob.ordinal()); msg.setSourceType(GameObjectType.Mob.ordinal());
msg.setSourceID(agent.getObjectUUID()); msg.setSourceID(agent.getObjectUUID());
msg.setStartCoord(startLoc); msg.setStartCoord(startLoc);
msg.setEndCoord(endLoc); msg.setEndCoord(endLoc);
msg.setUnknown01(-1); msg.setUnknown01(-1);
msg.setInBuilding(-1); msg.setInBuilding(-1);
msg.setTargetType(0); msg.setTargetType(0);
msg.setTargetID(0); msg.setTargetID(0);
try { try {
MovementManager.movement(msg, agent); MovementManager.movement(msg, agent);
} catch (MsgSendException e) { } catch (MsgSendException e) {
// TODO Figure out how we want to handle the msg send exception // TODO Figure out how we want to handle the msg send exception
e.printStackTrace(); e.printStackTrace();
} }
} }
public static Vector3fImmutable GetDestinationToCharacter(Mob aiAgent, AbstractCharacter character){ public static Vector3fImmutable GetDestinationToCharacter(Mob aiAgent, AbstractCharacter character) {
if (!character.isMoving()) if (!character.isMoving())
return character.getLoc(); return character.getLoc();
float agentDistanceEndLoc = aiAgent.getLoc().distanceSquared2D(character.getEndLoc()); float agentDistanceEndLoc = aiAgent.getLoc().distanceSquared2D(character.getEndLoc());
float characterDistanceEndLoc = character.getLoc().distanceSquared2D(character.getEndLoc()); float characterDistanceEndLoc = character.getLoc().distanceSquared2D(character.getEndLoc());
if (agentDistanceEndLoc > characterDistanceEndLoc) if (agentDistanceEndLoc > characterDistanceEndLoc)
return character.getEndLoc(); return character.getEndLoc();
return character.getLoc(); return character.getLoc();
} }
public static boolean updateMovementToCharacter(Mob aiAgent, AbstractCharacter aggroTarget){ public static boolean updateMovementToCharacter(Mob aiAgent, AbstractCharacter aggroTarget) {
if (aiAgent.destination.equals(Vector3fImmutable.ZERO)) if (aiAgent.destination.equals(Vector3fImmutable.ZERO))
return true; return true;
if (!aiAgent.isMoving()) if (!aiAgent.isMoving())
return true; return true;
if (aggroTarget.isMoving()) {
return !aiAgent.destination.equals(aggroTarget.getEndLoc()) && !aiAgent.destination.equals(aggroTarget.getLoc());
if (aggroTarget.isMoving()){ } else {
if (!aiAgent.destination.equals(aggroTarget.getEndLoc()) && !aiAgent.destination.equals(aggroTarget.getLoc())) if (aiAgent.destination.equals(aggroTarget.getLoc()))
return true; return false;
}else{ }
if (aiAgent.destination.equals(aggroTarget.getLoc()))
return false; return false;
} }
return false;
}
} }

1
src/engine/ai/utilities/PowerUtilities.java

@ -7,7 +7,6 @@
// www.magicbane.com // www.magicbane.com
package engine.ai.utilities; package engine.ai.utilities;
public class PowerUtilities { public class PowerUtilities {

Loading…
Cancel
Save