Example #1
0
        public void OnCapturePointOwnerChanged(FlagCapturePoint flagCapturePoint, Team ownerTeam)
        {
            this._capturePointOwners[flagCapturePoint.FlagIndex] = ownerTeam;
            Action <FlagCapturePoint, Team> ownerChangedEvent = this.OnCapturePointOwnerChangedEvent;

            if (ownerChangedEvent != null)
            {
                ownerChangedEvent(flagCapturePoint, ownerTeam);
            }
            if (this._myRepresentative == null || this._myRepresentative.MissionPeer.Team == null)
            {
                return;
            }
            MatrixFrame cameraFrame = Mission.Current.GetCameraFrame();
            Vec3        position    = cameraFrame.origin + cameraFrame.rotation.u;

            if (this._myRepresentative.MissionPeer.Team == ownerTeam)
            {
                MBSoundEvent.PlaySound(SoundEvent.GetEventIdFromString("event:/alerts/report/flag_captured"), position);
            }
            else
            {
                MBSoundEvent.PlaySound(SoundEvent.GetEventIdFromString("event:/alerts/report/flag_lost"), position);
            }
        }
Example #2
0
 public void CheckReinforcement(int numberOfTroops)
 {
     if (!this.IsInitialSpawnOver)
     {
         return;
     }
     for (int index = 0; index < 2; ++index)
     {
         int val1 = numberOfTroops;
         if (val1 > 0 && this._numberOfTroopsInQueueForReinforcement[index] > 0 && this._missionSides[index].TroopSpawningActive)
         {
             int number = Math.Min(MBMath.Floor((float)val1 * this.BattleSizeEffect), this._numberOfTroopsInQueueForReinforcement[index]);
             this._missionSides[index].SpawnTroops(number, true);
             InformationManager.AddQuickInformation(this._missionSides[index].IsPlayerSide ? GameTexts.FindText("str_new_reinforcements_have_arrived_for_ally_side") : GameTexts.FindText("str_new_reinforcements_have_arrived_for_enemy_side"));
             MatrixFrame cameraFrame = Mission.Current.GetCameraFrame();
             Vec3        position    = cameraFrame.origin + cameraFrame.rotation.u;
             MBSoundEvent.PlaySound(this._missionSides[index].IsPlayerSide ? SoundEvent.GetEventIdFromString("event:/alerts/report/reinforcements_ally") : SoundEvent.GetEventIdFromString("event:/alerts/report/reinforcements_enemy"), position);
             int num1 = Math.Min(val1, this._numberOfTroopsInQueueForReinforcement[index]);
             this._numberOfTroopsInQueueForReinforcement[index] -= num1;
             int num2 = num1 - number;
             this.GetActivePhaseForSide((BattleSideEnum)index).RemainingSpawnNumber += num2;
             Debug.Print("Side: " + (object)(BattleSideEnum)index, color: Debug.DebugColor.Green, debugFilter: 64UL);
             Debug.Print("NumberOfTroopsRemovedFromQueue: " + (object)num1, color: Debug.DebugColor.Green, debugFilter: 64UL);
             Debug.Print("NumberOfTroopsAddedToRemainingPool: " + (object)num2, color: Debug.DebugColor.Green, debugFilter: 64UL);
         }
     }
 }
Example #3
0
        private void HandleServerEventFormationWipedMessage(FormationWipedMessage message)
        {
            MatrixFrame cameraFrame = Mission.Current.GetCameraFrame();
            Vec3        position    = cameraFrame.origin + cameraFrame.rotation.u;

            MBSoundEvent.PlaySound(SoundEvent.GetEventIdFromString("event:/alerts/report/squad_wiped"), position);
        }
Example #4
0
 public void Execute(ReplyContext context, object config)
 {
     if (!string.IsNullOrEmpty(context.Args) && Agent.Main != null)
     {
         Mission.Current.MakeSound(SoundEvent.GetEventIdFromString(context.Args), Agent.Main.AgentVisuals.GetGlobalFrame().origin, false, true, Agent.Main.Index, -1);
     }
 }
        public void OnCapturePointOwnerChanged(FlagCapturePoint flagCapturePoint, Team ownerTeam)
        {
            this._capturePointOwners[flagCapturePoint.FlagIndex] = ownerTeam;
            Action <FlagCapturePoint, Team> ownerChangedEvent = this.OnCapturePointOwnerChangedEvent;

            if (ownerChangedEvent != null)
            {
                ownerChangedEvent(flagCapturePoint, ownerTeam);
            }
            if (ownerTeam != null && ownerTeam.Side == BattleSideEnum.Defender && ((double)this._remainingTimeForBellSoundToStop > 8.0 && flagCapturePoint == this._masterFlag))
            {
                this._bellSoundEvent.Stop();
                this._bellSoundEvent = (SoundEvent)null;
                this._remainingTimeForBellSoundToStop = float.MinValue;
                this._lastBellSoundPercentage        += 0.2f;
            }
            if (this._myRepresentative == null || this._myRepresentative.MissionPeer.Team == null)
            {
                return;
            }
            MatrixFrame cameraFrame = Mission.Current.GetCameraFrame();
            Vec3        position    = cameraFrame.origin + cameraFrame.rotation.u;

            if (this._myRepresentative.MissionPeer.Team == ownerTeam)
            {
                MBSoundEvent.PlaySound(SoundEvent.GetEventIdFromString("event:/alerts/report/flag_captured"), position);
            }
            else
            {
                MBSoundEvent.PlaySound(SoundEvent.GetEventIdFromString("event:/alerts/report/flag_lost"), position);
            }
        }
Example #6
0
 public static bool PlaySound(
     string soundPath,
     ref SoundEventParameter parameter,
     Vec3 position)
 {
     int  eventIdFromString = SoundEvent.GetEventIdFromString(soundPath);
     Vec3 vec3 = position;
     ref SoundEventParameter local1 = ref parameter;
        public static void Trigger(string particleEffect, string sound, MatrixFrame location, int relatedAgentIndex = -1)
        {
            if (!string.IsNullOrEmpty(particleEffect))
            {
                Mission.Current.Scene.CreateBurstParticle(
                    ParticleSystemManager.GetRuntimeIdByName(particleEffect),
                    location);
            }

            if (!string.IsNullOrEmpty(sound))
            {
                Mission.Current.MakeSound(SoundEvent.GetEventIdFromString(sound),
                                          location.origin, false, true, relatedAgentIndex, -1);
            }
        }
 public bool CheckRemove()
 {
     if (config.Duration.HasValue &&
         MBCommon.GetTime(MBCommon.TimeType.Mission) > config.Duration.Value + started)
     {
         Log.LogFeedEvent($"{config.Name} expired on {agent.Name}!");
         if (!string.IsNullOrEmpty(config.DeactivateParticleEffect))
         {
             Mission.Current.Scene.CreateBurstParticle(ParticleSystemManager.GetRuntimeIdByName(config.DeactivateParticleEffect), agent.AgentVisuals.GetGlobalFrame());
         }
         if (!string.IsNullOrEmpty(config.DeactivateSound))
         {
             Mission.Current.MakeSound(SoundEvent.GetEventIdFromString(config.DeactivateSound), agent.AgentVisuals.GetGlobalFrame().origin, false, true, agent.Index, -1);
         }
         Stop();
         return(true);
     }
     return(false);
 }
Example #9
0
        private void OnAgentWentOut(Agent agent, float startTimeInSeconds)
        {
            MissionTimer missionTimer = GameNetwork.IsClient ? MissionTimer.CreateSynchedTimerClient(startTimeInSeconds, 10f) : new MissionTimer(10f);

            if (GameNetwork.IsServer)
            {
                this._agentTimers.Add(agent, missionTimer);
                MissionPeer         missionPeer  = agent.MissionPeer;
                NetworkCommunicator communicator = missionPeer != null?missionPeer.GetNetworkPeer() : (NetworkCommunicator)null;

                if (communicator != null && !communicator.IsServerPeer)
                {
                    GameNetwork.BeginModuleEventAsServer(communicator);
                    GameNetwork.WriteMessage((GameNetworkMessage) new SetBoundariesState(true, missionTimer.GetStartTime().NumberOfTicks));
                    GameNetwork.EndModuleEventAsServer();
                }
            }
            if (this.Mission.MainAgent != agent)
            {
                return;
            }
            this._mainAgentLeaveTimer = missionTimer;
            Action <float, float> startTime = this.StartTime;

            if (startTime != null)
            {
                startTime(10f, 0.0f);
            }
            MatrixFrame cameraFrame = Mission.Current.GetCameraFrame();
            Vec3        position    = cameraFrame.origin + cameraFrame.rotation.u;

            if (Mission.Current.Mode != MissionMode.Battle)
            {
                return;
            }
            MBSoundEvent.PlaySound(SoundEvent.GetEventIdFromString("event:/alerts/report/out_of_map"), position);
        }
Example #10
0
        private void OnTeamScoresChanged()
        {
            if (GameNetwork.IsDedicatedServer || this._battleEndingNotificationGiven || (this._myRepresentative.MissionPeer.Team == null || this._myRepresentative.MissionPeer.Team.Side == BattleSideEnum.None))
            {
                return;
            }
            int         intValue    = MultiplayerOptions.OptionType.MinScoreToWinMatch.GetIntValue();
            float       num1        = (float)(intValue - this.ScoreboardComponent.GetRoundScore(this._myRepresentative.MissionPeer.Team.Side)) / (float)intValue;
            float       num2        = (float)(intValue - this.ScoreboardComponent.GetRoundScore(this._myRepresentative.MissionPeer.Team.Side.GetOppositeSide())) / (float)intValue;
            MatrixFrame cameraFrame = Mission.Current.GetCameraFrame();
            Vec3        position    = cameraFrame.origin + cameraFrame.rotation.u;

            if ((double)num1 <= 0.100000001490116 && (double)num2 > 0.100000001490116)
            {
                MBSoundEvent.PlaySound(SoundEvent.GetEventIdFromString("event:/alerts/report/battle_winning"), position);
                this._battleEndingNotificationGiven = true;
            }
            if ((double)num2 > 0.100000001490116 || (double)num1 <= 0.100000001490116)
            {
                return;
            }
            MBSoundEvent.PlaySound(SoundEvent.GetEventIdFromString("event:/alerts/report/battle_losing"), position);
            this._battleEndingNotificationGiven = true;
        }
        protected override void ExecuteInternal(ReplyContext context, object baseConfig,
                                                Action <string> onSuccess, Action <string> onFailure)
        {
            if (Mission.Current == null)
            {
                onFailure($"No mission is active!");
                return;
            }

            if (BLTBuffetModule.EffectsConfig.DisableEffectsInTournaments &&
                MissionHelpers.InTournament())
            {
                onFailure($"Not allowed during tournament!");
                return;
            }

            if (!Mission.Current.IsLoadingFinished ||
                Mission.Current.CurrentState != Mission.State.Continuing ||
                Mission.Current?.GetMissionBehaviour <TournamentFightMissionController>() != null && Mission.Current.Mode != MissionMode.Battle)
            {
                onFailure($"The mission has not started yet!");
                return;
            }

            if (Mission.Current.IsMissionEnding || Mission.Current.MissionResult?.BattleResolved == true)
            {
                onFailure($"The mission is ending!");
                return;
            }

            var effectsBehaviour = BLTEffectsBehaviour.Get();

            var config = (Config)baseConfig;

            bool GeneralAgentFilter(Agent agent)
            => agent.IsHuman && (!config.TargetOnFootOnly || agent.HasMount == false) && !effectsBehaviour.Contains(agent, config);

            var target = config.Target switch
            {
                Target.Player => Agent.Main,
                Target.AdoptedHero => Mission.Current.Agents.FirstOrDefault(a => a.IsAdoptedBy(context.UserName)),
                Target.Any => Mission.Current.Agents.Where(GeneralAgentFilter).Where(a => !a.IsAdopted()).SelectRandom(),
                Target.EnemyTeam => Mission.Current.Agents.Where(GeneralAgentFilter)
                .Where(a => a.Team?.IsValid == true &&
                       Mission.Current.PlayerTeam?.IsValid == true &&
                       !a.Team.IsFriendOf(Mission.Current.PlayerTeam) &&
                       !a.IsAdopted())
                .SelectRandom(),
                Target.PlayerTeam => Mission.Current.Agents.Where(GeneralAgentFilter)
                .Where(a => a.Team?.IsPlayerTeam == true && !a.IsAdopted())
                .SelectRandom(),
                Target.AllyTeam => Mission.Current.Agents.Where(GeneralAgentFilter)
                .Where(a => a.Team?.IsPlayerAlly == false && !a.IsAdopted())
                .SelectRandom(),
                _ => null
            };

            if (target == null || target.AgentVisuals == null)
            {
                onFailure($"Couldn't find the target!");
                return;
            }

            if (string.IsNullOrEmpty(config.Name))
            {
                onFailure($"CharacterEffect {context.Source} configuration error: Name is missing!");
                return;
            }

            if (effectsBehaviour.Contains(target, config))
            {
                onFailure($"{target.Name} already affected by {config.Name}!");
                return;
            }

            if (config.TargetOnFootOnly && target.HasMount)
            {
                onFailure($"{target.Name} is mounted so cannot be affected by {config.Name}!");
                return;
            }

            var effectState = effectsBehaviour.Add(target, config);

            foreach (var pfx in config.ParticleEffects ?? Enumerable.Empty <ParticleEffectDef>())
            {
                var pfxState = new CharacterEffectState.PfxState();
                switch (pfx.AttachPoint)
                {
                case ParticleEffectDef.AttachPointEnum.OnWeapon:
                    pfxState.weaponEffects = CreateWeaponEffects(target, pfx.Name);
                    break;

                case ParticleEffectDef.AttachPointEnum.OnHands:
                    pfxState.boneAttachments = CreateAgentEffects(target,
                                                                  pfx.Name,
                                                                  MatrixFrame.Identity,
                                                                  Game.Current.HumanMonster.MainHandItemBoneIndex,
                                                                  Game.Current.HumanMonster.OffHandItemBoneIndex);
                    break;

                case ParticleEffectDef.AttachPointEnum.OnHead:
                    pfxState.boneAttachments = CreateAgentEffects(target,
                                                                  pfx.Name,
                                                                  MatrixFrame.Identity.Strafe(0.1f),
                                                                  Game.Current.HumanMonster.HeadLookDirectionBoneIndex);
                    break;

                case ParticleEffectDef.AttachPointEnum.OnBody:
                    pfxState.boneAttachments = CreateAgentEffects(target, pfx.Name, MatrixFrame.Identity.Elevate(0.1f));
                    break;

                default:
                    Log.Error($"{config.Name}: No location specified for particle Id {pfx.Name} in CharacterEffect");
                    break;
                }
                effectState.state.Add(pfxState);
            }

            // if (config.Properties != null && target.AgentDrivenProperties != null)
            // {
            //     ApplyPropertyModifiers(target, config);
            // }

            // if (config.Light != null)
            // {
            //     effectState.light = CreateLight(target, config.Light.Radius, config.Light.Intensity, config.Light.ColorParsed);
            // }

            if (config.RemoveArmor)
            {
                foreach (var(_, index) in target.SpawnEquipment.YieldArmorSlots())
                {
                    target.SpawnEquipment[index] = EquipmentElement.Invalid;
                }
                target.UpdateSpawnEquipmentAndRefreshVisuals(target.SpawnEquipment);
            }

            if (!string.IsNullOrEmpty(config.ActivateParticleEffect))
            {
                Mission.Current.Scene.CreateBurstParticle(ParticleSystemManager.GetRuntimeIdByName(config.ActivateParticleEffect), target.AgentVisuals.GetGlobalFrame());
            }
            if (!string.IsNullOrEmpty(config.ActivateSound))
            {
                Mission.Current.MakeSound(SoundEvent.GetEventIdFromString(config.ActivateSound), target.AgentVisuals.GetGlobalFrame().origin, false, true, target.Index, -1);
            }

            Log.LogFeedEvent($"{config.Name} is active on {target.Name}!");

            onSuccess($"{config.Name} is active on {target.Name}!");
        }
        public void OnMoraleChanged(
            int attackerMorale,
            int defenderMorale,
            int[] capturePointRemainingMoraleGains)
        {
            float num1 = (float)attackerMorale / 360f;
            float num2 = (float)defenderMorale / 360f;

            if (this._myRepresentative?.MissionPeer.Team != null && this._myRepresentative.MissionPeer.Team.Side != BattleSideEnum.None)
            {
                if ((this._capturePointOwners[this._masterFlag.FlagIndex] == null || this._capturePointOwners[this._masterFlag.FlagIndex].Side != BattleSideEnum.Defender) && (double)this._remainingTimeForBellSoundToStop < 0.0)
                {
                    if ((double)num2 > (double)this._lastBellSoundPercentage)
                    {
                        this._lastBellSoundPercentage += 0.2f;
                    }
                    if ((double)num2 <= 0.400000005960464)
                    {
                        if ((double)this._lastBellSoundPercentage > 0.400000005960464)
                        {
                            this._remainingTimeForBellSoundToStop = float.MaxValue;
                            this._lastBellSoundPercentage         = 0.4f;
                        }
                    }
                    else if ((double)num2 <= 0.600000023841858)
                    {
                        if ((double)this._lastBellSoundPercentage > 0.600000023841858)
                        {
                            this._remainingTimeForBellSoundToStop = 8f;
                            this._lastBellSoundPercentage         = 0.6f;
                        }
                    }
                    else if ((double)num2 <= 0.800000011920929 && (double)this._lastBellSoundPercentage > 0.800000011920929)
                    {
                        this._remainingTimeForBellSoundToStop = 4f;
                        this._lastBellSoundPercentage         = 0.8f;
                    }
                    if ((double)this._remainingTimeForBellSoundToStop > 0.0)
                    {
                        switch (this._myRepresentative.MissionPeer.Team.Side)
                        {
                        case BattleSideEnum.Defender:
                            this._bellSoundEvent = SoundEvent.CreateEventFromString("event:/multiplayer/warning_bells_defender", this.Mission.Scene);
                            break;

                        case BattleSideEnum.Attacker:
                            this._bellSoundEvent = SoundEvent.CreateEventFromString("event:/multiplayer/warning_bells_attacker", this.Mission.Scene);
                            break;
                        }
                        MatrixFrame globalFrame = this._masterFlag.GameEntity.GetGlobalFrame();
                        this._bellSoundEvent.PlayInPosition(globalFrame.origin + globalFrame.rotation.u * 3f);
                    }
                }
                if (!this._battleEndingNotificationGiven || !this._battleEndingLateNotificationGiven)
                {
                    float       num3        = !this._battleEndingNotificationGiven ? 0.25f : 0.15f;
                    MatrixFrame cameraFrame = Mission.Current.GetCameraFrame();
                    Vec3        position    = cameraFrame.origin + cameraFrame.rotation.u;
                    if ((double)num1 <= (double)num3 && (double)num2 > (double)num3)
                    {
                        MBSoundEvent.PlaySound(SoundEvent.GetEventIdFromString(this._myRepresentative.MissionPeer.Team.Side == BattleSideEnum.Attacker ? "event:/alerts/report/battle_losing" : "event:/alerts/report/battle_winning"), position);
                        if (this._myRepresentative.MissionPeer.Team.Side == BattleSideEnum.Attacker)
                        {
                            MBSoundEvent.PlaySound(SoundEvent.GetEventIdFromString("event:/multiplayer/retreat_horn_attacker"), this._retreatHornPosition);
                        }
                        else if (this._myRepresentative.MissionPeer.Team.Side == BattleSideEnum.Defender)
                        {
                            MBSoundEvent.PlaySound(SoundEvent.GetEventIdFromString("event:/multiplayer/retreat_horn_defender"), this._retreatHornPosition);
                        }
                        if (this._battleEndingNotificationGiven)
                        {
                            this._battleEndingLateNotificationGiven = true;
                        }
                        this._battleEndingNotificationGiven = true;
                    }
                    if ((double)num2 <= (double)num3 && (double)num1 > (double)num3)
                    {
                        MBSoundEvent.PlaySound(SoundEvent.GetEventIdFromString(this._myRepresentative.MissionPeer.Team.Side == BattleSideEnum.Defender ? "event:/alerts/report/battle_losing" : "event:/alerts/report/battle_winning"), position);
                        if (this._battleEndingNotificationGiven)
                        {
                            this._battleEndingLateNotificationGiven = true;
                        }
                        this._battleEndingNotificationGiven = true;
                    }
                }
            }
            Action <BattleSideEnum, float> moraleChangedEvent1 = this.OnMoraleChangedEvent;

            if (moraleChangedEvent1 != null)
            {
                moraleChangedEvent1(BattleSideEnum.Attacker, num1);
            }
            Action <BattleSideEnum, float> moraleChangedEvent2 = this.OnMoraleChangedEvent;

            if (moraleChangedEvent2 != null)
            {
                moraleChangedEvent2(BattleSideEnum.Defender, num2);
            }
            Action <int[]> gainsChangedEvent = this.OnCapturePointRemainingMoraleGainsChangedEvent;

            if (gainsChangedEvent == null)
            {
                return;
            }
            gainsChangedEvent(capturePointRemainingMoraleGains);
        }
 protected override void GetSoundEventIndices()
 {
     this.MoveSoundIndex   = SoundEvent.GetEventIdFromString("event:/mission/siege/ballista/move");
     this.ReloadSoundIndex = SoundEvent.GetEventIdFromString("event:/mission/siege/ballista/reload");
 }
Example #14
0
        private void ConstructListFromXML(string filePath)
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(filePath);
            try
            {
                foreach (XmlNode node in doc.DocumentElement)
                {
                    if (node.NodeType == XmlNodeType.Comment)
                    {
                        continue;
                    }

                    SpawnData dat = new SpawnData();

                    dat.PartyTemplate = (PartyTemplateObject)MBObjectManager.Instance.ReadObjectReferenceFromXml("party_template", typeof(PartyTemplateObject), node);

                    if (node.Attributes["party_template_prisoners"] != null)
                    {
                        dat.PartyTemplatePrisoner = (PartyTemplateObject)MBObjectManager.Instance.ReadObjectReferenceFromXml("party_template_prisoners", typeof(PartyTemplateObject), node);
                    }

                    if (node.Attributes["spawn_clan"] == null)
                    {
                        dat.SpawnClan = (Clan)MBObjectManager.Instance.ReadObjectReferenceFromXml("bandit_clan", typeof(Clan), node);
                    }
                    else
                    {
                        dat.SpawnClan = (Clan)MBObjectManager.Instance.ReadObjectReferenceFromXml("spawn_clan", typeof(Clan), node);
                    }

                    //have bannerlord read attributes

                    int    i = 0;
                    string s = "overriden_spawn_clan";
                    while (true)
                    {
                        string s1 = s + "_" + i.ToString();
                        if (node.Attributes[s1] == null || node.Attributes[s1].InnerText == "")
                        {
                            break;
                        }
                        else
                        {
                            dat.OverridenSpawnClan.Add((Clan)MBObjectManager.Instance.ReadObjectReferenceFromXml(s1, typeof(Clan), node));
                        }
                        i++;
                    }

                    string sc = "overriden_spawn_kingdom";
                    while (true)
                    {
                        string s1 = sc + "_" + i.ToString();
                        if (node.Attributes[s1] == null || node.Attributes[s1].InnerText == "")
                        {
                            break;
                        }
                        else
                        {
                            dat.OverridenSpawnKingdoms.Add((Kingdom)MBObjectManager.Instance.ReadObjectReferenceFromXml(s1, typeof(Kingdom), node));
                        }
                        i++;
                    }

                    int    j  = 0;
                    string st = "overriden_spawn_culture";
                    while (true)
                    {
                        string s1 = st + "_" + j.ToString();
                        if (node.Attributes[s1] == null || node.Attributes[s1].InnerText == "")
                        {
                            break;
                        }
                        else
                        {
                            dat.OverridenSpawnCultures.Add(((CultureObject)MBObjectManager.Instance.ReadObjectReferenceFromXml(s1, typeof(CultureObject), node)).GetCultureCode());
                        }
                        j++;
                    }

                    j  = 0;
                    st = "overriden_spawn_settlement";
                    while (true)
                    {
                        string s1 = st + "_" + j.ToString();
                        if (node.Attributes[s1] == null || node.Attributes[s1].InnerText == "")
                        {
                            break;
                        }
                        else
                        {
                            dat.OverridenSpawnSettlements.Add(((Settlement)MBObjectManager.Instance.ReadObjectReferenceFromXml(s1, typeof(Settlement), node)));
                        }
                        j++;
                    }

                    //get elements
                    dat.MaximumOnMap = node["MaximumOnMap"] == null? 0 : int.Parse(node["MaximumOnMap"].InnerText);
                    if (dat.MaximumOnMap < 1)
                    {
                        throw new Exception("the node 'MaximumOnMap' cannot be less than 1!");
                    }

                    dat.InheritClanFromSettlement = node["GetClanFromSettlement"] == null ? false : bool.Parse(node["GetClanFromSettlement"].InnerText);
                    dat.PartyType             = node["PartyType"] == null ? Track.PartyTypeEnum.Bandit : StringToPartyTypeEnumIfInvalidBandit(node["PartyType"].InnerText);
                    dat.ChanceOfSpawn         = node["ChanceOfSpawn"] == null? 1 : float.Parse(node["ChanceOfSpawn"].InnerText);
                    dat.Name                  = node["Name"] == null ? "Unnamed" : node["Name"].InnerText;
                    dat.ChanceInverseConstant = node["ChanceInverseConstant"] == null? 0 : float.Parse(node["ChanceInverseConstant"].InnerText);
                    dat.RepeatSpawnRolls      = node["RepeatSpawnRolls"] == null? 1 : int.Parse(node["RepeatSpawnRolls"].InnerText);

                    dat.PatrolAroundSpawn             = node["PatrolAroundSpawn"] == null ? false : bool.Parse(node["PatrolAroundSpawn"].InnerText);
                    dat.MinimumNumberOfDaysUntilSpawn = node["MinimumNumberOfDaysUntilSpawn"] == null ? -1 : int.Parse(node["MinimumNumberOfDaysUntilSpawn"].InnerText);

                    dat.AttackClosestIfIdleForADay = node["AttackClosestIfIdleForADay"] == null ? true : bool.Parse(node["AttackClosestIfIdleForADay"].InnerText);

                    dat.DynamicSpawnChancePeriod = node["DynamicSpawnChancePeriod"] == null ? 0 :
                                                   (float.Parse(node["DynamicSpawnChancePeriod"].InnerText) > 1? float.Parse(node["DynamicSpawnChancePeriod"].InnerText) : 0);

                    dat.DynamicSpawnChanceEffect = node["DynamicSpawnChanceEffect"] == null ? 0 :
                                                   (MathF.Clamp(float.Parse(node["DynamicSpawnChanceEffect"].InnerText), 0, 1));

                    //try spawn at list creation
                    if (node["TrySpawnAt"] != null && node["TrySpawnAt"].InnerText != "")
                    {
                        dat.TrySpawnAtList = ConstructTrySettlementList(node["TrySpawnAt"].InnerText);
                    }

                    //message
                    string msg   = node["SpawnMessage"] == null? "" : node["SpawnMessage"].InnerText;
                    string color = node["SpawnMessageColor"] == null ? "" : node["SpawnMessageColor"].InnerText;

                    if (msg != "")
                    {
                        if (color == "")
                        {
                            dat.spawnMessage = new InformationMessage(msg, Color.Black);
                        }
                        else
                        {
                            Color c = UX.GetMessageColour(color) == "" ? (color[0] == '#'? Color.ConvertStringToColor(color) : Color.Black) : Color.ConvertStringToColor(UX.GetMessageColour(color));
                            dat.spawnMessage = new InformationMessage(msg, c);
                        }
                    }

                    // sound event
                    dat.SoundEvent = node["SpawnSound"] == null ? -1 : SoundEvent.GetEventIdFromString(node["SpawnSound"].InnerText);

                    //inquiry message (message box with options)
                    string inqTitle           = node["SpawnMessageBoxTitle"] == null ? "" : node["SpawnMessageBoxTitle"].InnerText;
                    string inqText            = node["SpawnMessageBoxText"] == null ? "" : node["SpawnMessageBoxText"].InnerText;
                    string inqAffirmativeText = node["SpawnMessageBoxButton"] == null ? "Ok" : node["SpawnMessageBoxButton"].InnerText;

                    if (inqText != "")
                    {
                        dat.inquiryMessage = new InquiryData(inqTitle, inqText, true, false, inqAffirmativeText, "", null, null);
                        dat.inquiryPause   = node["SpawnMessageBoxPause"] == null ? false : bool.Parse(node["SpawnMessageBoxPause"].InnerText);
                    }

                    //death message
                    string deathMsg   = node["DeathMessage"] == null ? "" : node["DeathMessage"].InnerText;
                    string deathColor = node["DeathMessage"] == null ? "" : node["DeathMessageColor"].InnerText;

                    if (deathMsg != "")
                    {
                        if (deathColor == "")
                        {
                            dat.deathMessage = new InformationMessage(deathMsg, Color.Black);
                        }
                        else
                        {
                            Color c = UX.GetMessageColour(deathColor) == "" ? (deathColor[0] == '#' ? Color.ConvertStringToColor(deathColor) : Color.Black) : Color.ConvertStringToColor(UX.GetMessageColour(deathColor));
                            dat.deathMessage = new InformationMessage(deathMsg, c);
                        }
                    }

                    //handle extra linear speed.
                    float extraSpeed = float.MinValue;
                    if (node["ExtraLinearSpeed"] != null)
                    {
                        if (!float.TryParse(node["ExtraLinearSpeed"].InnerText, out extraSpeed))
                        {
                            throw new Exception("ExtraLinearSpeed must be a float value! ");
                        }
                        Main.customSpeedModel.RegisterPartyExtraSpeed(dat.PartyTemplate.StringId, extraSpeed);
                    }

                    //handle base speed override
                    float baseSpeedOverride = float.MinValue;
                    if (node["BaseSpeedOverride"] != null)
                    {
                        if (!float.TryParse(node["BaseSpeedOverride"].InnerText, out baseSpeedOverride))
                        {
                            throw new Exception("BaseSpeedOverride must be a float value! ");
                        }
                        Main.customSpeedModel.RegisterPartyBaseSpeed(dat.PartyTemplate.StringId, baseSpeedOverride);
                    }
                    else
                    {
                        Main.customSpeedModel.RegisterPartyBaseSpeed(dat.PartyTemplate.StringId, float.MinValue);
                    }

                    //minimum devestation override
                    float minimumDevestationToSpawnOverride = 0;
                    if (node["MinimumDevestationToSpawn"] != null)
                    {
                        if (!float.TryParse(node["MinimumDevestationToSpawn"].InnerText, out minimumDevestationToSpawnOverride))
                        {
                            throw new Exception("MinimumDevestationToSpawn must be a float value!");
                        }
                        dat.MinimumDevestationToSpawn = minimumDevestationToSpawnOverride;
                    }

                    //devestation linear multiplier
                    float devestationLinearMultiplierOverride = 0;
                    if (node["MinimumDevestationToSpawn"] != null)
                    {
                        if (!float.TryParse(node["DevestationLinearMultiplier"].InnerText, out devestationLinearMultiplierOverride))
                        {
                            throw new Exception("DevestationLinearMultiplier must be a float value!");
                        }
                        dat.DevestationLinearMultiplier = devestationLinearMultiplierOverride;
                    }

                    //patrol around closest lest interrupted and switch
                    if (node["PatrolAroundClosestLestInterruptedAndSwitch"] != null)
                    {
                        bool val = false;
                        if (!bool.TryParse(node["PatrolAroundClosestLestInterruptedAndSwitch"].InnerText, out val))
                        {
                            break;
                        }
                        if (!val)
                        {
                            break;
                        }
                        XmlNode innerNode = node["PatrolAroundClosestLestInterruptedAndSwitch"];
                        float   minDays   = 0;
                        float   maxDays   = 10;
                        List <SpawnSettlementType> TryPatrolAround = new List <SpawnSettlementType>();
                        try
                        {
                            if (!float.TryParse(innerNode.Attributes["min_stable_days"].InnerText, out minDays))
                            {
                                throw new Exception("min_stable_days must be a float value!");
                            }
                            if (!float.TryParse(innerNode.Attributes["max_stable_days"].InnerText, out maxDays))
                            {
                                throw new Exception("max_stable_days must be a float value!");
                            }
                            if (innerNode.Attributes["try_patrol_around"] != null && innerNode.Attributes["try_patrol_around"].InnerText != "")
                            {
                                TryPatrolAround = ConstructTrySettlementList(innerNode.Attributes["try_patrol_around"].InnerText);
                            }
                        }catch
                        {
                            throw new Exception("not all attributes in PatrolAroundClosestLestInterruptedAndSwitch were filled properly!");
                        }
                        dat.PatrolAroundClosestLestInterruptedAndSwitch =
                            new AI.PatrolAroundClosestLestInterruptedAndSwitchBehaviour.PatrolAroundClosestLestInterruptedAndSwitchBehaviourData(null, minDays, maxDays, TryPatrolAround);
                    }

                    //min max party speed modifiers
                    float minSpeed = float.MinValue;
                    if (node["MinimumFinalSpeed"] != null)
                    {
                        if (!float.TryParse(node["MinimumFinalSpeed"].InnerText, out minSpeed))
                        {
                            throw new Exception("MinimumFinalSpeed must be a float value! ");
                        }
                        Main.customSpeedModel.RegisterPartyMinimumSpeed(dat.PartyTemplate.StringId, minSpeed);
                    }

                    float maxSpeed = float.MinValue;
                    if (node["MaximumFinalSpeed"] != null)
                    {
                        if (!float.TryParse(node["MaximumFinalSpeed"].InnerText, out maxSpeed))
                        {
                            throw new Exception("MaximumFinalSpeed must be a float value! ");
                        }
                        Main.customSpeedModel.RegisterPartyMaximumSpeed(dat.PartyTemplate.StringId, maxSpeed);
                    }

                    //Spawn along with
                    int    k   = 0;
                    string str = "spawn_along_with";
                    while (true)
                    {
                        string s1 = str + "_" + k.ToString();
                        if (node.Attributes[s1] == null || node.Attributes[s1].InnerText == "")
                        {
                            break;
                        }
                        else
                        {
                            PartyTemplateObject pt = (PartyTemplateObject)MBObjectManager.Instance.ReadObjectReferenceFromXml(s1, typeof(PartyTemplateObject), node);
                            dat.SpawnAlongWith.Add(new AccompanyingParty(pt, NameSignifierData.Instance.GetPartyNameFromID(pt.StringId),
                                                                         NameSignifierData.Instance.GetPartyFollowBehaviourFlagFromID(pt.StringId)));
                            Main.customSpeedModel.RegisterPartyExtraSpeed(pt.StringId, NameSignifierData.Instance.GetSpeedModifierFromID(pt.StringId));
                            Main.customSpeedModel.RegisterPartyBaseSpeed(pt.StringId, NameSignifierData.Instance.GetBaseSpeedModifierOverrideFromID(pt.StringId));
                            if (minSpeed != float.MinValue)
                            {
                                Main.customSpeedModel.RegisterPartyMinimumSpeed(pt.StringId, minSpeed);
                            }
                            if (maxSpeed != float.MinValue)
                            {
                                Main.customSpeedModel.RegisterPartyMaximumSpeed(pt.StringId, maxSpeed);
                            }
                        }
                        k++;
                    }

                    data.Add(dat);
                    if (!partyIDtoData.ContainsKey(dat.PartyTemplate.StringId)) //TODO add way to alert modder that he should use one party template for one AI
                    {
                        partyIDtoData.Add(dat.PartyTemplate.StringId, dat);
                    }
                }
            }
            catch (Exception e)
            {
                ErrorHandler.HandleException(e, "Spawn Data Parsing of " + filePath);
            }
        }
Example #15
0
 public override void OnAgentRemoved(
     Agent affectedAgent,
     Agent affectorAgent,
     AgentState agentState,
     KillingBlow blow)
 {
     base.OnAgentRemoved(affectedAgent, affectorAgent, agentState, blow);
     if (this.UseGold() && affectorAgent != null && (affectedAgent != null && affectedAgent.IsHuman) && (blow.DamageType != DamageTypes.Invalid && (agentState == AgentState.Unconscious || agentState == AgentState.Killed)))
     {
         Agent.Hitter assistingHitter = affectedAgent.GetAssistingHitter(affectorAgent.MissionPeer);
         MultiplayerClassDivisions.MPHeroClass classForCharacter = MultiplayerClassDivisions.GetMPHeroClassForCharacter(affectedAgent.Character);
         if (affectorAgent.MissionPeer != null && affectorAgent.MissionPeer.Representative is FlagDominationMissionRepresentative representative10)
         {
             int gainsFromKillData = representative10.GetGoldGainsFromKillData(MPPerkObject.GetPerkHandler(affectorAgent.MissionPeer), MPPerkObject.GetPerkHandler(assistingHitter?.HitterPeer), classForCharacter, false);
             if (gainsFromKillData > 0)
             {
                 this.ChangeCurrentGoldForPeer(affectorAgent.MissionPeer, representative10.Gold + gainsFromKillData);
             }
         }
         if (assistingHitter?.HitterPeer != null && !assistingHitter.IsFriendlyHit && assistingHitter.HitterPeer.Representative is FlagDominationMissionRepresentative representative11)
         {
             int gainsFromKillData = representative11.GetGoldGainsFromKillData(MPPerkObject.GetPerkHandler(affectorAgent.MissionPeer), MPPerkObject.GetPerkHandler(assistingHitter.HitterPeer), classForCharacter, false);
             if (gainsFromKillData > 0)
             {
                 this.ChangeCurrentGoldForPeer(assistingHitter.HitterPeer, representative11.Gold + gainsFromKillData);
             }
         }
         if (affectedAgent.MissionPeer?.Team != null)
         {
             IEnumerable <(MissionPeer, int)> goldRewardsOnDeath = MPPerkObject.GetPerkHandler(affectedAgent.MissionPeer)?.GetTeamGoldRewardsOnDeath();
             if (goldRewardsOnDeath != null)
             {
                 foreach ((MissionPeer peer6, int baseAmount6) in goldRewardsOnDeath)
                 {
                     if (baseAmount6 > 0 && peer6?.Representative is FlagDominationMissionRepresentative representative12)
                     {
                         int local_11 = representative12.GetGoldGainsFromAllyDeathReward(baseAmount6);
                         if (local_11 > 0)
                         {
                             this.ChangeCurrentGoldForPeer(peer6, representative12.Gold + local_11);
                         }
                     }
                 }
             }
         }
     }
     if (affectedAgent.IsPlayerControlled)
     {
         affectedAgent.MissionPeer.GetComponent <FlagDominationMissionRepresentative>().UpdateSelectedClassServer((Agent)null);
     }
     else
     {
         if (MultiplayerOptions.OptionType.NumberOfBotsPerFormation.GetIntValue() <= 0 || this.WarmupComponent != null && this.WarmupComponent.IsInWarmup || (affectedAgent.IsMount || affectedAgent.OwningAgentMissionPeer == null || (affectedAgent.Formation == null || affectedAgent.Formation.CountOfUnits != 1)))
         {
             return;
         }
         if (!GameNetwork.IsDedicatedServer)
         {
             MatrixFrame cameraFrame = Mission.Current.GetCameraFrame();
             Vec3        position    = cameraFrame.origin + cameraFrame.rotation.u;
             MBSoundEvent.PlaySound(SoundEvent.GetEventIdFromString("event:/alerts/report/squad_wiped"), position);
         }
         GameNetwork.BeginBroadcastModuleEvent();
         GameNetwork.WriteMessage((GameNetworkMessage) new FormationWipedMessage());
         GameNetwork.EndBroadcastModuleEvent(GameNetwork.EventBroadcastFlags.ExcludeOtherTeamPlayers, affectedAgent.OwningAgentMissionPeer.GetNetworkPeer());
     }
 }