Merge branch 'community' into optimizations

# Conflicts:
#	src/DiIiS-NA/Core/Helpers/Math/RandomHelper.cs
This commit is contained in:
Stepan Goremykin 2023-01-29 01:45:49 +01:00
commit 4da0b6373d
59 changed files with 7939 additions and 7443 deletions

View File

@ -28,6 +28,118 @@
| | | `!lookup actor zombie` | | | | | `!lookup actor zombie` | |
| | | `!lookup power Punch` | | | | | `!lookup power Punch` | |
# All Commands
Available commands from `!commands`:
### !account
Provides account management commands.
### !mute
Disables chat messages for the account for some defined time span.
### !tag
Switch private Tag for connect
### !powerful
Makes your character with absurd amount of damage. Useful for testing.
### !resourceful
Makes your character with full resource. Useful for testing.
### !info
Get current game information.
### !followers
Manage your followers.
### !difficulty
Changes difficulty of the game
### !heal
Heals yourself
### !invulnerable
Makes you invulnerable
### !spawn
Spawns a mob.
Usage: spawn [actorSNO] [amount]
### !levelup
Levels your character.
Optionally specify the number of levels: !levelup [count]
### !unlockart
Unlock all artisans: !unlockart
### !platinum
Platinum for your character.
Optionally specify the number of levels: !platinum [count]
### !stashup
Upgrade Stash.
### !gold
Gold for your character.
Optionally specify the number of gold: !gold [count]
### !achiplatinum
Platinum for your character.
Optionally specify the number of levels: !platinum [count]
### !eff
Platinum for your character.
Optionally specify the number of levels: !eff [count]
### !item
Spawns an item (with a name or type).
Usage: item [type <type>|<name>] [amount]
### !drop
Drops an epic item for your class.
Optionally specify the number of items: !drop [1-20]
### !tp
Transfers your character to another world.
### !conversation
Starts a conversation.
Usage: conversation snoConversation
### !speed
Modify speed walk of you character.
Usage: !speed <value>
Reset: !speed
### !commands
Lists available commands for your user-level.
### !help
usage: help <command>
Type 'commands' to get a list of available commands.
### !quest
Retrieves information about quest states and manipulates quest progress.
Usage: quest [triggers | trigger eventType eventValue | advance snoQuest]
### !lookup
Searches in sno databases.
Usage: lookup [actor|conv|power|scene|la|sp|weather] <pattern>
# Item List # Item List
You can use the official website to search items: https://eu.diablo3.blizzard.com/en-us/item/ You can use the official website to search items: https://eu.diablo3.blizzard.com/en-us/item/

View File

@ -175,7 +175,7 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
{ {
var bTag = DBAccount.BattleTagName; var bTag = DBAccount.BattleTagName;
//(controller as HandlerController).Client.Account.GameAccount.ProgramField.Value //((HandlerController) controller).Client.Account.GameAccount.ProgramField.Value
if(GameAccount.ProgramField.Value == "APP") if(GameAccount.ProgramField.Value == "APP")
return bTag; return bTag;

View File

@ -9,6 +9,7 @@ using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Spectre.Console; using Spectre.Console;
@ -132,16 +133,16 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
List<DBAccount> dbAcc = DBSessions.SessionQueryWhere<DBAccount>(dba => dba.Email == email); List<DBAccount> dbAcc = DBSessions.SessionQueryWhere<DBAccount>(dba => dba.Email == email);
if (dbAcc.Count == 0) if (dbAcc.Count == 0)
{ {
Logger.Warn($"$[olive]$GetAccountByEmail(\"{email}\")$[/]$: DBAccount is null!"); Logger.Warn($"DBAccount is null from email {email}!");
return null; return null;
} }
if (dbAcc.First() == null) if (dbAcc.First() == null)
{ {
Logger.Warn($"$[olive]$GetAccountByEmail(\"{email}\")$[/]$: DBAccount id is not null!"); Logger.Warn($"DBAccount is null from email {email}!");
return null; return null;
} }
else
Logger.MethodTrace($"$[olive]$GetAccountByEmail(\"{email}\")$[/]$: id - {dbAcc.First().Id}"); Logger.MethodTrace($"id - {dbAcc.First().Id}");
return GetAccountByDBAccount(dbAcc.First()); return GetAccountByDBAccount(dbAcc.First());
} }
} }

View File

@ -948,7 +948,7 @@ public class GameAccount : PersistentRPCObject
.SetName("D3.NotificationMessage.Payload") .SetName("D3.NotificationMessage.Payload")
.SetValue(bgs.protocol.Variant.CreateBuilder().SetMessageValue(update.Build().ToByteString()))); .SetValue(bgs.protocol.Variant.CreateBuilder().SetMessageValue(update.Build().ToByteString())));
LoggedInClient.MakeRPC((lid) => LoggedInClient.MakeRpc((lid) =>
bgs.protocol.notification.v1.NotificationListener.CreateStub(LoggedInClient).OnNotificationReceived( bgs.protocol.notification.v1.NotificationListener.CreateStub(LoggedInClient).OnNotificationReceived(
new HandlerController() new HandlerController()
{ {

View File

@ -16,19 +16,19 @@ namespace DiIiS_NA.LoginServer.Battle
{ {
public class BattleBackend public class BattleBackend
{ {
private static readonly Logger Logger = LogManager.CreateLogger("BattleNetEmu"); private static readonly Logger Logger = LogManager.CreateLogger("BattleBackend");
public WatsonTcpServer GameServerSocket; public readonly WatsonTcpServer GameServerSocket;
public struct ServerDescriptor public struct ServerDescriptor
{ {
public string GameIP; public string GameIp;
public int GamePort; public int GamePort;
}; };
public Dictionary<string, ServerDescriptor> GameServers = new Dictionary<string, ServerDescriptor>(); public readonly Dictionary<string, ServerDescriptor> GameServers = new();
public Dictionary<string, ServerDescriptor> PvPGameServers = new Dictionary<string, ServerDescriptor>(); private readonly Dictionary<string, ServerDescriptor> _pvPGameServers = new();
public BattleBackend(string battleHost, int port) public BattleBackend(string battleHost, int port)
{ {
@ -38,33 +38,36 @@ namespace DiIiS_NA.LoginServer.Battle
private bool ReceiverClientConnected(string ipPort) private bool ReceiverClientConnected(string ipPort)
{ {
Logger.Info($"Blizzless server loaded {ipPort} - connecting..."); Logger.Info($"Blizzless client connected {ipPort}...");
return true; return true;
} }
private bool ReceiverClientDisconnected(string ipPort) private bool ReceiverClientDisconnected(string ipPort)
{ {
Logger.Warn("Blizzless server at {0} was disconnected!", ipPort); Logger.Warn("Blizzless client disconnected $[white]${0}$[/]$!", ipPort);
if (GameServers.ContainsKey(ipPort)) GameServers.Remove(ipPort); if (GameServers.ContainsKey(ipPort)) GameServers.Remove(ipPort);
if (PvPGameServers.ContainsKey(ipPort)) PvPGameServers.Remove(ipPort); if (_pvPGameServers.ContainsKey(ipPort)) _pvPGameServers.Remove(ipPort);
if (GameServers.Count == 0) if (GameServers.Count == 0)
Logger.Warn("GameServers list is empty! Unable to use PvE game activities atm."); Logger.Warn("GameServers list is empty! Unable to use PvE game activities atm.");
if (PvPGameServers.Count == 0) if (_pvPGameServers.Count == 0)
Logger.Warn("PvPGameServers list is empty! Unable to use PvP game activities atm."); Logger.Warn("PvPGameServers list is empty! Unable to use PvP game activities atm.");
return true; return true;
} }
public void CreateGame(string ipPort, int GameId, int level, int act, int difficulty, int questId, int questStepId, bool isHardcore, int gamemode, bool iSseasoned, int perftest_id = 0) public void CreateGame(string ipPort, int gameId, int level, int act, int difficulty, int questId, int questStepId, bool isHardcore, int gameMode, bool isSeasoned, int perftestId = 0)
{ {
GameServerSocket.Send(ipPort, Encoding.UTF8.GetBytes(string.Format("diiiscg|{0}/{1}/{2}/{3}/{4}/{5}/{6}/{7}/{8}", GameId, level, act, difficulty, questId, questStepId, isHardcore, gamemode, iSseasoned, perftest_id))); Send(ipPort, $"diiiscg|{gameId}/{level}/{act}/{difficulty}/{questId}/{questStepId}/{isHardcore}/{gameMode}/{isSeasoned}");
} }
private void Send(string ipPort, string data)
=> GameServerSocket.Send(ipPort, Encoding.UTF8.GetBytes(data));
private bool ReceiverMessageReceived(string ipPort, byte[] data) private bool ReceiverMessageReceived(string ipPort, byte[] data)
{ {
string msg = ""; string msg = "";
if (data != null && data.Length > 0) msg = Encoding.UTF8.GetString(data); if (data != null && data.Length > 0) msg = Encoding.UTF8.GetString(data);
Logger.Trace("Message received from {0}: {1}", ipPort, msg); Logger.Trace("Message received from $[grey69]${0}$[/]$: $[white]${1}$[/]$", ipPort, msg);
var message = msg.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); var message = msg.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
var args = message[1].Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); var args = message[1].Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
@ -72,134 +75,134 @@ namespace DiIiS_NA.LoginServer.Battle
{ {
case "rngsr": case "rngsr":
if (GameServers.ContainsKey(ipPort)) GameServers.Remove(ipPort); if (GameServers.ContainsKey(ipPort)) GameServers.Remove(ipPort);
string rgs_ip = args[0]; string rgsIp = args[0];
int rgs_port = int.Parse(args[1].Trim()); int rgsPort = int.Parse(args[1].Trim());
GameServers.Add(ipPort, new ServerDescriptor { GameIP = rgs_ip, GamePort = rgs_port }); GameServers.Add(ipPort, new ServerDescriptor { GameIp = rgsIp, GamePort = rgsPort });
Logger.Info("Game server was registered for Blizzless {0}:{1}.", rgs_ip, rgs_port); Logger.Info("Game server was registered for Blizzless {0}:{1}.", rgsIp, rgsPort);
break; break;
case "rnpvpgsr": case "rnpvpgsr":
if (PvPGameServers.ContainsKey(ipPort)) PvPGameServers.Remove(ipPort); if (_pvPGameServers.ContainsKey(ipPort)) _pvPGameServers.Remove(ipPort);
string rpgs_ip = args[0]; string rpgsIp = args[0];
int rpgs_port = int.Parse(args[1].Trim()); int rpgsPort = int.Parse(args[1].Trim());
PvPGameServers.Add(ipPort, new ServerDescriptor { GameIP = rpgs_ip, GamePort = rpgs_port }); _pvPGameServers.Add(ipPort, new ServerDescriptor { GameIp = rpgsIp, GamePort = rpgsPort });
Logger.Info("PvP GameServer at {0}:{1} successfully signed and ready to work.", rpgs_ip, rpgs_port); Logger.Info("PvP GameServer at {0}:{1} successfully signed and ready to work.", rpgsIp, rpgsPort);
break; break;
case "grachi": case "grachi":
ulong gachi_accId = ulong.Parse(args[0].Trim()); ulong gachiAccId = ulong.Parse(args[0].Trim());
ulong gachi_achId = ulong.Parse(args[1].Trim()); ulong gachiAchId = ulong.Parse(args[1].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var gachi_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == gachi_accId)) foreach (var gachiInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == gachiAccId))
AchievementManager.GrantAchievement(gachi_invokerClient, gachi_achId); AchievementManager.GrantAchievement(gachiInvokerClient, gachiAchId);
}); });
break; break;
case "gcrit": case "gcrit":
ulong gc_accId = ulong.Parse(args[0].Trim()); ulong gcAccId = ulong.Parse(args[0].Trim());
ulong gc_criId = ulong.Parse(args[1].Trim()); ulong gcCriId = ulong.Parse(args[1].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var gc_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == gc_accId)) foreach (var gcInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == gcAccId))
AchievementManager.GrantCriteria(gc_invokerClient, gc_criId); AchievementManager.GrantCriteria(gcInvokerClient, gcCriId);
}); });
break; break;
case "upequt": case "upequt":
ulong uq_accId = ulong.Parse(args[0].Trim()); ulong uqAccId = ulong.Parse(args[0].Trim());
ulong uq_achId = ulong.Parse(args[1].Trim()); ulong uqAchId = ulong.Parse(args[1].Trim());
uint uq_addCounter = uint.Parse(args[2].Trim()); uint uqAddCounter = uint.Parse(args[2].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var uq_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == uq_accId)) foreach (var uqInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == uqAccId))
AchievementManager.UpdateQuantity(uq_invokerClient, uq_achId, uq_addCounter); AchievementManager.UpdateQuantity(uqInvokerClient, uqAchId, uqAddCounter);
}); });
break; break;
case "uoacce": case "uoacce":
ulong uac_accId = ulong.Parse(args[0].Trim()); ulong uacAccId = ulong.Parse(args[0].Trim());
int uac_typeId = int.Parse(args[1].Trim()); int uacTypeId = int.Parse(args[1].Trim());
uint uac_addCounter = uint.Parse(args[2].Trim()); uint uacAddCounter = uint.Parse(args[2].Trim());
int uac_comparand = int.Parse(args[3].Trim()); int uacComparand = int.Parse(args[3].Trim());
ulong uac_achi = ulong.Parse(args[4].Trim()); ulong uacAchi = ulong.Parse(args[4].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
if (uac_achi == 0) if (uacAchi == 0)
foreach (var uac_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == uac_accId)) foreach (var uacInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == uacAccId))
AchievementManager.UpdateAllCounters(uac_invokerClient, uac_typeId, uac_addCounter, uac_comparand); AchievementManager.UpdateAllCounters(uacInvokerClient, uacTypeId, uacAddCounter, uacComparand);
else else
foreach (var uac_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == uac_accId)) foreach (var uacInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == uacAccId))
AchievementManager.UpdateAllCounters(uac_invokerClient, uac_typeId, uac_addCounter, uac_comparand); AchievementManager.UpdateAllCounters(uacInvokerClient, uacTypeId, uacAddCounter, uacComparand);
}); });
break; break;
case "upsnaccr": //UpdateSingleAchievementCounter case "upsnaccr": //UpdateSingleAchievementCounter
ulong usac_accId = ulong.Parse(args[0].Trim()); ulong usacAccId = ulong.Parse(args[0].Trim());
ulong usac_achId = ulong.Parse(args[1].Trim()); ulong usacAchId = ulong.Parse(args[1].Trim());
uint usac_addCounter = uint.Parse(args[2].Trim()); uint usacAddCounter = uint.Parse(args[2].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var usac_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == usac_accId)) foreach (var usacInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == usacAccId))
AchievementManager.UpdateQuantity(usac_invokerClient, usac_achId, usac_addCounter); AchievementManager.UpdateQuantity(usacInvokerClient, usacAchId, usacAddCounter);
}); });
break; break;
case "cqc": //CheckQuestCriteria case "cqc": //CheckQuestCriteria
ulong cqc_accId = ulong.Parse(args[0].Trim()); ulong cqcAccId = ulong.Parse(args[0].Trim());
int cqc_qId = int.Parse(args[1].Trim()); int cqcQId = int.Parse(args[1].Trim());
bool cqc_isCoop = (args[2].Trim() == "True" ? true : false); bool cqcIsCoop = (args[2].Trim() == "True" ? true : false);
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var cqc_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == cqc_accId)) foreach (var cqcInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == cqcAccId))
AchievementManager.CheckQuestCriteria(cqc_invokerClient, cqc_qId, cqc_isCoop); AchievementManager.CheckQuestCriteria(cqcInvokerClient, cqcQId, cqcIsCoop);
}); });
break; break;
case "ckmc": //CheckKillMonsterCriteria case "ckmc": //CheckKillMonsterCriteria
ulong ckmc_accId = ulong.Parse(args[0].Trim()); ulong ckmcAccId = ulong.Parse(args[0].Trim());
int ckmc_actorId = int.Parse(args[1].Trim()); int ckmcActorId = int.Parse(args[1].Trim());
int ckmc_type = int.Parse(args[2].Trim()); int ckmcType = int.Parse(args[2].Trim());
bool ckmc_isHardcore = (args[3].Trim() == "True" ? true : false); bool ckmcIsHardcore = (args[3].Trim() == "True" ? true : false);
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var ckmc_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == ckmc_accId)) foreach (var ckmcInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == ckmcAccId))
AchievementManager.CheckKillMonsterCriteria(ckmc_invokerClient, ckmc_actorId, ckmc_type, ckmc_isHardcore); AchievementManager.CheckKillMonsterCriteria(ckmcInvokerClient, ckmcActorId, ckmcType, ckmcIsHardcore);
}); });
break; break;
case "clc": //CheckLevelCap case "clc": //CheckLevelCap
ulong clc_accId = ulong.Parse(args[0].Trim()); ulong clcAccId = ulong.Parse(args[0].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var clc_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == clc_accId)) foreach (var clcInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == clcAccId))
AchievementManager.CheckLevelCap(clc_invokerClient); AchievementManager.CheckLevelCap(clcInvokerClient);
}); });
break; break;
case "csic": //CheckSalvageItemCriteria case "csic": //CheckSalvageItemCriteria
ulong csic_accId = ulong.Parse(args[0].Trim()); ulong csicAccId = ulong.Parse(args[0].Trim());
int csic_itemId = int.Parse(args[1].Trim()); int csicItemId = int.Parse(args[1].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var csic_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == csic_accId)) foreach (var csicInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == csicAccId))
AchievementManager.CheckSalvageItemCriteria(csic_invokerClient, csic_itemId); AchievementManager.CheckSalvageItemCriteria(csicInvokerClient, csicItemId);
}); });
break; break;
case "clac": //CheckLevelAreaCriteria case "clac": //CheckLevelAreaCriteria
ulong clac_accId = ulong.Parse(args[0].Trim()); ulong clacAccId = ulong.Parse(args[0].Trim());
int clac_laId = int.Parse(args[1].Trim()); int clacLaId = int.Parse(args[1].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var clac_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == clac_accId)) foreach (var clacInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == clacAccId))
AchievementManager.CheckLevelAreaCriteria(clac_invokerClient, clac_laId); AchievementManager.CheckLevelAreaCriteria(clacInvokerClient, clacLaId);
}); });
break; break;
case "ccc": //CheckConversationCriteria case "ccc": //CheckConversationCriteria
ulong ccc_accId = ulong.Parse(args[0].Trim()); ulong cccAccId = ulong.Parse(args[0].Trim());
int ccc_cId = int.Parse(args[1].Trim()); int cccCId = int.Parse(args[1].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var ccc_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == ccc_accId)) foreach (var cccInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == cccAccId))
AchievementManager.CheckConversationCriteria(ccc_invokerClient, ccc_cId); AchievementManager.CheckConversationCriteria(cccInvokerClient, cccCId);
}); });
break; break;
case "plu": //ParagonLevelUp case "plu": //ParagonLevelUp
ulong plu_accId = ulong.Parse(args[0].Trim()); ulong pluAccId = ulong.Parse(args[0].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
var plr_client = PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == plu_accId).FirstOrDefault(); var plrClient = PlayerManager.OnlinePlayers.FirstOrDefault(c => c.Account.GameAccount.PersistentID == pluAccId);
if (plr_client != null && plr_client.Account.GameAccount. Clan != null) if (plrClient != null && plrClient.Account.GameAccount. Clan != null)
plr_client.Account.GameAccount.Clan.ParagonRatings[plr_client.Account.GameAccount] = plr_client.Account.GameAccount.DBGameAccount.ParagonLevel; plrClient.Account.GameAccount.Clan.ParagonRatings[plrClient.Account.GameAccount] = plrClient.Account.GameAccount.DBGameAccount.ParagonLevel;
}); });
break; break;
case "uii": //UniqueItemIdentified case "uii": //UniqueItemIdentified
ulong uii_accId = ulong.Parse(args[0].Trim()); ulong uiiAccId = ulong.Parse(args[0].Trim());
ulong uii_itemId = ulong.Parse(args[1].Trim()); ulong uiiItemId = ulong.Parse(args[1].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
var plr_client = PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == uii_accId).FirstOrDefault(); var plrClient = PlayerManager.OnlinePlayers.FirstOrDefault(c => c.Account.GameAccount.PersistentID == uiiAccId);
if (plr_client != null && plr_client.Account.GameAccount.Clan != null) if (plrClient != null && plrClient.Account.GameAccount.Clan != null)
{ {
var dbItem = DBSessions.SessionGet<DBInventory>(uii_itemId); var dbItem = DBSessions.SessionGet<DBInventory>(uiiItemId);
if (dbItem != null) if (dbItem != null)
{ {
var generator = D3.Items.Generator.CreateBuilder() var generator = D3.Items.Generator.CreateBuilder()
@ -219,92 +222,92 @@ namespace DiIiS_NA.LoginServer.Battle
generator.AddBaseAffixes(result); generator.AddBaseAffixes(result);
} }
plr_client.Account.GameAccount.Clan.AddNews(plr_client.Account.GameAccount, 0, generator.Build().ToByteArray()); plrClient.Account.GameAccount.Clan.AddNews(plrClient.Account.GameAccount, 0, generator.Build().ToByteArray());
} }
} }
}); });
break; break;
case "uc": //UpdateClient case "uc": //UpdateClient
ulong uc_accId = ulong.Parse(args[0].Trim()); ulong ucAccId = ulong.Parse(args[0].Trim());
int uc_level = int.Parse(args[1].Trim()); int ucLevel = int.Parse(args[1].Trim());
int uc_screen = int.Parse(args[2].Trim()); int ucScreen = int.Parse(args[2].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
try try
{ {
foreach (var uc_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == uc_accId)) foreach (var ucInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == ucAccId))
{ {
if (!uc_invokerClient.Account.IsOnline) continue; if (!ucInvokerClient.Account.IsOnline) continue;
uc_invokerClient.Account.GameAccount.ChangedFields.SetPresenceFieldValue(uc_invokerClient.Account.GameAccount.CurrentToon.HeroLevelField); ucInvokerClient.Account.GameAccount.ChangedFields.SetPresenceFieldValue(ucInvokerClient.Account.GameAccount.CurrentToon.HeroLevelField);
uc_invokerClient.Account.GameAccount.ChangedFields.SetPresenceFieldValue(uc_invokerClient.Account.GameAccount.CurrentToon.HeroParagonLevelField); ucInvokerClient.Account.GameAccount.ChangedFields.SetPresenceFieldValue(ucInvokerClient.Account.GameAccount.CurrentToon.HeroParagonLevelField);
if (uc_screen != -1) uc_invokerClient.Account.GameAccount.ScreenStatus = D3.PartyMessage.ScreenStatus.CreateBuilder().SetScreen(uc_screen).SetStatus(0).Build(); if (ucScreen != -1) ucInvokerClient.Account.GameAccount.ScreenStatus = D3.PartyMessage.ScreenStatus.CreateBuilder().SetScreen(ucScreen).SetStatus(0).Build();
uc_invokerClient.Account.GameAccount.NotifyUpdate(); ucInvokerClient.Account.GameAccount.NotifyUpdate();
} }
} }
catch { } catch { }
}); });
break; break;
case "gpj": //PlayerJoined case "gpj": //PlayerJoined
int gpj_gameId = int.Parse(args[0].Trim()); int gpjGameId = int.Parse(args[0].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
try try
{ {
GameFactoryManager.FindGameByDynamicId((ulong)gpj_gameId).PlayersCount++; GameFactoryManager.FindGameByDynamicId((ulong)gpjGameId).PlayersCount++;
} }
catch { } catch { }
}); });
break; break;
case "gpl": //PlayerLeft case "gpl": //PlayerLeft
int gpl_gameId = int.Parse(args[0].Trim()); int gplGameId = int.Parse(args[0].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
try try
{ {
if (GameFactoryManager.FindGameByDynamicId((ulong)gpl_gameId) != null) if (GameFactoryManager.FindGameByDynamicId((ulong)gplGameId) != null)
GameFactoryManager.FindGameByDynamicId((ulong)gpl_gameId).PlayersCount--; GameFactoryManager.FindGameByDynamicId((ulong)gplGameId).PlayersCount--;
} }
catch { } catch { }
}); });
break; break;
case "gsp": //SetGamePublic case "gsp": //SetGamePublic
int gsp_gameId = int.Parse(args[0].Trim()); int gspGameId = int.Parse(args[0].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
try try
{ {
GameFactoryManager.FindGameByDynamicId((ulong)gsp_gameId).Public = true; GameFactoryManager.FindGameByDynamicId((ulong)gspGameId).Public = true;
} }
catch { } catch { }
}); });
break; break;
case "tsc": //ToonStateChanged case "tsc": //ToonStateChanged
int tsc_toonId = int.Parse(args[0].Trim()); int tscToonId = int.Parse(args[0].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
try try
{ {
Toons.ToonManager.GetToonByLowID((ulong)tsc_toonId).StateChanged(); Toons.ToonManager.GetToonByLowID((ulong)tscToonId).StateChanged();
} }
catch { } catch { }
}); });
break; break;
case "pvpsp": //PvPSaveProgress case "pvpsp": //PvPSaveProgress
ulong pvpsp_gAccId = ulong.Parse(args[0].Trim()); ulong pvpspGAccId = ulong.Parse(args[0].Trim());
int pvpsp_kills = int.Parse(args[1].Trim()); int pvpspKills = int.Parse(args[1].Trim());
int pvpsp_wins = int.Parse(args[2].Trim()); int pvpspWins = int.Parse(args[2].Trim());
int pvpsp_gold = int.Parse(args[3].Trim()); int pvpspGold = int.Parse(args[3].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => { System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
var gAcc = GameAccountManager.GetAccountByPersistentID(pvpsp_gAccId); var gAcc = GameAccountManager.GetAccountByPersistentID(pvpspGAccId);
lock (gAcc.DBGameAccount) lock (gAcc.DBGameAccount)
{ {
var dbGAcc = gAcc.DBGameAccount; var dbGAcc = gAcc.DBGameAccount;
dbGAcc.PvPTotalKilled += (ulong)pvpsp_kills; dbGAcc.PvPTotalKilled += (ulong)pvpspKills;
dbGAcc.PvPTotalWins += (ulong)pvpsp_wins; dbGAcc.PvPTotalWins += (ulong)pvpspWins;
dbGAcc.PvPTotalGold += (ulong)pvpsp_gold; dbGAcc.PvPTotalGold += (ulong)pvpspGold;
DBSessions.SessionUpdate(dbGAcc); DBSessions.SessionUpdate(dbGAcc);
} }
}); });
break; break;
default: default:
Logger.Warn("Unknown message type: {0}|{1}", message[0], message[1]); Logger.Warn("Unknown message type: $[white]${0}|{1}$[/]$", message[0], message[1]);
break; break;
} }
return true; return true;

View File

@ -30,33 +30,33 @@ namespace DiIiS_NA.LoginServer.Battle
public ISocketChannel SocketConnection { get; private set; } public ISocketChannel SocketConnection { get; private set; }
public IChannelHandlerContext Connect { get; private set; } public IChannelHandlerContext Connect { get; private set; }
public bool AuthenticationStatus = false; public bool AuthenticationStatus = false;
public ClientLocale ClientLanguage = ClientLocale.enUS; public ClientLocale ClientLanguage = ClientLocale.EN_US;
public IRpcController ListenerController; public IRpcController ListenerController;
private uint _tokenCounter = 0; private uint _tokenCounter = 0;
public static NO_RESPONSE NO_RESPONSE = NO_RESPONSE.CreateBuilder().Build(); public static NO_RESPONSE NoResponse = NO_RESPONSE.CreateBuilder().Build();
private readonly Dictionary<int, RPCCallBack> _pendingResponses = new(); // TODO: Check usage and remove if not needed private readonly Dictionary<int, RPCCallBack> _pendingResponses = new(); // TODO: Check usage and remove if not needed
public bgs.protocol.v2.Attribute AttributeOfServer { get; set; } public bgs.protocol.v2.Attribute AttributeOfServer { get; set; }
public Account Account { get; set; } public Account Account { get; set; }
public const byte ServiceReply = 0xFE; public const byte SERVICE_REPLY = 0xFE;
public SslStream Ssl = null; public SslStream Ssl = null;
private static int REQUEST_SERVICE_ID = 0; private static int _requestServiceId = 0;
private static int RESPONSE_SERVICE_ID = 254; private static int _responseServiceId = 254;
//public object clientLock = new object(); //public object clientLock = new object();
public readonly object _serviceLock = new(); public readonly object ServiceLock = new();
public object messageLock = new(); public object MessageLock = new();
private ulong _listenerId; // last targeted rpc object. private ulong _listenerId; // last targeted rpc object.
public bool MOTDSent { get; private set; } public bool MotdSent { get; private set; }
private ConcurrentDictionary<ulong, ulong> MappedObjects { get; set; } private ConcurrentDictionary<ulong, ulong> MappedObjects { get; set; }
public bool GuildChannelsRevealed = false; public bool GuildChannelsRevealed = false;
public string GameTeamTag = ""; public string GameTeamTag = "";
public ulong CID = 0; public readonly ulong Cid = 0;
#region current channel #region current channel
public Dictionary<ulong, Channel> Channels = new(); public readonly Dictionary<ulong, Channel> Channels = new();
public List<Channel> ChatChannels = new(); public readonly List<Channel> ChatChannels = new();
public Channel PartyChannel; //Used for all non game related messages public Channel PartyChannel; //Used for all non game related messages
public Channel GameChannel; //Used for all game related messages public Channel GameChannel; //Used for all game related messages
@ -103,7 +103,7 @@ namespace DiIiS_NA.LoginServer.Battle
.AddAttribute(bgs.protocol.Attribute.CreateBuilder().SetName("whisper") .AddAttribute(bgs.protocol.Attribute.CreateBuilder().SetName("whisper")
.SetValue(Variant.CreateBuilder().SetStringValue(text).Build()).Build()).Build(); .SetValue(Variant.CreateBuilder().SetStringValue(text).Build()).Build()).Build();
MakeRPC((lid) => bgs.protocol.notification.v1.NotificationListener.CreateStub(this). MakeRpc((lid) => bgs.protocol.notification.v1.NotificationListener.CreateStub(this).
OnNotificationReceived(new HandlerController() OnNotificationReceived(new HandlerController()
{ {
ListenerId = lid ListenerId = lid
@ -120,8 +120,8 @@ namespace DiIiS_NA.LoginServer.Battle
public void LeaveAllChannels() public void LeaveAllChannels()
{ {
List<Channel> _channels = Channels.Values.ToList(); List<Channel> channels = Channels.Values.ToList();
foreach (var channel in _channels) foreach (var channel in channels)
{ {
try try
{ {
@ -134,12 +134,12 @@ namespace DiIiS_NA.LoginServer.Battle
#endregion #endregion
public BattleClient(ISocketChannel socketChannel, DotNetty.Handlers.Tls.TlsHandler TLS) public BattleClient(ISocketChannel socketChannel, DotNetty.Handlers.Tls.TlsHandler tls)
{ {
SocketConnection = socketChannel; SocketConnection = socketChannel;
Services = new Dictionary<uint, uint>(); Services = new Dictionary<uint, uint>();
MappedObjects = new ConcurrentDictionary<ulong, ulong>(); MappedObjects = new ConcurrentDictionary<ulong, ulong>();
MOTDSent = false; MotdSent = false;
if (SocketConnection.Active) if (SocketConnection.Active)
Logger.Trace("Client - {0} - successfully encrypted the connection", socketChannel.RemoteAddress); Logger.Trace("Client - {0} - successfully encrypted the connection", socketChannel.RemoteAddress);
} }
@ -150,7 +150,7 @@ namespace DiIiS_NA.LoginServer.Battle
Header header = msg.GetHeader(); Header header = msg.GetHeader();
byte[] payload = (byte[])msg.GetPayload(); byte[] payload = (byte[])msg.GetPayload();
if (msg.GetHeader().ServiceId == RESPONSE_SERVICE_ID) if (msg.GetHeader().ServiceId == _responseServiceId)
{ {
if (_pendingResponses.Count == 0) return; if (_pendingResponses.Count == 0) return;
RPCCallBack done = _pendingResponses[(int)header.Token]; RPCCallBack done = _pendingResponses[(int)header.Token];
@ -276,7 +276,7 @@ namespace DiIiS_NA.LoginServer.Battle
#endif #endif
service.CallMethod(method, controller, message, service.CallMethod(method, controller, message,
(IMessage m) => { sendResponse(ctx, (int)header.Token, m, controller.Status); }); (IMessage m) => { SendResponse(ctx, (int)header.Token, m, controller.Status); });
} }
} }
catch (NotImplementedException) catch (NotImplementedException)
@ -319,69 +319,69 @@ namespace DiIiS_NA.LoginServer.Battle
/// <summary> /// <summary>
/// Deutsch. /// Deutsch.
/// </summary> /// </summary>
deDE, DE_DE,
/// <summary> /// <summary>
/// English (EU) /// English (EU)
/// </summary> /// </summary>
enGB, EN_GB,
/// <summary> /// <summary>
/// English (Singapore) /// English (Singapore)
/// </summary> /// </summary>
enSG, EN_SG,
/// <summary> /// <summary>
/// English (US) /// English (US)
/// </summary> /// </summary>
enUS, EN_US,
/// <summary> /// <summary>
/// Espanol /// Espanol
/// </summary> /// </summary>
esES, ES_ES,
/// <summary> /// <summary>
/// Espanol (Mexico) /// Espanol (Mexico)
/// </summary> /// </summary>
esMX, ES_MX,
/// <summary> /// <summary>
/// French /// French
/// </summary> /// </summary>
frFR, FR_FR,
/// <summary> /// <summary>
/// Italian /// Italian
/// </summary> /// </summary>
itIT, IT_IT,
/// <summary> /// <summary>
/// Korean /// Korean
/// </summary> /// </summary>
koKR, KO_KR,
/// <summary> /// <summary>
/// Polish /// Polish
/// </summary> /// </summary>
plPL, PL_PL,
/// <summary> /// <summary>
/// Portuguese /// Portuguese
/// </summary> /// </summary>
ptPT, PT_PT,
/// <summary> /// <summary>
/// Portuguese (Brazil) /// Portuguese (Brazil)
/// </summary> /// </summary>
ptBR, PT_BR,
/// <summary> /// <summary>
/// Russian /// Russian
/// </summary> /// </summary>
ruRU, RU_RU,
/// <summary> /// <summary>
/// Turkish /// Turkish
/// </summary> /// </summary>
trTR, TR_TR,
/// <summary> /// <summary>
/// Chinese /// Chinese
/// </summary> /// </summary>
zhCN, ZH_CN,
/// <summary> /// <summary>
/// Chinese (Taiwan) /// Chinese (Taiwan)
/// </summary> /// </summary>
zhTW ZH_TW
} }
public virtual void MakeTargetedRPC(RPCObject targetObject, Action<ulong> rpc) public virtual void MakeTargetedRpc(RPCObject targetObject, Action<ulong> rpc)
{ {
Task.Run(() => Task.Run(() =>
{ {
@ -400,7 +400,7 @@ namespace DiIiS_NA.LoginServer.Battle
//} //}
}); });
} }
public virtual void MakeRPC(Action<ulong> rpc) public virtual void MakeRpc(Action<ulong> rpc)
{ {
Task.Run(() => Task.Run(() =>
{ {
@ -438,18 +438,18 @@ namespace DiIiS_NA.LoginServer.Battle
if (controller is HandlerController) if (controller is HandlerController)
{ {
status = (controller as HandlerController).Status; status = ((HandlerController) controller).Status;
_listenerId = (controller as HandlerController).ListenerId; _listenerId = ((HandlerController) controller).ListenerId;
} }
var serviceId = Services[serviceHash]; var serviceId = Services[serviceHash];
var token = _tokenCounter++; var token = _tokenCounter++;
sendRequest(Connect, serviceHash, GetMethodId(method), token, request, (uint)_listenerId, status); SendRequest(Connect, serviceHash, GetMethodId(method), token, request, (uint)_listenerId, status);
} }
public static void sendRequest(IChannelHandlerContext ctx, uint serviceHash, uint methodId, uint token, IMessage request, uint listenerId, uint status) public static void SendRequest(IChannelHandlerContext ctx, uint serviceHash, uint methodId, uint token, IMessage request, uint listenerId, uint status)
{ {
Header.Builder builder = Header.CreateBuilder(); Header.Builder builder = Header.CreateBuilder();
builder.SetServiceId((uint)REQUEST_SERVICE_ID); builder.SetServiceId((uint)_requestServiceId);
builder.SetServiceHash(serviceHash); builder.SetServiceHash(serviceHash);
builder.SetMethodId(methodId); builder.SetMethodId(methodId);
if (listenerId != 0) if (listenerId != 0)
@ -462,7 +462,7 @@ namespace DiIiS_NA.LoginServer.Battle
} }
/// <param name="localObjectId">The local objectId.</param> /// <param name="localObjectId">The local objectId.</param>
/// <param name="remoteObjectId">The remote objectId over client.</param> /// <param name="remoteObjectId">The remote objectId over client.</param>
public void MapLocalObjectID(ulong localObjectId, ulong remoteObjectId) public void MapLocalObjectId(ulong localObjectId, ulong remoteObjectId)
{ {
try try
{ {
@ -501,10 +501,10 @@ namespace DiIiS_NA.LoginServer.Battle
return (uint)(method.Index) + 1; return (uint)(method.Index) + 1;
} }
} }
public static void sendResponse(IChannelHandlerContext ctx, int token, IMessage response, uint status) public static void SendResponse(IChannelHandlerContext ctx, int token, IMessage response, uint status)
{ {
Header.Builder builder = Header.CreateBuilder(); Header.Builder builder = Header.CreateBuilder();
builder.SetServiceId((uint)RESPONSE_SERVICE_ID); builder.SetServiceId((uint)_responseServiceId);
builder.SetToken((uint)token); builder.SetToken((uint)token);
builder.SetStatus(status); builder.SetStatus(status);
if (response != null) if (response != null)
@ -512,15 +512,15 @@ namespace DiIiS_NA.LoginServer.Battle
ctx.Channel.WriteAndFlushAsync(new BNetPacket(builder.Build(), response)); ctx.Channel.WriteAndFlushAsync(new BNetPacket(builder.Build(), response));
} }
public void SendMOTD() public void SendMotd()
{ {
if (MOTDSent) if (MotdSent)
return; return;
var motd = "Welcome to BlizzLess.Net Alpha-Build Server!"; var motd = "Welcome to BlizzLess.Net Alpha-Build Server!";
SendServerWhisper(motd); SendServerWhisper(motd);
MOTDSent = true; MotdSent = true;
} }
public override void ChannelInactive(IChannelHandlerContext context) public override void ChannelInactive(IChannelHandlerContext context)

View File

@ -26,9 +26,9 @@ namespace DiIiS_NA.LoginServer.Battle
public static BattleClient GetClientByEmail(string email) => OnlinePlayers.FirstOrDefault(cli => cli.Account.Email == email); public static BattleClient GetClientByEmail(string email) => OnlinePlayers.FirstOrDefault(cli => cli.Account.Email == email);
public static BattleClient GetClientByBattleTag(string battleTag) => OnlinePlayers.FirstOrDefault(cli => cli.Account.BattleTag == battleTag); public static BattleClient GetClientByBattleTag(string battleTag) => OnlinePlayers.FirstOrDefault(cli => cli.Account.BattleTag == battleTag);
public static BattleClient GetClientByCID(ulong cid) public static BattleClient GetClientByCid(ulong cid)
{ {
return OnlinePlayers.FirstOrDefault(bc => bc.CID == cid); return OnlinePlayers.FirstOrDefault(bc => bc.Cid == cid);
} }
public static void SendWhisper(string message) public static void SendWhisper(string message)

View File

@ -93,7 +93,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
this.IsGuildChatChannel = false; this.IsGuildChatChannel = false;
if ((client != null) && (remoteObjectId != 0)) if ((client != null) && (remoteObjectId != 0))
client.MapLocalObjectID(this.DynamicId, remoteObjectId); client.MapLocalObjectId(this.DynamicId, remoteObjectId);
if (this.IsChatChannel) if (this.IsChatChannel)
Program.Watchdog.AddTask(10, new Action(() => Program.Watchdog.AddTask(10, new Action(() =>
@ -175,7 +175,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
.AddStateChange(channelMember) .AddStateChange(channelMember)
.Build(); .Build();
client.MakeTargetedRPC(this, (lid) => client.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnUpdateMemberState(new HandlerController() { ListenerId = lid } , notification, callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnUpdateMemberState(new HandlerController() { ListenerId = lid } , notification, callback => { }));
} }
@ -201,7 +201,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
//Notify all Channel members //Notify all Channel members
foreach (var n_member in this.Members.Keys) foreach (var n_member in this.Members.Keys)
{ {
n_member.MakeTargetedRPC(this, (lid) => n_member.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(n_member).OnUpdateMemberState(new HandlerController() { ListenerId = lid }, notification, callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(n_member).OnUpdateMemberState(new HandlerController() { ListenerId = lid }, notification, callback => { }));
} }
} }
@ -213,7 +213,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
public void Join(BattleClient client, ulong remoteObjectId) public void Join(BattleClient client, ulong remoteObjectId)
{ {
client.MapLocalObjectID(this.DynamicId, remoteObjectId); client.MapLocalObjectId(this.DynamicId, remoteObjectId);
this.AddMember(client); this.AddMember(client);
} }
@ -249,7 +249,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
.AddRangeMember(members) .AddRangeMember(members)
.Build(); .Build();
client.MakeTargetedRPC(this, (lid) => client.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnJoin(new HandlerController() { ListenerId = lid }, joinNotification, callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnJoin(new HandlerController() { ListenerId = lid }, joinNotification, callback => { }));
@ -276,7 +276,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
foreach (var pair in this.Members.Where(pair => pair.Value != addedMember)) // only send this to previous members of the channel. foreach (var pair in this.Members.Where(pair => pair.Value != addedMember)) // only send this to previous members of the channel.
{ {
pair.Key.MakeTargetedRPC(this, (lid) => pair.Key.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(pair.Key).OnMemberAdded(new HandlerController() { ListenerId = lid }, addNotification, callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(pair.Key).OnMemberAdded(new HandlerController() { ListenerId = lid }, addNotification, callback => { }));
} }
@ -348,10 +348,10 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
foreach (var pair in this.Members) foreach (var pair in this.Members)
{ {
if (pair.Key != client) if (pair.Key != client)
pair.Key.MakeTargetedRPC(this, (lid) => pair.Key.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(pair.Key).OnMemberRemoved(new HandlerController() { ListenerId = lid }, removeMessage, callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(pair.Key).OnMemberRemoved(new HandlerController() { ListenerId = lid }, removeMessage, callback => { }));
} }
client.MakeTargetedRPC(this, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnLeave(new HandlerController() { ListenerId = lid }, leaveMessage, callback => client.MakeTargetedRpc(this, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnLeave(new HandlerController() { ListenerId = lid }, leaveMessage, callback =>
{ {
client.UnmapLocalObjectId(this.DynamicId); })); client.UnmapLocalObjectId(this.DynamicId); }));
@ -431,7 +431,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
foreach (var pair in this.Members) // send to all members of channel even to the actual one that sent the message else he'll not see his own message. foreach (var pair in this.Members) // send to all members of channel even to the actual one that sent the message else he'll not see his own message.
{ {
if (pair.Key.Account.IgnoreIds.Contains(client.Account.PersistentID)) continue; if (pair.Key.Account.IgnoreIds.Contains(client.Account.PersistentID)) continue;
pair.Key.MakeTargetedRPC(this, (lid) => pair.Key.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(pair.Key).OnSendMessage(new HandlerController() { ListenerId = lid }, notification, callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(pair.Key).OnSendMessage(new HandlerController() { ListenerId = lid }, notification, callback => { }));
} }
} }

View File

@ -54,7 +54,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
var notification = bgs.protocol.channel.v1.InvitationAddedNotification.CreateBuilder().SetInvitation(invitation); var notification = bgs.protocol.channel.v1.InvitationAddedNotification.CreateBuilder().SetInvitation(invitation);
invitee.MakeTargetedRPC(this, (lid) => invitee.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelInvitationListener.CreateStub(invitee).OnReceivedInvitationAdded(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { })); bgs.protocol.channel.v1.ChannelInvitationListener.CreateStub(invitee).OnReceivedInvitationAdded(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
} }
@ -80,7 +80,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
_onGoingInvitations.Remove(invitation.Id); _onGoingInvitations.Remove(invitation.Id);
GoingInvitations.Remove(request.InvitationId); GoingInvitations.Remove(request.InvitationId);
client.MakeTargetedRPC(this, (lid) => client.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelInvitationListener.CreateStub(client).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { })); bgs.protocol.channel.v1.ChannelInvitationListener.CreateStub(client).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
channel.Join(client, request.ObjectId); channel.Join(client, request.ObjectId);
@ -92,7 +92,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
foreach (var member in channel.Members.Keys) foreach (var member in channel.Members.Keys)
{ {
member.MakeTargetedRPC(channel, (lid) => member.MakeTargetedRpc(channel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, stateNotification, callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, stateNotification, callback => { }));
} }
@ -157,7 +157,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
.SetStateChange(channelStatePermission) .SetStateChange(channelStatePermission)
.Build(); .Build();
JoinClient.MakeTargetedRPC(JoinClient.CurrentChannel, (lid) => JoinClient.MakeTargetedRpc(JoinClient.CurrentChannel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(JoinClient).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notificationPermission, callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(JoinClient).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notificationPermission, callback => { }));
} }
gameFound.StartGame(clients, gameFound.DynamicId); gameFound.StartGame(clients, gameFound.DynamicId);
@ -171,7 +171,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
.SetValue(Variant.CreateBuilder().SetUintValue(gameFound.RequestId).Build()); .SetValue(Variant.CreateBuilder().SetUintValue(gameFound.RequestId).Build());
notificationFound.AddAttribute(attrF); notificationFound.AddAttribute(attrF);
JoinClient.MakeRPC((lid) => JoinClient.MakeRpc((lid) =>
bgs.protocol.notification.v1.NotificationListener.CreateStub(JoinClient).OnNotificationReceived(new HandlerController() { ListenerId = lid }, notificationFound.Build(), callback => { })); bgs.protocol.notification.v1.NotificationListener.CreateStub(JoinClient).OnNotificationReceived(new HandlerController() { ListenerId = lid }, notificationFound.Build(), callback => { }));
@ -186,7 +186,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
notification.SetGameHandle(gh); notification.SetGameHandle(gh);
System.Threading.Tasks.Task.Delay(2000).ContinueWith(delegate { System.Threading.Tasks.Task.Delay(2000).ContinueWith(delegate {
JoinClient.MakeRPC((lid) => bgs.protocol.matchmaking.v1.GameRequestListener.CreateStub(JoinClient).OnMatchmakingResult(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { })); JoinClient.MakeRpc((lid) => bgs.protocol.matchmaking.v1.GameRequestListener.CreateStub(JoinClient).OnMatchmakingResult(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
}); });
#endregion #endregion
@ -236,9 +236,9 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
foreach (var member in channel.Members.Keys) foreach (var member in channel.Members.Keys)
{ {
member.MakeTargetedRPC(channel, (lid) => member.MakeTargetedRpc(channel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, stateNotification, callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, stateNotification, callback => { }));
member.MakeTargetedRPC(channel, (lid) => member.MakeTargetedRpc(channel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnJoin(new HandlerController() { ListenerId = lid }, joinstateNotification, callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnJoin(new HandlerController() { ListenerId = lid }, joinstateNotification, callback => { }));
} }
@ -264,7 +264,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
client.MakeTargetedRPC(this, (lid) => bgs.protocol.channel.v1.ChannelInvitationListener.CreateStub(client).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { })); client.MakeTargetedRpc(this, (lid) => bgs.protocol.channel.v1.ChannelInvitationListener.CreateStub(client).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
channel.Join(mem, request.ObjectId); // add invitee to channel -- so inviter and other members will also be notified too. channel.Join(mem, request.ObjectId); // add invitee to channel -- so inviter and other members will also be notified too.
@ -281,7 +281,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
foreach (var member in channel.Members.Keys) foreach (var member in channel.Members.Keys)
{ {
member.MakeTargetedRPC(channel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, stateNotification, callback => { })); member.MakeTargetedRpc(channel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, stateNotification, callback => { }));
//member.MakeTargetedRPC(channel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnJoin(new HandlerController() { ListenerId = lid }, build, callback => { })); //member.MakeTargetedRPC(channel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnJoin(new HandlerController() { ListenerId = lid }, build, callback => { }));
} }
@ -305,7 +305,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
_onGoingInvitations.Remove(invitation.Id); _onGoingInvitations.Remove(invitation.Id);
GoingInvitations.Remove(request.InvitationId); GoingInvitations.Remove(request.InvitationId);
inviter.LoggedInClient.MakeTargetedRPC(inviter.LoggedInClient.CurrentChannel, (lid) => inviter.LoggedInClient.MakeTargetedRpc(inviter.LoggedInClient.CurrentChannel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(inviter.LoggedInClient).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(inviter.LoggedInClient).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
} }
@ -328,7 +328,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
_onGoingInvitations.Remove(request.InvitationId); _onGoingInvitations.Remove(request.InvitationId);
GoingInvitations.Remove(request.InvitationId); GoingInvitations.Remove(request.InvitationId);
inviter.LoggedInClient.MakeTargetedRPC(inviter.LoggedInClient.CurrentChannel, (lid) => inviter.LoggedInClient.MakeTargetedRpc(inviter.LoggedInClient.CurrentChannel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, updateChannelNotification.Build(), callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, updateChannelNotification.Build(), callback => { }));
//notify invitee about revoke //notify invitee about revoke
@ -339,7 +339,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
if (Subscribers.All(subscriber => subscriber.Key.Account.GameAccount.BnetEntityId.Low != invitation.InviteeIdentity.AccountId.Low)) return; if (Subscribers.All(subscriber => subscriber.Key.Account.GameAccount.BnetEntityId.Low != invitation.InviteeIdentity.AccountId.Low)) return;
client.MakeTargetedRPC(this, (lid) => client.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelInvitationListener.CreateStub(client).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, invitationRemoved.Build(), callback => { })); bgs.protocol.channel.v1.ChannelInvitationListener.CreateStub(client).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, invitationRemoved.Build(), callback => { }));
} }

View File

@ -67,7 +67,7 @@ namespace DiIiS_NA.LoginServer.FriendsSystem
.SetInvitation(invitation) .SetInvitation(invitation)
.SetAccountId(invitee.BnetEntityId); .SetAccountId(invitee.BnetEntityId);
invitee.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) => invitee.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(invitee.GameAccount.LoggedInClient).OnReceivedInvitationAdded(new HandlerController() { ListenerId = lid }, notification.Build(), callback => bgs.protocol.friends.v1.FriendsListener.CreateStub(invitee.GameAccount.LoggedInClient).OnReceivedInvitationAdded(new HandlerController() { ListenerId = lid }, notification.Build(), callback =>
{ {
})); }));
@ -89,13 +89,13 @@ namespace DiIiS_NA.LoginServer.FriendsSystem
if (inviter.GameAccount.IsOnline) if (inviter.GameAccount.IsOnline)
{ {
inviter.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) => inviter.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(inviter.GameAccount.LoggedInClient).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, declinedNotification, callback => { })); bgs.protocol.friends.v1.FriendsListener.CreateStub(inviter.GameAccount.LoggedInClient).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, declinedNotification, callback => { }));
} }
if (invitee.GameAccount.IsOnline) if (invitee.GameAccount.IsOnline)
{ {
invitee.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) => invitee.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(invitee.GameAccount.LoggedInClient).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, declinedNotification, callback => { })); bgs.protocol.friends.v1.FriendsListener.CreateStub(invitee.GameAccount.LoggedInClient).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, declinedNotification, callback => { }));
} }
@ -144,19 +144,19 @@ namespace DiIiS_NA.LoginServer.FriendsSystem
if (inviter.GameAccount.IsOnline) if (inviter.GameAccount.IsOnline)
{ {
inviter.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) => inviter.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(inviter.GameAccount.LoggedInClient).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, notificationToInviter, callback => { })); bgs.protocol.friends.v1.FriendsListener.CreateStub(inviter.GameAccount.LoggedInClient).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, notificationToInviter, callback => { }));
inviter.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) => inviter.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(inviter.GameAccount.LoggedInClient).OnFriendAdded(new HandlerController() { ListenerId = lid }, friendAddedNotificationToInviter, callback => { })); bgs.protocol.friends.v1.FriendsListener.CreateStub(inviter.GameAccount.LoggedInClient).OnFriendAdded(new HandlerController() { ListenerId = lid }, friendAddedNotificationToInviter, callback => { }));
} }
if (invitee.GameAccount.IsOnline) if (invitee.GameAccount.IsOnline)
{ {
invitee.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) => invitee.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(invitee.GameAccount.LoggedInClient).OnFriendAdded(new HandlerController() { ListenerId = lid }, friendAddedNotificationToInvitee, callback => { })); bgs.protocol.friends.v1.FriendsListener.CreateStub(invitee.GameAccount.LoggedInClient).OnFriendAdded(new HandlerController() { ListenerId = lid }, friendAddedNotificationToInvitee, callback => { }));
invitee.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) => invitee.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(invitee.GameAccount.LoggedInClient).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, notificationToInvitee, callback => { })); bgs.protocol.friends.v1.FriendsListener.CreateStub(invitee.GameAccount.LoggedInClient).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, notificationToInvitee, callback => { }));
} }
@ -177,13 +177,13 @@ namespace DiIiS_NA.LoginServer.FriendsSystem
if (inviter.GameAccount.IsOnline) if (inviter.GameAccount.IsOnline)
{ {
inviter.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) => inviter.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(inviter.GameAccount.LoggedInClient).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, declinedNotification, callback => { })); bgs.protocol.friends.v1.FriendsListener.CreateStub(inviter.GameAccount.LoggedInClient).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, declinedNotification, callback => { }));
} }
if (invitee.GameAccount.IsOnline) if (invitee.GameAccount.IsOnline)
{ {
invitee.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) => invitee.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(invitee.GameAccount.LoggedInClient).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, declinedNotification, callback => { })); bgs.protocol.friends.v1.FriendsListener.CreateStub(invitee.GameAccount.LoggedInClient).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, declinedNotification, callback => { }));
} }
@ -215,13 +215,13 @@ namespace DiIiS_NA.LoginServer.FriendsSystem
.SetAccountId(remover.BnetEntityId) .SetAccountId(remover.BnetEntityId)
.Build(); .Build();
client.MakeTargetedRPC(FriendManager.Instance, (lid) => client.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(client).OnFriendRemoved(new HandlerController() { ListenerId = lid }, notifyRemover, callback => { })); bgs.protocol.friends.v1.FriendsListener.CreateStub(client).OnFriendRemoved(new HandlerController() { ListenerId = lid }, notifyRemover, callback => { }));
if (removee.GameAccount.IsOnline) if (removee.GameAccount.IsOnline)
{ {
var notifyRemovee = bgs.protocol.friends.v1.FriendNotification.CreateBuilder().SetTarget(removerAsFriend).SetAccountId(removee.BnetEntityId).Build(); var notifyRemovee = bgs.protocol.friends.v1.FriendNotification.CreateBuilder().SetTarget(removerAsFriend).SetAccountId(removee.BnetEntityId).Build();
removee.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) => bgs.protocol.friends.v1.FriendsListener.CreateStub(removee.GameAccount.LoggedInClient).OnFriendRemoved(new HandlerController() { ListenerId = lid }, notifyRemovee, callback => { })); removee.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) => bgs.protocol.friends.v1.FriendsListener.CreateStub(removee.GameAccount.LoggedInClient).OnFriendRemoved(new HandlerController() { ListenerId = lid }, notifyRemovee, callback => { }));
} }
} }

View File

@ -9,6 +9,7 @@ using DiIiS_NA.LoginServer.Objects;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -38,7 +39,7 @@ namespace DiIiS_NA.LoginServer.FriendsSystem
notifyBlock.SetPlayer(blockedPlayer); notifyBlock.SetPlayer(blockedPlayer);
notifyBlock.SetGameAccountId(blocked.BnetEntityId); notifyBlock.SetGameAccountId(blocked.BnetEntityId);
client.MakeTargetedRPC(UserManager.Instance, (lid) => client.MakeTargetedRpc(UserManager.Instance, (lid) =>
bgs.protocol.user_manager.v1.UserManagerListener.CreateStub(client).OnBlockedPlayerAdded(new HandlerController() { ListenerId = lid }, notifyBlock.Build(), callback => { })); bgs.protocol.user_manager.v1.UserManagerListener.CreateStub(client).OnBlockedPlayerAdded(new HandlerController() { ListenerId = lid }, notifyBlock.Build(), callback => { }));
} }
@ -60,13 +61,13 @@ namespace DiIiS_NA.LoginServer.FriendsSystem
var notifyUnblock = bgs.protocol.user_manager.v1.BlockedPlayerRemovedNotification.CreateBuilder(); var notifyUnblock = bgs.protocol.user_manager.v1.BlockedPlayerRemovedNotification.CreateBuilder();
notifyUnblock.SetPlayer(blockedPlayer); notifyUnblock.SetPlayer(blockedPlayer);
client.MakeTargetedRPC(UserManager.Instance, (lid) => client.MakeTargetedRpc(UserManager.Instance, (lid) =>
bgs.protocol.user_manager.v1.UserManagerListener.CreateStub(client).OnBlockedPlayerRemoved(new HandlerController() { ListenerId = lid }, notifyUnblock.Build(), callback => { })); bgs.protocol.user_manager.v1.UserManagerListener.CreateStub(client).OnBlockedPlayerRemoved(new HandlerController() { ListenerId = lid }, notifyUnblock.Build(), callback => { }));
} }
private static void AddIgnoreToDB(Account owner, Account target) private static void AddIgnoreToDB(Account owner, Account target)
{ {
Logger.Trace("AddIgnoreToDB(): owner {0}, target {1}", owner.PersistentID, target.PersistentID); Logger.MethodTrace($": owner {owner.PersistentID}, target {target.PersistentID}");
try try
{ {
if (DBSessions.SessionQueryWhere<DBAccountLists>(dbl => dbl.ListOwner.Id == owner.PersistentID && dbl.ListTarget.Id == target.PersistentID && dbl.Type == "IGNORE").Count() > 0) return; if (DBSessions.SessionQueryWhere<DBAccountLists>(dbl => dbl.ListOwner.Id == owner.PersistentID && dbl.ListTarget.Id == target.PersistentID && dbl.Type == "IGNORE").Count() > 0) return;
@ -87,7 +88,7 @@ namespace DiIiS_NA.LoginServer.FriendsSystem
private static void RemoveIgnoreFromDB(Account owner, Account target) private static void RemoveIgnoreFromDB(Account owner, Account target)
{ {
Logger.Trace("RemoveIgnoreFromDB(): owner {0}, target {1}", owner.PersistentID, target.PersistentID); Logger.MethodTrace($": owner {owner.PersistentID}, target {target.PersistentID}");
try try
{ {
var blockRecords = DBSessions.SessionQueryWhere<DBAccountLists>(dbl => dbl.ListOwner.Id == owner.PersistentID && dbl.ListTarget.Id == target.PersistentID && dbl.Type == "IGNORE"); var blockRecords = DBSessions.SessionQueryWhere<DBAccountLists>(dbl => dbl.ListOwner.Id == owner.PersistentID && dbl.ListTarget.Id == target.PersistentID && dbl.Type == "IGNORE");

View File

@ -8,6 +8,7 @@ using DiIiS_NA.LoginServer.Helpers;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -74,7 +75,7 @@ namespace DiIiS_NA.LoginServer.GamesSystem
public void StartGame(List<BattleClient> clients, ulong objectId) public void StartGame(List<BattleClient> clients, ulong objectId)
{ {
Logger.Trace("StartGame(): objectId: {0}", objectId); Logger.MethodTrace($"objectId: {objectId}");
var owner = this.Owner.Account.GameAccount.CurrentToon.DBToon; var owner = this.Owner.Account.GameAccount.CurrentToon.DBToon;
if (Program.BattleBackend.GameServers.Count == 0) return; if (Program.BattleBackend.GameServers.Count == 0) return;
@ -94,7 +95,7 @@ namespace DiIiS_NA.LoginServer.GamesSystem
foreach (var client in clients) foreach (var client in clients)
{ {
client.MapLocalObjectID(this.DynamicId, objectId); client.MapLocalObjectId(this.DynamicId, objectId);
this.SendConnectionInfo(client); this.SendConnectionInfo(client);
client.Account.GameAccount.ScreenStatus = D3.PartyMessage.ScreenStatus.CreateBuilder().SetScreen(0).SetStatus(0).Build(); client.Account.GameAccount.ScreenStatus = D3.PartyMessage.ScreenStatus.CreateBuilder().SetScreen(0).SetStatus(0).Build();
client.Account.GameAccount.NotifyUpdate(); client.Account.GameAccount.NotifyUpdate();
@ -108,7 +109,7 @@ namespace DiIiS_NA.LoginServer.GamesSystem
{ {
foreach (var client in clients) foreach (var client in clients)
{ {
client.MapLocalObjectID(this.DynamicId, objectId); client.MapLocalObjectId(this.DynamicId, objectId);
this.SendConnectionInfo(client); this.SendConnectionInfo(client);
client.Account.GameAccount.ScreenStatus = D3.PartyMessage.ScreenStatus.CreateBuilder().SetScreen(1).SetStatus(1).Build(); client.Account.GameAccount.ScreenStatus = D3.PartyMessage.ScreenStatus.CreateBuilder().SetScreen(1).SetStatus(1).Build();
client.Account.GameAccount.NotifyUpdate(); client.Account.GameAccount.NotifyUpdate();
@ -118,7 +119,7 @@ namespace DiIiS_NA.LoginServer.GamesSystem
public bgs.protocol.games.v2.ConnectInfo GetConnectionInfoForClient(BattleClient client) public bgs.protocol.games.v2.ConnectInfo GetConnectionInfoForClient(BattleClient client)
{ {
return bgs.protocol.games.v2.ConnectInfo.CreateBuilder() return bgs.protocol.games.v2.ConnectInfo.CreateBuilder()
.SetAddress(bgs.protocol.Address.CreateBuilder().SetAddress_(this.GServer.Value.GameIP).SetPort((uint)this.GServer.Value.GamePort)) .SetAddress(bgs.protocol.Address.CreateBuilder().SetAddress_(this.GServer.Value.GameIp).SetPort((uint)this.GServer.Value.GamePort))
.SetToken(Google.ProtocolBuffers.ByteString.CopyFrom(new byte[] { 0x31, 0x33, 0x38, 0x38, 0x35, 0x34, 0x33, 0x33, 0x32, 0x30, 0x38, 0x34, 0x30, 0x30, 0x38, 0x38, 0x35, 0x37, 0x39, 0x36 })) .SetToken(Google.ProtocolBuffers.ByteString.CopyFrom(new byte[] { 0x31, 0x33, 0x38, 0x38, 0x35, 0x34, 0x33, 0x33, 0x32, 0x30, 0x38, 0x34, 0x30, 0x30, 0x38, 0x38, 0x35, 0x37, 0x39, 0x36 }))
.AddAttribute(bgs.protocol.Attribute.CreateBuilder().SetName("Token").SetValue(bgs.protocol.Variant.CreateBuilder().SetUintValue(0xee34d06ffe821c43L))) .AddAttribute(bgs.protocol.Attribute.CreateBuilder().SetName("Token").SetValue(bgs.protocol.Variant.CreateBuilder().SetUintValue(0xee34d06ffe821c43L)))
@ -145,7 +146,7 @@ namespace DiIiS_NA.LoginServer.GamesSystem
.SetChannelState(channelStatePrivacyLevel) .SetChannelState(channelStatePrivacyLevel)
.Build(); .Build();
client.MakeTargetedRPC(client.CurrentChannel, (lid) => client.MakeTargetedRpc(client.CurrentChannel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notificationPrivacyLevel, callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notificationPrivacyLevel, callback => { }));
@ -165,7 +166,7 @@ namespace DiIiS_NA.LoginServer.GamesSystem
.SetChannelState(channelStatePartyLock) .SetChannelState(channelStatePartyLock)
.Build(); .Build();
client.MakeTargetedRPC(client.CurrentChannel, (lid) => client.MakeTargetedRpc(client.CurrentChannel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notificationPartyLock, callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notificationPartyLock, callback => { }));
} }
} }

View File

@ -486,7 +486,7 @@ namespace DiIiS_NA.LoginServer.GuildSystem
.SetTargetAccountId(account.Owner.BnetEntityId) .SetTargetAccountId(account.Owner.BnetEntityId)
.Build(); .Build();
account.LoggedInClient.MakeRPC((lid) => account.LoggedInClient.MakeRpc((lid) =>
bgs.protocol.notification.v1.NotificationListener.CreateStub(account.LoggedInClient).OnNotificationReceived(new HandlerController() { ListenerId = lid bgs.protocol.notification.v1.NotificationListener.CreateStub(account.LoggedInClient).OnNotificationReceived(new HandlerController() { ListenerId = lid
}, notificationBuilder, callback => { })); }, notificationBuilder, callback => { }));
@ -507,7 +507,7 @@ namespace DiIiS_NA.LoginServer.GuildSystem
.SetTargetAccountId(account.Owner.BnetEntityId) .SetTargetAccountId(account.Owner.BnetEntityId)
.Build(); .Build();
account.LoggedInClient.MakeRPC((lid) => account.LoggedInClient.MakeRpc((lid) =>
bgs.protocol.notification.v1.NotificationListener.CreateStub(account.LoggedInClient).OnNotificationReceived(new HandlerController() { ListenerId = lid bgs.protocol.notification.v1.NotificationListener.CreateStub(account.LoggedInClient).OnNotificationReceived(new HandlerController() { ListenerId = lid
}, chatNotificationBuilder, callback => { })); }, chatNotificationBuilder, callback => { }));
} }
@ -540,7 +540,7 @@ namespace DiIiS_NA.LoginServer.GuildSystem
foreach (var member in this.Channel.Members) foreach (var member in this.Channel.Members)
//member.Key.MakeTargetedRPC(this.Channel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(member.Key).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notification, callback => { })); //member.Key.MakeTargetedRPC(this.Channel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(member.Key).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notification, callback => { }));
member.Key.MakeTargetedRPC(this.Channel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(member.Key).OnJoin(new HandlerController() { ListenerId = lid }, altnotification, callback => { })); member.Key.MakeTargetedRpc(this.Channel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(member.Key).OnJoin(new HandlerController() { ListenerId = lid }, altnotification, callback => { }));
} }
public void UpdateMemberAttributes(GameAccount member) public void UpdateMemberAttributes(GameAccount member)
@ -565,7 +565,7 @@ namespace DiIiS_NA.LoginServer.GuildSystem
.Build(); .Build();
foreach (var mbr in this.Channel.Members) foreach (var mbr in this.Channel.Members)
mbr.Key.MakeTargetedRPC(this.Channel, (lid) => mbr.Key.MakeTargetedRpc(this.Channel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(mbr.Key).OnUpdateMemberState(new HandlerController() { ListenerId = lid }, notification, callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(mbr.Key).OnUpdateMemberState(new HandlerController() { ListenerId = lid }, notification, callback => { }));
} }

View File

@ -9,7 +9,7 @@ namespace DiIiS_NA.LoginServer.Objects
{ {
public class EntityIdPresenceFieldList public class EntityIdPresenceFieldList
{ {
public List<bgs.protocol.EntityId> Value = new List<bgs.protocol.EntityId>(); public List<bgs.protocol.EntityId> Value = new();
protected FieldKeyHelper.Program _program; protected FieldKeyHelper.Program _program;
protected FieldKeyHelper.OriginatingClass _originatingClass; protected FieldKeyHelper.OriginatingClass _originatingClass;

View File

@ -33,7 +33,7 @@ namespace DiIiS_NA.LoginServer.Objects
if (this.Subscribers.ContainsKey(client)) return; if (this.Subscribers.ContainsKey(client)) return;
this.Subscribers.TryAdd(client, 0); this.Subscribers.TryAdd(client, 0);
client.MapLocalObjectID(this.DynamicId, remoteObjectId); client.MapLocalObjectId(this.DynamicId, remoteObjectId);
if (client.SocketConnection.Active) if (client.SocketConnection.Active)
{ {
@ -56,7 +56,7 @@ namespace DiIiS_NA.LoginServer.Objects
return new List<bgs.protocol.presence.v1.FieldOperation>(); return new List<bgs.protocol.presence.v1.FieldOperation>();
} }
public Helpers.FieldKeyHelper ChangedFields = new Helpers.FieldKeyHelper(); public readonly Helpers.FieldKeyHelper ChangedFields = new();
protected void NotifySubscriptionAdded(BattleClient client) protected void NotifySubscriptionAdded(BattleClient client)
{ {
@ -96,8 +96,8 @@ namespace DiIiS_NA.LoginServer.Objects
var altnotification = bgs.protocol.channel.v1.JoinNotification.CreateBuilder().SetChannelState(channelState); var altnotification = bgs.protocol.channel.v1.JoinNotification.CreateBuilder().SetChannelState(channelState);
if (gameAccount.LoggedInClient != null) if (gameAccount.LoggedInClient != null)
{ {
gameAccount.LoggedInClient.MakeTargetedRPC(this, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(gameAccount.LoggedInClient).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { })); gameAccount.LoggedInClient.MakeTargetedRpc(this, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(gameAccount.LoggedInClient).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
gameAccount.LoggedInClient.MakeTargetedRPC(this, (lid) => gameAccount.LoggedInClient.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(gameAccount.LoggedInClient).OnJoin(new HandlerController() { ListenerId = lid }, altnotification.Build(), callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(gameAccount.LoggedInClient).OnJoin(new HandlerController() { ListenerId = lid }, altnotification.Build(), callback => { }));
} }
} }
@ -110,10 +110,10 @@ namespace DiIiS_NA.LoginServer.Objects
var channelState = bgs.protocol.channel.v1.ChannelState.CreateBuilder().SetExtension(bgs.protocol.presence.v1.ChannelState.Presence, state); var channelState = bgs.protocol.channel.v1.ChannelState.CreateBuilder().SetExtension(bgs.protocol.presence.v1.ChannelState.Presence, state);
var builder = bgs.protocol.channel.v1.JoinNotification.CreateBuilder().SetChannelState(channelState); var builder = bgs.protocol.channel.v1.JoinNotification.CreateBuilder().SetChannelState(channelState);
var notification = bgs.protocol.channel.v1.UpdateChannelStateNotification.CreateBuilder().SetStateChange(channelState); var notification = bgs.protocol.channel.v1.UpdateChannelStateNotification.CreateBuilder().SetStateChange(channelState);
client.MakeTargetedRPC(this, (lid) => client.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnJoin(new HandlerController() { ListenerId = lid }, builder.Build(), callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnJoin(new HandlerController() { ListenerId = lid }, builder.Build(), callback => { }));
client.MakeTargetedRPC(this, (lid) => client.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
} }

View File

@ -10,7 +10,7 @@ namespace DiIiS_NA.LoginServer.Objects
private static readonly Logger Logger = LogManager.CreateLogger(); private static readonly Logger Logger = LogManager.CreateLogger();
private static ulong _nextId = 10000; private static ulong _nextId = 10000;
public static readonly Dictionary<ulong, RPCObject> Objects = new Dictionary<ulong, RPCObject>(); public static readonly Dictionary<ulong, RPCObject> Objects = new();
static RPCObjectManager() static RPCObjectManager()
{ } { }

View File

@ -20,7 +20,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
GetAccountStateResponse.Builder builder = GetAccountStateResponse.CreateBuilder(); GetAccountStateResponse.Builder builder = GetAccountStateResponse.CreateBuilder();
var AccState = AccountState.CreateBuilder(); var AccState = AccountState.CreateBuilder();
if (request.EntityId.Low == (controller as HandlerController).Client.Account.BnetEntityId.Low) if (request.EntityId.Low == ((HandlerController) controller).Client.Account.BnetEntityId.Low)
{ {
if (request.Options.FieldPrivacyInfo) if (request.Options.FieldPrivacyInfo)
{ {
@ -49,9 +49,9 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
level.SetCountry("RUS"); level.SetCountry("RUS");
level.SetPreferredRegion(1); level.SetPreferredRegion(1);
level.SetFullName("Name LastName"); level.SetFullName("Name LastName");
level.SetBattleTag((controller as HandlerController).Client.Account.BattleTag); level.SetBattleTag(((HandlerController) controller).Client.Account.BattleTag);
level.SetAccountPaidAny(true); level.SetAccountPaidAny(true);
level.SetEmail((controller as HandlerController).Client.Account.Email).SetHeadlessAccount(false); level.SetEmail(((HandlerController) controller).Client.Account.Email).SetHeadlessAccount(false);
AccState.SetAccountLevelInfo(level); AccState.SetAccountLevelInfo(level);

View File

@ -88,21 +88,21 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
} }
switch (request.Locale) switch (request.Locale)
{ {
case "deDE": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.deDE; break; case "deDE": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.DE_DE; break;
case "enGB": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.enGB; break; case "enGB": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.EN_GB; break;
case "enSG": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.enSG; break; case "enSG": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.EN_SG; break;
case "enUS": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.enUS; break; case "enUS": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.EN_US; break;
case "esES": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.esES; break; case "esES": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.ES_ES; break;
case "esMX": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.esMX; break; case "esMX": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.ES_MX; break;
case "frFR": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.frFR; break; case "frFR": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.FR_FR; break;
case "itIT": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.itIT; break; case "itIT": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.IT_IT; break;
case "koKR": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.koKR; break; case "koKR": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.KO_KR; break;
case "plPL": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.plPL; break; case "plPL": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.PL_PL; break;
case "ptBR": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.ptBR; break; case "ptBR": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.PT_BR; break;
case "ptPT": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.ptPT; break; case "ptPT": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.PT_PT; break;
case "ruRU": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.ruRU; break; case "ruRU": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.RU_RU; break;
case "trTR": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.trTR; break; case "trTR": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.TR_TR; break;
case "zhCN": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.zhCN; break; case "zhCN": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.ZH_CN; break;
} }
done(NoData.CreateBuilder().Build()); done(NoData.CreateBuilder().Build());
var builder = ChallengeExternalRequest.CreateBuilder(); var builder = ChallengeExternalRequest.CreateBuilder();
@ -124,7 +124,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
builder.SetPayload(ByteString.CopyFromUtf8( builder.SetPayload(ByteString.CopyFromUtf8(
$"http://{Program.RESTSERVERIP}:{REST.Config.Instance.PORT}/battlenet/login")); $"http://{Program.RESTSERVERIP}:{REST.Config.Instance.PORT}/battlenet/login"));
((HandlerController)controller).Client.MakeRPC((lid) => ChallengeListener.CreateStub(((HandlerController)controller).Client).OnExternalChallenge(controller, builder.Build(), callback => { })); ((HandlerController)controller).Client.MakeRpc((lid) => ChallengeListener.CreateStub(((HandlerController)controller).Client).OnExternalChallenge(controller, builder.Build(), callback => { }));
#endregion #endregion
} }
break; break;
@ -191,7 +191,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
if (((HandlerController)controller).Client.Account == null) if (((HandlerController)controller).Client.Account == null)
{ {
var complete = LogonResult.CreateBuilder().SetErrorCode(2); var complete = LogonResult.CreateBuilder().SetErrorCode(2);
((HandlerController)controller).Client.MakeRPC((lid) => AuthenticationListener.CreateStub(((HandlerController)controller).Client).OnLogonComplete(controller, complete.Build(), callback => { })); ((HandlerController)controller).Client.MakeRpc((lid) => AuthenticationListener.CreateStub(((HandlerController)controller).Client).OnLogonComplete(controller, complete.Build(), callback => { }));
((HandlerController)controller).Client.SocketConnection.CloseAsync(); ((HandlerController)controller).Client.SocketConnection.CloseAsync();
((HandlerController)controller).Client.Connect.CloseAsync(); ((HandlerController)controller).Client.Connect.CloseAsync();
} }
@ -210,12 +210,12 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
.SetErrorCode(0) .SetErrorCode(0)
.AddGameAccountId(((HandlerController)controller).Client.Account.GameAccount.BnetEntityId); //D3 .AddGameAccountId(((HandlerController)controller).Client.Account.GameAccount.BnetEntityId); //D3
((HandlerController)controller).Client.Account.GameAccount.LoggedInClient = ((HandlerController)controller).Client; ((HandlerController)controller).Client.Account.GameAccount.LoggedInClient = ((HandlerController)controller).Client;
((HandlerController)controller).Client.MakeRPC((lid) => AuthenticationListener.CreateStub(((HandlerController)controller).Client).OnLogonComplete(controller, complete.Build(), callback => { })); ((HandlerController)controller).Client.MakeRpc((lid) => AuthenticationListener.CreateStub(((HandlerController)controller).Client).OnLogonComplete(controller, complete.Build(), callback => { }));
PlayerManager.PlayerConnected(((HandlerController)controller).Client); PlayerManager.PlayerConnected(((HandlerController)controller).Client);
var selectedGameAccount = GameAccountSelectedRequest.CreateBuilder().SetResult(0).SetGameAccountId(((HandlerController)controller).Client.Account.GameAccount.BnetEntityId); var selectedGameAccount = GameAccountSelectedRequest.CreateBuilder().SetResult(0).SetGameAccountId(((HandlerController)controller).Client.Account.GameAccount.BnetEntityId);
((HandlerController)controller).Client.MakeRPC((lid) => ((HandlerController)controller).Client.MakeRpc((lid) =>
AuthenticationListener.CreateStub(((HandlerController)controller).Client).OnGameAccountSelected(new HandlerController() { ListenerId = lid }, selectedGameAccount.Build(), callback => { })); AuthenticationListener.CreateStub(((HandlerController)controller).Client).OnGameAccountSelected(new HandlerController() { ListenerId = lid }, selectedGameAccount.Build(), callback => { }));
} }
#endregion #endregion

View File

@ -19,9 +19,9 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
public override void Subscribe(Google.ProtocolBuffers.IRpcController controller, SubscribeRequest request, Action<NoData> done) public override void Subscribe(Google.ProtocolBuffers.IRpcController controller, SubscribeRequest request, Action<NoData> done)
{ {
Logger.Trace("Subscribe() {0}", ((controller as HandlerController).Client)); Logger.Trace("Subscribe() {0}", (((HandlerController) controller).Client));
_invitationManager.AddSubscriber(((controller as HandlerController).Client), request.ObjectId); _invitationManager.AddSubscriber((((HandlerController) controller).Client), request.ObjectId);
done(NoData.DefaultInstance); done(NoData.DefaultInstance);
} }
@ -32,7 +32,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var response = AcceptInvitationResponse.CreateBuilder().SetObjectId(channel.DynamicId).Build(); var response = AcceptInvitationResponse.CreateBuilder().SetObjectId(channel.DynamicId).Build();
done(response); done(response);
_invitationManager.HandleAccept(((controller as HandlerController).Client), request); _invitationManager.HandleAccept((((HandlerController) controller).Client), request);
} }
public override void DeclineInvitation(Google.ProtocolBuffers.IRpcController controller, DeclineInvitationRequest request, Action<NoData> done) public override void DeclineInvitation(Google.ProtocolBuffers.IRpcController controller, DeclineInvitationRequest request, Action<NoData> done)
@ -40,7 +40,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var respone = NoData.CreateBuilder(); var respone = NoData.CreateBuilder();
done(respone.Build()); done(respone.Build());
_invitationManager.HandleDecline(((controller as HandlerController).Client), request); _invitationManager.HandleDecline((((HandlerController) controller).Client), request);
} }
public override void RevokeInvitation(Google.ProtocolBuffers.IRpcController controller, RevokeInvitationRequest request, Action<NoData> done) public override void RevokeInvitation(Google.ProtocolBuffers.IRpcController controller, RevokeInvitationRequest request, Action<NoData> done)
@ -48,16 +48,16 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var builder = NoData.CreateBuilder(); var builder = NoData.CreateBuilder();
done(builder.Build()); done(builder.Build());
_invitationManager.Revoke(((controller as HandlerController).Client), request); _invitationManager.Revoke((((HandlerController) controller).Client), request);
} }
public override void SendInvitation(Google.ProtocolBuffers.IRpcController controller, SendInvitationRequest request, Action<NoData> done) public override void SendInvitation(Google.ProtocolBuffers.IRpcController controller, SendInvitationRequest request, Action<NoData> done)
{ {
var invitee = GameAccountManager.GetAccountByPersistentID(request.TargetId.Low); var invitee = GameAccountManager.GetAccountByPersistentID(request.TargetId.Low);
if (invitee.Owner.IgnoreIds.Contains((controller as HandlerController).Client.Account.PersistentID)) if (invitee.Owner.IgnoreIds.Contains(((HandlerController) controller).Client.Account.PersistentID))
{ {
((controller as HandlerController).Status) = 403; (((HandlerController) controller).Status) = 403;
done(NoData.CreateBuilder().Build()); done(NoData.CreateBuilder().Build());
return; return;
} }
@ -82,8 +82,8 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var invitation = Invitation.CreateBuilder(); var invitation = Invitation.CreateBuilder();
invitation.SetId(ChannelInvitationManager.InvitationIdCounter++) invitation.SetId(ChannelInvitationManager.InvitationIdCounter++)
.SetInviterIdentity(Identity.CreateBuilder().SetGameAccountId((controller as HandlerController).Client.Account.GameAccount.BnetEntityId).Build()) .SetInviterIdentity(Identity.CreateBuilder().SetGameAccountId(((HandlerController) controller).Client.Account.GameAccount.BnetEntityId).Build())
.SetInviterName((controller as HandlerController).Client.Account.GameAccount.Owner.BattleTag) .SetInviterName(((HandlerController) controller).Client.Account.GameAccount.Owner.BattleTag)
.SetInviteeIdentity(Identity.CreateBuilder().SetGameAccountId(request.TargetId).Build()) .SetInviteeIdentity(Identity.CreateBuilder().SetGameAccountId(request.TargetId).Build())
.SetInviteeName(invitee.Owner.BattleTag) .SetInviteeName(invitee.Owner.BattleTag)
.SetInvitationMessage(request.Params.InvitationMessage) .SetInvitationMessage(request.Params.InvitationMessage)
@ -101,12 +101,12 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var builder = JoinNotification.CreateBuilder().SetChannelState(ChannelState.CreateBuilder().AddInvitation(invitation.Clone())); var builder = JoinNotification.CreateBuilder().SetChannelState(ChannelState.CreateBuilder().AddInvitation(invitation.Clone()));
(controller as HandlerController).Client.MakeTargetedRPC(channel, (lid) => ChannelListener.CreateStub((controller as HandlerController).Client) ((HandlerController) controller).Client.MakeTargetedRpc(channel, (lid) => ChannelListener.CreateStub(((HandlerController) controller).Client)
.OnUpdateChannelState(controller, notification.Build(), callback => { })); .OnUpdateChannelState(controller, notification.Build(), callback => { }));
(controller as HandlerController).Client.MakeTargetedRPC(channel, (lid) => ((HandlerController) controller).Client.MakeTargetedRpc(channel, (lid) =>
ChannelListener.CreateStub((controller as HandlerController).Client).OnJoin(new HandlerController() { ListenerId = lid }, builder.Build(), callback => { })); ChannelListener.CreateStub(((HandlerController) controller).Client).OnJoin(new HandlerController() { ListenerId = lid }, builder.Build(), callback => { }));
_invitationManager.HandleInvitation((controller as HandlerController).Client, invitation.Build()); _invitationManager.HandleInvitation(((HandlerController) controller).Client, invitation.Build());
} }
@ -118,7 +118,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
if (suggestee.Owner.IgnoreIds.Contains(suggester.Owner.PersistentID)) if (suggestee.Owner.IgnoreIds.Contains(suggester.Owner.PersistentID))
{ {
((controller as HandlerController).Status) = 403; (((HandlerController) controller).Status) = 403;
done(NoData.CreateBuilder().Build()); done(NoData.CreateBuilder().Build());
return; return;
} }
@ -137,7 +137,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var notification = SuggestionAddedNotification.CreateBuilder().SetSuggestion(suggestion); var notification = SuggestionAddedNotification.CreateBuilder().SetSuggestion(suggestion);
suggestee.LoggedInClient.MakeTargetedRPC(_invitationManager, (lid) => suggestee.LoggedInClient.MakeTargetedRpc(_invitationManager, (lid) =>
ChannelInvitationListener.CreateStub(suggestee.LoggedInClient).OnReceivedSuggestionAdded(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { })); ChannelInvitationListener.CreateStub(suggestee.LoggedInClient).OnReceivedSuggestionAdded(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
} }

View File

@ -16,15 +16,15 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
public override void CreateChannel(IRpcController controller, CreateChannelRequest request, Action<CreateChannelResponse> done) public override void CreateChannel(IRpcController controller, CreateChannelRequest request, Action<CreateChannelResponse> done)
{ {
var channel = ChannelManager.CreateNewChannel(((controller as HandlerController).Client), request.ObjectId); var channel = ChannelManager.CreateNewChannel((((HandlerController) controller).Client), request.ObjectId);
var builder = CreateChannelResponse.CreateBuilder() var builder = CreateChannelResponse.CreateBuilder()
.SetObjectId(channel.DynamicId) .SetObjectId(channel.DynamicId)
.SetChannelId(channel.BnetEntityId) .SetChannelId(channel.BnetEntityId)
; ;
done(builder.Build()); done(builder.Build());
channel.SetOwner(((controller as HandlerController).Client)); channel.SetOwner((((HandlerController) controller).Client));
channel.AddMember(((controller as HandlerController).Client)); channel.AddMember((((HandlerController) controller).Client));
} }
public override void ListChannels(IRpcController controller, ListChannelsRequest request, Action<ListChannelsResponse> done) public override void ListChannels(IRpcController controller, ListChannelsRequest request, Action<ListChannelsResponse> done)
@ -34,7 +34,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
foreach (Channel channel in chatChannels) foreach (Channel channel in chatChannels)
{ {
if (!channel.HasUser(((controller as HandlerController).Client)) && (request.Options.HasName ? request.Options.Name == channel.Name : true) && channel.MaxMembers > channel.Members.Count) if (!channel.HasUser((((HandlerController) controller).Client)) && (request.Options.HasName ? request.Options.Name == channel.Name : true) && channel.MaxMembers > channel.Members.Count)
builder.AddChannel(ChannelDescription.CreateBuilder().SetCurrentMembers((uint)channel.Members.Count) builder.AddChannel(ChannelDescription.CreateBuilder().SetCurrentMembers((uint)channel.Members.Count)
.SetChannelId(bgs.protocol.EntityId.CreateBuilder().SetHigh(channel.BnetEntityId.High).SetLow(channel.BnetEntityId.Low)) .SetChannelId(bgs.protocol.EntityId.CreateBuilder().SetHigh(channel.BnetEntityId.High).SetLow(channel.BnetEntityId.Low))
.SetState(channel.State)); .SetState(channel.State));
@ -59,10 +59,10 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
{ {
var channel = ChannelManager.GetChannelByEntityId(request.ChannelId); var channel = ChannelManager.GetChannelByEntityId(request.ChannelId);
channel.Join(((controller as HandlerController).Client), request.ObjectId); channel.Join((((HandlerController) controller).Client), request.ObjectId);
var builder = JoinChannelResponse.CreateBuilder().SetObjectId(channel.DynamicId).SetMemberId((controller as HandlerController).Client.Account.BnetEntityId); var builder = JoinChannelResponse.CreateBuilder().SetObjectId(channel.DynamicId).SetMemberId(((HandlerController) controller).Client.Account.BnetEntityId);
((controller as HandlerController).Client).ChatChannels.Add(channel); (((HandlerController) controller).Client).ChatChannels.Add(channel);
done(builder.Build()); done(builder.Build());
} }
@ -77,8 +77,8 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
builder.SetObjectId(channel.DynamicId); builder.SetObjectId(channel.DynamicId);
done(builder.Build()); done(builder.Build());
((controller as HandlerController).Client).ChatChannels.Add(channel); (((HandlerController) controller).Client).ChatChannels.Add(channel);
channel.Join(((controller as HandlerController).Client), request.ObjectId); channel.Join((((HandlerController) controller).Client), request.ObjectId);
} }
} }

View File

@ -10,6 +10,7 @@ using DiIiS_NA.LoginServer.ChannelSystem;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -28,8 +29,8 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
public override void RemoveMember(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.RemoveMemberRequest request, Action<bgs.protocol.NoData> done) public override void RemoveMember(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.RemoveMemberRequest request, Action<bgs.protocol.NoData> done)
{ {
Logger.Trace("RemoveMember()"); Logger.MethodTrace("");
var channel = ChannelManager.GetChannelByDynamicId(((controller as HandlerController).LastCallHeader).ObjectId); var channel = ChannelManager.GetChannelByDynamicId((((HandlerController) controller).LastCallHeader).ObjectId);
var gameAccount = GameAccountManager.GetAccountByPersistentID(request.MemberId.Low); var gameAccount = GameAccountManager.GetAccountByPersistentID(request.MemberId.Low);
var builder = bgs.protocol.NoData.CreateBuilder(); var builder = bgs.protocol.NoData.CreateBuilder();
@ -38,17 +39,17 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
channel.RemoveMember(gameAccount.LoggedInClient, Channel.GetRemoveReasonForRequest((Channel.RemoveRequestReason)request.Reason)); channel.RemoveMember(gameAccount.LoggedInClient, Channel.GetRemoveReasonForRequest((Channel.RemoveRequestReason)request.Reason));
if (request.Reason == 0) if (request.Reason == 0)
{ {
ulong invId = ChannelInvitationManager.FindInvAsForClient((controller as HandlerController).Client); ulong invId = ChannelInvitationManager.FindInvAsForClient(((HandlerController) controller).Client);
if (invId != UInt64.MaxValue) if (invId != UInt64.MaxValue)
ChannelInvitationManager.AltConnectToJoin((controller as HandlerController).Client, bgs.protocol.channel.v1.AcceptInvitationRequest.CreateBuilder().SetInvitationId(invId).SetObjectId(0).Build()); ChannelInvitationManager.AltConnectToJoin(((HandlerController) controller).Client, bgs.protocol.channel.v1.AcceptInvitationRequest.CreateBuilder().SetInvitationId(invId).SetObjectId(0).Build());
//ServicesSystem.Services.ChannelInvitationService.CreateStub((controller as HandlerController).Client).AcceptInvitation(controller, bgs.protocol.channel.v1.AcceptInvitationRequest.CreateBuilder().SetInvitationId(invId).SetObjectId(0).Build(), callback => { }); //ServicesSystem.Services.ChannelInvitationService.CreateStub(((HandlerController) controller).Client).AcceptInvitation(controller, bgs.protocol.channel.v1.AcceptInvitationRequest.CreateBuilder().SetInvitationId(invId).SetObjectId(0).Build(), callback => { });
} }
} }
public override void SendMessage(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.SendMessageRequest request, Action<bgs.protocol.NoData> done) public override void SendMessage(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.SendMessageRequest request, Action<bgs.protocol.NoData> done)
{ {
var channel = ChannelManager.GetChannelByDynamicId(((controller as HandlerController).LastCallHeader).ObjectId); var channel = ChannelManager.GetChannelByDynamicId((((HandlerController) controller).LastCallHeader).ObjectId);
//Logger.Trace("{0} sent a message to channel {1}.", ((controller as HandlerController).Client).Account.GameAccount.CurrentToon, channel); //Logger.Trace("{0} sent a message to channel {1}.", (((HandlerController) controller).Client).Account.GameAccount.CurrentToon, channel);
var builder = bgs.protocol.NoData.CreateBuilder(); var builder = bgs.protocol.NoData.CreateBuilder();
done(builder.Build()); done(builder.Build());
@ -59,10 +60,10 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
if (request.Message.AttributeCount == 0 || !request.Message.AttributeList.First().HasValue) if (request.Message.AttributeCount == 0 || !request.Message.AttributeList.First().HasValue)
return; // check if it has attributes. return; // check if it has attributes.
var parsedAsCommand = CommandManager.TryParse(request.Message.AttributeList[0].Value.StringValue, ((controller as HandlerController).Client)); // try parsing the message as a command var parsedAsCommand = CommandManager.TryParse(request.Message.AttributeList[0].Value.StringValue, (((HandlerController) controller).Client)); // try parsing the message as a command
if (!parsedAsCommand) if (!parsedAsCommand)
channel.SendMessage(((controller as HandlerController).Client), request.Message); // if it's not parsed as an command - let channel itself to broadcast message to it's members. channel.SendMessage((((HandlerController) controller).Client), request.Message); // if it's not parsed as an command - let channel itself to broadcast message to it's members.
} }
public override void UpdateChannelState(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.UpdateChannelStateRequest request, Action<bgs.protocol.NoData> done) public override void UpdateChannelState(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.UpdateChannelStateRequest request, Action<bgs.protocol.NoData> done)
@ -75,9 +76,9 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
ServicesSystem.Services.ChannelInvitationService.CreateStub(this.LoggedInClient).AcceptInvitation(null, request.Build(), callback => { }); ServicesSystem.Services.ChannelInvitationService.CreateStub(this.LoggedInClient).AcceptInvitation(null, request.Build(), callback => { });
} }
//*/ //*/
Channel channel = ChannelManager.GetChannelByDynamicId(((controller as HandlerController).LastCallHeader).ObjectId); Channel channel = ChannelManager.GetChannelByDynamicId((((HandlerController) controller).LastCallHeader).ObjectId);
Logger.Debug("UpdateChannelState(): {0}", request.ToString()); Logger.MethodTrace(request.ToString());
foreach (bgs.protocol.Attribute attribute in request.StateChange.AttributeList) foreach (bgs.protocol.Attribute attribute in request.StateChange.AttributeList)
{ {
@ -88,7 +89,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var gameCreateParams = D3.OnlineService.GameCreateParams.ParseFrom(attribute.Value.MessageValue); var gameCreateParams = D3.OnlineService.GameCreateParams.ParseFrom(attribute.Value.MessageValue);
Logger.Debug("D3.Party.GameCreateParams: {0}", gameCreateParams.ToString()); Logger.Debug("D3.Party.GameCreateParams: {0}", gameCreateParams.ToString());
//D3.OnlineService.EntityId hero = gameCreateParams.Coop.ResumeFromSaveHeroId; //D3.OnlineService.EntityId hero = gameCreateParams.Coop.ResumeFromSaveHeroId;
bool clear_quests = ((controller as HandlerController).Client.GameChannel != null && gameCreateParams.CampaignOrAdventureMode.QuestStepId == -1 && bool clear_quests = (((HandlerController) controller).Client.GameChannel != null && gameCreateParams.CampaignOrAdventureMode.QuestStepId == -1 &&
(gameCreateParams.CampaignOrAdventureMode.SnoQuest == 87700 || (gameCreateParams.CampaignOrAdventureMode.SnoQuest == 87700 ||
gameCreateParams.CampaignOrAdventureMode.SnoQuest == 80322 || gameCreateParams.CampaignOrAdventureMode.SnoQuest == 80322 ||
gameCreateParams.CampaignOrAdventureMode.SnoQuest == 93595 || gameCreateParams.CampaignOrAdventureMode.SnoQuest == 93595 ||
@ -97,9 +98,9 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var paramsBuilder = D3.OnlineService.GameCreateParams.CreateBuilder(gameCreateParams); var paramsBuilder = D3.OnlineService.GameCreateParams.CreateBuilder(gameCreateParams);
var Mode = D3.OnlineService.CampaignOrAdventureModeCreateParams.CreateBuilder(gameCreateParams.CampaignOrAdventureMode); var Mode = D3.OnlineService.CampaignOrAdventureModeCreateParams.CreateBuilder(gameCreateParams.CampaignOrAdventureMode);
lock ((controller as HandlerController).Client.Account.GameAccount.CurrentToon.DBToon) lock (((HandlerController) controller).Client.Account.GameAccount.CurrentToon.DBToon)
{ {
DBToon toonByClient = ((controller as HandlerController).Client).Account.GameAccount.CurrentToon.DBToon; DBToon toonByClient = (((HandlerController) controller).Client).Account.GameAccount.CurrentToon.DBToon;
if(toonByClient.CurrentAct == 400) if(toonByClient.CurrentAct == 400)
toonByClient.CurrentAct = gameCreateParams.CampaignOrAdventureMode.Act; toonByClient.CurrentAct = gameCreateParams.CampaignOrAdventureMode.Act;
if (!clear_quests) if (!clear_quests)
@ -128,7 +129,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
//paramsBuilder.ClearCoop(); //paramsBuilder.ClearCoop();
//paramsBuilder.SetPvp(D3.OnlineService.PvPCreateParams.CreateBuilder().SetSnoWorld(79100)); //paramsBuilder.SetPvp(D3.OnlineService.PvPCreateParams.CreateBuilder().SetSnoWorld(79100));
/*var toon = ((controller as HandlerController).Client).Account.GameAccount.CurrentToon.DBToon; /*var toon = (((HandlerController) controller).Client).Account.GameAccount.CurrentToon.DBToon;
paramsBuilder.SetCoop(D3.OnlineService.CoopCreateParams.CreateBuilder() paramsBuilder.SetCoop(D3.OnlineService.CoopCreateParams.CreateBuilder()
.SetDifficultyLevel(toon.CurrentDifficulty) .SetDifficultyLevel(toon.CurrentDifficulty)
.SetAct(toon.CurrentAct) .SetAct(toon.CurrentAct)
@ -151,8 +152,8 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
else else
{ {
var gameCreateParamsBuilder = D3.OnlineService.GameCreateParams.CreateBuilder(); var gameCreateParamsBuilder = D3.OnlineService.GameCreateParams.CreateBuilder();
var toon = ((controller as HandlerController).Client).Account.GameAccount.CurrentToon; var toon = (((HandlerController) controller).Client).Account.GameAccount.CurrentToon;
var dbToon = ((controller as HandlerController).Client).Account.GameAccount.CurrentToon.DBToon; var dbToon = (((HandlerController) controller).Client).Account.GameAccount.CurrentToon.DBToon;
gameCreateParamsBuilder.SetGameType(1); gameCreateParamsBuilder.SetGameType(1);
gameCreateParamsBuilder.SetCreationFlags(0); gameCreateParamsBuilder.SetCreationFlags(0);
gameCreateParamsBuilder.SetCampaignOrAdventureMode(D3.OnlineService.CampaignOrAdventureModeCreateParams.CreateBuilder() gameCreateParamsBuilder.SetCampaignOrAdventureMode(D3.OnlineService.CampaignOrAdventureModeCreateParams.CreateBuilder()
@ -197,7 +198,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
else else
{ {
var oldScreen = D3.PartyMessage.ScreenStatus.ParseFrom(attribute.Value.MessageValue); var oldScreen = D3.PartyMessage.ScreenStatus.ParseFrom(attribute.Value.MessageValue);
((controller as HandlerController).Client).Account.GameAccount.ScreenStatus = oldScreen; (((HandlerController) controller).Client).Account.GameAccount.ScreenStatus = oldScreen;
// TODO: save screen status for use with friends -Egris // TODO: save screen status for use with friends -Egris
var attr = bgs.protocol.Attribute.CreateBuilder() var attr = bgs.protocol.Attribute.CreateBuilder()
@ -313,7 +314,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
} }
else else
{ {
Logger.Debug("UpdateChannelState(): Unknown attribute: {0}", attribute.Name); Logger.MethodTrace($"Unknown attribute: {attribute.Name}");
} }
} }
@ -324,13 +325,13 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
done(builder.Build()); done(builder.Build());
var notification = bgs.protocol.channel.v1.UpdateChannelStateNotification.CreateBuilder() var notification = bgs.protocol.channel.v1.UpdateChannelStateNotification.CreateBuilder()
.SetAgentId(((controller as HandlerController).Client).Account.GameAccount.BnetEntityId) .SetAgentId((((HandlerController) controller).Client).Account.GameAccount.BnetEntityId)
/* /*
.SetChannelId(bgs.protocol.channel.v1.ChannelId.CreateBuilder().SetId((uint)channel.BnetEntityId.Low)) .SetChannelId(bgs.protocol.channel.v1.ChannelId.CreateBuilder().SetId((uint)channel.BnetEntityId.Low))
.SetSubscriber(bgs.protocol.account.v1.Identity.CreateBuilder() .SetSubscriber(bgs.protocol.account.v1.Identity.CreateBuilder()
.SetAccount(bgs.protocol.account.v1.AccountId.CreateBuilder().SetId((uint)((controller as HandlerController).Client).Account.BnetEntityId.Low)) .SetAccount(bgs.protocol.account.v1.AccountId.CreateBuilder().SetId((uint)(((HandlerController) controller).Client).Account.BnetEntityId.Low))
.SetGameAccount(bgs.protocol.account.v1.GameAccountHandle.CreateBuilder() .SetGameAccount(bgs.protocol.account.v1.GameAccountHandle.CreateBuilder()
.SetId((uint)((controller as HandlerController).Client).Account.GameAccount.BnetEntityId.Low) .SetId((uint)(((HandlerController) controller).Client).Account.GameAccount.BnetEntityId.Low)
.SetProgram(17459) .SetProgram(17459)
.SetRegion(1)) .SetRegion(1))
.SetProcess(bgs.protocol.ProcessId.CreateBuilder().SetLabel(0).SetEpoch(DateTime.Today.ToUnixTime()))) .SetProcess(bgs.protocol.ProcessId.CreateBuilder().SetLabel(0).SetEpoch(DateTime.Today.ToUnixTime())))
@ -340,18 +341,18 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var altnotif = bgs.protocol.channel.v1.JoinNotification.CreateBuilder().SetChannelState(channel.State).Build(); var altnotif = bgs.protocol.channel.v1.JoinNotification.CreateBuilder().SetChannelState(channel.State).Build();
var client = (controller as HandlerController).Client; var client = ((HandlerController) controller).Client;
//Notify all Channel members //Notify all Channel members
foreach (var member in channel.Members.Keys) foreach (var member in channel.Members.Keys)
{ {
member.MakeTargetedRPC(channel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notification, callback => { })); member.MakeTargetedRpc(channel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notification, callback => { }));
} }
} }
public override void UpdateMemberState(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.UpdateMemberStateRequest request, Action<bgs.protocol.NoData> done) public override void UpdateMemberState(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.UpdateMemberStateRequest request, Action<bgs.protocol.NoData> done)
{ {
var channel = ChannelManager.GetChannelByDynamicId(((controller as HandlerController).LastCallHeader).ObjectId); var channel = ChannelManager.GetChannelByDynamicId((((HandlerController) controller).LastCallHeader).ObjectId);
var builder = bgs.protocol.NoData.CreateBuilder(); var builder = bgs.protocol.NoData.CreateBuilder();
done(builder.Build()); done(builder.Build());
@ -372,7 +373,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
else else
{ {
Logger.Trace("D3.PartyMember.GameId = null"); Logger.Trace("D3.PartyMember.GameId = null");
channel.RemoveMember((controller as HandlerController).Client, Channel.GetRemoveReasonForRequest((Channel.RemoveRequestReason)2)); channel.RemoveMember(((HandlerController) controller).Client, Channel.GetRemoveReasonForRequest((Channel.RemoveRequestReason)2));
} }
} }
@ -384,7 +385,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
channelMember.SetState(state); channelMember.SetState(state);
var notification = bgs.protocol.channel.v1.UpdateMemberStateNotification.CreateBuilder() var notification = bgs.protocol.channel.v1.UpdateMemberStateNotification.CreateBuilder()
.SetAgentId(((controller as HandlerController).Client).Account.GameAccount.BnetEntityId) .SetAgentId((((HandlerController) controller).Client).Account.GameAccount.BnetEntityId)
.AddStateChange(channelMember) .AddStateChange(channelMember)
.Build(); .Build();
@ -400,7 +401,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
//Notify all Channel members //Notify all Channel members
foreach (var member in channel.Members.Keys) foreach (var member in channel.Members.Keys)
{ {
member.MakeTargetedRPC(channel, (lid) => member.MakeTargetedRpc(channel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnUpdateMemberState(new HandlerController() { ListenerId = lid }, notification, callback => { })); bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnUpdateMemberState(new HandlerController() { ListenerId = lid }, notification, callback => { }));
} }
//*/ //*/

View File

@ -28,29 +28,29 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
if (request.HasUseBindlessRpc) if (request.HasUseBindlessRpc)
builder.SetUseBindlessRpc(true); builder.SetUseBindlessRpc(true);
(controller as HandlerController).Client.Services.Add(0x54DFDA17, 0x01); ((HandlerController) controller).Client.Services.Add(0x54DFDA17, 0x01);
(controller as HandlerController).Client.Services.Add(0xD4DCD093, 0x02); ((HandlerController) controller).Client.Services.Add(0xD4DCD093, 0x02);
(controller as HandlerController).Client.Services.Add(0x71240E35, 0x03); ((HandlerController) controller).Client.Services.Add(0x71240E35, 0x03);
(controller as HandlerController).Client.Services.Add(0xBBDA171F, 0x04); ((HandlerController) controller).Client.Services.Add(0xBBDA171F, 0x04);
(controller as HandlerController).Client.Services.Add(0xF084FC20, 0x05); ((HandlerController) controller).Client.Services.Add(0xF084FC20, 0x05);
(controller as HandlerController).Client.Services.Add(0xBF8C8094, 0x06); ((HandlerController) controller).Client.Services.Add(0xBF8C8094, 0x06);
(controller as HandlerController).Client.Services.Add(0x166FE4A1, 0x07); ((HandlerController) controller).Client.Services.Add(0x166FE4A1, 0x07);
(controller as HandlerController).Client.Services.Add(0xB96F5297, 0x08); ((HandlerController) controller).Client.Services.Add(0xB96F5297, 0x08);
(controller as HandlerController).Client.Services.Add(0x6F259A13, 0x09); ((HandlerController) controller).Client.Services.Add(0x6F259A13, 0x09);
(controller as HandlerController).Client.Services.Add(0xE1CB2EA8, 0x0A); ((HandlerController) controller).Client.Services.Add(0xE1CB2EA8, 0x0A);
(controller as HandlerController).Client.Services.Add(0xBC872C22, 0x0B); ((HandlerController) controller).Client.Services.Add(0xBC872C22, 0x0B);
(controller as HandlerController).Client.Services.Add(0x7FE36B32, 0x0C); ((HandlerController) controller).Client.Services.Add(0x7FE36B32, 0x0C);
(controller as HandlerController).Client.Services.Add(233634817, 0x0D); ((HandlerController) controller).Client.Services.Add(233634817, 0x0D);
(controller as HandlerController).Client.Services.Add(0x62DA0891, 0x0E); //AccountService ((HandlerController) controller).Client.Services.Add(0x62DA0891, 0x0E); //AccountService
(controller as HandlerController).Client.Services.Add(510168069, 0x0F); ((HandlerController) controller).Client.Services.Add(510168069, 0x0F);
(controller as HandlerController).Client.Services.Add(0x45E59C4D, 0x10); ((HandlerController) controller).Client.Services.Add(0x45E59C4D, 0x10);
(controller as HandlerController).Client.Services.Add(0x135185EF, 0x11); ((HandlerController) controller).Client.Services.Add(0x135185EF, 0x11);
(controller as HandlerController).Client.Services.Add(1910276758, 0x51); ((HandlerController) controller).Client.Services.Add(1910276758, 0x51);
//(controller as HandlerController).Client.Services.Add(2495170438, 0x25); //((HandlerController) controller).Client.Services.Add(2495170438, 0x25);
(controller as HandlerController).Client.Services.Add(2119327385, 0x26); ((HandlerController) controller).Client.Services.Add(2119327385, 0x26);
done(builder.Build()); done(builder.Build());
Logger.Info("Connect with Blizzless established. Client - {0}", (controller as HandlerController).Client.SocketConnection.RemoteAddress); Logger.Info("Connect with Blizzless established. Client - {0}", ((HandlerController) controller).Client.SocketConnection.RemoteAddress);
} }
public override void Echo(IRpcController controller, EchoRequest request, Action<EchoResponse> done) public override void Echo(IRpcController controller, EchoRequest request, Action<EchoResponse> done)
@ -74,22 +74,22 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
public override void RequestDisconnect(IRpcController controller, DisconnectRequest request, Action<NO_RESPONSE> done) public override void RequestDisconnect(IRpcController controller, DisconnectRequest request, Action<NO_RESPONSE> done)
{ {
Logger.Info("Client - {0} , disconnected", (controller as HandlerController).Client.SocketConnection.RemoteAddress); Logger.Info("Client - {0} , disconnected", ((HandlerController) controller).Client.SocketConnection.RemoteAddress);
DisconnectClient(controller as HandlerController); DisconnectClient((HandlerController) controller);
if ((controller as HandlerController).Client.Account != null) if (((HandlerController) controller).Client.Account != null)
(controller as HandlerController).Client.Account.GameAccount.IsLoggedIn = false; ((HandlerController) controller).Client.Account.GameAccount.IsLoggedIn = false;
((controller as HandlerController).Client).Connect.CloseAsync(); (((HandlerController) controller).Client).Connect.CloseAsync();
(controller as HandlerController).Client.SocketConnection.CloseAsync(); ((HandlerController) controller).Client.SocketConnection.CloseAsync();
/* /*
if ((controller as HandlerController).Client.Account != null) if (((HandlerController) controller).Client.Account != null)
{ {
(controller as HandlerController).Client.Account.CurrentGameAccount.Logined = false; ((HandlerController) controller).Client.Account.CurrentGameAccount.Logined = false;
AccountManager.SaveToDB((controller as HandlerController).Client.Account); AccountManager.SaveToDB(((HandlerController) controller).Client.Account);
if ((controller as HandlerController).Client.Account.CurrentGameAccount != null) if (((HandlerController) controller).Client.Account.CurrentGameAccount != null)
{ {
GameAccountManager.SaveToDB((controller as HandlerController).Client.Account.CurrentGameAccount); GameAccountManager.SaveToDB(((HandlerController) controller).Client.Account.CurrentGameAccount);
(controller as HandlerController).Client.SocketConnection.CloseAsync(); ((HandlerController) controller).Client.SocketConnection.CloseAsync();
(controller as HandlerController).Client.Connect.CloseAsync(); ((HandlerController) controller).Client.Connect.CloseAsync();
} }
} }
//*/ //*/

View File

@ -9,6 +9,7 @@ using DiIiS_NA.LoginServer.Helpers;
using Google.ProtocolBuffers; using Google.ProtocolBuffers;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection;
namespace DiIiS_NA.LoginServer.ServicesSystem.Services namespace DiIiS_NA.LoginServer.ServicesSystem.Services
{ {
@ -19,10 +20,10 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
public override void Subscribe(IRpcController controller, SubscribeRequest request, Action<SubscribeResponse> done) public override void Subscribe(IRpcController controller, SubscribeRequest request, Action<SubscribeResponse> done)
{ {
Logger.Trace("Subscribe() {0}", ((controller as HandlerController).Client)); Logger.Trace("Subscribe() {0}", (((HandlerController) controller).Client));
FriendManager.Instance.AddSubscriber(((controller as HandlerController).Client), request.ObjectId); FriendManager.Instance.AddSubscriber((((HandlerController) controller).Client), request.ObjectId);
var builder = SubscribeResponse.CreateBuilder() var builder = SubscribeResponse.CreateBuilder()
.SetMaxFriends(127) .SetMaxFriends(127)
@ -31,7 +32,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
.AddRole(Role.CreateBuilder().SetId(1).SetName("battle_tag_friend").Build()) .AddRole(Role.CreateBuilder().SetId(1).SetName("battle_tag_friend").Build())
.AddRole(Role.CreateBuilder().SetId(2).SetName("real_id_friend").Build()); .AddRole(Role.CreateBuilder().SetId(2).SetName("real_id_friend").Build());
var friendsIDs = ((controller as HandlerController).Client).Account.FriendsIds; var friendsIDs = (((HandlerController) controller).Client).Account.FriendsIds;
foreach (var dbidFriend in friendsIDs) // send friends list. foreach (var dbidFriend in friendsIDs) // send friends list.
{ {
var resp = Friend.CreateBuilder() var resp = Friend.CreateBuilder()
@ -46,7 +47,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
foreach (var invitation in FriendManager.OnGoingInvitations.Values) foreach (var invitation in FriendManager.OnGoingInvitations.Values)
{ {
if (invitation.InviteeIdentity.AccountId == ((controller as HandlerController).Client).Account.BnetEntityId && !friendsIDs.Contains(invitation.InviterIdentity.AccountId.Low)) if (invitation.InviteeIdentity.AccountId == (((HandlerController) controller).Client).Account.BnetEntityId && !friendsIDs.Contains(invitation.InviterIdentity.AccountId.Low))
{ {
invitations.Add(invitation); invitations.Add(invitation);
} }
@ -64,16 +65,16 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var response = NoData.CreateBuilder(); var response = NoData.CreateBuilder();
if (friendRequest.TargetEmail.ToLower() == ((controller as HandlerController).Client).Account.Email.ToLower()) if (friendRequest.TargetEmail.ToLower() == (((HandlerController) controller).Client).Account.Email.ToLower())
{ {
((controller as HandlerController).Status) = 317202; (((HandlerController) controller).Status) = 317202;
done(response.Build()); done(response.Build());
return; return;
} }
if (friendRequest.TargetBattleTag == ((controller as HandlerController).Client).Account.BattleTag) if (friendRequest.TargetBattleTag == (((HandlerController) controller).Client).Account.BattleTag)
{ {
((controller as HandlerController).Status) = 317202; (((HandlerController) controller).Status) = 317202;
done(response.Build()); done(response.Build());
return; return;
} }
@ -90,44 +91,44 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
if (invitee == null) if (invitee == null)
{ {
if (friendRequest.HasTargetEmail) if (friendRequest.HasTargetEmail)
((controller as HandlerController).Status) = 4; (((HandlerController) controller).Status) = 4;
else else
((controller as HandlerController).Status) = 317203; (((HandlerController) controller).Status) = 317203;
done(response.Build()); done(response.Build());
return; return;
} }
else if (FriendManager.AreFriends(((controller as HandlerController).Client).Account, invitee)) else if (FriendManager.AreFriends((((HandlerController) controller).Client).Account, invitee))
{ {
if (friendRequest.HasTargetEmail) if (friendRequest.HasTargetEmail)
((controller as HandlerController).Status) = 317201; (((HandlerController) controller).Status) = 317201;
else else
((controller as HandlerController).Status) = 5003; (((HandlerController) controller).Status) = 5003;
done(response.Build()); done(response.Build());
return; return;
} }
else if (FriendManager.InvitationExists(((controller as HandlerController).Client).Account, invitee)) else if (FriendManager.InvitationExists((((HandlerController) controller).Client).Account, invitee))
{ {
if (friendRequest.HasTargetEmail) if (friendRequest.HasTargetEmail)
((controller as HandlerController).Status) = 317200; (((HandlerController) controller).Status) = 317200;
else else
((controller as HandlerController).Status) = 5005; (((HandlerController) controller).Status) = 5005;
done(response.Build()); done(response.Build());
return; return;
} }
else if (invitee.IgnoreIds.Contains((controller as HandlerController).Client.Account.PersistentID)) else if (invitee.IgnoreIds.Contains(((HandlerController) controller).Client.Account.PersistentID))
{ {
((controller as HandlerController).Status) = 5006; (((HandlerController) controller).Status) = 5006;
done(response.Build()); done(response.Build());
return; return;
} }
Logger.Trace("{0} sent {1} friend invitation.", ((controller as HandlerController).Client).Account, invitee); Logger.Trace("{0} sent {1} friend invitation.", (((HandlerController) controller).Client).Account, invitee);
var invitation = ReceivedInvitation.CreateBuilder() var invitation = ReceivedInvitation.CreateBuilder()
.SetId(FriendManager.InvitationIdCounter++) // we may actually need to store invitation ids in database with the actual invitation there. /raist. .SetId(FriendManager.InvitationIdCounter++) // we may actually need to store invitation ids in database with the actual invitation there. /raist.
.SetInviterIdentity(Identity.CreateBuilder().SetAccountId(((controller as HandlerController).Client).Account.BnetEntityId)) .SetInviterIdentity(Identity.CreateBuilder().SetAccountId((((HandlerController) controller).Client).Account.BnetEntityId))
.SetInviteeIdentity(Identity.CreateBuilder().SetAccountId(invitee.BnetEntityId)) .SetInviteeIdentity(Identity.CreateBuilder().SetAccountId(invitee.BnetEntityId))
.SetInviterName(((controller as HandlerController).Client).Account.BattleTagName) .SetInviterName((((HandlerController) controller).Client).Account.BattleTagName)
.SetInviteeName(invitee.BattleTagName) .SetInviteeName(invitee.BattleTagName)
.SetCreationTime(DateTime.Now.ToUnixTime()) .SetCreationTime(DateTime.Now.ToUnixTime())
.SetUnknownFields(UnknownFieldSet.CreateBuilder() .SetUnknownFields(UnknownFieldSet.CreateBuilder()
@ -138,19 +139,19 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
done(response.Build()); done(response.Build());
// notify the invitee on invitation. // notify the invitee on invitation.
FriendManager.HandleInvitation(((controller as HandlerController).Client), invitation.Build()); FriendManager.HandleInvitation((((HandlerController) controller).Client), invitation.Build());
FriendManager.Instance.NotifyUpdate(); FriendManager.Instance.NotifyUpdate();
(controller as HandlerController).Client.Account.NotifyUpdate(); ((HandlerController) controller).Client.Account.NotifyUpdate();
(controller as HandlerController).Client.Account.GameAccount.NotifyUpdate(); ((HandlerController) controller).Client.Account.GameAccount.NotifyUpdate();
} }
public override void AcceptInvitation(IRpcController controller, AcceptInvitationRequest request, Action<NoData> done) public override void AcceptInvitation(IRpcController controller, AcceptInvitationRequest request, Action<NoData> done)
{ {
Logger.Trace("{0} accepted friend invitation.", ((controller as HandlerController).Client).Account); Logger.Trace("{0} accepted friend invitation.", (((HandlerController) controller).Client).Account);
var response = NoData.CreateBuilder(); var response = NoData.CreateBuilder();
done(response.Build()); done(response.Build());
FriendManager.HandleAccept(((controller as HandlerController).Client), request); FriendManager.HandleAccept((((HandlerController) controller).Client), request);
} }
public override void RevokeInvitation(IRpcController controller, RevokeInvitationRequest request, Action<NoData> done) public override void RevokeInvitation(IRpcController controller, RevokeInvitationRequest request, Action<NoData> done)
{ {
@ -158,12 +159,12 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
} }
public override void DeclineInvitation(IRpcController controller, DeclineInvitationRequest request, Action<NoData> done) public override void DeclineInvitation(IRpcController controller, DeclineInvitationRequest request, Action<NoData> done)
{ {
Logger.Trace("{0} declined friend invitation.", ((controller as HandlerController).Client).Account); Logger.Trace("{0} declined friend invitation.", (((HandlerController) controller).Client).Account);
var response = NoData.CreateBuilder(); var response = NoData.CreateBuilder();
done(response.Build()); done(response.Build());
FriendManager.HandleDecline(((controller as HandlerController).Client), request); FriendManager.HandleDecline((((HandlerController) controller).Client), request);
} }
public override void IgnoreInvitation(IRpcController controller, IgnoreInvitationRequest request, Action<NoData> done) public override void IgnoreInvitation(IRpcController controller, IgnoreInvitationRequest request, Action<NoData> done)
{ {
@ -172,25 +173,25 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var response = NoData.CreateBuilder(); var response = NoData.CreateBuilder();
done(response.Build()); done(response.Build());
FriendManager.HandleIgnore(((controller as HandlerController).Client), request); FriendManager.HandleIgnore((((HandlerController) controller).Client), request);
} }
public override void RemoveFriend(IRpcController controller, RemoveFriendRequest request, Action<NoData> done) public override void RemoveFriend(IRpcController controller, RemoveFriendRequest request, Action<NoData> done)
{ {
Logger.Trace("{0} removed friend with id {1}.", ((controller as HandlerController).Client).Account, request.TargetId); Logger.Trace("{0} removed friend with id {1}.", (((HandlerController) controller).Client).Account, request.TargetId);
done(NoData.DefaultInstance); done(NoData.DefaultInstance);
FriendManager.HandleRemove(((controller as HandlerController).Client), request); FriendManager.HandleRemove((((HandlerController) controller).Client), request);
FriendManager.Instance.NotifyUpdate(); FriendManager.Instance.NotifyUpdate();
(controller as HandlerController).Client.Account.NotifyUpdate(); ((HandlerController) controller).Client.Account.NotifyUpdate();
(controller as HandlerController).Client.Account.GameAccount.NotifyUpdate(); ((HandlerController) controller).Client.Account.GameAccount.NotifyUpdate();
} }
public override void ViewFriends(IRpcController controller, ViewFriendsRequest request, Action<ViewFriendsResponse> done) public override void ViewFriends(IRpcController controller, ViewFriendsRequest request, Action<ViewFriendsResponse> done)
{ {
Logger.Trace("ViewFriends(): {0}.", request.ToString()); Logger.MethodTrace(request.ToString());
var builder = ViewFriendsResponse.CreateBuilder(); var builder = ViewFriendsResponse.CreateBuilder();
var friendsIDs = AccountManager.GetAccountByPersistentID(request.TargetId.Low).FriendsIds; var friendsIDs = AccountManager.GetAccountByPersistentID(request.TargetId.Low).FriendsIds;
@ -209,7 +210,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
} }
public override void UpdateFriendState(IRpcController controller, UpdateFriendStateRequest request, Action<NoData> done) public override void UpdateFriendState(IRpcController controller, UpdateFriendStateRequest request, Action<NoData> done)
{ {
Logger.Trace("UpdateFriendState(): {0}.", request.ToString()); Logger.MethodTrace(request.ToString());
done(NoData.CreateBuilder().Build()); done(NoData.CreateBuilder().Build());
} }

View File

@ -72,7 +72,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
QueueEntryNotification.Builder qen = QueueEntryNotification.CreateBuilder(); QueueEntryNotification.Builder qen = QueueEntryNotification.CreateBuilder();
qen.SetRequestId(id).SetWaitTimes(timers).AddMember(member).SetRequestInitiator(member); qen.SetRequestId(id).SetWaitTimes(timers).AddMember(member).SetRequestInitiator(member);
((HandlerController) controller).Client.MakeRPC((lid) => GameRequestListener.CreateStub(((HandlerController) controller).Client).OnQueueEntry(new HandlerController() { ListenerId = lid }, qen.Build(), callback => { })); ((HandlerController) controller).Client.MakeRpc((lid) => GameRequestListener.CreateStub(((HandlerController) controller).Client).OnQueueEntry(new HandlerController() { ListenerId = lid }, qen.Build(), callback => { }));
#endregion #endregion
#region Update Queue #region Update Queue
@ -80,7 +80,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
qun.SetRequestId(id) qun.SetRequestId(id)
.SetWaitTimes(timers) .SetWaitTimes(timers)
.SetIsMatchmaking(true); .SetIsMatchmaking(true);
((HandlerController) controller).Client.MakeRPC((lid) => GameRequestListener.CreateStub(((HandlerController) controller).Client).OnQueueUpdate(new HandlerController() { ListenerId = lid }, qun.Build(), callback => { })); ((HandlerController) controller).Client.MakeRpc((lid) => GameRequestListener.CreateStub(((HandlerController) controller).Client).OnQueueUpdate(new HandlerController() { ListenerId = lid }, qun.Build(), callback => { }));
#endregion #endregion
@ -124,7 +124,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var joinNotification = bgs.protocol.channel.v1.JoinNotification.CreateBuilder().SetChannelState(channelStatePermission).Build(); var joinNotification = bgs.protocol.channel.v1.JoinNotification.CreateBuilder().SetChannelState(channelStatePermission).Build();
(((HandlerController) controller).Client).MakeTargetedRPC((((HandlerController) controller).Client).CurrentChannel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub((((HandlerController) controller).Client)).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notificationPermission, callback => { })); (((HandlerController) controller).Client).MakeTargetedRpc((((HandlerController) controller).Client).CurrentChannel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub((((HandlerController) controller).Client)).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notificationPermission, callback => { }));
} }
gameFound.StartGame(clients, gameFound.DynamicId); gameFound.StartGame(clients, gameFound.DynamicId);
@ -137,7 +137,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
.SetValue(Variant.CreateBuilder().SetUintValue(gameFound.RequestId).Build()); .SetValue(Variant.CreateBuilder().SetUintValue(gameFound.RequestId).Build());
notificationFound.AddAttribute(attrF); notificationFound.AddAttribute(attrF);
(((HandlerController) controller).Client).MakeRPC((lid) => (((HandlerController) controller).Client).MakeRpc((lid) =>
bgs.protocol.notification.v1.NotificationListener.CreateStub((((HandlerController) controller).Client)).OnNotificationReceived(new HandlerController() { ListenerId = lid }, notificationFound.Build(), callback => { })); bgs.protocol.notification.v1.NotificationListener.CreateStub((((HandlerController) controller).Client)).OnNotificationReceived(new HandlerController() { ListenerId = lid }, notificationFound.Build(), callback => { }));
@ -152,7 +152,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
notification.SetGameHandle(gh); notification.SetGameHandle(gh);
System.Threading.Tasks.Task.Delay(2000).ContinueWith(delegate { System.Threading.Tasks.Task.Delay(2000).ContinueWith(delegate {
((HandlerController) controller).Client.MakeRPC((lid) => GameRequestListener.CreateStub(((HandlerController) controller).Client).OnMatchmakingResult(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { })); ((HandlerController) controller).Client.MakeRpc((lid) => GameRequestListener.CreateStub(((HandlerController) controller).Client).OnMatchmakingResult(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
}); });
} }
} }

View File

@ -21,6 +21,7 @@ using Google.ProtocolBuffers;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection;
namespace DiIiS_NA.LoginServer.ServicesSystem.Services namespace DiIiS_NA.LoginServer.ServicesSystem.Services
{ {
@ -196,7 +197,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
builder.AddAttribute(messageId); builder.AddAttribute(messageId);
builder.AddAttribute(payload); builder.AddAttribute(payload);
Client.MakeRPC((lid) => Client.MakeRpc((lid) =>
NotificationListener.CreateStub(Client) NotificationListener.CreateStub(Client)
.OnNotificationReceived(new HandlerController() { ListenerId = lid }, builder.Build(), .OnNotificationReceived(new HandlerController() { ListenerId = lid }, builder.Build(),
callback => { })); callback => { }));
@ -1184,7 +1185,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
private ByteString SearchGuilds(BattleClient client, ByteString data) private ByteString SearchGuilds(BattleClient client, ByteString data)
{ {
GuildSearch request = GuildSearch.ParseFrom(data); GuildSearch request = GuildSearch.ParseFrom(data);
Logger.Debug("GuildSearch(): {0}", request.ToString()); Logger.MethodTrace(request.ToString());
var builder = D3.Guild.GuildSearchResultList.CreateBuilder(); var builder = D3.Guild.GuildSearchResultList.CreateBuilder();
List<Guild> allGuilds = request.ClanOrGroup == 1 ? GuildManager.GetCommunities() : GuildManager.GetClans(); List<Guild> allGuilds = request.ClanOrGroup == 1 ? GuildManager.GetCommunities() : GuildManager.GetClans();
@ -1260,7 +1261,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
private void GuildKickMemberP(BattleClient client, GuildKickMember request) private void GuildKickMemberP(BattleClient client, GuildKickMember request)
{ {
Logger.Debug("GuildKickMember(): {0}", request.ToString()); Logger.MethodTrace(request.ToString());
var guild = GuildManager.GetGuildById(request.GuildId); var guild = GuildManager.GetGuildById(request.GuildId);
if (guild != null && client.Account.GameAccount.PersistentID == guild.Owner.PersistentID) if (guild != null && client.Account.GameAccount.PersistentID == guild.Owner.PersistentID)
@ -1272,7 +1273,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
private void GuildDisband(BattleClient client, GuildId request) private void GuildDisband(BattleClient client, GuildId request)
{ {
Logger.Debug("GuildDisband(): {0}", request.ToString()); Logger.MethodTrace(request.ToString());
var guild = GuildManager.GetGuildById(request.GuildId_); var guild = GuildManager.GetGuildById(request.GuildId_);
if (guild != null && client.Account.GameAccount.PersistentID == guild.Owner.PersistentID) if (guild != null && client.Account.GameAccount.PersistentID == guild.Owner.PersistentID)
@ -1288,7 +1289,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
private ByteString GuildFetchNews(BattleClient client, GuildFetchNews request) private ByteString GuildFetchNews(BattleClient client, GuildFetchNews request)
{ {
Logger.Debug("GuildFetchNews(): {0}", request.ToString()); Logger.MethodTrace(request.ToString());
var builder = D3.Guild.NewsList.CreateBuilder(); var builder = D3.Guild.NewsList.CreateBuilder();
/* news types: /* news types:
@ -1325,7 +1326,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
private ByteString GuildPromoteMember(BattleClient client, GuildPromoteMember request) private ByteString GuildPromoteMember(BattleClient client, GuildPromoteMember request)
{ {
Logger.Debug("GuildPromoteMember(): {0}", request.ToString()); Logger.MethodTrace(request.ToString());
var guild = GuildManager.GetGuildById(request.GuildId); var guild = GuildManager.GetGuildById(request.GuildId);
var account = GameAccountManager.GetAccountByPersistentID(request.MemberId); var account = GameAccountManager.GetAccountByPersistentID(request.MemberId);
@ -1346,7 +1347,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
private ByteString GuildDemoteMember(BattleClient client, GuildDemoteMember request) private ByteString GuildDemoteMember(BattleClient client, GuildDemoteMember request)
{ {
Logger.Debug("GuildDemoteMember(): {0}", request.ToString()); Logger.MethodTrace(request.ToString());
var guild = GuildManager.GetGuildById(request.GuildId); var guild = GuildManager.GetGuildById(request.GuildId);
var account = GameAccountManager.GetAccountByPersistentID(request.MemberId); var account = GameAccountManager.GetAccountByPersistentID(request.MemberId);
@ -1510,7 +1511,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
private ByteString CreateCommunity(BattleClient client, ByteString data) private ByteString CreateCommunity(BattleClient client, ByteString data)
{ {
var request = GroupCreate.ParseFrom(data); var request = GroupCreate.ParseFrom(data);
Logger.Debug("CreateCommunity(): {0}", request.ToString()); Logger.MethodTrace(request.ToString());
var guild = GuildManager.CreateNewGuild(client.Account.GameAccount, request.Name, "", false, var guild = GuildManager.CreateNewGuild(client.Account.GameAccount, request.Name, "", false,
request.SearchCategory, false, request.Language); request.SearchCategory, false, request.Language);

View File

@ -29,20 +29,20 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
case NotificationTypeHelper.NotificationType.Whisper: case NotificationTypeHelper.NotificationType.Whisper:
var targetAccount = GameAccountManager.GetAccountByPersistentID(request.TargetId.Low); var targetAccount = GameAccountManager.GetAccountByPersistentID(request.TargetId.Low);
Logger.Trace(string.Format("NotificationRequest.Whisper by {0} to {1}", (controller as HandlerController).Client.Account.GameAccount, targetAccount)); Logger.Trace(string.Format("NotificationRequest.Whisper by {0} to {1}", ((HandlerController) controller).Client.Account.GameAccount, targetAccount));
if (targetAccount.LoggedInClient == null) return; if (targetAccount.LoggedInClient == null) return;
if (targetAccount == (controller as HandlerController).Client.Account.GameAccount) if (targetAccount == ((HandlerController) controller).Client.Account.GameAccount)
CommandManager.TryParse(request.AttributeList[0].Value.StringValue, (controller as HandlerController).Client); // try parsing it as a command and respond it if so. CommandManager.TryParse(request.AttributeList[0].Value.StringValue, ((HandlerController) controller).Client); // try parsing it as a command and respond it if so.
else else
{ {
var notification = Notification.CreateBuilder(request) var notification = Notification.CreateBuilder(request)
.SetSenderId((controller as HandlerController).Client.Account.GameAccount.BnetEntityId) .SetSenderId(((HandlerController) controller).Client.Account.GameAccount.BnetEntityId)
.SetSenderAccountId((controller as HandlerController).Client.Account.BnetEntityId) .SetSenderAccountId(((HandlerController) controller).Client.Account.BnetEntityId)
.Build(); .Build();
targetAccount.LoggedInClient.MakeRPC((lid) => targetAccount.LoggedInClient.MakeRpc((lid) =>
NotificationListener.CreateStub(targetAccount.LoggedInClient).OnNotificationReceived(controller, notification, callback => { })); NotificationListener.CreateStub(targetAccount.LoggedInClient).OnNotificationReceived(controller, notification, callback => { }));
} }
break; break;

View File

@ -1,5 +1,6 @@
//Blizzless Project 2022 //Blizzless Project 2022
using System; using System;
using System.Reflection;
using Google.ProtocolBuffers; using Google.ProtocolBuffers;
using bgs.protocol; using bgs.protocol;
using bgs.protocol.presence.v1; using bgs.protocol.presence.v1;
@ -34,7 +35,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var account = AccountManager.GetAccountByPersistentID(req.Low); var account = AccountManager.GetAccountByPersistentID(req.Low);
if (account != null) if (account != null)
{ {
Logger.MethodTrace("Subscribe() {0} {1}", (((HandlerController)controller).Client), account); Logger.MethodTrace($"{(((HandlerController)controller).Client)} {account}");
account.AddSubscriber((((HandlerController)controller).Client), request.ObjectId); account.AddSubscriber((((HandlerController)controller).Client), request.ObjectId);
response.AddSubscribeFailed(SubscribeResult.CreateBuilder().SetEntityId(req) response.AddSubscribeFailed(SubscribeResult.CreateBuilder().SetEntityId(req)
.SetResult(0)); .SetResult(0));
@ -46,8 +47,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var gameAccount = GameAccountManager.GetAccountByPersistentID(req.Low); var gameAccount = GameAccountManager.GetAccountByPersistentID(req.Low);
if (gameAccount != null) if (gameAccount != null)
{ {
Logger.MethodTrace("Subscribe() {0} {1}", (((HandlerController)controller).Client), Logger.MethodTrace($"{(((HandlerController)controller).Client)} {gameAccount}");
gameAccount);
gameAccount.AddSubscriber((((HandlerController)controller).Client), request.ObjectId); gameAccount.AddSubscriber((((HandlerController)controller).Client), request.ObjectId);
response.AddSubscribeFailed(SubscribeResult.CreateBuilder().SetEntityId(req) response.AddSubscribeFailed(SubscribeResult.CreateBuilder().SetEntityId(req)
.SetResult(0)); .SetResult(0));
@ -83,9 +83,8 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var gameAccount = AccountManager.GetAccountByPersistentID(request.EntityId.Low); var gameAccount = AccountManager.GetAccountByPersistentID(request.EntityId.Low);
foreach (var key in request.KeyList) foreach (var key in request.KeyList)
{ {
Logger.Debug("Query() {0} {1} - {2}, {3}, {4}", (((HandlerController)controller).Client), Logger.MethodTrace(
gameAccount, (FieldKeyHelper.Program)key.Program, (FieldKeyHelper.OriginatingClass)key.Group, $"{(((HandlerController)controller).Client)} {gameAccount} - {(FieldKeyHelper.Program)key.Program}, {(FieldKeyHelper.OriginatingClass)key.Group}, {key.Field}");
key.Field);
var field = gameAccount.QueryField(key); var field = gameAccount.QueryField(key);
if (field != null) builder.AddField(field); if (field != null) builder.AddField(field);
} }
@ -97,9 +96,8 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var gameAccount = GameAccountManager.GetAccountByPersistentID(request.EntityId.Low); var gameAccount = GameAccountManager.GetAccountByPersistentID(request.EntityId.Low);
foreach (var key in request.KeyList) foreach (var key in request.KeyList)
{ {
Logger.Debug("Query() {0} {1} - {2}, {3}, {4}", (((HandlerController)controller).Client), Logger.MethodTrace(
gameAccount, (FieldKeyHelper.Program)key.Program, $"{(((HandlerController)controller).Client)} {gameAccount} - {(FieldKeyHelper.Program)key.Program}, {(FieldKeyHelper.OriginatingClass)key.Group}, {key.Field}");
(FieldKeyHelper.OriginatingClass)key.Group, key.Field);
var field = gameAccount.QueryField(key); var field = gameAccount.QueryField(key);
if (field != null) builder.AddField(field); if (field != null) builder.AddField(field);
} }
@ -124,7 +122,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var gameAccount = AccountManager.GetAccountByPersistentID(request.EntityId.Low); var gameAccount = AccountManager.GetAccountByPersistentID(request.EntityId.Low);
if (gameAccount != null) if (gameAccount != null)
{ {
Logger.MethodTrace("Subscribe() {0} {1}", (((HandlerController)controller).Client), gameAccount); Logger.MethodTrace($"{(((HandlerController)controller).Client)} {gameAccount}");
gameAccount.AddSubscriber((((HandlerController)controller).Client), request.ObjectId); gameAccount.AddSubscriber((((HandlerController)controller).Client), request.ObjectId);
} }
} }
@ -134,7 +132,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var gameaccount = GameAccountManager.GetAccountByPersistentID(request.EntityId.Low); var gameaccount = GameAccountManager.GetAccountByPersistentID(request.EntityId.Low);
if (gameaccount != null) if (gameaccount != null)
{ {
Logger.MethodTrace("Subscribe() {0} {1}", (((HandlerController)controller).Client), gameaccount); Logger.MethodTrace($"{(((HandlerController)controller).Client)} {gameaccount}");
gameaccount.AddSubscriber((((HandlerController)controller).Client), request.ObjectId); gameaccount.AddSubscriber((((HandlerController)controller).Client), request.ObjectId);
} }
} }
@ -161,7 +159,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
if (gameAccount != null) if (gameAccount != null)
{ {
gameAccount.RemoveSubscriber((((HandlerController) controller).Client)); gameAccount.RemoveSubscriber((((HandlerController) controller).Client));
Logger.MethodTrace("Unsubscribe() {0} {1}", (((HandlerController) controller).Client), gameAccount); Logger.MethodTrace($"{(((HandlerController)controller).Client)} {gameAccount}");
} }
} }
break; break;
@ -171,7 +169,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
if (gameAccount != null) if (gameAccount != null)
{ {
gameAccount.RemoveSubscriber((((HandlerController)controller).Client)); gameAccount.RemoveSubscriber((((HandlerController)controller).Client));
Logger.MethodTrace("Unsubscribe() {0} {1}", (((HandlerController) controller).Client), gameAccount); Logger.MethodTrace($"{(((HandlerController)controller).Client)} {gameAccount}");
} }
} }
break; break;
@ -196,7 +194,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
if (request.EntityId.Low <= 0) break; if (request.EntityId.Low <= 0) break;
var gameAccount = AccountManager.GetAccountByPersistentID(request.EntityId.Low); var gameAccount = AccountManager.GetAccountByPersistentID(request.EntityId.Low);
if (gameAccount == null) break; if (gameAccount == null) break;
var traceData = $"Update() {(((HandlerController)controller).Client)} {gameAccount} - {request.FieldOperationCount} Operations"; var traceData = $"{(((HandlerController)controller).Client)} {gameAccount} - {request.FieldOperationCount} Operations";
foreach (var fieldOp in request.FieldOperationList) foreach (var fieldOp in request.FieldOperationList)
{ {
traceData += $"\t{(FieldKeyHelper.Program)fieldOp.Field.Key.Program}, {(FieldKeyHelper.OriginatingClass)fieldOp.Field.Key.Group}, {fieldOp.Field.Key.Field}"; traceData += $"\t{(FieldKeyHelper.Program)fieldOp.Field.Key.Program}, {(FieldKeyHelper.OriginatingClass)fieldOp.Field.Key.Group}, {fieldOp.Field.Key.Field}";
@ -212,7 +210,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var gameAccount = GameAccountManager.GetAccountByPersistentID(request.EntityId.Low); var gameAccount = GameAccountManager.GetAccountByPersistentID(request.EntityId.Low);
if (gameAccount == null) break; if (gameAccount == null) break;
var traceData = var traceData =
$"Update() {(((HandlerController) controller).Client)} {gameAccount} - {request.FieldOperationCount} Operations"; $"{(((HandlerController) controller).Client)} {gameAccount} - {request.FieldOperationCount} Operations";
foreach (var fieldOp in request.FieldOperationList) foreach (var fieldOp in request.FieldOperationList)
{ {
traceData += traceData +=

View File

@ -1,5 +1,6 @@
//Blizzless Project 2022 //Blizzless Project 2022
using System; using System;
using System.Reflection;
using bgs.protocol; using bgs.protocol;
using bgs.protocol.resources.v1; using bgs.protocol.resources.v1;
using DiIiS_NA.Core.Extensions; using DiIiS_NA.Core.Extensions;
@ -19,7 +20,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
public override void GetContentHandle(IRpcController controller, ContentHandleRequest request, Action<ContentHandle> done) public override void GetContentHandle(IRpcController controller, ContentHandleRequest request, Action<ContentHandle> done)
{ {
Logger.Trace("GetContentHandle(): ProgramId: 0x{0:X8} StreamId: 0x{1:X8}", request.Program, request.Stream); Logger.MethodTrace($"ProgramId: 0x{request.Program:X8} StreamId: 0x{request.Stream:X8}");
if (request.Program == (uint)FieldKeyHelper.Program.BNet) if (request.Program == (uint)FieldKeyHelper.Program.BNet)
{ {
var builder = ContentHandle.CreateBuilder() var builder = ContentHandle.CreateBuilder()
@ -54,7 +55,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
default: default:
Logger.Warn("Unknown StreamId: 0x{0:X8}", request.Stream); Logger.Warn("Unknown StreamId: 0x{0:X8}", request.Stream);
builder.SetHash(ByteString.Empty); builder.SetHash(ByteString.Empty);
(controller as HandlerController).Status = 4; ((HandlerController) controller).Status = 4;
break; break;
} }
done(builder.Build()); done(builder.Build());

View File

@ -1,5 +1,6 @@
//Blizzless Project 2022 //Blizzless Project 2022
using System; using System;
using System.Reflection;
using bgs.protocol; using bgs.protocol;
using bgs.protocol.session.v1; using bgs.protocol.session.v1;
using DiIiS_NA.Core.Helpers.Math; using DiIiS_NA.Core.Helpers.Math;
@ -27,7 +28,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
n.SetIdentity(request.Identity) n.SetIdentity(request.Identity)
.SetReason(0) .SetReason(0)
.SetSessionId(session); .SetSessionId(session);
((HandlerController) controller).Client.MakeRPC((lid) => SessionListener.CreateStub(((HandlerController) controller).Client).OnSessionCreated(controller, n.Build(), callback => { })); ((HandlerController) controller).Client.MakeRpc((lid) => SessionListener.CreateStub(((HandlerController) controller).Client).OnSessionCreated(controller, n.Build(), callback => { }));
} }
private void DisconnectClient(HandlerController controller) private void DisconnectClient(HandlerController controller)
@ -38,13 +39,16 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
public override void DestroySession(IRpcController controller, DestroySessionRequest request, Action<NoData> done) public override void DestroySession(IRpcController controller, DestroySessionRequest request, Action<NoData> done)
{ {
Logger.MethodTrace(nameof(SessionService)); Logger.MethodTrace("");
Logger.Trace("Destroying game session for client {0}", ((HandlerController) controller).Client); Logger.Trace("Destroying game session for client {0}", ((HandlerController) controller).Client);
DisconnectClient((HandlerController) controller); if (controller is HandlerController handlerController)
if (((HandlerController) controller).Client.Account != null) {
((HandlerController) controller).Client.Account.GameAccount.IsLoggedIn = false; DisconnectClient(handlerController);
(((HandlerController) controller).Client).Connect.CloseAsync(); if (handlerController.Client.Account != null)
((HandlerController) controller).Client.SocketConnection.CloseAsync(); handlerController.Client.Account.GameAccount.IsLoggedIn = false;
(handlerController.Client).Connect.CloseAsync();
handlerController.Client.SocketConnection.CloseAsync();
}
done(NoData.CreateBuilder().Build()); done(NoData.CreateBuilder().Build());
} }

View File

@ -8,6 +8,7 @@ using DiIiS_NA.LoginServer.FriendsSystem;
using DiIiS_NA.LoginServer.Helpers; using DiIiS_NA.LoginServer.Helpers;
using Google.ProtocolBuffers; using Google.ProtocolBuffers;
using System; using System;
using System.Reflection;
namespace DiIiS_NA.LoginServer.ServicesSystem.Services namespace DiIiS_NA.LoginServer.ServicesSystem.Services
{ {
@ -18,13 +19,13 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
public override void Subscribe(IRpcController controller, SubscribeRequest request, Action<SubscribeResponse> done) public override void Subscribe(IRpcController controller, SubscribeRequest request, Action<SubscribeResponse> done)
{ {
Logger.MethodTrace("Subscribe({0})", ((controller as HandlerController).Client)); Logger.MethodTrace((((HandlerController) controller).Client).ToString());
UserManager.Instance.AddSubscriber(((controller as HandlerController).Client), request.ObjectId); UserManager.Instance.AddSubscriber((((HandlerController) controller).Client), request.ObjectId);
var builder = SubscribeResponse.CreateBuilder(); var builder = SubscribeResponse.CreateBuilder();
var blockedIds = (controller as HandlerController).Client.Account.IgnoreIds; var blockedIds = ((HandlerController) controller).Client.Account.IgnoreIds;
foreach (var blocked in blockedIds) foreach (var blocked in blockedIds)
{ {
@ -41,7 +42,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
public override void AddRecentPlayers(IRpcController controller, AddRecentPlayersRequest request, Action<NoData> done) public override void AddRecentPlayers(IRpcController controller, AddRecentPlayersRequest request, Action<NoData> done)
{ {
Logger.MethodTrace("AddRecentPlayers()"); Logger.MethodTrace("");
done(NoData.DefaultInstance); done(NoData.DefaultInstance);
} }
@ -52,18 +53,18 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
public override void BlockPlayer(IRpcController controller, BlockPlayerRequest request, Action<NoData> done) public override void BlockPlayer(IRpcController controller, BlockPlayerRequest request, Action<NoData> done)
{ {
Logger.MethodTrace("BlockEntity()"); Logger.MethodTrace("");
done(NoData.CreateBuilder().Build()); done(NoData.CreateBuilder().Build());
UserManager.BlockAccount(((controller as HandlerController).Client), request); UserManager.BlockAccount((((HandlerController) controller).Client), request);
} }
public override void UnblockPlayer(IRpcController controller, UnblockPlayerRequest request, Action<NoData> done) public override void UnblockPlayer(IRpcController controller, UnblockPlayerRequest request, Action<NoData> done)
{ {
Logger.MethodTrace("UnblockPlayer()"); Logger.MethodTrace("");
done(NoData.CreateBuilder().Build()); done(NoData.CreateBuilder().Build());
UserManager.UnblockAccount(((controller as HandlerController).Client), request); UserManager.UnblockAccount((((HandlerController) controller).Client), request);
} }
public override void BlockPlayerForSession(IRpcController controller, BlockPlayerRequest request, Action<NoData> done) public override void BlockPlayerForSession(IRpcController controller, BlockPlayerRequest request, Action<NoData> done)

View File

@ -74,7 +74,6 @@ public static class RandomHelper
public class ItemRandomHelper public class ItemRandomHelper
{ {
private static readonly Logger Logger = LogManager.CreateLogger("RH");
uint a; uint a;
uint b; uint b;
public ItemRandomHelper(int seed) public ItemRandomHelper(int seed)
@ -94,7 +93,6 @@ public class ItemRandomHelper
a = (uint)temp; a = (uint)temp;
b = (uint)(temp >> 32); b = (uint)(temp >> 32);
//Logger.Debug("Next(): a {0}, b {1}", a, b);
return a; return a;
} }

View File

@ -57,8 +57,14 @@ public class AnsiTarget : LogTarget
CancellationTokenSource.Cancel(); CancellationTokenSource.Cancel();
} }
/// <summary>
public static string Filter(string text) /// Logging keywords to beautify the output.
/// It's ugly, I know.
/// Changes are welcome - @iamdroppy
/// </summary>
/// <param name="text">Text to "beautify"</param>
/// <returns>Replaced with color changes</returns>
public static string Beautify(string text)
{ {
return text return text
.Replace("Blizzless", "[dodgerblue1]Blizz[/][deepskyblue2]less[/]", StringComparison.CurrentCultureIgnoreCase) .Replace("Blizzless", "[dodgerblue1]Blizz[/][deepskyblue2]less[/]", StringComparison.CurrentCultureIgnoreCase)
@ -81,7 +87,7 @@ public class AnsiTarget : LogTarget
/// </summary> /// </summary>
/// <param name="x"></param> /// <param name="x"></param>
/// <returns></returns> /// <returns></returns>
string Cleanup(string x) => Filter(x.Replace("[", "[[").Replace("]", "]]").Replace("$[[/]]$", "[/]").Replace("$[[", "[").Replace("]]$", "]")); string Cleanup(string x) => Beautify(x.Replace("[", "[[").Replace("]", "]]").Replace("$[[/]]$", "[/]").Replace("$[[", "[").Replace("]]$", "]"));
public override void LogMessage(Logger.Level level, string logger, string message) public override void LogMessage(Logger.Level level, string logger, string message)
{ {
@ -128,7 +134,7 @@ public class AnsiTarget : LogTarget
Logger.Level.RenameAccountLog => new Style(Color.DarkSlateGray3),// Logger.Level.RenameAccountLog => new Style(Color.DarkSlateGray3),//
Logger.Level.ChatMessage => new Style(Color.DarkSlateGray2),// Logger.Level.ChatMessage => new Style(Color.DarkSlateGray2),//
Logger.Level.Debug => new Style(Color.Olive),// Logger.Level.Debug => new Style(Color.Olive),//
Logger.Level.MethodTrace => new Style(Color.Purple),// Logger.Level.MethodTrace => new Style(Color.DarkOliveGreen1_1),//
Logger.Level.Trace => new Style(Color.BlueViolet),// Logger.Level.Trace => new Style(Color.BlueViolet),//
Logger.Level.Info => new Style(Color.White), Logger.Level.Info => new Style(Color.White),
Logger.Level.Success => new Style(Color.Green3_1), Logger.Level.Success => new Style(Color.Green3_1),

View File

@ -52,7 +52,7 @@ namespace DiIiS_NA.Core.Logging
/// </summary> /// </summary>
/// <param name="x"></param> /// <param name="x"></param>
/// <returns></returns> /// <returns></returns>
string Cleanup(string x) => AnsiTarget.Filter(x.Replace("[", "[[").Replace("]", "]]").Replace("$[[/]]$", "[/]").Replace("$[[", "[").Replace("]]$", "]")); string Cleanup(string x) => AnsiTarget.Beautify(x.Replace("[", "[[").Replace("]", "]]").Replace("$[[/]]$", "[/]").Replace("$[[", "[").Replace("]]$", "]"));
/// <param name="level"></param> /// <param name="level"></param>
private static string SetColor(Logger.Level level, bool withBackground = false) private static string SetColor(Logger.Level level, bool withBackground = false)

View File

@ -1,6 +1,8 @@
//Blizzless Project 2022 //Blizzless Project 2022
using System; using System;
using System.Globalization; using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text; using System.Text;
using DiIiS_NA.Core.Extensions; using DiIiS_NA.Core.Extensions;
using DiIiS_NA.GameServer.MessageSystem; using DiIiS_NA.GameServer.MessageSystem;
@ -100,11 +102,7 @@ namespace DiIiS_NA.Core.Logging
public void Trace(string message, params object[] args) => Log(Level.Trace, message, args); public void Trace(string message, params object[] args) => Log(Level.Trace, message, args);
/// <param name="message">The log message.</param> /// <param name="message">The log message.</param>
public void MethodTrace(string message) => Log(Level.MethodTrace, message, null); public void MethodTrace(string message, [CallerMemberName] string methodName = "") => Log(Level.MethodTrace, $"$[olive]${methodName}()$[/]$: " + message, null);
/// <param name="message">The log message.</param>
/// <param name="args">Additional arguments.</param>
public void MethodTrace(string message, params object[] args) => Log(Level.MethodTrace, message, args);
/// <param name="message">The log message.</param> /// <param name="message">The log message.</param>
public void Debug(string message) => Log(Level.Debug, message, null); public void Debug(string message) => Log(Level.Debug, message, null);

View File

@ -11,6 +11,7 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -174,9 +175,9 @@ namespace DiIiS_NA.GameServer.AchievementSystem
{ {
Task.Run(() => Task.Run(() =>
{ {
lock (client._serviceLock) lock (client.ServiceLock)
{ {
Logger.Trace("GrantAchievement(): id {0}", achievementId); Logger.MethodTrace($"id {achievementId}");
if (client.Account.GameAccount.Achievements.Where(a => a.AchievementId == achievementId && a.Completion != -1).Count() > 0) return; if (client.Account.GameAccount.Achievements.Where(a => a.AchievementId == achievementId && a.Completion != -1).Count() > 0) return;
DBAchievements achievement = null; DBAchievements achievement = null;
var achs = DBSessions.SessionQueryWhere<DBAchievements>(dbi => var achs = DBSessions.SessionQueryWhere<DBAchievements>(dbi =>
@ -239,9 +240,9 @@ namespace DiIiS_NA.GameServer.AchievementSystem
{ {
Task.Run(() => Task.Run(() =>
{ {
lock (client._serviceLock) lock (client.ServiceLock)
{ {
Logger.Trace("GrantCriteria(): id {0}", criteriaId); Logger.MethodTrace($"id {criteriaId}");
D3.AchievementsStaticData.StaticCriteriaDefinition definition = null; D3.AchievementsStaticData.StaticCriteriaDefinition definition = null;
uint UCriteriaId = (uint)criteriaId; uint UCriteriaId = (uint)criteriaId;
@ -261,7 +262,7 @@ namespace DiIiS_NA.GameServer.AchievementSystem
var achievement = new DBAchievements(); var achievement = new DBAchievements();
if (achs.Count == 0) if (achs.Count == 0)
{ {
Logger.Trace("GrantCriteria(): creating new ach data"); Logger.MethodTrace("creating new ach data");
achievement.DBGameAccount = client.Account.GameAccount.DBGameAccount; achievement.DBGameAccount = client.Account.GameAccount.DBGameAccount;
achievement.AchievementId = definition.ParentAchievementId; achievement.AchievementId = definition.ParentAchievementId;
achievement.IsHardcore = IsHardcore(definition.ParentAchievementId); achievement.IsHardcore = IsHardcore(definition.ParentAchievementId);
@ -270,7 +271,8 @@ namespace DiIiS_NA.GameServer.AchievementSystem
List<uint> crits = new List<uint>(); List<uint> crits = new List<uint>();
crits.Add(UCriteriaId); crits.Add(UCriteriaId);
achievement.Criteria = SerializeBytes(crits); achievement.Criteria = SerializeBytes(crits);
Logger.Trace("GrantCriteria(): {0} - {1} - {2} - {3}", client.Account.GameAccount.PersistentID, definition.ParentAchievementId, achievement.CompleteTime, UCriteriaId); Logger.MethodTrace(
$"{client.Account.GameAccount.PersistentID} - {definition.ParentAchievementId} - {achievement.CompleteTime} - {UCriteriaId}");
DBSessions.SessionSave(achievement); DBSessions.SessionSave(achievement);
} }
else else
@ -278,7 +280,7 @@ namespace DiIiS_NA.GameServer.AchievementSystem
achievement = achs.First(); achievement = achs.First();
if (!UnserializeBytes(achievement.Criteria).Contains(UCriteriaId)) if (!UnserializeBytes(achievement.Criteria).Contains(UCriteriaId))
{ {
Logger.Trace("GrantCriteria(): editing ach data, id: {0}", achievement.Id); Logger.MethodTrace($"editing ach data, id: {achievement.Id}");
List<uint> crits = UnserializeBytes(achievement.Criteria); List<uint> crits = UnserializeBytes(achievement.Criteria);
crits.Add(UCriteriaId); crits.Add(UCriteriaId);
achievement.Criteria = SerializeBytes(crits); achievement.Criteria = SerializeBytes(crits);
@ -287,7 +289,7 @@ namespace DiIiS_NA.GameServer.AchievementSystem
else return; else return;
} }
Logger.Trace("GrantCriteria(): ach data updated"); Logger.MethodTrace("achievement data updated");
var record = D3.Achievements.CriteriaUpdateRecord.CreateBuilder() var record = D3.Achievements.CriteriaUpdateRecord.CreateBuilder()
.SetCriteriaId32AndFlags8(UCriteriaId) .SetCriteriaId32AndFlags8(UCriteriaId)
@ -340,7 +342,7 @@ namespace DiIiS_NA.GameServer.AchievementSystem
{ {
achievement = achs.First(); achievement = achs.First();
Logger.Trace("GrantCriteria(): editing ach data, id: {0}", achievement.Id); Logger.MethodTrace($"editing ach data, id: {achievement.Id}");
List<uint> crits = UnserializeBytes(achievement.Criteria); List<uint> crits = UnserializeBytes(achievement.Criteria);
crits.Add(UCriteriaId); crits.Add(UCriteriaId);
achievement.Criteria = SerializeBytes(crits); achievement.Criteria = SerializeBytes(crits);
@ -374,10 +376,10 @@ namespace DiIiS_NA.GameServer.AchievementSystem
{ {
Task.Run(() => Task.Run(() =>
{ {
lock (client._serviceLock) lock (client.ServiceLock)
{ {
if (additionalQuantity == 0) return; if (additionalQuantity == 0) return;
Logger.Debug("UpdateQuantity(): id {0}", achievementId); Logger.MethodTrace($"id {achievementId}");
if (client.Account.GameAccount.Achievements.Where(a => a.AchievementId == achievementId && a.Completion != -1).Count() > 0) return; if (client.Account.GameAccount.Achievements.Where(a => a.AchievementId == achievementId && a.Completion != -1).Count() > 0) return;
ulong mainCriteriaId = GetMainCriteria(achievementId); ulong mainCriteriaId = GetMainCriteria(achievementId);
@ -410,7 +412,7 @@ namespace DiIiS_NA.GameServer.AchievementSystem
var achievement = new DBAchievements(); var achievement = new DBAchievements();
if (achs.Count == 0) if (achs.Count == 0)
{ {
Logger.Debug("UpdateQuantity(): creating new ach data"); Logger.MethodTrace("creating new ach data");
achievement.DBGameAccount = client.Account.GameAccount.DBGameAccount; achievement.DBGameAccount = client.Account.GameAccount.DBGameAccount;
achievement.AchievementId = achievementId; achievement.AchievementId = achievementId;
achievement.IsHardcore = IsHardcore(achievementId); achievement.IsHardcore = IsHardcore(achievementId);
@ -423,7 +425,7 @@ namespace DiIiS_NA.GameServer.AchievementSystem
else else
{ {
achievement = achs.First(); achievement = achs.First();
Logger.Trace("UpdateQuantity(): editing ach data, id: {0}", achievement.Id); Logger.MethodTrace($"editing ach data, id: {achievement.Id}");
achievement.Quantity = (int)newQuantity; achievement.Quantity = (int)newQuantity;
DBSessions.SessionUpdate(achievement); DBSessions.SessionUpdate(achievement);
} }

View File

@ -11,7 +11,7 @@ namespace DiIiS_NA.GameServer.CommandManager
{ {
public class CommandGroup public class CommandGroup
{ {
private static readonly Logger Logger = LogManager.CreateLogger("CM"); private static readonly Logger Logger = LogManager.CreateLogger("CmdGrp");
public CommandGroupAttribute Attributes { get; private set; } public CommandGroupAttribute Attributes { get; private set; }
@ -37,7 +37,7 @@ namespace DiIiS_NA.GameServer.CommandManager
if (!_commands.ContainsKey(attribute)) if (!_commands.ContainsKey(attribute))
_commands.Add(attribute, method); _commands.Add(attribute, method);
else else
Logger.Error("Command '{0}' already exists.", attribute.Name); Logger.Fatal("Command '$[underline white]${0}$[/]$' already exists.", attribute.Name);
} }
} }
@ -62,8 +62,11 @@ namespace DiIiS_NA.GameServer.CommandManager
// check if the user has enough privileges to access command group. // check if the user has enough privileges to access command group.
// check if the user has enough privileges to invoke the command. // check if the user has enough privileges to invoke the command.
if (invokerClient != null && Attributes.MinUserLevel > invokerClient.Account.UserLevel) if (invokerClient != null && Attributes.MinUserLevel > invokerClient.Account.UserLevel)
#if DEBUG
return $"You don't have enough privileges to invoke that command (Min. level: {Attributes.MinUserLevel}).";
#else
return "You don't have enough privileges to invoke that command."; return "You don't have enough privileges to invoke that command.";
#endif
string[] @params = null; string[] @params = null;
CommandAttribute target = null; CommandAttribute target = null;
@ -80,7 +83,11 @@ namespace DiIiS_NA.GameServer.CommandManager
// check if the user has enough privileges to invoke the command. // check if the user has enough privileges to invoke the command.
if (invokerClient != null && target.MinUserLevel > invokerClient.Account.UserLevel) if (invokerClient != null && target.MinUserLevel > invokerClient.Account.UserLevel)
#if DEBUG
return $"You don't have enough privileges to invoke that command (Min. level: {Attributes.MinUserLevel}).";
#else
return "You don't have enough privileges to invoke that command."; return "You don't have enough privileges to invoke that command.";
#endif
return (string)_commands[target].Invoke(this, new object[] { @params, invokerClient }); return (string)_commands[target].Invoke(this, new object[] { @params, invokerClient });
} }
@ -99,13 +106,10 @@ namespace DiIiS_NA.GameServer.CommandManager
[DefaultCommand] [DefaultCommand]
public virtual string Fallback(string[] @params = null, BattleClient invokerClient = null) public virtual string Fallback(string[] @params = null, BattleClient invokerClient = null)
{ {
var output = "Available subcommands: "; var output = _commands
foreach (var pair in _commands) .Where(pair => pair.Key.Name.Trim() != string.Empty)
{ .Where(pair => invokerClient == null || pair.Key.MinUserLevel <= invokerClient.Account.UserLevel)
if (pair.Key.Name.Trim() == string.Empty) continue; // skip fallback command. .Aggregate("Available subcommands: ", (current, pair) => current + (pair.Key.Name + ", "));
if (invokerClient != null && pair.Key.MinUserLevel > invokerClient.Account.UserLevel) continue;
output += pair.Key.Name + ", ";
}
return output.Substring(0, output.Length - 2) + "."; return output.Substring(0, output.Length - 2) + ".";
} }

View File

@ -11,7 +11,7 @@ namespace DiIiS_NA.GameServer.CommandManager
{ {
public static class CommandManager public static class CommandManager
{ {
private static readonly Logger Logger = LogManager.CreateLogger("CM"); private static readonly Logger Logger = LogManager.CreateLogger("CmdMan");
private static readonly Dictionary<CommandGroupAttribute, CommandGroup> CommandGroups = new Dictionary<CommandGroupAttribute, CommandGroup>(); private static readonly Dictionary<CommandGroupAttribute, CommandGroup> CommandGroups = new Dictionary<CommandGroupAttribute, CommandGroup>();
static CommandManager() static CommandManager()
@ -150,21 +150,12 @@ namespace DiIiS_NA.GameServer.CommandManager
public override string Fallback(string[] parameters = null, BattleClient invokerClient = null) public override string Fallback(string[] parameters = null, BattleClient invokerClient = null)
{ {
var output = "Available commands: "; var output = "Available commands: ";
if (invokerClient != null) output =
{ invokerClient != null
foreach (var pair in CommandGroups.Where(pair => ? CommandGroups.Where(pair => pair.Key.MinUserLevel > invokerClient?.Account.UserLevel)
pair.Key.MinUserLevel > invokerClient?.Account.UserLevel)) .Aggregate(output, (current, pair) => current + ($"{Config.Instance.CommandPrefix}{pair.Key.Name}: {pair.Key.Help}\n\n"))
{ : CommandGroups
output += "!" + pair.Key.Name + ": " + pair.Key.Help + "\n\n"; .Aggregate(output, (current, pair) => current + (($"$[underline green]${Config.Instance.CommandPrefix}{pair.Key.Name}$[/]$: {pair.Key.Help}\n\n")));
}
}
else
{
foreach (var pair in CommandGroups)
{
output += "!" + pair.Key.Name + ": " + pair.Key.Help + "\n\n";
}
}
return output + "Type 'help <command>' to get help about a specific command."; return output + "Type 'help <command>' to get help about a specific command.";
} }
@ -173,10 +164,7 @@ namespace DiIiS_NA.GameServer.CommandManager
[CommandGroup("help", "usage: help <command>\nType 'commands' to get a list of available commands.")] [CommandGroup("help", "usage: help <command>\nType 'commands' to get a list of available commands.")]
public class HelpCommandGroup : CommandGroup public class HelpCommandGroup : CommandGroup
{ {
public override string Fallback(string[] parameters = null, BattleClient invokerClient = null) public override string Fallback(string[] parameters = null, BattleClient invokerClient = null) => "usage: help <command>\nType 'commands' to get a list of available commands.";
{
return "usage: help <command>\nType 'commands' to get a list of available commands.";
}
public override string Handle(string parameters, BattleClient invokerClient = null) public override string Handle(string parameters, BattleClient invokerClient = null)
{ {
@ -189,11 +177,8 @@ namespace DiIiS_NA.GameServer.CommandManager
var group = @params[0]; var group = @params[0];
var command = @params.Count() > 1 ? @params[1] : string.Empty; var command = @params.Count() > 1 ? @params[1] : string.Empty;
foreach (var pair in CommandGroups) foreach (var pair in CommandGroups.Where(pair => group == pair.Key.Name))
{ {
if (group != pair.Key.Name)
continue;
if (command == string.Empty) if (command == string.Empty)
return pair.Key.Help; return pair.Key.Help;
@ -202,7 +187,7 @@ namespace DiIiS_NA.GameServer.CommandManager
} }
if (!found) if (!found)
output = string.Format("Unknown command: {0} {1}", group, command); output = $"Unknown command: {group} {command}";
return output; return output;
} }

View File

@ -19,15 +19,14 @@ using System.Linq;
using DiIiS_NA.GameServer.GSSystem.GameSystem; using DiIiS_NA.GameServer.GSSystem.GameSystem;
using DiIiS_NA.GameServer.GSSystem.ObjectsSystem; using DiIiS_NA.GameServer.GSSystem.ObjectsSystem;
using DiIiS_NA.GameServer.GSSystem.PlayerSystem; using DiIiS_NA.GameServer.GSSystem.PlayerSystem;
using DiIiS_NA.GameServer.MessageSystem.Message.Definitions.Animation;
using DiIiS_NA.GameServer.MessageSystem.Message.Fields;
using DiIiS_NA.LoginServer.AccountsSystem; using DiIiS_NA.LoginServer.AccountsSystem;
using FluentNHibernate.Utils;
using static DiIiS_NA.Core.MPQ.FileFormats.GameBalance; using static DiIiS_NA.Core.MPQ.FileFormats.GameBalance;
using Actor = DiIiS_NA.Core.MPQ.FileFormats.Actor;
namespace DiIiS_NA.GameServer.CommandManager namespace DiIiS_NA.GameServer.CommandManager;
{
[CommandGroup("powerful", "Makes your character with absurd amount of damage. Useful for testing.", Account.UserLevels.Tester)] [CommandGroup("powerful", "Makes your character with absurd amount of damage. Useful for testing.",
Account.UserLevels.Tester)]
public class PowerfulCommand : CommandGroup public class PowerfulCommand : CommandGroup
{ {
[DefaultCommand] [DefaultCommand]
@ -50,18 +49,47 @@ namespace DiIiS_NA.GameServer.CommandManager
attributes[GameAttribute.Damage_Weapon_Delta, 0] = float.MaxValue; attributes[GameAttribute.Damage_Weapon_Delta, 0] = float.MaxValue;
attributes[GameAttribute.Damage_Weapon_Min, 0] = float.MaxValue; attributes[GameAttribute.Damage_Weapon_Min, 0] = float.MaxValue;
}); });
player.Attributes.BroadcastChangedIfRevealed(); player.Attributes.BroadcastChangedIfRevealed();
return "You are now powerful."; return "You are now powerful.";
} }
} }
[CommandGroup("resourcefull", "Makes your character with full resource. Useful for testing.",
Account.UserLevels.Tester)]
public class ResourcefullCommand : CommandGroup
{
[DefaultCommand]
public string Resourcefull(string[] @params, BattleClient invokerClient)
{
if (invokerClient?.InGameClient?.Player is not { } player)
return "You must be in game to use this command.";
if (player.Attributes.FixedMap.Contains(FixedAttribute.Resourcefull))
{
player.Attributes.FixedMap.Remove(FixedAttribute.Resourcefull);
player.Attributes.BroadcastChangedIfRevealed();
return "You are no longer Resourcefull.";
}
player.Attributes.FixedMap.Add(FixedAttribute.Resourcefull, (attributes) =>
{
attributes[GameAttribute.Resource_Cur, 1] = 100;
});
player.Attributes.BroadcastChangedIfRevealed();
return "You are full resource.";
}
}
[CommandGroup("info", "Get current game information.")] [CommandGroup("info", "Get current game information.")]
public class InfoCommand : CommandGroup public class InfoCommand : CommandGroup
{ {
[DefaultCommand] [DefaultCommand]
public string Info(string[] @params, BattleClient invokerClient) public string Info(string[] @params, BattleClient invokerClient)
{ {
if (invokerClient?.InGameClient?.Game is not { } game || invokerClient.InGameClient.Player is not { } player || invokerClient.Account is not{} account) if (invokerClient?.InGameClient?.Game is not { } game || invokerClient.InGameClient.Player is not { } player ||
invokerClient.Account is not { } account)
return "You are not in game."; return "You are not in game.";
return GetInfo(account, player, game); return GetInfo(account, player, game);
} }
@ -78,7 +106,6 @@ namespace DiIiS_NA.GameServer.CommandManager
}; };
if (account.UserLevel >= Account.UserLevels.GM) if (account.UserLevel >= Account.UserLevels.GM)
{
foreach (var world in game.Worlds) foreach (var world in game.Worlds)
{ {
info.Add($"World: {world.SNO.ToString()} - {(int)world.SNO}"); info.Add($"World: {world.SNO.ToString()} - {(int)world.SNO}");
@ -101,7 +128,6 @@ namespace DiIiS_NA.GameServer.CommandManager
info.Add(""); info.Add("");
} }
}
return string.Join('\n', info); return string.Join('\n', info);
} }
@ -117,7 +143,7 @@ namespace DiIiS_NA.GameServer.CommandManager
return "You must be in game to use this command."; return "You must be in game to use this command.";
var unidentified = player.Inventory.GetBackPackItems().Where(i => i.Unidentified).ToArray(); var unidentified = player.Inventory.GetBackPackItems().Where(i => i.Unidentified).ToArray();
int count = unidentified.Length; var count = unidentified.Length;
player.StartCasting(60 * 2, new Action(() => player.StartCasting(60 * 2, new Action(() =>
{ {
foreach (var item in unidentified) foreach (var item in unidentified)
@ -126,6 +152,7 @@ namespace DiIiS_NA.GameServer.CommandManager
return $"Identified {count} items."; return $"Identified {count} items.";
} }
} }
[CommandGroup("followers", "Manage your followers.", Account.UserLevels.Tester)] [CommandGroup("followers", "Manage your followers.", Account.UserLevels.Tester)]
public class FollowersCommand : CommandGroup public class FollowersCommand : CommandGroup
{ {
@ -137,9 +164,7 @@ namespace DiIiS_NA.GameServer.CommandManager
List<string> followers = new(); List<string> followers = new();
foreach (var follower in player.Followers.OrderBy(s => s.Value)) foreach (var follower in player.Followers.OrderBy(s => s.Value))
{
followers.Add($"[{follower.Key}] {follower.Value.ToString()}"); followers.Add($"[{follower.Key}] {follower.Value.ToString()}");
}
return string.Join('\n', followers); return string.Join('\n', followers);
} }
@ -152,10 +177,7 @@ namespace DiIiS_NA.GameServer.CommandManager
var followers = player.Followers.ToArray(); var followers = player.Followers.ToArray();
// destroy followers // destroy followers
foreach (var follower in followers) foreach (var follower in followers) player.DestroyFollower(follower.Value);
{
player.DestroyFollower(follower.Value);
}
return $"Dismissed {followers.Length} followers."; return $"Dismissed {followers.Length} followers.";
} }
@ -254,7 +276,7 @@ namespace DiIiS_NA.GameServer.CommandManager
return "You cannot invoke this command from console."; return "You cannot invoke this command from console.";
if (invokerClient.InGameClient == null) if (invokerClient.InGameClient == null)
return "You can only invoke this command while ingame."; return "You can only invoke this command while in-game.";
var player = invokerClient.InGameClient.Player; var player = invokerClient.InGameClient.Player;
var actorSNO = 6652; /* zombie */ var actorSNO = 6652; /* zombie */
@ -275,32 +297,31 @@ namespace DiIiS_NA.GameServer.CommandManager
*/ */
if (@params != null) if (@params != null)
{ {
if (!Int32.TryParse(@params[0], out actorSNO)) if (!int.TryParse(@params[0], out actorSNO))
actorSNO = 6652; actorSNO = 6652;
if (@params.Count() > 1) if (@params.Count() > 1)
if (!Int32.TryParse(@params[1], out amount)) if (!int.TryParse(@params[1], out amount))
amount = 1; amount = 1;
if (amount > 100) amount = 100; if (amount > 100) amount = 100;
} }
for (int i = 0; i < amount; i++) for (var i = 0; i < amount; i++)
{ {
var position = new Vector3D(player.Position.X + (float)RandomHelper.NextDouble() * 20f, var position = new Vector3D(player.Position.X + (float)RandomHelper.NextDouble() * 20f,
player.Position.Y + (float)RandomHelper.NextDouble() * 20f, player.Position.Y + (float)RandomHelper.NextDouble() * 20f,
player.Position.Z); player.Position.Z);
var monster = player.World.SpawnMonster((ActorSno)actorSNO, position); var monster = player.World.SpawnMonster((ActorSno)actorSNO, position);
} }
return $"Spawned {amount} mobs with ActorSNO: {actorSNO}"; return $"Spawned {amount} mobs with ActorSNO: {actorSNO}";
} }
} }
[CommandGroup("levelup", "Levels your character.\nOptionally specify the number of levels: !levelup [count]", Account.UserLevels.GM)] [CommandGroup("levelup", "Levels your character.\nOptionally specify the number of levels: !levelup [count]",
Account.UserLevels.GM)]
public class LevelUpCommand : CommandGroup public class LevelUpCommand : CommandGroup
{ {
[DefaultCommand] [DefaultCommand]
@ -310,19 +331,16 @@ namespace DiIiS_NA.GameServer.CommandManager
return "You cannot invoke this command from console."; return "You cannot invoke this command from console.";
if (invokerClient.InGameClient == null) if (invokerClient.InGameClient == null)
return "You can only invoke this command while ingame."; return "You can only invoke this command while in-game.";
var player = invokerClient.InGameClient.Player; var player = invokerClient.InGameClient.Player;
var amount = 1; var amount = 1;
if (@params != null) if (@params != null)
{ if (!int.TryParse(@params[0], out amount))
if (!Int32.TryParse(@params[0], out amount))
amount = 1; amount = 1;
}
for (int i = 0; i < amount; i++) for (var i = 0; i < amount; i++)
{
if (player.Level >= 70) if (player.Level >= 70)
{ {
player.UpdateExp((int)player.Attributes[GameAttribute.Alt_Experience_Next_Lo]); player.UpdateExp((int)player.Attributes[GameAttribute.Alt_Experience_Next_Lo]);
@ -335,13 +353,9 @@ namespace DiIiS_NA.GameServer.CommandManager
player.PlayEffect(Effect.LevelUp, null, false); player.PlayEffect(Effect.LevelUp, null, false);
player.World.PowerManager.RunPower(player, 85954); player.World.PowerManager.RunPower(player, 85954);
} }
}
player.Toon.GameAccount.NotifyUpdate(); player.Toon.GameAccount.NotifyUpdate();
if (player.Level >= 70) return player.Level >= 70 ? $"New paragon level: {player.ParagonLevel}" : $"New level: {player.Toon.Level}";
return $"New paragon level: {player.ParagonLevel}";
else
return $"New level: {player.Toon.Level}";
} }
} }
@ -355,7 +369,7 @@ namespace DiIiS_NA.GameServer.CommandManager
return "You cannot invoke this command from console."; return "You cannot invoke this command from console.";
if (invokerClient.InGameClient == null) if (invokerClient.InGameClient == null)
return "You can only invoke this command while ingame."; return "You can only invoke this command while in-game.";
var player = invokerClient.InGameClient.Player; var player = invokerClient.InGameClient.Player;
@ -378,12 +392,13 @@ namespace DiIiS_NA.GameServer.CommandManager
player.LoadCrafterData(); player.LoadCrafterData();
player.Toon.GameAccount.NotifyUpdate(); player.Toon.GameAccount.NotifyUpdate();
return string.Format("All artisans Unlocked"); return "All artisans Unlocked";
} }
} }
[CommandGroup("platinum", [CommandGroup("platinum",
"Platinum for your character.\nOptionally specify the number of levels: !platinum [count]", Account.UserLevels.Tester)] "Platinum for your character.\nOptionally specify the number of levels: !platinum [count]",
Account.UserLevels.Tester)]
public class PlatinumCommand : CommandGroup public class PlatinumCommand : CommandGroup
{ {
[DefaultCommand] [DefaultCommand]
@ -393,16 +408,14 @@ namespace DiIiS_NA.GameServer.CommandManager
return "You cannot invoke this command from console."; return "You cannot invoke this command from console.";
if (invokerClient.InGameClient == null) if (invokerClient.InGameClient == null)
return "You can only invoke this command while ingame."; return "You can only invoke this command while in-game.";
var player = invokerClient.InGameClient.Player; var player = invokerClient.InGameClient.Player;
var amount = 1; var amount = 1;
if (@params != null) if (@params != null)
{ if (!int.TryParse(@params[0], out amount))
if (!Int32.TryParse(@params[0], out amount))
amount = 1; amount = 1;
}
player.InGameClient.SendMessage(new PlatinumAwardedMessage player.InGameClient.SendMessage(new PlatinumAwardedMessage
@ -413,7 +426,7 @@ namespace DiIiS_NA.GameServer.CommandManager
player.InGameClient.BnetClient.Account.GameAccount.Platinum += amount; player.InGameClient.BnetClient.Account.GameAccount.Platinum += amount;
return string.Format("Platinum test"); return "Platinum test";
} }
} }
@ -427,17 +440,18 @@ namespace DiIiS_NA.GameServer.CommandManager
return "You cannot invoke this command from console."; return "You cannot invoke this command from console.";
if (invokerClient.InGameClient == null) if (invokerClient.InGameClient == null)
return "You can only invoke this command while ingame."; return "You can only invoke this command while in-game.";
var player = invokerClient.InGameClient.Player; var player = invokerClient.InGameClient.Player;
player.Inventory.OnBuySharedStashSlots(null); player.Inventory.OnBuySharedStashSlots(null);
return string.Format("Stash Upgraded"); return "Stash Upgraded";
} }
} }
[CommandGroup("gold", "Gold for your character.\nOptionally specify the number of gold: !gold [count]", Account.UserLevels.GM)] [CommandGroup("gold", "Gold for your character.\nOptionally specify the number of gold: !gold [count]",
Account.UserLevels.GM)]
public class GoldCommand : CommandGroup public class GoldCommand : CommandGroup
{ {
[DefaultCommand] [DefaultCommand]
@ -447,16 +461,14 @@ namespace DiIiS_NA.GameServer.CommandManager
return "You cannot invoke this command from console."; return "You cannot invoke this command from console.";
if (invokerClient.InGameClient == null) if (invokerClient.InGameClient == null)
return "You can only invoke this command while ingame."; return "You can only invoke this command while in-game.";
var player = invokerClient.InGameClient.Player; var player = invokerClient.InGameClient.Player;
var amount = 1; var amount = 1;
if (@params != null) if (@params != null)
{ if (!int.TryParse(@params[0], out amount))
if (!Int32.TryParse(@params[0], out amount))
amount = 1; amount = 1;
}
player.Inventory.AddGoldAmount(amount); player.Inventory.AddGoldAmount(amount);
@ -475,22 +487,17 @@ namespace DiIiS_NA.GameServer.CommandManager
return "You cannot invoke this command from console."; return "You cannot invoke this command from console.";
if (invokerClient.InGameClient == null) if (invokerClient.InGameClient == null)
return "You can only invoke this command while ingame."; return "You can only invoke this command while in-game.";
var player = invokerClient.InGameClient.Player; var player = invokerClient.InGameClient.Player;
var amount = 1; var amount = 1;
var achiid = 74987243307074; var achiid = 74987243307074;
if (@params != null) if (@params != null)
{ if (!int.TryParse(@params[0], out amount))
if (!Int32.TryParse(@params[0], out amount))
amount = 1; amount = 1;
//if (!Int32.TryParse(@params[1], out amount)) //if (!Int32.TryParse(@params[1], out amount))
// achiid = 74987243307074; // achiid = 74987243307074;
}
player.InGameClient.SendMessage(new PlatinumAchievementAwardedMessage player.InGameClient.SendMessage(new PlatinumAchievementAwardedMessage
{ {
CurrentPlatinum = 0, CurrentPlatinum = 0,
@ -499,11 +506,12 @@ namespace DiIiS_NA.GameServer.CommandManager
}); });
return string.Format("Achievement test"); return "Achievement test";
} }
} }
[CommandGroup("eff", "Platinum for your character.\nOptionally specify the number of levels: !eff [count]", Account.UserLevels.GM)] [CommandGroup("eff", "Platinum for your character.\nOptionally specify the number of levels: !eff [count]",
Account.UserLevels.GM)]
public class PlayEffectGroup : CommandGroup public class PlayEffectGroup : CommandGroup
{ {
[DefaultCommand] [DefaultCommand]
@ -513,16 +521,14 @@ namespace DiIiS_NA.GameServer.CommandManager
return "You cannot invoke this command from console."; return "You cannot invoke this command from console.";
if (invokerClient.InGameClient == null) if (invokerClient.InGameClient == null)
return "You can only invoke this command while ingame."; return "You can only invoke this command while in-game.";
var player = invokerClient.InGameClient.Player; var player = invokerClient.InGameClient.Player;
var id = 1; var id = 1;
if (@params != null) if (@params != null)
{ if (!int.TryParse(@params[0], out id))
if (!Int32.TryParse(@params[0], out id))
id = 1; id = 1;
}
player.PlayEffectGroup(id); player.PlayEffectGroup(id);
@ -530,7 +536,8 @@ namespace DiIiS_NA.GameServer.CommandManager
} }
} }
[CommandGroup("item", "Spawns an item (with a name or type).\nUsage: item [type <type>|<name>] [amount]", Account.UserLevels.GM)] [CommandGroup("item", "Spawns an item (with a name or type).\nUsage: item [type <type>|<name>] [amount]",
Account.UserLevels.GM)]
public class ItemCommand : CommandGroup public class ItemCommand : CommandGroup
{ {
[DefaultCommand] [DefaultCommand]
@ -540,7 +547,7 @@ namespace DiIiS_NA.GameServer.CommandManager
return "You cannot invoke this command from console."; return "You cannot invoke this command from console.";
if (invokerClient.InGameClient == null) if (invokerClient.InGameClient == null)
return "You can only invoke this command while ingame."; return "You can only invoke this command while in-game.";
var player = invokerClient.InGameClient.Player; var player = invokerClient.InGameClient.Player;
var name = "Dye_02"; var name = "Dye_02";
@ -556,12 +563,12 @@ namespace DiIiS_NA.GameServer.CommandManager
return "You need to specify a valid item name!"; return "You need to specify a valid item name!";
if (@params.Count() == 1 || !Int32.TryParse(@params[1], out amount)) if (@params.Count() == 1 || !int.TryParse(@params[1], out amount))
amount = 1; amount = 1;
if (amount > 100) amount = 100; if (amount > 100) amount = 100;
for (int i = 0; i < amount; i++) for (var i = 0; i < amount; i++)
{ {
var position = new Vector3D(player.Position.X + (float)RandomHelper.NextDouble() * 20f, var position = new Vector3D(player.Position.X + (float)RandomHelper.NextDouble() * 20f,
player.Position.Y + (float)RandomHelper.NextDouble() * 20f, player.Position.Y + (float)RandomHelper.NextDouble() * 20f,
@ -572,7 +579,6 @@ namespace DiIiS_NA.GameServer.CommandManager
} }
return $"Spawned {amount} items with name: {name}"; return $"Spawned {amount} items with name: {name}";
} }
[Command("type", "Spawns random items of a given type.\nUsage: item type <type> [amount]")] [Command("type", "Spawns random items of a given type.\nUsage: item type <type> [amount]")]
@ -582,7 +588,7 @@ namespace DiIiS_NA.GameServer.CommandManager
return "You cannot invoke this command from console."; return "You cannot invoke this command from console.";
if (invokerClient.InGameClient == null) if (invokerClient.InGameClient == null)
return "You can only invoke this command while ingame."; return "You can only invoke this command while in-game.";
var player = invokerClient.InGameClient.Player; var player = invokerClient.InGameClient.Player;
var name = "Dye"; var name = "Dye";
@ -599,12 +605,12 @@ namespace DiIiS_NA.GameServer.CommandManager
if (type == null) if (type == null)
return "The type given is not a valid item type."; return "The type given is not a valid item type.";
if (@params.Count() == 1 || !Int32.TryParse(@params[1], out amount)) if (@params.Count() == 1 || !int.TryParse(@params[1], out amount))
amount = 1; amount = 1;
if (amount > 100) amount = 100; if (amount > 100) amount = 100;
for (int i = 0; i < amount; i++) for (var i = 0; i < amount; i++)
{ {
var position = new Vector3D(player.Position.X + (float)RandomHelper.NextDouble() * 20f, var position = new Vector3D(player.Position.X + (float)RandomHelper.NextDouble() * 20f,
player.Position.Y + (float)RandomHelper.NextDouble() * 20f, player.Position.Y + (float)RandomHelper.NextDouble() * 20f,
@ -624,7 +630,7 @@ namespace DiIiS_NA.GameServer.CommandManager
return "You cannot invoke this command from console."; return "You cannot invoke this command from console.";
if (invokerClient.InGameClient == null) if (invokerClient.InGameClient == null)
return "You can only invoke this command while ingame."; return "You can only invoke this command while in-game.";
var player = invokerClient.InGameClient.Player; var player = invokerClient.InGameClient.Player;
@ -636,11 +642,13 @@ namespace DiIiS_NA.GameServer.CommandManager
var msg = new InventoryDropItemMessage { ItemID = item.DynamicID(player) }; var msg = new InventoryDropItemMessage { ItemID = item.DynamicID(player) };
player.Inventory.Consume(invokerClient.InGameClient, msg); player.Inventory.Consume(invokerClient.InGameClient, msg);
} }
return $"Dropped {bpItems.Count} Items for you"; return $"Dropped {bpItems.Count} Items for you";
} }
} }
[CommandGroup("drop", "Drops an epic item for your class.\nOptionally specify the number of items: !drop [1-20]", Account.UserLevels.Owner)] [CommandGroup("drop", "Drops an epic item for your class.\nOptionally specify the number of items: !drop [1-20]",
Account.UserLevels.Owner)]
public class DropCommand : CommandGroup public class DropCommand : CommandGroup
{ {
[DefaultCommand] [DefaultCommand]
@ -651,7 +659,8 @@ namespace DiIiS_NA.GameServer.CommandManager
var amount = 1; var amount = 1;
if (@params != null && @params.Any()) if (@params != null && @params.Any())
if (!Int32.TryParse(@params[0], out amount)) amount = 1; if (!int.TryParse(@params[0], out amount))
amount = 1;
amount = amount switch amount = amount switch
{ {
@ -662,19 +671,21 @@ namespace DiIiS_NA.GameServer.CommandManager
try try
{ {
for (int i = 0; i < amount; i++) for (var i = 0; i < amount; i++)
player.World.SpawnRandomEquip(player, player, 11, player.Level, toonClass: player.Toon.Class, canBeUnidentified: false); player.World.SpawnRandomEquip(player, player, 11, player.Level, toonClass: player.Toon.Class,
canBeUnidentified: false);
} }
catch catch
{ {
for (int i = 0; i < amount; i++) for (var i = 0; i < amount; i++)
player.World.SpawnRandomEquip(player, player, 8, player.Level, toonClass: player.Toon.Class, canBeUnidentified: false); player.World.SpawnRandomEquip(player, player, 8, player.Level, toonClass: player.Toon.Class,
canBeUnidentified: false);
} }
return $"Dropped {amount} random equipment."; return $"Dropped {amount} random equipment.";
} }
} }
[CommandGroup("tp", "Transfers your character to another world.")] [CommandGroup("tp", "Transfers your character to another world.")]
public class TeleportCommand : CommandGroup public class TeleportCommand : CommandGroup
{ {
@ -685,12 +696,11 @@ namespace DiIiS_NA.GameServer.CommandManager
return "You cannot invoke this command from console."; return "You cannot invoke this command from console.";
if (invokerClient.InGameClient == null) if (invokerClient.InGameClient == null)
return "You can only invoke this command while ingame."; return "You can only invoke this command while in-game.";
if (@params != null && @params.Count() > 0) if (@params != null && @params.Any())
{ {
var worldId = 0; int.TryParse(@params[0], out var worldId);
Int32.TryParse(@params[0], out worldId);
if (worldId == 0) if (worldId == 0)
return "Invalid arguments. Type 'help tp' to get help."; return "Invalid arguments. Type 'help tp' to get help.";
@ -714,10 +724,8 @@ namespace DiIiS_NA.GameServer.CommandManager
var scene = scenes[0]; // Parent scene /fasbat var scene = scenes[0]; // Parent scene /fasbat
if (scenes.Count == 2) // What if it's a subscene? if (scenes.Count == 2) // What if it's a subscene?
{
if (scenes[1].ParentChunkID != 0xFFFFFFFF) if (scenes[1].ParentChunkID != 0xFFFFFFFF)
scene = scenes[1]; scene = scenes[1];
}
var levelArea = scene.Specification.SNOLevelAreas[0]; var levelArea = scene.Specification.SNOLevelAreas[0];
@ -728,7 +736,6 @@ namespace DiIiS_NA.GameServer.CommandManager
var trigger = var trigger =
invokerClient.InGameClient.Player.World.Game.SideQuestProgress.GlobalQuestTriggers[levelArea]; invokerClient.InGameClient.Player.World.Game.SideQuestProgress.GlobalQuestTriggers[levelArea];
if (trigger.triggerType == QuestStepObjectiveType.EnterLevelArea) if (trigger.triggerType == QuestStepObjectiveType.EnterLevelArea)
{
try try
{ {
trigger.questEvent.Execute(invokerClient.InGameClient.Player.World); // launch a questEvent trigger.questEvent.Execute(invokerClient.InGameClient.Player.World); // launch a questEvent
@ -737,7 +744,6 @@ namespace DiIiS_NA.GameServer.CommandManager
{ {
} }
} }
}
foreach (var bounty in invokerClient.InGameClient.Player.World.Game.QuestManager.Bounties) foreach (var bounty in invokerClient.InGameClient.Player.World.Game.QuestManager.Bounties)
bounty.CheckLevelArea(levelArea); bounty.CheckLevelArea(levelArea);
@ -758,15 +764,15 @@ namespace DiIiS_NA.GameServer.CommandManager
return "You cannot invoke this command from console."; return "You cannot invoke this command from console.";
if (invokerClient.InGameClient == null) if (invokerClient.InGameClient == null)
return "You can only invoke this command while ingame."; return "You can only invoke this command while in-game.";
if (@params.Count() != 1) if (@params.Count() != 1)
return "Invalid arguments. Type 'help conversation' to get help."; return "Invalid arguments. Type 'help conversation' to get help.";
try try
{ {
var conversation = MPQStorage.Data.Assets[SNOGroup.Conversation][Int32.Parse(@params[0])]; var conversation = MPQStorage.Data.Assets[SNOGroup.Conversation][int.Parse(@params[0])];
invokerClient.InGameClient.Player.Conversations.StartConversation(Int32.Parse(@params[0])); invokerClient.InGameClient.Player.Conversations.StartConversation(int.Parse(@params[0]));
return $"Started conversation {conversation.FileName}"; return $"Started conversation {conversation.FileName}";
} }
catch (Exception e) catch (Exception e)
@ -795,8 +801,8 @@ namespace DiIiS_NA.GameServer.CommandManager
if (@params.Any()) if (@params.Any())
{ {
if (!float.TryParse(@params[0], out speedValue) || speedValue < 0 || speedValue > maxSpeed) if (!float.TryParse(@params[0], out speedValue) || speedValue is < 0 or > maxSpeed)
return ("Invalid speed value. Must be a number between 0 and 2."); return "Invalid speed value. Must be a number between 0 and 2.";
} }
else else
{ {
@ -830,7 +836,7 @@ namespace DiIiS_NA.GameServer.CommandManager
return "You cannot invoke this command from console."; return "You cannot invoke this command from console.";
if (invokerClient.InGameClient == null) if (invokerClient.InGameClient == null)
return "You can only invoke this command while ingame."; return "You can only invoke this command while in-game.";
return ""; return "";
} }
@ -841,7 +847,7 @@ namespace DiIiS_NA.GameServer.CommandManager
try try
{ {
invokerClient.InGameClient.Game.QuestManager.Advance(); invokerClient.InGameClient.Game.QuestManager.Advance();
return String.Format("Advancing main quest line"); return "Advancing main quest line";
} }
catch (Exception e) catch (Exception e)
{ {
@ -855,7 +861,7 @@ namespace DiIiS_NA.GameServer.CommandManager
try try
{ {
invokerClient.InGameClient.Game.QuestManager.SideAdvance(); invokerClient.InGameClient.Game.QuestManager.SideAdvance();
return String.Format("Advancing side quest line"); return "Advancing side quest line";
} }
catch (Exception e) catch (Exception e)
{ {
@ -872,12 +878,12 @@ namespace DiIiS_NA.GameServer.CommandManager
if (@params.Count() != 1) if (@params.Count() != 1)
return "Invalid arguments. Type 'help text public' to get help."; return "Invalid arguments. Type 'help text public' to get help.";
int questId = Int32.Parse(@params[0]); var questId = int.Parse(@params[0]);
try try
{ {
invokerClient.InGameClient.Game.QuestManager.LaunchSideQuest(questId, true); invokerClient.InGameClient.Game.QuestManager.LaunchSideQuest(questId, true);
return String.Format("Advancing side quest line"); return "Advancing side quest line";
} }
catch (Exception e) catch (Exception e)
{ {
@ -894,13 +900,13 @@ namespace DiIiS_NA.GameServer.CommandManager
if (@params.Count() != 2) if (@params.Count() != 2)
return "Invalid arguments. Type 'help text public' to get help."; return "Invalid arguments. Type 'help text public' to get help.";
int eventId = Int32.Parse(@params[0]); var eventId = int.Parse(@params[0]);
int duration = Int32.Parse(@params[1]); var duration = int.Parse(@params[1]);
invokerClient.InGameClient.Game.QuestManager.LaunchQuestTimer(eventId, (float)duration, invokerClient.InGameClient.Game.QuestManager.LaunchQuestTimer(eventId, (float)duration,
new Action<int>((q) => { })); new Action<int>((q) => { }));
return String.Format("Message sent."); return "Message sent.";
} }
[Command("info", "Retrieves information about quest states.\n Usage: info")] [Command("info", "Retrieves information about quest states.\n Usage: info")]
@ -932,84 +938,59 @@ namespace DiIiS_NA.GameServer.CommandManager
var matches = new List<Asset>(); var matches = new List<Asset>();
if (@params.Count() < 1) if (!@params.Any())
return "Invalid arguments. Type 'help lookup actor' to get help."; return "Invalid arguments. Type 'help lookup actor' to get help.";
var pattern = @params[0].ToLower(); var pattern = @params[0].ToLower();
foreach (var groupPair in MPQStorage.Data.Assets) foreach (var groupPair in MPQStorage.Data.Assets) matches.AddRange(from pair in groupPair.Value where pair.Value.Name.ToLower().Contains(pattern) select pair.Value);
{
foreach (var pair in groupPair.Value)
{
if (pair.Value.Name.ToLower().Contains(pattern))
matches.Add(pair.Value);
}
}
return matches.Aggregate(matches.Count >= 1 ? "Matches:\n" : "No matches found.", return matches.Aggregate(matches.Count >= 1 ? "Matches:\n" : "No matches found.",
(current, match) => current + (current, match) =>
$"[{match.SNOId.ToString("D6")}] [{match.Group}] {match.Name}\n"); $"{current} [{match.SNOId:D6}] [{match.Group}] {match.Name}\n");
} }
[Command("actor", "Allows you to search for an actor.\nUsage: lookup actor <pattern>")] [Command("actor", "Allows you to search for an actor.\nUsage: lookup actor <pattern>")]
public string Actor(string[] @params, BattleClient invokerClient) public string Actor(string[] @params, BattleClient invokerClient)
{ {
var matches = new List<Asset>(); if (!@params.Any())
if (@params.Count() < 1)
return "Invalid arguments. Type 'help lookup actor' to get help."; return "Invalid arguments. Type 'help lookup actor' to get help.";
var pattern = @params[0].ToLower(); var pattern = @params[0].ToLower();
foreach (var pair in MPQStorage.Data.Assets[SNOGroup.Actor]) var matches = (from pair in MPQStorage.Data.Assets[SNOGroup.Actor] where pair.Value.Name.ToLower().Contains(pattern) select pair.Value).ToList();
{
if (pair.Value.Name.ToLower().Contains(pattern))
matches.Add(pair.Value);
}
return matches.Aggregate(matches.Count >= 1 ? "Actor Matches:\n" : "No match found.", return matches.Aggregate(matches.Count >= 1 ? "Actor Matches:\n" : "No match found.",
(current, match) => current + (current, match) => current +
$"[{match.SNOId.ToString("D6")}] {match.Name} ({(match.Data as DiIiS_NA.Core.MPQ.FileFormats.Actor).Type} {(((match.Data as DiIiS_NA.Core.MPQ.FileFormats.Actor).Type == ActorType.Gizmo) ? ((int)(match.Data as DiIiS_NA.Core.MPQ.FileFormats.Actor).TagMap[ActorKeys.GizmoGroup]).ToString() : "")})\n"); $"[{match.SNOId:D6}] {match.Name} ({((Actor)match.Data).Type} {(((Actor)match.Data).Type == ActorType.Gizmo ? ((int)((Actor)match.Data).TagMap[ActorKeys.GizmoGroup]).ToString() : "")})\n");
} }
[Command("rope", "Allows you to search for an rope.\nUsage: lookup rope <pattern>")] [Command("rope", "Allows you to search for an rope.\nUsage: lookup rope <pattern>")]
public string Rope(string[] @params, BattleClient invokerClient) public string Rope(string[] @params, BattleClient invokerClient)
{ {
var matches = new List<Asset>(); if (!@params.Any())
if (@params.Count() < 1)
return "Invalid arguments. Type 'help lookup actor' to get help."; return "Invalid arguments. Type 'help lookup actor' to get help.";
var pattern = @params[0].ToLower(); var pattern = @params[0].ToLower();
foreach (var pair in MPQStorage.Data.Assets[SNOGroup.Rope]) var matches = (from pair in MPQStorage.Data.Assets[SNOGroup.Rope] where pair.Value.Name.ToLower().Contains(pattern) select pair.Value).ToList();
{
if (pair.Value.Name.ToLower().Contains(pattern))
matches.Add(pair.Value);
}
return matches.Aggregate(matches.Count >= 1 ? "Rope Matches:\n" : "No match found.", return matches.Aggregate(matches.Count >= 1 ? "Rope Matches:\n" : "No match found.",
(current, match) => current + $"[{match.SNOId.ToString("D6")}] {match.Name}\n"); (current, match) => current + $"[{match.SNOId:D6}] {match.Name}\n");
} }
[Command("conv", "Allows you to search for an conversation.\nUsage: lookup conv <pattern>")] [Command("conv", "Allows you to search for an conversation.\nUsage: lookup conv <pattern>")]
public string Conversation(string[] @params, BattleClient invokerClient) public string Conversation(string[] @params, BattleClient invokerClient)
{ {
var matches = new List<Asset>(); if (!@params.Any())
if (@params.Count() < 1)
return "Invalid arguments. Type 'help lookup actor' to get help."; return "Invalid arguments. Type 'help lookup actor' to get help.";
var pattern = @params[0].ToLower(); var pattern = @params[0].ToLower();
foreach (var pair in MPQStorage.Data.Assets[SNOGroup.Conversation]) var matches = (from pair in MPQStorage.Data.Assets[SNOGroup.Conversation] where pair.Value.Name.ToLower().Contains(pattern) select pair.Value).ToList();
{
if (pair.Value.Name.ToLower().Contains(pattern))
matches.Add(pair.Value);
}
return matches.Aggregate(matches.Count >= 1 ? "Conversation Matches:\n" : "No match found.", return matches.Aggregate(matches.Count >= 1 ? "Conversation Matches:\n" : "No match found.",
(current, match) => current + $"[{match.SNOId.ToString("D6")}] {match.Name}\n"); (current, match) => current + $"[{match.SNOId:D6}] {match.Name}\n");
} }
[Command("power", "Allows you to search for a power.\nUsage: lookup power <pattern>")] [Command("power", "Allows you to search for a power.\nUsage: lookup power <pattern>")]
@ -1017,31 +998,23 @@ namespace DiIiS_NA.GameServer.CommandManager
{ {
var matches = new List<Asset>(); var matches = new List<Asset>();
if (@params.Count() < 1) if (!@params.Any())
return "Invalid arguments. Type 'help lookup power' to get help."; return "Invalid arguments. Type 'help lookup power' to get help.";
if (@params[0].ToLower() == "id") if (@params[0].ToLower() == "id")
{ {
var num = Int32.Parse(@params[1]); var num = int.Parse(@params[1]);
foreach (var pair in MPQStorage.Data.Assets[SNOGroup.Power]) matches.AddRange(from pair in MPQStorage.Data.Assets[SNOGroup.Power] where pair.Value.SNOId == num select pair.Value);
{
if (pair.Value.SNOId == num)
matches.Add(pair.Value);
}
} }
else else
{ {
var pattern = @params[0].ToLower(); var pattern = @params[0].ToLower();
foreach (var pair in MPQStorage.Data.Assets[SNOGroup.Power]) matches.AddRange(from pair in MPQStorage.Data.Assets[SNOGroup.Power] where pair.Value.Name.ToLower().Contains(pattern) select pair.Value);
{
if (pair.Value.Name.ToLower().Contains(pattern))
matches.Add(pair.Value);
}
} }
return matches.Aggregate(matches.Count >= 1 ? "World Matches:\n" : "No match found.", return matches.Aggregate(matches.Count >= 1 ? "World Matches:\n" : "No match found.",
(current, match) => current + (current, match) => current +
$"[{match.SNOId.ToString("D6")}] {match.Name} - {(match.Data as World).DynamicWorld}\n"); $"[{match.SNOId:D6}] {match.Name} - {((World)match.Data).DynamicWorld}\n");
} }
[Command("world", [Command("world",
@ -1050,31 +1023,27 @@ namespace DiIiS_NA.GameServer.CommandManager
{ {
var matches = new List<Asset>(); var matches = new List<Asset>();
if (@params.Count() < 1) if (!@params.Any())
return "Invalid arguments. Type 'help lookup world' to get help."; return "Invalid arguments. Type 'help lookup world' to get help.";
if (@params[0].ToLower() == "id") if (@params[0].ToLower() == "id")
{ {
var num = Int32.Parse(@params[1]); var num = int.Parse(@params[1]);
foreach (var pair in MPQStorage.Data.Assets[SNOGroup.Worlds]) foreach (var pair in MPQStorage.Data.Assets[SNOGroup.Worlds])
{
if (pair.Value.SNOId == num) if (pair.Value.SNOId == num)
matches.Add(pair.Value); matches.Add(pair.Value);
} }
}
else else
{ {
var pattern = @params[0].ToLower(); var pattern = @params[0].ToLower();
foreach (var pair in MPQStorage.Data.Assets[SNOGroup.Worlds]) foreach (var pair in MPQStorage.Data.Assets[SNOGroup.Worlds])
{
if (pair.Value.Name.ToLower().Contains(pattern)) if (pair.Value.Name.ToLower().Contains(pattern))
matches.Add(pair.Value); matches.Add(pair.Value);
} }
}
return matches.Aggregate(matches.Count >= 1 ? "World Matches:\n" : "No match found.", return matches.Aggregate(matches.Count >= 1 ? "World Matches:\n" : "No match found.",
(current, match) => current + (current, match) => current +
$"[{match.SNOId.ToString("D6")}] {match.Name} - {(match.Data as World).DynamicWorld}\n"); $"[{match.SNOId:D6}] {match.Name} - {(match.Data as World).DynamicWorld}\n");
} }
[Command("qr", "Show QuestRange of an actor.\nUsage: lookup qr <id>")] [Command("qr", "Show QuestRange of an actor.\nUsage: lookup qr <id>")]
@ -1082,20 +1051,18 @@ namespace DiIiS_NA.GameServer.CommandManager
{ {
var matches = new List<Asset>(); var matches = new List<Asset>();
if (@params.Count() < 1) if (!@params.Any())
return "Invalid arguments. Type 'help lookup world' to get help."; return "Invalid arguments. Type 'help lookup world' to get help.";
var num = Int32.Parse(@params[0]); var num = int.Parse(@params[0]);
string qr_id = "-1"; var qr_id = "-1";
string qr_name = "None"; var qr_name = "None";
foreach (var pair in MPQStorage.Data.Assets[SNOGroup.QuestRange]) foreach (var pair in MPQStorage.Data.Assets[SNOGroup.QuestRange])
{
if (pair.Value.SNOId == num) if (pair.Value.SNOId == num)
{ {
qr_id = pair.Value.SNOId.ToString("D6"); qr_id = pair.Value.SNOId.ToString("D6");
qr_name = pair.Value.Name; qr_name = pair.Value.Name;
} }
}
return $"[{qr_id}] {qr_name}"; return $"[{qr_id}] {qr_name}";
} }
@ -1103,21 +1070,21 @@ namespace DiIiS_NA.GameServer.CommandManager
public static int GetExitBits(Asset scene) public static int GetExitBits(Asset scene)
{ {
if (scene.Name.Contains("_N_")) return 1; if (scene.Name.Contains("_N_")) return 1;
else if (scene.Name.Contains("_S_")) return 2; if (scene.Name.Contains("_S_")) return 2;
else if (scene.Name.Contains("_NS_")) return 3; if (scene.Name.Contains("_NS_")) return 3;
else if (scene.Name.Contains("_E_")) return 4; if (scene.Name.Contains("_E_")) return 4;
else if (scene.Name.Contains("_NE_")) return 5; if (scene.Name.Contains("_NE_")) return 5;
else if (scene.Name.Contains("_SE_")) return 6; if (scene.Name.Contains("_SE_")) return 6;
else if (scene.Name.Contains("_NSE_")) return 7; if (scene.Name.Contains("_NSE_")) return 7;
else if (scene.Name.Contains("_W_")) return 8; if (scene.Name.Contains("_W_")) return 8;
else if (scene.Name.Contains("_NW_")) return 9; if (scene.Name.Contains("_NW_")) return 9;
else if (scene.Name.Contains("_SW_")) return 10; if (scene.Name.Contains("_SW_")) return 10;
else if (scene.Name.Contains("_NSW_")) return 11; if (scene.Name.Contains("_NSW_")) return 11;
else if (scene.Name.Contains("_EW_")) return 12; if (scene.Name.Contains("_EW_")) return 12;
else if (scene.Name.Contains("_NEW_")) return 13; if (scene.Name.Contains("_NEW_")) return 13;
else if (scene.Name.Contains("_SEW_")) return 14; if (scene.Name.Contains("_SEW_")) return 14;
else if (scene.Name.Contains("_NSEW_")) return 15; if (scene.Name.Contains("_NSEW_")) return 15;
else return 0; return 0;
} }
[Command("la", "Allows you to search for a LevelArea.\nUsage: lookup la <pattern>")] [Command("la", "Allows you to search for a LevelArea.\nUsage: lookup la <pattern>")]
@ -1125,19 +1092,17 @@ namespace DiIiS_NA.GameServer.CommandManager
{ {
var matches = new List<Asset>(); var matches = new List<Asset>();
if (@params.Count() < 1) if (!@params.Any())
return "Invalid arguments. Type 'help lookup la' to get help."; return "Invalid arguments. Type 'help lookup la' to get help.";
var pattern = @params[0].ToLower(); var pattern = @params[0].ToLower();
foreach (var pair in MPQStorage.Data.Assets[SNOGroup.LevelArea]) foreach (var pair in MPQStorage.Data.Assets[SNOGroup.LevelArea])
{
if (pair.Value.Name.ToLower().Contains(pattern)) if (pair.Value.Name.ToLower().Contains(pattern))
matches.Add(pair.Value); matches.Add(pair.Value);
}
return matches.Aggregate(matches.Count >= 1 ? "LevelArea Matches:\n" : "No match found.", return matches.Aggregate(matches.Count >= 1 ? "LevelArea Matches:\n" : "No match found.",
(current, match) => current + $"[{match.SNOId.ToString("D6")}] {match.Name}\n"); (current, match) => current + $"[{match.SNOId:D6}] {match.Name}\n");
} }
[Command("sp", "List all Starting Points in world.\nUsage: lookup sp")] [Command("sp", "List all Starting Points in world.\nUsage: lookup sp")]
@ -1155,19 +1120,17 @@ namespace DiIiS_NA.GameServer.CommandManager
{ {
var matches = new List<Asset>(); var matches = new List<Asset>();
if (@params.Count() < 1) if (!@params.Any())
return "Invalid arguments. Type 'help lookup weather' to get help."; return "Invalid arguments. Type 'help lookup weather' to get help.";
var pattern = @params[0].ToLower(); var pattern = @params[0].ToLower();
foreach (var pair in MPQStorage.Data.Assets[SNOGroup.Weather]) foreach (var pair in MPQStorage.Data.Assets[SNOGroup.Weather])
{
if (pair.Value.Name.ToLower().Contains(pattern)) if (pair.Value.Name.ToLower().Contains(pattern))
matches.Add(pair.Value); matches.Add(pair.Value);
}
return matches.Aggregate(matches.Count >= 1 ? "Weather Matches:\n" : "No match found.", return matches.Aggregate(matches.Count >= 1 ? "Weather Matches:\n" : "No match found.",
(current, match) => current + $"[{match.SNOId.ToString("D6")}] {match.Name}\n"); (current, match) => current + $"[{match.SNOId:D6}] {match.Name}\n");
} }
[Command("scene", "Allows you to search for a scene.\nUsage: lookup scene <pattern>")] [Command("scene", "Allows you to search for a scene.\nUsage: lookup scene <pattern>")]
@ -1175,20 +1138,18 @@ namespace DiIiS_NA.GameServer.CommandManager
{ {
var matches = new List<Asset>(); var matches = new List<Asset>();
if (@params.Count() < 1) if (!@params.Any())
return "Invalid arguments. Type 'help lookup scene' to get help."; return "Invalid arguments. Type 'help lookup scene' to get help.";
var pattern = @params[0].ToLower(); var pattern = @params[0].ToLower();
foreach (var pair in MPQStorage.Data.Assets[SNOGroup.Scene]) foreach (var pair in MPQStorage.Data.Assets[SNOGroup.Scene])
{
if (pair.Value.Name.ToLower().Contains(pattern)) if (pair.Value.Name.ToLower().Contains(pattern))
matches.Add(pair.Value); matches.Add(pair.Value);
}
return matches.Aggregate(matches.Count >= 1 ? "Scene Matches:\n" : "No match found.", return matches.Aggregate(matches.Count >= 1 ? "Scene Matches:\n" : "No match found.",
(current, match) => current + (current, match) => current +
$"[{match.SNOId.ToString("D6")}] {match.Name} - {GetExitBits(match)}\n"); $"[{match.SNOId:D6}] {match.Name} - {GetExitBits(match)}\n");
} }
[Command("eg", "Allows you to search for an EffectGroup.\nUsage: lookup eg <pattern>")] [Command("eg", "Allows you to search for an EffectGroup.\nUsage: lookup eg <pattern>")]
@ -1196,20 +1157,18 @@ namespace DiIiS_NA.GameServer.CommandManager
{ {
var matches = new List<Asset>(); var matches = new List<Asset>();
if (@params.Count() < 1) if (!@params.Any())
return "Invalid arguments. Type 'help lookup eg' to get help."; return "Invalid arguments. Type 'help lookup eg' to get help.";
var pattern = @params[0].ToLower(); var pattern = @params[0].ToLower();
foreach (var pair in MPQStorage.Data.Assets[SNOGroup.EffectGroup]) foreach (var pair in MPQStorage.Data.Assets[SNOGroup.EffectGroup])
{
if (pair.Value.Name.ToLower().Contains(pattern)) if (pair.Value.Name.ToLower().Contains(pattern))
matches.Add(pair.Value); matches.Add(pair.Value);
}
return matches.Aggregate(matches.Count >= 1 ? "EffectGroup Matches:\n" : "No match found.", return matches.Aggregate(matches.Count >= 1 ? "EffectGroup Matches:\n" : "No match found.",
(current, match) => current + (current, match) => current +
$"[{match.SNOId.ToString("D6")}] {match.Name} - {GetExitBits(match)}\n"); $"[{match.SNOId:D6}] {match.Name} - {GetExitBits(match)}\n");
} }
[Command("item", "Allows you to search for an item.\nUsage: lookup item <pattern>")] [Command("item", "Allows you to search for an item.\nUsage: lookup item <pattern>")]
@ -1217,7 +1176,7 @@ namespace DiIiS_NA.GameServer.CommandManager
{ {
var matches = new List<ItemTable>(); var matches = new List<ItemTable>();
if (@params.Count() < 1) if (!@params.Any())
return "Invalid arguments. Type 'help lookup item' to get help."; return "Invalid arguments. Type 'help lookup item' to get help.";
var pattern = @params[0].ToLower(); var pattern = @params[0].ToLower();
@ -1228,15 +1187,12 @@ namespace DiIiS_NA.GameServer.CommandManager
if (data == null || data.Type != BalanceType.Items) continue; if (data == null || data.Type != BalanceType.Items) continue;
foreach (var itemDefinition in data.Item) foreach (var itemDefinition in data.Item)
{
if (itemDefinition.Name.ToLower().Contains(pattern)) if (itemDefinition.Name.ToLower().Contains(pattern))
matches.Add(itemDefinition); matches.Add(itemDefinition);
} }
}
return matches.Aggregate(matches.Count >= 1 ? "Item Matches:\n" : "No match found.", return matches.Aggregate(matches.Count >= 1 ? "Item Matches:\n" : "No match found.",
(current, match) => current + $"[{match.SNOActor.ToString("D6")}] {match.Name}\n"); (current, match) => current + $"[{match.SNOActor:D6}] {match.Name}\n");
}
} }
} }
} }

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection;
using DiIiS_NA.Core.Logging; using DiIiS_NA.Core.Logging;
using DiIiS_NA.GameServer.MessageSystem; using DiIiS_NA.GameServer.MessageSystem;
using DiIiS_NA.GameServer.GSSystem.ActorSystem; using DiIiS_NA.GameServer.GSSystem.ActorSystem;
@ -12,7 +13,7 @@ namespace DiIiS_NA.GameServer.Core
{ {
public class InventoryGrid : IRevealable public class InventoryGrid : IRevealable
{ {
static readonly Logger Logger = LogManager.CreateLogger("IG"); static readonly Logger Logger = LogManager.CreateLogger(nameof(InventoryGrid));
public int EquipmentSlot { get; private set; } public int EquipmentSlot { get; private set; }
public int Rows { get { return _backpack.GetLength(0); } } public int Rows { get { return _backpack.GetLength(0); } }
@ -74,7 +75,6 @@ namespace DiIiS_NA.GameServer.Core
} }
return new InventorySize() { Width = 1, Height = 1 }; return new InventorySize() { Width = 1, Height = 1 };
} }
@ -167,7 +167,7 @@ namespace DiIiS_NA.GameServer.Core
foreach (var itm in baseItems) foreach (var itm in baseItems)
have += itm.Attributes[GameAttribute.ItemStackQuantityLo]; have += itm.Attributes[GameAttribute.ItemStackQuantityLo];
Logger.Trace("HaveEnough(): gbid {0}, count {1}", GBid, have); Logger.MethodTrace($"gbid {GBid}, count {have}");
return (have >= count); return (have >= count);
} }

View File

@ -213,7 +213,7 @@ namespace DiIiS_NA.GameServer.GSSystem.AISystem.Brains
{ {
if (PresetPowers.ContainsKey(powerSNO)) if (PresetPowers.ContainsKey(powerSNO))
{ {
// Logger.Debug("AddPresetPower(): power sno {0} already defined for monster \"{1}\"", // Logger.MethodTrace("power sno {0} already defined for monster \"{1}\"",
//powerSNO, this.Body.ActorSNO.Name); //powerSNO, this.Body.ActorSNO.Name);
return; return;
} }

View File

@ -455,7 +455,7 @@ namespace DiIiS_NA.GameServer.GSSystem.AISystem.Brains
if (PresetPowers.ContainsKey(powerSNO)) if (PresetPowers.ContainsKey(powerSNO))
{ {
Logger.Debug($"Monster $[red]$\"{Body.Name}\"$[/]$ already has power {powerSNO}."); Logger.Debug($"Monster $[red]$\"{Body.Name}\"$[/]$ already has power {powerSNO}.");
// Logger.Debug("AddPresetPower(): power sno {0} already defined for monster \"{1}\"", // Logger.MethodTrace("power sno {0} already defined for monster \"{1}\"",
//powerSNO, this.Body.ActorSNO.Name); //powerSNO, this.Body.ActorSNO.Name);
return; return;
} }

View File

@ -118,7 +118,7 @@ namespace DiIiS_NA.GameServer.GSSystem.ActorSystem
/// <summary> /// <summary>
/// Attribute map. /// Attribute map.
/// </summary> /// </summary>
public GameAttributeMap Attributes { get; set; } //TODO: this needs to be "private set", but without errors on speed modifications public GameAttributeMap Attributes { get; }
/// <summary> /// <summary>
/// Affix list. /// Affix list.

View File

@ -41,7 +41,7 @@ namespace DiIiS_NA.GameServer.GSSystem.ActorSystem.Implementations.ScriptObjects
{ {
try try
{ {
(World.FindAt(ActorSno._a3dun_keep_bridge, Position, 60.0f) as Door).Open(); (World.FindActorAt(ActorSno._a3dun_keep_bridge, Position, 60.0f) as Door).Open();
} }
catch { } catch { }
} }

View File

@ -43,12 +43,12 @@ namespace DiIiS_NA.GameServer.GSSystem.ActorSystem.Implementations.ScriptObjects
if (Attributes[GameAttribute.Disabled] == true) return; if (Attributes[GameAttribute.Disabled] == true) return;
try try
{ {
Door waterfall = World.FindAt(ActorSno._caout_oasis_door_aqueduct_a_top, Position, 80.0f) as Door; Door waterfall = World.FindActorAt(ActorSno._caout_oasis_door_aqueduct_a_top, Position, 80.0f) as Door;
if (waterfall == null) if (waterfall == null)
{ {
Door gate = World.FindAt(ActorSno._caout_oasis_door_aqueduct_a, Position, 80.0f) as Door; Door gate = World.FindActorAt(ActorSno._caout_oasis_door_aqueduct_a, Position, 80.0f) as Door;
if (gate == null) if (gate == null)
(World.FindAt(ActorSno._caout_oasis_cenote_door, Position, 80.0f) as Door).Open(); (World.FindActorAt(ActorSno._caout_oasis_cenote_door, Position, 80.0f) as Door).Open();
else else
gate.Open(); gate.Open();
} }

View File

@ -2,6 +2,7 @@
using DiIiS_NA.Core.Logging; using DiIiS_NA.Core.Logging;
using System; using System;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using WatsonTcp; using WatsonTcp;
@ -42,8 +43,8 @@ namespace DiIiS_NA.GameServer.GSSystem.GameSystem
{ {
game.SetAct(int.Parse(args[2].Trim())); game.SetAct(int.Parse(args[2].Trim()));
game.SetGameMode((Game.Mode)int.Parse(args[7].Trim())); game.SetGameMode((Game.Mode)int.Parse(args[7].Trim()));
game.IsHardcore = (args[6].Trim() == "True" ? true : false); game.IsHardcore = args[6].Trim() == "True" ? true : false;
game.IsSeasoned = (args[8].Trim() == "True" ? true : false); game.IsSeasoned = args[8].Trim() == "True" ? true : false;
game.SetDifficulty(int.Parse(args[3].Trim())); game.SetDifficulty(int.Parse(args[3].Trim()));
if (game.GameMode != Game.Mode.Portals) if (game.GameMode != Game.Mode.Portals)
game.SetQuestProgress(int.Parse(args[4].Trim()), int.Parse(args[5].Trim())); game.SetQuestProgress(int.Parse(args[4].Trim()), int.Parse(args[5].Trim()));
@ -95,136 +96,134 @@ namespace DiIiS_NA.GameServer.GSSystem.GameSystem
private bool SenderServerDisconnected() private bool SenderServerDisconnected()
{ {
Logger.Warn("MooNetServer was disconnected!"); Logger.Warn("Blizznet was disconnected!");
return true; return true;
} }
public void RegisterGameServer(string ip, int port) public void RegisterGameServer(string ip, int port)
{ {
Logger.Debug("RegisterGameServer(): ip {0}, port {1}", ip, port); Logger.MethodTrace($"ip {ip}, port {port}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"rngsr|{ip}/{port}")); BattleNetSocketSend($"rngsr|{ip}/{port}");
} }
public void RegisterPvPGameServer(string ip, int port) public void RegisterPvPGameServer(string ip, int port)
{ {
Logger.Debug("RegisterPvPGameServer(): ip {0}, port {1}", ip, port); Logger.MethodTrace($"ip {ip}, port {port}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"rnpvpgsr|{ip}/{port}")); BattleNetSocketSend($"rnpvpgsr|{ip}/{port}");
} }
public void GrantAchievement(ulong gameAccountId, ulong achievementId) public void GrantAchievement(ulong gameAccountId, ulong achievementId)
{ {
Logger.Debug("GrantAchievement(): gameAccountId {0}, achievementId {1}", gameAccountId, achievementId); Logger.MethodTrace($"gameAccountId {gameAccountId}, achievementId {achievementId}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"grachi|{gameAccountId}/{achievementId}")); BattleNetSocketSend($"grachi|{gameAccountId}/{achievementId}");
} }
public void GrantCriteria(ulong gameAccountId, ulong criteriaId) public void GrantCriteria(ulong gameAccountId, ulong criteriaId)
{ {
Logger.Debug("GrantCriteria(): gameAccountId {0}, criteriaId {1}", gameAccountId, criteriaId); Logger.MethodTrace($"gameAccountId {gameAccountId}, achievementId {criteriaId}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"gcrit|{gameAccountId}/{criteriaId}")); BattleNetSocketSend($"gcrit|{gameAccountId}/{criteriaId}");
} }
public void UpdateAchievementCounter(ulong gameAccountId, int type, uint addCounter, int comparand, ulong achievement = 0) public void UpdateAchievementCounter(ulong gameAccountId, int type, uint addCounter, int comparand, ulong achievement = 0)
{ {
Logger.Debug("UpdateAchievementCounter(): type {0}, addCounter {1}, comparand {2}", type, addCounter, comparand); Logger.MethodTrace($"type {type}, addCounter {addCounter}, comparand {comparand}");
BattleNetSocketSend(Encoding.UTF8.GetBytes( BattleNetSocketSend($"uoacce|{gameAccountId}/{type}/{addCounter}/{comparand}/{achievement}");
$"uoacce|{gameAccountId}/{type}/{addCounter}/{comparand}/{achievement}"));
} }
public void UpdateSingleAchievementCounter(ulong gameAccountId, ulong achId, uint addCounter) public void UpdateSingleAchievementCounter(ulong gameAccountId, ulong achId, uint addCounter)
{ {
Logger.Debug("UpdateSingleAchievementCounter(): type {0}, addCounter {1}", achId, addCounter); Logger.MethodTrace($"type {achId}, addCounter {addCounter}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"upsnaccr|{gameAccountId}/{achId}/{addCounter}")); BattleNetSocketSend($"upsnaccr|{gameAccountId}/{achId}/{addCounter}");
} }
public void UpdateQuantity(ulong gameAccountId, ulong achievementId, uint addCounter) public void UpdateQuantity(ulong gameAccountId, ulong achievementId, uint addCounter)
{ {
Logger.Debug("UpdateQuantity(): achievementId {0}, addCounter {1}", achievementId, addCounter); Logger.MethodTrace($"achievementId {achievementId}, addCounter {addCounter}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"upequt|{gameAccountId}/{achievementId}/{addCounter}")); BattleNetSocketSend($"upequt|{gameAccountId}/{achievementId}/{addCounter}");
} }
public void CheckQuestCriteria(ulong gameAccountId, int questId, bool isCoop) public void CheckQuestCriteria(ulong gameAccountId, int questId, bool isCoop)
{ {
Logger.Debug("CheckQuestCriteria(): gameAccountId {0}, questId {1}, coop {2}", gameAccountId, questId, isCoop); Logger.MethodTrace($"gameAccountId {gameAccountId}, questId {questId}, coop {isCoop}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"cqc|{gameAccountId}/{questId}/{(isCoop ? "True" : "False")}")); BattleNetSocketSend($"cqc|{gameAccountId}/{questId}/{(isCoop ? "True" : "False")}");
} }
public void CheckKillMonsterCriteria(ulong gameAccountId, int actorId, int type, bool isHardcore) public void CheckKillMonsterCriteria(ulong gameAccountId, int actorId, int type, bool isHardcore)
{ {
Logger.Debug("CheckKillMonsterCriteria(): gameAccountId {0}, actorId {1}, type {2}, hc {3}", gameAccountId, actorId, type, isHardcore); Logger.MethodTrace($"gameAccountId {gameAccountId}, actorId {actorId}, type {type}, hc {isHardcore}");
BattleNetSocketSend(Encoding.UTF8.GetBytes( BattleNetSocketSend($"ckmc|{gameAccountId}/{actorId}/{type}/{ (isHardcore ? "True" : "False")}");
$"ckmc|{gameAccountId}/{actorId}/{type}/{(isHardcore ? "True" : "False")}"));
} }
public void CheckSalvageItemCriteria(ulong gameAccountId, int itemId) public void CheckSalvageItemCriteria(ulong gameAccountId, int itemId)
{ {
Logger.Debug("CheckSalvageItemCriteria(): gameAccountId {0}, itemId {1}", gameAccountId, itemId); Logger.MethodTrace($"gameAccountId {gameAccountId}, itemId {itemId}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"csic|{gameAccountId}/{itemId}")); BattleNetSocketSend($"csic|{gameAccountId}/{itemId}");
} }
public void CheckLevelCap(ulong gameAccountId) public void CheckLevelCap(ulong gameAccountId)
{ {
Logger.Debug("CheckLevelCap(): gameAccountId {0}", gameAccountId); Logger.MethodTrace($"gameAccountId {gameAccountId}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"clc|{gameAccountId}")); BattleNetSocketSend($"clc|{gameAccountId}");
} }
public void CheckConversationCriteria(ulong gameAccountId, int convId) public void CheckConversationCriteria(ulong gameAccountId, int convId)
{ {
Logger.Debug("CheckConversationCriteria(): gameAccountId {0}, convId {1}", gameAccountId, convId); Logger.MethodTrace($"gameAccountId {gameAccountId}, convId {convId}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"ccc|{gameAccountId}/{convId}")); BattleNetSocketSend($"ccc|{gameAccountId}/{convId}");
} }
public void CheckLevelAreaCriteria(ulong gameAccountId, int laId) public void CheckLevelAreaCriteria(ulong gameAccountId, int laId)
{ {
Logger.Debug("CheckLevelAreaCriteria(): gameAccountId {0}, laId {1}", gameAccountId, laId); Logger.MethodTrace($"gameAccountId {gameAccountId}, laId {laId}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"clac|{gameAccountId}/{laId}")); BattleNetSocketSend($"clac|{gameAccountId}/{laId}");
} }
public void UpdateClient(ulong gameAccountId, int level, int screen) public void UpdateClient(ulong gameAccountId, int level, int screen)
{ {
Logger.Debug("UpdateClient(): gameAccountId {0}", gameAccountId); Logger.MethodTrace($"gameAccountId {gameAccountId}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"uc|{gameAccountId}/{level}/{screen}")); BattleNetSocketSend($"uc|{gameAccountId}/{level}/{screen}");
} }
public void PlayerJoined(int gameId) public void PlayerJoined(int gameId)
{ {
Logger.Debug("PlayerJoined(): gameId {0}", gameId); Logger.MethodTrace($"gameId {gameId}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"gpj|{gameId}")); BattleNetSocketSend($"gpj|{gameId}");
} }
public void PlayerLeft(int gameId) public void PlayerLeft(int gameId)
{ {
Logger.Debug("PlayerLeft(): gameId {0}", gameId); Logger.MethodTrace($"gameId {gameId}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"gpl|{gameId}")); BattleNetSocketSend($"gpl|{gameId}");
} }
public void SetGamePublic(int gameId) public void SetGamePublic(int gameId)
{ {
Logger.Debug("SetGamePublic(): gameId {0}", gameId); Logger.MethodTrace($"gameId {gameId}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"gsp|{gameId}")); BattleNetSocketSend($"gsp|{gameId}");
} }
public void PvPSaveProgress(ulong gameAccountId, int kills, int wins, int gold) public void PvPSaveProgress(ulong gameAccountId, int kills, int wins, int gold)
{ {
Logger.Debug("PvPSaveProgress(): gameAccountId {0}", gameAccountId); Logger.MethodTrace($"game account id {gameAccountId}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"pvpsp|{gameAccountId}/{kills}/{wins}/{gold}")); BattleNetSocketSend($"pvpsp|{gameAccountId}/{kills}/{wins}/{gold}");
} }
public void ParagonLevelUp(ulong gameAccountId) public void ParagonLevelUp(ulong gameAccountId)
{ {
Logger.Debug("ParagonLevelUp(): gameAccountId {0}", gameAccountId); Logger.MethodTrace($"game account id {gameAccountId}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"plu|{gameAccountId}")); BattleNetSocketSend($"plu|{gameAccountId}");
} }
public void ToonStateChanged(ulong toonId) public void ToonStateChanged(ulong toonId)
{ {
Logger.Debug("ToonStateChanged(): toonID {0}", toonId); Logger.MethodTrace($"game account id {toonId}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"tsc|{toonId}")); BattleNetSocketSend($"tsc|{toonId}");
} }
public void UniqueItemIdentified(ulong gameAccountId, ulong itemId) public void UniqueItemIdentified(ulong gameAccountId, ulong itemId)
{ {
Logger.Debug("UniqueItemIdentified(): gameAccountId {0}, itemId {1}", gameAccountId, itemId); Logger.MethodTrace($"gameAccountId {gameAccountId}, itemId {itemId}");
BattleNetSocketSend(Encoding.UTF8.GetBytes($"uii|{gameAccountId}/{itemId}")); BattleNetSocketSend($"uii|{gameAccountId}/{itemId}");
} }
} }
} }

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection;
using DiIiS_NA.Core.Extensions; using DiIiS_NA.Core.Extensions;
using DiIiS_NA.Core.Helpers.Hash; using DiIiS_NA.Core.Helpers.Hash;
using DiIiS_NA.Core.Helpers.Math; using DiIiS_NA.Core.Helpers.Math;
@ -25,18 +26,18 @@ namespace DiIiS_NA.D3_GameServer.GSSystem.GameSystem
{ {
public class QuestManager public class QuestManager
{ {
private static readonly Logger Logger = new Logger("QuestManager"); private static readonly Logger Logger = new(nameof(QuestManager));
/// <summary> /// <summary>
/// Accessor for quests /// Accessor for quests
/// </summary> /// </summary>
/// <param name="snoQuest">snoId of the quest to retrieve</param> /// <param name="snoQuest">snoId of the quest to retrieve</param>
/// <returns></returns> /// <returns></returns>
public Dictionary<int, QuestRegistry.Quest> Quests = new Dictionary<int, QuestRegistry.Quest>(); public readonly Dictionary<int, QuestRegistry.Quest> Quests = new();
public Dictionary<int, QuestRegistry.Quest> SideQuests = new Dictionary<int, QuestRegistry.Quest>(); public readonly Dictionary<int, QuestRegistry.Quest> SideQuests = new();
public List<Bounty> Bounties = new List<Bounty>(); public readonly List<Bounty> Bounties = new();
public Game Game { get; set; } public Game Game { get; set; }
@ -190,7 +191,7 @@ namespace DiIiS_NA.D3_GameServer.GSSystem.GameSystem
if (!Game.Empty) if (!Game.Empty)
{ {
SaveQuestProgress(true); SaveQuestProgress(true);
Logger.Trace(" (Advance) quest {0} completed: {1}", Game.CurrentQuest, Quests[Game.CurrentQuest].Completed); Logger.Trace($"$[white]$(Advance)$[/]$ Game {Game.GameId} Advanced to quest $[underline white]${Game.CurrentQuest}$[/], completed $[underline white]${Quests[Game.CurrentQuest].Completed}$[/]$");
foreach (var player in Game.Players.Values) foreach (var player in Game.Players.Values)
{ {
int xpReward = (int)(Quests[Game.CurrentQuest].RewardXp * Game.XPModifier); int xpReward = (int)(Quests[Game.CurrentQuest].RewardXp * Game.XPModifier);
@ -268,7 +269,7 @@ namespace DiIiS_NA.D3_GameServer.GSSystem.GameSystem
} }
OnQuestProgress(); OnQuestProgress();
AutoSetQuestMarker(); AutoSetQuestMarker();
Logger.Trace(" (Advance) Advanced to quest {0}, step {1}", Game.CurrentQuest, Game.CurrentStep); Logger.Trace($"$[white]$(Advance)$[/]$ Game {Game.GameId} Advanced to quest $[underline white]${Game.CurrentQuest}$[/], step $[underline white]${Game.CurrentStep}$[/]$");
} }
public void SideAdvance() public void SideAdvance()
@ -294,7 +295,7 @@ namespace DiIiS_NA.D3_GameServer.GSSystem.GameSystem
SideQuests[Game.CurrentSideQuest].Steps[Game.CurrentSideStep] == SideQuests[Game.CurrentSideQuest].Steps.Last().Value) SideQuests[Game.CurrentSideQuest].Steps[Game.CurrentSideStep] == SideQuests[Game.CurrentSideQuest].Steps.Last().Value)
{ {
SideQuests[Game.CurrentSideQuest].Completed = true; SideQuests[Game.CurrentSideQuest].Completed = true;
Logger.Trace(" (SideAdvance) quest {0} completed: {1}", Game.CurrentSideQuest, SideQuests[Game.CurrentSideQuest].Completed); Logger.Trace($"$[white]$(Side-Advance)$[/]$ Game {Game.GameId} Side-Advanced to quest {Game.CurrentSideQuest} completed: {SideQuests[Game.CurrentSideQuest].Completed}");
foreach (var player in Game.Players.Values) foreach (var player in Game.Players.Values)
{ {
@ -338,7 +339,7 @@ namespace DiIiS_NA.D3_GameServer.GSSystem.GameSystem
} }
OnQuestProgress(); OnQuestProgress();
Logger.Trace(" (SideAdvance) Advanced to side quest {0}, step {1}", Game.CurrentSideQuest, Game.CurrentSideStep); Logger.Trace($"$[white]$(Side-Advance)$[/]$ Game {Game.GameId} Side-Advanced to side-quest {Game.CurrentSideQuest} completed: {Game.CurrentSideStep}");
} }
public void LaunchSideQuest(int questId, bool forceAbandon = false) public void LaunchSideQuest(int questId, bool forceAbandon = false)
@ -539,7 +540,7 @@ namespace DiIiS_NA.D3_GameServer.GSSystem.GameSystem
{ {
if (Game.QuestProgress.QuestTriggers.Count == 1) if (Game.QuestProgress.QuestTriggers.Count == 1)
{ {
Logger.MethodTrace($"AutoSetQuestMarker() - {Game.QuestProgress.QuestTriggers.Count} triggers found"); Logger.MethodTrace($"{Game.QuestProgress.QuestTriggers.Count} triggers found");
var trigger = Game.QuestProgress.QuestTriggers.First(); var trigger = Game.QuestProgress.QuestTriggers.First();
if (trigger.Value.triggerType == QuestStepObjectiveType.InteractWithActor) if (trigger.Value.triggerType == QuestStepObjectiveType.InteractWithActor)
foreach (var world in Game.Worlds) foreach (var world in Game.Worlds)
@ -854,7 +855,7 @@ namespace DiIiS_NA.D3_GameServer.GSSystem.GameSystem
public List<int> LevelAreaChecks { get; set; } public List<int> LevelAreaChecks { get; set; }
public bool Finished = false; public bool Finished = false;
public static Dictionary<int, int> LevelAreaOverrides = new Dictionary<int, int>() //first is in-game, second is in-data public static Dictionary<int, int> LevelAreaOverrides = new() //first is in-game, second is in-data
{ {
{338602, 377700}, //battlefields of eterntity {338602, 377700}, //battlefields of eterntity
{271234, 370512}, //x1 fortress lv1 {271234, 370512}, //x1 fortress lv1

View File

@ -2,6 +2,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection;
using DiIiS_NA.Core.Logging; using DiIiS_NA.Core.Logging;
using DiIiS_NA.Core.Helpers.Math; using DiIiS_NA.Core.Helpers.Math;
using DiIiS_NA.Core.Storage.AccountDataBase.Entities; using DiIiS_NA.Core.Storage.AccountDataBase.Entities;
@ -1330,7 +1331,7 @@ namespace DiIiS_NA.GameServer.GSSystem.ItemsSystem
return; return;
} }
Logger.Warn("OnRequestUse(): gbid {0} not implemented", GBHandle.GBID); Logger.MethodTrace($"gbid {GBHandle.GBID} not implemented");
} }
private void SwitchWingsBuff(Player player, int powerId) private void SwitchWingsBuff(Player player, int powerId)

View File

@ -1,5 +1,14 @@
using DiIiS_NA.Core.Helpers.Math; using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using DiIiS_NA.Core.Helpers.Hash;
using DiIiS_NA.Core.Helpers.Math;
using DiIiS_NA.Core.Logging; using DiIiS_NA.Core.Logging;
using DiIiS_NA.Core.MPQ;
using DiIiS_NA.Core.MPQ.FileFormats;
using DiIiS_NA.D3_GameServer.Core.Types.SNO; using DiIiS_NA.D3_GameServer.Core.Types.SNO;
using DiIiS_NA.GameServer.Core.Types.Math; using DiIiS_NA.GameServer.Core.Types.Math;
using DiIiS_NA.GameServer.Core.Types.QuadTrees; using DiIiS_NA.GameServer.Core.Types.QuadTrees;
@ -7,27 +16,22 @@ using DiIiS_NA.GameServer.Core.Types.SNO;
using DiIiS_NA.GameServer.Core.Types.TagMap; using DiIiS_NA.GameServer.Core.Types.TagMap;
using DiIiS_NA.GameServer.GSSystem.ActorSystem; using DiIiS_NA.GameServer.GSSystem.ActorSystem;
using DiIiS_NA.GameServer.GSSystem.ActorSystem.Implementations; using DiIiS_NA.GameServer.GSSystem.ActorSystem.Implementations;
using DiIiS_NA.GameServer.GSSystem.ActorSystem.Movement;
using DiIiS_NA.GameServer.GSSystem.GameSystem; using DiIiS_NA.GameServer.GSSystem.GameSystem;
using DiIiS_NA.GameServer.GSSystem.ItemsSystem; using DiIiS_NA.GameServer.GSSystem.ItemsSystem;
using DiIiS_NA.GameServer.GSSystem.ObjectsSystem; using DiIiS_NA.GameServer.GSSystem.ObjectsSystem;
using DiIiS_NA.GameServer.GSSystem.PlayerSystem; using DiIiS_NA.GameServer.GSSystem.PlayerSystem;
using DiIiS_NA.GameServer.GSSystem.PowerSystem; using DiIiS_NA.GameServer.GSSystem.PowerSystem;
using DiIiS_NA.GameServer.MessageSystem; using DiIiS_NA.GameServer.MessageSystem;
using DiIiS_NA.GameServer.MessageSystem.Message.Definitions.ACD;
using DiIiS_NA.GameServer.MessageSystem.Message.Definitions.Animation; using DiIiS_NA.GameServer.MessageSystem.Message.Definitions.Animation;
using DiIiS_NA.GameServer.MessageSystem.Message.Definitions.Misc; using DiIiS_NA.GameServer.MessageSystem.Message.Definitions.Misc;
using DiIiS_NA.GameServer.MessageSystem.Message.Definitions.World; using DiIiS_NA.GameServer.MessageSystem.Message.Definitions.World;
using DiIiS_NA.GameServer.MessageSystem.Message.Fields; using DiIiS_NA.GameServer.MessageSystem.Message.Fields;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DiIiS_NA.Core.MPQ.FileFormats;
using DiIiS_NA.LoginServer.Toons; using DiIiS_NA.LoginServer.Toons;
using Actor = DiIiS_NA.GameServer.GSSystem.ActorSystem.Actor; using Actor = DiIiS_NA.GameServer.GSSystem.ActorSystem.Actor;
using Circle = DiIiS_NA.GameServer.Core.Types.Misc.Circle; using Circle = DiIiS_NA.GameServer.Core.Types.Misc.Circle;
using Environment = DiIiS_NA.Core.MPQ.FileFormats.Environment;
using Monster = DiIiS_NA.GameServer.GSSystem.ActorSystem.Monster; using Monster = DiIiS_NA.GameServer.GSSystem.ActorSystem.Monster;
using ResolvedPortalDestination = DiIiS_NA.GameServer.MessageSystem.Message.Fields.ResolvedPortalDestination; using ResolvedPortalDestination = DiIiS_NA.GameServer.MessageSystem.Message.Fields.ResolvedPortalDestination;
@ -36,8 +40,8 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
public sealed class World : DynamicObject, IRevealable, IUpdateable public sealed class World : DynamicObject, IRevealable, IUpdateable
{ {
static readonly Logger Logger = LogManager.CreateLogger(); static readonly Logger Logger = LogManager.CreateLogger();
public readonly Dictionary<World, List<Item>> DbItems = new Dictionary<World, List<Item>>(); //we need this list to delete item_instances from items which have no owner anymore. public readonly Dictionary<World, List<Item>> DbItems = new(); //we need this list to delete item_instances from items which have no owner anymore.
public readonly Dictionary<ulong, Item> CachedItems = new Dictionary<ulong, Item>(); public readonly Dictionary<ulong, Item> CachedItems = new();
public int LastCEId = 3000; public int LastCEId = 3000;
@ -52,30 +56,24 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
/// SNOHandle for the world. /// SNOHandle for the world.
/// </summary> /// </summary>
public SNOHandle WorldSNO { get; private set; } public SNOHandle WorldSNO { get; private set; }
public WorldSno SNO public WorldSno SNO => (WorldSno)WorldSNO.Id;
{
get { return (WorldSno)WorldSNO.Id; }
}
/// <summary> /// <summary>
/// QuadTree that contains scenes & actors. /// QuadTree that contains scenes & actors.
/// </summary> /// </summary>
private QuadTree _quadTree; private QuadTree _quadTree;
public static QuadTree _PvPQuadTree = new QuadTree(new Size(60, 60), 0); public static QuadTree _PvPQuadTree = new(new Size(60, 60), 0);
public QuadTree QuadTree public QuadTree QuadTree
{ {
get get => (IsPvP ? _PvPQuadTree : _quadTree);
{
return (IsPvP ? _PvPQuadTree : _quadTree);
}
set { } set { }
} }
/// <summary> /// <summary>
/// WorldData loaded from MPQs/DB /// WorldData loaded from MPQs/DB
/// </summary> /// </summary>
public DiIiS_NA.Core.MPQ.FileFormats.World worldData = new DiIiS_NA.Core.MPQ.FileFormats.World(); public DiIiS_NA.Core.MPQ.FileFormats.World worldData = new();
/// <summary> /// <summary>
/// Destination for portals(on Exit and DungeonStone) /// Destination for portals(on Exit and DungeonStone)
@ -92,14 +90,11 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
/// </summary> /// </summary>
private readonly ConcurrentDictionary<uint, Scene> _scenes; private readonly ConcurrentDictionary<uint, Scene> _scenes;
private static readonly ConcurrentDictionary<uint, Scene> _PvPscenes = new ConcurrentDictionary<uint, Scene>(); private static readonly ConcurrentDictionary<uint, Scene> _PvPscenes = new();
public ConcurrentDictionary<uint, Scene> Scenes public ConcurrentDictionary<uint, Scene> Scenes
{ {
get get => (IsPvP ? _PvPscenes : _scenes);
{
return (IsPvP ? _PvPscenes : _scenes);
}
set { } set { }
} }
@ -108,46 +103,36 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
/// </summary> /// </summary>
private readonly ConcurrentDictionary<uint, Actor> _actors; private readonly ConcurrentDictionary<uint, Actor> _actors;
public static readonly ConcurrentDictionary<uint, Actor> _PvPActors = new ConcurrentDictionary<uint, Actor>(); public static readonly ConcurrentDictionary<uint, Actor> _PvPActors = new();
public ConcurrentDictionary<uint, Actor> Actors public ConcurrentDictionary<uint, Actor> Actors
{ {
get get => (IsPvP ? _PvPActors : _actors);
{
return (IsPvP ? _PvPActors : _actors);
}
set { } set { }
} }
public Dictionary<int, WorldSno> PortalOverrides = new Dictionary<int, WorldSno>(); public Dictionary<int, WorldSno> PortalOverrides = new();
/// <summary> /// <summary>
/// List of players contained in the world. /// List of players contained in the world.
/// </summary> /// </summary>
private readonly ConcurrentDictionary<uint, Player> _players; private readonly ConcurrentDictionary<uint, Player> _players;
public static readonly ConcurrentDictionary<uint, Player> _PvPPlayers = new ConcurrentDictionary<uint, Player>(); public static readonly ConcurrentDictionary<uint, Player> _PvPPlayers = new();
public ConcurrentDictionary<uint, Player> Players public ConcurrentDictionary<uint, Player> Players => (IsPvP ? _PvPPlayers : _players);
{
get
{
return (IsPvP ? _PvPPlayers : _players);
}
set { }
}
/// <summary> /// <summary>
/// Returns true if the world has players in. /// Returns true if the world has players in.
/// </summary> /// </summary>
public bool HasPlayersIn { get { return Players.Count > 0; } } public bool HasPlayersIn => Players.Count > 0;
/// <summary> /// <summary>
/// Returns a new dynamicId for scenes. /// Returns a new dynamicId for scenes.
/// </summary> /// </summary>
public uint NewSceneID { get { return IsPvP ? NewPvPSceneID : Game.NewSceneID; } } public uint NewSceneID => IsPvP ? NewPvPSceneID : Game.NewSceneID;
public bool IsPvP { get { return SNO == WorldSno.pvp_duel_small_multi; } } //PvP_Duel_Small public bool IsPvP => SNO == WorldSno.pvp_duel_small_multi; //PvP_Duel_Small
public static bool PvPMapLoaded = false; public static bool PvPMapLoaded = false;
@ -164,21 +149,15 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
} }
// Environment // Environment
public DiIiS_NA.Core.MPQ.FileFormats.Environment Environment public Environment Environment => ((DiIiS_NA.Core.MPQ.FileFormats.World)MPQStorage.Data.Assets[SNOGroup.Worlds][WorldSNO.Id].Data).Environment;
{
get
{
return ((DiIiS_NA.Core.MPQ.FileFormats.World)DiIiS_NA.Core.MPQ.MPQStorage.Data.Assets[SNOGroup.Worlds][WorldSNO.Id].Data).Environment;
}
}
private static uint _lastPvPObjectID = 10001; private static uint _lastPvPObjectID = 10001;
private static object obj = new object(); private static readonly object _obj = new();
public static uint NewActorPvPID public static uint NewActorPvPID
{ {
get get
{ {
lock (obj) lock (_obj)
{ {
_lastPvPObjectID++; _lastPvPObjectID++;
return _lastPvPObjectID; return _lastPvPObjectID;
@ -191,7 +170,7 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
{ {
get get
{ {
lock (obj) lock (_obj)
{ {
_lastPvPSceneID++; _lastPvPSceneID++;
return _lastPvPSceneID; return _lastPvPSceneID;
@ -218,14 +197,14 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
} }
private PowerManager _powerManager; private PowerManager _powerManager;
public static PowerManager _PvPPowerManager = new PowerManager(); public static PowerManager _PvPPowerManager = new();
public PowerManager PowerManager { get { return IsPvP ? _PvPPowerManager : _powerManager; } } public PowerManager PowerManager => IsPvP ? _PvPPowerManager : _powerManager;
private BuffManager _buffManager; private BuffManager _buffManager;
public static BuffManager _PvPBuffManager = new BuffManager(); public static BuffManager _PvPBuffManager = new();
public BuffManager BuffManager { get { return IsPvP ? _PvPBuffManager : _buffManager; } } public BuffManager BuffManager => IsPvP ? _PvPBuffManager : _buffManager;
/// <summary> /// <summary>
/// Creates a new world for the given game with given snoId. /// Creates a new world for the given game with given snoId.
@ -257,8 +236,8 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
if (SNO == WorldSno.x1_bog_01) //Blood Marsh if (SNO == WorldSno.x1_bog_01) //Blood Marsh
{ {
var worlds = new List<WorldSno>() { WorldSno.x1_catacombs_level01, WorldSno.x1_catacombs_fakeentrance_02, WorldSno.x1_catacombs_fakeentrance_03, WorldSno.x1_catacombs_fakeentrance_04 }; var worlds = new List<WorldSno> { WorldSno.x1_catacombs_level01, WorldSno.x1_catacombs_fakeentrance_02, WorldSno.x1_catacombs_fakeentrance_03, WorldSno.x1_catacombs_fakeentrance_04 };
var scenes = new List<int>() { 265624, 265655, 265678, 265693 }; var scenes = new List<int> { 265624, 265655, 265678, 265693 };
foreach (var scene in scenes) foreach (var scene in scenes)
{ {
var wld = worlds[FastRandom.Instance.Next(worlds.Count)]; var wld = worlds[FastRandom.Instance.Next(worlds.Count)];
@ -283,17 +262,17 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
{ {
foreach (var actor in player.GetActorsInRange().OfType<IUpdateable>()) // get IUpdateable actors in range. foreach (var actor in player.GetActorsInRange().OfType<IUpdateable>()) // get IUpdateable actors in range.
{ {
if (actorsToUpdate.Contains(actor as IUpdateable)) // don't let a single actor in range of more than players to get updated more thance per tick /raist. if (actorsToUpdate.Contains(actor)) // don't let a single actor in range of more than players to get updated more thance per tick /raist.
continue; continue;
actorsToUpdate.Add(actor as IUpdateable); actorsToUpdate.Add(actor);
} }
} }
foreach (var minion in Actors.Values.OfType<Minion>()) foreach (var minion in Actors.Values.OfType<Minion>())
{ {
if (actorsToUpdate.Contains(minion as IUpdateable)) if (actorsToUpdate.Contains(minion))
continue; continue;
actorsToUpdate.Add(minion as IUpdateable); actorsToUpdate.Add(minion);
} }
foreach (var actor in actorsToUpdate) // trigger the updates. foreach (var actor in actorsToUpdate) // trigger the updates.
{ {
@ -313,6 +292,49 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
#region message broadcasting #region message broadcasting
/// <summary>
/// Broadcasts a message to all players in the world.
/// </summary>
/// <param name="action">The action that will be invoked to all players</param>
/// <exception cref="Exception">If there was an error to broadcast to player.</exception>
public void BroadcastOperation(Action<Player> action)
{
foreach (var player in Players.Values)
{
if (player == null) continue;
try
{
action(player);
}
catch (Exception ex)
{
throw new Exception("Error while broadcasting to player " + player.Name, ex);
}
}
}
/// <summary>
/// Broadcasts a message to all players in the world where the <param name="predicate"></param> is true.
/// </summary>
/// <param name="predicate">Players matching criteria</param>
/// <param name="action">The action that will be invoked to all players</param>
/// <exception cref="Exception">If there was an error to broadcast to player</exception>
public void BroadcastOperation(Func<Player, bool> predicate, Action<Player> action)
{
foreach (var player in Players.Values.Where(predicate))
{
if (player == null) continue;
try
{
action(player);
}
catch (Exception ex)
{
throw new Exception("Error while broadcasting to player " + player.Name, ex);
}
}
}
// NOTE: Scenes are actually laid out in cells with Subscenes filling in certain areas under a Scene. // NOTE: Scenes are actually laid out in cells with Subscenes filling in certain areas under a Scene.
// We can use this design feature to track Actors' current scene and send updates to it and neighboring // We can use this design feature to track Actors' current scene and send updates to it and neighboring
// scenes instead of distance checking for broadcasting messages. / komiga // scenes instead of distance checking for broadcasting messages. / komiga
@ -325,11 +347,7 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
/// <param name="actor">The actor.</param> /// <param name="actor">The actor.</param>
public void BroadcastIfRevealed(Func<Player, GameMessage> message, Actor actor) public void BroadcastIfRevealed(Func<Player, GameMessage> message, Actor actor)
{ {
foreach (var player in Players.Values) BroadcastOperation(player => player.RevealedObjects.ContainsKey(actor.GlobalID), player => player.InGameClient.SendMessage(message(player)));
{
if (player.RevealedObjects.ContainsKey(actor.GlobalID))
player.InGameClient.SendMessage(message(player));
}
} }
/// <summary> /// <summary>
@ -338,10 +356,7 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
/// <param name="message"></param> /// <param name="message"></param>
public void BroadcastGlobal(Func<Player, GameMessage> message) public void BroadcastGlobal(Func<Player, GameMessage> message)
{ {
foreach (var player in Players.Values) BroadcastOperation(player => player.InGameClient.SendMessage(message(player)));
{
player.InGameClient.SendMessage(message(player));
}
} }
/// <summary> /// <summary>
@ -349,9 +364,9 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
/// </summary> /// </summary>
/// <param name="message">The message to broadcast.</param> /// <param name="message">The message to broadcast.</param>
/// <param name="actor">The actor.</param> /// <param name="actor">The actor.</param>
public void BroadcastInclusive(Func<Player, GameMessage> message, Actor actor) public void BroadcastInclusive(Func<Player, GameMessage> message, Actor actor, float? radius = null)
{ {
var players = actor.GetPlayersInRange(); var players = actor.GetPlayersInRange(radius);
foreach (var player in players) foreach (var player in players)
{ {
player.InGameClient.SendMessage(message(player)); player.InGameClient.SendMessage(message(player));
@ -404,12 +419,12 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
WorldSizeInFeetY = 5040, WorldSizeInFeetY = 5040,
snoDungeonFinderSourceWorld = -1 snoDungeonFinderSourceWorld = -1
}); });
player.InGameClient.SendMessage(new WorldStatusMessage() { WorldID = GlobalID, Field1 = false }); player.InGameClient.SendMessage(new WorldStatusMessage { WorldID = GlobalID, Field1 = false });
//* //*
player.InGameClient.SendMessage(new WorldSyncedDataMessage() player.InGameClient.SendMessage(new WorldSyncedDataMessage
{ {
WorldID = GlobalID, WorldID = GlobalID,
SyncedData = new WorldSyncedData() SyncedData = new WorldSyncedData
{ {
SnoWeatherOverride = -1, SnoWeatherOverride = -1,
WeatherIntensityOverride = 0, WeatherIntensityOverride = 0,
@ -436,7 +451,7 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
foreach (var scene in Scenes.Values) scene.Unreveal(player); foreach (var scene in Scenes.Values) scene.Unreveal(player);
player.RevealedObjects.Remove(GlobalID); player.RevealedObjects.Remove(GlobalID);
player.InGameClient.SendMessage(new WorldStatusMessage() { WorldID = GlobalID, Field1 = true }); player.InGameClient.SendMessage(new WorldStatusMessage { WorldID = GlobalID, Field1 = true });
player.InGameClient.SendMessage(new PrefetchDataMessage(Opcodes.PrefetchWorldMessage) { SNO = WorldSNO.Id }); player.InGameClient.SendMessage(new PrefetchDataMessage(Opcodes.PrefetchWorldMessage) { SNO = WorldSNO.Id });
//player.InGameClient.SendMessage(new WorldDeletedMessage() { WorldID = this.GlobalID }); //player.InGameClient.SendMessage(new WorldDeletedMessage() { WorldID = this.GlobalID });
@ -560,7 +575,7 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
UnitAniimStartTime = 0, UnitAniimStartTime = 0,
tAnim = new PlayAnimationMessageSpec[] tAnim = new PlayAnimationMessageSpec[]
{ {
new PlayAnimationMessageSpec() new()
{ {
Duration = 150, Duration = 150,
AnimationSNO = monster.AnimationSet.TagMapAnimDefault[animationTag], AnimationSNO = monster.AnimationSet.TagMapAnimDefault[animationTag],
@ -576,7 +591,7 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
return monster; return monster;
} }
private Queue<Queue<Action>> _flippyTimers = new Queue<Queue<Action>>(); private Queue<Queue<Action>> _flippyTimers = new();
private const int FlippyDurationInTicks = 10; private const int FlippyDurationInTicks = 10;
private const int FlippyMaxDistanceManhattan = 10; // length of one side of the square around the player where the item will appear private const int FlippyMaxDistanceManhattan = 10; // length of one side of the square around the player where the item will appear
@ -592,14 +607,14 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
public void PlayPieAnimation(Actor actor, Actor User, int PowerSNO, Vector3D TargetPosition) public void PlayPieAnimation(Actor actor, Actor User, int PowerSNO, Vector3D TargetPosition)
{ {
BroadcastIfRevealed(plr => new MessageSystem.Message.Definitions.ACD.ACDTranslateDetPathPieWedgeMessage BroadcastIfRevealed(plr => new ACDTranslateDetPathPieWedgeMessage
{ {
ann = (int)actor.DynamicID(plr), ann = (int)actor.DynamicID(plr),
StartPos = User.Position, StartPos = User.Position,
FirstTagetPos = User.Position, FirstTagetPos = User.Position,
MoveFlags = 9, MoveFlags = 9,
AnimTag = 1, AnimTag = 1,
PieData = new DPathPieData() PieData = new DPathPieData
{ {
Field0 = TargetPosition, Field0 = TargetPosition,
Field1 = 1, Field1 = 1,
@ -613,7 +628,7 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
public void PlayCircleAnimation(Actor actor, Actor User, int PowerSNO, Vector3D TargetPosition) public void PlayCircleAnimation(Actor actor, Actor User, int PowerSNO, Vector3D TargetPosition)
{ {
BroadcastIfRevealed(plr => new MessageSystem.Message.Definitions.ACD.ACDTranslateDetPathSinMessage BroadcastIfRevealed(plr => new ACDTranslateDetPathSinMessage
{ {
ActorID = actor.DynamicID(plr), ActorID = actor.DynamicID(plr),
DPath = 6, DPath = 6,
@ -625,14 +640,14 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
Seed = 1, Seed = 1,
Carry = 1, Carry = 1,
TargetPostition = TargetPosition, TargetPostition = TargetPosition,
Angle = ActorSystem.Movement.MovementHelpers.GetFacingAngle(User.Position, TargetPosition), Angle = MovementHelpers.GetFacingAngle(User.Position, TargetPosition),
StartPosition = User.Position, StartPosition = User.Position,
MoveFlags = 1, MoveFlags = 1,
AnimTag = 1, AnimTag = 1,
PowerSNO = PowerSNO, PowerSNO = PowerSNO,
Var0Int = 1, Var0Int = 1,
Var0Fl = 1f, Var0Fl = 1f,
SinData = new DPathSinData() SinData = new DPathSinData
{ {
annOwner = (int)actor.DynamicID(plr), annOwner = (int)actor.DynamicID(plr),
SinIncAccel = 0f, SinIncAccel = 0f,
@ -649,28 +664,28 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
public void PlayZigAnimation(Actor actor, Actor User, int PowerSNO, Vector3D TargetPosition) public void PlayZigAnimation(Actor actor, Actor User, int PowerSNO, Vector3D TargetPosition)
{ {
BroadcastIfRevealed(plr => new MessageSystem.Message.Definitions.ACD.ACDTranslateFacingMessage BroadcastIfRevealed(plr => new ACDTranslateFacingMessage
{ {
ActorId = actor.DynamicID(plr), ActorId = actor.DynamicID(plr),
Angle = ActorSystem.Movement.MovementHelpers.GetFacingAngle(User.Position, TargetPosition), Angle = MovementHelpers.GetFacingAngle(User.Position, TargetPosition),
TurnImmediately = true TurnImmediately = true
}, actor); }, actor);
BroadcastIfRevealed(plr => new MessageSystem.Message.Definitions.ACD.ACDTranslateDetPathSinMessage BroadcastIfRevealed(plr => new ACDTranslateDetPathSinMessage
{ {
ActorID = actor.DynamicID(plr), ActorID = actor.DynamicID(plr),
DPath = 5, DPath = 5,
Seed = 1, Seed = 1,
Carry = 1, Carry = 1,
TargetPostition = TargetPosition, TargetPostition = TargetPosition,
Angle = ActorSystem.Movement.MovementHelpers.GetFacingAngle(User.Position, TargetPosition), Angle = MovementHelpers.GetFacingAngle(User.Position, TargetPosition),
StartPosition = User.Position, StartPosition = User.Position,
MoveFlags = 1, MoveFlags = 1,
AnimTag = 1, AnimTag = 1,
PowerSNO = PowerSNO, PowerSNO = PowerSNO,
Var0Int = 1, Var0Int = 1,
Var0Fl = 1f, Var0Fl = 1f,
SinData = new DPathSinData() SinData = new DPathSinData
{ {
annOwner = (int)actor.DynamicID(plr), annOwner = (int)actor.DynamicID(plr),
SinIncAccel = 0f, SinIncAccel = 0f,
@ -687,14 +702,14 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
public void PlayReverSpiralAnimation(Actor actor, Actor User, int PowerSNO, Vector3D TargetPosition) public void PlayReverSpiralAnimation(Actor actor, Actor User, int PowerSNO, Vector3D TargetPosition)
{ {
BroadcastIfRevealed(plr => new MessageSystem.Message.Definitions.ACD.ACDTranslateFacingMessage BroadcastIfRevealed(plr => new ACDTranslateFacingMessage
{ {
ActorId = actor.DynamicID(plr), ActorId = actor.DynamicID(plr),
Angle = ActorSystem.Movement.MovementHelpers.GetFacingAngle(User.Position, TargetPosition), Angle = MovementHelpers.GetFacingAngle(User.Position, TargetPosition),
TurnImmediately = true TurnImmediately = true
}, actor); }, actor);
BroadcastIfRevealed(plr => new MessageSystem.Message.Definitions.ACD.ACDTranslateDetPathSinMessage BroadcastIfRevealed(plr => new ACDTranslateDetPathSinMessage
{ {
ActorID = actor.DynamicID(plr), ActorID = actor.DynamicID(plr),
DPath = 4, DPath = 4,
@ -706,14 +721,14 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
Seed = 1, Seed = 1,
Carry = 1, Carry = 1,
TargetPostition = TargetPosition, TargetPostition = TargetPosition,
Angle = ActorSystem.Movement.MovementHelpers.GetFacingAngle(User.Position, TargetPosition), Angle = MovementHelpers.GetFacingAngle(User.Position, TargetPosition),
StartPosition = User.Position, StartPosition = User.Position,
MoveFlags = 1, MoveFlags = 1,
AnimTag = 1, AnimTag = 1,
PowerSNO = PowerSNO, PowerSNO = PowerSNO,
Var0Int = 1, Var0Int = 1,
Var0Fl = 1f, Var0Fl = 1f,
SinData = new DPathSinData() SinData = new DPathSinData
{ {
annOwner = (int)actor.DynamicID(plr), annOwner = (int)actor.DynamicID(plr),
SinIncAccel = 0.2f, SinIncAccel = 0.2f,
@ -730,14 +745,14 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
public void PlaySpiralAnimation(Actor actor, Actor User, int PowerSNO, Vector3D TargetPosition) public void PlaySpiralAnimation(Actor actor, Actor User, int PowerSNO, Vector3D TargetPosition)
{ {
BroadcastIfRevealed(plr => new MessageSystem.Message.Definitions.ACD.ACDTranslateFacingMessage BroadcastIfRevealed(plr => new ACDTranslateFacingMessage
{ {
ActorId = actor.DynamicID(plr), ActorId = actor.DynamicID(plr),
Angle = ActorSystem.Movement.MovementHelpers.GetFacingAngle(User.Position, TargetPosition), Angle = MovementHelpers.GetFacingAngle(User.Position, TargetPosition),
TurnImmediately = true TurnImmediately = true
}, actor); }, actor);
BroadcastIfRevealed(plr => new MessageSystem.Message.Definitions.ACD.ACDTranslateDetPathSinMessage BroadcastIfRevealed(plr => new ACDTranslateDetPathSinMessage
{ {
ActorID = actor.DynamicID(plr), ActorID = actor.DynamicID(plr),
DPath = 3, DPath = 3,
@ -749,14 +764,14 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
Seed = 1, Seed = 1,
Carry = 1, Carry = 1,
TargetPostition = TargetPosition, TargetPostition = TargetPosition,
Angle = ActorSystem.Movement.MovementHelpers.GetFacingAngle(User.Position, TargetPosition), Angle = MovementHelpers.GetFacingAngle(User.Position, TargetPosition),
StartPosition = User.Position, StartPosition = User.Position,
MoveFlags = 1, MoveFlags = 1,
AnimTag = 1, AnimTag = 1,
PowerSNO = PowerSNO, PowerSNO = PowerSNO,
Var0Int = 1, Var0Int = 1,
Var0Fl = 1f, Var0Fl = 1f,
SinData = new DPathSinData() SinData = new DPathSinData
{ {
annOwner = (int)actor.DynamicID(plr), annOwner = (int)actor.DynamicID(plr),
SinIncAccel = 0.2f, SinIncAccel = 0.2f,
@ -773,7 +788,7 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
public Item SpawnRandomEquip(Actor source, Player player, int forceQuality = -1, int forceLevel = -1, public Item SpawnRandomEquip(Actor source, Player player, int forceQuality = -1, int forceLevel = -1,
GameBalance.ItemTypeTable type = null, bool canBeUnidentified = true, ToonClass toonClass = ToonClass.Unknown) GameBalance.ItemTypeTable type = null, bool canBeUnidentified = true, ToonClass toonClass = ToonClass.Unknown)
{ {
Logger.Debug("SpawnRandomEquip(): quality {0}", forceQuality); Logger.MethodTrace($"quality {forceQuality}");
if (player != null) if (player != null)
{ {
int level = (forceLevel > 0 ? forceLevel : source.Attributes[GameAttribute.Level]); int level = (forceLevel > 0 ? forceLevel : source.Attributes[GameAttribute.Level]);
@ -801,7 +816,7 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
} }
public void SpawnRandomLegOrSetEquip(Actor source, Player player) public void SpawnRandomLegOrSetEquip(Actor source, Player player)
{ {
//Logger.Debug("SpawnRandomEquip(): quality {0}", forceQuality); //Logger.MethodTrace("quality {0}", forceQuality);
if (player != null) if (player != null)
{ {
var item = ItemGenerator.GenerateLegOrSetRandom(player); var item = ItemGenerator.GenerateLegOrSetRandom(player);
@ -857,7 +872,7 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
} }
public void SpawnRandomPotion(Actor source, Player player) public void SpawnRandomPotion(Actor source, Player player)
{ {
if (player != null && !player.Inventory.HaveEnough(DiIiS_NA.Core.Helpers.Hash.StringHashHelper.HashItemName("HealthPotionBottomless"), 1)) if (player != null && !player.Inventory.HaveEnough(StringHashHelper.HashItemName("HealthPotionBottomless"), 1))
{ {
var item = ItemGenerator.GenerateRandomPotion(player); var item = ItemGenerator.GenerateRandomPotion(player);
if (item == null) return; if (item == null) return;
@ -946,7 +961,7 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
/// <returns></returns> /// <returns></returns>
public bool HasActorsInGroup(string group) public bool HasActorsInGroup(string group)
{ {
var groupHash = DiIiS_NA.Core.Helpers.Hash.StringHashHelper.HashItemName(group); var groupHash = StringHashHelper.HashItemName(group);
foreach (var actor in Actors.Values) foreach (var actor in Actors.Values)
{ {
if (actor.Tags != null) if (actor.Tags != null)
@ -963,7 +978,7 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
public List<Actor> GetActorsInGroup(string group) public List<Actor> GetActorsInGroup(string group)
{ {
List<Actor> matchingActors = new List<Actor>(); List<Actor> matchingActors = new List<Actor>();
var groupHash = DiIiS_NA.Core.Helpers.Hash.StringHashHelper.HashItemName(group); var groupHash = StringHashHelper.HashItemName(group);
foreach (var actor in Actors.Values) foreach (var actor in Actors.Values)
{ {
if (actor.Tags != null) if (actor.Tags != null)
@ -1087,7 +1102,7 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
public void AddScene(Scene scene) public void AddScene(Scene scene)
{ {
if (scene.GlobalID == 0 || HasScene(scene.GlobalID)) if (scene.GlobalID == 0 || HasScene(scene.GlobalID))
throw new Exception(String.Format("Scene has an invalid ID or was already present (ID = {0})", scene.GlobalID)); throw new Exception($"Scene has an invalid ID or was already present (ID = {scene.GlobalID})");
Scenes.TryAdd(scene.GlobalID, scene); // add to scenes collection. Scenes.TryAdd(scene.GlobalID, scene); // add to scenes collection.
QuadTree.Insert(scene); // add it to quad-tree too. QuadTree.Insert(scene); // add it to quad-tree too.
@ -1100,10 +1115,9 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
public void RemoveScene(Scene scene) public void RemoveScene(Scene scene)
{ {
if (scene.GlobalID == 0 || !HasScene(scene.GlobalID)) if (scene.GlobalID == 0 || !HasScene(scene.GlobalID))
throw new Exception(String.Format("Scene has an invalid ID or was not present (ID = {0})", scene.GlobalID)); throw new Exception($"Scene has an invalid ID or was not present (ID = {scene.GlobalID})");
Scene remotedScene; Scenes.TryRemove(scene.GlobalID, out _); // remove it from scenes collection.
Scenes.TryRemove(scene.GlobalID, out remotedScene); // remove it from scenes collection.
QuadTree.Remove(scene); // remove from quad-tree too. QuadTree.Remove(scene); // remove from quad-tree too.
} }
@ -1114,8 +1128,7 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
/// <returns></returns> /// <returns></returns>
public Scene GetScene(uint dynamicID) public Scene GetScene(uint dynamicID)
{ {
Scene scene; Scenes.TryGetValue(dynamicID, out var scene);
Scenes.TryGetValue(dynamicID, out scene);
return scene; return scene;
} }
@ -1161,10 +1174,9 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
private void RemoveActor(Actor actor) private void RemoveActor(Actor actor)
{ {
if (actor.GlobalID == 0 || !Actors.ContainsKey(actor.GlobalID)) if (actor.GlobalID == 0 || !Actors.ContainsKey(actor.GlobalID))
throw new Exception(String.Format("Actor has an invalid ID or was not present (ID = {0})", actor.GlobalID)); throw new Exception($"Actor has an invalid ID or was not present (ID = {actor.GlobalID})");
Actor removedActor; Actors.TryRemove(actor.GlobalID, out _); // remove it from actors collection.
Actors.TryRemove(actor.GlobalID, out removedActor); // remove it from actors collection.
QuadTree.Remove(actor); // remove from quad-tree too. QuadTree.Remove(actor); // remove from quad-tree too.
if (actor.ActorType == ActorType.Player) // if actors is a player, remove it from players collection too. if (actor.ActorType == ActorType.Player) // if actors is a player, remove it from players collection too.
@ -1173,8 +1185,7 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
public Actor GetActorByGlobalId(uint globalID) public Actor GetActorByGlobalId(uint globalID)
{ {
Actor actor; Actors.TryGetValue(globalID, out var actor);
Actors.TryGetValue(globalID, out actor);
return actor; return actor;
} }
@ -1204,7 +1215,6 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
{ {
if (actor.ActorType == matchType) if (actor.ActorType == matchType)
return actor; return actor;
else
Logger.Warn("Attempted to get actor ID {0} as a {1}, whereas the actor is type {2}", Logger.Warn("Attempted to get actor ID {0} as a {1}, whereas the actor is type {2}",
dynamicID, Enum.GetName(typeof(ActorType), matchType), Enum.GetName(typeof(ActorType), actor.ActorType)); dynamicID, Enum.GetName(typeof(ActorType), matchType), Enum.GetName(typeof(ActorType), actor.ActorType));
} }
@ -1247,37 +1257,42 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
/// Adds given player to world. /// Adds given player to world.
/// </summary> /// </summary>
/// <param name="player">The player to add.</param> /// <param name="player">The player to add.</param>
private void AddPlayer(Player player) private bool AddPlayer(Player player)
{ {
if (player.GlobalID == 0 || HasPlayer(player.GlobalID)) if (player == null)
throw new Exception(String.Format("Player has an invalid ID or was already present (ID = {0})", player.GlobalID)); throw new Exception($"Player in world {SNO} is null and cannot be removed.");
Players.TryAdd(player.GlobalID, player); // add it to players collection. if (player.GlobalID == 0 || HasPlayer(player.GlobalID))
throw new Exception($"Player has an invalid ID or was already present (ID = {player.GlobalID})");
return Players.TryAdd(player.GlobalID, player); // add it to players collection.
} }
/// <summary> /// <summary>
/// Removes given player from world. /// Removes given player from world.
/// </summary> /// </summary>
/// <param name="player"></param> /// <param name="player"></param>
private void RemovePlayer(Player player) private bool RemovePlayer(Player player)
{ {
if (player.GlobalID == 0 || !Players.ContainsKey(player.GlobalID)) if (player == null)
throw new Exception(String.Format("Player has an invalid ID or was not present (ID = {0})", player.GlobalID)); throw new Exception($"Player in world {SNO} is null and cannot be removed.");
Player removedPlayer; if (player.GlobalID == 0 || !Players.ContainsKey(player.GlobalID))
Players.TryRemove(player.GlobalID, out removedPlayer); // remove it from players collection. throw new Exception($"Player has an invalid ID or was not present (ID = {player.GlobalID})");
return Players.TryRemove(player.GlobalID, out _); // remove it from players collection.
} }
/// <summary> /// <summary>
/// Returns player with given dynamicId. /// Returns player with a given predicate
/// </summary> /// </summary>
/// <param name="dynamicID">The dynamicId of the player.</param> /// <param name="predicate">Predicate to find player</param>
/// <returns></returns> /// <param name="player">Player result</param>
public Player GetPlayer(uint dynamicID) /// <returns>Whether the player was found.</returns>
public bool TryGetPlayer(Func<Player, bool> predicate, out Player player)
{ {
Player player; player = Players.Values.FirstOrDefault(predicate);
Players.TryGetValue(dynamicID, out player); return player != null;
return player;
} }
/// <summary> /// <summary>
@ -1285,40 +1300,28 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
/// </summary> /// </summary>
/// <param name="dynamicID">The dynamicId of the player.</param> /// <param name="dynamicID">The dynamicId of the player.</param>
/// <returns><see cref="bool"/></returns> /// <returns><see cref="bool"/></returns>
public bool HasPlayer(uint dynamicID) public bool HasPlayer(uint dynamicID) => Players.ContainsKey(dynamicID);
{
return Players.ContainsKey(dynamicID);
}
/// <summary> /// <summary>
/// Returns item with given dynamicId. /// Returns item with given dynamicId.
/// </summary> /// </summary>
/// <param name="dynamicID">The dynamicId of the item.</param> /// <param name="dynamicID">The dynamicId of the item.</param>
/// <returns></returns> /// <returns></returns>
public Item GetItem(uint dynamicID) public Item GetItem(uint dynamicID) => (Item)GetActorByGlobalId(dynamicID, ActorType.Item);
{
return (Item)GetActorByGlobalId(dynamicID, ActorType.Item);
}
/// <summary> /// <summary>
/// Returns true if world contains a monster with given dynamicId. /// Returns true if world contains a monster with given dynamicId.
/// </summary> /// </summary>
/// <param name="dynamicID">The dynamicId of the monster.</param> /// <param name="dynamicID">The dynamicId of the monster.</param>
/// <returns><see cref="bool"/></returns> /// <returns><see cref="bool"/></returns>
public bool HasMonster(uint dynamicID) public bool HasMonster(uint dynamicID) => HasActor(dynamicID, ActorType.Monster);
{
return HasActor(dynamicID, ActorType.Monster);
}
/// <summary> /// <summary>
/// Returns true if world contains an item with given dynamicId. /// Returns true if world contains an item with given dynamicId.
/// </summary> /// </summary>
/// <param name="dynamicID">The dynamicId of the item.</param> /// <param name="dynamicID">The dynamicId of the item.</param>
/// <returns><see cref="bool"/></returns> /// <returns><see cref="bool"/></returns>
public bool HasItem(uint dynamicID) public bool HasItem(uint dynamicID) => HasActor(dynamicID, ActorType.Item);
{
return HasActor(dynamicID, ActorType.Item);
}
#endregion #endregion
@ -1330,17 +1333,14 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
/// <param name="id">The id of the StartingPoint.</param> /// <param name="id">The id of the StartingPoint.</param>
/// <returns><see cref="StartingPoint"/></returns> /// <returns><see cref="StartingPoint"/></returns>
public StartingPoint GetStartingPointById(int id) public StartingPoint GetStartingPointById(int id) => Actors.Values.OfType<StartingPoint>().Where(sp => sp.TargetId == id).ToList().FirstOrDefault();
{
return Actors.Values.OfType<StartingPoint>().Where(sp => sp.TargetId == id).ToList().FirstOrDefault();
}
public Actor FindAt(ActorSno actorSno, Vector3D position, float radius = 3.0f) public Actor FindActorAt(ActorSno actorSno, Vector3D position, float radius = 3.0f)
{ {
var proximityCircle = new Circle(position.X, position.Y, radius); var proximityCircle = new Circle(position.X, position.Y, radius);
var actors = QuadTree.Query<Actor>(proximityCircle); var actors = QuadTree.Query<Actor>(proximityCircle);
foreach (var actr in actors) foreach (var actor in actors)
if (actr.Attributes[GameAttribute.Disabled] == false && actr.Attributes[GameAttribute.Gizmo_Has_Been_Operated] == false && actr.SNO == actorSno) return actr; if (actor.Attributes[GameAttribute.Disabled] == false && actor.Attributes[GameAttribute.Gizmo_Has_Been_Operated] == false && actor.SNO == actorSno) return actor;
return null; return null;
} }
@ -1349,10 +1349,13 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
/// </summary> /// </summary>
/// <param name="id">The id of the WayPoint</param> /// <param name="id">The id of the WayPoint</param>
/// <returns><see cref="Waypoint"/></returns> /// <returns><see cref="Waypoint"/></returns>
public Waypoint GetWayPointById(int id) public Waypoint GetWayPointById(int id) => Actors.Values.OfType<Waypoint>().FirstOrDefault(waypoint => waypoint.WaypointId == id);
{
return Actors.Values.OfType<Waypoint>().FirstOrDefault(waypoint => waypoint.WaypointId == id); public Waypoint[] GetAllWaypoints() => Actors.Values.OfType<Waypoint>().ToArray();
}
public Waypoint[] GetAllWaypointsInWorld(WorldSno worldSno) => Actors.Values.OfType<Waypoint>().Where(waypoint => waypoint.World.SNO == worldSno).ToArray();
public Waypoint[] GetAllWaypointsInWorld(World world) => Actors.Values.OfType<Waypoint>().Where(waypoint => waypoint.World == world).ToArray();
#endregion #endregion
@ -1360,8 +1363,27 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
public override void Destroy() public override void Destroy()
{ {
// TODO: Destroy all objects /raist Logger.Trace($"$[red]$Destroying$[/]$ World #{GlobalID} $[underline red]${SNO}$[/]$");
// TODO: Destroy all objects @iamdroppy - solution below added for testing on 21/01/2023
// foreach (var actor in Actors.Values)
// try
// {
// actor.Destroy();
// }
// catch {}
//
// foreach (var player in Players.Values)
// try
// {
// player.Destroy();
// }
// catch{}
// foreach (var portal in Portals)
// try
// {
// portal.Destroy();
// }
// catch{}
// TODO: Destroy pre-generated tile set // TODO: Destroy pre-generated tile set
worldData = null; worldData = null;
@ -1384,18 +1406,15 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
if (s.Parent != null) { scene = s.Parent; } if (s.Parent != null) { scene = s.Parent; }
if (s.Subscenes.Count > 0) if (s.Subscenes.Count > 0)
{ {
foreach (var subscene in s.Subscenes) foreach (var subScene in s.Subscenes.Where(subScene => subScene.Bounds.Contains(location.X, location.Y)))
{ {
if (subscene.Bounds.Contains(location.X, location.Y)) scene = subScene;
{
scene = subscene;
}
} }
} }
int x = (int)((location.X - scene.Bounds.Left) / 2.5f); int x = (int)((location.X - scene.Bounds.Left) / 2.5f);
int y = (int)((location.Y - scene.Bounds.Top) / 2.5f); int y = (int)((location.Y - scene.Bounds.Top) / 2.5f);
int total = (int)((y * scene.NavMesh.SquaresCountX) + x); int total = (y * scene.NavMesh.SquaresCountX) + x;
if (total < 0 || total > scene.NavMesh.NavMeshSquareCount) if (total < 0 || total > scene.NavMesh.NavMeshSquareCount)
{ {
Logger.Error("Navmesh overflow!"); Logger.Error("Navmesh overflow!");
@ -1413,31 +1432,34 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
public float GetZForLocation(Vector3D location, float defaultZ) public float GetZForLocation(Vector3D location, float defaultZ)
{ {
foreach (Scene s in Scenes.Values) foreach (Scene s in Scenes.Values.Where(s => s.Bounds.Contains(location.X, location.Y)))
{
if (s.Bounds.Contains(location.X, location.Y))
{ {
Scene scene = s; Scene scene = s;
if (s.Parent != null) { scene = s.Parent; } if (s.Parent != null)
{
scene = s.Parent;
}
if (s.Subscenes.Count > 0) if (s.Subscenes.Count > 0)
{ {
foreach (var subscene in s.Subscenes) foreach (var subScene in s.Subscenes)
{ {
if (subscene.Bounds.Contains(location.X, location.Y)) if (subScene.Bounds.Contains(location.X, location.Y))
{ {
scene = subscene; scene = subScene;
} }
} }
} }
int x = (int)((location.X - scene.Bounds.Left) / 2.5f); int x = (int)((location.X - scene.Bounds.Left) / 2.5f);
int y = (int)((location.Y - scene.Bounds.Top) / 2.5f); int y = (int)((location.Y - scene.Bounds.Top) / 2.5f);
int total = (int)((y * scene.NavMesh.SquaresCountX) + x); int total = (y * scene.NavMesh.SquaresCountX) + x;
if (total < 0 || total > scene.NavMesh.NavMeshSquareCount) if (total < 0 || total > scene.NavMesh.NavMeshSquareCount)
{ {
Logger.Error("Navmesh overflow!"); Logger.Error("Navmesh overflow!");
return defaultZ; return defaultZ;
} }
try try
{ {
return scene.NavMesh.Squares[total].Z; return scene.NavMesh.Squares[total].Z;
@ -1447,23 +1469,22 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
return defaultZ; return defaultZ;
} }
} }
}
return defaultZ; return defaultZ;
} }
[Obsolete("Isn't used anymore")] // made obsolete by @iamdroppy on 28/01/2023
public bool CheckRayPath(Vector3D start, Vector3D destination) public bool CheckRayPath(Vector3D start, Vector3D destination)
{ {
var proximity = new RectangleF(start.X - 1f, start.Y - 1f, 2f, 2f); var proximity = new RectangleF(start.X - 1f, start.Y - 1f, 2f, 2f);
var scenes = QuadTree.Query<Scene>(proximity); var scenes = QuadTree.Query<Scene>(proximity);
if (scenes.Count == 0) return false; if (scenes.Count == 0) return false;
var scene = scenes[0]; // Parent scene /fasbat
if (scenes.Count == 2) // What if it's a subscene? /fasbat if (scenes.Count == 2) // What if it's a subscene? /fasbat
{ {
if (scenes[1].ParentChunkID != 0xFFFFFFFF) if (scenes[1].ParentChunkID != 0xFFFFFFFF)
scene = scenes[1]; {
}
} }
return true; return true;
@ -1471,7 +1492,7 @@ namespace DiIiS_NA.GameServer.GSSystem.MapSystem
public override string ToString() public override string ToString()
{ {
return string.Format("[World] SNOId: {0} GlobalId: {1} Name: {2}", WorldSNO.Id, GlobalID, WorldSNO.Name); return $"[World] SNOId: {WorldSNO.Id} GlobalId: {GlobalID} Name: {WorldSNO.Name}";
} }
} }
} }

View File

@ -8,7 +8,8 @@ namespace DiIiS_NA.GameServer.GSSystem.ObjectsSystem
{ {
Invulnerable, Invulnerable,
Speed, Speed,
Powerful Powerful,
Resourcefull
} }
public class FixedMap public class FixedMap

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,7 @@
using DiIiS_NA.Core.Logging; using DiIiS_NA.Core.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
@ -12,25 +13,40 @@ namespace DiIiS_NA.GameServer.GSSystem.PowerSystem
{ {
static readonly Logger Logger = LogManager.CreateLogger(); static readonly Logger Logger = LogManager.CreateLogger();
private static Dictionary<int, Type> _implementations = new Dictionary<int, Type>(); private static readonly Dictionary<int, Type> _implementations = new();
private static PowerScript TryActivate(int powerSno)
{
try
{
return (PowerScript)Activator.CreateInstance(_implementations[powerSno]);
}
catch(Exception ex)
{
Logger.FatalException(ex, $"Failed to activate power {powerSno}");
return null;
}
}
public static PowerScript CreateImplementationForPowerSNO(int powerSNO) public static PowerScript CreateImplementationForPowerSNO(int powerSNO)
{ {
if (_implementations.ContainsKey(powerSNO)) if (_implementations.ContainsKey(powerSNO))
{ {
PowerScript script = (PowerScript)Activator.CreateInstance(_implementations[powerSNO]); PowerScript script = TryActivate(powerSNO);
if (script != null)
{
script.PowerSNO = powerSNO; script.PowerSNO = powerSNO;
return script; return script;
} }
else }
{
#if DEBUG #if DEBUG
if (powerSNO != 30021 && powerSNO != 30022 && powerSNO != -1) if (powerSNO != 30021 && powerSNO != 30022 && powerSNO != -1) //for hiding annoying messages
Logger.Info("Unimplemented power: {0}", powerSNO); //for hiding annoying messages Logger.Info($"$[underline red]$Unimplemented power:$[/]$ $[underline]${powerSNO}$[/]$");
#else
if (powerSNO != 30021 && powerSNO != 30022 && powerSNO != -1) //for hiding annoying messages
Logger.Info($"$[underline red]$Unimplemented power:$[/]$ $[underline]${powerSNO}$[/]$");
#endif #endif
return null; return null;
} }
}
public static bool HasImplementationForPowerSNO(int powerSNO) public static bool HasImplementationForPowerSNO(int powerSNO)
{ {

View File

@ -1357,7 +1357,7 @@ namespace DiIiS_NA.GameServer.GSSystem.QuestSystem
var world = Game.GetWorld(WorldSno.trout_town); var world = Game.GetWorld(WorldSno.trout_town);
DestroyFollower(ActorSno._leah); DestroyFollower(ActorSno._leah);
AddFollower(world, ActorSno._leah); AddFollower(world, ActorSno._leah);
try { (world.FindAt(ActorSno._trout_tristramfield_field_gate, new Vector3D { X = 1523.13f, Y = 857.71f, Z = 39.26f }, 5.0f) as Door).Open(); } catch { } try { (world.FindActorAt(ActorSno._trout_tristramfield_field_gate, new Vector3D { X = 1523.13f, Y = 857.71f, Z = 39.26f }, 5.0f) as Door).Open(); } catch { }
StartConversation(world, 167677); StartConversation(world, 167677);
ListenConversation(167677, new Advance()); ListenConversation(167677, new Advance());
} }
@ -1405,7 +1405,7 @@ namespace DiIiS_NA.GameServer.GSSystem.QuestSystem
var world = Game.GetWorld(WorldSno.trout_town); var world = Game.GetWorld(WorldSno.trout_town);
DestroyFollower(ActorSno._leah); DestroyFollower(ActorSno._leah);
AddFollower(world, ActorSno._leah); AddFollower(world, ActorSno._leah);
try { (world.FindAt(ActorSno._trout_tristramfield_field_gate, new Vector3D { X = 1444.1f, Y = 786.64f, Z = 39.7f }, 4.0f) as Door).Open(); } catch { } try { (world.FindActorAt(ActorSno._trout_tristramfield_field_gate, new Vector3D { X = 1444.1f, Y = 786.64f, Z = 39.7f }, 4.0f) as Door).Open(); } catch { }
SetActorOperable(world, ActorSno._keybox_trout_tristramfield_02, false); SetActorOperable(world, ActorSno._keybox_trout_tristramfield_02, false);
SetActorOperable(world, ActorSno._keybox_trout_tristramfield, false); SetActorOperable(world, ActorSno._keybox_trout_tristramfield, false);
ListenProximity(ActorSno._waypoint, new Advance()); ListenProximity(ActorSno._waypoint, new Advance());

View File

@ -96,7 +96,7 @@ namespace DiIiS_NA.GameServer.GSSystem.QuestSystem
OnAdvance = new Action(() => { //go through canyon OnAdvance = new Action(() => { //go through canyon
try try
{ {
Door TDoor = (Game.GetWorld(WorldSno.caout_town).FindAt(ActorSno._a2dun_cald_exit_gate, new Vector3D { X = 2905.62f, Y = 1568.82f, Z = 250.75f }, 6.0f) as Door); Door TDoor = (Game.GetWorld(WorldSno.caout_town).FindActorAt(ActorSno._a2dun_cald_exit_gate, new Vector3D { X = 2905.62f, Y = 1568.82f, Z = 250.75f }, 6.0f) as Door);
//ListenProximity(TDoor, ) //ListenProximity(TDoor, )
TDoor.Open(); TDoor.Open();
} catch { } } catch { }
@ -926,7 +926,7 @@ namespace DiIiS_NA.GameServer.GSSystem.QuestSystem
var world = Game.GetWorld(WorldSno.a2dun_aqd_special_01); var world = Game.GetWorld(WorldSno.a2dun_aqd_special_01);
Game.AddOnLoadWorldAction(WorldSno.a2dun_aqd_special_01, () => Game.AddOnLoadWorldAction(WorldSno.a2dun_aqd_special_01, () =>
{ {
(world.FindAt(ActorSno._a2dun_aqd_act_stone_slab_a_01, new Vector3D { X = 175.1f, Y = 62.275f, Z = 50.17f }, 20.0f) as Door).Open(); (world.FindActorAt(ActorSno._a2dun_aqd_act_stone_slab_a_01, new Vector3D { X = 175.1f, Y = 62.275f, Z = 50.17f }, 20.0f) as Door).Open();
}); });
ListenInteract(ActorSno._a2dun_aqd_act_waterwheel_lever_a_01, 1, new CompleteObjective(0)); ListenInteract(ActorSno._a2dun_aqd_act_waterwheel_lever_a_01, 1, new CompleteObjective(0));
ListenInteract(ActorSno._a2dun_aqd_act_waterwheel_lever_b_01, 1, new Advance()); ListenInteract(ActorSno._a2dun_aqd_act_waterwheel_lever_b_01, 1, new Advance());
@ -948,7 +948,7 @@ namespace DiIiS_NA.GameServer.GSSystem.QuestSystem
Open(world, ActorSno._a2dun_aqd_act_stone_slab_a_01); Open(world, ActorSno._a2dun_aqd_act_stone_slab_a_01);
Open(world, ActorSno._a2dun_aqd_special_01_waterfall); Open(world, ActorSno._a2dun_aqd_special_01_waterfall);
Open(world, ActorSno._a2dun_aqd_mainpuzzle_door); Open(world, ActorSno._a2dun_aqd_mainpuzzle_door);
(world.FindAt(ActorSno._a2dun_aqd_act_stone_slab_a_01, new Vector3D { X = 80.5f, Y = 155.631f, Z = 50.33f }, 20.0f) as Door).Open(); (world.FindActorAt(ActorSno._a2dun_aqd_act_stone_slab_a_01, new Vector3D { X = 80.5f, Y = 155.631f, Z = 50.33f }, 20.0f) as Door).Open();
}); });
//try {(this.Game.GetWorld(59486).FindAt(83629, new Vector3D{X = 80.5f, Y = 155.631f, Z = 50.33f}, 20.0f) as Door).Open();} catch {} //try {(this.Game.GetWorld(59486).FindAt(83629, new Vector3D{X = 80.5f, Y = 155.631f, Z = 50.33f}, 20.0f) as Door).Open();} catch {}
ListenTeleport(192694, new Advance()); ListenTeleport(192694, new Advance());
@ -1365,7 +1365,7 @@ namespace DiIiS_NA.GameServer.GSSystem.QuestSystem
Objectives = new List<Objective> { Objective.Default() }, Objectives = new List<Objective> { Objective.Default() },
OnAdvance = new Action(() => { //todo: timed event 115494 OnAdvance = new Action(() => { //todo: timed event 115494
var world = Game.GetWorld(WorldSno.caout_town); var world = Game.GetWorld(WorldSno.caout_town);
try { (world.FindAt(ActorSno._a2dun_cald_exit_gate, new Vector3D { X = 3135.3f, Y = 1546.1f, Z = 250.545f }, 15.0f) as Door).Open(); } catch { } try { (world.FindActorAt(ActorSno._a2dun_cald_exit_gate, new Vector3D { X = 3135.3f, Y = 1546.1f, Z = 250.545f }, 15.0f) as Door).Open(); } catch { }
foreach (var Ashe in world.GetActorsBySNO(ActorSno._asheara)) foreach (var Ashe in world.GetActorsBySNO(ActorSno._asheara))
RemoveConversations(Ashe); RemoveConversations(Ashe);
StartConversation(world, 178852); StartConversation(world, 178852);

View File

@ -337,7 +337,7 @@ namespace DiIiS_NA.GameServer.GSSystem.QuestSystem
ListenConversation(134266, new Advance()); ListenConversation(134266, new Advance());
try try
{ {
Game.GetWorld(WorldSno.a3dun_hub_keep).FindAt(ActorSno._a3dun_hub_drawbridge_01, new Vector3D { X = 127.121f, Y = 353.211f, Z = 0.22f }, 25f).Hidden = true; Game.GetWorld(WorldSno.a3dun_hub_keep).FindActorAt(ActorSno._a3dun_hub_drawbridge_01, new Vector3D { X = 127.121f, Y = 353.211f, Z = 0.22f }, 25f).Hidden = true;
var world = Game.GetWorld(WorldSno.a3dun_keep_hub_inn); var world = Game.GetWorld(WorldSno.a3dun_keep_hub_inn);
var NStone = world.GetActorBySNO(ActorSno._a2dun_zolt_black_soulstone);//156328 var NStone = world.GetActorBySNO(ActorSno._a2dun_zolt_black_soulstone);//156328
foreach (var atr in world.GetActorsBySNO(ActorSno._leah)) foreach (var atr in world.GetActorsBySNO(ActorSno._leah))
@ -653,8 +653,8 @@ namespace DiIiS_NA.GameServer.GSSystem.QuestSystem
try try
{ {
var world = Game.GetWorld(WorldSno.a3dun_crater_st_level04b); var world = Game.GetWorld(WorldSno.a3dun_crater_st_level04b);
(world.FindAt(ActorSno._a3dun_crater_st_demon_chainpylon_fire_mistressofpain, new Vector3D { X = 457.04f, Y = 359.03f, Z = 0.39f }, 20f) as Door).Open(); (world.FindActorAt(ActorSno._a3dun_crater_st_demon_chainpylon_fire_mistressofpain, new Vector3D { X = 457.04f, Y = 359.03f, Z = 0.39f }, 20f) as Door).Open();
(world.FindAt(ActorSno._a3dun_crater_st_demon_chainpylon_fire_mistressofpain, new Vector3D { X = 356.04f, Y = 267.03f, Z = 0.28f }, 20f) as Door).Open(); (world.FindActorAt(ActorSno._a3dun_crater_st_demon_chainpylon_fire_mistressofpain, new Vector3D { X = 356.04f, Y = 267.03f, Z = 0.28f }, 20f) as Door).Open();
SetActorOperable(world, ActorSno._a3dun_crater_st_giantdemonheart_mob, false); SetActorOperable(world, ActorSno._a3dun_crater_st_giantdemonheart_mob, false);
} }
catch { } catch { }

View File

@ -166,7 +166,7 @@ namespace DiIiS_NA.GameServer.GSSystem.QuestSystem
{ {
if (Game.CurrentQuest == 251355 && Game.CurrentStep == 14) if (Game.CurrentQuest == 251355 && Game.CurrentStep == 14)
{ {
try { world.FindAt(ActorSno._x1_westm_door_cloister_locked, new Vector3D { X = 555.9f, Y = 403.47f, Z = 10.2f }, 5.0f).Destroy(); } catch { } try { world.FindActorAt(ActorSno._x1_westm_door_cloister_locked, new Vector3D { X = 555.9f, Y = 403.47f, Z = 10.2f }, 5.0f).Destroy(); } catch { }
} }
}); });
ListenKill(ActorSno._x1_skeleton_westmarch_a, 10, new Advance()); ListenKill(ActorSno._x1_skeleton_westmarch_a, 10, new Advance());

View File

@ -122,31 +122,31 @@ namespace DiIiS_NA.GameServer.GSSystem.QuestSystem
NextStep = -1, NextStep = -1,
Objectives = new List<Objective> { Objective.Default() }, Objectives = new List<Objective> { Objective.Default() },
OnAdvance = new Action(() => { //complete OnAdvance = new Action(() => { //complete
var NephalemWorld = Game.GetWorld(Game.WorldOfPortalNephalem); var nephalem = Game.GetWorld(Game.WorldOfPortalNephalem);
ActorSystem.Actor BossOfPortal = null; ActorSystem.Actor BossOfPortal = null;
switch (Game.WorldOfPortalNephalem) switch (Game.WorldOfPortalNephalem)
{ {
default: default:
List<MapSystem.Scene> Scenes = new List<MapSystem.Scene>(); List<MapSystem.Scene> scenes = new List<MapSystem.Scene>();
foreach (var scene in NephalemWorld.Scenes.Values) foreach (var scene in nephalem.Scenes.Values)
{ {
if (!scene.SceneSNO.Name.ToLower().Contains("filler")) if (!scene.SceneSNO.Name.ToLower().Contains("filler"))
Scenes.Add(scene); scenes.Add(scene);
} }
int SceneNum = Scenes.Count - DiIiS_NA.Core.Helpers.Math.RandomHelper.Next(0, 3); int sceneNum = scenes.Count - DiIiS_NA.Core.Helpers.Math.RandomHelper.Next(0, 3);
Vector3D SSV = Scenes[SceneNum - 1].Position; Vector3D SSV = scenes[sceneNum - 1].Position;
Vector3D SP = null; Vector3D location = null;
while (true) while (true)
{ {
SP = new Vector3D(SSV.X + DiIiS_NA.Core.Helpers.Math.RandomHelper.Next(0, 240), SSV.Y + DiIiS_NA.Core.Helpers.Math.RandomHelper.Next(0, 240), SSV.Z); location = new Vector3D(SSV.X + DiIiS_NA.Core.Helpers.Math.RandomHelper.Next(0, 240), SSV.Y + DiIiS_NA.Core.Helpers.Math.RandomHelper.Next(0, 240), SSV.Z);
if (NephalemWorld.CheckLocationForFlag(SP, DiIiS_NA.Core.MPQ.FileFormats.Scene.NavCellFlags.AllowWalk)) if (nephalem.CheckLocationForFlag(location, DiIiS_NA.Core.MPQ.FileFormats.Scene.NavCellFlags.AllowWalk))
break; break;
} }
BossOfPortal = NephalemWorld.SpawnMonster(ActorSno._x1_lr_boss_mistressofpain, SP); BossOfPortal = nephalem.SpawnMonster(ActorSno._x1_lr_boss_mistressofpain, location);
break; break;
} }
ActiveArrow(NephalemWorld, BossOfPortal.SNO); ActiveArrow(nephalem, BossOfPortal.SNO);
ListenKill(BossOfPortal.SNO, 1, new QuestEvents.SideAdvance()); ListenKill(BossOfPortal.SNO, 1, new QuestEvents.SideAdvance());
}) })
}); });

View File

@ -17,14 +17,14 @@ namespace DiIiS_NA.GameServer.GSSystem.QuestSystem.QuestEvents.Implementations
//if (world.Game.Empty) return; //if (world.Game.Empty) return;
//Logger.Trace("SpawnSnakemans event started"); //Logger.Trace("SpawnSnakemans event started");
var point = new Vector3D { X = 835.331f, Y = 410.121f, Z = 161.842f }; var point = new Vector3D { X = 835.331f, Y = 410.121f, Z = 161.842f };
var snakemanHandle = new Core.Types.SNO.SNOHandle((int)ActorSno._khamsin_snakeman_melee); var snakeManHandle = new Core.Types.SNO.SNOHandle((int)ActorSno._khamsin_snakeman_melee);
var snakemanActor = snakemanHandle.Target as DiIiS_NA.Core.MPQ.FileFormats.Actor; var snakeManActor = snakeManHandle.Target as DiIiS_NA.Core.MPQ.FileFormats.Actor;
try try
{ {
var guard_a = world.FindAt(ActorSno._caldeumguard_cleaver_a, point, 20.0f); var caldeumGuard = world.FindActorAt(ActorSno._caldeumguard_cleaver_a, point, 20.0f);
Vector3D guard_a_position = guard_a.Position; Vector3D guard_a_position = caldeumGuard.Position;
guard_a.Destroy(); //world.Game. caldeumGuard.Destroy(); //world.Game.
world.Game.WorldGenerator.LoadActor(snakemanHandle, world.Game.WorldGenerator.LoadActor(snakeManHandle,
new PRTransform() new PRTransform()
{ {
Quaternion = new Quaternion() Quaternion = new Quaternion()
@ -35,15 +35,15 @@ namespace DiIiS_NA.GameServer.GSSystem.QuestSystem.QuestEvents.Implementations
Vector3D = guard_a_position Vector3D = guard_a_position
}, },
world, world,
snakemanActor.TagMap); snakeManActor.TagMap);
} }
catch { } catch { }
try try
{ {
var guard_b = world.FindAt(ActorSno._caldeumguard_cleaver_a, point, 20.0f); var caldeumGuard = world.FindActorAt(ActorSno._caldeumguard_cleaver_a, point, 20.0f);
Vector3D guard_b_position = guard_b.Position; Vector3D caldeumGuardPosition = caldeumGuard.Position;
guard_b.Destroy(); caldeumGuard.Destroy();
world.Game.WorldGenerator.LoadActor(snakemanHandle, world.Game.WorldGenerator.LoadActor(snakeManHandle,
new PRTransform() new PRTransform()
{ {
Quaternion = new Quaternion() Quaternion = new Quaternion()
@ -51,18 +51,18 @@ namespace DiIiS_NA.GameServer.GSSystem.QuestSystem.QuestEvents.Implementations
W = 0.590017f, W = 0.590017f,
Vector3D = new Vector3D(0, 0, 0) Vector3D = new Vector3D(0, 0, 0)
}, },
Vector3D = guard_b_position Vector3D = caldeumGuardPosition
}, },
world, world,
snakemanActor.TagMap); snakeManActor.TagMap);
} }
catch { } catch { }
try try
{ {
var guard_c = world.FindAt(ActorSno._davydimpostor, point, 20.0f); var davydImpostor = world.FindActorAt(ActorSno._davydimpostor, point, 20.0f);
Vector3D guard_c_position = guard_c.Position; Vector3D davydPosition = davydImpostor.Position;
guard_c.Destroy(); davydImpostor.Destroy();
world.Game.WorldGenerator.LoadActor(snakemanHandle, world.Game.WorldGenerator.LoadActor(snakeManHandle,
new PRTransform() new PRTransform()
{ {
Quaternion = new Quaternion() Quaternion = new Quaternion()
@ -70,10 +70,10 @@ namespace DiIiS_NA.GameServer.GSSystem.QuestSystem.QuestEvents.Implementations
W = 0.590017f, W = 0.590017f,
Vector3D = new Vector3D(0, 0, 0) Vector3D = new Vector3D(0, 0, 0)
}, },
Vector3D = guard_c_position Vector3D = davydPosition
}, },
world, world,
snakemanActor.TagMap); snakeManActor.TagMap);
} }
catch { } catch { }
} }

View File

@ -2,6 +2,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -23,7 +24,7 @@ namespace DiIiS_NA.GameServer.GSSystem.QuestSystem.QuestEvents
public override void Execute(MapSystem.World world) public override void Execute(MapSystem.World world)
{ {
Logger.Trace("StartSideQuest(): {0}", QuestId); Logger.MethodTrace($"{QuestId}");
world.Game.QuestManager.LaunchSideQuest(QuestId, ForceAbandon); world.Game.QuestManager.LaunchSideQuest(QuestId, ForceAbandon);
} }
} }

View File

@ -40,7 +40,7 @@ namespace DiIiS_NA.GameServer.MessageSystem.Message.Definitions.Game
public void Handle(GameClient client) public void Handle(GameClient client)
{ {
Logger.Info("Client {0}, enter in game. Server loaded.", client.BnetClient.Account.BattleTag); Logger.Info("Client $[underline]${0}$[/]$, joined game.", client.BnetClient.Account.Email);
} }
} }
} }