Exemplo n.º 1
0
        public MonsterEvent(XElement element)
            : base(element)
        {
            characterFile = ToolBox.GetAttributeString(element, "characterfile", "");

            minAmount = ToolBox.GetAttributeInt(element, "minamount", 1);
            maxAmount = Math.Max(ToolBox.GetAttributeInt(element, "maxamount", 1), minAmount);

            var spawnPosTypeStr = ToolBox.GetAttributeString(element, "spawntype", "");

            if (string.IsNullOrWhiteSpace(spawnPosTypeStr) ||
                !Enum.TryParse <Level.PositionType>(spawnPosTypeStr, true, out spawnPosType))
            {
                spawnPosType = Level.PositionType.MainPath;
            }

            spawnDeep = ToolBox.GetAttributeBool(element, "spawndeep", false);

            if (GameMain.NetworkMember != null)
            {
                List <string> monsterNames = GameMain.NetworkMember.monsterEnabled.Keys.ToList();
                string        tryKey       = monsterNames.Find(s => characterFile.ToLower().Contains(s.ToLower()));
                if (!string.IsNullOrWhiteSpace(tryKey))
                {
                    if (!GameMain.NetworkMember.monsterEnabled[tryKey])
                    {
                        disallowed = true;                                                 //spawn was disallowed by host
                    }
                }
            }
        }
Exemplo n.º 2
0
        public BackgroundCreaturePrefab(XElement element)
        {
            Speed = ToolBox.GetAttributeFloat(element, "speed", 1.0f);

            WanderAmount = ToolBox.GetAttributeFloat(element, "wanderamount", 0.0f);

            WanderZAmount = ToolBox.GetAttributeFloat(element, "wanderzamount", 0.0f);

            SwarmMin = ToolBox.GetAttributeInt(element, "swarmmin", 1);
            SwarmMax = ToolBox.GetAttributeInt(element, "swarmmax", 1);

            SwarmRadius = ToolBox.GetAttributeFloat(element, "swarmradius", 200.0f);

            DisableRotation = ToolBox.GetAttributeBool(element, "disablerotation", false);

            foreach (XElement subElement in element.Elements())
            {
                if (subElement.Name.ToString().ToLowerInvariant() != "sprite")
                {
                    continue;
                }

                Sprite = new Sprite(subElement);
                break;
            }
        }
Exemplo n.º 3
0
        private Order(XElement orderElement)
        {
            Name      = ToolBox.GetAttributeString(orderElement, "name", "Name not found");
            DoingText = ToolBox.GetAttributeString(orderElement, "doingtext", "");

            string targetItemName = ToolBox.GetAttributeString(orderElement, "targetitemtype", "");

            if (!string.IsNullOrWhiteSpace(targetItemName))
            {
                try
                {
                    ItemComponentType = Type.GetType("Barotrauma.Items.Components." + targetItemName, true, true);
                }

                catch (Exception e)
                {
                    DebugConsole.ThrowError("Error in " + ConfigFile + ", item component type " + targetItemName + " not found", e);
                }
            }

            ItemName = ToolBox.GetAttributeString(orderElement, "targetitemname", "");

            Color = new Color(ToolBox.GetAttributeVector4(orderElement, "color", new Vector4(1.0f, 1.0f, 1.0f, 1.0f)));

            UseController = ToolBox.GetAttributeBool(orderElement, "usecontroller", false);

            string optionStr = ToolBox.GetAttributeString(orderElement, "options", "");

            if (string.IsNullOrWhiteSpace(optionStr))
            {
                Options = new string[0];
            }
            else
            {
                Options = optionStr.Split(',');

                for (int i = 0; i < Options.Length; i++)
                {
                    Options[i] = Options[i].Trim();
                }
            }



            foreach (XElement subElement in orderElement.Elements())
            {
                if (subElement.Name.ToString().ToLowerInvariant() != "sprite")
                {
                    continue;
                }
                SymbolSprite = new Sprite(subElement);
                break;
            }
        }
Exemplo n.º 4
0
        public Explosion(XElement element)
        {
            attack = new Attack(element);

            force = ToolBox.GetAttributeFloat(element, "force", 0.0f);

            sparks    = ToolBox.GetAttributeBool(element, "sparks", true);
            shockwave = ToolBox.GetAttributeBool(element, "shockwave", true);
            flames    = ToolBox.GetAttributeBool(element, "flames", true);
            smoke     = ToolBox.GetAttributeBool(element, "smoke", true);

            CameraShake = ToolBox.GetAttributeFloat(element, "camerashake", attack.Range * 0.1f);
        }
Exemplo n.º 5
0
        private void InitializeJobItem(Character character, WayPoint spawnPoint, XElement itemElement, Item parentItem = null)
        {
            string itemName = ToolBox.GetAttributeString(itemElement, "name", "");

            ItemPrefab itemPrefab = ItemPrefab.list.Find(ip => ip.Name == itemName) as ItemPrefab;

            if (itemPrefab == null)
            {
                DebugConsole.ThrowError("Tried to spawn \"" + Name + "\" with the item \"" + itemName + "\". Matching item prefab not found.");
                return;
            }

            Item item = new Item(itemPrefab, character.Position, null);

            if (GameMain.Server != null && Entity.Spawner != null)
            {
                Entity.Spawner.CreateNetworkEvent(item, false);
            }

            if (ToolBox.GetAttributeBool(itemElement, "equip", false))
            {
                List <InvSlotType> allowedSlots = new List <InvSlotType>(item.AllowedSlots);
                allowedSlots.Remove(InvSlotType.Any);

                character.Inventory.TryPutItem(item, null, allowedSlots);
            }
            else
            {
                character.Inventory.TryPutItem(item, null, item.AllowedSlots);
            }

            if (item.Prefab.Name == "ID Card" && spawnPoint != null)
            {
                foreach (string s in spawnPoint.IdCardTags)
                {
                    item.AddTag(s);
                }
            }

            if (parentItem != null)
            {
                parentItem.Combine(item);
            }

            foreach (XElement childItemElement in itemElement.Elements())
            {
                InitializeJobItem(character, spawnPoint, childItemElement, item);
            }
        }
Exemplo n.º 6
0
        public BackgroundSpritePrefab(XElement element)
        {
            string alignmentStr = ToolBox.GetAttributeString(element, "alignment", "");

            if (string.IsNullOrEmpty(alignmentStr) || !Enum.TryParse(alignmentStr, out Alignment))
            {
                Alignment = Alignment.Top | Alignment.Bottom | Alignment.Left | Alignment.Right;
            }

            Commonness = ToolBox.GetAttributeInt(element, "commonness", 1);

            SpawnOnWalls = ToolBox.GetAttributeBool(element, "spawnonwalls", true);

            Scale.X = ToolBox.GetAttributeFloat(element, "minsize", 1.0f);
            Scale.Y = ToolBox.GetAttributeFloat(element, "maxsize", 1.0f);

            DepthRange = ToolBox.GetAttributeVector2(element, "depthrange", new Vector2(0.0f, 1.0f));

            AlignWithSurface = ToolBox.GetAttributeBool(element, "alignwithsurface", false);

            RandomRotation   = ToolBox.GetAttributeVector2(element, "randomrotation", Vector2.Zero);
            RandomRotation.X = MathHelper.ToRadians(RandomRotation.X);
            RandomRotation.Y = MathHelper.ToRadians(RandomRotation.Y);

            SwingAmount = MathHelper.ToRadians(ToolBox.GetAttributeFloat(element, "swingamount", 0.0f));

            OverrideCommonness = new Dictionary <string, int>();

            foreach (XElement subElement in element.Elements())
            {
                switch (subElement.Name.ToString().ToLowerInvariant())
                {
                case "sprite":
                    Sprite = new Sprite(subElement);
                    break;

                case "overridecommonness":
                    string levelType = ToolBox.GetAttributeString(subElement, "leveltype", "");
                    if (!OverrideCommonness.ContainsKey(levelType))
                    {
                        OverrideCommonness.Add(levelType, ToolBox.GetAttributeInt(subElement, "commonness", 1));
                    }
                    break;
                }
            }
        }
Exemplo n.º 7
0
        public CharacterInfo(XElement element)
        {
            Name = ToolBox.GetAttributeString(element, "name", "unnamed");

            string genderStr = ToolBox.GetAttributeString(element, "gender", "male").ToLowerInvariant();

            gender = (genderStr == "m") ? Gender.Male : Gender.Female;

            File            = ToolBox.GetAttributeString(element, "file", "");
            Salary          = ToolBox.GetAttributeInt(element, "salary", 1000);
            headSpriteId    = ToolBox.GetAttributeInt(element, "headspriteid", 1);
            StartItemsGiven = ToolBox.GetAttributeBool(element, "startitemsgiven", false);

            int hullId = ToolBox.GetAttributeInt(element, "hull", -1);

            if (hullId > 0 && hullId <= ushort.MaxValue)
            {
                this.HullID = (ushort)hullId;
            }

            pickedItems = new List <ushort>();

            string pickedItemString = ToolBox.GetAttributeString(element, "items", "");

            if (!string.IsNullOrEmpty(pickedItemString))
            {
                string[] itemIds = pickedItemString.Split(',');
                foreach (string s in itemIds)
                {
                    pickedItems.Add((ushort)int.Parse(s));
                }
            }

            foreach (XElement subElement in element.Elements())
            {
                if (subElement.Name.ToString().ToLowerInvariant() != "job")
                {
                    continue;
                }

                Job = new Job(subElement);
                break;
            }
        }
Exemplo n.º 8
0
        public JobPrefab(XElement element)
        {
            Name = ToolBox.GetAttributeString(element, "name", "name not found");

            Description = ToolBox.GetAttributeString(element, "description", "");

            MinNumber = ToolBox.GetAttributeInt(element, "minnumber", 0);
            MaxNumber = ToolBox.GetAttributeInt(element, "maxnumber", 10);

            Commonness = ToolBox.GetAttributeInt(element, "commonness", 10);

            AllowAlways = ToolBox.GetAttributeBool(element, "allowalways", false);

            ItemNames = new List <string>();

            Skills = new List <SkillPrefab>();

            foreach (XElement subElement in element.Elements())
            {
                switch (subElement.Name.ToString().ToLowerInvariant())
                {
                case "items":
                    Items = subElement;
                    foreach (XElement itemElement in subElement.Elements())
                    {
                        string itemName = ToolBox.GetAttributeString(itemElement, "name", "");
                        if (!string.IsNullOrWhiteSpace(itemName))
                        {
                            ItemNames.Add(itemName);
                        }
                    }
                    break;

                case "skills":
                    foreach (XElement skillElement in subElement.Elements())
                    {
                        Skills.Add(new SkillPrefab(skillElement));
                    }
                    break;
                }
            }

            Skills.Sort((x, y) => y.LevelRange.X.CompareTo(x.LevelRange.X));
        }
Exemplo n.º 9
0
        public EnemyAIController(Character c, string file) : base(c)
        {
            targetMemories = new Dictionary <AITarget, AITargetMemory>();

            XDocument doc = ToolBox.TryLoadXml(file);

            if (doc == null || doc.Root == null)
            {
                return;
            }

            XElement aiElement = doc.Root.Element("ai");

            if (aiElement == null)
            {
                return;
            }

            attackRooms     = ToolBox.GetAttributeFloat(aiElement, 0.0f, "attackrooms", "attackpriorityrooms") / 100.0f;
            attackHumans    = ToolBox.GetAttributeFloat(aiElement, 0.0f, "attackhumans", "attackpriorityhumans") / 100.0f;
            attackWeaker    = ToolBox.GetAttributeFloat(aiElement, 0.0f, "attackweaker", "attackpriorityweaker") / 100.0f;
            attackStronger  = ToolBox.GetAttributeFloat(aiElement, 0.0f, "attackstronger", "attackprioritystronger") / 100.0f;
            eatDeadPriority = ToolBox.GetAttributeFloat(aiElement, "eatpriority", 0.0f) / 100.0f;

            combatStrength = ToolBox.GetAttributeFloat(aiElement, "combatstrength", 1.0f);

            attackCoolDown = ToolBox.GetAttributeFloat(aiElement, "attackcooldown", 5.0f);

            sight   = ToolBox.GetAttributeFloat(aiElement, "sight", 0.0f);
            hearing = ToolBox.GetAttributeFloat(aiElement, "hearing", 0.0f);

            attackWhenProvoked = ToolBox.GetAttributeBool(aiElement, "attackwhenprovoked", false);

            fleeHealthThreshold = ToolBox.GetAttributeFloat(aiElement, "fleehealththreshold", 0.0f);

            attachToWalls = ToolBox.GetAttributeBool(aiElement, "attachtowalls", false);

            outsideSteering = new SteeringManager(this);
            insideSteering  = new IndoorsSteeringManager(this, false);

            steeringManager = outsideSteering;

            state = AIState.None;
        }
Exemplo n.º 10
0
        public void StartServer()
        {
            XDocument doc = ToolBox.TryLoadXml(GameServer.SettingsFile);

            if (doc == null)
            {
                DebugConsole.ThrowError("File \"" + GameServer.SettingsFile + "\" not found. Starting the server with default settings.");
                Server = new GameServer("Server", 14242, false, "", false, 10);
                return;
            }

            Server = new GameServer(
                ToolBox.GetAttributeString(doc.Root, "name", "Server"),
                ToolBox.GetAttributeInt(doc.Root, "port", 14242),
                ToolBox.GetAttributeBool(doc.Root, "public", false),
                ToolBox.GetAttributeString(doc.Root, "password", ""),
                ToolBox.GetAttributeBool(doc.Root, "enableupnp", false),
                ToolBox.GetAttributeInt(doc.Root, "maxplayers", 10));
        }
Exemplo n.º 11
0
        public void Load(string filePath)
        {
            XDocument doc = ToolBox.TryLoadXml(filePath);

            if (doc == null)
            {
                DebugConsole.ThrowError("No config file found");

                MasterServerUrl = "";

                SelectedContentPackage = ContentPackage.list.Any() ? ContentPackage.list[0] : new ContentPackage("");

                return;
            }

            MasterServerUrl = ToolBox.GetAttributeString(doc.Root, "masterserverurl", "");

            AutoCheckUpdates = ToolBox.GetAttributeBool(doc.Root, "autocheckupdates", true);
            WasGameUpdated   = ToolBox.GetAttributeBool(doc.Root, "wasgameupdated", false);

            VerboseLogging = ToolBox.GetAttributeBool(doc.Root, "verboselogging", false);

            InitProjSpecific(doc);

            foreach (XElement subElement in doc.Root.Elements())
            {
                switch (subElement.Name.ToString().ToLowerInvariant())
                {
                case "contentpackage":
                    string path = ToolBox.GetAttributeString(subElement, "path", "");


                    SelectedContentPackage = ContentPackage.list.Find(cp => cp.Path == path);

                    if (SelectedContentPackage == null)
                    {
                        SelectedContentPackage = new ContentPackage(path);
                    }
                    break;
                }
            }
        }
Exemplo n.º 12
0
        public FishAnimController(Character character, XElement element)
            : base(character, element)
        {
            waveAmplitude = ConvertUnits.ToSimUnits(ToolBox.GetAttributeFloat(element, "waveamplitude", 0.0f));
            waveLength    = ConvertUnits.ToSimUnits(ToolBox.GetAttributeFloat(element, "wavelength", 0.0f));

            flip   = ToolBox.GetAttributeBool(element, "flip", true);
            mirror = ToolBox.GetAttributeBool(element, "mirror", false);

            float footRot = ToolBox.GetAttributeFloat(element, "footrotation", float.NaN);

            if (float.IsNaN(footRot))
            {
                footRotation = null;
            }
            else
            {
                footRotation = MathHelper.ToRadians(footRot);
            }

            rotateTowardsMovement = ToolBox.GetAttributeBool(element, "rotatetowardsmovement", true);
        }
Exemplo n.º 13
0
        public EnemyAIController(Character c, string file) : base(c)
        {
            targetMemories = new Dictionary <AITarget, AITargetMemory>();

            XDocument doc = ToolBox.TryLoadXml(file);

            if (doc == null || doc.Root == null)
            {
                return;
            }

            XElement aiElement = doc.Root.Element("ai");

            if (aiElement == null)
            {
                return;
            }

            attackRooms    = ToolBox.GetAttributeFloat(aiElement, "attackrooms", 0.0f) / 100.0f;
            attackHumans   = ToolBox.GetAttributeFloat(aiElement, "attackhumans", 0.0f) / 100.0f;
            attackWeaker   = ToolBox.GetAttributeFloat(aiElement, "attackweaker", 0.0f) / 100.0f;
            attackStronger = ToolBox.GetAttributeFloat(aiElement, "attackstronger", 0.0f) / 100.0f;

            attackCoolDown = ToolBox.GetAttributeFloat(aiElement, "attackcooldown", 5.0f);

            sight   = ToolBox.GetAttributeFloat(aiElement, "sight", 0.0f);
            hearing = ToolBox.GetAttributeFloat(aiElement, "hearing", 0.0f);

            attackWhenProvoked = ToolBox.GetAttributeBool(aiElement, "attackwhenprovoked", false);

            outsideSteering = new SteeringManager(this);
            insideSteering  = new IndoorsSteeringManager(this, false);

            steeringManager = outsideSteering;

            state = AiState.None;
        }
Exemplo n.º 14
0
        public static Mission LoadRandom(Location[] locations, MTRandom rand, string missionType = "", bool isSinglePlayer = false)
        {
            missionType = missionType.ToLowerInvariant();

            var    files      = GameMain.SelectedPackage.GetFilesOfType(ContentType.Missions);
            string configFile = files[rand.Next(files.Count)];

            XDocument doc = ToolBox.TryLoadXml(configFile);

            if (doc == null)
            {
                return(null);
            }

            int eventCount = doc.Root.Elements().Count();

            //int[] commonness = new int[eventCount];
            float[] eventProbability = new float[eventCount];

            float probabilitySum = 0.0f;

            List <XElement> matchingElements = new List <XElement>();

            if (missionType == "random")
            {
                matchingElements = doc.Root.Elements().ToList();
            }
            else if (missionType == "none")
            {
                return(null);
            }
            else if (string.IsNullOrWhiteSpace(missionType))
            {
                matchingElements = doc.Root.Elements().ToList();
            }
            else
            {
                matchingElements = doc.Root.Elements().ToList().FindAll(m => m.Name.ToString().ToLowerInvariant().Replace("mission", "") == missionType);
            }

            if (isSinglePlayer)
            {
                matchingElements.RemoveAll(m => ToolBox.GetAttributeBool(m, "multiplayeronly", false));
            }
            else
            {
                matchingElements.RemoveAll(m => ToolBox.GetAttributeBool(m, "singleplayeronly", false));
            }

            int i = 0;

            foreach (XElement element in matchingElements)
            {
                eventProbability[i] = ToolBox.GetAttributeInt(element, "commonness", 1);

                probabilitySum += eventProbability[i];

                i++;
            }

            float randomNumber = (float)rand.NextDouble() * probabilitySum;

            i = 0;
            foreach (XElement element in matchingElements)
            {
                if (randomNumber <= eventProbability[i])
                {
                    Type   t;
                    string type = element.Name.ToString();

                    try
                    {
                        t = Type.GetType("Barotrauma." + type, true, true);
                        if (t == null)
                        {
                            DebugConsole.ThrowError("Error in " + configFile + "! Could not find a mission class of the type \"" + type + "\".");
                            continue;
                        }
                    }
                    catch
                    {
                        DebugConsole.ThrowError("Error in " + configFile + "! Could not find a mission class of the type \"" + type + "\".");
                        continue;
                    }

                    ConstructorInfo constructor = t.GetConstructor(new[] { typeof(XElement), typeof(Location[]) });

                    object instance = constructor.Invoke(new object[] { element, locations });

                    Mission mission = (Mission)instance;

                    return(mission);
                }

                randomNumber -= eventProbability[i];
                i++;
            }

            return(null);
        }
Exemplo n.º 15
0
        public ItemPrefab(XElement element, string filePath)
        {
            configFile    = filePath;
            ConfigElement = element;

            name = ToolBox.GetAttributeString(element, "name", "");
            if (name == "")
            {
                DebugConsole.ThrowError("Unnamed item in " + filePath + "!");
            }

            DebugConsole.Log("    " + name);

            Description = ToolBox.GetAttributeString(element, "description", "");

            pickThroughWalls = ToolBox.GetAttributeBool(element, "pickthroughwalls", false);
            pickDistance     = ToolBox.GetAttributeFloat(element, "pickdistance", 0.0f);

            isLinkable = ToolBox.GetAttributeBool(element, "linkable", false);

            resizeHorizontal = ToolBox.GetAttributeBool(element, "resizehorizontal", false);
            resizeVertical   = ToolBox.GetAttributeBool(element, "resizevertical", false);

            focusOnSelected = ToolBox.GetAttributeBool(element, "focusonselected", false);

            offsetOnSelected = ToolBox.GetAttributeFloat(element, "offsetonselected", 0.0f);

            CanUseOnSelf = ToolBox.GetAttributeBool(element, "canuseonself", false);

            FireProof = ToolBox.GetAttributeBool(element, "fireproof", false);

            ImpactTolerance = ToolBox.GetAttributeFloat(element, "impacttolerance", 0.0f);

            string aliases = ToolBox.GetAttributeString(element, "aliases", "");

            if (!string.IsNullOrWhiteSpace(aliases))
            {
                Aliases = aliases.Split(',');
            }

            MapEntityCategory category;

            if (!Enum.TryParse(ToolBox.GetAttributeString(element, "category", "Misc"), true, out category))
            {
                category = MapEntityCategory.Misc;
            }

            Category = category;


            string spriteColorStr = ToolBox.GetAttributeString(element, "spritecolor", "1.0,1.0,1.0,1.0");

            SpriteColor = new Color(ToolBox.ParseToVector4(spriteColorStr));

            price = ToolBox.GetAttributeInt(element, "price", 0);

            Triggers = new List <Rectangle>();

            DeconstructItems = new List <DeconstructItem>();
            DeconstructTime  = 1.0f;

            tags = new List <string>();
            tags.AddRange(ToolBox.GetAttributeString(element, "tags", "").Split(','));

            foreach (XElement subElement in element.Elements())
            {
                switch (subElement.Name.ToString().ToLowerInvariant())
                {
                case "sprite":
                    string spriteFolder = "";
                    if (!ToolBox.GetAttributeString(subElement, "texture", "").Contains("/"))
                    {
                        spriteFolder = Path.GetDirectoryName(filePath);
                    }

                    canSpriteFlipX = ToolBox.GetAttributeBool(subElement, "canflipx", true);

                    sprite = new Sprite(subElement, spriteFolder);
                    size   = sprite.size;
                    break;

                case "deconstruct":
                    DeconstructTime = ToolBox.GetAttributeFloat(subElement, "time", 10.0f);

                    foreach (XElement deconstructItem in subElement.Elements())
                    {
                        string deconstructItemName  = ToolBox.GetAttributeString(deconstructItem, "name", "not found");
                        bool   requireFullCondition = ToolBox.GetAttributeBool(deconstructItem, "requirefullcondition", false);

                        DeconstructItems.Add(new DeconstructItem(deconstructItemName, requireFullCondition));
                    }

                    break;

                case "trigger":
                    Rectangle trigger = new Rectangle(0, 0, 10, 10);

                    trigger.X = ToolBox.GetAttributeInt(subElement, "x", 0);
                    trigger.Y = ToolBox.GetAttributeInt(subElement, "y", 0);

                    trigger.Width  = ToolBox.GetAttributeInt(subElement, "width", 0);
                    trigger.Height = ToolBox.GetAttributeInt(subElement, "height", 0);

                    Triggers.Add(trigger);

                    break;
                }
            }

            list.Add(this);
        }
Exemplo n.º 16
0
        protected StatusEffect(XElement element)
        {
            requiredItems = new List <RelatedItem>();

#if CLIENT
            particleEmitters = new List <ParticleEmitterPrefab>();
#endif

            IEnumerable <XAttribute> attributes         = element.Attributes();
            List <XAttribute>        propertyAttributes = new List <XAttribute>();

            foreach (XAttribute attribute in attributes)
            {
                switch (attribute.Name.ToString())
                {
                case "type":
                    try
                    {
                        type = (ActionType)Enum.Parse(typeof(ActionType), attribute.Value, true);
                    }

                    catch
                    {
                        string[] split = attribute.Value.Split('=');
                        type = (ActionType)Enum.Parse(typeof(ActionType), split[0], true);

                        string[] containingNames = split[1].Split(',');
                        onContainingNames = new HashSet <string>();
                        for (int i = 0; i < containingNames.Length; i++)
                        {
                            onContainingNames.Add(containingNames[i].Trim());
                        }
                    }

                    break;

                case "target":
                    string[] Flags = attribute.Value.Split(',');
                    foreach (string s in Flags)
                    {
                        targetTypes |= (TargetType)Enum.Parse(typeof(TargetType), s, true);
                    }

                    break;

                case "disabledeltatime":
                    disableDeltaTime = ToolBox.GetAttributeBool(attribute, false);
                    break;

                case "setvalue":
                    setValue = ToolBox.GetAttributeBool(attribute, false);
                    break;

                case "targetnames":
                    string[] names = attribute.Value.Split(',');
                    targetNames = new HashSet <string>();
                    for (int i = 0; i < names.Length; i++)
                    {
                        targetNames.Add(names[i].Trim());
                    }
                    break;

                case "duration":
                    duration = ToolBox.GetAttributeFloat(attribute, 0.0f);
                    break;

#if CLIENT
                case "sound":
                    sound = Sound.Load(attribute.Value.ToString());
                    break;
#endif
                default:
                    propertyAttributes.Add(attribute);
                    break;
                }
            }

            int count = propertyAttributes.Count;
            propertyNames   = new string[count];
            propertyEffects = new object[count];

            int n = 0;
            foreach (XAttribute attribute in propertyAttributes)
            {
                propertyNames[n]   = attribute.Name.ToString().ToLowerInvariant();
                propertyEffects[n] = ToolBox.GetAttributeObject(attribute);
                n++;
            }

            foreach (XElement subElement in element.Elements())
            {
                switch (subElement.Name.ToString().ToLowerInvariant())
                {
                case "explosion":
                    explosion = new Explosion(subElement);
                    break;

                case "fire":
                    FireSize = ToolBox.GetAttributeFloat(subElement, "size", 10.0f);
                    break;

                case "use":
                case "useitem":
                    useItem = true;
                    break;

                case "requireditem":
                case "requireditems":
                    RelatedItem newRequiredItem = RelatedItem.Load(subElement);

                    if (newRequiredItem == null)
                    {
                        continue;
                    }

                    requiredItems.Add(newRequiredItem);
                    break;

#if CLIENT
                case "particleemitter":
                    particleEmitters.Add(new ParticleEmitterPrefab(subElement));
                    break;
#endif
                }
            }
        }
Exemplo n.º 17
0
        public CharacterInfo(string file, string name = "", Gender gender = Gender.None, JobPrefab jobPrefab = null)
        {
            this.File = file;

            headSpriteRange = new Vector2[2];

            pickedItems = new List <ushort>();

            SpriteTags = new List <string>();

            //ID = -1;

            XDocument doc = ToolBox.TryLoadXml(file);

            if (doc == null)
            {
                return;
            }

            if (ToolBox.GetAttributeBool(doc.Root, "genders", false))
            {
                if (gender == Gender.None)
                {
                    float femaleRatio = ToolBox.GetAttributeFloat(doc.Root, "femaleratio", 0.5f);
                    this.gender = (Rand.Range(0.0f, 1.0f, Rand.RandSync.Server) < femaleRatio) ? Gender.Female : Gender.Male;
                }
                else
                {
                    this.gender = gender;
                }
            }

            headSpriteRange[0] = ToolBox.GetAttributeVector2(doc.Root, "headid", Vector2.Zero);
            headSpriteRange[1] = headSpriteRange[0];
            if (headSpriteRange[0] == Vector2.Zero)
            {
                headSpriteRange[0] = ToolBox.GetAttributeVector2(doc.Root, "maleheadid", Vector2.Zero);
                headSpriteRange[1] = ToolBox.GetAttributeVector2(doc.Root, "femaleheadid", Vector2.Zero);
            }

            int genderIndex = (this.gender == Gender.Female) ? 1 : 0;

            if (headSpriteRange[genderIndex] != Vector2.Zero)
            {
                HeadSpriteId = Rand.Range((int)headSpriteRange[genderIndex].X, (int)headSpriteRange[genderIndex].Y + 1);
            }

            this.Job = (jobPrefab == null) ? Job.Random() : new Job(jobPrefab);

            if (!string.IsNullOrEmpty(name))
            {
                this.Name = name;
                return;
            }

            name = "";

            if (doc.Root.Element("name") != null)
            {
                string firstNamePath = ToolBox.GetAttributeString(doc.Root.Element("name"), "firstname", "");
                if (firstNamePath != "")
                {
                    firstNamePath = firstNamePath.Replace("[GENDER]", (this.gender == Gender.Female) ? "f" : "");
                    this.Name     = ToolBox.GetRandomLine(firstNamePath);
                }

                string lastNamePath = ToolBox.GetAttributeString(doc.Root.Element("name"), "lastname", "");
                if (lastNamePath != "")
                {
                    lastNamePath = lastNamePath.Replace("[GENDER]", (this.gender == Gender.Female) ? "f" : "");
                    if (this.Name != "")
                    {
                        this.Name += " ";
                    }
                    this.Name += ToolBox.GetRandomLine(lastNamePath);
                }
            }

            Salary = CalculateSalary();
        }
Exemplo n.º 18
0
        public static StructurePrefab Load(XElement element)
        {
            StructurePrefab sp = new StructurePrefab();

            sp.name = element.Name.ToString();

            sp.tags = new List <string>();
            sp.tags.AddRange(ToolBox.GetAttributeString(element, "tags", "").Split(','));

            foreach (XElement subElement in element.Elements())
            {
                switch (subElement.Name.ToString())
                {
                case "sprite":
                    sp.sprite = new Sprite(subElement);

                    if (ToolBox.GetAttributeBool(subElement, "fliphorizontal", false))
                    {
                        sp.sprite.effects = SpriteEffects.FlipHorizontally;
                    }
                    if (ToolBox.GetAttributeBool(subElement, "flipvertical", false))
                    {
                        sp.sprite.effects = SpriteEffects.FlipVertically;
                    }

                    sp.canSpriteFlipX = ToolBox.GetAttributeBool(subElement, "canflipx", true);

                    break;

                case "backgroundsprite":
                    sp.BackgroundSprite = new Sprite(subElement);

                    if (ToolBox.GetAttributeBool(subElement, "fliphorizontal", false))
                    {
                        sp.BackgroundSprite.effects = SpriteEffects.FlipHorizontally;
                    }
                    if (ToolBox.GetAttributeBool(subElement, "flipvertical", false))
                    {
                        sp.BackgroundSprite.effects = SpriteEffects.FlipVertically;
                    }

                    break;
                }
            }

            MapEntityCategory category;

            if (!Enum.TryParse(ToolBox.GetAttributeString(element, "category", "Structure"), true, out category))
            {
                category = MapEntityCategory.Structure;
            }

            sp.Category = category;

            sp.Description = ToolBox.GetAttributeString(element, "description", "");

            sp.size   = Vector2.Zero;
            sp.size.X = ToolBox.GetAttributeFloat(element, "width", 0.0f);
            sp.size.Y = ToolBox.GetAttributeFloat(element, "height", 0.0f);

            string spriteColorStr = ToolBox.GetAttributeString(element, "spritecolor", "1.0,1.0,1.0,1.0");

            sp.SpriteColor = new Color(ToolBox.ParseToVector4(spriteColorStr));

            sp.maxHealth = ToolBox.GetAttributeFloat(element, "health", 100.0f);

            sp.resizeHorizontal = ToolBox.GetAttributeBool(element, "resizehorizontal", false);
            sp.resizeVertical   = ToolBox.GetAttributeBool(element, "resizevertical", false);

            sp.isPlatform     = ToolBox.GetAttributeBool(element, "platform", false);
            sp.stairDirection = (Direction)Enum.Parse(typeof(Direction), ToolBox.GetAttributeString(element, "stairdirection", "None"), true);

            sp.castShadow = ToolBox.GetAttributeBool(element, "castshadow", false);

            sp.hasBody = ToolBox.GetAttributeBool(element, "body", false);

            return(sp);
        }
Exemplo n.º 19
0
        public GUIComponentStyle(XElement element)
        {
            Sprites = new Dictionary <GUIComponent.ComponentState, List <UISprite> >();
            foreach (GUIComponent.ComponentState state in Enum.GetValues(typeof(GUIComponent.ComponentState)))
            {
                Sprites[state] = new List <UISprite>();
            }

            ChildStyles = new Dictionary <string, GUIComponentStyle>();

            Padding = ToolBox.GetAttributeVector4(element, "padding", Vector4.Zero);

            Vector4 colorVector = ToolBox.GetAttributeVector4(element, "color", new Vector4(0.0f, 0.0f, 0.0f, 0.0f));

            Color = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W);

            colorVector = ToolBox.GetAttributeVector4(element, "textcolor", new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
            textColor   = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W);

            colorVector = ToolBox.GetAttributeVector4(element, "hovercolor", new Vector4(0.0f, 0.0f, 0.0f, 0.0f));
            HoverColor  = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W);

            colorVector   = ToolBox.GetAttributeVector4(element, "selectedcolor", new Vector4(0.0f, 0.0f, 0.0f, 0.0f));
            SelectedColor = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W);

            colorVector  = ToolBox.GetAttributeVector4(element, "outlinecolor", new Vector4(0.0f, 0.0f, 0.0f, 0.0f));
            OutlineColor = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W);

            foreach (XElement subElement in element.Elements())
            {
                switch (subElement.Name.ToString().ToLowerInvariant())
                {
                case "sprite":
                    Sprite sprite         = new Sprite(subElement);
                    bool   maintainAspect = ToolBox.GetAttributeBool(subElement, "maintainaspectratio", false);
                    bool   tile           = ToolBox.GetAttributeBool(subElement, "tile", true);

                    string stateStr = ToolBox.GetAttributeString(subElement, "state", "None");
                    GUIComponent.ComponentState spriteState = GUIComponent.ComponentState.None;
                    Enum.TryParse(stateStr, out spriteState);

                    UISprite newSprite = new UISprite(sprite, tile, maintainAspect);

                    Vector4 sliceVec = ToolBox.GetAttributeVector4(subElement, "slice", Vector4.Zero);
                    if (sliceVec != Vector4.Zero)
                    {
                        Rectangle slice = new Rectangle((int)sliceVec.X, (int)sliceVec.Y, (int)(sliceVec.Z - sliceVec.X), (int)(sliceVec.W - sliceVec.Y));

                        newSprite.Slice = true;

                        newSprite.Slices = new Rectangle[9];

                        //top-left
                        newSprite.Slices[0] = new Rectangle(newSprite.Sprite.SourceRect.Location, slice.Location - newSprite.Sprite.SourceRect.Location);
                        //top-mid
                        newSprite.Slices[1] = new Rectangle(slice.Location.X, newSprite.Slices[0].Y, slice.Width, newSprite.Slices[0].Height);
                        //top-right
                        newSprite.Slices[2] = new Rectangle(slice.Right, newSprite.Slices[0].Y, newSprite.Sprite.SourceRect.Right - slice.Right, newSprite.Slices[0].Height);

                        //mid-left
                        newSprite.Slices[3] = new Rectangle(newSprite.Slices[0].X, slice.Y, newSprite.Slices[0].Width, slice.Height);
                        //center
                        newSprite.Slices[4] = slice;
                        //mid-right
                        newSprite.Slices[5] = new Rectangle(newSprite.Slices[2].X, slice.Y, newSprite.Slices[2].Width, slice.Height);

                        //bottom-left
                        newSprite.Slices[6] = new Rectangle(newSprite.Slices[0].X, slice.Bottom, newSprite.Slices[0].Width, newSprite.Sprite.SourceRect.Bottom - slice.Bottom);
                        //bottom-mid
                        newSprite.Slices[7] = new Rectangle(newSprite.Slices[1].X, slice.Bottom, newSprite.Slices[1].Width, newSprite.Sprite.SourceRect.Bottom - slice.Bottom);
                        //bottom-right
                        newSprite.Slices[8] = new Rectangle(newSprite.Slices[2].X, slice.Bottom, newSprite.Slices[2].Width, newSprite.Sprite.SourceRect.Bottom - slice.Bottom);
                    }

                    Sprites[spriteState].Add(newSprite);
                    break;

                default:
                    ChildStyles.Add(subElement.Name.ToString().ToLowerInvariant(), new GUIComponentStyle(subElement));
                    break;
                }
            }
        }
Exemplo n.º 20
0
        public Limb(Character character, XElement element, float scale = 1.0f)
        {
            this.character = character;

            wearingItems = new List <WearableSprite>();

            dir = Direction.Right;

            doesFlip = ToolBox.GetAttributeBool(element, "flip", false);

            this.scale = scale;

            body = new PhysicsBody(element, scale);

            if (ToolBox.GetAttributeBool(element, "ignorecollisions", false))
            {
                body.CollisionCategories = Category.None;
                body.CollidesWith        = Category.None;

                ignoreCollisions = true;
            }
            else
            {
                //limbs don't collide with each other
                body.CollisionCategories = Physics.CollisionCharacter;
                body.CollidesWith        = Physics.CollisionAll & ~Physics.CollisionCharacter & ~Physics.CollisionItem;
            }

            body.UserData = this;

            refJointIndex = -1;

            Vector2 pullJointPos = Vector2.Zero;

            if (element.Attribute("type") != null)
            {
                try
                {
                    type = (LimbType)Enum.Parse(typeof(LimbType), element.Attribute("type").Value, true);
                }
                catch
                {
                    type = LimbType.None;
                    DebugConsole.ThrowError("Error in " + element + "! \"" + element.Attribute("type").Value + "\" is not a valid limb type");
                }


                pullJointPos = ToolBox.GetAttributeVector2(element, "pullpos", Vector2.Zero) * scale;
                pullJointPos = ConvertUnits.ToSimUnits(pullJointPos);

                stepOffset = ToolBox.GetAttributeVector2(element, "stepoffset", Vector2.Zero) * scale;
                stepOffset = ConvertUnits.ToSimUnits(stepOffset);

                refJointIndex = ToolBox.GetAttributeInt(element, "refjoint", -1);
            }
            else
            {
                type = LimbType.None;
            }

            pullJoint          = new FixedMouseJoint(body.FarseerBody, pullJointPos);
            pullJoint.Enabled  = false;
            pullJoint.MaxForce = ((type == LimbType.LeftHand || type == LimbType.RightHand) ? 400.0f : 150.0f) * body.Mass;

            GameMain.World.AddJoint(pullJoint);

            steerForce = ToolBox.GetAttributeFloat(element, "steerforce", 0.0f);

            //maxHealth = Math.Max(ToolBox.GetAttributeFloat(element, "health", 100.0f),1.0f);

            armorSector   = ToolBox.GetAttributeVector2(element, "armorsector", Vector2.Zero);
            armorSector.X = MathHelper.ToRadians(armorSector.X);
            armorSector.Y = MathHelper.ToRadians(armorSector.Y);

            armorValue = Math.Max(ToolBox.GetAttributeFloat(element, "armor", 0.0f), 0.0f);

            if (element.Attribute("mouthpos") != null)
            {
                MouthPos = ConvertUnits.ToSimUnits(ToolBox.GetAttributeVector2(element, "mouthpos", Vector2.Zero));
            }

            body.BodyType = BodyType.Dynamic;
            body.FarseerBody.AngularDamping = LimbAngularDamping;

            foreach (XElement subElement in element.Elements())
            {
                switch (subElement.Name.ToString().ToLowerInvariant())
                {
                case "sprite":
                    string spritePath = subElement.Attribute("texture").Value;

                    string spritePathWithTags = spritePath;

                    if (character.Info != null)
                    {
                        spritePath = spritePath.Replace("[GENDER]", (character.Info.Gender == Gender.Female) ? "f" : "");
                        spritePath = spritePath.Replace("[HEADID]", character.Info.HeadSpriteId.ToString());

                        if (character.Info.HeadSprite != null && character.Info.SpriteTags.Any())
                        {
                            string tags = "";
                            character.Info.SpriteTags.ForEach(tag => tags += "[" + tag + "]");

                            spritePathWithTags = Path.Combine(
                                Path.GetDirectoryName(spritePath),
                                Path.GetFileNameWithoutExtension(spritePath) + tags + Path.GetExtension(spritePath));
                        }
                    }

                    if (File.Exists(spritePathWithTags))
                    {
                        sprite = new Sprite(subElement, "", spritePathWithTags);
                    }
                    else
                    {
                        sprite = new Sprite(subElement, "", spritePath);
                    }

                    break;

                case "damagedsprite":
                    string damagedSpritePath = subElement.Attribute("texture").Value;

                    if (character.Info != null)
                    {
                        damagedSpritePath = damagedSpritePath.Replace("[GENDER]", (character.Info.Gender == Gender.Female) ? "f" : "");
                        damagedSpritePath = damagedSpritePath.Replace("[HEADID]", character.Info.HeadSpriteId.ToString());
                    }

                    damagedSprite = new Sprite(subElement, "", damagedSpritePath);
                    break;

                case "attack":
                    attack = new Attack(subElement);
                    break;
                }
            }

            InitProjSpecific(element);
        }
Exemplo n.º 21
0
        public void Load(string filePath)
        {
            XDocument doc = ToolBox.TryLoadXml(filePath);

            if (doc == null)
            {
                DebugConsole.ThrowError("No config file found");

                GraphicsWidth  = 1024;
                GraphicsHeight = 678;

                MasterServerUrl = "";

                SelectedContentPackage = ContentPackage.list.Any() ? ContentPackage.list[0] : new ContentPackage("");

                JobNamePreferences = new List <string>();
                foreach (JobPrefab job in JobPrefab.List)
                {
                    JobNamePreferences.Add(job.Name);
                }

                return;
            }

            XElement graphicsMode = doc.Root.Element("graphicsmode");

            GraphicsWidth  = ToolBox.GetAttributeInt(graphicsMode, "width", 0);
            GraphicsHeight = ToolBox.GetAttributeInt(graphicsMode, "height", 0);
            VSyncEnabled   = ToolBox.GetAttributeBool(graphicsMode, "vsync", true);

            if (GraphicsWidth == 0 || GraphicsHeight == 0)
            {
                GraphicsWidth  = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
                GraphicsHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
            }

            //FullScreenEnabled = ToolBox.GetAttributeBool(graphicsMode, "fullscreen", true);

            var windowModeStr = ToolBox.GetAttributeString(graphicsMode, "displaymode", "Fullscreen");

            if (!Enum.TryParse <WindowMode>(windowModeStr, out windowMode))
            {
                windowMode = WindowMode.Fullscreen;
            }

            MasterServerUrl = ToolBox.GetAttributeString(doc.Root, "masterserverurl", "");

            AutoCheckUpdates = ToolBox.GetAttributeBool(doc.Root, "autocheckupdates", true);
            WasGameUpdated   = ToolBox.GetAttributeBool(doc.Root, "wasgameupdated", false);

            SoundVolume = ToolBox.GetAttributeFloat(doc.Root, "soundvolume", 1.0f);
            MusicVolume = ToolBox.GetAttributeFloat(doc.Root, "musicvolume", 0.3f);

            VerboseLogging = ToolBox.GetAttributeBool(doc.Root, "verboselogging", false);

            EnableSplashScreen = ToolBox.GetAttributeBool(doc.Root, "enablesplashscreen", true);

            keyMapping = new KeyOrMouse[Enum.GetNames(typeof(InputType)).Length];
            keyMapping[(int)InputType.Up]    = new KeyOrMouse(Keys.W);
            keyMapping[(int)InputType.Down]  = new KeyOrMouse(Keys.S);
            keyMapping[(int)InputType.Left]  = new KeyOrMouse(Keys.A);
            keyMapping[(int)InputType.Right] = new KeyOrMouse(Keys.D);
            keyMapping[(int)InputType.Run]   = new KeyOrMouse(Keys.LeftShift);


            keyMapping[(int)InputType.Chat]       = new KeyOrMouse(Keys.Tab);
            keyMapping[(int)InputType.CrewOrders] = new KeyOrMouse(Keys.C);

            keyMapping[(int)InputType.Select] = new KeyOrMouse(Keys.E);

            keyMapping[(int)InputType.Use] = new KeyOrMouse(0);
            keyMapping[(int)InputType.Aim] = new KeyOrMouse(1);

            foreach (XElement subElement in doc.Root.Elements())
            {
                switch (subElement.Name.ToString().ToLowerInvariant())
                {
                case "contentpackage":
                    string path = ToolBox.GetAttributeString(subElement, "path", "");


                    SelectedContentPackage = ContentPackage.list.Find(cp => cp.Path == path);

                    if (SelectedContentPackage == null)
                    {
                        SelectedContentPackage = new ContentPackage(path);
                    }
                    break;

                case "keymapping":
                    foreach (XAttribute attribute in subElement.Attributes())
                    {
                        InputType inputType;
                        if (Enum.TryParse(attribute.Name.ToString(), true, out inputType))
                        {
                            int mouseButton;
                            if (int.TryParse(attribute.Value.ToString(), out mouseButton))
                            {
                                keyMapping[(int)inputType] = new KeyOrMouse(mouseButton);
                            }
                            else
                            {
                                Keys key;
                                if (Enum.TryParse(attribute.Value.ToString(), true, out key))
                                {
                                    keyMapping[(int)inputType] = new KeyOrMouse(key);
                                }
                            }
                        }
                    }
                    break;

                case "gameplay":
                    JobNamePreferences = new List <string>();
                    foreach (XElement ele in subElement.Element("jobpreferences").Elements("job"))
                    {
                        JobNamePreferences.Add(ToolBox.GetAttributeString(ele, "name", ""));
                    }
                    break;
                }
            }

            foreach (InputType inputType in Enum.GetValues(typeof(InputType)))
            {
                if (keyMapping[(int)inputType] == null)
                {
                    DebugConsole.ThrowError("Key binding for the input type \"" + inputType + " not set!");
                    keyMapping[(int)inputType] = new KeyOrMouse(Keys.D1);
                }
            }


            UnsavedSettings = false;
        }