Иконка ресурса

FREE CraftingPanel : 1.2.10 1.2.10

Нет прав для скачивания
C#:
// Все права принадлежат дискорд сообществу https://discord.gg/VgNHPpNrz6
using Facepunch.Extend;
using Newtonsoft.Json;
using Oxide.Core.Plugins;
using Oxide.Core;
using Oxide.Game.Rust.Cui;
using Oxide.Game.Rust;
using System.Collections.Generic;
using System.Collections;
using System.Globalization;
using System.Linq;
using System.Text;
using System;
using Time = UnityEngine.Time;
using UnityEngine;
using VLB;
namespace Oxide.Plugins {
    [Info("CraftingPanel", "MTriper", "1.2.10")]
    [Description("A beautiful and convenient crafting panel, it's design and mechanics are similar to the in-game Rust crafting panel.")]
    class CraftingPanel : RustPlugin {
#region Fields
        [PluginReference]
        Plugin ImageLibrary, ItemRetriever, Backpacks, Notify, GUIAnnouncements, SimpleStatus, AdvancedStatus, Economics, ServerRewards, IQEconomic, SkillTree, ZLevelsRemastered;
        CraftingPanelConfig config;
        Coroutine configCheck = null;
        Coroutine additionalLang = null;
        Dictionary<string, UserData> data;
        ItemBlueprint[] dlcItems;
        static CraftingPanel ins;
        const bool isRus = false;
        private bool readyToWork = false;
#endregion
#region Config
        class CraftingPanelConfig {
            [JsonProperty(isRus ? "Команда для открытия панели" : "Command to open the craft panel")]
            public string command = "craft";
            [JsonProperty(isRus ? "Разрешить масштабирование панели при изменении размера интерфейса?" : "Allow panel scaling when the interface is scaled?")]
            public bool canScale = false;
            [JsonProperty(isRus ? "Закрывать панель после начала крафта?" : "Close the panel after starting craft?")]
            public bool closeAfterCraft = false;
            [JsonProperty(isRus ? "Запоминать последний выбранный раздел и предмет?" : "Remember the last selected section and item?")]
            public bool saveLastItem = true;
            [JsonProperty(isRus ? "Включить многоязычный режим?" : "Enable multilingual mode?")]
            public bool multilingualMode= false;
            [JsonProperty(isRus ? "Разрешить работать с плагином Backpacks?" : "Allow work with the Backpacks plugin?")]
            public bool useBackpacks = true;
            [JsonProperty(isRus ? "Разрешить работать с плагином ItemRetriever?" : "Allow work with the ItemRetriever plugin?")]
            public bool useItemRetriever = true;
            [JsonProperty(isRus ? "Удалять данные игроков из Data, если они не заходили на сервер столько дней" : "Delete player data from the Data file if they have not logged into the server for so many days")]
            public int lastSeenDays = 182;
            [JsonProperty(isRus ? "Эффект при начале крафта [пусто - ничего]" : "Effect at the start of crafting [empty - nothing]")]
            public string effectStart = "assets/prefabs/misc/xmas/snowballgun/effects/reload_start.prefab";
            [JsonProperty(isRus ? "Эффект при выдаче предмета [пусто - ничего]" : "Effect at the end of crafting [empty - nothing]")]
            public string effectFinish = "assets/prefabs/misc/xmas/presents/effects/wrap.prefab";
            [JsonProperty(isRus ? "Эффект при отмене крафта [пусто - ничего]" : "Effect of canceling the craft [empty - nothing]")]
            public string effectCancel = "assets/prefabs/instruments/xylophone/effects/xylophone-deploy.prefab";
            [JsonProperty(isRus ? "Укажите плагин для работы с экономикой (ServerRewards, Economics, IQEconomic) [пусто - отключить]" : "Specify a plugin to work with the economy (ServerRewards, Economics, IQEconomic) [empty - disable]")]
            public string economyType = string.Empty;
            [JsonProperty(isRus ? "Настройка бонусов крафта" : "Crafting bonuses")]
            public CraftingBonuses craftingBonuses = new CraftingBonuses();
            [JsonProperty(isRus ? "Настройка уведомлений плагина" : "Plugin notifications")]
            public Notification notify = new Notification();
            [JsonProperty(isRus ? "Настройка игрового статуса" : "Game status")]
            public GameStatus status = new GameStatus();
            [JsonProperty(isRus ? "Разделы" : "Sections", ObjectCreationHandling = ObjectCreationHandling.Replace)]
            public List<Section> sections = new List<Section> {
                new Section {
                    name = isRus ? "Избранное" : "Favorite", permission = "favorite", permissionIsActivate = true, img = "https://i.postimg.cc/43jc0tWp/favorite.png"
                }
                , new Section {
                    name = isRus ? "Предметы" : "Items", permission = "items", img = "https://i.postimg.cc/kGbJ85TZ/items.png", items = {
                        new SectionItem {
                            name = isRus ? "Нож для трофеев" : "Skinning Knife", permission = "skinningknife", description = isRus ? "Острый нож для снятия шкур.Чрезвычайно хорош в добыче мяса и может производить трофеи, которые можно установить на охотничьи трофеи." : "A sharp skinning knife.Extremely good at harvesting flesh and can produce trophies that can be mounted on Hunting Trophies.", shortname = "knife.skinning", properties = isRus ? "Урон   20\nСкорость   86\nРадиус атаки   0.3\nДальность   1.5\nДобыча мяса   18" : "Damage   20\nAttack Speed   86\nAttack Size   0.3\nRange   1.5\nFlesh Gather   18", time = 5.2f, ingredients = {
                                new Ingredient {
                                    name = isRus ? "Фрагменты металла" : "Metal fragments", shortname = "metal.fragments", amount = 75
                                }
                            }
                        }
                        , new SectionItem {
                            name = isRus ? "Водолазный костюм бездны" : "Abyss Diver Suit", permission = "hazmatdiver", description = isRus ? "Водолазный костюм, найденный в бездне, также служит надежным антирадиационным костюмом." : "A divers suit found in the abyss, doubles as a reliable hazmat suit.", shortname = "hazmatsuit.diver", properties = isRus ? "Огнестрел   +30 %\nБлижний бой   +30 %\nУкус   +8 %\nРадиация   +50 %\nХолод   +8 %\nВзрыв   +5 %" : "Projectile   +30 %\nMelee   +30 %\nBite   +8 %\nRadiation   +50 %\nCold   +8 %\nExplosion   +5 %", time = 0, workbench = 2, ingredients = {
                                new Ingredient {
                                    name = isRus ? "Ткань" : "Cloth", shortname = "cloth", amount = 20
                                }
                                , new Ingredient {
                                    name = isRus ? "Топливо низкого качества" : "Low Grade Fuel", shortname = "lowgradefuel", amount = 5
                                }
                            }
                        }
                    }
                }
                , new Section {
                    name = isRus ? "Трансопрт" : "Vehicles", permission = "vehicles", img = "https://i.postimg.cc/HsrtYbkp/vehicles.png", items = {
                        new SectionItem {
                            name = isRus ? "Миникоптер" : "Minicopter", permission = "minicopter", description = isRus ? "Миникоптер представляет собой небольшой вертолет, изготовленный из сломанных деталей." : "The Minicopter is a small helicopter made from scrapped parts.", shortname = "box.wooden.large", activPermission = true, useDefaultName = false, skinId = 2663605922, time = 30, workbench = 3, economicPrice = 500, ingredients = {
                                new Ingredient {
                                    name = isRus ? "Металлолом" : "Scrap", shortname = "scrap", amount = 300
                                }
                                , new Ingredient {
                                    name = isRus ? "Фрагменты металла" : "Metal fragments", shortname = "metal.fragments", amount = 450
                                }
                                , new Ingredient {
                                    name = isRus ? "Топливо низкого качества" : "Low Grade Fuel", shortname = "lowgradefuel", amount = 50
                                }
                            }
                        }
                        , new SectionItem {
                            name = isRus ? "Снегоход" : "Snowmobile", permission = "snowmobile", description = isRus ? "Наземное транспортное средство, быстро передвигается по песку и снегу.Появляется на арктической лаборатории.Имеет небольшой инвентарь сзади." : "The snowmobile is a two-seat vehicle that spawns at the Arctic Research Base.", img = "https://i.postimg.cc/VvVjGQVy/snowmobile.png", workbench = 3, time = 12, command = "givesnowmobile %steamid% %amount%", ingredients = {
                                new Ingredient {
                                    name = isRus ? "Металлолом" : "Scrap", shortname = "scrap", amount = 300
                                }
                                , new Ingredient {
                                    name = isRus ? "Фрагменты металла" : "Metal fragments", shortname = "metal.fragments", amount = 450
                                }
                                , new Ingredient {
                                    name = isRus ? "Топливо низкого качества" : "Low Grade Fuel", shortname = "lowgradefuel", amount = 50
                                }
                            }
                        }
                    }
                }
                , new Section {
                    name = isRus ? "Лунный НГ" : "Lunar NY", permission = "lunar", img = "https://i.postimg.cc/Fz1hz3G4/lunarNY.png", items = new List<SectionItem> {
                        new SectionItem {
                            name = isRus ? "Небесный фонарик" : "Sky Lantern", permission = "skylantern", description = isRus ? "Красивый небесный фонарь.Может быть запущен в любом направлении.Содержит один слот.Может быть зажжен с помощью факела." : "A beautiful sky lantern.Can be launched in any direction.Has one inventory slot.Can be Ignited with a lit torch.", shortname = "skylantern", time = 5, amount = 2, maxAmount = 5, itemSkins = {
                                new ItemSkin {
                                    name = isRus ? "ЗЕЛЕНЫЙ" : "GREEN", permission = "green", shortname = "skylantern.skylantern.green"
                                }
                                , new ItemSkin {
                                    name = isRus ? "ОРАНЖЕВЫЙ" : "ORANGE", permission = "orange", shortname = "skylantern.skylantern.orange"
                                }
                                , new ItemSkin {
                                    name = isRus ? "ФИОЛЕТОВЫЙ" : "PURPLE", activPermission = true, permission = "purple", shortname = "skylantern.skylantern.purple"
                                }
                                , new ItemSkin {
                                    name = isRus ? "КРАСНЫЙ" : "RED", permission = "red", shortname = "skylantern.skylantern.red"
                                }
                            }
                            , ingredients = new List<Ingredient> {
                                new Ingredient {
                                    name = isRus ? "Ткань" : "Cloth", shortname = "cloth", amount = 10
                                }
                                , new Ingredient {
                                    name = isRus ? "Топливо низкого качества" : "Low Grade Fuel", shortname = "lowgradefuel", amount = 5
                                }
                            }
                        }
                        , new SectionItem {
                            name = isRus ? "Новогодний гонг" : "New Year Gong", permission = "newyeargong", description = isRus ? "Встречайте Лунный Новый Год с массивным гонгом!" : "Ring in the Lunar new year with a massive gong!", activPermission = true, shortname = "newyeargong", time = 5, maxAmount = 3, workbench = 1, ingredients = new List<Ingredient> {
                                new Ingredient {
                                    name = isRus ? "Дерево" : "Wood", shortname = "wood", amount = 100
                                }
                                , new Ingredient {
                                    name = isRus ? "Фрагменты металла" : "Metal fragments", shortname = "metal.fragments", amount = 50
                                }
                            }
                        }
                    }
                }
            }
            ;
        }
        class Section {
            [JsonIgnore]
            public string jsonReadyItems;
            [JsonProperty(isRus ? "Название раздела" : "Section name")]
            public string name;
            [JsonProperty(isRus ? "Включить раздел?" : "Enable this section?")]
            public bool isEnable = true;
            [JsonProperty(isRus ? "Permission раздела [обязательно]" : "Section permission [required]")]
            public string permission;
            [JsonProperty(isRus ? "Регистрировать эту permission?" : "Register this permission?")]
            public bool permissionIsActivate;
            [JsonProperty(isRus ? "Иконка раздела" : "Section icon")]
            public string img;
            [JsonProperty(isRus ? "Предметы раздела" : "Section items")]
            public List<SectionItem> items = new List<SectionItem>();
        }
        class SectionItem {
            [JsonIgnore]
            public string parentSection = string.Empty;
            [JsonProperty(isRus ? "Название предмета [обязательно]" : "Item name [required]")]
            public string name = string.Empty;
            [JsonProperty(isRus ? "Включить крафт этого предмета?" : "Enable crafting of this item?")]
            public bool isEnable = true;
            [JsonProperty(isRus ? "Permission предмета [обязательно]" : "Item permission [required]")]
            public string permission = string.Empty;
            [JsonProperty(isRus ? "Регистрировать эту permission?" : "Register this permission?")]
            public bool activPermission = false;
            [JsonProperty(isRus ? "Описание предмета" : "Item description")]
            public string description = string.Empty;
            [JsonProperty(isRus ? "Параметры предмета" : "Item properties")]
            public string properties = string.Empty;
            [JsonProperty(isRus ? "Shortname предмета" : "Item shortname")]
            public string shortname = string.Empty;
            [JsonProperty(isRus ? "SkinID предмета" : "Item skinId")]
            public ulong skinId = 0;
            [JsonProperty(isRus ? "Это чертеж?" : "Is this a blueprint? ")]
            public bool isBlueprint = false;
            [JsonProperty(isRus ? "Создавать предмет со стандартным названием (true) или указанным сверху (false)?" : "Create an item with the default name (true) or the above name (false)?")]
            public bool useDefaultName = true;
            [JsonProperty(isRus ? "Изображение предмета [необязательно]" : "Item image [optional]")]
            public string img = string.Empty;
            [JsonProperty(isRus ? "Консольные команды выполняемые после крафта (%steamid%, %username%, %amount%) [необязательно]" : "Console commands executed after crafting (%steamid%, %username%, %amount%) [optional]")]
            public string command = string.Empty;
            [JsonProperty(isRus ? "Выдаваемое количество при крафте" : "Amount per craft")]
            public int amount = 1;
            [JsonProperty(isRus ? "Максимальный множитель крафта" : "Max craft multiplier")]
            public int maxAmount = 1;
            [JsonProperty(isRus ? "Время крафта [сек]" : "Crafting time [sec]")]
            public float time = 5f;
            [JsonProperty(isRus ? "Показывать уведомление в статус баре (если они включены)?" : "Show notification in game status (if they are enabled)?")]
            public bool showStatus = true;
            [JsonProperty(isRus ? "Применять бонусы крафта (если они включены)?" : "Apply craft bonuses (if they are enabled)?")]
            public bool canUseBonuses = true;
            [JsonProperty(isRus ? "Уровень верстака [0 - не нужен]" : "Workbench level [0 - not needed]")]
            public int workbench = 0;
            [JsonProperty(isRus ? "Стоимость крафта в плагине экономики [0 - отключено]" : "Crafting cost in the economy plugin [0 - disable]")]
            public int economicPrice = 0;
            [JsonProperty(isRus ? "Исполнения предмета" : "Item variations")]
            public List<ItemSkin> itemSkins = new List<ItemSkin>();
            [JsonProperty(isRus ? "Ингредиенты для крафта" : "Crafting ingredients")]
            public List<Ingredient> ingredients = new List<Ingredient>();
        }
        class Ingredient {
            [JsonProperty(isRus ? "Название ресурса [обязательно]" : "Resource name [required]")]
            public string name;
            [JsonProperty(isRus ? "Использовать этот ресурс в ингредиентах?" : "Use this resource in ingredients?")]
            public bool isEnable = true;
            [JsonProperty(isRus ? "Shortname ресурса [обязательно]" : "Resource shortname [required]")]
            public string shortname;
            [JsonProperty(isRus ? "SkinID ресурса" : "Resource skinId")]
            public ulong skinId = 0;
            [JsonProperty(isRus ? "Необходимое количество для крафта" : "Required quantity for crafting")]
            public int amount = 1;
            [JsonProperty(isRus ? "Возвращать предмет со стандартным названием (true) или указанным сверху (false)?" : "Return an item with the default name (true) or the above name (false)?")]
            public bool useDefaultName = true;
        }
        class ItemSkin {
            [JsonProperty(isRus ? "Название предмета [обязательно]" : "Item name [required]")]
            public string name = string.Empty;
            [JsonProperty(isRus ? "Включить крафт этого предмета?" : "Enable crafting of this item?")]
            public bool isEnable = true;
            [JsonProperty(isRus ? "Permission предмета [обязательно]" : "Item permission [required]")]
            public string permission = string.Empty;
            [JsonProperty(isRus ? "Регистрировать эту permission?" : "Register this permission?")]
            public bool activPermission = false;
            [JsonProperty(isRus ? "Shortname предмета" : "Item shortname")]
            public string shortname = string.Empty;
            [JsonProperty(isRus ? "SkinID предмета" : "Item skinId")]
            public ulong skinId = 0;
            [JsonProperty(isRus ? "Это чертеж?" : "Is this a blueprint? ")]
            public bool isBlueprint = false;
            [JsonProperty(isRus ? "Создавать предмет со стандартным названием (true) или указанным сверху (false)?" : "Create an item with the default name (true) or the above name (false)?")]
            public bool useDefaultName = true;
            [JsonProperty(isRus ? "Изображение предмета [необязательно]" : "Item image [optional]")]
            public string img = string.Empty;
            [JsonProperty(isRus ? "Консольные команды выполняемые после крафта (%steamid%, %username%, %amount%) [необязательно]" : "Console commands executed after crafting (%steamid%, %username%, %amount%) [optional]")]
            public string command = string.Empty;
        }
        class CraftingBonuses {
            [JsonProperty(isRus ? "Включить бонусы крафта?" : "Enable crafting bonuses?")]
            public bool isEnable = false;
            [JsonProperty(isRus ? "Укажите плагин для работы с бонусами (SkillTree, ZLevelsRemastered)" : "Specify a plugin to work with bonuses (SkillTree, ZLevelsRemastered)")]
            public string type = "SkillTree";
            [JsonProperty(isRus ? "Сколько выдавать опыта за крафт" : "Amount of experience given for crafting")]
            public float addXP = 0.25f;
            [JsonProperty(isRus ? "Сколько забирать опыта за отмену крафта" : "Amount of experience taken away for canceling the craft")]
            public float removeXP = 0.05f;
            [JsonProperty(isRus ? "Размер опыта будет зависеть от времени крафта?" : "Amount of experience will depend on crafting time?")]
            public bool basedOnTime = true;
            [JsonProperty(isRus ? "Иконка для сообщений в чате (из конфига используемого плагина) [0 - стандартная]" : "Icon for chat messages (from config of plugin used) [0 - default]")]
            public ulong chatId = 76561199514393612;
            [JsonProperty(isRus ? "SkillTree: использовать бафф Craft_Speed?" : "SkillTree: use Craft_Speed buff?")]
            public bool STCanUseCraftSpeed = true;
            [JsonProperty(isRus ? "SkillTree: использовать бафф Craft_Refund?" : "SkillTree: use Craft_Refund buff?")]
            public bool STCanUseCraftRefund = true;
            [JsonProperty(isRus ? "SkillTree: использовать бафф Craft_Duplicate?" : "SkillTree: use Craft_Duplicate buff?")]
            public bool STCanUseCraftDuplicate = true;
            [JsonProperty(isRus ? "ZLevelsRemastered: использовать бафф к скорости крафта?" : "ZLevelsRemastered: use the crafting speed buff?")]
            public bool ZLRCanUseCraftSpeed = true;
            [JsonProperty(isRus ? "ZLevelsRemastered: значение из конфига - Plugin Prefix" : "ZLevelsRemastered: config value - Plugin Prefix")]
            public string ZLRPluginPrefix = "<color=orange>ZLevels</color>: ";
            [JsonProperty(isRus ? "ZLevelsRemastered: значение из конфига - Skill Colors -> CRAFTING" : "ZLevelsRemastered: config value - Skill Colors -> CRAFTING")]
            public string ZLRSkillColor = "#00FF00";
            [JsonProperty(isRus ? "ZLevelsRemastered: значение из конфига - Crafting Details -> Percent Faster Per Level" : "ZLevelsRemastered: config value - Crafting Details -> Percent Faster Per Level")]
            public float ZLRPercentPerLevel = 5f;
            [JsonProperty(isRus ? "ZLevelsRemastered: значение из конфига - Level Caps -> CRAFTING" : "ZLevelsRemastered: config value - Level Caps -> CRAFTING")]
            public float ZLRLevelCup = 20f;
            [JsonProperty(isRus ? "ZLevelsRemastered: значение из конфига - Starting Stats -> Crafting Points" : "ZLevelsRemastered: config value - Starting Stats -> Crafting Points")]
            public float ZLRStartPoint = 10f;
        }
        class Notification {
            [JsonProperty(isRus ? "Включить уведомления?" : "Enable plugin notifications?")]
            public bool isEnable = true;
            [JsonProperty(isRus ? "Тип уведомления (Chat, GameTips, Notify, GUIAnnouncements)" : "Notification type (Chat, GameTips, Notify, GUIAnnouncements)")]
            public string type = "GameTips";
            [JsonProperty(isRus ? "Закрывать панель, чтобы показать уведомление?" : "Close the panel to show a notification?")]
            public bool closePanel = true;
            [JsonProperty(isRus ? "GameTips: тип уведомления (info, warning)" : "GameTips: notification type (info, warning)")]
            public string GameTipsType = "warning";
            [JsonProperty(isRus ? "Notify: тип уведомления" : "Notify: notification type")]
            public int NotifyType = 0;
            [JsonProperty(isRus ? "GUIAnnouncements: цвет банера" : "GUIAnnouncements: banner color")]
            public string GUIABanerColor = "Grey";
            [JsonProperty(isRus ? "GUIAnnouncements: цвет текста" : "GUIAnnouncements: text color")]
            public string GUIATextColor = "White";
            [JsonProperty(isRus ? "GUIAnnouncements: отступ сверху" : "GUIAnnouncements: vertical position")]
            public float GUIAMarginTop = 0.03f;
        }
        class GameStatus {
            [JsonProperty(isRus ? "Включить отображение игрового статуса?" : "Enable game status?")]
            public bool isEnable = true;
            [JsonProperty(isRus ? "Тип игрового статуса (Rust, SimpleStatus, AdvancedStatus)" : "Type of game status (Rust, SimpleStatus, AdvancedStatus)")]
            public string type = "Rust";
        }
        protected override void LoadDefaultConfig() {
            config = new CraftingPanelConfig();
            SaveConfig();
        }
        void ReadConfig() {
            config = Config.ReadObject<CraftingPanelConfig>();
            SaveConfig();
        }
        protected override void SaveConfig() => Config.WriteObject(config, true);
        IEnumerator CheckConfig(Action endAction) {
            Puts("The plugin has started checking the config...");
            if (config.command == "") {
                PrintError("No command to open the panel!");
                NextTick(() => Interface.Oxide.UnloadPlugin(Title));
                yield break;
            }
            else cmd.AddChatCommand(config.command, this, "OpenPanelCommand");
            if (config.useBackpacks && (Backpacks == null || !Backpacks.IsLoaded || ins.Backpacks.Author != "WhiteThunder")) {
                PrintWarning("The \"Backpacks\" plugin by WhiteThunder is not loaded.The plugin will not be able to take crafting ingredients from the optional backpack.");
                config.useBackpacks = false;
            }
            if (config.useItemRetriever && (ItemRetriever == null || !ItemRetriever.IsLoaded)) {
                PrintWarning("The \"ItemRetriever\" plugin is not loaded.The plugin will not be able to take crafting ingredients from the suppliers containers.");
                config.useItemRetriever = false;
            }
            if (config.economyType != "") {
                switch (config.economyType) {
                    case "ServerRewards" : if (ServerRewards == null || !ServerRewards.IsLoaded) {
                        PrintWarning("The \"ServerRewards\" plugin is not loaded.Economy will be disabled.");
                        config.economyType = "";
                    }
                    break;
                    case "Economics" : if (Economics == null || !Economics.IsLoaded) {
                        PrintWarning("The \"Economics\" plugin is not loaded.Economy will be disabled.");
                        config.economyType = "";
                    }
                    break;
                    case "IQEconomic" : if (IQEconomic == null || !IQEconomic.IsLoaded) {
                        PrintWarning("The \"IQEconomic\" plugin is not loaded.Economy will be disabled.");
                        config.economyType = "";
                    }
                    break;
                    default : PrintWarning("Incorrect economy plugin is specified.Economy will be disabled.");
                    config.economyType = "";
                    break;
                }
            }
            if (config.craftingBonuses.isEnable) {
                switch (config.craftingBonuses.type) {
                    case "SkillTree" : if (SkillTree == null || !SkillTree.IsLoaded) {
                        PrintError("SkillTree plugin is not loaded! Crafting bonuses will be disabled.");
                        config.craftingBonuses.isEnable = false;
                    }
                    break;
                    case "ZLevelsRemastered" : if (ZLevelsRemastered == null || !ZLevelsRemastered.IsLoaded) {
                        PrintError("ZLevelsRemastered plugin is not loaded! Crafting bonuses will be disabled.");
                        config.craftingBonuses.isEnable = false;
                    }
                    break;
                    default : PrintError("Incorrect plugin for working with crafting bonuses! Crafting bonuses will be disabled.");
                    config.craftingBonuses.isEnable = false;
                    break;
                }
            }
            if (config.notify.isEnable) {
                switch (config.notify.type) {
                    case "Chat" : break;
                    case "GameTips" : if (config.notify.GameTipsType != "info" && config.notify.GameTipsType != "warning") {
                        PrintError("GameTips: incorrect notification type! Notifications will be disabled.");
                        config.notify.isEnable = false;
                    }
                    break;
                    case "Notify" : if (Notify == null || !Notify.IsLoaded) {
                        PrintError("Notify: plugin is not loaded! Notifications will be disabled.");
                        config.notify.isEnable = false;
                    }
                    break;
                    case "GUIAnnouncements" : if (GUIAnnouncements == null || !GUIAnnouncements.IsLoaded) {
                        PrintError("GUIAnnouncements: plugin is not loaded! Notifications will be disabled.");
                        config.notify.isEnable = false;
                    }
                    break;
                    default : PrintError("Incorrect notification type! Notifications will be disabled.");
                    config.notify.isEnable = false;
                    break;
                }
            }
            if (config.status.isEnable) {
                switch (config.status.type) {
                    case "Rust" : break;
                    case "SimpleStatus" : if (SimpleStatus == null || !SimpleStatus.IsLoaded) {
                        PrintError("SimpleStatus plugin is not loaded! Game status will be disabled.");
                        config.status.isEnable = false;
                    }
                    else {
                        SimpleStatus.Call("CreateStatus", this, "CraftingPanel.Craft", "0.11 0.41 0.6 1", "Title", "0.84 0.94 0.99 1", "Text", "0.67 0.87 1 1", "assets/icons/gear.png", "0.26 0.61 0.84 1");
                        SimpleStatus.Call("CreateStatus", this, "CraftingPanel.Give", "0.34 0.4 0.26 1", "Title", "1 1 1 1", "Text", "1 1 1 1", "assets/icons/picked up.png", "0.65 1 0.02 1");
                        //SimpleStatus.Call("CreateStatus", this, "CraftingPanel.Drop", "0.42 0.13 0.09 1", "Title", "0.82 0.49 0.44 1", "Text", "0.82 0.49 0.44 1", "assets/icons/close.png", "1 0.24 0.1 1");
                    }
                    break;
                    case "AdvancedStatus" : if (AdvancedStatus == null || !AdvancedStatus.IsLoaded) {
                        PrintError("AdvancedStatus plugin is not loaded! Game status will be disabled.");
                        config.status.isEnable = false;
                    }
                    break;
                    default : PrintError("Incorrect game status type! Game status will be disabled.");
                    config.status.isEnable = false;
                    break;
                }
            }
            for (int i = config.sections.Count - 1; i > -1; i--) {
                yield return CoroutineEx.waitForSeconds(0.25f);
                if (!config.sections[i].isEnable) {
                    if (config.sections[i].permission == "favorite") {
                        Unsubscribe("OnUserPermissionRevoked");
                        Unsubscribe("OnGroupPermissionRevoked");
                        Unsubscribe("OnUserGroupRemoved");
                    }
                    config.sections.RemoveAt(i);
                    continue;
                }
                if (config.sections[i].permission == "") {
                    PrintError("One of the sections has no permission set.");
                    NextTick(() => Interface.Oxide.UnloadPlugin(Title));
                    yield break;
                }
                else if (config.sections[i].permission == "favorite") config.sections[i].items.Clear();
                if (config.sections.Count(x => x.permission == config.sections[i].permission) > 1) {
                    PrintError($"Several sections have the same permission - \"{config.sections[i].permission}\".");
                    NextTick(() => Interface.Oxide.UnloadPlugin(Title));
                    yield break;
                }
                if (config.sections[i].permissionIsActivate) permission.RegisterPermission($"craftingpanel.section.{config.sections[i].permission}", this);
                ImageLibrary.Call("AddImage", config.sections[i].img, $"CraftingPanel.Section.{config.sections[i].permission}");
                for (int j = config.sections[i].items.Count - 1; j > -1; j--) {
                    //yield return CoroutineEx.waitForFixedUpdate;
                    if (!config.sections[i].items[j].isEnable) {
                        config.sections[i].items.RemoveAt(j);
                        continue;
                    }
                    if (config.sections[i].items[j].name == "") {
                        PrintError($"You need to specify name for the item \"{config.sections[i].items[j].permission}\" in the \"{config.sections[i].permission}\" section.");
                        NextTick(() => Interface.Oxide.UnloadPlugin(Title));
                        yield break;
                    }
                    if (config.sections[i].items[j].permission == "") {
                        PrintError($"One of the items in the section \"{config.sections[i].permission})\" has no permission set.");
                        NextTick(() => Interface.Oxide.UnloadPlugin(Title));
                        yield break;
                    }
                    if (config.sections[i].items.Count(x => x.permission == config.sections[i].items[j].permission) > 1) {
                        PrintError($"Several items have the same permission - \"{config.sections[i].items[j].permission}\" in the \"{config.sections[i].permission}\" section.");
                        NextTick(() => Interface.Oxide.UnloadPlugin(Title));
                        yield break;
                    }
                    if (config.sections[i].items[j].shortname == "" && config.sections[i].items[j].command == "") {
                        PrintError($"You need to specify a shortname or command for the item \"{config.sections[i].items[j].permission}\" in the \"{config.sections[i].permission}\" section.");
                        NextTick(() => Interface.Oxide.UnloadPlugin(Title));
                        yield break;
                    }
                    config.sections[i].items[j].parentSection = config.sections[i].permission;
                    if (config.sections[i].items[j].activPermission) permission.RegisterPermission($"craftingpanel.{config.sections[i].permission}.{config.sections[i].items[j].permission}", this);
                    if (config.sections[i].items[j].img != "") ImageLibrary.Call("AddImage", config.sections[i].items[j].img, $"CraftingPanel.{config.sections[i].permission}.{config.sections[i].items[j].permission}");
                    for (int m = config.sections[i].items[j].itemSkins.Count - 1; m > -1; m--) {
                        if (!config.sections[i].items[j].itemSkins[m].isEnable) {
                            config.sections[i].items[j].itemSkins.RemoveAt(m);
                            continue;
                        }
                        if (config.sections[i].items[j].itemSkins[m].permission == "") {
                            PrintError($"One of the variations ({config.sections[i].permission}/{config.sections[i].items[j].permission}/*your variation*) has no permission set.");
                            NextTick(() => Interface.Oxide.UnloadPlugin(Title));
                            yield break;
                        }
                        if (config.sections[i].items[j].itemSkins.Count(x => x.permission == config.sections[i].items[j].itemSkins[m].permission) > 1) {
                            PrintError($"Several variations of items have the same permission - \"{config.sections[i].items[j].itemSkins[m].permission}\" ({config.sections[i].permission}/{config.sections[i].items[j].permission}/{config.sections[i].items[j].itemSkins[m].permission}).");
                            NextTick(() => Interface.Oxide.UnloadPlugin(Title));
                            yield break;
                        }
                        if (config.sections[i].items[j].itemSkins[m].shortname == "" && config.sections[i].items[j].itemSkins[m].command == "") {
                            PrintError($"You need to specify a shortname or command for the variation ({config.sections[i].permission}/{config.sections[i].items[j].permission}/{config.sections[i].items[j].itemSkins[m].permission}).");
                            NextTick(() => Interface.Oxide.UnloadPlugin(Title));
                            yield break;
                        }
                        if (config.sections[i].items[j].itemSkins[m].activPermission) permission.RegisterPermission($"craftingpanel.{config.sections[i].permission}.{config.sections[i].items[j].permission}.{config.sections[i].items[j].itemSkins[m].permission}", this);
                        if (config.sections[i].items[j].itemSkins[m].img != "") ImageLibrary.Call<string>("AddImage", config.sections[i].items[j].itemSkins[m].img, $"CraftingPanel.{config.sections[i].permission}.{config.sections[i].items[j].permission}.{config.sections[i].items[j].itemSkins[m].permission}");
                    }
                    if (config.sections[i].items[j].itemSkins.Count > 0) config.sections[i].items[j].itemSkins.Insert(0, new ItemSkin {
                        permission = "default", shortname = config.sections[i].items[j].shortname, skinId = config.sections[i].items[j].skinId, isBlueprint = config.sections[i].items[j].isBlueprint
                    }
                    );
                    for (int k = config.sections[i].items[j].ingredients.Count - 1; k > -1; k--) {
                        if (!config.sections[i].items[j].ingredients[k].isEnable) {
                            config.sections[i].items[j].ingredients.RemoveAt(k);
                            continue;
                        }
                        if (config.sections[i].items[j].ingredients[k].name == "") {
                            PrintError($"You need to specify ingredients name of the item \"{config.sections[i].items[j].permission}\" in the \"{config.sections[i].permission}\" section.");
                            NextTick(() => Interface.Oxide.UnloadPlugin(Title));
                            yield break;
                        }
                        if (config.sections[i].items[j].ingredients[k].shortname == "") {
                            PrintError($"You need to specify ingredients shortname of the item \"{config.sections[i].items[j].permission}\" in the \"{config.sections[i].permission}\" section.");
                            NextTick(() => Interface.Oxide.UnloadPlugin(Title));
                            yield break;
                        }
                    }
                    if (config.sections[i].items[j].ingredients.Count == 0 && config.sections[i].items[j].economicPrice == 0) {
                        PrintWarning($"All ingredients of the \"{config.sections[i].items[j].permission}\" item are disabled.Therefore, this item will also be disabled.");
                        config.sections[i].items.RemoveAt(j);
                    }
                }
                if (config.sections[i].items.Count == 0 && config.sections[i].permission != "favorite") {
                    PrintWarning($"All elements of the \"{config.sections[i].permission}\" section are disabled.Therefore, this section will also be disabled.");
                    config.sections.RemoveAt(i);
                    continue;
                }
                CuiElementContainer container = new CuiElementContainer();
                int a = 5;
                // Начало по x
                int b = -89;
                // Начало по y (размер кнопки 84)
                int c = 89;
                // Промежуток по x
                int d = 89;
                // Промежуток по y
                int scrollboxSize = Mathf.CeilToInt(config.sections[i].items.Count / 4f) * d + 5;
                if (scrollboxSize < 475) scrollboxSize = 475;
                container.Add(new CuiPanel {
                    Image = {
                        Color = "0 0 0 0"
                    }
                }
                , "CraftingPanel.ItemsBox", "CraftingPanel.InvisibleItemsBox", "CraftingPanel.InvisibleItemsBox");
                container.Add(new CuiElement {
                    Name = "CraftingPanel.ItemsBoxScrollbar", Parent = "CraftingPanel.InvisibleItemsBox", Components = {
                        new CuiRectTransformComponent {
                            AnchorMin = "0 0.001", AnchorMax = "0.995 0.9948"
                        }
                        , new CuiScrollViewComponent {
                            ContentTransform = new CuiRectTransform {
                                AnchorMin = "0 1", AnchorMax = "1 1", OffsetMin = $"0 -{scrollboxSize}", OffsetMax = "0 0"
                            }
                            , Horizontal = false, Vertical = true, MovementType = UnityEngine.UI.ScrollRect.MovementType.Elastic, Elasticity = 0.25f, Inertia = true, DecelerationRate = 0.3f, ScrollSensitivity = 24f, VerticalScrollbar = null
                        }
                    }
                }
                );
                container.Add(new CuiPanel {
                    Image = {
                        Color = "0 0 0 0"
                    }
                }
                , "CraftingPanel.ItemsBoxScrollbar");
                for (int l = 0; l < config.sections[i].items.Count; l++) {
                    container.Add(new CuiButton {
                        RectTransform = {
                            AnchorMin = "0 1", AnchorMax = "0 1", OffsetMin = $"{a} {b}", OffsetMax = $"{a+84} {b+84}"
                        }
                        , Button = {
                            Command = $"CraftingPanelSortingCommand items {config.sections[i].permission} {config.sections[i].items[l].permission} {config.sections[i].items[0].permission} {config.sections[i].items[l].parentSection}", Color = l == 0 ? "0.18 0.66 1 0.35" : "0 0 0 0"
                        }
                    }
                    , "CraftingPanel.ItemsBoxScrollbar", $"CraftingPanel.ItemsBoxScrollbar.Item.{config.sections[i].items[l].permission}");
                    if (config.sections[i].items[l].img != "") {
                        container.Add(new CuiElement {
                            Parent = $"CraftingPanel.ItemsBoxScrollbar.Item.{config.sections[i].items[l].permission}", Components = {
                                new CuiRectTransformComponent {
                                    AnchorMin = "0 0", AnchorMax = "1 1"
                                }
                                , new CuiRawImageComponent {
                                    Png = ImageLibrary.Call<string>("GetImage", $"CraftingPanel.{config.sections[i].items[l].parentSection}.{config.sections[i].items[l].permission}")
                                }
                            }
                        }
                        );
                    }
                    else {
                        if (config.sections[i].items[l].isBlueprint) {
                            container.Add(new CuiPanel {
                                RectTransform = {
                                    AnchorMin = "0 0", AnchorMax = "1 1"
                                }
                                , Image = {
                                    ItemId = ItemManager.FindItemDefinition("blueprintbase").itemid
                                }
                            }
                            , $"CraftingPanel.ItemsBoxScrollbar.Item.{config.sections[i].items[l].permission}");
                        }
                        container.Add(new CuiPanel {
                            RectTransform = {
                                AnchorMin = "0 0", AnchorMax = "1 1"
                            }
                            , Image = {
                                ItemId = ItemManager.FindItemDefinition(config.sections[i].items[l].shortname).itemid, SkinId = config.sections[i].items[l].skinId
                            }
                        }
                        , $"CraftingPanel.ItemsBoxScrollbar.Item.{config.sections[i].items[l].permission}");
                    }
                    if ((l + 1) % 4 == 0) {
                        a = 5;
                        b -= d;
                    }
                    else a += c;
                }
                config.sections[i].jsonReadyItems = CuiHelper.ToJson(container);
            }
            if (config.sections.Count == 0) {
                PrintError("All sections are disabled!");
                NextTick(() => Interface.Oxide.UnloadPlugin(Title));
                yield break;
            }
            Puts("The config has been successfully checked.");
            endAction?.Invoke();
            configCheck = null;
        }
#endregion
#region Lang
        IEnumerator LoadCustomLang() {
            CraftingPanelConfig rawConfig = Config.ReadObject<CraftingPanelConfig>();
            Dictionary<string, string> rus = new Dictionary<string, string> {
                ["SEARCH"]
                = "Поиск...", ["SEARCHING"] = "ИДЕТ ПОИСК...", ["SEARCH_EMPTY"] = "НЕ НАЙДЕНО", ["CRAFTING_QUEUE"] = "ОЧЕРЕДЬ СОЗДАНИЯ", ["BACK"] = "НАЗАД", ["NEXT"] = "ВПЕРЕД", ["FAVORITE"] = "ИЗБРАННОЕ", ["PERMISSION"] = "ПРИВИЛЕГИЯ", ["NO_PERMISSION"] = "НЕТ\nПРИВИЛЕГИИ", ["INFORMATION"] = "ИНФОРМАЦИЯ", ["VARIATIONS"] = "ИСПОЛНЕНИЯ", ["AMOUNT"] = "НЕОБХОДИМО", ["ITEM_TYPE"] = "НАЗВАНИЕ ПРЕДМЕТА", ["TOTAL"] = "ВСЕГО", ["HAVE"] = "ИМЕЕТСЯ", ["CRAFT"] = "СОЗДАТЬ", ["BUY"] = "КУПИТЬ", ["ECONOMY"] = "БАЛАНС:\nСТОИМОСТЬ:", ["CURRENCY"] = "{0} $\n{1} $", ["CRAFT_ADMIN"] = "ВЫДАТЬ СЕБЕ", ["WB_TIER"] = "ТРЕБУЕТСЯ ВЕРСТАК {0}-ГО УРОВНЯ", ["UNAVAILABLE"] = "ОТСУТСТВУЮТ", ["TIMER"] = "{0}с", ["SS_AMOUNT"] = "{0} шт",  //["QUEUE_BUSY"] = "Вся очередь крафта занята!",
                ["WB_LEVEL"]
                = "Недостаточный уровень верстака!", ["NO_PERM"] = "Отсутствует необходимая привилегия!", ["NO_INGREDIENT"] = "Недостаточно ингредиентов для крафта!", ["NO_MONEY"] = "На балансе недостаточно средств для покупки!", ["PERM_REVOKE"] = "С вас снята привилегия на раздел '{0}'.Предметы этого раздела удалены из '{1}'.", ["COMMAND_INVALID"] = "Команда указана неверно.\nВведите:", ["COMMAND_PLAYER_ERROR"] = "Игрок не найден.\nВведите:", ["COMMAND_SECTION_ERROR"] = "Раздел не найден.\nВведите:", ["COMMAND_ITEM_ERROR"] = "Предмет не найден.\nВведите:", ["COMMAND_NUMBER_ERROR"] = "Кол-во указано неверно.\nВведите:", ["COMMAND_VARIATION_ERROR"] = "Исполнение предемта указано неверно.\nВведите:", ["COMMAND_PLUGIN_ERROR"] = "У этого игрока не работает панель крафта! Пожалуйста сообщите разработчику об этой ошибке."
            }
            ;
            Dictionary<string, string> eng = new Dictionary<string, string> {
                ["SEARCH"]
                = "Search...", ["SEARCHING"] = "SEARCHING...", ["SEARCH_EMPTY"] = "NOT FOUND", ["CRAFTING_QUEUE"] = "CRAFTING QUEUE", ["BACK"] = "BACK", ["NEXT"] = "NEXT", ["FAVORITE"] = "FAVORITE", ["PERMISSION"] = "PERMISSION", ["NO_PERMISSION"] = "NO\nPERMISSION", ["INFORMATION"] = "INFORMATION", ["VARIATIONS"] = "VARIATIONS", ["AMOUNT"] = "AMOUNT", ["ITEM_TYPE"] = "ITEM TYPE", ["TOTAL"] = "TOTAL", ["HAVE"] = "HAVE", ["CRAFT"] = "CRAFT", ["BUY"] = "PURCHASE", ["ECONOMY"] 
// ... [Code preview truncated due to length. Full source in attached file] ...

Автор
15FPS
Скачиваний
0
Просмотры
1
Первый выпуск
Обновление
Оценка
0.00 звёзд 0 оценок
Сверху