示例#1
0
        public void EditShouldEditNameVersionDescriptionOfMod()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "EditShouldEditNameVersionDescriptionOfMod_DB")
                          .Options;

            var dbContext  = new ApplicationDbContext(options);
            var modService = new ModService(dbContext);

            var mod = new Mod
            {
                Name        = "FlairDante",
                Version     = "1.1",
                Description = "Purple Dante",
            };

            dbContext.Mods.Add(mod);
            dbContext.SaveChanges();

            string newName        = "FlairDanteV2";
            string newVersion     = "2.0";
            string newDescription = "Longer Hair";

            modService.Edit(mod.Id, newName, newVersion, newDescription);

            Assert.Equal(newName, mod.Name);
            Assert.Equal(newVersion, mod.Version);
            Assert.Equal(newDescription, mod.Description);
        }
        public CommandHandlingService(IServiceProvider provider, DiscordSocketClient discord, CommandService commands)
        {
            InitializeLoader();
            LoadDatabase();
            _discord  = discord;
            _commands = commands;
            _provider = provider;

            _epService         = _provider.GetService <EPService>();
            _afkSertvice       = _provider.GetService <AfkSertvice>();
            _updateService     = _provider.GetService <UserGuildUpdateService>();
            _starBoardService  = _provider.GetService <StarBoardService>();
            _musicService      = _provider.GetService <MusicService>();
            _modService        = _provider.GetService <ModService>();
            _blackListService  = _provider.GetService <BlackListService>();
            _ratelimitService2 = _provider.GetService <RatelimitService2>();
            _globalBans        = _provider.GetService <GlobalBanService>();
            _playingService    = new PlayingWith(_discord);

            SentryService.client = _discord;


            ChangelogService.LoadChangelog();

            _discord.MessageReceived       += _epService.IncreaseEP;
            _discord.MessageReceived       += _afkSertvice.Client_MessageReceived;
            _discord.UserJoined            += _updateService.UserJoined;
            _discord.UserLeft              += _updateService.UserLeft;
            _discord.ReactionAdded         += _starBoardService.StarAddedNew;
            _discord.ReactionRemoved       += _starBoardService.StarRemovedNew;
            _discord.UserVoiceStateUpdated += _musicService.CheckIfAlone;

            //Bans

            _discord.UserBanned   += _modService.Client_UserBanned;
            _discord.UserUnbanned += _modService.Client_UserUnbanned;

            //Modlog

            _discord.MessageDeleted += _modService.Client_MessageDeleted;
            _discord.RoleCreated    += _modService.Client_RoleCreated;
            _discord.RoleDeleted    += _modService.Client_RoleDeleted;
            _discord.RoleUpdated    += _modService.Client_RoleUpdated;

            _discord.ChannelCreated   += _modService.Client_ChannelCreated;
            _discord.ChannelDestroyed += _modService.Client_ChannelDestroyed;
            _discord.ChannelUpdated   += _modService.Client_ChannelUpdated;

            _discord.GuildUpdated += _modService.Client_GuildUpdated;

            //Owner

            _discord.MessageReceived += MessageReceived;
            _discord.GuildAvailable  += Client_GuildAvailable;
            _discord.JoinedGuild     += Client_JoinedGuild;
            _discord.LeftGuild       += Client_LeftGuild;

            //CommandService
            _commands.Log += CommandsOnLog;
        }
示例#3
0
        public void DownloadsCountUpShpouldIncreaseDownloadCountForGameAndMod()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "DownloadsCountUpShpouldIncreaseDownloadCountForGameAndMod_DB")
                          .Options;

            var dbContext = new ApplicationDbContext(options);

            var modService = new ModService(dbContext);

            var mod = new Mod
            {
                TotalDownloadCount = 100,
            };
            var game = new Game
            {
                TotalDownloadCount = 56
            };

            dbContext.Mods.Add(mod);
            dbContext.Games.Add(game);
            dbContext.SaveChanges();

            modService.DownloadsCountUp(mod.Id, game.Id);

            Assert.Equal(101, mod.TotalDownloadCount);
            Assert.Equal(57, game.TotalDownloadCount);
        }
示例#4
0
        public void DeleteShouldDeleteModAndReduceModCount()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "DeleteShouldDeleteModAndReduceModCount_DB")
                          .Options;

            var dbContext = new ApplicationDbContext(options);

            var modService = new ModService(dbContext);
            var game       = new Game
            {
                ModCount = 10,
            };
            var user = new ApplicationUser
            {
                ModCount = 6,
            };

            dbContext.Users.Add(user);
            dbContext.Games.Add(game);
            dbContext.SaveChanges();
            var mod = new Mod
            {
                Game = game,
                User = user,
            };

            dbContext.Mods.Add(mod);
            dbContext.SaveChanges();

            modService.Delete(mod.Id);

            Assert.Equal(9, game.ModCount);
            Assert.Equal(5, user.ModCount);
        }
示例#5
0
        public void AddGalleryUrlsShouldAddMultipleImagesToMod()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "AddGalleryUrlsShouldAddMultipleImagesToMod_DB")
                          .Options;

            var dbContext  = new ApplicationDbContext(options);
            var modService = new ModService(dbContext);

            var urls = new List <string>();

            urls.Add("qqq");
            urls.Add("222");
            urls.Add("rrr");

            var mod = new Mod();

            dbContext.Mods.Add(mod);
            dbContext.SaveChanges();

            modService.AddGalleryUrls(mod.Id, urls);

            var gallery = mod.Pictures.ToList();

            Assert.Equal(3, gallery.Count);
        }
示例#6
0
        public void CreatingModShouldIncreaseGameModCount()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "CreatingModShouldIncreaseGameModCount_DB")
                          .Options;

            var dbContext = new ApplicationDbContext(options);

            var modService = new ModService(dbContext);

            var game = new Game
            {
                ModCount = 0,
            };
            var user = new ApplicationUser
            {
                ModCount = 0,
            };

            dbContext.Users.Add(user);
            dbContext.Games.Add(game);
            dbContext.SaveChanges();
            var mod = new Mod
            {
                Game = game,
                User = user,
            };

            modService.Create(mod);

            Assert.Equal(1, mod.Game.ModCount);
        }
示例#7
0
        public ManageModsViewModel()
        {
            var ms = new ModService();

            AvailableMods = ms.ListAvailableMods();
            InstalledMods = ms.ListInstalledMods();
        }
示例#8
0
        public void DeleteImagesShouldRemoveTheImagesOfMod()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "RemoveImagesOnEditShouldRemoveTheImagesOfModOnEdit_DB")
                          .Options;

            var dbContext  = new ApplicationDbContext(options);
            var modService = new ModService(dbContext);

            var urls = new List <string>();

            urls.Add("qqq");
            urls.Add("222");
            urls.Add("rrr");

            var mod = new Mod();

            dbContext.Mods.Add(mod);
            dbContext.SaveChanges();

            modService.AddGalleryUrls(mod.Id, urls);

            modService.DeleteImages(mod.Id);

            Assert.Empty(mod.Pictures);
        }
示例#9
0
        public FactorioLoader()
        {
            var path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), Environment.Is64BitProcess ? "x64" : "x86", "7z.dll");

            SevenZip.SevenZipBase.SetLibraryPath(path);

            Profiles = new ModProfileService();
            Mods     = new ModService();
            Config   = new LoaderConfig();
        }
示例#10
0
        public ModViewModel(
            GamePathService gamePathService,
            ModService modService,
            LanguageService languageService)
        {
            _gamePathService = gamePathService;
            _modService      = modService;
            _languageService = languageService;

            Mods          = new BindableCollection <Mod>();
            _selectedMods = new List <Mod>(32);
        }
示例#11
0
        // ReSharper disable once UnusedMember.Local
        public static void Main()
        {
            // Breaking the rules for the examine event because the result of the services is used in the following
            // service call. We still signal an event for this, but in general all of the logic should go into this method.

            using (new Profiler(nameof(mod_on_examine)))
            {
                NWPlayer examiner       = (_.OBJECT_SELF);
                NWObject examinedObject = NWNXObject.StringToObject(NWNXEvents.GetEventData("EXAMINEE_OBJECT_ID"));
                if (ExaminationService.OnModuleExamine(examiner, examinedObject))
                {
                    MessageHub.Instance.Publish(new OnModuleExamine());
                    return;
                }

                string description;

                if (_.GetIsPC(examinedObject.Object) == true)
                {
                    // https://github.com/zunath/SWLOR_NWN/issues/853
                    // safest probably to get the modified (non-original) description only for players
                    // may want to always get the modified description for later flexibility?
                    description = _.GetDescription(examinedObject.Object, false) + "\n\n";
                }
                else
                {
                    description = _.GetDescription(examinedObject.Object, true) + "\n\n";
                }

                if (examinedObject.IsCreature)
                {
                    var    racialID   = Convert.ToInt32(_.Get2DAString("racialtypes", "Name", (int)_.GetRacialType(examinedObject)));
                    string racialtype = _.GetStringByStrRef(racialID);
                    if (!description.Contains(ColorTokenService.Green("Racial Type: ") + racialtype))
                    {
                        description += ColorTokenService.Green("Racial Type: ") + racialtype;
                    }
                }

                description = ModService.OnModuleExamine(description, examiner, examinedObject);
                description = ItemService.OnModuleExamine(description, examinedObject);
                description = DurabilityService.OnModuleExamine(description, examinedObject);

                if (!string.IsNullOrWhiteSpace(description))
                {
                    _.SetDescription(examinedObject.Object, description, false);
                    _.SetDescription(examinedObject.Object, description);
                }
            }

            MessageHub.Instance.Publish(new OnModuleExamine());
        }
示例#12
0
        public void GetAllByUserNameShouldReturnAllModsDependingOnSortType()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "GetAllByUserNameShouldReturnAllModsDependingOnSortType_DB")
                          .Options;

            var dbContext  = new ApplicationDbContext(options);
            var modService = new ModService(dbContext);

            var user = new ApplicationUser
            {
                UserName = "******",
            };

            dbContext.Users.Add(user);

            var mod1 = new Mod
            {
                UserId             = user.Id,
                Views              = 100,
                TotalDownloadCount = 25,
                VoteCount          = 50,
            };
            var mod2 = new Mod
            {
                UserId             = user.Id,
                Views              = 25,
                TotalDownloadCount = 100,
                VoteCount          = 50,
            };
            var mod3 = new Mod
            {
                UserId             = user.Id,
                Views              = 25,
                TotalDownloadCount = 50,
                VoteCount          = 100,
            };

            dbContext.Mods.Add(mod1);
            dbContext.Mods.Add(mod2);
            dbContext.Mods.Add(mod3);
            dbContext.SaveChanges();

            var viewsSort     = modService.GetAllByUserName(user.UserName, "Views").First();
            var votesSort     = modService.GetAllByUserName(user.UserName, "Votes").First();
            var downloadsSort = modService.GetAllByUserName(user.UserName, "Downloads").First();

            Assert.Equal(mod1.Views, viewsSort.Views);
            Assert.Equal(mod2.TotalDownloadCount, downloadsSort.TotalDownloadCount);
            Assert.Equal(mod3.VoteCount, votesSort.VoteCount);
        }
示例#13
0
        public void GetAllByGameIdShouldReturnAllModsDependingOnSortType()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "AddGalleryUrlsShouldAddMultipleImagesToMod_DB")
                          .Options;

            var dbContext  = new ApplicationDbContext(options);
            var modService = new ModService(dbContext);

            var game = new Game();

            dbContext.Games.Add(game);

            var mod1 = new Mod
            {
                GameId             = game.Id,
                Views              = 100,
                TotalDownloadCount = 25,
                VoteCount          = 50,
            };
            var mod2 = new Mod
            {
                GameId             = game.Id,
                Views              = 25,
                TotalDownloadCount = 100,
                VoteCount          = 50,
            };
            var mod3 = new Mod
            {
                GameId             = game.Id,
                Views              = 25,
                TotalDownloadCount = 50,
                VoteCount          = 100,
            };

            dbContext.Mods.Add(mod1);
            dbContext.Mods.Add(mod2);
            dbContext.Mods.Add(mod3);
            dbContext.SaveChanges();

            var viewsSort     = modService.GetAllByGameId(game.Id, "Views").First();
            var votesSort     = modService.GetAllByGameId(game.Id, "Votes").First();
            var downloadsSort = modService.GetAllByGameId(game.Id, "Downloads").First();

            Assert.Equal(mod1.Views, viewsSort.Views);
            Assert.Equal(mod2.TotalDownloadCount, downloadsSort.TotalDownloadCount);
            Assert.Equal(mod3.VoteCount, votesSort.VoteCount);
        }
示例#14
0
        public void AddFileUrlShouldAddFileToMod()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "AddFileUrlShouldAddFileToMod_DB")
                          .Options;

            var dbContext = new ApplicationDbContext(options);

            var modService = new ModService(dbContext);
            var file       = new Mock <IFormFile>();
            var mod        = new Mod();

            dbContext.Mods.Add(mod);
            dbContext.SaveChanges();

            modService.AddFileUrl(mod.Id, null, null, null, 10000000);

            Assert.Single(mod.Files);
        }
示例#15
0
        public void DeleteFilesShouldDeleteFilesFromMod()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "DeleteFilesShouldDeleteFilesFromMod_DB")
                          .Options;

            var dbContext = new ApplicationDbContext(options);

            var modService = new ModService(dbContext);

            var mod = new Mod();

            dbContext.Mods.Add(mod);
            dbContext.SaveChanges();

            modService.AddFileUrl(mod.Id, null, null, null, 10000000);
            modService.DeleteFiles(mod.Id);

            Assert.Empty(mod.Files);
        }
示例#16
0
        public void ViewUpShouldIncreaseTheViewsOfMod()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "ViewUpShouldIncreaseTheViewsOfMod_DB")
                          .Options;

            var dbContext = new ApplicationDbContext(options);

            var modService = new ModService(dbContext);

            var mod = new Mod
            {
                Views = 10,
            };

            dbContext.Mods.Add(mod);
            dbContext.SaveChanges();

            modService.ViewUp(mod.Id);

            Assert.Equal(11, mod.Views);
        }
示例#17
0
        public void GetByIdShouldReturnCorrectMod()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "GetByIdShouldReturnCorrectMod_DB")
                          .Options;

            var dbContext = new ApplicationDbContext(options);

            var modService = new ModService(dbContext);

            var mod = new Mod
            {
                Name = "DevilSwordNero",
            };

            dbContext.Mods.Add(mod);
            dbContext.SaveChanges();

            var test = modService.GetById(mod.Id);

            Assert.Equal(mod.Name, test.Name);
        }
示例#18
0
        // ReSharper disable once UnusedMember.Local
        private static void Main()
        {
            // Breaking the rules for the examine event because the result of the services is used in the following
            // service call. We still signal an event for this, but in general all of the logic should go into this method.

            using (new Profiler(nameof(mod_on_examine)))
            {
                NWPlayer examiner       = (Object.OBJECT_SELF);
                NWObject examinedObject = NWNXEvents.OnExamineObject_GetTarget();
                if (ExaminationService.OnModuleExamine(examiner, examinedObject))
                {
                    MessageHub.Instance.Publish(new OnModuleExamine());
                    return;
                }

                string description = _.GetDescription(examinedObject.Object, _.TRUE) + "\n\n";

                if (examinedObject.IsCreature)
                {
                    int    racialID   = Convert.ToInt32(_.Get2DAString("racialtypes", "Name", _.GetRacialType(examinedObject)));
                    string racialtype = _.GetStringByStrRef(racialID);
                    description += ColorTokenService.Green("Racial Type: ") + racialtype;
                }

                description = ModService.OnModuleExamine(description, examiner, examinedObject);
                description = ItemService.OnModuleExamine(description, examiner, examinedObject);
                description = DurabilityService.OnModuleExamine(description, examinedObject);
                description = FarmingService.OnModuleExamine(description, examinedObject);

                if (!string.IsNullOrWhiteSpace(description))
                {
                    _.SetDescription(examinedObject.Object, description, _.FALSE);
                    _.SetDescription(examinedObject.Object, description);
                }
            }

            MessageHub.Instance.Publish(new OnModuleExamine());
        }
示例#19
0
        public void AddImageUrlShouldAddAnImageToMod()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "AddImageUrlShouldAddAnImageToMod_DB")
                          .Options;

            var dbContext = new ApplicationDbContext(options);

            var modService = new ModService(dbContext);

            string imageUrl = "qweqwe";

            var mod = new Mod
            {
                MainPicturePath = "asdasd",
            };

            dbContext.Mods.Add(mod);
            dbContext.SaveChanges();

            modService.AddImageUrl(mod.Id, imageUrl);

            Assert.Equal(imageUrl, mod.MainPicturePath);
        }
示例#20
0
        public CommandHandler(IServiceProvider provider, DiscordSocketClient client, CommandService commandService,
                              AfkService afkService, RatelimitingService ratelimitingService, StarboardService starboardService, SelfAssignableRolesService selfService, AnnouncementService announcementService,
                              ModService modService, GuildCountUpdaterService guildUpdate, ExpService expService, BanService banService, InteractionsService interactionsService)
        {
            _client                     = client;
            _commands                   = commandService;
            _afkService                 = afkService;
            _services                   = provider;
            _ratelimitingService        = ratelimitingService;
            _starboardService           = starboardService;
            _selfAssignableRolesService = selfService;
            _announcementService        = announcementService;
            _modService                 = modService;
            _guildCount                 = guildUpdate;
            _banService                 = banService;
            _interactionsService        = interactionsService;

            _guildCount.Initialize(client.ShardId, Utility.TOTAL_SHARDS, client.Guilds.Count);


            _client.MessageReceived += HandleCommandsAsync;
            //_client.MessageReceived += _afkService.Client_MessageReceived;
            _commands.Log           += CommandsOnLog;
            _client.JoinedGuild     += ClientOnJoinedGuild;
            _client.LeftGuild       += ClientOnLeftGuild;
            _client.MessageReceived += expService.IncreaseEpOnMessageReceive;
            _client.ReactionAdded   += _starboardService.ClientOnReactionAdded;
            _client.ReactionRemoved += _starboardService.ClientOnReactionRemoved;
            _client.UserJoined      += _selfAssignableRolesService.ClientOnUserJoined;
            _client.UserJoined      += _announcementService.ClientOnUserJoined;
            _client.UserLeft        += _announcementService.ClientOnUserLeft;

            //mod Service
            _client.UserBanned   += _modService.ClientOnUserBanned;
            _client.UserUnbanned += _modService.ClientOnUserUnbanned;
        }
示例#21
0
        private static void Main(string[] args)
        {
            //var sourceDirectory = @"C:\Users\Stephen Weistra\gitrepos\RogueTech";
            //var sourceDirectory = @"D:\XLRP Fixes\XLRP - Reference - 20190725 - With CAB";
            //var sourceDirectory = @"C:\Users\Stephen Weistra\gitrepos\XLRP-Sammael\Build\XLRP\1.8 Clean Build";
            //var sourceDirectory = @"C:\Users\Stephen Weistra\gitrepos\XLRP-Complete";
            //var sourceDirectory = @"D:\Test Data\XAI";

            //var sourceDirectory = @"C:\Users\Stephen Weistra\gitrepos\XLRP-Complete";
            //var btDirectory = @"D:\Test Data\BT Base Data";
            //var dlcDirectory = @"C:\Users\Stephen Weistra\gitrepos\bt-dlc-designdata";

            var sourceDirectory = @"C:\Games\Steam\steamapps\common\BATTLETECH\Mods";
            var btDirectory     = @"C:\Games\Steam\steamapps\common\BATTLETECH";
            var dlcDirectory    = @"C:\Games\Steam\steamapps\common\BATTLETECH\Repository\bt-dlc-designdata";

            var manifestService = new ManifestService();
            var manifest        = manifestService.InitManifestFromDisk(btDirectory, dlcDirectory);

            System.Console.WriteLine("Unknown types = \r\n" +
                                     $"{string.Join("\r\n", VersionManifestParser.UnknownTypes.ToList())}");

            var modService    = new ModService();
            var modCollection = modService.LoadModCollectionFromDirectory(sourceDirectory);

            modService.PublishLoadResults(modCollection);

            /*var typeUnion = VersionManifestParser.AllTypes;
             * modCollection.Mods.SelectMany(mod => mod.ManifestEntryGroups.Select(group => group.Type)).Distinct()
             *  .ToList().ForEach(s => typeUnion.Add(s));
             * var sortedTypes = typeUnion.ToList();
             * sortedTypes.Sort(string.CompareOrdinal);
             * var typeEnumString = TypeEnumGenerator.GenerateEnum(
             *  sortedTypes,
             *  "",
             *  "GameObjectTypeEnum"
             * );
             *
             * System.Console.WriteLine("Generated Type Enum:\r\n" +
             *                       $"{typeEnumString}");*/

            modCollection.ExpandManifestGroups();

            var result = ModMerger.Merge(manifest, modCollection);

            System.Console.WriteLine("Failed Merges : \r\n" +
                                     $"{string.Join("\r\n", ModMerger.FailedMerges.Select(tuple => $"{tuple.Item1.FileInfo.FullName} - {tuple.Item2}"))}");

            /*var objectsWithStatusEffects = result.mergedManifestEntries.Where(entry =>
             * {
             *  if (entry.GameObjectType == GameObjectTypeEnum.Prefab || !entry.FileInfo.Extension.Contains("json"))
             *  {
             *      return false;
             *  }
             *
             *  var statusEffects = entry.Json["statusEffects"];
             *  if (statusEffects == null)
             *  {
             *      return false;
             *  }
             *
             *  if (!(statusEffects is JArray))
             *  {
             *      if (statusEffects.Type != JTokenType.Null)
             *      {
             *          return true;
             *      }
             *
             *      return false;
             *  }
             *
             *  statusEffects = (JArray) statusEffects;
             *  foreach (var statusEffect in statusEffects)
             *  {
             *      var description = statusEffect["Description"];
             *      if (description == null)
             *      {
             *          return true;
             *      }
             *
             *      var id = description["Id"];
             *      if (id == null)
             *      {
             *          return true;
             *      }
             *  }
             *
             *  return false;
             * });*/

            ContentExtractors.GenerateStoreContentList(result.mergedManifestEntries, @"C:\tmp\",
                                                       @"test-xlrp-store-content.xlsx");
            // ContentExtractors.GenerateTacticalContentList(result.mergedManifestEntries, @"C:\tmp\", @"content.xlsx");

            /*var planetTags = PlanetTagEnumerator.EnumeratePlanetTags(result.mergedManifestEntries);
             * planetTags.GroupBy(tag => tag.category, tag => tag.value, (category, tags) => new {category = category, tags = tags}).ToList().ForEach(tagGroup =>
             * {
             *  System.Console.WriteLine($"-----{tagGroup.category}");
             *  System.Console.WriteLine(string.Join("\r\n", tagGroup.tags));
             * });*/

            //System.Console.WriteLine(string.Join("\r\n", );

            /*System.Console.WriteLine($"Objects with JObject statusEffects, status effects with NULL descriptions or description.IDs:\r\n" +
             *                       $"{string.Join("\r\n", objectsWithStatusEffects.Select(entry => entry.FileInfo.FullName))}");*/

            //var ablities = result.mergedManifestEntries.Where(entry => entry.GameObjectType == GameObjectTypeEnum.AbilityDef).ToList();
            //var bad_abilities = ablities.Where(entry => entry.Json["Description"] == null || entry.Json["Description"].ToString() == string.Empty).ToList();

            /*var modifiedIds = result.manifestEntryStackById.Where(pair => pair.Value.Count > 1);
             * System.Console.WriteLine($"Ids modified multiple times via modifications:\r\n" +
             *                       $"{string.Join("\r\n", modifiedIds.Select(pair => $"\t{pair.Key} - {pair.Value.Count}"))}");*/

            /*var weapons = result.mergedManifestEntries.Where(entry => entry.GameObjectType == GameObjectTypeEnum.WeaponDef).Select(entry => WeaponBase.FromJson(entry.Json.ToString())).ToList();
             * weapons.Sort((weapon1, weapon2) => string.CompareOrdinal(weapon1.Description.Id, weapon2.Description.Id));
             * using (var file = File.CreateText(@"c:\tmp\btms-weapons.csv"))
             * {
             *  file.WriteLine($"Description.Id|Category|AttackRecoil|weapon.AccuracyModifier|weapon.AmmoCategory|weapon.AoeCapable|" +
             *                 $"weapon.BonusValueA|weapon.BonusValueB|weapon.CanExplode|weapon.Category|weapon.CriticalChanceMultiplier|" +
             *                 $"weapon.Damage|weapon.DamageVariance|weapon.EvasiveDamageMultiplier|weapon.EvasivePipsIgnored|weapon.HeatDamage|weapon.HeatGenerated|" +
             *                 $"weapon.IndirectFireCapable|weapon.Instability|weapon.InventorySize|weapon.MaxRange|weapon.MinRange|weapon.OverheatedDamageMultiplier|" +
             *                 $"weapon.ProjectilesPerShot|weapon.RefireModifier|weapon.ShotsWhenFired|weapon.StartingAmmoCapacity|weapon.RangeSplit|" +
             *                 $"weapon.WeaponSubType");
             *  foreach (var weapon in weapons)
             *  {
             *      file.WriteLine($"{weapon.Description.Id}|{weapon.Category}|{weapon.AttackRecoil}|{weapon.AccuracyModifier}|{weapon.AmmoCategory}|{weapon.AoeCapable}|" +
             *                     $"'{weapon.BonusValueA}|'{weapon.BonusValueB}|{weapon.CanExplode}|{weapon.Category}|{weapon.CriticalChanceMultiplier}|" +
             *                     $"{weapon.Damage}|{weapon.DamageVariance}|{weapon.EvasiveDamageMultiplier}|{weapon.EvasivePipsIgnored}|{weapon.HeatDamage}|{weapon.HeatGenerated}|" +
             *                     $"{weapon.IndirectFireCapable}|{weapon.Instability}|{weapon.InventorySize}|{weapon.MaxRange}|{weapon.MinRange}|{weapon.OverheatedDamageMultiplier}|" +
             *                     $"{weapon.ProjectilesPerShot}|{weapon.RefireModifier}|{weapon.ShotsWhenFired}|{weapon.StartingAmmoCapacity}|{string.Join(",", weapon.RangeSplit)}|" +
             *                     $"{weapon.WeaponSubType}");
             *  }
             * }*/

            /*System.Console.WriteLine($"Mechs!\r\n" +
             *                       $"{string.Join("\r\n", result.mergedManifestEntries.Where(entry => entry.GameObjectType == GameObjectTypeEnum.MechDef).Select(entry => entry.Id))}");*/

            /*var weapons = result.mergedManifestEntries.Where(entry => entry.GameObjectType == GameObjectTypeEnum.WeaponDef).Select(entry => $"{entry.Id} - {entry.GameObjectType} - {entry.AssetBundleName}").ToList();
             * weapons.Sort();
             * System.Console.WriteLine("Distinct Weapon Definitions:\r\n" +
             *                       $"{string.Join("\r\n", weapons)}");
             *
             * System.Console.WriteLine($"Mechs!\r\n" +
             *  $"{string.Join("\r\n", result.mergedManifestEntries.Where(entry => entry.GameObjectType == GameObjectTypeEnum.MechDef).Select(entry => entry.Id))}");
             *
             * System.Console.WriteLine($"mechdef_annihilator_ANH-1A\r\n" +
             *                       $"{result.mergedManifestEntries.First(entry => entry.Id == "mechdef_annihilator_ANH-1A").Json}");*/

            System.Console.WriteLine("Press any key to exit...");
            System.Console.ReadKey();
        }
 public PlatformBansController(ModService service)
 {
     _service = service;
 }
示例#23
0
 public ModModule(ModService ser)
 {
     _modService = ser;
 }
示例#24
0
        public static void Main(string[] args)
        {
            args.ToList().ForEach(s =>
            {
                if (!Directory.Exists(s))
                {
                    throw new InvalidProgramException($"Specified directory [{s}] cannot be found.");
                }
            });

            var designsDirectory = args[0];
            var btDirectory      = args[1];
            var dlcDirectory     = args[2];
            var sourceDirectory  = args[3];

            // Load all Battle Engine designs available from the specified directory...
            var designFiles = Directory.EnumerateFiles(designsDirectory, "*.bed", SearchOption.AllDirectories);
            var mechDesigns = new List <MechDesign>();

            designFiles
            .ToList()
            .ForEach(filePath =>
            {
                var mechDesign = MechDesign.MechDesignFromFile(filePath);
                mechDesigns.Add(mechDesign);
            });

            Console.WriteLine($"Processed [{mechDesigns.Count()}] designs...");

            // Load the base HBS BT manifest...
            var manifestService = new ManifestService();
            var manifest        = manifestService.InitManifestFromDisk(btDirectory, dlcDirectory);

            // Load the Mod Collection resources...
            var modService    = new ModService();
            var modCollection = modService.LoadModCollectionFromDirectory(sourceDirectory);

            modService.PublishLoadResults(modCollection);
            modCollection.ExpandManifestGroups();

            // Merge the base manifest with the mod collection resources
            var result      = ModMerger.Merge(manifest, modCollection);
            var groupedData = result.mergedManifestEntries.GroupBy(entry => entry.GameObjectType, entry => entry,
                                                                   (type, entries) => new { GameObjectType = type, objects = entries });

            // Build up a handy-dandy type dictionary from the merged manifests...
            var typeDictionary = groupedData
                                 .ToDictionary(arg => arg.GameObjectType, arg => arg.objects.ToList());

            // Build up a handy-dandy list of mech asset bundles from chassis data...
            var chassisUsedAssetBundles = typeDictionary[GameObjectTypeEnum.ChassisDef]
                                          .Select(entry => entry.Json["PrefabIdentifier"].ToString().ToLower()).Distinct();

            var foundAssetBundles = typeDictionary[GameObjectTypeEnum.AssetBundle].Select(entry => entry.Id.ToLower());

            var unionAssetBundles = chassisUsedAssetBundles.Union(foundAssetBundles).Distinct().ToList();

            // Console.WriteLine(string.Join("\r\n", unionAssetBundles));

            System.Console.WriteLine("Failed Merges : \r\n" +
                                     $"{string.Join("\r\n", ModMerger.FailedMerges.Select(tuple => $"{tuple.Item1.FileInfo.FullName} - {tuple.Item2}"))}");

            var filterEras = new List <Era>()
            {
                Era.Star_League,
                Era.EarlySuccessionWar,
                Era.LateSuccessionWarLosTech,
                Era.LateSuccessionWarRenaissance,
                Era.Clan_Invasion
            };

            var filterTech = new List <TechLevel>()
            {
                TechLevel.IS
            };

            var filterChassisType = new List <ChassisType>()
            {
                ChassisType.Biped
            };

            var filteredDesigns =
                mechDesigns
                .Where(design => design.Eras.Any(data => filterEras.Contains(data.EraDetail.Era)))
                .Where(design => filterTech.Contains(design.TechLevel))
                .Where(design => filterChassisType.Contains(design.ChassisType))
                .ToList();

            Console.WriteLine(
                $"Filtered designs from [{mechDesigns.Count()}] to [{filteredDesigns.Count()}]. Filtering by available asset bundles...");

            var assetFilteredDesigns = filteredDesigns
                                       .Where(design => unionAssetBundles.Any(s =>
                                                                              s.Contains(design.InnerSphereChassisDesignation.ToLower()) ||
                                                                              (!string.IsNullOrEmpty(design.FilthyClanChassisDesignation) && s.Contains(design.FilthyClanChassisDesignation.ToLower()))))
                                       .ToList();

            Console.WriteLine($"Found [{assetFilteredDesigns.Count}] designs with dedicated asset bundles, filtering by chassis defs...");

            var chassisFilteredDesigns = assetFilteredDesigns
                                         .Where(design => typeDictionary[GameObjectTypeEnum.ChassisDef]
                                                .Where(entry => (entry.Id.ToLower().Contains(design.InnerSphereChassisDesignation.ToLower()) ||
                                                                 (!string.IsNullOrEmpty(design.FilthyClanChassisDesignation) &&
                                                                  entry.Id.ToLower().Contains(design.FilthyClanChassisDesignation.ToLower()))))
                                                .Any(entry =>
            {
                var id    = entry.Id.ToLower();
                var parts = id.ToLower().Split('_');
                if (!string.IsNullOrEmpty(design.VariantDesignation) && !parts.Contains(design.VariantDesignation.ToLower()))
                {
                    return(false);
                }

                // Must contain all hero designations if any exist
                var missingHeroDesignations = design.HeroDesignations.Except(parts);
                if (missingHeroDesignations.Any())
                {
                    return(false);
                }

                return(true);
            }))
                                         .ToList();

            Console.WriteLine($"Found [{chassisFilteredDesigns.Count()}] designs with dedicated chassis defs...");
            var outputDirectory = @"c:\tmp\Beds";

            if (Directory.Exists(outputDirectory))
            {
                Directory.Delete(outputDirectory);
            }

            Directory.CreateDirectory(outputDirectory);
            chassisFilteredDesigns.AsParallel().ForAll(design => File.Copy(design.FileInfo.FullName, Path.Combine(outputDirectory, design.FileInfo.Name)));
        }
示例#25
0
        public void ApplyEffects(NWCreature user, NWItem modItem, NWObject target, Location targetLocation, CustomData customData)
        {
            NWPlayer player                = (user.Object);
            NWItem   targetItem            = (target.Object);
            ModSlots slots                 = ModService.GetModSlots(targetItem);
            CustomItemPropertyType modType = ModService.GetModType(modItem);
            int modID = modItem.GetLocalInt("RUNE_ID");

            string[] modArgs       = modItem.GetLocalString("RUNE_VALUE").Split(',');
            int      modLevel      = modItem.RecommendedLevel;
            int      levelIncrease = modItem.LevelIncrease;

            var mod = ModService.GetModHandler(modID);

            mod.Apply(player, targetItem, modArgs);

            string description  = mod.Description(player, targetItem, modArgs);
            bool   usePrismatic = false;

            switch (modType)
            {
            case CustomItemPropertyType.RedMod:
                if (slots.FilledRedSlots < slots.RedSlots)
                {
                    targetItem.SetLocalInt("MOD_SLOT_RED_" + (slots.FilledRedSlots + 1), modID);
                    targetItem.SetLocalString("MOD_SLOT_RED_DESC_" + (slots.FilledRedSlots + 1), description);
                    player.SendMessage("Mod installed into " + ColorTokenService.Red("red") + " slot #" + (slots.FilledRedSlots + 1));
                }
                else
                {
                    usePrismatic = true;
                }
                break;

            case CustomItemPropertyType.BlueMod:
                if (slots.FilledBlueSlots < slots.BlueSlots)
                {
                    targetItem.SetLocalInt("MOD_SLOT_BLUE_" + (slots.FilledBlueSlots + 1), modID);
                    targetItem.SetLocalString("MOD_SLOT_BLUE_DESC_" + (slots.FilledBlueSlots + 1), description);
                    player.SendMessage("Mod installed into " + ColorTokenService.Blue("blue") + " slot #" + (slots.FilledBlueSlots + 1));
                }
                else
                {
                    usePrismatic = true;
                }
                break;

            case CustomItemPropertyType.GreenMod:
                if (slots.FilledBlueSlots < slots.GreenSlots)
                {
                    targetItem.SetLocalInt("MOD_SLOT_GREEN_" + (slots.FilledGreenSlots + 1), modID);
                    targetItem.SetLocalString("MOD_SLOT_GREEN_DESC_" + (slots.FilledGreenSlots + 1), description);
                    player.SendMessage("Mod installed into " + ColorTokenService.Green("green") + " slot #" + (slots.FilledGreenSlots + 1));
                }
                else
                {
                    usePrismatic = true;
                }
                break;

            case CustomItemPropertyType.YellowMod:
                if (slots.FilledBlueSlots < slots.YellowSlots)
                {
                    targetItem.SetLocalInt("MOD_SLOT_YELLOW_" + (slots.FilledYellowSlots + 1), modID);
                    targetItem.SetLocalString("MOD_SLOT_YELLOW_DESC_" + (slots.FilledYellowSlots + 1), description);
                    player.SendMessage("Mod installed into " + ColorTokenService.Yellow("yellow") + " slot #" + (slots.FilledYellowSlots + 1));
                }
                else
                {
                    usePrismatic = true;
                }
                break;
            }

            if (usePrismatic)
            {
                string prismaticText = ModService.PrismaticString();
                targetItem.SetLocalInt("MOD_SLOT_PRISMATIC_" + (slots.FilledPrismaticSlots + 1), modID);
                targetItem.SetLocalString("MOD_SLOT_PRISMATIC_DESC_" + (slots.FilledPrismaticSlots + 1), description);
                player.SendMessage("Mod installed into " + prismaticText + " slot #" + (slots.FilledPrismaticSlots + 1));
            }

            targetItem.RecommendedLevel += levelIncrease;
            modItem.Destroy();

            SkillType skillType;

            if (ArmorBaseItemTypes.Contains(targetItem.BaseItemType))
            {
                skillType = SkillType.Armorsmith;
            }
            else if (WeaponsmithBaseItemTypes.Contains(targetItem.BaseItemType))
            {
                skillType = SkillType.Weaponsmith;
            }
            else if (EngineeringBaseItemTypes.Contains(targetItem.BaseItemType))
            {
                skillType = SkillType.Engineering;
            }
            else
            {
                return;
            }

            int rank = SkillService.GetPCSkillRank(player, skillType);
            int xp   = (int)SkillService.CalculateRegisteredSkillLevelAdjustedXP(400, modLevel, rank);

            SkillService.GiveSkillXP(player, skillType, xp);
        }
示例#26
0
        public string IsValidTarget(NWCreature user, NWItem mod, NWObject target, Location targetLocation)
        {
            if (target.ObjectType != OBJECT_TYPE_ITEM)
            {
                return("Only items may be targeted by mods.");
            }
            if (!user.IsPlayer)
            {
                return("Only players may use mods.");
            }
            NWPlayer player     = (user.Object);
            NWItem   targetItem = (target.Object);

            int modLevel          = mod.RecommendedLevel;
            int itemLevel         = targetItem.RecommendedLevel;
            int requiredPerkLevel = modLevel / 5;

            if (requiredPerkLevel <= 0)
            {
                requiredPerkLevel = 1;
            }
            int perkLevel = 0;
            CustomItemPropertyType modType = ModService.GetModType(mod);
            ModSlots modSlots = ModService.GetModSlots(targetItem);
            int      modID    = mod.GetLocalInt("RUNE_ID");

            string[] modArgs = mod.GetLocalString("RUNE_VALUE").Split(',');

            // Check for a misconfigured mod item.
            if (modType == CustomItemPropertyType.Unknown)
            {
                return("Mod color couldn't be found. Notify an admin that this mod item is not set up properly.");
            }
            if (modID <= 0)
            {
                return("Mod ID couldn't be found. Notify an admin that this mod item is not set up properly.");
            }
            if (modArgs.Length <= 0)
            {
                return("Mod value couldn't be found. Notify an admin that this mod item is not set up properly.");
            }

            // No available slots on target item
            if (modType == CustomItemPropertyType.RedMod && !modSlots.CanRedModBeAdded)
            {
                return("That item has no available red mod slots.");
            }
            if (modType == CustomItemPropertyType.BlueMod && !modSlots.CanBlueModBeAdded)
            {
                return("That item has no available blue mod slots.");
            }
            if (modType == CustomItemPropertyType.GreenMod && !modSlots.CanGreenModBeAdded)
            {
                return("That item has no available green mod slots.");
            }
            if (modType == CustomItemPropertyType.YellowMod && !modSlots.CanYellowModBeAdded)
            {
                return("That item has no available yellow mod slots.");
            }

            // Get the perk level based on target item type and mod type.
            if (WeaponsmithBaseItemTypes.Contains(targetItem.BaseItemType))
            {
                switch (modType)
                {
                case CustomItemPropertyType.RedMod:
                    perkLevel = PerkService.GetPCPerkLevel(player, PerkType.CombatModInstallationWeapons);
                    break;

                case CustomItemPropertyType.BlueMod:
                    perkLevel = PerkService.GetPCPerkLevel(player, PerkType.ForceModInstallationWeapons);
                    break;

                case CustomItemPropertyType.GreenMod:
                    perkLevel = PerkService.GetPCPerkLevel(player, PerkType.CraftingModInstallationWeapons);
                    break;

                case CustomItemPropertyType.YellowMod:
                    perkLevel = PerkService.GetPCPerkLevel(player, PerkType.SpecialModInstallationWeapons);
                    break;

                default:
                    perkLevel = 0;
                    break;
                }
            }
            else if (ArmorBaseItemTypes.Contains(targetItem.BaseItemType))
            {
                switch (modType)
                {
                case CustomItemPropertyType.RedMod:
                    perkLevel = PerkService.GetPCPerkLevel(player, PerkType.CombatModInstallationArmors);
                    break;

                case CustomItemPropertyType.BlueMod:
                    perkLevel = PerkService.GetPCPerkLevel(player, PerkType.ForceModInstallationArmors);
                    break;

                case CustomItemPropertyType.GreenMod:
                    perkLevel = PerkService.GetPCPerkLevel(player, PerkType.CraftingModInstallationArmors);
                    break;

                case CustomItemPropertyType.YellowMod:
                    perkLevel = PerkService.GetPCPerkLevel(player, PerkType.SpecialModInstallationArmors);
                    break;

                default:
                    perkLevel = 0;
                    break;
                }
            }
            else if (EngineeringBaseItemTypes.Contains(targetItem.BaseItemType))
            {
                switch (modType)
                {
                case CustomItemPropertyType.RedMod:
                    perkLevel = PerkService.GetPCPerkLevel(player, PerkType.CombatModInstallationEngineering);
                    break;

                case CustomItemPropertyType.BlueMod:
                    perkLevel = PerkService.GetPCPerkLevel(player, PerkType.ForceModInstallationEngineering);
                    break;

                case CustomItemPropertyType.GreenMod:
                    perkLevel = PerkService.GetPCPerkLevel(player, PerkType.CraftingModInstallationEngineering);
                    break;

                case CustomItemPropertyType.YellowMod:
                    perkLevel = PerkService.GetPCPerkLevel(player, PerkType.SpecialModInstallationEngineering);
                    break;

                default:
                    perkLevel = 0;
                    break;
                }
            }

            // Ensure item isn't equipped.
            for (int slot = 0; slot < NUM_INVENTORY_SLOTS; slot++)
            {
                if (_.GetItemInSlot(slot, user.Object) == targetItem.Object)
                {
                    return("Targeted item must be unequipped before installing a mod.");
                }
            }

            // Check for perk level requirement
            if (perkLevel < requiredPerkLevel)
            {
                return("You do not have the necessary perk rank required. (Required: " + requiredPerkLevel + ", Your level: " + perkLevel + ")");
            }

            // Can't modify items above perk level * 10
            if (itemLevel > perkLevel * 10)
            {
                return("Your current perks allow you to add mods to items up to level " + perkLevel * 10 + ". This item is level " + itemLevel + " so you can't install a mod into it.");
            }

            // Item must be in the user's inventory.
            if (!targetItem.Possessor.Equals(player))
            {
                return("Targeted item must be in your inventory.");
            }

            var handler = ModService.GetModHandler(modID);

            // Run the individual mod's rules for application. Will return the error message or a null.
            return(handler.CanApply(player, targetItem, modArgs));
        }
 public ModActionController(ModService service)
 {
     _service = service;
 }
示例#28
0
        public string IsValidTarget(NWCreature user, NWItem mod, NWObject target, Location targetLocation)
        {
            if (target.ObjectType != ObjectType.Item)
            {
                return("Only items may be targeted by mods.");
            }
            if (!user.IsPlayer && !user.IsDM)
            {
                return("Only players may use mods.");
            }
            NWPlayer player     = (user.Object);
            NWItem   targetItem = (target.Object);

            int modLevel          = mod.RecommendedLevel;
            int itemLevel         = targetItem.RecommendedLevel;
            int requiredPerkLevel = modLevel / 5;

            if (requiredPerkLevel <= 0)
            {
                requiredPerkLevel = 1;
            }
            int perkLevel             = 0;
            ItemPropertyType modType  = ModService.GetModType(mod);
            ModSlots         modSlots = ModService.GetModSlots(targetItem);
            int modID = mod.GetLocalInt("RUNE_ID");

            string[] modArgs = mod.GetLocalString("RUNE_VALUE").Split(',');

            // Check for a misconfigured mod item.
            if (modType == ItemPropertyType.Invalid)
            {
                return("Mod color couldn't be found. Notify an admin that this mod item is not set up properly.");
            }
            if (modID <= 0)
            {
                return("Mod ID couldn't be found. Notify an admin that this mod item is not set up properly.");
            }
            if (modArgs.Length <= 0)
            {
                return("Mod value couldn't be found. Notify an admin that this mod item is not set up properly.");
            }

            // No available slots on target item
            if (modType == ItemPropertyType.RedMod && !modSlots.CanRedModBeAdded)
            {
                return("That item has no available red mod slots.");
            }
            if (modType == ItemPropertyType.BlueMod && !modSlots.CanBlueModBeAdded)
            {
                return("That item has no available blue mod slots.");
            }
            if (modType == ItemPropertyType.GreenMod && !modSlots.CanGreenModBeAdded)
            {
                return("That item has no available green mod slots.");
            }
            if (modType == ItemPropertyType.YellowMod && !modSlots.CanYellowModBeAdded)
            {
                return("That item has no available yellow mod slots.");
            }

            // Get the perk level based on target item type and mod type.
            if (GetLocalBool(targetItem, "LIGHTSABER") == false && WeaponsmithBaseItemTypes.Contains(targetItem.BaseItemType))
            {
                perkLevel = PerkService.GetCreaturePerkLevel(player, PerkType.WeaponModInstallation);
            }
            else if (ArmorBaseItemTypes.Contains(targetItem.BaseItemType))
            {
                perkLevel = PerkService.GetCreaturePerkLevel(player, PerkType.ArmorModInstallation);
            }
            else if (GetLocalBool(targetItem, "LIGHTSABER") == true || EngineeringBaseItemTypes.Contains(targetItem.BaseItemType))
            {
                perkLevel = PerkService.GetCreaturePerkLevel(player, PerkType.EngineeringModInstallation);
            }

            // Ensure item isn't equipped.
            for (int slot = 0; slot < NumberOfInventorySlots; slot++)
            {
                if (_.GetItemInSlot((InventorySlot)slot, user.Object) == targetItem.Object)
                {
                    return("Targeted item must be unequipped before installing a mod.");
                }
            }

            // Check for perk level requirement
            if (perkLevel < requiredPerkLevel && !player.IsDM)
            {
                return("You do not have the necessary perk rank required. (Required: " + requiredPerkLevel + ", Your level: " + perkLevel + ")");
            }

            // Can't modify items above perk level * 10
            if (itemLevel > perkLevel * 10 && !player.IsDM)
            {
                return("Your current perks allow you to add mods to items up to level " + perkLevel * 10 + ". This item is level " + itemLevel + " so you can't install a mod into it.");
            }

            // Item must be in the user's inventory.
            if (!targetItem.Possessor.Equals(player))
            {
                return("Targeted item must be in your inventory.");
            }

            // It's possible that this mod is no longer usable. Notify the player if we can't find one registered.
            if (!ModService.IsModHandlerRegistered(modID))
            {
                return("Unfortunately, this mod can no longer be used.");
            }

            var handler = ModService.GetModHandler(modID);

            // Run the individual mod's rules for application. Will return the error message or a null.
            return(handler.CanApply(player, targetItem, modArgs));
        }
示例#29
0
 public ModModule(ModService modService)
 {
     _modService = modService;
 }