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

FREE PlayerSkins : 2.0.3 2.0.3

Нет прав для скачивания
C#:
// Все права принадлежат дискорд сообществу https://discord.gg/VgNHPpNrz6
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Core.Configuration;
using Oxide.Game.Rust.Cui;
using Oxide.Core.Plugins;
using UnityEngine;
using System.Linq;
using System.Collections;
using System.Globalization;
namespace Oxide.Plugins {
    [Info("PlayerSkins", "k1lly0u", "2.0.3", ResourceId = 0)]
    //  Слив плагинов server-rust by Apolo YouGame
    class PlayerSkins : RustPlugin {
#region Fields
        [PluginReference]
        Plugin Economics, ImageLibrary, ServerRewards;
        private Dictionary<string, Dictionary<ulong, SkinData>> skinData;
        private Dictionary<ulong, UserData> userData;
        private DynamicConfigFile userdata, skindata;
        private Dictionary<string, Dictionary<ulong, WorkshopItem>> workshopItems = new Dictionary<string, Dictionary<ulong, WorkshopItem>>();
        private Dictionary<string, string> shortnameToDisplayname = new Dictionary<string, string>();
        private List<ulong> adminToggle = new List<ulong>();
        private List<ulong> ownedToggle = new List<ulong>();
        private bool initialized = false;
        private Facepunch.Steamworks.Workshop.Query query = null;
        private bool workshopInitialized = false;
        private static Dictionary<Colors, string> uiColor;
        private TokenType purchaseType;
        private DisplayMode forcedMode;
        public enum TokenType {
            None, ServerRewards, Economics
        }
#endregion
#region Oxide Hooks
        private void Loaded() {
            skindata = Interface.Oxide.DataFileSystem.GetFile("PlayerSkins/skinlist");
            userdata = Interface.Oxide.DataFileSystem.GetFile("PlayerSkins/userdata");
            permission.RegisterPermission("playerskins.shop", this);
            permission.RegisterPermission("playerskins.reskin", this);
            permission.RegisterPermission("playerskins.admin", this);
            lang.RegisterMessages(Messages, this);
        }
        private void OnServerInitialized() {
            LoadData();
            purchaseType = ParseType<TokenType>(configData.Purchase.Type);
            if (configData.Purchase.Enabled && purchaseType == TokenType.None) {
                PrintError("Invalid purchase plugin specified in config.Must be either 'ServerRewards' or 'Economics'!");
                return;
            }
            forcedMode = ParseType<DisplayMode>(configData.Shop.ForcedMode);
            foreach (string perm in configData.Shop.Permissions) {
                if (!perm.StartsWith("playerskins.")) permission.RegisterPermission($"playerskins.{perm}", this);
                else permission.RegisterPermission(perm, this);
            }
            uiColor = new Dictionary<Colors, string>();
            foreach (var color in configData.UI.Colors) uiColor.Add(color.Key, UI.Color(color.Value.Color, color.Value.Alpha));
            foreach (ItemDefinition item in ItemManager.itemList) {
                shortnameToDisplayname.Add(item.shortname, item.displayName.english);
                string workshopName = item.displayName.english.ToLower().Replace("skin", "").Replace(" ", "").Replace("-", "");
                if (!workshopNameToShortname.ContainsKey(workshopName)) workshopNameToShortname.Add(workshopName, item.shortname);
            }
            GetItemSkins();
        }
        private void OnServerSave() => SaveUserData();
        private void Unload() {
            if (query != null) {
                ServerMgr.Instance.StopCoroutine(GetWorkshopSkins());
                query.Dispose();
            }
            foreach (BasePlayer player in BasePlayer.activePlayerList) DestroyUI(player);
        }
        private void OnUseNPC(BasePlayer npc, BasePlayer player) {
            if (player == null || npc == null) return;
            if (!userData.ContainsKey(player.userID)) userData.Add(player.userID, new UserData());
            if (configData.Shop.NPCs.Contains(npc.UserIDString)) OpenSkinMenu(player, "", 0, 0);
            else if (configData.Reskin.NPCs.Contains(npc.UserIDString) && !configData.Shop.GiveItemOnPurchase) CreateReskinMenu(player);
        }
        private void OnItemCraftFinished(ItemCraftTask task, Item item) {
            BasePlayer player = task?.owner;
            if (player == null || item == null) return;
            if (item.skin != 0) return;
            UserData data;
            if (!userData.TryGetValue(player.userID, out data)) return;
            if (data.defaultSkins.ContainsKey(item.info.shortname)) ChangeItemSkin(item, data.defaultSkins[item.info.shortname]);
        }
#endregion
#region Functions
        private T ParseType<T>(string type) {
            try {
                return (T)Enum.Parse(typeof(T), type, true);
            }
            catch {
                return default(T);
            }
        }
        private bool HasPermission(BasePlayer player, string perm) {
            if (!perm.StartsWith("playerskins.")) perm = $"playerskins.{perm}";
            return permission.UserHasPermission(player.UserIDString, perm);
        }
        private void BroadcastAnnouncement() {
            if (!configData.Announcements.Enabled && configData.Announcements.Interval > 0) return;
            foreach(BasePlayer player in BasePlayer.activePlayerList) {
                if (configData.Shop.DisableCommand) SendReply(player, msg("Help.Shop.NPC", player.userID));
                else SendReply(player, msg("Help.Shop.Command", player.userID));
                if (configData.Reskin.DisableCommand) SendReply(player, msg("Help.Reskin.NPC", player.userID));
                else SendReply(player, msg("Help.Reskin.Command", player.userID));
            }
            timer.In(configData.Announcements.Interval * 60, BroadcastAnnouncement);
        }
        private void ChangeItemSkin(BasePlayer player, ulong targetSkin) {
            Item item = player.GetActiveItem();
            if (item == null) return;
            ChangeItemSkin(item, targetSkin);
            int slot = item.position;
            item.SetParent(null);
            item.MarkDirty();
            timer.Once(0.15f, () => {
                if (item == null) return;
                item.SetParent(player.inventory.containerBelt);
                item.position = slot;
                item.MarkDirty();
            }
            );
        }
        private void ChangeItemSkin(Item item, ulong targetSkin) {
            item.skin = targetSkin;
            item.MarkDirty();
            BaseEntity heldEntity = item.GetHeldEntity();
            if (heldEntity != null) {
                heldEntity.skinID = targetSkin;
                heldEntity.SendNetworkUpdate(BasePlayer.NetworkQueue.Update);
            }
        }
#endregion
#region Skin List Initialization
        private Dictionary<string, string> workshopNameToShortname = new Dictionary<string, string> {
            {
                "longtshirt", "tshirt.long"
            }
            , {
                "cap", "hat.cap"
            }
            , {
                "beenie", "hat.beenie"
            }
            , {
                "boonie", "hat.boonie"
            }
            , {
                "balaclava", "mask.balaclava"
            }
            , {
                "pipeshotgun", "shotgun.waterpipe"
            }
            , {
                "woodstorage", "box.wooden"
            }
            , {
                "ak47", "rifle.ak"
            }
            , {
                "bearrug", "rug.bear"
            }
            , {
                "boltrifle", "rifle.bolt"
            }
            , {
                "bandana", "mask.bandana"
            }
            , {
                "hideshirt", "attire.hide.vest"
            }
            , {
                "snowjacket", "jacket.snow"
            }
            , {
                "buckethat", "bucket.helmet"
            }
            , {
                "semiautopistol", "pistol.semiauto"
            }
            , {
                "burlapgloves", "burlap.gloves"
            }
            , {
                "roadsignvest", "roadsign.jacket"
            }
            , {
                "roadsignpants", "roadsign.kilt"
            }
            , {
                "burlappants", "burlap.trousers"
            }
            , {
                "collaredshirt", "shirt.collared"
            }
            , {
                "mp5", "smg.mp5"
            }
            , {
                "sword", "salvaged.sword"
            }
            , {
                "workboots", "shoes.boots"
            }
            , {
                "vagabondjacket", "jacket"
            }
            , {
                "hideshoes", "attire.hide.boots"
            }
            , {
                "deerskullmask", "deer.skull.mask"
            }
            , {
                "minerhat", "hat.miner"
            }
            , {
                "lr300", "rifle.lr300"
            }
            , {
                "lr300.item", "rifle.lr300"
            }
        }
        ;
        private void GetItemSkins() {
            PrintWarning("Retrieving approved skin lists...");
            webrequest.Enqueue("http://s3.amazonaws.com/s3.playrust.com/icons/inventory/rust/schema.json", null, (code, response) => {
                if (response != null && code == 200) {
                    Rust.Workshop.ItemSchema.Item[] items = JsonConvert.DeserializeObject<Rust.Workshop.ItemSchema>(response).items;
                    Dictionary<string, Dictionary<ulong, string>> loadOrder = new Dictionary<string, Dictionary<ulong, string>>();
                    int loadOrderCount = 0;
                    int skinCount = 0;
                    foreach (var item in items) {
                        if (item == null || string.IsNullOrEmpty(item.itemshortname) || string.IsNullOrEmpty(item.icon_url)) continue;
                        string shortname = item.itemshortname;
                        if (workshopNameToShortname.ContainsKey(shortname)) shortname = workshopNameToShortname[shortname];
                        if (!ItemManager.itemList.Find(x => x.shortname == shortname)?.HasSkins ?? false) continue;
                        ulong skinId = 0;
                        if (item.itemdefid < 20000) skinId = item.itemdefid;
                        else {
                            if (!string.IsNullOrEmpty(item.workshopid)) skinId = ulong.Parse(item.workshopid);
                            else skinId = item.itemdefid;
                        }
                        if (!skinData.ContainsKey(shortname)) skinData.Add(shortname, new Dictionary<ulong, SkinData>());
                        if (!skinData[shortname].ContainsKey(skinId)) skinData[shortname].Add(skinId, new SkinData());
                        if (!workshopItems.ContainsKey(shortname)) workshopItems.Add(shortname, new Dictionary<ulong, WorkshopItem>());
                        if (!workshopItems[shortname].ContainsKey(skinId)) workshopItems[shortname].Add(skinId, new WorkshopItem(item));
                        if (!HasImage(shortname, skinId)) {
                            if (!loadOrder.ContainsKey(shortname)) loadOrder.Add(shortname, new Dictionary<ulong, string>());
                            if (!loadOrder[shortname].ContainsKey(skinId)) {
                                loadOrder[shortname].Add(skinId, item.icon_url);
                                skinCount++;
                            }
                            if (skinCount >= 500) {
                                loadOrderCount++;
                                Puts($"Creating a skin load order (Order #{loadOrderCount})");
                                ImageLibrary.Call("ImportItemList", $"{Title} approved skin icons (Order #{loadOrderCount})", loadOrder);
                                loadOrder = new Dictionary<string, Dictionary<ulong, string>>();
                                skinCount = 0;
                            }
                        }
                    }
                    if (skinCount > 0) {
                        loadOrderCount++;
                        Puts($"Creating a skin load order (Order #{loadOrderCount})");
                        ImageLibrary.Call("ImportItemList", $"{Title} approved skin icons (Order #{loadOrderCount})", loadOrder);
                    }
                    PrintWarning("Successfully retrieved the approved skin list");
                }
                else PrintWarning($"There was an error retrieving the approved skin list.Code : {code}");
                initialized = true;
                if (configData.Workshop.Enabled) ServerMgr.Instance.StartCoroutine(GetWorkshopSkins());
                else ClearEmptyLists();
            }
            , this);
        }
        private IEnumerator GetWorkshopSkins() {
            PrintWarning("Querying Steam for workshop items.This process can take up to 15 minutes!\nWorkshop skins will be unavailable in the skin shop and reskin menu until this process has completed.Once the workshop data has been loaded any registered workshop skins will appear.");
            query = Rust.Global.SteamServer.Workshop.CreateQuery();
            query.Page = 1;
            query.PerPage = 50000;
            query.RequireTags.Add("version3");
            query.RequireTags.Add("skin");
            query.RequireAllTags = true;
            query.Run();
            yield return new WaitWhile(new Func<bool>(() => query.IsRunning));
            if (ImageLibrary == null) yield break;
            Dictionary<string, Dictionary<ulong, string>> loadOrder = new Dictionary<string, Dictionary<ulong, string>>();
            int loadOrderCount = 0;
            int skinCount = 0;
            int count = 0;
            foreach (var item in query.Items) {
                if (ContainsKeyword(item.Title)) continue;
                if (!string.IsNullOrEmpty(item.PreviewImageUrl)) {
                    foreach (string tag in item.Tags) {
                        string adjTag = tag.ToLower().Replace("skin", "").Replace(" ", "").Replace("-", "").Replace(".item", "");
                        if (workshopNameToShortname.ContainsKey(adjTag)) {
                            string identifier = workshopNameToShortname[adjTag];
                            if (!workshopItems.ContainsKey(identifier)) workshopItems.Add(identifier, new Dictionary<ulong, WorkshopItem>());
                            if (!workshopItems[identifier].ContainsKey(item.Id)) {
                                workshopItems[identifier].Add(item.Id, new WorkshopItem(item));
                                count++;
                            }
                            if (skinData.ContainsKey(identifier)) {
                                if (skinData[identifier].ContainsKey(item.Id)) {
                                    if (!HasImage(identifier, item.Id)) {
                                        if (!loadOrder.ContainsKey(identifier)) loadOrder.Add(identifier, new Dictionary<ulong, string>());
                                        if (!loadOrder[identifier].ContainsKey(item.Id)) {
                                            loadOrder[identifier].Add(item.Id, item.PreviewImageUrl);
                                            skinCount++;
                                        }
                                        if (skinCount >= 500) {
                                            loadOrderCount++;
                                            Puts($"Creating a skin load order (Order #{loadOrderCount})");
                                            ImageLibrary.Call("ImportItemList", $"{Title} workshop skin icons (Order #{loadOrderCount})", loadOrder);
                                            loadOrder = new Dictionary<string, Dictionary<ulong, string>>();
                                            skinCount = 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (skinCount > 0) {
                loadOrderCount++;
                Puts($"Creating a skin load order (Order #{loadOrderCount})");
                ImageLibrary.Call("ImportItemList", $"{Title} workshop skin icons (Order #{loadOrderCount})", loadOrder);
            }
            query.Dispose();
            query = null;
            PrintWarning($"Workshop skin list retrieval completed.{count} workshop skins are now available!");
            ClearEmptyLists();
            workshopInitialized = true;
        }
        private void ClearEmptyLists() {
            for (int i = skinData.Keys.Count - 1; i >= 0; i--) {
                var skinInfo = skinData.ElementAt(i);
                //  Слив плагинов server-rust by Apolo YouGame
                if (skinInfo.Value.Count < 2)  //  Слив плагинов server-rust by Apolo YouGame
                skinData.Remove(skinInfo.Key);
                //  Слив плагинов server-rust by Apolo YouGame
            }
            RemoveInvalidSkins();
        }
        private void RemoveInvalidSkins() {
            for (int i = skinData.Count - 1; i >= 0; i--) {
                var skinInfo = skinData.ElementAt(i);
                //  Слив плагинов server-rust by Apolo YouGame
                for (int y = skinInfo.Value.Count - 1; y >= 0; y--)  //  Слив плагинов server-rust by Apolo YouGame
                {
                    var skin = skinInfo.Value.ElementAt(y);
                    //  Слив плагинов server-rust by Apolo YouGame
                    if (!workshopItems.ContainsKey(skinInfo.Key) || !workshopItems[skinInfo.Key].ContainsKey(skin.Key))  //  Слив плагинов server-rust by Apolo YouGame
                    skinData[skinInfo.Key].Remove(skin.Key);
                    //  Слив плагинов server-rust by Apolo YouGame
                }
            }
            SaveSkinData();
        }
        private bool ContainsKeyword(string title) {
            foreach (string keyword in configData.Workshop.Filter) {
                if (title.ToLower().Contains(keyword.ToLower())) return true;
            }
            return false;
        }
#endregion
#region Image Library
        private string GetImage(string shortname, ulong skin = 0) => (string)ImageLibrary.Call("GetImage", shortname, skin);
        private bool AddImage(string url, string shortname, ulong skin = 0) => (bool)ImageLibrary.Call("AddImage", url, shortname, skin);
        private bool HasImage(string shortname, ulong skin = 0) => (bool)ImageLibrary.Call("HasImage", shortname, skin);
        private bool IsReady() => (bool)ImageLibrary.Call("IsReady");
#endregion
#region Chat Commands
        [ChatCommand("skin")]
        private void cmdSkin(BasePlayer player, string command, string[] args) {
            if (!userData.ContainsKey(player.userID)) userData.Add(player.userID, new UserData());
            if (args.Length == 0) {
                if (!permission.UserHasPermission(player.UserIDString, "playerskins.reskin")) {
                    SendReply(player, "You do not have permission to use this command");
                    return;
                }
                if (configData.Shop.GiveItemOnPurchase) return;
                if (configData.Reskin.DisableCommand) {
                    SendReply(player, "You can only access the re-skin menu via a re-skin NPC");
                    return;
                }
                CreateReskinMenu(player);
            }
            else {
                if (args[0].ToLower() != "shop") {
                    SendReply(player, "/skin - Open the re-skin menu");
                    SendReply(player, "/skin shop - Open the skin shop");
                    return;
                }
                if (!permission.UserHasPermission(player.UserIDString, "playerskins.shop")) {
                    SendReply(player, "You do not have permission to use this command");
                    return;
                }
                if (configData.Shop.DisableCommand) {
                    SendReply(player, "You can only access the skin shop menu via a skin shop NPC");
                    return;
                }
                OpenSkinMenu(player, string.Empty, 0, 0);
            }
        }
#endregion
#region Console Commands
        [ConsoleCommand("playerskins.skins")]
        private void ccmdSkinManager(ConsoleSystem.Arg arg) {
            if (arg.Connection != null) {
                if (arg.Connection.authLevel < 2) {
                    SendReply(arg, "You do not have permission to use this command");
                    return;
                }
            }
            if (arg.Args == null || arg.Args.Length < 3) {
                SendReply(arg, "playerskins.skins import <item shortname> <skin ID> - Import the specified workshop skin");
                SendReply(arg, "playerskins.skins import random <amount> - Import the specified amount of random skins for random items");
                SendReply(arg, "playerskins.skins import random <item shortname> <amount> - Import the specified amount of random skins for the specified item");
                SendReply(arg, "playerskins.skins remove <item shortname> <skin ID> - Remove the specified skin from the skin shop");
                return;
            }
            if (!configData.Workshop.Enabled) {
                SendReply(arg, "You have workshop disabled in your config.The playerskins.skins commands are unavailable when workshop is disabled");
                return;
            }
            if (!workshopInitialized) {
                SendReply(arg, "Workshop initialization has not yet finished.The playerskins.skins commands are unavailable until that process is complete");
                return;
            }
            switch (arg.GetString(0).ToLower()) {
                case "import" : if (arg.Args[1].ToLower() == "random") {
                    if (arg.Args.Length == 4) {
                        string shortname = arg.GetString(2).ToLower();
                        if (!ItemManager.itemList.Select(x => x.shortname).Contains(shortname) || !workshopItems.ContainsKey(shortname)) {
                            SendReply(arg, "The item shortname you have entered either does not have any skins, or is invalid");
                            return;
                        }
                        int amount;
                        if (!int.TryParse(arg.GetString(3), out amount)) {
                            SendReply(arg, "You must enter an amount of random skins to import");
                            return;
                        }
                        Dictionary<string, Dictionary<ulong, string>> loadOrder = new Dictionary<string, Dictionary<ulong, string>>();
                        int skinCount = 0;
                        int loadOrderCount = 0;
                        List<KeyValuePair<ulong, WorkshopItem>> newList = new List<KeyValuePair<ulong, WorkshopItem>>(workshopItems[shortname].ToList());
                        for (int i = 0; i < amount; i++) {
                            var skinInfo = newList.GetRandom();
                            //  Слив плагинов server-rust by Apolo YouGame
                            newList.Remove(skinInfo);
                            //  Слив плагинов server-rust by Apolo YouGame
                            if ((skinData.ContainsKey(shortname) && skinData[shortname].ContainsKey(skinInfo.Key)) || string.IsNullOrEmpty(skinInfo.Value.imageUrl))  //  Слив плагинов server-rust by Apolo YouGame
                            {
                                i--;
                                continue;
                            }
                            if (!skinData.ContainsKey(shortname)) skinData.Add(shortname, new Dictionary<ulong, SkinData>());
                            skinData[shortname].Add(skinInfo.Key, new SkinData());
                            //  Слив плагинов server-rust by Apolo YouGame
                            if (!HasImage(shortname, skinInfo.Key))  //  Слив плагинов server-rust by Apolo YouGame
                            {
                                if (!loadOrder.ContainsKey(shortname)) loadOrder.Add(shortname, new Dictionary<ulong, string>());
                                if (!loadOrder[shortname].ContainsKey(skinInfo.Key))  //  Слив плагинов server-rust by Apolo YouGame
                                {
                                    loadOrder[shortname].Add(skinInfo.Key, skinInfo.Value.imageUrl);
                                    //  Слив плагинов server-rust by Apolo YouGame
                                    skinCount++;
                                }
                            }
                            if (skinCount >= 500) {
                                loadOrderCount++;
                                Puts($"Creating a skin load order (Order #{loadOrderCount})");
                                ImageLibrary.Call("ImportItemList", $"{Title} skin icons (Order #{loadOrderCount})", loadOrder);
                                loadOrder = new Dictionary<string, Dictionary<ulong, string>>();
                                skinCount = 0;
                            }
                        }
                        if (skinCount > 0) {
                            loadOrderCount++;
                            Puts($"Creating a skin load order (Order #{loadOrderCount})");
                            ImageLibrary.Call("ImportItemList", $"{Title} skin icons (Order #{loadOrderCount})", loadOrder);
                        }
                        SendReply(arg, $"Importing {amount} random {shortname} workshop skins to ImageLibrary");
                        SaveSkinData();
                    }
                    else {
                        int amount;
                        if (!int.TryParse(arg.GetString(2), out amount)) {
                            SendReply(arg, "You must enter an amount of random skins to import");
                            return;
                        }
                        Dictionary<string, Dictionary<ulong, string>> loadOrder = new Dictionary<string, Dictionary<ulong, string>>();
                        int skinCount = 0;
                        int loadOrderCount = 0;
                        Dictionary<string, Dictionary<ulong, WorkshopItem>> newList = new Dictionary<string, Dictionary<ulong, WorkshopItem>>(workshopItems);
                        for (int i = 0; i < amount; i++) {
                            string shortname = newList.Keys.ToArray().GetRandom();
                            var skinInfo = newList[shortname].ToArray().GetRandom();
                            //  Слив плагинов server-rust by Apolo YouGame
                            if ((skinData.ContainsKey(shortname) && skinData[shortname].ContainsKey(skinInfo.Key)) || string.IsNullOrEmpty(skinInfo.Value.imageUrl))  //  Слив плагинов server-rust by Apolo YouGame
                            {
                                i--;
                                continue;
                            }
                            if (!skinData.ContainsKey(shortname)) skinData.Add(shortname, new Dictionary<ulong, SkinData>());
                            skinData[shortname].Add(skinInfo.Key, new SkinData());
                            //  Слив плагинов server-rust by Apolo YouGame
                            if (!HasImage(shortname, skinInfo.Key))  //  Слив плагинов server-rust by Apolo YouGame
                            {
                                if (!loadOrder.ContainsKey(shortname)) loadOrder.Add(shortname, new Dictionary<ulong, string>());
                                if (!loadOrder[shortname].ContainsKey(skinInfo.Key))  //  Слив плагинов server-rust by Apolo YouGame
                                {
                                    loadOrder[shortname].Add(skinInfo.Key, skinInfo.Value.imageUrl);
                                    //  Слив плагинов server-rust by Apolo YouGame
                                    skinCount++;
                                }
                            }
                            if (skinCount >= 500) {
                                loadOrderCount++;
                                Puts($"Creating a skin load order (Order #{loadOrderCount})");
                                ImageLibrary.Call("ImportItemList", $"{Title} skin icons (Order #{loadOrderCount})", loadOrder);
                                loadOrder = new Dictionary<string, Dictionary<ulong, string>>();
                                skinCount = 0;
                            }
                        }
                        if (skinCount > 0) {
                            loadOrderCount++;
                            Puts($"Creating a skin load order (Order #{loadOrderCount})");
                            ImageLibrary.Call("ImportItemList", $"{Title} skin icons (Order #{loadOrderCount})", loadOrder);
                        }
                        SendReply(arg, $"Importing {amount} random workshop skins to ImageLibrary");
                        SaveSkinData();
                    }
                }
                else {
                    string shortname = arg.GetString(1).ToLower();
                    if (!ItemManager.itemList.Select(x => x.shortname).Contains(shortname) || !workshopItems.ContainsKey(shortname)) {
                        SendReply(arg, "The item shortname you have entered either does not have any skins, or is invalid");
                        return;
                    }
                    ulong skinId = 0U;
                    if (!ulong.TryParse(arg.GetString(2), out skinId) || !workshopItems[shortname].ContainsKey(skinId)) {
                        SendReply(arg, "The skin ID you have entered is either invalid or there is no skin with that ID");
                        return;
                    }
                    WorkshopItem workshopItem = workshopItems[shortname][skinId];
                    if (string.IsNullOrEmpty(workshopItem.imageUrl)) {
                        SendReply(arg, "The specified workshop skin can not be imported");
                        return;
                    }
                    if (!skinData.ContainsKey(shortname)) skinData.Add(shortname, new Dictionary<ulong, SkinData>());
                    if (!skinData[shortname].ContainsKey(skinId)) skinData[shortname].Add(skinId, new SkinData());
                    if (!HasImage(shortname, skinId)) {
                        Dictionary<string, Dictionary<ulong, string>> loadOrder = new Dictionary<string, Dictionary<ulong, string>> {
                            [shortname]
                            = new Dictionary<ulong, string> {
                                [skinId]
                                = workshopItem.imageUrl
                            }
                        }
                        ;
                        ImageLibrary.Call("ImportItemList", $"{Title} - {shortname} {skinId}", loadOrder);
                    }
                    SendReply(arg, $"Importing skin ID {skinId} for {shortname} to ImageLibrary!");
                    SaveSkinData();
                }
                return;
                case "remove" : {
                    string shortname = arg.GetString(1).ToLower();
                    if (!ItemManager.itemList.Select(x => x.shortname).Contains(shortname) || !skinData.ContainsKey(shortname)) {
                        SendReply(arg, "The item shortname you have entered either does not have any available skins, or is invalid");
                        return;
                    }
                    ulong skinId = 0U;
                    if (!ulong.TryParse(arg.GetString(2), out skinId) || !skinData[shortname].ContainsKey(skinId)) {
                        SendReply(arg, "The skin ID you have entered is either invalid or has not been added to the list of available skins");
                        return;
                    }
                    skinData[shortname][skinId].isDisabled = true;
                    ImageLibrary.Call("RemoveImage", shortname, skinId);
                    SendReply(arg, $"You have removed skin ID {skinId} for {shortname}!");
                    SaveSkinData();
                }
                return;
                default : SendReply(arg, "Invalid syntax!");
                break;
            }
        }
        [ConsoleCommand("playerskins.setprice")]
        private void ccmdSetSkinPrice(ConsoleSystem.Arg arg) {
            if (arg.Connection != null) {
                if (arg.Connection.authLevel < 2) {
                    SendReply(arg, "You do not have permission to use this command");
                    return;
                }
            }
            if (arg.Args == null || arg.Args.Length != 2) {
                SendReply(arg, "playerskins.setprice <item shortname> <amount> - Set the price for all skins for the specified item");
                SendReply(arg, "playerskins.setprice all <amount> - Set the price for all skins for all items");
                return;
            }
            int amount = 0;
            if (!int.TryParse(arg.GetString(1), out amount)) {
                SendReply(arg, "You must enter a number to set the price");
                return;
            }
            string shortname = arg.GetString(0);
            if (shortname.ToLower() == "all") {
                foreach (var item in skinData.Values) {
                    foreach (var skin in item.Values) skin.cost = amount;
                }
                SendReply(arg, $"You have set all skin costs to {amount}");
            }
            else {
                Dictionary<ulong, SkinData> data;
                if (!skinData.TryGetValue(shortname, out data)) {
                    SendReply(arg, $"Either an invalid shortname was entered, or there are no skins for the specified item : {shortname}");
                    return;
                }
                foreach (var skin in data.Values) skin.cost = amount;
                SendReply(arg, $"You have set all {shortname} skin costs to {amount}");
            }
            SaveSkinData();
        }
#endregion
#region UI Helper
        const string MainPanel = "PSMainPanel";
        const string SelectPanel = "PSSelectionPanel";
        const string PopupPanel = "PSPopupPanel";
        const string ReskinPanel = "PSReskinPanel";
        private void DestroyUI(BasePlayer player) {
            CuiHelper.DestroyUi(player, MainPanel);
            CuiHelper.DestroyUi(player, SelectPanel);
            CuiHelper.DestroyUi(player, PopupPanel);
            CuiHelper.DestroyUi(player, ReskinPanel);
        }
        public static class UI {
            static public CuiElementContainer Container(string panel, string color, UI4 dimensions, bool useCursor = false, string parent = "Overlay") {
                CuiElementContainer container = new CuiElementContainer() {
                    {
                        new CuiPanel {
                            Image = {
                                Color = color
                            }
                            , RectTransform = {
                                AnchorMin = dimensions.GetMin(), AnchorMax = dimensions.GetMax()
                            }
                            , CursorEnabled = useCursor
                        }
                        , new CuiElement().Parent = parent, panel
                    }
                }
                ;
                return container;
            }
            static public void Panel(ref CuiElementContainer container, string panel, string color, UI4 dimensions, bool cursor = false) {
                container.Add(new CuiPanel {
                    Image = {
                        Color = color
                    }
                    , RectTransform = {
                        AnchorMin = dimensions.GetMin(), AnchorMax = dimensions.GetMax()
                    }
                    , CursorEnabled = cursor
                }
                , panel);
            }
            static public void Label(ref CuiElementContainer container, string panel, string text, int size, UI4 dimensions, TextAnchor align = TextAnchor.MiddleCenter) {
                container.Add(new CuiLabel {
                    Text = {
                        FontSize = size, Align = align, Text = text
                    }
                    , RectTransform = {
                        AnchorMin = dimensions.GetMin(), AnchorMax = dimensions.GetMax()
                    }
                }
                , panel);
            }
            static public void Button(ref CuiElementContainer container, string panel, string color, string text, int size, UI4 dimensions, string command, TextAnchor align = TextAnchor.MiddleCenter) {
                container.Add(new CuiButton {
                    Button = {
                        Color = color, Command = command, FadeIn = 0f
                    }
                    , RectTransform = {
                        AnchorMin = dimensions.GetMin(), AnchorMax = dimensions.GetMax()
                    }
                    , Text = {
                        Text = text, FontSize = size, Align = align
                    }
                }
                , panel);
            }
            static public void Image(ref CuiElementContainer container, string panel, string png, UI4 dimensions) {
                container.Add(new CuiElement {
                    Name = CuiHelper.GetGuid(), Parent = panel, Components = {
                        new CuiRawImageComponent {
                            Png = png
                        }
                        , new CuiRectTransformComponent {
                            AnchorMin = dimensions.GetMin(), AnchorMax = dimensions.GetMax()
                        }
                    }
                }
                );
            }
            public static string Color(string hexColor, float alpha) {
                if (hexColor.StartsWith("#")) hexColor = hexColor.Substring(1);
                int red = int.Parse(hexColor.Substring(0, 2), NumberStyles.AllowHexSpecifier);
                int green = int.Parse(hexColor.Substring(2, 2), NumberStyles.AllowHexSpecifier);
                int blue = int.Parse(hexColor.Substring(4, 2), NumberStyles.AllowHexSpecifier);
                return $"{(double)red / 255} {(double)green / 255} {(double)blue / 255} {alpha}";
            }
        }
        public class UI4 {
            public float xMin, yMin, xMax, yMax;
            public UI4(float xMin, float yMin, float xMax, float yMax) {
                this.xMin = xMin;
                this.yMin = yMin;
                this.xMax = xMax;
                this.yMax = yMax;
            }
            public string GetMin() => $"{xMin} {yMin}";
            public string GetMax() => $"{xMax} {yMax}";
        }
#endregion
#region UI Creation
        private void OpenSkinMenu(BasePlayer player, string shortname = "", int column = 0, int page = 0) {
            DisplayMode displayMode;
            if (forcedMode == DisplayMode.None) {
                UserData data;
                if (userData.TryGetValue(player.userID, out data)) displayMode = data.displayMode;
                else displayMode = DisplayMode.Full;
            }
            else displayMode = forcedMode;
            if (displayMode == DisplayMode.Full) CreateSelectionMenu(player, shortname, column, page);
            else CreateSmallSelectionMenu(player, shortname, column, page);
        }
        private void CreateSelectionMenu(BasePlayer player, string shortname = "", int column = 0, int page = 0) {
            CuiElementContainer container = UI.Container(MainPanel, uiColor[Colors.Background], new UI4(0, 0, 1, 1), true);
            bool adminMode = adminToggle.Contains(player.userID);
            bool ownedMode = ownedToggle.Contains(player.userID);
            UserData data = userData[player.userID];
            int indexCount = 0;
            int columnIndex = column * 20;
            if (columnIndex > 0) UI.Button(ref container, MainPanel, uiColor[Colors.Button], msg("UI.Button.Up", player.userID), 12, new UI4(0.02f, 0.92f, 0.14f, 0.95f), $"psui.changepage {(string.IsNullOrEmpty(shortname) ? "empty" : shortname)} {column - 1} {page}");
            if (columnIndex + 20 < skinData.Keys.Count - 1) UI.Button(ref container, MainPanel, uiColor[Colors.Button], msg("UI.Button.Down", player.userID), 12, new UI4(0.02f, 0.08f, 0.14f, 0.11f), $"psui.changepage {(string.IsNullOrEmpty(shortname) ? "empty" : shortname)} {column + 1} {page}");
            string[] skinKeys = skinData.Keys.OrderBy(x => shortnameToDisplayname[x]).ToArray();
            for (int i = columnIndex; i < columnIndex + 20; i++) {
                if (i > skinKeys.Length - 1) break;
                string itemShortname = skinKeys.ElementAt(i);
                string displayName = shortnameToDisplayname[itemShortname];
                float[] position = GetItemPosition(indexCount);
                UI.Button(ref container, MainPanel, shortname == itemShortname ? uiColor[Colors.ButtonSelected] : uiColor[Colors.Button], displayName, 12, new UI4(position[0], position[1], position[2], position[3]), shortname == itemShortname ? "" : $"psui.changepage {itemShortname} {column} 0");
                indexCount++;
            }
            if (!string.IsNullOrEmpty(shortname)) {
                int itemCount = 0;
                int itemIndex = 48 * page;
                ulong[] skins = ownedMode ? (data.purchasedSkins.ContainsKey(shortname) ? data.purchasedSkins[shortname].Where(x => workshopItems.ContainsKey(shortname) && workshopItems[shortname].ContainsKey(x) && skinData.ContainsKey(shortname) && skinData[shortname].ContainsKey(x) && !skinData[shortname][x].isDisabled && HasImage(shortname, x)).ToArray() : new ulong[0]) : skinData[shortname].Where(x => workshopItems.ContainsKey(shortname) && workshopItems[shortname].ContainsKey(x.Key) && !x.Value.isDisabled && HasImage(shortname, x.Key)).Select(x => x.Key).ToArray();
                for (int i = itemIndex; i < itemIndex + 48; i++) {
                    if (i > skins.Length - 1) break;
                    ulong skinId = skins[i];
                    float[] position = GetButtonPosition(itemCount, 8);
                    UI.Image(ref container, MainPanel, GetImage(shortname, skinId), new UI4(position[0] + 0.01f, position[1], position[2] - 0.01f, position[3] - 0.01f));
                    UI.Button(ref container, MainPanel, "0 0 0 0", "", 0, new UI4(position[0], position[1], position[2] + 0.1f, position[3] - 0.01f), $"psui.selectitem {shortname} {skinId}");
                    itemCount++;
                }
                if (itemIndex > 0) UI.Button(ref container, MainPanel, uiColor[Colors.Button], msg("UI.Button.Previous", player.userID), 12, new UI4(0.17f, 0.04f, 0.27f, 0.07f), $"psui.changepage {(string.IsNullOrEmpty(shortname) ? "empty" : shortname)} {column} {page - 1}");
                if (itemIndex + 48 < skinData[shortname].Where(x => !x.Value.isDisabled).Count()) UI.Button(ref container, MainPanel, uiColor[Colors.Button], msg("UI.Button.Next", player.userID), 12, new UI4(0.87f, 0.04f, 0.97f, 0.07f), $"psui.changepage {(string.IsNullOrEmpty(shortname) ? "empty" : shortname)} {column} {page + 1}");
            }
            else UI.Label(ref container, MainPanel, FormatHelpText(DisplayMode.Full, player.userID), 12, new UI4(0.17f, 0.1f, 0.97f, 0.92f), TextAnchor.UpperLeft);
            UI.Button(ref container, MainPanel, uiColor[Colors.ButtonSelected], msg("UI.Exit", player.userID), 12, new UI4(0.02f, 0.04f, 0.14f, 0.07f), "psui.exit");
            UI.Button(ref container, MainPanel, ownedMode ? uiColor[Colors.ButtonSelected] : uiColor[Colors.Button], msg("UI.ShowOwned", player.userID), 12, new UI4(0.76f, 0.04f, 0.86f, 0.07f), $"psui.toggle owned {(string.IsNullOrEmpty(shortname) ? "empty" : shortname)} {column} 0");
            if (forcedMode == DisplayMode.None) UI.Button(ref container, MainPanel, uiColor[Colors.Button], msg("UI.Minimised", player.userID), 12, new UI4(0.65f, 0.04f, 0.75f, 0.07f), $"psui.toggle size {(string.IsNullOrEmpty(shortname) ? "empty" : shortname)} {column} {page}");
            if (permission.UserHasPermission(player.UserIDString, "playerskins.admin")) UI.Button(ref container, MainPanel, adminMode ? uiColor[Colors.ButtonSelected] : uiColor[Colors.Button], msg("UI.AdminMode", player.userID), 12, new UI4(0.28f, 0.04f, 0.38f, 0.07f), $"psui.toggle admin {(string.IsNullOrEmpty(shortname) ? "empty" : shortname)} {column} 0");
            if (configData.Purchase.Enabled) {
                UI.Panel(ref container, MainPanel, uiColor[Colors.Panel], new UI4(0.39f, 0.04f, 0.64f, 0.07f));
                UI.Label(ref container, MainPanel, string.Format((purchaseType == TokenType.ServerRewards ? msg("Money.RP", player.userID) : msg("Money.Eco", player.userID)), GetBalance(player.userID)), 12, new UI4(0.38f, 0.04f, 0.65f, 0.07f));
            }
            CuiHelper.DestroyUi(player, PopupPanel);
            CuiHelper.DestroyUi(player, MainPanel);
            CuiHelper.AddUi(player, container);
        }
        private void CreateSmallSelectionMenu(BasePlayer player, string shortname = "", int column = 0, int page = 0) {
            CuiElementContainer container = UI.Container(MainPanel, uiColor[Colors.Background], new UI4(0.2f, 0.12f, 0.45f, 0.92f), true);
            bool adminMode = adminToggle.Contains(player.userID);
            bool ownedMode = ownedToggle.Contains(player.userID);
            UserData data = userData[player.userID];
            int indexCount = 0;
            int columnIndex = column * 20;
            if (columnIndex > 0) UI.Button(ref container, MainPanel, uiColor[Colors.Button], msg("UI.Button.Up", player.userID), 10, new UI4(0.04f, 0.92f, 0.5f, 0.95f), $"psui.changepage {(string.IsNullOrEmpty(shortname) ? "empty" : shortname)} {column - 1} {page}");
            if (columnIndex + 20 < skinData.Keys.Count - 1) UI.Button(ref container, MainPanel, uiColor[Colors.Button], msg("UI.Button.Down", player.userID), 10, new UI4(0.04f, 0.08f, 0.5f, 0.11f), $"psui.changepage {(string.IsNullOrEmpty(shortname) ? "empty" : shortname)} {column + 1} {page}");
            string[] skinKeys = skinData.Keys.OrderBy(x => shortnameToDisplayname[x]).ToArray();
            for (int i = columnIndex; i < columnIndex + 20; i++) {
                if (i > skinKeys.Length - 1) break;
                string itemShortname = skinKeys.ElementAt(i);
                string displayName = shortnameToDisplayname[itemShortname];
                float[] position = GetItemPosition(indexCount, 0.04f, 0.88f, 0.46f, 0.04f);
                UI.Button(ref container, MainPanel, shortname == itemShortname ? uiColor[Colors.ButtonSelected] : uiColor[Colors.Button], displayName, 10, new UI4(position[0], position[1], position[2], position[3]), shortname == itemShortname ? "" : $"psui.changepage {itemShortname} {column} 0");
                indexCount++;
            }
            if (!string.IsNullOrEmpty(shortname)) {
// ... [Code preview truncated due to length. Full source in attached file] ...

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