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

FREE WipeBlock : 2.0.0 2.0.0

Нет прав для скачивания
C#:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
using Network;
using Oxide.Core;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using UnityEngine;
using Facepunch;
namespace Oxide.Plugins {
    [Info("Wipe Block", "King.", "2.0.0")]
    public class WipeBlock : RustPlugin {
        [PluginReference]
        private Plugin Stadia;
#region [Vars]
        private const String effectSoundSuccess = "assets/bundled/prefabs/fx/notice/item.select.fx.prefab";
        private const String Layer = "WipeBlock.Layer";
        private const String IgnorePermission = "WipeBlock.ignore";
        private const Int32 PermanentBlockTime = 99999999;
        static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0);
        static Double CurrentTime() {
            return DateTime.UtcNow.Subtract(epoch).TotalSeconds;
        }
        private Double IsBlocked(ItemDefinition itemDefinition) => IsBlocked(itemDefinition.shortname);
        private Double UnBlockTime(Int32 amount) => SaveRestore.SaveCreatedTime.ToUniversalTime().Subtract(epoch).TotalSeconds + amount;
        private Dictionary<String, Int32> _itemIds = new Dictionary<String, Int32>();
        private List<BasePlayer> openUI = new List<BasePlayer>();
        private List<UInt64> fix = new List<UInt64>();
        private List<String> unlockedItem = new List<String>();
        private readonly HashSet<String> stageBlockedItems = new HashSet<String>();
        private String currentStage = String.Empty;
        private static readonly String[] PermanentDefaultItems = {
            "flameturret", "trap.landmine", "tincan.alarm", "ammo.rifle.explosive", "ammo.rifle.hv", "ammo.rifle.incendiary", "samsite", "spikes.floor", "explosive.satchel", "grenade.f1", "ammo.rocket.sam", "trap.bear", "guntrap", "spikes.trap", "catapult.ammo.bee", "ammo.rocket.fire", "grenade.beancan", "ammo.shotgun.fire", "ammo.rocket.smoke", "grenade.flashbang", "ammo.rocket.hv", "grenade.bee", "ammo.rocket.seeker", "grenade.smoke", "catapult.ammo.explosive", "arrow.fire", "heavy.plate.helmet", "heavy.plate.jacket", "heavy.plate.pants"
        }
        ;
        private static readonly String[] PermanentThrownPrefabs = {
            "explosive.satchel.deployed", "grenade.f1.deployed", "grenade.beancan.deployed", "grenade.flashbang.deployed", "grenade.smoke.deployed"
        }
        ;
        private static readonly String[] PvpBlockedItems = {
            "explosive.timed", "ammo.grenadelauncher.smoke", "ammo.grenadelauncher.buckshot", "rocket.launcher", "ammo.rocket.basic", "ammo.rocket.hv", "ammo.rocket.mlrs", "rocket.launcher.dragon", "multiplegrenadelauncher", "ammo.grenadelauncher.he", "rocket.launcher.rpg7"
        }
        ;
        private static readonly String[] PvpBlockedThrownPrefabs = {
            "explosive.timed.deployed", "explosive.timed", "ammo.grenadelauncher.smoke", "ammo.grenadelauncher.buckshot", "rocket.launcher", "ammo.rocket.basic", "ammo.rocket.hv", "rocket.launcher.dragon", "multiplegrenadelauncher", "ammo.grenadelauncher.he", "rocket.launcher.rpg7"
        }
        ;
#endregion
#region [Config]
        private PluginConfig config;
        protected override void LoadDefaultConfig() {
            config = PluginConfig.DefaultConfig();
        }
        protected override void LoadConfig() {
            base.LoadConfig();
            config = Config.ReadObject<PluginConfig>();
            if (config.PluginVersion < Version) UpdateConfigValues();
            EnsurePermanentDefaults();
            Config.WriteObject(config, true);
        }
        private void UpdateConfigValues() {
            PluginConfig baseConfig = PluginConfig.DefaultConfig();
            if (config.PluginVersion < Version) {
                config.PluginVersion = Version;
                if (Version == new VersionNumber(1, 0, 0)) {
                }
                PrintWarning("Config checked completed!");
            }
            config.PluginVersion = Version;
        }
        protected override void SaveConfig() {
            Config.WriteObject(config);
        }
        private class PluginConfig {
            [JsonProperty(PropertyName = "Блокировка предметов")]
            public Dictionary<String, Int32> blockItems;
            [JsonProperty("Предметы которые нельзя кидать")]
            public List<String> blockItemsThrown;
            [JsonProperty("Config version")]
            public VersionNumber PluginVersion = new VersionNumber();
            public static PluginConfig DefaultConfig() {
                return new PluginConfig() {
                    blockItems = new Dictionary<String, Int32>() {
                        ["flameturret"]
                        = PermanentBlockTime, ["trap.landmine"] = PermanentBlockTime, ["tincan.alarm"] = PermanentBlockTime, ["ammo.rifle.explosive"] = PermanentBlockTime, ["ammo.rifle.hv"] = PermanentBlockTime, ["ammo.rifle.incendiary"] = PermanentBlockTime, ["samsite"] = PermanentBlockTime, ["spikes.floor"] = PermanentBlockTime, ["explosive.satchel"] = PermanentBlockTime, ["grenade.f1"] = PermanentBlockTime, ["ammo.rocket.sam"] = PermanentBlockTime, ["trap.bear"] = PermanentBlockTime, ["guntrap"] = PermanentBlockTime, ["spikes.trap"] = PermanentBlockTime, ["catapult.ammo.bee"] = PermanentBlockTime, ["ammo.rocket.fire"] = PermanentBlockTime, ["grenade.beancan"] = PermanentBlockTime, ["ammo.shotgun.fire"] = PermanentBlockTime, ["ammo.rocket.smoke"] = PermanentBlockTime, ["grenade.flashbang"] = PermanentBlockTime, ["ammo.rocket.hv"] = PermanentBlockTime, ["grenade.bee"] = PermanentBlockTime, ["ammo.rocket.seeker"] = PermanentBlockTime, ["grenade.smoke"] = PermanentBlockTime, ["catapult.ammo.explosive"] = PermanentBlockTime, ["arrow.fire"] = PermanentBlockTime, ["heavy.plate.helmet"] = PermanentBlockTime, ["heavy.plate.jacket"] = PermanentBlockTime, ["heavy.plate.pants"] = PermanentBlockTime,
                    }
                    , blockItemsThrown = new List<String>() {
                        "explosive.satchel.deployed", "grenade.f1.deployed", "grenade.beancan.deployed", "grenade.flashbang.deployed", "grenade.smoke.deployed",
                    }
                    , PluginVersion = new VersionNumber()
                }
                ;
            }
        }
        private void EnsurePermanentDefaults() {
            if (config.blockItems == null) config.blockItems = new Dictionary<String, Int32>();
            foreach (String shortName in PermanentDefaultItems) config.blockItems[shortName] = PermanentBlockTime;
            foreach (String shortName in PvpBlockedItems) if (!config.blockItems.ContainsKey(shortName)) config.blockItems[shortName] = 0;
            if (config.blockItemsThrown == null) config.blockItemsThrown = new List<String>();
            foreach (String prefab in PermanentThrownPrefabs) if (!config.blockItemsThrown.Contains(prefab)) config.blockItemsThrown.Add(prefab);
        }
#endregion
#region [Oxide-Api]
        private void OnServerInitialized() {
            if (!permission.PermissionExists(IgnorePermission)) permission.RegisterPermission(IgnorePermission, this);
            foreach (KeyValuePair<String, Int32> item in config.blockItems) if (item.Value != PermanentBlockTime && IsBlocked(item.Key) <= 0) AddUnlockedItem(item.Key);
            foreach (AutoTurret turrets in BaseNetworkable.serverEntities.Where(t => t is AutoTurret && !(t is NPCAutoTurret))) OnEntitySpawned(turrets);
            foreach (StorageContainer turrets in BaseNetworkable.serverEntities.Where(t => t is AttackHelicopterTurret or AttackHelicopterRockets)) OnEntitySpawned(turrets);
            foreach (BaseSubmarine submarine in BaseNetworkable.serverEntities.Where(t => t is BaseSubmarine)) OnEntitySpawned(submarine);
            foreach (SamSite site in BaseNetworkable.serverEntities.Where(t => t is SamSite)) OnEntitySpawned(site);
            foreach (GunTrap trap in BaseNetworkable.serverEntities.Where(t => t is GunTrap)) OnEntitySpawned(trap);
            foreach (FlameTurret flame in BaseNetworkable.serverEntities.Where(t => t is FlameTurret)) OnEntitySpawned(flame);
            CheckPlayers();
            String phase = Stadia?.Call<String>("GetCurrentPhase") ?? String.Empty;
            if (!String.IsNullOrEmpty(phase)) ApplyStage(phase);
            ServerMgr.Instance.InvokeRepeating(CheckUnlockedItem, 0f, 1f);
        }
        private void OnStadiaPhaseChanged(String phase) {
            ApplyStage(phase);
        }
        [ConsoleCommand("wipeblock.stage")]
        private void WipeBlockStageCommand(ConsoleSystem.Arg arg) {
            BasePlayer player = arg.Player();
            if (player != null && !player.IsAdmin) return;
            ApplyStage(arg.Args != null && arg.Args.Length > 0 ? arg.Args[0].ToString() : "raid");
        }
        [ConsoleCommand("wb.stage")]
        private void WipeBlockShortStageCommand(ConsoleSystem.Arg arg) {
            BasePlayer player = arg.Player();
            if (player != null && !player.IsAdmin) return;
            ApplyStage(arg.Args != null && arg.Args.Length > 0 ? arg.Args[0].ToString() : "raid");
        }
        private void Unload() {
            ServerMgr.Instance.CancelInvoke(CheckUnlockedItem);
            foreach (BasePlayer player in openUI) {
                if (player == null || !player.IsConnected) continue;
                CuiHelper.DestroyUi(player, Layer);
            }
        }
#endregion
#region [Rust-Api]
        private void OnEntitySpawned(StorageContainer containerAttackHelicopter) {
            if(containerAttackHelicopter is AttackHelicopterTurret or AttackHelicopterRockets) {
                if (containerAttackHelicopter.IsValid() && containerAttackHelicopter.inventory != null) containerAttackHelicopter.inventory.onItemAddedRemoved += (item, b) => ValidsItemAttackHelicopter(containerAttackHelicopter, item, b);
            }
        }
        private void OnEntitySpawned(BaseSubmarine submarine) {
            NextTick(() => {
                if (submarine.IsValid() && submarine.GetTorpedoContainer() != null) submarine.GetTorpedoContainer().inventory.onItemAddedRemoved += (item, b) => ValidsItemSubmarine(submarine, item, b);
            }
            );
        }
        private void OnEntitySpawned(AutoTurret turret) {
            if (turret is NPCAutoTurret || !turret.OwnerID.IsSteamId()) return;
            NextTick(() => {
                if (turret.IsValid() && turret.inventory != null) turret.inventory.onItemAddedRemoved += (item, b) => ValidsItemTurret(turret, item, b);
            }
            );
        }
        private void OnEntitySpawned(SamSite site) {
            NextTick(() => {
                if (site.IsValid() && site.inventory != null) site.inventory.onItemAddedRemoved += (item, b) => ValidsBlockedDeployable(site, item, b);
            }
            );
        }
        private void OnEntitySpawned(GunTrap trap) {
            NextTick(() => {
                if (trap.IsValid() && trap.inventory != null) trap.inventory.onItemAddedRemoved += (item, b) => ValidsBlockedDeployable(trap, item, b);
            }
            );
        }
        private void OnEntitySpawned(FlameTurret flame) {
            NextTick(() => {
                if (flame.IsValid() && flame.inventory != null) flame.inventory.onItemAddedRemoved += (item, b) => ValidsBlockedDeployable(flame, item, b);
            }
            );
        }
        private object CanEquipItem(PlayerInventory inventory, Item item) => CanWearItem(inventory, item);
        private object CanWearItem(PlayerInventory inventory, Item item) {
            BasePlayer player = inventory.GetComponent<BasePlayer>();
            if (!IsValid(player) || IsItemUnlocked(item.info.shortname)) return null;
            if (IsBlocked(item.info.shortname) > 0) {
                if (!fix.Contains(player.userID)) {
                    player.ShowToast(GameTip.Styles.Error, "Информация о заблокированных\nпредметах - /block", false, Array.Empty<String>());
                    fix.Add(player.userID);
                    timer.Once(0.1f, () => fix.Remove(player.userID));
                }
                return false;
            }
            return null;
        }
        private object OnWeaponReload(BaseProjectile projectile, BasePlayer player) => CanReloadProjectile(projectile, player.inventory, player);
        private object OnMagazineReload(BaseProjectile projectile, IAmmoContainer desiredAmount, BasePlayer player) => CanReloadProjectile(projectile, desiredAmount, player);
        private object CanReloadProjectile(BaseProjectile projectile, IAmmoContainer desiredAmount, BasePlayer player) {
            if (!IsValid(player) || projectile?.primaryMagazine == null || desiredAmount == null || player.inventory == null) return null;
            Item weapon = projectile.GetItem();
            if (IsBlockedNow(weapon?.info) || IsBlockedNow(GetReloadAmmo(projectile, desiredAmount))) return BlockAction(player);
            return null;
        }
        private object OnAmmoSwitch(BaseProjectile projectile, BasePlayer player, ItemDefinition itemDefinition) {
            if (!IsValid(player) || !IsBlockedNow(itemDefinition)) return null;
            return BlockAction(player);
        }
        private object CanAcceptItem(ItemContainer container, Item item, Int32 targetPos) {
            if (container == null || item == null || !IsBlockedTurretContainer(container)) return null;
            if (IsBlockedNow(item.info) || HasBlockedWeapon(container)) return ItemContainer.CanAcceptResult.CannotAccept;
            return null;
        }
        private object CanMoveItem(Item item, PlayerInventory inventory, ItemContainerId targetContainerId, Int32 targetSlot, Int32 amount, ItemMoveModifier moveModifier) {
            if (item == null || inventory == null || !targetContainerId.IsValid) return null;
            ItemContainer target = inventory.FindContainer(targetContainerId);
            if (target == null || !IsBlockedTurretContainer(target)) return null;
            if (IsBlockedNow(item.info) || HasBlockedWeapon(target)) {
                BasePlayer player = inventory.GetComponent<BasePlayer>();
                if (IsValid(player)) BlockAction(player);
                return false;
            }
            return null;
        }
        private object CanCraft(ItemCrafter itemCrafter, ItemBlueprint bp, Int32 amount, Boolean free) {
            BasePlayer player = itemCrafter?.owner;
            if (!IsValid(player) || !IsBlockedNow(bp?.targetItem)) return null;
            return BlockAction(player);
        }
        private object OnItemCraft(IndustrialCrafter crafter, ItemBlueprint bp) {
            return IsBlockedNow(bp?.targetItem) ? true : null;
        }
        private object CanDeployItem(BasePlayer player, Deployer deployer, NetworkableId entityId) {
            if (!IsValid(player) || !IsBlockedNow(deployer?.GetOwnerItemDefinition(player))) return null;
            return BlockAction(player);
        }
        private object OnRackedWeaponLoad(Item weapon, ItemDefinition itemDefinition, BasePlayer player, WeaponRack instance) {
            if (!IsValid(player)) return null;
            if (IsBlocked(itemDefinition.shortname) > 0) {
                if (!fix.Contains(player.userID)) {
                    player.ShowToast(GameTip.Styles.Error, "Информация о заблокированных\nпредметах - /block", false, Array.Empty<String>());
                    fix.Add(player.userID);
                    timer.Once(0.1f, () => fix.Remove(player.userID));
                }
                return false;
            }
            if (IsBlocked(weapon.info.shortname) > 0) {
                if (!fix.Contains(player.userID)) {
                    player.ShowToast(GameTip.Styles.Error, "Информация о заблокированных\nпредметах - /block", false, Array.Empty<String>());
                    fix.Add(player.userID);
                    timer.Once(0.1f, () => fix.Remove(player.userID));
                }
                return false;
            }
            return null;
        }
        private object CanMountEntity(BasePlayer player, MLRS entity) {
            if (!IsValid(player)) return null;
            if (IsBlocked("ammo.rocket.mlrs") > 0) {
                player.ChatMessage($"Установка MLRS будет доступна через <color=#eb7d6a>{Convert.ToInt32(Math.Floor(TimeSpan.FromSeconds(IsBlocked("ammo.rocket.mlrs")).TotalHours))}ч{TimeSpan.FromSeconds(IsBlocked("ammo.rocket.mlrs")).Minutes}м</color>");
                return false;
            }
            return null;
        }
        private void OnExplosiveDropped(BasePlayer player, BaseEntity entity) => OnExplosiveThrown(player, entity);
        private void OnExplosiveThrown(BasePlayer player, BaseEntity entity) {
            if (!IsValid(player)) return;
            if (entity == null || !IsThrownBlockedNow(entity.ShortPrefabName)) return;
            entity.Kill();
            player.ChatMessage("Вы <color=#70C3F8>не можете</color> кидать этот предмет!");
        }
#endregion
        [ConsoleCommand("cmdCloseWipeBlock")]
        private void cmdRemoveUi(ConsoleSystem.Arg arg) {
            BasePlayer player = arg.Player();
            if (player == null) return;
            CuiHelper.DestroyUi(player, Layer);
            openUI.Remove(player);
        }
#region [Ui]
        [ChatCommand("block")]
        private void MainUi(BasePlayer player) {
            if (openUI.Contains(player)) return;
            if (!openUI.Contains(player)) openUI.Add(player);
            CuiElementContainer container = new CuiElementContainer();
            Int32 i = 0;
            IEnumerable<KeyValuePair<String, Int32>> ItemsBlocked = config.blockItems.Where(x => !IsItemUnlocked(x.Key)).OrderBy(x => x.Value);
            IEnumerable<KeyValuePair<String, Int32>> ItemsUnBlocked = config.blockItems.Where(x => IsItemUnlocked(x.Key)).OrderBy(x => x.Value);
            container.Add(new CuiPanel {
                CursorEnabled = true, RectTransform = {
                    AnchorMin = "0 0", AnchorMax = "1 1"
                }
                , Image = {
                    Color = "0 0 0 0.8", Material = "assets/content/ui/uibackgroundblur-ingamemenu.mat"
                }
            }
            , "Overlay", Layer);
            container.Add(new CuiButton() {
                RectTransform = {
                    AnchorMin = "0 0", AnchorMax = "1 1"
                }
                , Button = {
                    Color = HexToRustFormat("#343434"), Sprite = "assets/content/ui/ui.background.transparent.radial.psd", Command = "cmdCloseWipeBlock"
                }
                , Text = {
                    Text = ""
                }
            }
            , Layer);
            container.Add(new CuiPanel {
                RectTransform = {
                    AnchorMin = "0.5 0.5", AnchorMax = "0.5 0.5", OffsetMin = "-368 40", OffsetMax = "368 142"
                }
                , Image = {
                    Color = HexToRustFormat("#D0C6BD33")
                }
            }
            , Layer, Layer + ".C");
            container.Add(new CuiPanel {
                RectTransform = {
                    AnchorMin = "0 0", AnchorMax = "1 1", OffsetMin = "10 30", OffsetMax = "-10 -10"
                }
                , Image = {
                    Color = HexToRustFormat("#D0C6BD33")
                }
            }
            , Layer + ".C");
            container.Add(new CuiElement {
                Name = Layer + ".C" + ".ScrollView", Parent = Layer + ".C", Components = {
                    new CuiImageComponent {
                        Color = "0 0 0 0"
                    }
                    , new CuiScrollViewComponent {
                        Horizontal = true, Vertical = false, MovementType = UnityEngine.UI.ScrollRect.MovementType.Elastic, Elasticity = 0.25f, Inertia = true, DecelerationRate = 0.3f, ContentTransform = new CuiRectTransform() {
                            AnchorMin = $"0 0", AnchorMax = $"0 1", OffsetMin = $"0 0", OffsetMax = $"{(ItemsBlocked.Count() < 12 ? 12 : ItemsBlocked.Count()) * 59.5} 0"
                        }
                        , ScrollSensitivity = 14.0f, HorizontalScrollbar = new CuiScrollbar {
                            Invert = true, AutoHide = false, HandleColor = "0.82 0.78 0.74 0.3", HighlightColor = "0.82 0.78 0.74 0.1", TrackColor = "0.82 0.78 0.74 0.05", Size = 6, PressedColor = "0.82 0.78 0.74 0.2"
                        }
                    }
                    , new CuiRectTransformComponent {
                        AnchorMin = "0 0", AnchorMax = "1 1", OffsetMin = "10 20", OffsetMax = "-12 -10"
                    }
                }
            }
            );
            foreach (KeyValuePair<String, Int32> item in ItemsBlocked) {
                container.Add(new CuiElement {
                    Name = Layer + ".C" + ".ScrollView" + $".Item{i}", Parent = Layer + ".C" + ".ScrollView", Components = {
                        new CuiImageComponent {
                            Color = HexToRustFormat("#D0C6BD33")
                        }
                        , new CuiRectTransformComponent {
                            AnchorMin = "0 1", AnchorMax = "0 1", OffsetMin = $"{5 + (i * 59.5)} -54.5", OffsetMax = $"{55 + (i * 59.5)} -5"
                        }
                    }
                }
                );
                container.Add(new CuiElement {
                    Parent = Layer + ".C" + ".ScrollView" + $".Item{i}", Components = {
                        new CuiImageComponent {
                            ItemId = FindItemID(item.Key), SkinId = 0, Color = "1 1 1 0.45"
                        }
                        , new CuiRectTransformComponent {
                            AnchorMin = "0 0", AnchorMax = "1 1", OffsetMin = "3 3", OffsetMax = "-3 -3"
                        }
                    }
                }
                );
                String Time = stageBlockedItems.Contains(ShortnameValidation(item.Key)) ? "ФАЗА" : FormatTime(TimeSpan.FromSeconds(IsBlocked(item.Key)));
                container.Add(new CuiElement {
                    Parent = Layer + ".C" + ".ScrollView" + $".Item{i}", Components = {
                        new CuiTextComponent {
                            Text = $"{(Time.Length > 10 ? Time.Substring(0, 8) : Time)}", Color = HexToRustFormat("#D0C6BD4D"), FontSize = 10, Font = "robotocondensed-regular.ttf", Align = TextAnchor.LowerRight
                        }
                        , new CuiRectTransformComponent {
                            AnchorMin = "0 0", AnchorMax = "1 1", OffsetMin = "0 0", OffsetMax = "-1 1"
                        }
                        ,
                    }
                }
                );
                container.Add(new CuiElement {
                    Parent = Layer + ".C" + ".ScrollView" + $".Item{i}", Components = {
                        new CuiImageComponent {
                            Sprite = "assets/icons/lock.png", Color = HexToRustFormat("#D0C6BD4D")
                        }
                        , new CuiRectTransformComponent {
                            AnchorMin = "0 0", AnchorMax = "1 1", OffsetMin = "7 7", OffsetMax = "-7 -7"
                        }
                    }
                }
                );
                i++;
            }
            container.Add(new CuiPanel {
                RectTransform = {
                    AnchorMin = "0 1", AnchorMax = "1 1", OffsetMin = "0 7", OffsetMax = "0 47"
                }
                , Image = {
                    Color = "0 0 0 0"
                }
            }
            , Layer + ".C", Layer + ".C" + ".LU");
            container.Add(new CuiLabel() {
                RectTransform = {
                    AnchorMin = "0 0", AnchorMax = "1 1", OffsetMin = "0 0", OffsetMax = "0 0"
                }
                , Text = {
                    Text = "Недоступные предметы", Font = "robotocondensed-bold.ttf", Color = HexToRustFormat("#D0C6BD"), FontSize = 24, Align = TextAnchor.UpperLeft
                }
            }
            , Layer + ".C" + ".LU");
            container.Add(new CuiLabel() {
                RectTransform = {
                    AnchorMin = "0 0", AnchorMax = "1 1", OffsetMin = "0 0", OffsetMax = "0 0"
                }
                , Text = {
                    Text = "Оружие и боеприпасы недоступные для использования", Font = "robotocondensed-regular.ttf", Color = HexToRustFormat("#D0C6BD4D"), FontSize = 14, Align = TextAnchor.LowerLeft
                }
            }
            , Layer + ".C" + ".LU");
            container.Add(new CuiPanel {
                RectTransform = {
                    AnchorMin = "0.5 0.5", AnchorMax = "0.5 0.5", OffsetMin = "-368 -180", OffsetMax = "368 -14"
                }
                , Image = {
                    Color = HexToRustFormat("#D0C6BD33")
                }
            }
            , Layer, Layer + ".CL");
            container.Add(new CuiPanel {
                RectTransform = {
                    AnchorMin = "0 0", AnchorMax = "1 1", OffsetMin = "10 40", OffsetMax = "-10 -10"
                }
                , Image = {
                    Color = HexToRustFormat("#D0C6BD33")
                }
            }
            , Layer + ".CL");
            Int32 UnBlocked = ItemsUnBlocked.Count() / 2;
            if (UnBlocked % 2 != 0) UnBlocked++;
            container.Add(new CuiElement {
                Name = Layer + ".CL" + ".ScrollView", Parent = Layer + ".CL", Components = {
                    new CuiImageComponent {
                        Color = "0 0 0 0"
                    }
                    , new CuiScrollViewComponent {
                        Horizontal = true, Vertical = false, MovementType = UnityEngine.UI.ScrollRect.MovementType.Elastic, Elasticity = 0.25f, Inertia = true, DecelerationRate = 0.3f, ContentTransform = new CuiRectTransform() {
                            AnchorMin = $"0 0", AnchorMax = $"0 1", OffsetMin = $"0 0", OffsetMax = $"{(UnBlocked < 12 ? 12 : UnBlocked) * 59} 0"
                        }
                        , ScrollSensitivity = 14.0f, HorizontalScrollbar = new CuiScrollbar {
                            Invert = true, AutoHide = false, HandleColor = "0.82 0.78 0.74 0.3", HighlightColor = "0.82 0.78 0.74 0.1", TrackColor = "0.82 0.78 0.74 0.05", Size = 6, PressedColor = "0.82 0.78 0.74 0.2"
                        }
                    }
                    , new CuiRectTransformComponent {
                        AnchorMin = "0 0", AnchorMax = "1 1", OffsetMin = "10 20", OffsetMax = "-12 -10"
                    }
                }
            }
            );
            i = 0;
            Int32 x = 0, y = 0;
            foreach (KeyValuePair<String, Int32> item in ItemsUnBlocked) {
                if (i % 2 == 0) {
                    container.Add(new CuiElement {
                        Name = Layer + ".CL" + ".ScrollView" + $".Item{i}", Parent = Layer + ".CL" + ".ScrollView", Components = {
                            new CuiImageComponent {
                                Color = HexToRustFormat("#D0C6BD33")
                            }
                            , new CuiRectTransformComponent {
                                AnchorMin = "0 1", AnchorMax = "0 1", OffsetMin = $"{5 + (y * 59)} -54.5", OffsetMax = $"{55 + (y * 59)} -5"
                            }
                        }
                    }
                    );
                    y++;
                }
                else {
                    container.Add(new CuiElement {
                        Name = Layer + ".CL" + ".ScrollView" + $".Item{i}", Parent = Layer + ".CL" + ".ScrollView", Components = {
                            new CuiImageComponent {
                                Color = HexToRustFormat("#D0C6BD33")
                            }
                            , new CuiRectTransformComponent {
                                AnchorMin = "0 1", AnchorMax = "0 1", OffsetMin = $"{5 + (x * 59)} -111", OffsetMax = $"{55 + (x * 59)} -61.5"
                            }
                        }
                    }
                    );
                    x++;
                }
                container.Add(new CuiElement {
                    Parent = Layer + ".CL" + ".ScrollView" + $".Item{i}", Components = {
                        new CuiImageComponent {
                            ItemId = FindItemID(item.Key), SkinId = 0, Color = "1 1 1 0.85"
                        }
                        , new CuiRectTransformComponent {
                            AnchorMin = "0 0", AnchorMax = "1 1", OffsetMin = "3 3", OffsetMax = "-3 -3"
                        }
                    }
                }
                );
                i++;
            }
            container.Add(new CuiPanel {
                RectTransform = {
                    AnchorMin = "0 1", AnchorMax = "1 1", OffsetMin = "0 7", OffsetMax = "0 47"
                }
                , Image = {
                    Color = "0 0 0 0"
                }
            }
            , Layer + ".CL", Layer + ".CL" + ".LB");
            container.Add(new CuiLabel() {
                RectTransform = {
                    AnchorMin = "0 0", AnchorMax = "1 1", OffsetMin = "0 0", OffsetMax = "0 0"
                }
                , Text = {
                    Text = "Доступные предметы", Font = "robotocondensed-bold.ttf", Color = HexToRustFormat("#D0C6BD"), FontSize = 24, Align = TextAnchor.UpperLeft
                }
            }
            , Layer + ".CL" + ".LB");
            container.Add(new CuiLabel() {
                RectTransform = {
                    AnchorMin = "0 0", AnchorMax = "1 1", OffsetMin = "0 0", OffsetMax = "0 0"
                }
                , Text = {
                    Text = "Оружие и боеприпасы доступные для использования", Font = "robotocondensed-regular.ttf", Color = HexToRustFormat("#D0C6BD4D"), FontSize = 14, Align = TextAnchor.LowerLeft
                }
            }
            , Layer + ".CL" + ".LB");
            CuiHelper.DestroyUi(player, Layer);
            CuiHelper.AddUi(player, container);
        }
#endregion
#region [Functional]
        private String HexToRustFormat(String hex) {
            if (String.IsNullOrEmpty(hex)) hex = "#FFFFFFFF";
            String str = hex.Trim('#');
            if (str.Length == 6) str += "FF";
            if (str.Length != 8) {
                throw new Exception(hex);
                throw new InvalidOperationException("Cannot convert a wrong format.");
            }
            Byte r = Byte.Parse(str.Substring(0, 2), NumberStyles.HexNumber);
            Byte g = Byte.Parse(str.Substring(2, 2), NumberStyles.HexNumber);
            Byte b = Byte.Parse(str.Substring(4, 2), NumberStyles.HexNumber);
            Byte a = Byte.Parse(str.Substring(6, 2), NumberStyles.HexNumber);
            UnityEngine.Color color = new Color32(r, g, b, a);
            return String.Format("{0:F2} {1:F2} {2:F2} {3:F2}", color.r, color.g, color.b, color.a);
        }
        private String FormatTime(TimeSpan time) {
            String result = String.Empty;
            if (time.Days != 0) {
                if (!String.IsNullOrEmpty(result)) result += " ";
                result += $"{Format(time.Days, "д.", "д.", "д.")}";
            }
            if (time.Hours != 0) {
                if (!String.IsNullOrEmpty(result)) result += " ";
                result += $"{Format(time.Hours, "ч.", "ч.", "ч.")}";
            }
            if (time.Minutes != 0) {
                if (!String.IsNullOrEmpty(result)) result += " ";
                result += $"{Format(time.Minutes, "м.", "м.", "м.")}";
            }
            if (time.Days == 0) {
                if (time.Seconds != 0) {
                    if (!String.IsNullOrEmpty(result)) result += " ";
                    result += $"{Format(time.Seconds, "с.", "с.", "с.")}";
                }
            }
            if (String.IsNullOrEmpty(result)) result = "0 секунд";
            return result;
        }
        private String Format(Int32 units, String form1, String form2, String form3) {
            Int32 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 Double IsBlocked(String shortName) {
            shortName = ShortnameValidation(shortName);
            if (IsPvpStage() && shortName == "ammo.rocket.hv") return 0;
            if (IsRaidStage() && IsPvpBlockedItem(shortName)) return 0;
            if (stageBlockedItems.Contains(shortName)) return 86400;
            if (!config.blockItems.ContainsKey(shortName)) return 0;
            if (IsItemUnlocked(shortName)) return 0;
            if (config.blockItems[shortName] == PermanentBlockTime) return PermanentBlockTime;
            Double blockTime = UnBlockTime(config.blockItems[shortName]) - CurrentTime();
            return blockTime > 0 ? blockTime : 0;
        }
        private Boolean BlockTimeGui(String shortName) {
            shortName = ShortnameValidation(shortName);
            return IsBlocked(shortName) > 0;
        }
        private Boolean IsValid(BasePlayer player) {
            return player != null && player.userID.IsSteamId() && !permission.UserHasPermission(player.UserIDString, IgnorePermission);
        }
        private Boolean IsBlockedNow(ItemDefinition itemDefinition) {
            return itemDefinition != null && IsBlocked(itemDefinition.shortname) > 0;
        }
        private Boolean IsItemUnlocked(String shortName) {
            shortName = ShortnameValidation(shortName);
            return unlockedItem.Contains(shortName) && !stageBlockedItems.Contains(shortName);
        }
        private void AddUnlockedItem(String shortName) {
            shortName = ShortnameValidation(shortName);
            if (!unlockedItem.Contains(shortName)) unlockedItem.Add(shortName);
        }
        private Boolean IsRaidStage() => currentStage == "phase_raid" || currentStage == "raid";
        private Boolean IsPvpStage() => currentStage == "phase_pvp" || currentStage == "pvp";
        private Boolean IsPvpBlockedItem(String shortName) {
            if (String.IsNullOrWhiteSpace(shortName)) return false;
            shortName = ShortnameValidation(shortName);
            return PvpBlockedItems.Any(item => ShortnameValidation(item) == shortName);
        }
        private Boolean IsThrownBlockedNow(String prefabName) {
            if (String.IsNullOrWhiteSpace(prefabName)) return false;
            prefabName = prefabName.ToLowerInvariant();
            if (IsRaidStage()) return false;
            if (stageBlockedItems.Count > 0 && PvpBlockedThrownPrefabs.Any(prefab => prefab == prefabName)) return true;
            return config.blockItemsThrown != null && config.blockItemsThrown.Contains(prefabName);
        }
        private object BlockAction(BasePlayer player) {
            if (player != null && !fix.Contains(player.userID)) {
                player.ShowToast(GameTip.Styles.Error, "Информация о заблокированных\nпредметах - /block", false, Array.Empty<String>());
                fix.Add(player.userID);
                timer.Once(0.1f, () => fix.Remove(player.userID));
            }
            return false;
        }
        private ItemDefinition GetReloadAmmo(BaseProjectile projectile, IAmmoContainer ammoContainer) {
            ItemDefinition currentAmmo = projectile.primaryMagazine.ammoType;
            if (currentAmmo != null) {
                List<Item> items = Pool.Get<List<Item>>();
                ammoContainer.FindItemsByItemID(items, currentAmmo.itemid);
                Boolean hasCurrentAmmo = items.Count > 0;
                Pool.FreeUnmanaged(ref items);
                if (hasCurrentAmmo) return currentAmmo;
            }
            if (!projectile.primaryMagazine.allowAmmoSwitching) return null;
            Item ammo = ammoContainer.FindAmmo(projectile.primaryMagazine.definition.ammoTypes);
            return ammo?.info;
        }
        private Boolean IsBlockedTurretContainer(ItemContainer container) {
            BaseEntity owner = container.entityOwner;
            if (owner == null) return false;
            if (owner is AutoTurret or AttackHelicopterTurret or AttackHelicopterRockets or SamSite or GunTrap or FlameTurret) return true;
            if (owner is StorageContainer storageContainer && storageContainer.ShortPrefabName != null && storageContainer.ShortPrefabName.Contains("torpedo")) return true;
            for (BaseEntity e = owner; e != null; e = e.GetParentEntity()) {
                if (e is MLRS) return true;
            }
            return false;
        }
        private Boolean HasBlockedWeapon(ItemContainer container) {
            for (Int32 i = 0; i < container.itemList.Count; i++) {
                Item item = container.itemList[i];
                if (IsBlockedNow(item?.info)) return true;
            }
            return false;
        }
        private Int32 FindItemID(String shortName) {
            Int32 val;
            if (_itemIds.TryGetValue(shortName, out val)) return val;
            ItemDefinition definition = ItemManager.FindItemDefinition(shortName);
            if (definition == null) return 0;
            val = definition.itemid;
            _itemIds[shortName] = val;
            return val;
        }
        private void CheckBlockedItem(BasePlayer player, Item item) {
            if (!IsValid(player) || IsItemUnlocked(item.info.shortname)) return;
            if (IsBlocked(item.info.shortname) > 0) {
                if (item.MoveToContainer(player.inventory.containerMain)) player.Command("note.inv", item.info.itemid, item.amount, !String.IsNullOrEmpty(item.name) ? item.name : String.Empty, (Int32) BaseEntity.GiveItemReason.PickedUp);
                else item.Drop(player.inventory.containerMain.dropPosition, player.inventory.containerMain.dropVelocity);
            }
        }
        private void CheckPlayers() {
            foreach (BasePlayer player in BasePlayer.activePlayerList) {
                player.inventory.containerBelt.itemList.ToList().ForEach(item => CheckBlockedItem(player, item));
                player.inventory.containerWear.itemList.ToList().ForEach(item => CheckBlockedItem(player, item));
            }
        }
        private String ShortnameValidation(String Shortname) {
            if (Shortname.Equals("wall.external.high.ice")) Shortname = Shortname.Replace("ice", "stone");
            else {
                Int32 IndexIce = Shortname.IndexOf(".ice", StringComparison.Ordinal);
                if (IndexIce > 0) Shortname = Shortname.Substring(0, IndexIce);
                Int32 IndexHockey = Shortname.IndexOf(".hockey", StringComparison.Ordinal);
                if (IndexHockey > 0) Shortname = Shortname.Substring(0, IndexHockey);
                Int32 IndexDiving = Shortname.IndexOf(".diver", StringComparison.Ordinal);
                if (IndexDiving > 0) Shortname = Shortname.Substring(0, IndexDiving);
                Int32 IndexDragon = Shortname.IndexOf(".dragon", StringComparison.Ordinal);
                if (IndexDragon > 0) Shortname = Shortname.Substring(0, IndexDragon);
            }
            return Shortname;
        }
        private void ValidsBlockedDeployable(BaseEntity entity, Item item, Boolean AddedOrRemove) {
            if (!AddedOrRemove || item.parent == null) return;
            if (IsBlocked(item.info.shortname) <= 0) return;
            BasePlayer player = BasePlayer.FindByID(entity.OwnerID);
            if (player != null && item.MoveToContainer(player.inventory.containerMain)) {
                if (!fix.Contains(player.userID)) {
                    player.ShowToast(GameTip.Styles.Error, "Информация о заблокированных\nпредметах - /block", false, Array.Empty<String>());
                    fix.Add(player.userID);
                    timer.Once(0.1f, () => fix.Remove(player.userID));
                }
                return;
            }
            item.Drop(entity.transform.position + new Vector3(0f, 1f, 0f), entity.GetDropVelocity());
        }
        private void ValidsItemTurret(AutoTurret Turret, Item item, Boolean AddedOrRemove) {
            if (!AddedOrRemove || item.parent == null || item.parent.uid.Value == 384258468) return;
            if (IsBlocked(item.info.shortname) == 0) {
                if (Turret.inventory.itemList.Count == 0 || Turret.inventory.itemList[0] == null) return;
                if (IsBlocked(Turret.inventory.itemList[0].info.shortname) == 0) return;
            }
            BasePlayer player = BasePlayer.FindByID(Turret.OwnerID);
            if (player != null && item.MoveToContainer(player.inventory.containerMain)) {
                if (!fix.Contains(player.userID)) {
                    player.ShowToast(GameTip.Styles.Error, "Информация о заблокированных\nпредметах - /block", false, Array.Empty<String>());
                    fix.Add(player.userID);
                    timer.Once(0.1f, () => fix.Remove(player.userID));
                }
                return;
            }
            item.Drop(Turret.transform.position + new Vector3(0f, 1f, 0f), Turret.GetDropVelocity());
        }
        private void ValidsItemAttackHelicopter(StorageContainer container, Item item, Boolean AddedOrRemove) {
            if (!AddedOrRemove || item.parent == null || item.parent.uid.Value == 384258468) return;
            if (IsBlocked(item.info.shortname) == 0) {
                if (container.inventory.itemList.Count == 0 || container.inventory.itemList[0] == null) return;
                if (IsBlocked(container.inventory.itemList[0].info.shortname) == 0) return;
            }
            BasePlayer player = BasePlayer.FindByID(container.OwnerID);
            if (player != null && item.MoveToContainer(player.inventory.containerMain)) {
                if (!fix.Contains(player.userID)) {
                    player.ShowToast(GameTip.Styles.Error, "Информация о заблокированных\nпредметах - /block", false, Array.Empty<String>());
                    fix.Add(player.userID);
                    timer.Once(0.1f, () => fix.Remove(player.userID));
                }
                return;
            }
            item.Drop(container.transform.position + new Vector3(0f, 1f, 0f), GetDropVelocity(container));
        }
        private void ValidsItemSubmarine(BaseSubmarine submarine, Item item, Boolean AddedOrRemove) {
            if (!AddedOrRemove || item.parent == null || item.parent.uid.Value == 878743) return;
            if (IsBlocked(item.info.shortname) == 0) return;
            UInt64 getPlayerID = submarine.GetDriver() != null ? submarine.GetDriver().userID : 0;
            BasePlayer player = BasePlayer.FindByID(getPlayerID);
            if (player != null && item.MoveToContainer(player.inventory.containerMain)) {
                if (!fix.Contains(player.userID)) {
                    player.ShowToast(GameTip.Styles.Error, "Информация о заблокированных\nпредметах - /block", false, Array.Empty<String>());
                    fix.Add(player.userID);
                    timer.Once(0.1f, () => fix.Remove(player.userID));
                }
                return;
            }
            item.Drop(submarine.transform.position + new Vector3(0f, 1f, 0f), submarine.GetDropVelocity());
        }
        private Vector3 GetDropVelocity(StorageContainer container) {
            return container switch {
                AttackHelicopterTurret turret => turret.GetDropVelocity(), AttackHelicopterRockets rockets => rockets.GetDropVelocity(), _ => new Vector3(0f, 0f, 0f)
            }
            ;
        }
        private void CheckUnlockedItem() {
            List<String> list = Pool.Get<List<String>>();
            foreach (KeyValuePair<String, Int32> item in config.blockItems.Where(p => p.Value != PermanentBlockTime && !unlockedItem.Contains(ShortnameValidation(p.Key)) && IsBlocked(p.Key) <= 0)) {
                list.Add(item.Key);
                AddUnlockedItem(item.Key);
            }
            BroadcastUnlockedItems(list);
            if (!config.blockItems.Any(p => p.Value != PermanentBlockTime && !unlockedItem.Contains(ShortnameValidation(p.Key)))) ServerMgr.Instance.CancelInvoke(CheckUnlockedItem);
            Pool.FreeUnmanaged(ref list);
        }
        private void ApplyStage(String phase) {
            phase = String.IsNullOrWhiteSpace(phase) ? String.Empty : phase.ToLowerInvariant();
            currentStage = phase;
            stageBlockedItems.Clear();
            if (phase == "phase_raid" || phase == "raid") {
                UnlockStageItems();
                return;
            }
            if (phase == "phase_pvp" || phase == "pvp") {
                stageBlockedItems.Clear();
                BroadcastUnlockedItems(new List<String> {
                    "explosive.timed", "rocket.launcher", "ammo.rocket.basic", "ammo.rocket.hv", "ammo.rocket.mlrs", "rocket.launcher.dragon", "multiplegrenadelauncher", "ammo.grenadelauncher.he", "rocket.launcher.rpg7", "ammo.grenadelauncher.smoke", "ammo.grenadelauncher.buckshot"
                }
                );
                CheckPlayers();
                RefreshOpenUI();
                return;
            }
            AddStageBlockedItems(PvpBlockedItems);
            foreach (KeyValuePair<String, Int32> item in config.blockItems.Where(p => p.Value != PermanentBlockTime)) stageBlockedItems.Add(ShortnameValidation(item.Key));
            CheckPlayers();
            RefreshOpenUI();
        }
        private void AddStageBlockedItems(IEnumerable<String> shortNames) {
            foreach (String shortName in shortNames) stageBlockedItems.Add(ShortnameValidation(shortName));
        }
        private void UnlockStageItems() {
            List<String> list = Pool.Get<List<String>>();
            stageBlockedItems.Clear();
            foreach (KeyValuePair<String, Int32> item in config.blockItems.Where(p => p.Value != PermanentBlockTime && !unlockedItem.Contains(ShortnameValidation(p.Key)))) {
                list.Add(item.Key);
                AddUnlockedItem(item.Key);
            }
            BroadcastUnlockedItems(list);
            CheckPlayers();
            ServerMgr.Instance.CancelInvoke(CheckUnlockedItem);
            RefreshOpenUI();
            Pool.FreeUnmanaged(ref list);
        }
        private void RefreshOpenUI() {
            List<BasePlayer> players = Pool.Get<List<BasePlayer>>();
            players.AddRange(openUI);
            foreach (BasePlayer player in players) {
                if (player == null || !player.IsConnected) {
                    openUI.Remove(player);
                    continue;
                }
                CuiHelper.DestroyUi(player, Layer);
                openUI.Remove(player);
                MainUi(player);
            }
            Pool.FreeUnmana
// ... [Code preview truncated due to length. Full source in attached file] ...

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