Пример #1
0
        private static void CCTestBots(ConCommandArgs args)
        {
            if (Stage.instance == null)
            {
                return;
            }

            NetworkUser user = args.sender;

            foreach (GameObject gameObject in playerbots)
            {
                CharacterMaster master      = gameObject.GetComponent <CharacterMaster>();
                AIOwnership     aiOwnership = gameObject.GetComponent <AIOwnership>();
                string          name        = master.GetBody().GetDisplayName();

                if (aiOwnership.ownerMaster)
                {
                    Debug.Log(name + "'s master: " + aiOwnership.ownerMaster.GetBody().GetUserName());
                }
                else
                {
                    Debug.Log(name + " has no master");
                }

                Debug.Log(name + "'s money: " + master.money);
            }
        }
        private static void CCPermissionAddUser(ConCommandArgs args)
        {
            if (args.Count == 0)
            {
                Log.MessageNetworked(Lang.PERM_MOD_ARGS, args, Log.LogLevel.Error);
                return;
            }
            try
            {
                NetworkUser nu = Util.GetNetUserFromString(args.userArgs);

                if (IsEnabled.Value)
                {
                    if (Enum.TryParse(args[0], out PermissionLevel level))
                    {
                        // TODO: finish that lol
                        Log.MessageNetworked("Please edit the users permissions through the config file for now and reload using perm_reload in the console", args, Log.LogLevel.Error);
                    }
                    else
                    {
                        Log.MessageNetworked($"Couldn't parse correctly the level you provided ({args[0]})", args, Log.LogLevel.Error);
                    }
                }
                else
                {
                    Log.MessageNetworked("The permission system is currently disabled, enable it first with perm_enable", args, Log.LogLevel.Error);
                }
            }
            catch
            {
                Log.MessageNetworked(Lang.PLAYER_NOTFOUND, args, Log.LogLevel.Error);
            }
        }
Пример #3
0
        // try and setup our character, if we hit an error we set it to false
        //TODO: Find a way to stop it from checking whilst in main menu/lobby menu
        private static void GetCharacter()
        {
            try
            {
                LocalNetworkUser = null;
                foreach (NetworkUser readOnlyInstance in NetworkUser.readOnlyInstancesList)
                {
                    //localplayer == you!
                    if (readOnlyInstance.isLocalPlayer)
                    {
                        LocalNetworkUser = readOnlyInstance;
                        LocalPlayer      = LocalNetworkUser.master;
                        LocalPlayerInv   = LocalPlayer.GetComponent <Inventory>();                 //gets player inventory
                        LocalHealth      = LocalPlayer.GetBody().GetComponent <HealthComponent>(); //gets players local health numbers
                        LocalSkills      = LocalPlayer.GetBody().GetComponent <SkillLocator>();    //gets current for local character skills
                        Localbody        = LocalPlayer.GetBody().GetComponent <CharacterBody>();   //gets all stats for local character
                        LocalMotor       = LocalPlayer.GetBody().GetComponent <CharacterMotor>();

                        if (LocalPlayer.alive)
                        {
                            _CharacterCollected = true;
                        }
                        else
                        {
                            _CharacterCollected = false;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _CharacterCollected = false;
            }
        }
Пример #4
0
        internal static void GiveAveragedItems(NetworkUser joiningPlayer, bool includeRed, bool includeLunar, bool includeBoss)
        {
            RefreshItemCaches(); // Not sure if drop lists can change during a run, so refresh the cache each time a player joins just incase

            Inventory targetInventory = joiningPlayer?.master?.inventory;

            Inventory[] otherPlayerInventories = NetworkUser.readOnlyInstancesList
                                                 .Where(player => !player.id.Equals(joiningPlayer.id) && player?.master?.inventory != null) // Don't include self or any other players who don't have a character
                                                 .Select(p => p.master.inventory)
                                                 .ToArray();

            if (targetInventory == null ||          // The new player does not have character yet
                otherPlayerInventories.Length <= 0) // We are the only player
            {
                return;
            }

            AddToItemsToMatch(targetInventory, otherPlayerInventories, ItemTier.Tier1);
            AddToItemsToMatch(targetInventory, otherPlayerInventories, ItemTier.Tier2);
            if (includeRed)
            {
                AddToItemsToMatch(targetInventory, otherPlayerInventories, ItemTier.Tier3);
            }
            if (includeLunar)
            {
                AddToItemsToMatch(targetInventory, otherPlayerInventories, ItemTier.Lunar);
            }
            if (includeBoss)
            {
                AddToItemsToMatch(targetInventory, otherPlayerInventories, ItemTier.Boss);
            }
        }
Пример #5
0
        public override void OnEnter()
        {
            base.OnEnter();
            if (base.isAuthority)
            {
                // prepare anim
                netTriggerContainer = new ClientAnimatorTriggerContainer();
                netTriggerContainer.characterDirection = base.characterDirection.gameObject;
                // prepare network user
                thisInstance = base.GetComponent <NetworkIdentity>();
                thisUser     = NetworkUser.readOnlyInstancesList.Where(x => x.netId == thisInstance.netId).FirstOrDefault();

                // get animation time
                hitDuration = GetAnimationTime("seph_ground_combo");
                // play anim
                base.characterDirection.modelAnimator.SetTrigger("isGroundCombo1");
                netTriggerContainer.animName = "isGroundCombo1";
                NetServerRequestAnimTrigger.Invoke(netTriggerContainer, thisUser);

                // force aim
                base.StartAimMode(hitDuration);

                // damage coroutine
                thisSephiroth = base.gameObject.GetComponentInChildren <SephirothModelSwap>();
                thisSephiroth.StartCoroutine(PrimaryGroundCoroutine());
            }
        }
Пример #6
0
        private static void UpdateLobbyControls(NetworkUser exceptUser = null)
        {
            var interactable =
                SteamworksLobbyManager.isInLobby == SteamworksLobbyManager.ownsLobby &&
                File.Exists(SaveFileMetadata.GetCurrentLobbySaveMetadata(exceptUser)?.FilePath);

            try
            {
                if (lobbyButton)
                {
                    var component = lobbyButton?.GetComponent <HGButton>();
                    if (component)
                    {
                        component.interactable = interactable;
                    }
                }
            }
            catch { }
            try
            {
                if (lobbyGlyphAndDescription)
                {
                    var color = interactable ? Color.white : new Color(0.3F, 0.3F, 0.3F);

                    var glyphText = lobbyGlyphAndDescription.transform.GetChild(0).GetComponent <HGTextMeshProUGUI>();
                    glyphText.color = color;

                    var descriptionText = lobbyGlyphAndDescription.transform.GetChild(1).GetComponent <HGTextMeshProUGUI>();
                    descriptionText.color = color;
                }
            }
            catch { }
        }
Пример #7
0
 public void SetHale(NetworkUser networkUser)
 {
     if (networkUser)
     {
         if (networkUsers.Contains(networkUser))
         {
             currentHale = networkUser;
             bossMemory  = new BossGroup.BossMemory()
             {
                 cachedMaster = currentHale.master,
                 cachedBody   = currentHale.GetCurrentBody()
             };
             combatSquad = new CombatSquad();
             combatSquad.AddMember(currentHale.master);
             bossGroup = new BossGroup()
             {
                 combatSquad          = this.combatSquad,
                 bestObservedName     = currentHale.userName,
                 bestObservedSubtitle = "The Boss",
             };
             bossGroup.AddBossMemory(currentHale.master);
             bossGroup.combatSquad = combatSquad;
         }
         else
         {
             Debug.LogError("Couldn't find NetworkUser" + networkUser + "in list of available NetworkUsers");
         }
     }
     else
     {
         Debug.LogError("NetworkUser " + networkUser + " does not exist!");
     }
 }
Пример #8
0
        public static void GiveAveragedItems(NetworkUser joiningPlayer, bool includeRed, bool includeLunar, bool includeBoss)
        {
            var targetInventory        = joiningPlayer?.master?.inventory;
            var otherPlayerInventories = NetworkUser.readOnlyInstancesList
                                         .Where(player => !player.id.Equals(joiningPlayer.id) && player?.master?.inventory != null) // Don't include self or any other players who don't have a character
                                         .Select(p => p.master.inventory)
                                         .ToArray();

            if (targetInventory == null ||          // The new player does not have character yet
                otherPlayerInventories.Length <= 0) // We are the only player
            {
                return;
            }

            AddToItemsToMatch(targetInventory, otherPlayerInventories, ItemCatalog.tier1ItemList, ItemTier.Tier1);
            AddToItemsToMatch(targetInventory, otherPlayerInventories, ItemCatalog.tier2ItemList, ItemTier.Tier2);
            if (includeRed)
            {
                AddToItemsToMatch(targetInventory, otherPlayerInventories, ItemCatalog.tier3ItemList, ItemTier.Tier3);
            }
            if (includeLunar)
            {
                AddToItemsToMatch(targetInventory, otherPlayerInventories, ItemCatalog.lunarItemList, ItemTier.Lunar);
            }
            if (includeBoss)
            {
                if (_bossItems == null)
                {
                    _bossItems = ItemCatalog.allItems.Select(idx => ItemCatalog.GetItemDef(idx)).Where(item => item.tier == ItemTier.Boss).Select(item => item.itemIndex).ToList();
                }
                AddToItemsToMatch(targetInventory, otherPlayerInventories, _bossItems, ItemTier.Boss);
            }
        }
Пример #9
0
    public static void Invoke(NetworkUser user, StatsUpdateList updateList)
    {
        string json = JsonUtility.ToJson(updateList);

        // string json = JsonConvert.SerializeObject(updateList, Formatting.Indented);
        _instance.TargetReceiveUpdate(user.connectionToClient, json);
    }
Пример #10
0
        private static IEnumerator UpdateUsernameDelayed(NetworkUser userToUpdate, NetworkUserId realId)
        {
            yield return(new WaitForSeconds(1));

            userToUpdate.Network_id = realId;
            userToUpdate.SetDirtyBit(1u);
        }
Пример #11
0
        //[AutoCompletion(typeof(NetworkUser), "instancesList", "_id/value", true)] // ideathhd : breaks the whole console for me
        private static void RespawnPlayer(ConCommandArgs args)
        {
            if (args.sender == null && args.Count < 1)
            {
                Log.Message(Lang.DS_REQUIREFULLQUALIFY, LogLevel.Error);
                return;
            }
            CharacterMaster master = args.sender?.master;

            if (args.Count > 0)
            {
                NetworkUser player = Util.GetNetUserFromString(args.userArgs);
                if (player != null)
                {
                    master = player.master;
                }
                else
                {
                    Log.MessageNetworked(Lang.PLAYER_NOTFOUND, args, LogLevel.MessageClientOnly);
                    return;
                }
            }

            Transform spawnPoint = Stage.instance.GetPlayerSpawnTransform();

            master.Respawn(spawnPoint.position, spawnPoint.rotation, false);
            Log.MessageNetworked(string.Format(Lang.SPAWN_ATTEMPT_1, master.name), args);
        }
Пример #12
0
 private static void CreateCostDefGurrenSummon()
 {
     costTypeDefGurrenSummon = new CostTypeDef();
     costTypeDefGurrenSummon.costStringFormatToken = "COST_LUNARCOIN_FORMAT";
     costTypeDefGurrenSummon.isAffordable          = delegate(CostTypeDef costTypeDef, CostTypeDef.IsAffordableContext context)
     {
         CharacterBody characterBody = context.activator.GetComponent <CharacterBody>();
         bool          result        = false;
         if (characterBody && characterBody.bodyIndex == BodyCatalog.FindBodyIndex("LagannBody"))
         {
             var master = characterBody.master;
             if (master)
             {
                 var         gurrenMinionCache = GurrenMinionCache.GetOrSetGurrenStatusCache(master);
                 NetworkUser networkUser       = Util.LookUpBodyNetworkUser(context.activator.gameObject);
                 result = (networkUser &&
                           (ulong)networkUser.lunarCoins >= (ulong)((long)context.cost) &&
                           !gurrenMinionCache.gurrenMinion);
             }
         }
         return(result);
     };
     costTypeDefGurrenSummon.payCost = delegate(CostTypeDef costTypeDef, CostTypeDef.PayCostContext context)
     {
         NetworkUser networkUser = Util.LookUpBodyNetworkUser(context.activator.gameObject);
         bool        flag        = networkUser;
         if (flag)
         {
             networkUser.DeductLunarCoins((uint)context.cost);
         }
     };
     costTypeDefGurrenSummon.colorIndex = ColorCatalog.ColorIndex.LunarCoin;
     CostTypeDefs.Add(costTypeDefGurrenSummon);
 }
Пример #13
0
        private static SaveFileMeta GetLobbySaveMetadata(NetworkUser exceptUser = null)
        {
            var users = NetworkUser.readOnlyInstancesList.Select(el => el.Network_id.steamId.value).ToList();

            if (exceptUser != null)
            {
                users.Remove(exceptUser.Network_id.steamId.value);
            }
            var usersCount = users.Count();

            if (usersCount == 0)
            {
                return(null);
            }
            var gameMode = PreGameController.instance ? PreGameController.instance.gameModeIndex : Run.instance ? Run.instance.gameModeIndex : GameModeIndex.Invalid;

            if (gameMode == GameModeIndex.Invalid)
            {
                return(null);
            }
            if (usersCount == 1)
            {
                var profile = LocalUserManager.readOnlyLocalUsersList[0].userProfile.fileName.Replace(".xml", "");
                return(SavesMetadata.FirstOrDefault(el => el.UserProfileId == profile && el.SteamIds.Length == 1 && el.GameMode == gameMode));
            }
            return(SavesMetadata.FirstOrDefault(el => el.SteamIds.DifferenceCount(users) == 0 && el.GameMode == gameMode));
        }
Пример #14
0
        private void GenericPickupController_GrantLunarCoin(On.RoR2.GenericPickupController.orig_GrantLunarCoin orig, GenericPickupController self, CharacterBody body, uint count)
        {
            if (!NetworkServer.active)
            {
                Debug.LogWarning("[Server] function 'System.Void RoR2.GenericPickupController::GrantLunarCoin(RoR2.CharacterBody,System.UInt32)' called on client");
                return;
            }
            CharacterMaster master      = body.master;
            NetworkUser     networkUser = Util.LookUpBodyNetworkUser(body);

            if (networkUser)
            {
                if (master)
                {
                    GenericPickupController.SendPickupMessage(master, self.pickupIndex);
                }
                networkUser.AwardLunarCoins(count);
                UnityEngine.Object.Destroy(self.gameObject);
            }
            else
            {
                if (master && master.teamIndex != TeamIndex.Player)
                {
                    var component = master.GetBodyObject().GetComponent <DropInventoryOnDeath>();
                    if (!component)
                    {
                        component = master.GetBodyObject().AddComponent <DropInventoryOnDeath>();
                    }
                    component.incrementCoins();
                    GenericPickupController.SendPickupMessage(master, self.pickupIndex);
                    UnityEngine.Object.Destroy(self.gameObject);
                }
            }
        }
Пример #15
0
        // Token: 0x06002388 RID: 9096 RVA: 0x000A7378 File Offset: 0x000A5578
        public void UpdateFromVotes()
        {
            int  num = PreGameRuleVoteController.votesForEachChoice[this.currentChoiceDef.globalIndex];
            bool isInSinglePlayer = RoR2Application.isInSinglePlayer;

            if (num > 0 && !isInSinglePlayer)
            {
                this.voteCounter.enabled = true;
                this.voteCounter.text    = num.ToString();
            }
            else
            {
                this.voteCounter.enabled = false;
            }
            bool        enabled     = false;
            NetworkUser networkUser = this.FindNetworkUser();

            if (networkUser)
            {
                PreGameRuleVoteController preGameRuleVoteController = PreGameRuleVoteController.FindForUser(networkUser);
                if (preGameRuleVoteController)
                {
                    enabled = preGameRuleVoteController.IsChoiceVoted(this.currentChoiceDef);
                }
            }
            this.selectionDisplayPanel.enabled = enabled;
        }
        public static bool isPlayerTooFar(CharacterBody body, float max_distance)
        {
            if (!body)
            {
                return(false);
            }

            NetworkUser n = NetworkUser.readOnlyInstancesList[0];

            if (!n.master)
            {
                return(false);
            }
            CharacterBody cb = n.master.GetBody();

            if (!cb)
            {
                return(false);
            }

            Vector3 footPosition   = body.footPosition;
            Vector3 targetPosition = cb.footPosition;

            // If the distance is greater than a threshold
            if (Vector3.Distance(footPosition, targetPosition) > max_distance)
            {
                return(true);
            }
            return(false);
        }
Пример #17
0
        // Token: 0x0600238B RID: 9099 RVA: 0x000A750C File Offset: 0x000A570C
        public void OnClick()
        {
            if (!this.canVote)
            {
                return;
            }
            NetworkUser networkUser = this.FindNetworkUser();

            Debug.Log(networkUser);
            if (networkUser)
            {
                PreGameRuleVoteController preGameRuleVoteController = PreGameRuleVoteController.FindForUser(networkUser);
                if (preGameRuleVoteController)
                {
                    int choiceValue = this.currentChoiceDef.localIndex;
                    if (preGameRuleVoteController.IsChoiceVoted(this.currentChoiceDef))
                    {
                        choiceValue = -1;
                    }
                    preGameRuleVoteController.SetVote(this.currentChoiceDef.ruleDef.globalIndex, choiceValue);
                    Debug.LogFormat("voteController.SetVote({0}, {1})", new object[]
                    {
                        this.currentChoiceDef.ruleDef.globalIndex,
                        this.currentChoiceDef.localIndex
                    });
                    return;
                }
                Debug.Log("voteController=null");
            }
        }
Пример #18
0
        private void UserDied(On.RoR2.GlobalEventManager.orig_OnPlayerCharacterDeath orig, GlobalEventManager self,
                              DamageInfo damageInfo, GameObject victim, NetworkUser victimNetworkUser)
        {
            var killer = damageInfo.attacker.GetComponent <CharacterBody>();

            if (killer != null && teams.ContainsKey(killer.master))
            {
                teams[killer.master].kills++;
            }

            var char_master = victimNetworkUser.master;

            if (!teams.ContainsKey(char_master))
            {
                return;
            }
            teams[char_master].time_to_revive = Run.TimeStamp.now.t + respawn_delay;
            teams[char_master].deaths++;
            // Give the user something nice :)
            var availableItems = selection.Evaluate(Run.instance.treasureRng.nextNormalizedFloat);
            var item           = availableItems[Run.instance.treasureRng.RangeInt(0, availableItems.Count)];

            char_master.inventory.GiveItem(item);

            Chat.SendBroadcastChat(new Chat.UserChatMessage {
                sender = victimNetworkUser.gameObject,
                text   = String.Format("{0} murdered me. Grabbing [{1}] for a boost.",
                                       killer.master.GetComponent <PlayerCharacterMasterController>().networkUser.userName,
                                       ItemCatalog.GetItemDef(item).unlockableName)
            });
            orig(self, damageInfo, victim, victimNetworkUser);
        }
        /// <summary>
        /// Authenticates the user.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <returns>the grpc response</returns>
        private async Task <GrpcResponse> AuthenticateUser(NetworkUser user)
        {
            var result = new GrpcResponse()
            {
                Result = ResultCode.Ok
            };

            try
            {
                user.AuthenticationToken = await this.handler.Authenticate(user.LoginName, user.PasswordHash);

                if (string.IsNullOrEmpty(user.AuthenticationToken))
                {
                    throw new Exception("Invalid user or password");
                }

                result.Data.Add(Any.Pack(user));
            }
            catch (Exception ex)
            {
                result = new GrpcResponse()
                {
                    Result = ResultCode.Error
                };
                result.Data.Add(Any.Pack(ex.ToProtoException()));
            }

            return(result);
        }
Пример #20
0
        private NetworkUser getNetworkUserOfDamageReport(DamageReport report, bool withMaster)
        {
            NetworkUser tempNetworkUser = null;

            foreach (var element in NetworkUser.readOnlyInstancesList)
            {
                if (report.attackerOwnerMaster != null && withMaster)
                {
                    if (element.GetCurrentBody() != null)
                    {
                        if (element.GetCurrentBody().netId == report.attackerOwnerMaster.GetBody().netId)
                        {
                            tempNetworkUser = element;
                        }
                    }
                }
                else
                {
                    if (element.GetCurrentBody() != null)
                    {
                        if (element.GetCurrentBody().netId == report.attackerBody.netId)
                        {
                            tempNetworkUser = element;
                        }
                    }
                }
            }
            return(tempNetworkUser);
        }
Пример #21
0
        /** <summary>Sends a message to a console.</summary>
         * <param name="input">The message to display</param>
         * <param name="level">The level of the message, note that info may always be displayed in some cases</param>
         * <param name="target">Target console, note that everything to ror2 is also passed to bepinex.</param>
         */
        public static void Message(object input, LogLevel level = LogLevel.Message, Target target = Target.Ror2)
        {
            switch (target)
            {
            case Target.Ror2:
                Ror2Log(input, level);
                break;

            case Target.Bepinex:
                BepinexLog(input, level);
                break;

            default:
                int targetNr = (int)target;
                if (NetworkUser.readOnlyInstancesList.Count - 1 >= targetNr && targetNr >= 0)
                {
                    if (input.GetType() != typeof(string))
                    {
                        Message($"Couldn't send network message because the message was not a string: {input}.", LogLevel.Error, Target.Bepinex);
                        return;
                    }
                    NetworkUser user = NetworkUser.readOnlyInstancesList[targetNr];
                    MessageInfo($"Send a network message to {targetNr}, length={((string) input).Length}");
                    Message((string)input, user, level);
                }
                else
                {
                    Message($"Couldn't find target {targetNr} for message: {input}", LogLevel.Error, Target.Bepinex);
                }
                break;
            }
        }
Пример #22
0
        // Token: 0x060020F4 RID: 8436 RVA: 0x0009AE1C File Offset: 0x0009901C
        public bool IsClientReady()
        {
            int num = 0;

            if (!PreGameController.instance)
            {
                return(false);
            }
            VoteController component = PreGameController.instance.GetComponent <VoteController>();

            if (!component)
            {
                return(false);
            }
            int i         = 0;
            int voteCount = component.GetVoteCount();

            while (i < voteCount)
            {
                VoteController.UserVote vote = component.GetVote(i);
                if (vote.networkUserObject && vote.receivedVote)
                {
                    NetworkUser component2 = vote.networkUserObject.GetComponent <NetworkUser>();
                    if (component2 && component2.isLocalPlayer)
                    {
                        num++;
                    }
                }
                i++;
            }
            return(num == NetworkUser.readOnlyLocalPlayersList.Count);
        }
Пример #23
0
        private static void CCTpBots(ConCommandArgs args)
        {
            NetworkUser user = args.sender;

            if (Stage.instance == null || user.master == null || user.master.IsDeadAndOutOfLivesServer())
            {
                return;
            }

            foreach (GameObject gameObject in playerbots)
            {
                if (gameObject)
                {
                    CharacterMaster master = gameObject.GetComponent <CharacterMaster>();

                    if (!master.IsDeadAndOutOfLivesServer())
                    {
                        TeleportHelper.TeleportGameObject(master.GetBody().gameObject, new Vector3(
                                                              user.master.GetBody().transform.position.x,
                                                              user.master.GetBody().transform.position.y,
                                                              user.master.GetBody().transform.position.z
                                                              ));
                    }
                }
            }
        }
Пример #24
0
        private static void CCGiveEquipment(ConCommandArgs args)
        {
            string equipString  = ArgsHelper.GetValue(args.userArgs, 0);
            string playerString = ArgsHelper.GetValue(args.userArgs, 1);

            NetworkUser player = GetNetUserFromString(playerString);

            Inventory inventory = player != null ? player.master.inventory : args.sender.master.inventory;

            int            equipIndex = 0;
            EquipmentIndex equipType  = EquipmentIndex.None;

            if (int.TryParse(equipString, out equipIndex))
            {
                if (equipIndex < (int)EquipmentIndex.Count && equipIndex >= -1)
                {
                    inventory.SetEquipmentIndex((EquipmentIndex)equipIndex);
                }
            }
            else if (Enum.TryParse <EquipmentIndex>(equipString, true, out equipType))
            {
                inventory.SetEquipmentIndex(equipType);
            }
            else
            {
                Debug.Log("Incorrect arguments. Try: give_equip meteor   --- list_equips for a list of all equipments");
            }
        }
Пример #25
0
    public static void damage(Vector3 position, int amount, NetworkPlayer player)
    {
        NetworkUser user       = NetworkUserList.getUserFromPlayer(player);
        int         permission = UserList.getPermission(user.id);

        if (permission < 1)
        {
            Reference.Tell(player, "Building destroy not allowed!");
            return;
        }

        int num = 0;

        while (num < SpawnStructures.structures.Count)
        {
            if (SpawnStructures.structures[num].position != position)
            {
                num++;
            }
            else
            {
                ServerStructure item = SpawnStructures.structures[num];
                item.health = item.health - amount;
                if (SpawnStructures.structures[num].health <= 0)
                {
                    NetworkEffects.askEffect("Effects/debrisWood", position, Quaternion.Euler(-90f, 0f, 0f), -1f);
                    NetworkSounds.askSound("Sounds/Barricades/debrisWood", position, 1f, UnityEngine.Random.Range(0.9f, 1.1f), 1f);
                    SpawnStructures.tool.networkView.RPC("destroyStructure", RPCMode.All, new object[] { num });
                }
                break;
            }
        }
    }
Пример #26
0
        private void ChangeOrSetCharacter(NetworkUser player, GameObject bodyPrefab, bool firstTimeJoining)
        {
            var master  = player.master;
            var oldBody = master.GetBody();

            master.bodyPrefab = bodyPrefab;

            CharacterBody body;

            if (firstTimeJoining)
            {
                var spawnTransform = Stage.instance.GetPlayerSpawnTransform();
                body = master.SpawnBody(bodyPrefab, spawnTransform.position + _spawnOffset, spawnTransform.rotation);
                Run.instance.HandlePlayerFirstEntryAnimation(body, spawnTransform.position + _spawnOffset, spawnTransform.rotation);
            }
            else
            {
                if (BodyCatalog.GetBodyName(oldBody.bodyIndex) == "CaptainBody")
                {
                    master.inventory.RemoveItem(ItemIndex.CaptainDefenseMatrix, 1);
                }

                if (bodyPrefab.name == "CaptainBody")
                {
                    master.inventory.GiveItem(ItemIndex.CaptainDefenseMatrix, 1);
                }
                body = master.Respawn(master.GetBody().transform.position, master.GetBody().transform.rotation);
            }

            AddChatMessage($"{player.userName} is spawning as {body.GetDisplayName()}!");
        }
Пример #27
0
        // ReSharper disable once UnusedMember.Local
        private static void LogNetworkCommandsAndCheckPermissions(Console self, NetworkUser sender, string concommandName, List <string> userArgs)
        {
            StringBuilder s = new StringBuilder();

            userArgs.ForEach((str) => s.AppendLine(str));

            if (sender != null && sender.isLocalPlayer == false)
            {
                Log.Message(string.Format(Lang.NETWORKING_OTHERPLAYER_4, sender.userName, sender.id.value, concommandName, s.ToString()));
            }
            else if (Application.isBatchMode)
            {
                Log.Message(string.Format(Lang.NETWORKING_OTHERPLAYER_4, "Server", 0, concommandName, s.ToString()));
            }

            var canExecute = true;

            if (sender != null && !sender.isLocalPlayer && PermissionSystem.IsEnabled.Value)
            {
                canExecute = PermissionSystem.CanUserExecute(sender, concommandName, userArgs);
            }

            if (canExecute)
            {
                _origRunCmd(self, sender, concommandName, userArgs);
                ScrollConsoleDown();
            }
        }
 public void RespawnUser(NetworkUser user)
 {
     if (user?.master && CheckIfCanRespawn(user.master))
     {
         Stage.instance.RespawnCharacter(user.master);
     }
 }
Пример #29
0
        public void Deserialize(NetworkReader reader)
        {
            Util.LogSerialization(this, true);

            NetUser = reader.ReadGameObject().GetComponent <PlayerCharacterMasterController>().networkUser;
            Util.LogVariable(NetUser.userName, nameof(NetUser));
        }
Пример #30
0
        // method copied from RoR2.Inventory::GiveRandomItems
        private void BoostPlayerWithRandomItem(NetworkUser user)
        {
            if (!user || !user.master || !user.master.inventory)
            {
                return;
            }

            var inventory = user.master.inventory;

            try
            {
                WeightedSelection <List <PickupIndex> > weightedSelection = new WeightedSelection <List <PickupIndex> >(8);
                weightedSelection.AddChoice(Run.instance.availableTier1DropList, 100f);
                weightedSelection.AddChoice(Run.instance.availableTier2DropList, 20f);

                List <PickupIndex> list      = weightedSelection.Evaluate(UnityEngine.Random.value);
                PickupDef          pickupDef = PickupCatalog.GetPickupDef(list[UnityEngine.Random.Range(0, list.Count)]);
                inventory.GiveItem((pickupDef != null) ? pickupDef.itemIndex : ItemIndex.None, 1);

                ChatHelper.PlayerBoostedWithItem(user.userName, pickupDef.nameToken, pickupDef.baseColor);
            }
            catch (System.ArgumentException)
            {
            }
        }
        public void IgnoreNumberTypeDifferencesWithDefaultValue()
        {
            NetworkUser user = new NetworkUser
            {
                Firstname = "blub"
            };

            string json = JsonConvert.SerializeObject(user, Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore });

            Assert.AreEqual(@"{""firstName"":""blub""}", json);
        }
Пример #32
0
 private void UserLoop(TcpClient user)
 {
     try
     {
         Console.WriteLine("Connect " + user);
         var strRemote = user.GetStream();
         var netUser = new NetworkUser() { state = NetworkUserState.connected, userName = "" };
         clients.Add(user, netUser);
         BinaryFormatter bf = new BinaryFormatter();
         while (true)
         {
             bool breakExecute = false;
             var message = (CToSMessage)bf.Deserialize(strRemote);
             if (ValidateUserStateForClientMessage(user, message))
             {
                 Console.WriteLine("Receive message with type = {0}", message.type);
                 switch (message.type)
                 {
                     case CToSMessagesType.Login:
                         var loginMessage = message as CToSLoginRequest;
                         //TODO: Remove when I made registration
                         userStorage.AddUser(loginMessage.userName, loginMessage.password);
                         if (!userStorage.CheckUserInfoPairExist(loginMessage.userName, loginMessage.password))
                         {
                             var loginError = new SToCErrorInfo() { errorType = SToCErrorType.LoginFailed };
                             bf.Serialize(strRemote, loginError);
                         }
                         else
                         {
                             netUser.state = NetworkUserState.authorized;
                             netUser.userName = loginMessage.userName;
                             bf.Serialize(strRemote, new SToCMessage(SToCMessagesType.LoginAccepted));
                         }
                         break;
                     case CToSMessagesType.Logout:
                         netUser.state = NetworkUserState.connected;
                         break;
                     case CToSMessagesType.Disconnect:
                         netUser.state = NetworkUserState.disconnected;
                         bf.Serialize(strRemote, new SToCMessage(SToCMessagesType.Disconnect));
                         breakExecute = true;
                         break;
                     case CToSMessagesType.NotesSync:
                         var notesRequest = message as CToSNotesRequest;
                         switch (notesRequest.syncType)
                         {
                             case NotesSyncType.GetNotes:
                                 var notes = notesStorage.GetUserNotes(netUser.userName);
                                 bf.Serialize(strRemote, new SToCNotesContainer() { notes = notes, syncType = NotesSyncType.AddNotes });
                                 //bf.Serialize(strRemote, new SToCNotesContainer() { syncType = NotesSyncType.GetNotes });
                                 break;
                             default:
                                 if (notesRequest.syncType == NotesSyncType.AddNotes)
                                     notesStorage.AddNotesToUser(netUser.userName, notesRequest.notes);
                                 else if (notesRequest.syncType == NotesSyncType.ModifyNotes)
                                     notesStorage.ModifyNotesToUser(netUser.userName, notesRequest.notes);
                                 else
                                     notesStorage.RemoveNotesFromUser(netUser.userName, notesRequest.notes);
                                 var sameUsers = GetAllConnectionWithSameUserName(user);
                                 var response = new SToCNotesContainer() { notes = notesRequest.notes, syncType = notesRequest.syncType };
                                 foreach (var u in sameUsers)
                                     bf.Serialize(u.GetStream(), response);
                                 break;
                         }
                         break;
                 }
             }
             if (breakExecute)
                 break;
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
     finally
     {
         user.Close();// TODO: WTF?! Google it!
         clients.Remove(user);
         Thread.CurrentThread.Abort();
     }
 }