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

FREE Remove : 1.2.4 1.2.4

Нет прав для скачивания
C#:
using Facepunch;
using Oxide.Core;
using Oxide.Core.Configuration;
using Oxide.Core.Libraries;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Oxide.Plugins {
    [Info("Remove", "Admin", "1.2.4")]
    class Remove : RustPlugin {
        static Remove inst;
        int resetTime;
        float refundPercent;
        float refundItemsPercent;
        float refundStoragePercent;
        bool friendRemove;
        bool clanRemove;
        bool EnTimedRemove;
        bool cupboardRemove;
        bool selfRemove;
        bool removeFriends;
        bool removeClans;
        bool refundItemsGive;
        float Timeout;
        private string PanelAnchorMin;
        private string PanelAnchorMax;
        private string PanelColor;
        private bool useNoEscape;
        private int TextFontSize;
        private string TextСolor;
        private string TextAnchorMin;
        private string TextAnchorMax;
        private bool EnabledBuildingUpgrade;
        protected override void LoadDefaultConfig() {
            GetVariable(Config, "Время действия режима удаления", out resetTime, 40);
            GetVariable(Config, "Включить выключение авто-улучшения при включении режима удаления (Поддержка плагина BuildingUpgrade с сайта RustPlugin.ru)", out EnabledBuildingUpgrade, false);
            GetVariable(Config, "Включить запрет на удаление объекта для игрока после истечения N времени указанным в конфигурации", out EnTimedRemove, false);
            GetVariable(Config, "Время на запрет удаление объекта после истечения указаного времени (в секундах)", out Timeout, 3600.0f);
            GetVariable(Config, "Процент возвращаемых ресурсов с Items (Максимум 1.0 - это 100%)", out refundItemsPercent, 1.0f);
            GetVariable(Config, "Процент возвращаемых ресурсов с построек (Максимум 1.0 - это 100%)", out refundPercent, 1.0f);
            GetVariable(Config, "Включить возрат объектов (При удаление объектов(сундуки, печки и тд.) будет возращать объект а не ресурсы)", out refundItemsGive, false);
            GetVariable(Config, "Процент выпадающих ресурсов (не вещей) с удаляемых ящиков (Максимум 1.0 - это 100%)", out refundStoragePercent, 1.0f);
            GetVariable(Config, "Разрешить удаление объектов друзей без авторизации в шкафу", out friendRemove, false);
            GetVariable(Config, "Разрешить удаление объектов соклановцев без авторизации в шкафу", out clanRemove, false);
            GetVariable(Config, "Разрешить удаление чужих объектов при наличии авторизации в шкафу", out cupboardRemove, false);
            GetVariable(Config, "Разрешить удаление собственных объектов без авторизации в шкафу", out selfRemove, false);
            GetVariable(Config, "Включить поддержку NoEscape (С сайта RustPlugin.ru)", out useNoEscape, false);
            GetVariable(Config, "Разрешить удаление обьектов друзьям", out removeFriends, false);
            GetVariable(Config, "Разрешить удаление объектов соклановцев", out removeClans, false);
            GetVariable(Config, "GUI: Панель AnchorMin", out PanelAnchorMin, "0.0 0.908");
            GetVariable(Config, "GUI: Панель AnchorMax", out PanelAnchorMax, "1 0.958");
            GetVariable(Config, "GUI: Цвет фона", out PanelColor, "0 0 0 0.50");
            GetVariable(Config, "GUI: Размер текста", out TextFontSize, 18);
            GetVariable(Config, "GUI: Цвет текста", out TextСolor, "0 0 0 1");
            GetVariable(Config, "GUI: Текст AnchorMin", out TextAnchorMin, "0 0");
            GetVariable(Config, "GUI: Текст AnchorMax", out TextAnchorMax, "1 1");
            SaveConfig();
        }
        public static void GetVariable<T>(DynamicConfigFile config, string name, out T value, T defaultValue) {
            config[name] = value = config[name] == null ? defaultValue : (T)Convert.ChangeType(config[name], typeof(T));
        }
        static int constructionColl = LayerMask.GetMask(new string[] {
            "Construction", "Deployable", "Prevent Building", "Deployed"
        }
        );
        private static Dictionary<string, int> deployedToItem = new Dictionary<string, int>();
        Dictionary<BasePlayer, int> timers = new Dictionary<BasePlayer, int>();
        Dictionary<ulong, string> activePlayers = new Dictionary<ulong, string>();
        int currentRemove = 0;
        [PluginReference]
        Plugin Clans;
        [PluginReference]
        Plugin Friends;
        [PluginReference]
        Plugin NoEscape;
        [PluginReference]
        Plugin MutualPermission;
        [PluginReference]
        Plugin BuildingUpgrade;
        bool IsClanMember(ulong playerID, ulong targetID) {
            if (plugins.Exists("Clans")) return (bool)(Clans?.Call("IsTeammate", playerID, targetID) ?? false);
            return false;
        }
        bool IsFriends(ulong playerID, ulong friendId) {
            if (plugins.Exists("Friends")) {
                return (bool)(Friends?.Call("AreFriends", playerID, friendId) ?? false);
            }
            if (plugins.Exists("MutualPermission")) return (bool)(MutualPermission?.Call("isPermissionAllowed", "Home", playerID, friendId) ?? false);
            return false;
        }
        private Dictionary<BasePlayer, DateTime> Cooldowns = new Dictionary<BasePlayer, DateTime>();
        private double Cooldown = 30f;
        private void OnPlayerActiveItemChanged(BasePlayer player, Item newItem) {
            Item activeItem = player.GetActiveItem();
            if (activeItem == null || activeItem.info.shortname != "building.planner") return;
            if (EnTimedRemove) {
                if (activeItem.info.shortname == "building.planner") {
                    if (Cooldowns.ContainsKey(player)) {
                        double seconds = Cooldowns[player].Subtract(DateTime.Now).TotalSeconds;
                        if (seconds >= 0) return;
                    }
                    SendReply(player, Messages["enabledRemoveTimer"], NumericalFormatter.FormatTime(Timeout, player.userID));
                    Cooldowns[player] = DateTime.Now.AddSeconds(Cooldown);
                }
            }
        }
        [ChatCommand("remove")]
        void cmdRemove(BasePlayer player, string command, string[] args) {
            if (player == null) return;
            if (!permission.UserHasPermission(player.UserIDString, "remove.use")) {
                SendReply(player, Messages["NoPermission"]);
                return;
            }
            if (args == null || args.Length == 0) {
                if (activePlayers.ContainsKey(player.userID)) {
                    timers.Remove(player);
                    DeactivateRemove(player.userID);
                    DestroyUI(player);
                    return;
                }
                else {
                    if (EnabledBuildingUpgrade) {
                        var upgradeEnabled = (bool)BuildingUpgrade?.Call("BuildingUpgradeActivate", player.userID);
                        if (upgradeEnabled) {
                            BuildingUpgrade?.Call("BuildingUpgradeDeactivate", player.userID);
                        }
                    }
                    SendReply(player, Messages["enabledRemove"]);
                    timers[player] = resetTime;
                    DrawUI(player, resetTime, "normal");
                    ActivateRemove(player.userID, "normal");
                    return;
                }
            }
            switch (args[0]) {
                case "admin" : if (!permission.UserHasPermission(player.UserIDString, "remove.admin") && !player.IsAdmin) {
                    SendReply(player, Messages["NoPermission"]);
                    return;
                }
                if (activePlayers.ContainsKey(player.userID)) {
                    timers.Remove(player);
                    DeactivateRemove(player.userID);
                    DestroyUI(player);
                    return;
                }
                timers[player] = resetTime;
                DrawUI(player, resetTime, "admin");
                ActivateRemove(player.userID, "admin");
                break;
                case "all" : if (!permission.UserHasPermission(player.UserIDString, "remove.admin") && !player.IsAdmin) {
                    SendReply(player, Messages["NoPermission"]);
                    return;
                }
                if (activePlayers.ContainsKey(player.userID)) {
                    timers.Remove(player);
                    DeactivateRemove(player.userID);
                    DestroyUI(player);
                    return;
                }
                timers[player] = resetTime;
                DrawUI(player, resetTime, "all");
                ActivateRemove(player.userID, "all");
                break;
            }
        }
        [ConsoleCommand("remove.toggle")]
        void cmdConsoleRemove(ConsoleSystem.Arg args) {
            var player = args.Player();
            if (player == null) return;
            if (!permission.UserHasPermission(player.UserIDString, "remove.use")) {
                SendReply(player, Messages["NoPermission"]);
                return;
            }
            if (args.Args == null || args.Args.Length == 0) {
                if (activePlayers.ContainsKey(player.userID)) {
                    timers.Remove(player);
                    DeactivateRemove(player.userID);
                    DestroyUI(player);
                    return;
                }
                else {
                    SendReply(player, Messages["enabledRemove"]);
                    timers[player] = resetTime;
                    DrawUI(player, resetTime, "normal");
                    ActivateRemove(player.userID, "normal");
                    return;
                }
            }
            switch (args.Args[0]) {
                case "admin" : if (!permission.UserHasPermission(player.UserIDString, "remove.admin") && !player.IsAdmin) {
                    SendReply(player, Messages["NoPermission"]);
                    return;
                }
                if (activePlayers.ContainsKey(player.userID)) {
                    timers.Remove(player);
                    DeactivateRemove(player.userID);
                    DestroyUI(player);
                    return;
                }
                timers[player] = resetTime;
                DrawUI(player, resetTime, "admin");
                ActivateRemove(player.userID, "admin");
                break;
                case "all" : if (!permission.UserHasPermission(player.UserIDString, "remove.admin") && !player.IsAdmin) {
                    SendReply(player, Messages["NoPermission"]);
                    return;
                }
                if (activePlayers.ContainsKey(player.userID)) {
                    timers.Remove(player);
                    DeactivateRemove(player.userID);
                    DestroyUI(player);
                    return;
                }
                timers[player] = resetTime;
                DrawUI(player, resetTime, "all");
                ActivateRemove(player.userID, "all");
                break;
            }
        }
        Dictionary<uint, float> entityes = new Dictionary<uint, float>();
        void LoadEntity() {
            try {
                entityes = Interface.GetMod().DataFileSystem.ReadObject<Dictionary<uint, float>>($"Remove_NewEntity");
            }
            catch {
                entityes = new Dictionary<uint, float>();
            }
        }
        void CheckEntity() {
            List<uint> Listed = new List<uint>();
            foreach (var ent in entityes) {
                var Entity = BaseEntity.serverEntities.Find(ent.Key);
                if (Entity == null) {
                    Listed.Add(ent.Key);
                }
            }
            if (Listed.Count > 0) {
                Listed.ForEach(p => entityes.Remove(p));
            }
        }
        void OnEntityBuilt(Planner plan, GameObject go) {
            if (plan == null || go == null) return;
            if (EnTimedRemove) {
                BaseEntity entity = go.ToBaseEntity();
                if (entity?.net?.ID == null) return;
                entityes.Add(entity.net.ID, Timeout);
            }
        }
        void OnEntityKill(BaseNetworkable entity) {
            if (entity == null || entity?.net?.ID == null) return;
            try {
                if (entityes.ContainsKey(entity.net.ID)) entityes.Remove(entity.net.ID);
            }
            catch (NullReferenceException) {
            }
        }
        void OnNewSave() {
            if (EnTimedRemove) {
                Puts("Обнаружен вайп.Очищаем сохраненные объекты");
                LoadEntity();
                entityes.Clear();
            }
        }
        void OnServerSave() {
            Interface.Oxide.DataFileSystem.WriteObject("Remove_NewEntity", entityes);
        }
        void Loaded() {
            if (EnTimedRemove) LoadEntity();
            PermissionService.RegisterPermissions(this, permisions);
        }
        public List<string> permisions = new List<string>() {
            "remove.admin", "remove.use"
        }
        ;
        void Unload() {
            foreach (var player in BasePlayer.activePlayerList) {
                DestroyUI(player);
            }
            OnServerSave();
        }
        private Timer entitycheck;
        int check = 30;
        void OnServerInitialized() {
            inst = this;
            LoadDefaultConfig();
            if (removeFriends) {
                if (!plugins.Exists("Friends")) {
                    PrintWarning("Plugin Friends not found.Remove of friends buildings is disabled");
                    removeFriends = false;
                }
            }
            if (removeClans) {
                if (!plugins.Exists("Clans")) {
                    PrintWarning("Plugin Clans not found.Remove of clans buildings is disabled");
                    removeClans = false;
                }
            }
            deployedToItem.Clear();
            LoadEntity();
            CheckEntity();
            lang.RegisterMessages(Messages, this, "en");
            Messages = lang.GetMessages("en", this);
            InitRefundItems();
            timer.Every(1f, TimerHandler);
            if (EnTimedRemove) entitycheck = timer.Every(check, TimerEntity);
            List<ItemDefinition> ItemsDefinition = ItemManager.GetItemDefinitions() as List<ItemDefinition>;
            foreach (ItemDefinition itemdef in ItemsDefinition) {
                if (itemdef?.GetComponent<ItemModDeployable>() == null) continue;
                if (deployedToItem.ContainsKey(itemdef.GetComponent<ItemModDeployable>().entityPrefab.resourcePath)) continue;
                deployedToItem.Add(itemdef.GetComponent<ItemModDeployable>().entityPrefab.resourcePath, itemdef.itemid);
            }
        }
        private bool CupboardPrivlidge(BasePlayer player, Vector3 position, BaseEntity entity) {
            return player.IsBuildingAuthed(position, new Quaternion(0, 0, 0, 0), new Bounds(Vector3.zero, Vector3.zero));
        }
        void RemoveAllFrom(Vector3 pos) {
            removeFrom.Add(pos);
            DelayRemoveAll();
        }
        List<BaseEntity> wasRemoved = new List<BaseEntity>();
        List<Vector3> removeFrom = new List<Vector3>();
        void DelayRemoveAll() {
            if (currentRemove >= removeFrom.Count) {
                currentRemove = 0;
                removeFrom.Clear();
                wasRemoved.Clear();
                return;
            }
            List<BaseEntity> list = Pool.GetList<BaseEntity>();
            Vis.Entities<BaseEntity>(removeFrom[currentRemove], 3f, list, constructionColl);
            for (int i = 0; i < list.Count; i++) {
                BaseEntity ent = list[i];
                if (wasRemoved.Contains(ent)) continue;
                if (!removeFrom.Contains(ent.transform.position)) removeFrom.Add(ent.transform.position);
                wasRemoved.Add(ent);
                DoRemove(ent);
            }
            currentRemove++;
            timer.Once(0.01f, () => DelayRemoveAll());
        }
        static void DoRemove(BaseEntity removeObject) {
            if (removeObject == null) return;
            StorageContainer Container = removeObject.GetComponent<StorageContainer>();
            if (Container != null) {
                DropUtil.DropItems(Container.inventory, removeObject.transform.position, Container.dropChance);
            }
            EffectNetwork.Send(new Effect("assets/bundled/prefabs/fx/item_break.prefab", removeObject, 0, Vector3.up, Vector3.zero) {
                scale = UnityEngine.Random.Range(0f, 1f)
            }
            );
            removeObject.KillMessage();
        }
        void TryRemove(BasePlayer player, BaseEntity removeObject) {
            RemoveAllFrom(removeObject.transform.position);
        }
        bool OnRemoveActivate(ulong player) {
            if (activePlayers.ContainsKey(player)) {
                return true;
            }
            return false;
        }
        void RemoveDeativate(ulong player) {
            if (activePlayers.ContainsKey(player)) {
                var pl = BasePlayer.FindByID(player);
                if (pl != null) {
                    timers.Remove(pl);
                    DeactivateRemove(pl.userID);
                    DestroyUI(pl);
                }
            }
        }
        object OnHammerHit(BasePlayer player, HitInfo info) {
            if (info == null) return null;
            var entity = info?.HitEntity;
            if (entity == null) return null;
            if (entity.IsDestroyed) return false;
            if (!activePlayers.ContainsKey(player.userID)) return null;
            if (entity.OwnerID == 0) return false;
            switch (activePlayers[player.userID]) {
                case "all" : TryRemove(player, info.HitEntity);
                var pos = player.transform.position;
                RemoveEntityAll(player, entity, pos);
                return true;
                case "admin" : RemoveEntityAdmin(player, entity);
                return true;
                case "normal" : if (entity.ShortPrefabName.Contains("recycler")) return false;
                if ((!(entity is DecayEntity) && !(entity is Signage)) && !entity.ShortPrefabName.Contains("shelves") && !entity.ShortPrefabName.Contains("ladder") && !entity.ShortPrefabName.Contains("quarry")) return null;
                if (!entity.OwnerID.IsSteamId()) return null;
                var ret = Interface.Call("CanRemove", player, entity);
                if (ret is string) {
                    SendReply(player, (string)ret);
                    return null;
                }
                if (ret is bool && (bool)ret) {
                    RemoveEntity(player, entity);
                    return true;
                }
                if (useNoEscape) {
                    if (plugins.Exists("NoEscape")) {
                        var time = (bool)NoEscape.Call("IsRaidBlock", player.userID);
                        if (time) {
                            SendReply(player, string.Format(Messages["raidremove"], NumericalFormatter.FormatTime(Convert.ToInt32(time), player.userID)));
                            return null;
                        }
                    }
                }
                var privilege = player.GetBuildingPrivilege(player.WorldSpaceBounds());
                if (cupboardRemove) {
                    if (privilege != null && player.IsBuildingAuthed()) {
                        RemoveEntity(player, entity);
                        return true;
                    }
                }
                if (privilege != null && !player.IsBuildingAuthed()) {
                    if (selfRemove && entity.OwnerID == player.userID) {
                        RemoveEntity(player, entity);
                        return true;
                    }
                    if (friendRemove) {
                        if (removeFriends) {
                            if (IsFriends(entity.OwnerID, player.userID)) {
                                RemoveEntity(player, entity);
                                return true;
                            }
                        }
                    }
                    if (clanRemove) {
                        if (removeClans) {
                            if (IsClanMember(entity.OwnerID, player.userID)) {
                                RemoveEntity(player, entity);
                                return true;
                            }
                        }
                    }
                    SendReply(player, Messages["ownerCup"]);
                    return false;
                }
                if (entity.OwnerID != player.userID) {
                    if (removeFriends) {
                        if (IsFriends(entity.OwnerID, player.userID)) {
                            RemoveEntity(player, entity);
                            return true;
                        }
                    }
                    if (removeClans) {
                        if (IsClanMember(entity.OwnerID, player.userID)) {
                            RemoveEntity(player, entity);
                            return true;
                        }
                    }
                    SendReply(player, Messages["norights"]);
                    return false;
                }
                RemoveEntity(player, entity);
                return true;
            }
            return null;
        }
        private static string Format(int units, string form1, string form2, string form3) {
            var tmp = units % 10;
            if (units >= 5 && units <= 20 || tmp >= 5 && tmp <= 9) return $"{units} {form1}";
            if (tmp >= 2 && tmp <= 4) return $"{units} {form2}";
            return $"{units} {form3}";
        }
        private static class NumericalFormatter {
            private static string GetNumEndings(int origNum, string[] forms) {
                string result;
                var num = origNum % 100;
                if (num >= 11 && num <= 19) {
                    result = forms[2];
                }
                else {
                    num = num % 10;
                    switch (num) {
                        case 1 : result = forms[0];
                        break;
                        case 2 : case 3 : case 4 : result = forms[1];
                        break;
                        default : result = forms[2];
                        break;
                    }
                }
                return string.Format("{0} {1} ", origNum, result);
            }
            private static bool IsEng(object player) => inst.lang.GetLanguage(GetUserId(player)) != "ru";
            private static string FormatSeconds(int seconds, bool eng) => GetNumEndings(seconds, eng ? new[] {
                "second", "seconds", "seconds"
            }
            : new[] {
                "секунда", "секунды", "секунд"
            }
            );
            private static string FormatMinutes(int minutes, bool eng) => GetNumEndings(minutes, eng ? new[] {
                "minute", "minutes", "minutes"
            }
            : new[] {
                "минута", "минуты", "минут"
            }
            );
            private static string FormatHours(int hours, bool eng) => GetNumEndings(hours, eng ? new[] {
                "hour", "hours", "hours"
            }
            : new[] {
                "час", "часа", "часов"
            }
            );
            private static string FormatDays(int days, bool eng) => GetNumEndings(days, eng ? new[] {
                "day", "days", "days"
            }
            : new[] {
                "день", "дня", "дней"
            }
            );
            private static string FormatTime(TimeSpan timeSpan, bool eng) {
                string result = string.Empty;
                if (timeSpan.Days > 0) result += FormatDays(timeSpan.Days, eng);
                if (timeSpan.Hours > 0) result += FormatHours(timeSpan.Hours, eng);
                if (timeSpan.Minutes > 0) result += FormatMinutes(timeSpan.Minutes, eng);
                if (timeSpan.Seconds > 0) result += FormatSeconds(timeSpan.Seconds, eng).TrimEnd(' ');
                return result;
            }
            public static string FormatTime(int seconds, object player) => FormatTime(new TimeSpan(0, 0, seconds), IsEng(player));
            public static string FormatTime(float seconds, object player) => FormatTime((int)Math.Round(seconds), player);
            public static string FormatTime(TimeSpan time, object player) => FormatTime((int)Math.Round(time.TotalSeconds), player);
            public static string FromatSlots(int slots, object player) => GetNumEndings(slots, IsEng(player) ? new[] {
                "slot", "slots", "slots"
            }
            : new[] {
                "слот", "слота", "слотов"
            }
            );
        }
        private static string GetUserId(object player) {
            var id = player is BasePlayer ? ((BasePlayer)player).UserIDString : player.ToString();
            if (inst.permission.UserIdValid(id)) return id;
            inst.PrintError($"Trying to get the player data with invalide UserID \"{player}\"!");
            return null;
        }
        void TimerEntity() {
            List<uint> remove = entityes.Keys.ToList().Where(ent => (entityes[ent] -= check) < 0).ToList();
            List<uint> Remove = new List<uint>();
            foreach (var entity in entityes) {
                var seconds = entity.Value;
                if (seconds < 0.0f) {
                    Remove.Add(entity.Key);
                    continue;
                }
                if (seconds > Timeout) {
                    entityes[entity.Key] = Timeout;
                    continue;
                }
            }
            foreach (var id in Remove) {
                entityes.Remove(id);
            }
        }
        void TimerHandler() {
            foreach (var player in timers.Keys.ToList()) {
                var seconds = --timers[player];
                if (seconds <= 0) {
                    timers.Remove(player);
                    DeactivateRemove(player.userID);
                    DestroyUI(player);
                    continue;
                }
                DrawUI(player, seconds, activePlayers[player.userID]);
            }
        }
        void RemoveEntity(BasePlayer player, BaseEntity entity) {
            if (EnTimedRemove) {
                if (!entityes.ContainsKey(entity.net.ID)) {
                    SendReply(player, Messages["blockremovetime"], NumericalFormatter.FormatTime(Timeout, player.userID));
                    return;
                }
            }
            Refund(player, entity);
            entity.Kill();
            UpdateTimer(player, "normal");
        }
        void RemoveEntityAdmin(BasePlayer player, BaseEntity entity) {
            entity.Kill();
            UpdateTimerAdmin(player, "admin");
        }
        void RemoveEntityAll(BasePlayer player, BaseEntity entity, Vector3 pos) {
            removeFrom.Add(pos);
            DelayRemoveAll();
            UpdateTimerAll(player, "all");
        }
        Dictionary<uint, Dictionary<ItemDefinition, int>> refundItems = new Dictionary<uint, Dictionary<ItemDefinition, int>>();
        void Refund(BasePlayer player, BaseEntity entity) {
            if (entity is BuildingBlock) {
                BuildingBlock buildingblock = entity as BuildingBlock;
                if (buildingblock.blockDefinition == null) return;
                int buildingblockGrade = (int)buildingblock.grade;
                if (buildingblock.blockDefinition.grades[buildingblockGrade] != null) {
                    float refundRate = buildingblock.healthFraction * refundPercent;
                    List<ItemAmount> currentCost = buildingblock.blockDefinition.grades[buildingblockGrade].costToBuild as List<ItemAmount>;
                    foreach (ItemAmount ia in currentCost) {
                        int amount = (int)(ia.amount * refundRate);
                        if (amount <= 0 || amount > ia.amount || amount >= int.MaxValue) amount = 1;
                        if (refundRate != 0) {
                            Item x = ItemManager.CreateByItemID(ia.itemid, amount);
                            player.GiveItem(x, BaseEntity.GiveItemReason.PickedUp);
                        }
                    }
                }
                return;
            }
            StorageContainer storage = entity as StorageContainer;
            if (storage) {
                if (storage.inventory.itemList.Count > 0) for (int i = storage.inventory.itemList.Count - 1; i >= 0; i--) {
                    var item = storage.inventory.itemList[i];
                    if (item == null) continue;
                    if (item.info.shortname == "water") continue;
                    item.amount = (int)(item.amount * refundStoragePercent);
                    float single = 20f;
                    Vector3 vector32 = Quaternion.Euler(UnityEngine.Random.Range(-single * 0.1f, single * 0.1f), UnityEngine.Random.Range(-single * 0.1f, single * 0.1f), UnityEngine.Random.Range(-single * 0.1f, single * 0.1f)) * Vector3.up;
                    BaseEntity baseEntity = item.Drop(storage.transform.position + (Vector3.up * 0f), vector32 * UnityEngine.Random.Range(5f, 10f), UnityEngine.Random.rotation);
                    baseEntity.SetAngularVelocity(UnityEngine.Random.rotation.eulerAngles * 5f);
                }
            }
            if (deployedToItem.ContainsKey(entity.gameObject.name)) {
                ItemDefinition def = ItemManager.FindItemDefinition(deployedToItem[entity.gameObject.name]);
                foreach (var ingredient in def.Blueprint.ingredients) {
                    var reply = 1312;
                    if (reply == 0) {
                    }
                    var amountOfIngridient = ingredient.amount;
                    var amount = Mathf.Floor(amountOfIngridient * refundItemsPercent);
                    if (amount <= 0 || amount > amountOfIngridient || amount >= int.MaxValue) amount = 1;
                    if (!refundItemsGive) {
                        if (refundItemsPercent != 0) {
                            Item x = ItemManager.Create(ingredient.itemDef, (int)amount);
                            player.GiveItem(x, BaseEntity.GiveItemReason.PickedUp);
                        }
                    }
                    else {
                        GiveAndShowItem(player, deployedToItem[entity.PrefabName], 1);
                        return;
                    }
                }
            }
        }
        void GiveAndShowItem(BasePlayer player, int item, int amount) {
            Item x = ItemManager.CreateByItemID(item, amount);
            player.GiveItem(x, BaseEntity.GiveItemReason.PickedUp);
        }
        void InitRefundItems() {
            foreach (var item in ItemManager.itemList) {
                var deployable = item.GetComponent<ItemModDeployable>();
                if (deployable != null) {
                    if (item.Blueprint == null || deployable.entityPrefab == null) continue;
                    refundItems.Add(deployable.entityPrefab.resourceID, item.Blueprint.ingredients.ToDictionary(p => p.itemDef, p => (Mathf.CeilToInt(p.amount * refundPercent))));
                }
            }
        }
        private string GUI = @"[{""name"": ""remove.panel"",""parent"": ""Hud"",""components"": [{""type"": ""UnityEngine.UI.Image"",""color"": ""{PanelColor}""},{""type"": ""RectTransform"",""anchormin"": ""{PanelAnchorMin}"",""anchormax"": ""{PanelAnchorMax}""}]}, {""name"": ""remove.text"",""parent"": ""remove.panel"",""components"": [{""type"": ""UnityEngine.UI.Text"",""text"": ""{msg}"",""fontSize"": ""{TextFontSize}"",""align"": ""MiddleCenter""}, {""type"": ""UnityEngine.UI.Outline"",""color"": ""{TextСolor}"",""distance"": ""0.1 -0.1""}, {""type"": ""RectTransform"",""anchormin"": ""{TextAnchorMin}"",""anchormax"": ""{TextAnchorMax}""}]}]";
        void DrawUI(BasePlayer player, int seconds, string type) {
            DestroyUI(player);
            var msg = "";
            if (type == "normal") {
                msg = Messages["RNormal"];
            }
            else msg = type == "admin" ? Messages["RAdmin"] : Messages["RAll"];
            CuiHelper.AddUi(player, GUI.Replace("{PanelColor}", PanelColor.ToString()).Replace("{PanelAnchorMin}", PanelAnchorMin.ToString()).Replace("{PanelAnchorMax}", PanelAnchorMax.ToString()).Replace("{TextFontSize}", TextFontSize.ToString()).Replace("{TextСolor}", TextСolor.ToString()).Replace("{TextAnchorMin}", TextAnchorMin.ToString()).Replace("{TextAnchorMax}", TextAnchorMax.ToString()).Replace("{msg}", msg).Replace("{1}", NumericalFormatter.FormatTime(seconds, player.userID)));
        }
        void DestroyUI(BasePlayer player) {
            CuiHelper.DestroyUi(player, "remove.panel");
            CuiHelper.DestroyUi(player, "remove.text");
        }
        void ActivateRemove(ulong userId, string type) {
            if (!activePlayers.ContainsKey(userId)) {
                activePlayers.Add(userId, type);
            }
        }
        void DeactivateRemove(ulong userId) {
            if (activePlayers.ContainsKey(userId)) {
                activePlayers.Remove(userId);
            }
        }
        void UpdateTimer(BasePlayer player, string type) {
            timers[player] = resetTime;
            DrawUI(player, timers[player], type);
        }
        void UpdateTimerAdmin(BasePlayer player, string type) {
            timers[player] = resetTime;
            DrawUI(player, timers[player], type);
        }
        void UpdateTimerAll(BasePlayer player, string type) {
            timers[player] = resetTime;
            DrawUI(player, timers[player], type);
        }
        Dictionary<string, string> Messages = new Dictionary<string, string>() {
            {
                "raidremove", "Ремув во время рейда запрещён!\nОсталось<color=#ffd479> {0}</color>"
            }
            , {
                "blockremovetime", "Извините, но этот объект уже нельзя удалить, он был создан более чем <color=#ffd479>{0}</color> назад"
            }
            , {
                "NoPermission", "У Вас нету прав на использование этой команды"
            }
            , {
                "enabledRemove", "<size=16>Используйте киянку для удаления объектов</size>"
            }
            , {
                "enabledRemoveTimer", "<color=#ffd479>Внимание:</color> Объекты созданые более чем <color=#ffd479>{0}</color> назад, удалить нельзя"
            }
            , {
                "ownerCup", "Что бы удалять постройки, вы должны быть авторизированы в шкафу"
            }
            , {
                "norights", "Вы не имеете права удалять чужие постройки!"
            }
            , {
                "RNormal", "Режим удаления выключится через <color=#ffd479>{1}</color>"
            }
            , {
                "RAdmin", "Режим админ удаления выключится через <color=#ffd479>{1}</color>"
            }
            , {
                "RAll", "Режим удаления всех объектов выключится через <color=#ffd479>{1}</color>"
            }
            ,
        }
        ;
        public static class PermissionService {
            public static Permission permission = Interface.GetMod().GetLibrary<Permission>();
            public static bool HasPermission(BasePlayer player, string permissionName) {
                if (player == null || string.IsNullOrEmpty(permissionName)) return false;
                var uid = player.UserIDString;
                if (permission.UserHasPermission(uid, permissionName)) return true;
                return false;
            }
            public static void RegisterPermissions(Plugin owner, List<string> permissions) {
                if (owner == null) throw new ArgumentNullException("owner");
                if (permissions == null) throw new ArgumentNullException("commands");
                foreach (var permissionName in permissions.Where(permissionName => !permission.PermissionExists(permissionName))) {
                    permission.RegisterPermission(permissionName, owner);
                }
            }
        }
    }
}

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