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

FREE BetterTC : 1.4.81 1.4.81

Нет прав для скачивания
C#:
using HarmonyLib;
using System;
using System.Net;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using Oxide.Core;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using ProtoBuf;
using UnityEngine;
using Newtonsoft.Json;
namespace Oxide.Plugins {
    [Info("BetterTC", "ninco90", "1.4.81")]
    internal class BetterTC : RustPlugin {
#region Fields
        [PluginReference]
        private Plugin ImageLibrary, NoEscape, RaidBlock, TiersMode, Notify, UINotify, TCLevels;
        string[] incompatiblePlugins = {
            "BuildingSkin", "BuildingSkins", "XBuildingSkinMenu"
        }
        ;
        private const string InstanceId = "com.ninco90.BetterTC";
        //private static Harmony _harmony;
        private const string fxnoresources = "assets/bundled/prefabs/fx/ore_break.prefab";
        private const string fxfinish = "assets/prefabs/deployable/research table/effects/research-success.prefab";
        private const string fxspray = "assets/prefabs/deployable/repair bench/effects/skinchange_spraypaint.prefab";
        private const string fxreskin = "assets/prefabs/tools/spraycan/reskineffect.prefab";
        private const string fxcloth = "assets/prefabs/wallpaper/effects/place.prefab";
        //old assets/bundled/prefabs/fx/impacts/blunt/cloth/cloth1.prefab
        private const string fxrepair = "assets/prefabs/deployable/modular car lift/effects/modular-car-lift-repair.prefab";
        private const string fxerror = "assets/prefabs/weapons/toolgun/effects/repairerror.prefab";
        private const string permadmin = "bettertc.admin";
        private const string permupgrade = "bettertc.upgrade";
        private const string permupgradenocost = "bettertc.upgrade.nocost";
        private const string permrepair = "bettertc.repair";
        private const string permrepairnocost = "bettertc.repair.nocost";
        private const string permreskin = "bettertc.reskin";
        private const string permreskinnocost = "bettertc.reskin.nocost";
        private const string permwallpaper = "bettertc.wallpaper";
        private const string permwallpapernocost = "bettertc.wallpaper.nocost";
        private const string permlist = "bettertc.authlist";
        private const string permdelauth = "bettertc.deleteauth";
        private const string permtcskin = "bettertc.tcskinchange";
        private const string permtcskindeployed = "bettertc.tcskindeployed";
        private const string permupskin = "bettertc.upskin";
        private const string upgrade_0 = "upgrade.base";
        private const string upgrade_1 = "upgrade.windows";
        private const string upgrade_2 = "upgrade.item";
        private const string upgrade_3 = "upgrade.subitem";
        private const string buttons_0 = "buttons.cup";
        private const string color_0 = "color.base";
        private const string color_1 = "color.windows";
        private const string color_2 = "color.item";
        private const string color_3 = "color.subitem";
        private const string tcskin_0 = "color.base";
        private const string tcskin_1 = "color.windows";
        private const string tcskin_2 = "color.item";
        private const string tcskin_3 = "color.subitem";
        private const string authlist_0 = "authlist.base";
        private const string authlist_1 = "authlist.windows";
        private const string authlist_2 = "authlist.item";
        private const string authlist_3 = "authlist.subitem";
        private const string apiUrl = "https://app.rustspain.com/facepunch/bettertc_update.json";
        private Dictionary<BuildingPrivlidge, TCConfig> BuildingCupboard = new Dictionary<BuildingPrivlidge, TCConfig>();
        private int maxGradeTier;
        private Dictionary<ulong, TCSkin> playerSelectedSkins = new Dictionary<ulong, TCSkin>();
        string[] skins = {
            "cupboard.tool", "cupboard.tool.retro", "cupboard.tool.shockbyte"
        }
        ;
        int[] skins2 = {
            -97956382, 1488606552, 1174957864
        }
        ;
        bool incompatibleFound = false;
        public enum TCSkin {
            Default, Retro, Shockbyte
        }
#endregion
#region Hooks
        private void OnServerInitialized() {
            if (!permission.PermissionExists(permadmin, this)) permission.RegisterPermission(permadmin, this);
            if (!permission.PermissionExists(permupgrade, this)) permission.RegisterPermission(permupgrade, this);
            if (!permission.PermissionExists(permupgradenocost, this)) permission.RegisterPermission(permupgradenocost, this);
            if (!permission.PermissionExists(permrepair, this)) permission.RegisterPermission(permrepair, this);
            if (!permission.PermissionExists(permrepairnocost, this)) permission.RegisterPermission(permrepairnocost, this);
            if (!permission.PermissionExists(permreskin, this)) permission.RegisterPermission(permreskin, this);
            if (!permission.PermissionExists(permreskinnocost, this)) permission.RegisterPermission(permreskinnocost, this);
            if (!permission.PermissionExists(permwallpaper, this)) permission.RegisterPermission(permwallpaper, this);
            if (!permission.PermissionExists(permwallpapernocost, this)) permission.RegisterPermission(permwallpapernocost, this);
            if (!permission.PermissionExists(permlist, this)) permission.RegisterPermission(permlist, this);
            if (!permission.PermissionExists(permdelauth, this)) permission.RegisterPermission(permdelauth, this);
            if (!permission.PermissionExists(permtcskin, this)) permission.RegisterPermission(permtcskin, this);
            if (!permission.PermissionExists(permtcskindeployed, this)) permission.RegisterPermission(permtcskindeployed, this);
            if (!permission.PermissionExists(permupskin, this)) permission.RegisterPermission(permupskin, this);
            foreach (var check in config.FrequencyUpgrade) {
                if (!permission.PermissionExists(check.Key, this)) permission.RegisterPermission(check.Key, this);
            }
            Dictionary<string, string> imageListCraft = new Dictionary<string, string>();
            foreach (var recipe in config.itemsList) {
                if (!permission.PermissionExists(recipe.permission, this)) permission.RegisterPermission(recipe.permission, this);
                if (recipe.img != "" && !imageListCraft.ContainsKey(recipe.img)) imageListCraft.Add(recipe.img, recipe.img);
            }
            for (int i = 0; i <= 16; i++) {
                imageListCraft.Add("color_" + i, "https://img.rustspain.com/bettertc/colours/" + i + ".png");
            }
            imageListCraft.Add("lock5", "https://img.rustspain.com/bettertc/lock5.png");
            imageListCraft.Add("upgrade2", "https://img.rustspain.com/bettertc/upgrade2.png");
            imageListCraft.Add("https://img.rustspain.com/bettertc/wallpaper/no.png", "https://img.rustspain.com/bettertc/wallpaper/no.png");
            ImageLibrary?.Call("ImportImageList", Title, imageListCraft, 0UL, true, null);
            if (config.forcebothsides) {
                //_harmony = new Harmony(InstanceId);
                //_harmony.PatchAll();
                HarmonyPatches();
                Puts($"Harmony Patched (Force both sides wallpapers: true)");
            }
            foreach (var tc in BaseNetworkable.serverEntities.OfType<BuildingPrivlidge>()) {
                if (tc == null) {
                    continue;
                }
                UpdateBlockedItems(tc);
            }
            if (config.autoCheck) GetNewItems(null);
            incompatibleFound = incompatiblePlugins.Any(plugin => plugins.Exists(plugin));
        }
        private void Unload() {
            foreach (var player in BasePlayer.activePlayerList) {
                CuiHelper.DestroyUi(player, buttons_0);
                CuiHelper.DestroyUi(player, upgrade_0);
                CuiHelper.DestroyUi(player, color_0);
                CuiHelper.DestroyUi(player, tcskin_0);
                CuiHelper.DestroyUi(player, authlist_0);
            }
            foreach (var cup in BuildingCupboard) {
                if (cup.Value.workupgrade != null) ServerMgr.Instance.StopCoroutine(cup.Value.workupgrade);
                if (cup.Value.workrepair != null) ServerMgr.Instance.StopCoroutine(cup.Value.workrepair);
                if (cup.Value.workreskin != null) ServerMgr.Instance.StopCoroutine(cup.Value.workreskin);
                if (cup.Value.workwallpaper != null) ServerMgr.Instance.StopCoroutine(cup.Value.workwallpaper);
            }
            //if (_harmony != null) _harmony.UnpatchAll(InstanceId);
        }
        private void OnEntityBuilt(Planner plan, GameObject go) {
            if(plan == null || go == null || !(go.ToBaseEntity() is BuildingPrivlidge)) return;
            BasePlayer player = plan.GetOwnerPlayer();
            if(!HasPermission(player.UserIDString, permtcskindeployed)) return;
            BuildingPrivlidge tc = go.ToBaseEntity() as BuildingPrivlidge;
            if(tc.ShortPrefabName != "cupboard.tool.deployed") return;
            TCSkin selectedSkin = TCSkin.Retro;
            if (playerSelectedSkins.TryGetValue(player.userID, out TCSkin storedSkin)) {
                selectedSkin = storedSkin;
            }
            TCSkinReplace(tc, player, selectedSkin);
        }
        private void OnLootEntity(BasePlayer player, BuildingPrivlidge cup) {
            if (player == null || cup == null) return;
            if (!BuildingCupboard.ContainsKey(cup)) {
                BuildingCupboard.Add(cup, new TCConfig() {
                    grade = BuildingGrade.Enum.Wood, skinid = 0, color = false, colour = 0, work = false, repair = false, reskin = false, effect = true, downgrade = false, wallpaperid = 1, wpbothsides = false
                }
                );
            }
            ShowButtonTC(player, cup);
        }
        private void OnLootEntityEnd(BasePlayer player, BaseCombatEntity entity) {
            if (player == null) return;
            CuiHelper.DestroyUi(player, buttons_0);
            CuiHelper.DestroyUi(player, upgrade_0);
            CuiHelper.DestroyUi(player, authlist_0);
        }
        private void OnRaidBlockStarted(BasePlayer player) => OnRaidBlock(player);
        private void OnRaidBlock(BasePlayer player, Vector3 pos) => OnRaidBlock(player);
        private void OnRaidBlock(BasePlayer player) {
            if(player == null || player.userID == null) return;
            foreach (var cup in BuildingCupboard) {
                if (cup.Value.player == player.userID) {
                    if (cup.Value.workupgrade != null) {
                        ServerMgr.Instance.StopCoroutine(cup.Value.workupgrade);
                    }
                    if (cup.Value.workrepair != null) {
                        ServerMgr.Instance.StopCoroutine(cup.Value.workrepair);
                    }
                    if (cup.Value.workreskin != null) {
                        ServerMgr.Instance.StopCoroutine(cup.Value.workreskin);
                    }
                    if (cup.Value.workwallpaper != null) {
                        ServerMgr.Instance.StopCoroutine(cup.Value.workwallpaper);
                    }
                    cup.Value.workupgrade = null;
                    cup.Value.workrepair = null;
                    cup.Value.workreskin = null;
                    cup.Value.workwallpaper = null;
                    break;
                }
            }
        }
#endregion
#region Function
        private IEnumerator RepairProgress(BasePlayer player, BuildingPrivlidge cup) {
            var building = cup.GetBuilding();
            yield return CoroutineEx.waitForSeconds(0.15f);
            var cd = Frequency(player.UserIDString, config.FrequencyRepair);
            var cost = ResourcesRepair(player.UserIDString);
            bool show = true;
            for (int index = 0; index < building.buildingBlocks.Count; index++) {
                var entity = building.buildingBlocks[index];
                if (!BuildingCupboard[cup].repair) {
                    show = false;
                    break;
                }
                if (!RepairBlock(player, entity, cup, cost, false)) continue;
                yield return CoroutineEx.waitForSeconds(cd);
            }
            if (config.Deployables) {
                for (int index = 0; index < building.decayEntities.Count; index++) {
                    var entity = building.decayEntities[index];
                    if (!BuildingCupboard[cup].repair) {
                        show = false;
                        break;
                    }
                    if (!RepairBlock(player, entity, cup, cost, true)) continue;
                    yield return CoroutineEx.waitForSeconds(cd);
                }
            }
            BuildingCupboard[cup].repair = false;
            BuildingCupboard[cup].workrepair = null;
            if(show) CreateGameTip(cup, Languaje("RepairFinish", player.UserIDString), player, fxfinish, 10);
            yield return 0;
        }
        private IEnumerator UpdateProgress(BasePlayer player, BuildingPrivlidge cup) {
            var set = cup.GetBuilding().buildingBlocks;
            yield return CoroutineEx.waitForSeconds(0.15f);
            var cd = Frequency(player.UserIDString, config.FrequencyUpgrade);
            bool show = true;
            List<ulong> playerTeamMembers = new List<ulong>();
            if (config.teamupdate) {
                var playerTeam = RelationshipManager.ServerInstance.FindPlayersTeam(player.userID);
                if(playerTeam == null) {
                    playerTeamMembers.Add(player.userID);
                }
                else {
                    playerTeamMembers = playerTeam?.members?.ToList() ?? new List<ulong>();
                    //Puts("Team detectado.Con " + playerTeamMembers.Count + " jugadores en el Team.");
                }
            }
            for (var index = 0; index < set.Count; index++) {
                var block = set[index];
                if (cup == null) yield break;
                if (!BuildingCupboard[cup].work) {
                    show = false;
                    break;
                }
                var grade = BuildingCupboard[cup].grade;
                if (!config.teamupdate || playerTeamMembers.Contains(block.OwnerID)) {
                    if (grade == block.grade) continue;
                    if (!incompatibleFound) {
                        if (Interface.CallHook("OnStructureUpgrade", block, player, grade) != null) {
                            BuildingCupboard[cup].work = false;
                            ShowButtonTC(player, cup);
                            CreateGameTip(cup, Languaje("UpgradeBlock", player.UserIDString), player, fxnoresources, 10, "danger");
                            show = false;
                            break;
                        }
                    }
                    bool canDowngrade = config.downgrade && BuildingCupboard[cup].downgrade;
                    bool isOwner = player.userID == block.OwnerID;
                    bool shouldOnlyOwnerDowngrade = config.onlyowner && !isOwner;
                    bool shouldOnlyOwnerUpgrade = config.onlyownerup && !isOwner;
                    if ((!canDowngrade || shouldOnlyOwnerDowngrade) && (grade < block.grade)) continue;
                    if (shouldOnlyOwnerUpgrade && (grade > block.grade)) continue;
                    //Puts("canDowngrade " + canDowngrade  + " shouldOnlyOwnerDowngrade" + shouldOnlyOwnerDowngrade + " grade < block.grade " + (grade < block.grade));
                    //Puts("shouldOnlyOwnerUpgrade " + shouldOnlyOwnerUpgrade  + " (grade > block.grade) " + (grade > block.grade));
                    /*if (config.teamupdate && player.userID != block.OwnerID){
                        Puts("Check Team");
                        if(!CheckTeam(block.OwnerID, player.userID)) continue;
                    }*/
                    UpgradeBlock(cup, block, grade, player);
                    yield return CoroutineEx.waitForSeconds(cd);
                }
            }
            BuildingCupboard[cup].work = false;
            BuildingCupboard[cup].workupgrade = null;
            if(show) {
                if (playerTeamMembers.Count == 1) {
                    CreateGameTip(cup, Languaje("UpgradeFinishNoPlayer", player.UserIDString), player, fxfinish, 10);
                }
                else {
                    CreateGameTip(cup, Languaje("UpgradeFinish", player.UserIDString), player, fxfinish, 10);
                }
                /*Puts("Mostrando miembros del Team:");
                foreach (ulong member in playerTeamMembers){
                    Puts("SteamID " + member);
                }*/
            }
            playerTeamMembers.Clear();
            yield return 0;
        }
        private IEnumerator UpdateCost(BasePlayer player, BuildingPrivlidge cup) {
            var set = cup.GetBuilding().buildingBlocks;
            List<ulong> playerTeamMembers = new List<ulong>();
            if (config.teamupdate) {
                var playerTeam = RelationshipManager.ServerInstance.FindPlayersTeam(player.userID);
                if(playerTeam == null) {
                    playerTeamMembers.Add(player.userID);
                }
                else {
                    playerTeamMembers = playerTeam?.members?.ToList() ?? new List<ulong>();
                }
            }
            Dictionary<ItemDefinition, int> totalCost = new Dictionary<ItemDefinition, int>();
            for (var index = 0; index < set.Count; index++) {
                var block = set[index];
                if (cup == null) yield break;
                var grade = BuildingCupboard[cup].grade;
                if (!config.teamupdate || playerTeamMembers.Contains(block.OwnerID)) {
                    if (grade == block.grade) continue;
                    bool canDowngrade = config.downgrade && BuildingCupboard[cup].downgrade;
                    bool isOwner = player.userID == block.OwnerID;
                    bool shouldOnlyOwnerDowngrade = config.onlyowner && !isOwner;
                    bool shouldOnlyOwnerUpgrade = config.onlyownerup && !isOwner;
                    if ((!canDowngrade || shouldOnlyOwnerDowngrade) && (grade < block.grade)) continue;
                    if (shouldOnlyOwnerUpgrade && (grade > block.grade)) continue;
                    List<ItemAmount> upgradeCost = block.blockDefinition.GetGrade(grade, 0).CostToBuild();
                    foreach (var item in upgradeCost) {
                        if (totalCost.ContainsKey(item.itemDef)) {
                            totalCost[item.itemDef] += (int)item.amount;
                        }
                        else {
                            totalCost[item.itemDef] = (int)item.amount;
                        }
                    }
                }
            }
            string costMessage = "";
            foreach (var cost in totalCost) {
                costMessage += $"{cost.Value} x {cost.Key.displayName.english}\n";
            }
            CreateGameTip(cup, totalCost.Count == 0 ? Languaje("NoUpgradeAvailable", player.UserIDString) : Languaje("TotalCostUP", player.UserIDString, costMessage), player, fxfinish, 10);
            //Puts("Cost Upgrade: " + (totalCost.Count == 0 ? Languaje("NoUpgradeAvailable", player.UserIDString) : Languaje("TotalCostUP", player.UserIDString, costMessage)) + " TC: " + player.transform.position);
            playerTeamMembers.Clear();
            totalCost.Clear();
            yield return 0;
        }
        private IEnumerator ReskinProgress(BasePlayer player, BuildingPrivlidge cup) {
            var set = cup.GetBuilding().buildingBlocks;
            yield return CoroutineEx.waitForSeconds(0.15f);
            var cd = Frequency(player.UserIDString, config.FrequencyReskin);
            bool show = true;
            for (var index = 0; index < set.Count; index++) {
                var block = set[index];
                if (cup == null) yield break;
                if(!BuildingCupboard[cup].reskin) {
                    show = false;
                    break;
                }
                var grade = BuildingCupboard[cup].grade;
                if (grade != block.grade) continue;
                if (Convert.ToUInt32(BuildingCupboard[cup].skinid) == block.skinID && BuildingCupboard[cup].colour == block.customColour) continue;
                ReskinBlock(cup, block, grade, player);
                yield return CoroutineEx.waitForSeconds(cd);
            }
            BuildingCupboard[cup].reskin = false;
            BuildingCupboard[cup].workreskin = null;
            if(show) CreateGameTip(cup, Languaje("ReskinFinish", player.UserIDString), player, fxfinish, 10);
            yield return 0;
        }
        private IEnumerator WallpaperProgress(BasePlayer player, BuildingPrivlidge cup) {
            var set = cup.GetBuilding().buildingBlocks;
            yield return CoroutineEx.waitForSeconds(0.15f);
            var cd = Frequency(player.UserIDString, config.FrequencyWallpaper);
            bool show = true;
            List<ulong> playerTeamMembers = new List<ulong>();
            if (config.teamupdate) {
                var playerTeam = RelationshipManager.ServerInstance.FindPlayersTeam(player.userID);
                if(playerTeam == null) {
                    playerTeamMembers.Add(player.userID);
                }
                else {
                    playerTeamMembers = playerTeam?.members?.ToList() ?? new List<ulong>();
                }
            }
            var grade = BuildingCupboard[cup].grade;
            for (var index = 0; index < set.Count; index++) {
                var block = set[index];
                if (cup == null) yield break;
                if (!BuildingCupboard[cup].work) {
                    show = false;
                    break;
                }
                var wallpaperid = BuildingCupboard[cup].wallpaperid;
                if (!config.teamupdate || playerTeamMembers.Contains(block.OwnerID)) {
                    if (wallpaperid == block.wallpaperID && block.wallpaperHealth != -1) continue;
                    if (grade != block.grade && !BuildingCupboard[cup].wallpall) continue;
                    if (!block.ShortPrefabName.Contains("wall") || block.ShortPrefabName.Contains("wall.frame")) continue;
                    if (Convert.ToUInt32(BuildingCupboard[cup].skinid) != block.skinID && !BuildingCupboard[cup].wallpall) continue;
                    WallpaperBlock(cup, block, player);
                    yield return CoroutineEx.waitForSeconds(cd);
                }
            }
            BuildingCupboard[cup].work = false;
            BuildingCupboard[cup].workwallpaper = null;
            if(show) {
                if (playerTeamMembers.Count == 1) {
                    CreateGameTip(cup, Languaje("WallpaperFinishNoPlayer", player.UserIDString), player, fxfinish, 10);
                }
                else {
                    CreateGameTip(cup, Languaje("WallpaperFinish", player.UserIDString), player, fxfinish, 10);
                }
            }
            playerTeamMembers.Clear();
            yield return 0;
        }
        private bool RepairBlock(BasePlayer player, BaseCombatEntity entity, BuildingPrivlidge cup, float cost, bool deployed) {
            if (entity == null || !entity.IsValid() || entity.IsDestroyed || entity.transform == null) return false;
            if (!entity.repair.enabled || entity.health == entity.MaxHealth()) return false;
            if (Interface.CallHook("OnStructureRepair", entity, player) != null) return false;
            var missingHealth = entity.MaxHealth() - entity.health;
            var healthPercentage = missingHealth / entity.MaxHealth();
            if (missingHealth <= 0f || healthPercentage <= 0f) {
                entity.OnRepairFailed(null, string.Empty);
                return false;
            }
            var itemAmounts = entity.RepairCost(healthPercentage);
            if (itemAmounts.Sum(x => x.amount) <= 0f) {
                entity.health += missingHealth;
                entity.SendNetworkUpdate();
                entity.OnRepairFinished();
                return true;
            }
            if (!HasPermission(player.UserIDString, permrepairnocost)) {
                foreach (var amount in itemAmounts) {
                    amount.amount *= cost;
                }
                if (itemAmounts.Any(ia => cup.inventory.GetAmount(ia.itemid, false) < (int)ia.amount)) {
                    entity.OnRepairFailed(null, string.Empty);
                    CreateGameTip(cup, Languaje("NoResourcesRepair", player.UserIDString), player, fxnoresources, 10, "danger");
                    BuildingCupboard[cup].repair = false;
                    return false;
                }
                foreach (var amount in itemAmounts) {
                    cup.inventory.Take(null, amount.itemid, (int)amount.amount);
                }
            }
            if (config.playfx && BuildingCupboard[cup].effect && deployed) {
                Effect.server.Run(fxrepair, entity.transform.position);
            }
            entity.health += missingHealth;
            entity.SendNetworkUpdate();
            if (entity.health < entity.MaxHealth()) {
                entity.OnRepair();
            }
            else {
                entity.OnRepairFinished();
            }
            return true;
        }
        private void UpgradeBlock(BuildingPrivlidge cup, BuildingBlock block, BuildingGrade.Enum grade, BasePlayer player) {
            if (!HasPermission(player.UserIDString, permupgradenocost) && !CanUpgrade(player, cup, block, grade)) {
                BuildingCupboard[cup].work = false;
                CreateGameTip(cup, Languaje("NoResourcesUpgrade", player.UserIDString), player, fxnoresources, 10, "danger");
                return;
            }
            if (CheckBlock(block)) return;
            if (!HasPermission(player.UserIDString, permupgradenocost)) {
                var list = block.blockDefinition.GetGrade(grade, 0).CostToBuild();
                for (var index = 0; index < list.Count; index++) {
                    var check = list[index];
                    TakeResources(cup.inventory.itemList, check.itemDef.shortname, (int)check.amount);
                }
            }
            ulong skin = Convert.ToUInt32(BuildingCupboard[cup].skinid);
            block.skinID = skin;
            if (config.playfx && BuildingCupboard[cup].effect) {
                var effect = "assets/bundled/prefabs/fx/build/promote_toptier.prefab";
                if(grade == BuildingGrade.Enum.Wood) {
                    effect = "assets/bundled/prefabs/fx/build/frame_place.prefab";
                    block.ClientRPC<int, ulong>(null, "DoUpgradeEffect", (int)BuildingGrade.Enum.Wood, skin);
                }
                else if(grade == BuildingGrade.Enum.Stone) {
                    effect = "assets/bundled/prefabs/fx/build/promote_stone.prefab";
                    block.ClientRPC<int, ulong>(null, "DoUpgradeEffect", (int)BuildingGrade.Enum.Stone, skin);
                }
                else if(grade == BuildingGrade.Enum.Metal) {
                    effect = "assets/bundled/prefabs/fx/build/promote_metal.prefab";
                    block.ClientRPC<int, ulong>(null, "DoUpgradeEffect", (int)BuildingGrade.Enum.Metal, skin);
                }
                else {
                    block.ClientRPC<int, ulong>(null, "DoUpgradeEffect", (int)BuildingGrade.Enum.TopTier, skin);
                }
                Effect.server.Run(effect, block.transform.position);
            }
            block.SetGrade(grade);
            block.UpdateSkin();
            block.SetHealthToMax();
            if(BuildingCupboard[cup].color) block.SetCustomColour(BuildingCupboard[cup].colour);
            block.SendNetworkUpdateImmediate();
        }
        private void WallpaperBlock(BuildingPrivlidge cup, BuildingBlock block, BasePlayer player) {
            if (!HasPermission(player.UserIDString, permwallpapernocost) && !CanWallpaper(player, cup)) {
                BuildingCupboard[cup].work = false;
                CreateGameTip(cup, Languaje("NoResourcesWallpaper", player.UserIDString), player, fxnoresources, 10, "danger");
                return;
            }
            if (CheckBlock(block)) return;
            ulong wallpaperID = Convert.ToUInt32(BuildingCupboard[cup].wallpaperid);
            if(wallpaperID == 1) {
                block.RemoveWallpaper(0);
                block.RemoveWallpaper(1);
            }
            else {
                if (!HasPermission(player.UserIDString, permupgradenocost)) {
                    TakeResources(cup.inventory.itemList, "cloth", config.wallresource);
                }
                block.SetWallpaper(wallpaperID);
                if(config.bothsides && BuildingCupboard[cup].wpbothsides) block.SetWallpaper(wallpaperID, 1);
            }
            if (config.playfx && BuildingCupboard[cup].effect) {
                Effect.server.Run(fxcloth, block.transform.position);
            }
        }
        private void ReskinBlock(BuildingPrivlidge cup, BuildingBlock block, BuildingGrade.Enum grade, BasePlayer player) {
            if (!HasPermission(player.UserIDString, permreskinnocost) && !CanUpgrade(player, cup, block, grade)) {
                BuildingCupboard[cup].reskin = false;
                CreateGameTip(cup, Languaje("NoResourcesReskin", player.UserIDString), player, fxnoresources, 10, "danger");
                return;
            }
            if (CheckBlock(block)) return;
            if (!HasPermission(player.UserIDString, permreskinnocost)) {
                var list = block.blockDefinition.GetGrade(grade, 0).CostToBuild();
                for (var index = 0; index < list.Count; index++) {
                    var check = list[index];
                    TakeResources(cup.inventory.itemList, check.itemDef.shortname, (int)check.amount);
                }
            }
            ulong skin = Convert.ToUInt32(BuildingCupboard[cup].skinid);
            block.skinID = skin;
            block.UpdateSkin();
            if(BuildingCupboard[cup].color) block.SetCustomColour(BuildingCupboard[cup].colour);
            block.SendNetworkUpdateImmediate();
            if (config.playfx && BuildingCupboard[cup].effect) {
                Effect.server.Run(fxspray, block.transform.position);
                Effect.server.Run(fxreskin, block.transform.position);
            }
        }
        private bool CanUpgrade(BasePlayer player, BuildingPrivlidge cup, BuildingBlock block, BuildingGrade.Enum grade) {
            var list = block.blockDefinition.GetGrade(grade, 0).CostToBuild();
            for (var index = 0; index < list.Count; index++) {
                ItemAmount itemAmount = list[index];
                if (cup.inventory.GetAmount(itemAmount.itemid, false) < (double) itemAmount.amount) return false;
            }
            return true;
        }
        private bool CanWallpaper(BasePlayer player, BuildingPrivlidge cup) {
            if (cup.inventory.GetAmount(-858312878, false) < (double) config.wallresource) return false;
            return true;
        }
        private bool Unlock(int maxGradeTier, string requiredGrade) {
            if (maxGradeTier == 1 && requiredGrade == "wood") return true;
            if (maxGradeTier == 2 && (requiredGrade == "wood" || requiredGrade == "stone")) return true;
            if (maxGradeTier == 3 && (requiredGrade == "wood" || requiredGrade == "stone" || requiredGrade == "metal")) return true;
            if (maxGradeTier == 4) return true;
            return false;
        }
        private static void TakeResources(IEnumerable<Item> itemList, string name, int takeitems) {
            if (takeitems == 0) return;
            var list = Facepunch.Pool.Get<List<Item>>();
            var num1 = 0;
            foreach (var obj in itemList) {
                if (obj.info.shortname != name) continue;
                var num2 = takeitems - num1;
                if (num2 <= 0) continue;
                if (obj.amount > num2) {
                    obj.MarkDirty();
                    obj.amount -= num2;
                    break;
                }
                if (obj.amount <= num2) {
                    num1 += obj.amount;
                    list.Add(obj);
                }
                if (num1 == takeitems) break;
            }
            foreach (var obj in list) obj.Remove();
            Facepunch.Pool.FreeUnmanaged(ref list);
        }
        private void TCSkinReplace(BuildingPrivlidge tc, BasePlayer player, TCSkin skin) {
            string prefabPath = skin switch {
                TCSkin.Retro => "assets/prefabs/deployable/tool cupboard/retro/cupboard.tool.retro.deployed.prefab", TCSkin.Shockbyte => "assets/prefabs/deployable/tool cupboard/shockbyte/cupboard.tool.shockbyte.deployed.prefab", _ => "assets/prefabs/deployable/tool cupboard/cupboard.tool.deployed.prefab"
            }
            ;
            BaseEntity tcskin = GameManager.server.CreateEntity(prefabPath, tc.transform.position, tc.transform.rotation, true) as BaseEntity;
            tcskin.OwnerID = tc.OwnerID;
            tcskin.Spawn();
            NextTick(() => {
                var Building = tcskin as BuildingPrivlidge;
                if (Building == null) return;
                foreach (var authorized in tc.authorizedPlayers) {
                    Building.authorizedPlayers.Add(new PlayerNameID {
                        userid = authorized.userid, username = authorized.username
                    }
                    );
                }
                Building.AttachToBuilding(tc.buildingID);
                Building.BuildingDirty();
                Building.SendNetworkUpdate(BasePlayer.NetworkQueue.Update);
                UpdateBlockedItems(Building);
                if (tc.inventory != null && Building.inventory != null) {
                    foreach (var item in tc.inventory.itemList.ToList()) {
                        var newItem = ItemManager.CreateByItemID(item.info.itemid, item.amount, item.skin);
                        if (newItem != null) {
                            newItem.condition = item.condition;
                            newItem.maxCondition = item.maxCondition;
                            newItem.MoveToContainer(Building.inventory);
                        }
                    }
                }
                var originalLock = tc.GetSlot(BaseEntity.Slot.Lock) as CodeLock;
                if (originalLock != null) {
                    var codeLock = GameManager.server.CreateEntity(originalLock.PrefabName) as CodeLock;
                    if (codeLock != null) {
                        codeLock.OwnerID = originalLock.OwnerID;
                        codeLock.code = originalLock.code;
                        codeLock.whitelistPlayers = new List<ulong>(originalLock.whitelistPlayers);
                        codeLock.guestCode = originalLock.guestCode;
                        codeLock.guestPlayers = new List<ulong>(originalLock.guestPlayers);
                        codeLock.SetFlag(BaseEntity.Flags.Locked, true);
                        codeLock.SetParent(Building, Building.GetSlotAnchorName(BaseEntity.Slot.Lock));
                        codeLock.Spawn();
                        Building.SetSlot(BaseEntity.Slot.Lock, codeLock);
                    }
                }
                var originalLock2 = tc.GetSlot(BaseEntity.Slot.Lock) as KeyLock;
                if (originalLock2 != null) {
                    var keyLock = GameManager.server.CreateEntity(originalLock2.PrefabName) as KeyLock;
                    if (keyLock != null) {
                        keyLock.OwnerID = originalLock2.OwnerID;
                        keyLock.keyCode = originalLock2.keyCode;
                        keyLock.SetFlag(BaseEntity.Flags.Locked, true);
                        keyLock.SetParent(Building, Building.GetSlotAnchorName(BaseEntity.Slot.Lock));
                        keyLock.Spawn();
                        Building.SetSlot(BaseEntity.Slot.Lock, keyLock);
                    }
                }
                string effectPath = skin switch {
                    TCSkin.Retro => "assets/prefabs/deployable/tool cupboard/retro/effects/tool-cupboard-retro-deploy.prefab", TCSkin.Shockbyte => "assets/prefabs/deployable/tool cupboard/effects/tool-cupboard-deploy.prefab", _ => "assets/prefabs/deployable/tool cupboard/effects/tool-cupboard-deploy.prefab"
                }
                ;
                Effect.server.Run(effectPath, tcskin.transform.position);
                tc.Kill();
            }
            );
        }
        private bool CheckTeam(ulong owner, ulong player) => RelationshipManager.ServerInstance.FindPlayersTeam(owner)?.members?.Contains(player) ?? false;
        private bool CheckBlock(BuildingBlock block) => block.blockDefinition.checkVolumeOnUpgrade && DeployVolume.Check(block.transform.position, block.transform.rotation, PrefabAttribute.server.FindAll<DeployVolume>(block.prefabID), ~(1 << block.gameObject.layer));
        private List<ProtoBuf.PlayerNameID> GetAuthPlayers(BuildingPrivlidge cup) {
            return cup.authorizedPlayers.Where(player => (HasPermission(player.userid.ToString(), permadmin) && config.adminshow == true) || !HasPermission(player.userid.ToString(), permadmin)).ToList();
        }
        private List<ItemInfo> GetBuildingItems(BasePlayer player) {
            return config.itemsList.Where(item => item.enabled == true).ToList();
        }
        private List<ItemInfoWallpaper> GetWallpaperItems(BasePlayer player) {
            return config.itemsWallpaperList.Where(item => item.enabled == true).ToList();
        }
        private float Frequency(string steamid, Dictionary<string, float> frequency) {
            float c = 100.0f;
            foreach (var item in frequency) {
                if (HasPermission(steamid, item.Key)) c = Math.Min(c, item.Value);
            }
            return c;
        }
        private float ResourcesRepair(string steamid) {
            float r = 100.0f;
            foreach (var item in config.CostListRepair) {
                if (HasPermission(steamid, item.Key)) r = Math.Min(r, item.Value);
            }
            return r;
        }
        private void GetNewItems(BasePlayer player) {
            try {
                using (WebClient client = new WebClient()) {
                    string json = client.DownloadString(apiUrl);
                    var parsedData = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
                    if (parsedData != null) {
                        List<ItemInfo> buildingList = parsedData.ContainsKey("building") ? JsonConvert.DeserializeObject<List<ItemInfo>>(parsedData["building"].ToString()) : new List<ItemInfo>();
                        List<ItemInfoWallpaper> wallpaperList = parsedData.ContainsKey("wallpaper") ? JsonConvert.DeserializeObject<List<ItemInfoWallpaper>>(parsedData["wallpaper"].ToString()) : new List<ItemInfoWallpaper>();
                        Dictionary<string, string> imageListCraft = new Dictionary<string, string>();
                        bool configUpdated = false;
                        foreach (var newItem in buildingList) {
                            if (newItem.ID > GetMaxItemId()) {
                                var newItemInfo = new ItemInfo {
                                    ID = newItem.ID, enabled = newItem.enabled, name = newItem.name, grade = newItem.grade, img = newItem.img, itemID = newItem.itemID, skinid = newItem.skinid, color = newItem.color, permission = newItem.permission
                                }
                                ;
                                if (!string.IsNullOrEmpty(newItem.img) && !imageListCraft.ContainsKey(newItem.img)) {
                                    imageListCraft.Add(newItem.img, newItem.img);
                                }
                                config.itemsList.Add(newItemInfo);
                                configUpdated = true;
                            }
                        }
                        foreach (var newItem in wallpaperList) {
                            if (newItem.ID > GetMaxItemId2()) {
                                var newItemInfo2 = new ItemInfoWallpaper {
                                    ID = newItem.ID, enabled = newItem.enabled, name = newItem.name, img = newItem.img, itemID = newItem.itemID, skinid = newItem.skinid, permission = newItem.permission
                                }
                                ;
                                if (!string.IsNullOrEmpty(newItem.img) && !imageListCraft.ContainsKey(newItem.img)) {
                                    imageListCraft.Add(newItem.img, newItem.img);
                                }
                                config.itemsWallpaperList.Add(newItemInfo2);
                                configUpdated = true;
                            }
                        }
                        if (configUpdated) {
                            ImageLibrary?.Call("ImportImageList", Title, imageListCraft, 0UL, true, null);
                            SaveConfig();
                            if(player != null) {
                                var soundEffect = new Effect(fxfinish, player.transform.position, Vector3.zero);
                                if (soundEffect == null) return;
                                EffectNetwork.Send(soundEffect, player.net.connection);
                                player.ShowToast(GameTip.Styles.Blue_Normal, "Updated configuration with new items.");
                            }
                            Puts("CheckUpdate: Updated configuration with new items.");
                        }
                        else {
                            if(player != null) player.ShowToast(GameTip.Styles.Error, "There are no new items.");
                            Puts("CheckUpdate: There are no new items.");
                        }
                    }
                }
            }
            catch (Exception ex) {
                Puts("Error getting new items: " + ex.Message);
            }
        }
        int GetMaxItemId() {
            int maxId = 0;
            foreach (var item in config.itemsList) {
                if (item.ID > maxId) maxId = item.ID;
            }
            return maxId;
        }
        int GetMaxItemId2() {
            int maxId = -1;
            foreach (var item in config.itemsWallpaperList) {
                if (item.ID > maxId) maxId = item.ID;
            }
            return maxId;
        }
        private bool HasPermission(string userID, string perm) {
            return string.IsNullOrEmpty(perm) || permission.UserHasPermission(userID, perm);
        }
        private string GetImageLibrary(string name, ulong skinid = 0) {
            return ImageLibrary?.Call<string>("GetImage", name, skinid);
        }
        private void CreateGameTip(BuildingPrivlidge cup, string text, BasePlayer player, string sound, float length = 10f, string red = "") {
            if (player == null) return;
            int type = config.notifyType["info"];
            if (red == "danger") type = config.notifyType["error"];
            if (cup != null) {
                Effect.server.Run(sound, cup.transform.position);
                foreach (ProtoBuf.PlayerNameID pnid in cup.authorizedPlayers) {
                    BasePlayer foundPlayer = BasePlayer.Find(pnid.userid.ToString());
                    if(foundPlayer != null) {
                        if(config.alertgametip) {
                            if (red == "danger") {
                                //foundPlayer.SendConsoleCommand($"gametip.showtoast {1} \"{text}\"  ");
                                foundPlayer.ShowToast(GameTip.Styles.Error, text);
                            }
                            else {
                                foundPlayer.SendConsoleCommand("gametip.hidegametip");
                                foundPlayer.SendConsoleCommand("gametip.showgametip", text);
                                timer.Once(length, () => foundPlayer.SendConsoleCommand("gametip.hidegametip"));
                            }
                        }
                        if(config.alertnotify && (Notify != null || UINotify != null)) Interface.Oxide.CallHook("SendNotify", foundPlayer, type, text);
                        if(config.alertchat) PrintToChat(foundPlayer, text);
                    }
                }
            }
            else {
                Effect.server.Run(sound, player.transform.position);
                if(config.alertgametip) {
                    if (red == "danger") {
                        player.SendConsoleCommand($"gametip.showtoast {1} \"{text}\"  ");
                    }
                    else {
                        player.SendConsoleCommand("gametip.hidegametip");
                        player.SendConsoleCommand("gametip.showgametip", text);
                        timer.Once(length, () => player.SendConsoleCommand("gametip.hidegametip"));
                    }
                }
                if(config.alertnotify && (Notify != null || UINotify != null)) Interface.Oxide.CallHook("SendNotify", player, type, text);
                if(config.alertchat) PrintToChat(player, text);
            }
        }
        private void UpdateBlockedItems(BuildingPrivlidge cupboard) {
            if (cupboard == null || cupboard.inventory == null || cupboard.inventory.blockedItems == null) return;
            HashSet<ItemDefinition> newBlockedItems = new HashSet<ItemDefinition>(cupboard.inventory.blockedItems);
            HashSet<ItemDefinition> newAllowedItems;
            if (cupboard.inventory.onlyAllowedItems == null || cupboard.inventory.onlyAllowedItems.Length == 0) {
                newAllowedItems = new HashSet<ItemDefinition>(ItemManager.itemList.Where(itemDef => itemDef.category == ItemCategory.Resources || itemDef.category == ItemCategory.Construction) );
            }
            else {
                newAllowedItems = new HashSet<ItemDefinition>(cupboard.inventory.onlyAllowedItems);
            }
            foreach (var item in ItemManager.itemList) {
                if (config.allowedItemsConfig.TryGetValue(item.shortname, out bool isAllowed)) {
                    if (isAllowed) {
                        newBlockedItems.Remove(item);
                        newAllowedItems.Add(item);
                    }
                    else {
                        newBlockedItems.Add(item);
                        newAllowedItems.Remove(item);
                    }
                }
            }
            cupboard.inventory.blockedItems = newBlockedItems;
            cupboard.inventory.MarkDirty();
        }
        BuildingPrivlidge GetPlayerTC(BasePlayer
// ... [Code preview truncated due to length. Full source in attached file] ...

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

Другие ресурсы пользователя 15FPS

Сверху