Esempio n. 1
0
        public override TImport Import(string filename, ContentImporterContext context)
        {
            _context = context;

            // _animfiles will contain list of new temp anim files.
            _animfiles = new List<string>();

            // Decouple header and animation data.
            ExtractAnimations(filename);

            // Process master file (this will also process the first animation)
            _master = base.Import(filename, context);

            // Process the remaining animations.
            foreach (string file in _animfiles) {
                TImport anim = base.Import(file, context);

                // Append animation to master NodeContent.
                AppendAnimation(_master, anim);
            }

            // Delete the temporary animation files.
            DeleteTempFiles();

            return _master;
        }
Esempio n. 2
0
        public UnitContent(XmlDocument document, ContentImporterContext context)
        {
            XmlNode unitNode = document["unit"];

            Name = unitNode.Attributes["name"].Value;
            Width = int.Parse(unitNode.Attributes["width"].Value, CultureInfo.InvariantCulture);
            Height = int.Parse(unitNode.Attributes["height"].Value, CultureInfo.InvariantCulture);

            XmlNode spritesetNode = document.SelectSingleNode("unit/spriteset");

            if (spritesetNode != null)
            {
                XmlNode imageNode = document.SelectSingleNode("unit/spriteset/image");

                if (imageNode != null)
                {
                    imagePath = imageNode.Attributes["source"].Value;
                    imageSize = new Vector2(
                        int.Parse(imageNode.Attributes["width"].Value, CultureInfo.InvariantCulture),
                        int.Parse(imageNode.Attributes["height"].Value, CultureInfo.InvariantCulture)
                        );
                }
            }

            Animations = Animation.animationListFromXmlNodeList(document.SelectNodes("unit/animations/animation"), Width, Height);

            XmlNode dataNode = document.SelectSingleNode("unit/data");

            if (dataNode != null)
                foreach (XmlNode node in dataNode.ChildNodes)
                    Data[node.Name] = node.InnerXml;
        }
Esempio n. 3
0
        public KeyframeContent(XmlNode xmlNode, ContentImporterContext context)
        {
            Bones = new List<BoneContent>();

            FrameNumber = int.Parse(xmlNode.Attributes["frame"].Value);
            if (xmlNode.Attributes["trigger"] != null)
                Trigger = xmlNode.Attributes["trigger"].Value;
            else
                Trigger = "";

            if (xmlNode.Attributes["vflip"] != null)
                FlipVertically = bool.Parse(xmlNode.Attributes["vflip"].Value);
            else
                FlipVertically = false;

            if (xmlNode.Attributes["hflip"] != null)
                FlipHorizontally = bool.Parse(xmlNode.Attributes["hflip"].Value);
            else
                FlipHorizontally = false;

            XmlNodeList boneNodeList = xmlNode.SelectNodes("Bone");
            foreach (XmlNode boneNode in boneNodeList)
            {
                BoneContent boneContent = new BoneContent(boneNode, context);
                Bones.Add(boneContent);
            }
        }
Esempio n. 4
0
        public TileSetContent(XmlNode node, ContentImporterContext context)
        {
            FirstId = int.Parse(node.Attributes["firstgid"].Value, CultureInfo.InvariantCulture);

            var preparedNode = this.PrepareXmlNode(node);
            this.Initialize(preparedNode, context);
        }
        public MapObjectContent(XmlNode node, ContentImporterContext context)
        {
            if (node.Attributes["name"] != null)
            {
                Name = node.Attributes["name"].Value;
            }

            if (node.Attributes["type"] != null)
            {
                Type = node.Attributes["type"].Value;
            }

            // values default to 0 if the attribute is missing from the node
            int x = node.Attributes["x"] != null ? int.Parse(node.Attributes["x"].Value, CultureInfo.InvariantCulture) : 0;
            int y = node.Attributes["y"] != null ? int.Parse(node.Attributes["y"].Value, CultureInfo.InvariantCulture) : 0;
            int width = node.Attributes["width"] != null ? int.Parse(node.Attributes["width"].Value, CultureInfo.InvariantCulture) : 0;
            int height = node.Attributes["height"] != null ? int.Parse(node.Attributes["height"].Value, CultureInfo.InvariantCulture) : 0;

            Location = new Rectangle(x, y, width, height);

            XmlNode propertiesNode = node["properties"];
            if (propertiesNode != null)
            {
                Properties = Property.ReadProperties(propertiesNode, context);
            }
        }
Esempio n. 6
0
        public MapObjectContent(XmlNode node, ContentImporterContext context)
        {
            // get the object's name and type
            if (node.Attributes["name"] != null)
                Name = node.Attributes["name"].Value;
            if (node.Attributes["type"] != null)
                Type = node.Attributes["type"].Value;

            // read the object properties
            if (node["properties"] != null)
                Properties = new PropertyCollection(node["properties"], context);

            // parse out the bounds of the object. values default to 0 if the attribute is missing from the node.
            int x = node.Attributes["x"] != null ? int.Parse(node.Attributes["x"].Value, CultureInfo.InvariantCulture) : 0;
            int y = node.Attributes["y"] != null ? int.Parse(node.Attributes["y"].Value, CultureInfo.InvariantCulture) : 0;
            int width = node.Attributes["width"] != null ? int.Parse(node.Attributes["width"].Value, CultureInfo.InvariantCulture) : 0;
            int height = node.Attributes["height"] != null ? int.Parse(node.Attributes["height"].Value, CultureInfo.InvariantCulture) : 0;
            Bounds = new Rectangle(x, y, width, height);

            // stores a string of points to parse out if this object is a polygon or polyline
            string pointsAsString = null;

            // if there's a GID, it's a tile object
            if (node.Attributes["gid"] != null)
            {
                ObjectType = MapObjectType.Tile;
                GID = int.Parse(node.Attributes["gid"].Value, CultureInfo.InvariantCulture);
            }
            // if there's a polygon node, it's a polygon object
            else if (node["polygon"] != null)
            {
                ObjectType = MapObjectType.Polygon;
                pointsAsString = node["polygon"].Attributes["points"].Value;
            }
            // if there's a polyline node, it's a polyline object
            else if (node["polyline"] != null)
            {
                ObjectType = MapObjectType.Polyline;
                pointsAsString = node["polyline"].Attributes["points"].Value;
            }

            // if we have some points to parse, we do that now
            if (pointsAsString != null)
            {
                // points are separated first by spaces
                string[] pointPairs = pointsAsString.Split(' ');
                foreach (string p in pointPairs)
                {
                    // then we split on commas
                    string[] coords = p.Split(',');

                    // then we parse the X/Y coordinates
                    Points.Add(new Vector2(
                        float.Parse(coords[0], CultureInfo.InvariantCulture),
                        float.Parse(coords[1], CultureInfo.InvariantCulture)));
                }
            }
        }
Esempio n. 7
0
        public DXSPrimitive(XmlNode node, ContentImporterContext context)
        {
            Id = node.Attributes["id"] != null ? int.Parse(node.Attributes["id"].Value) : 0;

            if (node.Attributes["name"] != null)
                Name = node.Attributes["name"].Value;
            if (node.Attributes["type"] != null)
                Type = node.Attributes["type"].Value;
            if (node.Attributes["visible"] != null)
                Visible = bool.Parse(node.Attributes["visible"].Value);
            if (node.Attributes["snap"] != null)
                Snap = node.Attributes["snap"].Value;
            if (node.Attributes["autoUV"] != null)
                AutoUV = bool.Parse(node.Attributes["autoUV"].Value);

            GroupId = node.Attributes["groupID"] != null ? int.Parse(node.Attributes["groupID"].Value) : -1;
            SkeletonId = node.Attributes["skeletonID"] != null ? int.Parse(node.Attributes["skeletonID"].Value) : -1;

            if (node["comments"] != null)
                Comments = node["comments"].Value;

            if (node["tag"] != null)
            {
                Tags = new TagCollection(node["tag"], context);
            }

            foreach (XmlNode v in node.SelectNodes("vertices/vertex"))
            {
                VertexContent vtx = new VertexContent();
                vtx.Id = v.Attributes["id"] != null ? int.Parse(v.Attributes["id"].Value) : 0;
                vtx.JointId = v.Attributes["jointID"] != null ? int.Parse(v.Attributes["jointID"].Value) : -1;
                vtx.Vertex.X = v.Attributes["x"] != null ? float.Parse(v.Attributes["x"].Value, CultureInfo.InvariantCulture) : 0;
                vtx.Vertex.Y = v.Attributes["y"] != null ? float.Parse(v.Attributes["y"].Value, CultureInfo.InvariantCulture) : 0;
                vtx.Vertex.Z = v.Attributes["z"] != null ? float.Parse(v.Attributes["z"].Value, CultureInfo.InvariantCulture) : 0;

                Vertices.Add(vtx);
            }

            foreach (XmlNode p in node.SelectNodes("polygons/poly"))
            {
                PolygonContent poly = new PolygonContent();
                poly.MaterialId = int.Parse(p.Attributes["mid"].Value);
                foreach (XmlNode pv in p.SelectNodes("vertex"))
                {
                    VertexContent vtx = new VertexContent();
                    vtx.Id = pv.Attributes["vid"] != null ? int.Parse(pv.Attributes["vid"].Value) : 0;
                    vtx.UV.X = pv.Attributes["u0"] != null ? float.Parse(pv.Attributes["u0"].Value) : 0;
                    vtx.UV.Y = pv.Attributes["v0"] != null ? float.Parse(pv.Attributes["v0"].Value) : 0;
                    vtx.UV1.X = pv.Attributes["u1"] != null ? float.Parse(pv.Attributes["u1"].Value) : 0;
                    vtx.UV1.Y = pv.Attributes["v1"] != null ? float.Parse(pv.Attributes["v1"].Value) : 0;

                    poly.Vertices.Add(vtx);
                }

                Polys.Add(poly);
            }
        }
 public TextureBoundsContent(XmlNode xmlNode, ContentImporterContext context)
 {
     Name = xmlNode.Attributes["name"].Value;
     Location = new Rectangle(int.Parse(xmlNode.SelectSingleNode("X").InnerText),
         int.Parse(xmlNode.SelectSingleNode("Y").InnerText),
         int.Parse(xmlNode.SelectSingleNode("Width").InnerText),
         int.Parse(xmlNode.SelectSingleNode("Height").InnerText));
     Origin = new Vector2(float.Parse(xmlNode.SelectSingleNode("OriginX").InnerText, CultureInfo.InvariantCulture),
         float.Parse(xmlNode.SelectSingleNode("OriginY").InnerText, CultureInfo.InvariantCulture));
 }
Esempio n. 9
0
        /// <summary>
        /// Called by the XNA Framework when importing a .spritefont file to be used as a game asset. This is the method called by the XNA Framework when an asset is to be imported into an object that can be recognized by the Content Pipeline.
        /// </summary>
        /// <param name="filename">Name of a game asset file.</param>
        /// <param name="context">Contains information for importing a game asset, such as a logger interface.</param>
        /// <returns>Resulting game asset.</returns>
        public override FontDescription Import(string filename, ContentImporterContext context)
        {
            FontDescription fontDescription = null;

            using (var input = XmlReader.Create(filename))
                fontDescription = IntermediateSerializer.Deserialize <FontDescription>(input, filename);

            fontDescription.Identity = new ContentIdentity(new FileInfo(filename).FullName, "FontDescriptionImporter");

            return(fontDescription);
        }
Esempio n. 10
0
 /// <summary>
 /// Called by the framework when importing a game asset. This is the method called by XNA when an asset is to be imported into an object that can be recognized by the Content Pipeline.
 /// </summary>
 /// <param name="filename">Name of a game asset file.</param>
 /// <param name="context">Contains information for importing a game asset, such as a logger interface.</param>
 /// <returns>Resulting game asset.</returns>
 object IContentImporter.Import(string filename, ContentImporterContext context)
 {
     if (filename == null)
     {
         throw new ArgumentNullException("filename");
     }
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     return(Import(filename, context));
 }
Esempio n. 11
0
        /// <summary>
        /// Called by the XNA Framework when importing a .spritefont file to be used as a game asset. This is the method called by the XNA Framework when an asset is to be imported into an object that can be recognized by the Content Pipeline.
        /// </summary>
        /// <param name="filename">Name of a game asset file.</param>
        /// <param name="context">Contains information for importing a game asset, such as a logger interface.</param>
        /// <returns>Resulting game asset.</returns>
        public override FontDescription Import(string filename, ContentImporterContext context)
        {
            var xmldoc = XElement.Load(filename, LoadOptions.PreserveWhitespace);

            xmldoc = xmldoc.Element("Asset");

            var fontName   = xmldoc.Element("FontName").Value;
            var fontSize   = float.Parse(xmldoc.Element("Size").Value);
            var spacing    = float.Parse(xmldoc.Element("Spacing").Value);
            var useKerning = bool.Parse(xmldoc.Element("UseKerning").Value);

            var styleVal = xmldoc.Element("Style").Value;

            FontDescriptionStyle style = FontDescriptionStyle.Regular;

            if (styleVal.Contains("Bold") && styleVal.Contains("Italic"))
            {
                style = FontDescriptionStyle.Bold | FontDescriptionStyle.Italic;
            }
            else
            {
                style = (FontDescriptionStyle)Enum.Parse(typeof(FontDescriptionStyle), styleVal, false);
            }

            char?defaultCharacter = null;
            var  defChar          = xmldoc.Element("DefaultCharacter");

            if (defChar != null)
            {
                defaultCharacter = defChar.Value[0];
            }

            var characters = new List <char>();

            foreach (var region in xmldoc.Descendants("CharacterRegion"))
            {
                var Start = (int)region.Element("Start").Value[0];
                var End   = (int)region.Element("End").Value[0];

                for (var x = Start; x <= End; x++)
                {
                    var character = (char)x;
                    if (characters.Contains(character))
                    {
                        continue;
                    }

                    characters.Add(character);
                }
            }

            return(new FontDescription(fontName, fontSize, spacing, style, useKerning, characters));
        }
Esempio n. 12
0
 /// <summary>
 /// Create the bone content.
 /// </summary>
 /// <param name="node">The xml node to get the information from.</param>
 /// <param name="context">The content importer context.</param>
 public BoneContent(XmlNode node, ContentImporterContext context)
 {
     //Parse the xml data.
     Name = node.Attributes["Name"].Value;
     Index = int.Parse(node.SelectSingleNode("Index").InnerText);
     ParentIndex = int.Parse(node.SelectSingleNode("ParentIndex").InnerText);
     Position = new Vector2(float.Parse(node.SelectSingleNode("Position/X").InnerText),
         float.Parse(node.SelectSingleNode("Position/Y").InnerText));
     Rotation = float.Parse(node.SelectSingleNode("Rotation").InnerText);
     Scale = new Vector2(float.Parse(node.SelectSingleNode("Scale/X").InnerText), float.Parse(node.SelectSingleNode("Scale/Y").InnerText));
     Length = float.Parse(node.SelectSingleNode("Length").InnerText);
 }
Esempio n. 13
0
        public DXSScene(XmlDocument document, ContentImporterContext context)
        {
            XmlNode sceneNode = document["scene"];

            Version = sceneNode.Attributes["version"].Value;

            XmlNode settingsNode = document.SelectSingleNode("scene/settings");
            if (settingsNode != null)
            {
                Name = settingsNode.Attributes["name"].Value;
                Author = settingsNode.Attributes["author"].Value;
                Comments = settingsNode.Attributes["comments"].Value;

                if (settingsNode["ambient"] != null)
                {
                    int r = int.Parse(settingsNode["ambient"].Attributes["r"].Value);
                    int g = int.Parse(settingsNode["ambient"].Attributes["g"].Value);
                    int b = int.Parse(settingsNode["ambient"].Attributes["b"].Value);

                    AmbientLight = new Color(r, g, b);
                }
            }

            XmlNode materialsNode = document.SelectSingleNode("scene/materials");
            if(materialsNode != null)
            {
                foreach (XmlNode matCat in materialsNode.SelectNodes("category"))
                {
                    string catName = matCat.Attributes["name"].Value;
                    List<DXSMaterial> mats = new List<DXSMaterial>();
                    foreach (XmlNode matNode in matCat.SelectNodes("material"))
                    {
                        mats.Add(new DXSMaterial(matNode, context));
                    }
                    Materials.Add(catName, mats);
                }
            }

            foreach (XmlNode primNode in document.SelectNodes("scene/primitives/primitive"))
            {

                Primitives.Add(new DXSPrimitive(primNode, context));
                PrimitiveCount++;

            }

            foreach (XmlNode lightNode in document.SelectNodes("scene/lights/light"))
            {
                Lights.Add(new DXSLight(lightNode, context));
            }
        }
        public TextureDictionaryContent(XmlDocument xmlDocument, ContentImporterContext context)
        {
            TextureCollection = new Dictionary<string, TextureBoundsContent>();

            XmlNode pathNode = xmlDocument.SelectSingleNode("/TextureDictionary/TexturePath");
            TexturePath = pathNode.InnerText;

            XmlNodeList textureNodeList = xmlDocument.SelectNodes("/TextureDictionary/Texture");
            foreach (XmlNode textureNode in textureNodeList)
            {
                TextureBoundsContent textureBoundsContent = new TextureBoundsContent(textureNode, context);
                TextureCollection.Add(textureBoundsContent.Name, textureBoundsContent);
            }
        }
Esempio n. 15
0
        public NPCDataContent(XmlDocument document, ContentImporterContext context)
        {
            stringType = document.SelectSingleNode("npcdata").Attributes["type"].Value;

            XmlNode conversationsNode = document.SelectSingleNode("npcdata/conversations");

            if (conversationsNode != null)
            {
                foreach (XmlNode conversation in document.SelectNodes("npcdata/conversations/conversation")) {
                    conversations.Add(conversation.Attributes["trigger"].Value, conversation.Attributes["conversation_id"].Value);
                }

            }
        }
Esempio n. 16
0
        public MapObjectLayerContent(XmlNode node, ContentImporterContext context)
            : base(node, context)
        {
            if (node.Attributes["color"] != null)
            {
                // get the color string, removing the leading #
                string color = node.Attributes["color"].Value.Substring(1);

                // get the RGB individually
                string r = color.Substring(0, 2);
                string g = color.Substring(2, 2);
                string b = color.Substring(4, 2);

                // convert to the color
                Color = new Color(
                    (byte)int.Parse(r, NumberStyles.AllowHexSpecifier),
                    (byte)int.Parse(g, NumberStyles.AllowHexSpecifier),
                    (byte)int.Parse(b, NumberStyles.AllowHexSpecifier));
            }

            foreach (XmlNode objectNode in node.SelectNodes("object"))
            {
                MapObjectContent mapObjectContent = new MapObjectContent(objectNode, context);

                // Object names need to be unique for our lookup system, but Tiled
                // doesn't require unique names.
                string objectName = mapObjectContent.Name;
                int duplicateCount = 2;

                // if a object already has the same name...
                if (Objects.Find(o => o.Name == objectName) != null)
                {
                    // figure out a object name that does work
                    do
                    {
                        objectName = string.Format("{0}{1}", mapObjectContent.Name, duplicateCount);
                        duplicateCount++;
                    } while (Objects.Find(o => o.Name == objectName) != null);

                    // log a warning for the user to see
                    context.Logger.LogWarning(string.Empty, new ContentIdentity(), "Renaming object \"{0}\" to \"{1}\" in layer \"{2}\" to make a unique name.", mapObjectContent.Name, objectName, Name);

                    // save that name
                    mapObjectContent.Name = objectName;
                }

                Objects.Add(mapObjectContent);
            }
        }
 public TextureEntryContent(XmlNode xmlNode, ContentImporterContext context)
 {
     if (xmlNode.Attributes["dictionary"] != null && xmlNode.Attributes["name"] != null)
     {
         LoadPath = xmlNode.Attributes["dictionary"].Value;
         Name = xmlNode.Attributes["name"].Value;
         UseDictionary = true;
     }
     else
     {
         LoadPath = xmlNode.InnerText;
         Name = xmlNode.InnerText;
         UseDictionary = false;
     }
 }
Esempio n. 18
0
        /// <summary>
        /// Create the keyframe content.
        /// </summary>
        /// <param name="node">The xml node to get the information from.</param>
        /// <param name="context">The content importer context.</param>
        public KeyframeContent(XmlNode node, ContentImporterContext context)
        {
            //Create and instantiate the various variables.
            BonesToBe = new List<BoneContent>();

            //Parse the xml data.
            FrameNumber = int.Parse(node.Attributes["FrameNumber"].Value);

            //Go through all bone nodes in the xml node.
            foreach (XmlNode boneNode in node.SelectNodes("Bone"))
            {
                //Create a new bone content instance object and add it to the list.
                BonesToBe.Add(new BoneContent(boneNode, context));
            }
        }
Esempio n. 19
0
        public override NodeContent Import(string filename, ContentImporterContext context)
        {
            if (filename == null)
            {
                throw new ArgumentNullException("filename");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var importer = new OpenAssetImporter("FbxImporter", true);

            return(importer.Import(filename, context));
        }
Esempio n. 20
0
        public DXSMaterial(XmlNode node, ContentImporterContext context)
        {
            Id = node.Attributes["id"] != null ? int.Parse(node.Attributes["id"].Value) : 0;

            if (node.Attributes["name"] != null)
                Name = node.Attributes["name"].Value;
            if (node.Attributes["used"] != null)
                Used = bool.Parse(node.Attributes["used"].Value);
            if (node.Attributes["lightmap"] != null)
                Lightmap = bool.Parse(node.Attributes["lightmap"].Value);
            if (node.Attributes["castShadows"] != null)
                CastShadows = bool.Parse(node.Attributes["castShadows"].Value);
            if (node.Attributes["receiveShadows"] != null)
                ReceiveShadows = bool.Parse(node.Attributes["receiveShadows"].Value);
        }
Esempio n. 21
0
        private void Initialize(XmlNode node, ContentImporterContext context)
        {
            this.Name = node.Attributes["name"].Value;
            this.TileWidth = int.Parse(node.Attributes["tilewidth"].Value, CultureInfo.InvariantCulture);
            this.TileHeight = int.Parse(node.Attributes["tileheight"].Value, CultureInfo.InvariantCulture);

            if (node.Attributes["spacing"] != null)
            {
                this.Spacing = int.Parse(node.Attributes["spacing"].Value, CultureInfo.InvariantCulture);
            }

            if (node.Attributes["margin"] != null)
            {
                this.Margin = int.Parse(node.Attributes["margin"].Value, CultureInfo.InvariantCulture);
            }

            XmlNode imageNode = node["image"];
            this.Image = imageNode.Attributes["source"].Value;

            // if the image is in any director up from us, just take the filename
            if (this.Image.StartsWith(".."))
            {
                //this.Image = this.Image.Substring(this.Image.LastIndexOf("../") + 3);
                this.Image = Path.GetFileName(this.Image);
            }

            if (imageNode.Attributes["trans"] != null)
            {
                string color = imageNode.Attributes["trans"].Value;
                string r = color.Substring(0, 2);
                string g = color.Substring(2, 2);
                string b = color.Substring(4, 2);
                this.ColorKey = new Color((byte)Convert.ToInt32(r, 16), (byte)Convert.ToInt32(g, 16), (byte)Convert.ToInt32(b, 16));
            }
            foreach (XmlNode tileProperty in node.SelectNodes("tile"))
            {
                int id = this.FirstId + int.Parse(tileProperty.Attributes["id"].Value, CultureInfo.InvariantCulture);
                var properties = new PropertyCollection();

                XmlNode propertiesNode = tileProperty["properties"];
                if (propertiesNode != null)
                {
                    properties = new PropertyCollection(propertiesNode, context);
                }

                this.TileProperties.Add(id, properties);
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Create the animation content.
        /// </summary>
        /// <param name="xmlDocument">The Xml document to get the information from.</param>
        /// <param name="context">The content importer context.</param>
        public AnimationContent(XmlDocument xmlDocument, ContentImporterContext context)
        {
            //Create and instantiate the various variables.
            Keyframes = new List<KeyframeContent>();

            //Parse the xml data.
            FrameTime = float.Parse(xmlDocument.SelectSingleNode("/Animation/FrameTime").InnerText);
            NumberOfFrames = int.Parse(xmlDocument.SelectSingleNode("/Animation/NumberOfFrames").InnerText);

            //Go through all keyframe nodes in the xml document.
            foreach (XmlNode keyframeNode in xmlDocument.SelectNodes("/Animation/Keyframe"))
            {
                //Create a new keyframe content instance object and add it to the list.
                Keyframes.Add(new KeyframeContent(keyframeNode, context));
            }
        }
Esempio n. 23
0
        public static List<Property> ReadProperties(XmlNode node, ContentImporterContext context)
        {
            List<Property> properties = new List<Property>();

            foreach (XmlNode property in node.ChildNodes)
            {
                string name = property.Attributes["name"].Value;
                string value = property.Attributes["value"].Value;
                bool foundCopy = false;

                /*
                 * A bug in Tiled will sometimes cause the file to contain identical copies of properties.
                 * I would fix it, but I'd have to dig into the Tiled code. instead, we'll detect exact
                 * duplicates here and log some warnings, failing only if the value is actually different.
                 *
                 * To repro the bug, create two maps that use the same tileset. Open the first file in Tiled
                 * and set a property on a tile. Then open the second map and open the first back up. Look
                 * at the propertes on the tile. It will have two or three copies of the same property.
                 *
                 * If you encounter the bug, you can remedy it in Tiled by closing the current file (Ctrl-F4
                 * or use Close from the File menu) and then reopen it. The tile will no longer have the
                 * copies of the property.
                 */
                foreach (var p in properties)
                {
                    if (p.Name == name)
                    {
                        if (p.Value == value)
                        {
                            context.Logger.LogWarning("", new ContentIdentity(), "Multiple properties of name {0} found with value {1}", new object[] { name, value });
                            foundCopy = true;
                        }
                        else
                        {
                            throw new Exception(string.Format("Multiple properties of name {0} exist with different values: {1} and {2}", name, value, p.Value));
                        }
                    }
                }

                // we only want to add one copy of any duplicate properties
                if (!foundCopy)
                    properties.Add(new Property(name, value));
            }

            return properties;
        }
        public TileSetContent(XmlNode node, ContentImporterContext context)
        {
            FirstId = int.Parse(node.Attributes["firstgid"].Value, CultureInfo.InvariantCulture);
            Name = node.Attributes["name"].Value;
            TileWidth = int.Parse(node.Attributes["tilewidth"].Value, CultureInfo.InvariantCulture);
            TileHeight = int.Parse(node.Attributes["tileheight"].Value, CultureInfo.InvariantCulture);

            if (node.Attributes["spacing"] != null)
            {
                Spacing = int.Parse(node.Attributes["spacing"].Value, CultureInfo.InvariantCulture);
            }

            if (node.Attributes["margin"] != null)
            {
                Margin = int.Parse(node.Attributes["margin"].Value, CultureInfo.InvariantCulture);
            }

            XmlNode imageNode = node["image"];
            Image = imageNode.Attributes["source"].Value;

            // if the image is in any director up from us, just take the filename
            if (Image.StartsWith(".."))
                Image = Path.GetFileName(Image);

            if (imageNode.Attributes["trans"] != null)
            {
                string color = imageNode.Attributes["trans"].Value;
                string r = color.Substring(0, 2);
                string g = color.Substring(2, 2);
                string b = color.Substring(4, 2);
                ColorKey = new Color((byte)Convert.ToInt32(r, 16), (byte)Convert.ToInt32(g, 16), (byte)Convert.ToInt32(b, 16));
            }
            foreach (XmlNode tileProperty in node.SelectNodes("tile"))
            {
                int id = FirstId + int.Parse(tileProperty.Attributes["id"].Value, CultureInfo.InvariantCulture);
                List<Property> properties = new List<Property>();

                XmlNode propertiesNode = tileProperty["properties"];
                if (propertiesNode != null)
                {
                    properties = Property.ReadProperties(propertiesNode, context);
                }

                TileProperties.Add(id, properties);
            }
        }
Esempio n. 25
0
        public override NodeContent Import(string filename, ContentImporterContext context)
        {
            var identity = new ContentIdentity(filename, GetType().Name);

            using (var importer = new AssimpContext())
            {
                _scene = importer.ImportFile(filename,
                                             //PostProcessSteps.FindInstances | // No effect + slow?
                                             PostProcessSteps.FindInvalidData |
                                             PostProcessSteps.FlipUVs |
                                             PostProcessSteps.FlipWindingOrder |
                                             //PostProcessSteps.MakeLeftHanded | // Appears to just mess things up
                                             PostProcessSteps.JoinIdenticalVertices |
                                             PostProcessSteps.ImproveCacheLocality |
                                             PostProcessSteps.OptimizeMeshes |
                                             //PostProcessSteps.OptimizeGraph | // Will eliminate helper nodes
                                             PostProcessSteps.RemoveRedundantMaterials |
                                             PostProcessSteps.Triangulate
                                             );

                _globalInverseXform = _scene.RootNode.Transform;
                _globalInverseXform.Inverse();

                _rootNode = new NodeContent
                {
                    Name      = _scene.RootNode.Name,
                    Identity  = identity,
                    Transform = ToXna(_scene.RootNode.Transform)
                };

                _materials = ImportMaterials(identity, _scene);

                FindMeshes(_scene.RootNode, _scene.RootNode.Transform);

                if (_scene.HasAnimations)
                {
                    var skeleton = CreateSkeleton();
                    CreateAnimation(skeleton);
                }

                _scene.Clear();
            }

            return(_rootNode);
        }
Esempio n. 26
0
        /// <summary>
        /// Called by the XNA Framework when importing an texture file to be used as a game asset. This
        /// is the method called by the XNA Framework when an asset is to be imported into an object
        /// that can be recognized by the Content Pipeline.
        /// </summary>
        /// <param name="filename">Name of a game asset file.</param>
        /// <param name="context">
        /// Contains information for importing a game asset, such as a logger interface.
        /// </param>
        /// <returns>Resulting game asset.</returns>
        public override TextureContent Import(string filename, ContentImporterContext context)
        {
            string extension = Path.GetExtension(filename);
              if (extension != null)
              {
            Texture texture = null;
            if (extension.Equals(".DDS", StringComparison.OrdinalIgnoreCase))
            {
              using (var stream = File.OpenRead(filename))
            texture = DdsHelper.Load(stream, DdsFlags.ForceRgb | DdsFlags.ExpandLuminance);
            }
            else if (extension.Equals(".TGA", StringComparison.OrdinalIgnoreCase))
            {
              using (var stream = File.OpenRead(filename))
            texture = TgaHelper.Load(stream);
            }

            if (texture != null)
            {
            #if !MONOGAME
              // When using the XNA content pipeline, check for MonoGame content.
              if (!string.IsNullOrEmpty(ContentHelper.GetMonoGamePlatform()))
            #endif
              {
            // These formats are not (yet) available in MonoGame.
            switch (texture.Description.Format)
            {
              case DataFormat.B5G5R5A1_UNORM:  // (16-bit TGA files.)
              case DataFormat.R8_UNORM:
              case DataFormat.A8_UNORM:
                texture = texture.ConvertTo(DataFormat.R8G8B8A8_UNORM);
                break;
            }
              }

              // Convert DigitalRune Texture to XNA TextureContent.
              var identity = new ContentIdentity(filename, "DigitalRune");
              return TextureHelper.ToContent(texture, identity);
            }
              }

              return base.Import(filename, context);
        }
Esempio n. 27
0
        /// <summary>
        /// Called by the XNA Framework when importing an ogg audio file to be used as a game asset. This is the method called by the XNA Framework when an asset is to be imported into an object that can be recognized by the Content Pipeline.
        /// </summary>
        /// <param name="filename">Name of a game asset file.</param>
        /// <param name="context">Contains information for importing a game asset, such as a logger interface.</param>
        /// <returns>Resulting game asset.</returns>
        public override AudioContent Import(string filename, ContentImporterContext context)
        {
            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentNullException("filename");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (!File.Exists(filename))
            {
                throw new FileNotFoundException(string.Format("Could not locate audio file {0}.", Path.GetFileName(filename)));
            }

            var content = new AudioContent(filename, AudioFileType.Ogg);

            return(content);
        }
Esempio n. 28
0
        public TileLayerContent(XmlNode node, ContentImporterContext context)
            : base(node, context)
        {
            XmlNode dataNode = node["data"];
            Data = new uint[Width * Height];

            // figure out what encoding is being used, if any, and process
            // the data appropriately
            if (dataNode.Attributes["encoding"] != null)
            {
                string encoding = dataNode.Attributes["encoding"].Value;

                if (encoding == "base64")
                {
                    ReadAsBase64(node, dataNode);
                }
                else if (encoding == "csv")
                {
                    ReadAsCsv(node, dataNode);
                }
                else
                {
                    throw new Exception("Unknown encoding: " + encoding);
                }
            }
            else
            {
                // XML format simply lays out a lot of <tile gid="X" /> nodes inside of data.

                int i = 0;
                foreach (XmlNode tileNode in dataNode.SelectNodes("tile"))
                {
                    Data[i] = uint.Parse(tileNode.Attributes["gid"].Value, CultureInfo.InvariantCulture);
                    i++;
                }

                if (i != Data.Length)
                    throw new Exception("Not enough tile nodes to fill data");
            }
        }
Esempio n. 29
0
        public AnimationContent(XmlDocument xmlDocument, ContentImporterContext context)
        {
            Textures = new List<TextureEntryContent>();
            Keyframes = new List<KeyframeContent>();

            FrameRate = int.Parse(xmlDocument.SelectSingleNode("/Animation/FrameRate").InnerText);
            LoopFrame = int.Parse(xmlDocument.SelectSingleNode("/Animation/LoopFrame").InnerText);

            XmlNodeList textureNodeList = xmlDocument.SelectNodes("/Animation/Texture");
            foreach (XmlNode textureNode in textureNodeList)
            {
                TextureEntryContent textureEntryContent = new TextureEntryContent(textureNode, context);
                Textures.Add(textureEntryContent);
            }

            XmlNodeList keyframeNodeList = xmlDocument.SelectNodes("/Animation/Keyframe");
            foreach (XmlNode keyframeNode in keyframeNodeList)
            {
                KeyframeContent keyframeContent = new KeyframeContent(keyframeNode, context);
                Keyframes.Add(keyframeContent);
            }
        }
Esempio n. 30
0
        public LayerContent(XmlNode node, ContentImporterContext context)
        {
            Type = node.Name;
            Name = node.Attributes["name"].Value;
            Width = int.Parse(node.Attributes["width"].Value, CultureInfo.InvariantCulture);
            Height = int.Parse(node.Attributes["height"].Value, CultureInfo.InvariantCulture);

            if (node.Attributes["opacity"] != null)
            {
                Opacity = float.Parse(node.Attributes["opacity"].Value, CultureInfo.InvariantCulture);
            }

            if (node.Attributes["visible"] != null)
            {
                Visible = int.Parse(node.Attributes["visible"].Value, CultureInfo.InvariantCulture) == 1;
            }

            XmlNode propertiesNode = node["properties"];
            if (propertiesNode != null)
            {
                Properties = new PropertyCollection(propertiesNode, context);
            }
        }
Esempio n. 31
0
        public BoneContent(XmlNode xmlNode, ContentImporterContext context)
        {
            Name = xmlNode.Attributes["name"].Value;
            Hidden = bool.Parse(xmlNode.SelectSingleNode("Hidden").InnerText);
            ParentIndex = int.Parse(xmlNode.SelectSingleNode("ParentIndex").InnerText);
            TextureIndex = int.Parse(xmlNode.SelectSingleNode("TextureIndex").InnerText);
            Position = new Vector2(float.Parse(xmlNode.SelectSingleNode("Position/X").InnerText, CultureInfo.InvariantCulture),
                float.Parse(xmlNode.SelectSingleNode("Position/Y").InnerText, CultureInfo.InvariantCulture));
            Rotation = float.Parse(xmlNode.SelectSingleNode("Rotation").InnerText, CultureInfo.InvariantCulture);
            Scale = new Vector2(float.Parse(xmlNode.SelectSingleNode("Scale/X").InnerText, CultureInfo.InvariantCulture),
                float.Parse(xmlNode.SelectSingleNode("Scale/Y").InnerText, CultureInfo.InvariantCulture));

            XmlNode tempNode = xmlNode.SelectSingleNode("TextureFlipHorizontal");
            if (tempNode != null)
                TextureFlipHorizontal = bool.Parse(tempNode.InnerText);
            else
                TextureFlipHorizontal = false;
            tempNode = xmlNode.SelectSingleNode("TextureFlipVertical");
            if (tempNode != null)
                TextureFlipVertical = bool.Parse(tempNode.InnerText);
            else
                TextureFlipVertical = false;
        }
Esempio n. 32
0
        /// <summary>
        /// Called by the XNA Framework when importing a texture audio file to be used as a game asset. This is the method called by the XNA Framework when an asset is to be imported into an object that can be recognized by the Content Pipeline.
        /// </summary>
        /// <param name="filename">Name of a game asset file.</param>
        /// <param name="context">Contains information for importing a game asset, such as a logger interface.</param>
        /// <returns>Resulting game asset.</returns>
        public override TextureContent Import(string filename, ContentImporterContext context)
        {
            var output = new Texture2DContent();
            var bmp    = new Bitmap(filename);

            var bitmapContent = new PixelBitmapContent <Color>(bmp.Width, bmp.Height);

            var bitmapData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height),
                                          System.Drawing.Imaging.ImageLockMode.ReadOnly,
                                          System.Drawing.Imaging.PixelFormat.DontCare);

            var length    = bitmapData.Stride * bitmapData.Height;
            var imageData = new byte[length];

            // Copy bitmap to byte[]
            Marshal.Copy(bitmapData.Scan0, imageData, 0, length);
            bmp.UnlockBits(bitmapData);

            bitmapContent.SetPixelData(imageData);

            output.Faces[0].Add(bitmapContent);
            return(output);
        }
Esempio n. 33
0
 /// <summary>
 /// Create the skeleton content.
 /// </summary>
 /// <param name="xmlDocument">The Xml document to get the information from.</param>
 /// <param name="context">The content importer context.</param>
 public SkeletonContent(XmlDocument xmlDocument, ContentImporterContext context)
 {
     //You gotta' work harder!
 }
Esempio n. 34
0
        public override NodeContent Import(string filename, ContentImporterContext context)
        {
#if LINUX
            var targetDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName;

            try
            {
                AssimpLibrary.Instance.LoadLibrary(
                    Path.Combine(targetDir, "libassimp.so"),
                    Path.Combine(targetDir, "libassimp.so"));
            }
            catch { }
#endif

            _identity = new ContentIdentity(filename, string.IsNullOrEmpty(ImporterName) ? GetType().Name : ImporterName);

            using (var importer = new AssimpContext())
            {
                // FBXPreservePivotsConfig(false) can be set to remove transformation
                // pivots. However, Assimp does not automatically correct animations!
                // --> Leave default settings, handle transformation pivots explicitly.
                //importer.SetConfig(new Assimp.Configs.FBXPreservePivotsConfig(false));

                // Note about Assimp post-processing:
                // Keep post-processing to a minimum. The ModelImporter should import
                // the model as is. We don't want to lose any information, i.e. empty
                // nodes shoud not be thrown away, meshes/materials should not be merged,
                // etc. Custom model processors may depend on this information!
                _scene = importer.ImportFile(filename,
                                             PostProcessSteps.FindDegenerates |
                                             PostProcessSteps.FindInvalidData |
                                             PostProcessSteps.FlipUVs |          // Required for Direct3D
                                             PostProcessSteps.FlipWindingOrder | // Required for Direct3D
                                             PostProcessSteps.JoinIdenticalVertices |
                                             PostProcessSteps.ImproveCacheLocality |
                                             PostProcessSteps.OptimizeMeshes |
                                             PostProcessSteps.Triangulate

                                             // Unused:
                                             //PostProcessSteps.CalculateTangentSpace
                                             //PostProcessSteps.Debone |
                                             //PostProcessSteps.FindInstances |      // No effect + slow?
                                             //PostProcessSteps.FixInFacingNormals |
                                             //PostProcessSteps.GenerateNormals |
                                             //PostProcessSteps.GenerateSmoothNormals |
                                             //PostProcessSteps.GenerateUVCoords |
                                             //PostProcessSteps.LimitBoneWeights |
                                             //PostProcessSteps.MakeLeftHanded |     // Not necessary, XNA is right-handed.
                                             //PostProcessSteps.OptimizeGraph |      // Will eliminate helper nodes
                                             //PostProcessSteps.PreTransformVertices |
                                             //PostProcessSteps.RemoveComponent |
                                             //PostProcessSteps.RemoveRedundantMaterials |
                                             //PostProcessSteps.SortByPrimitiveType |
                                             //PostProcessSteps.SplitByBoneCount |
                                             //PostProcessSteps.SplitLargeMeshes |
                                             //PostProcessSteps.TransformUVCoords |
                                             //PostProcessSteps.ValidateDataStructure |
                                             );

                FindSkeleton();     // Find _rootBone, _bones, _deformationBones.
                ImportMaterials();  // Create _materials.
                ImportNodes();      // Create _pivots and _rootNode (incl. children).
                ImportSkeleton();   // Create skeleton (incl. animations) and add to _rootNode.

                // If we have a simple hierarchy with no bones and just the one
                // mesh, we can flatten it out so the mesh is the root node.
                if (_rootNode.Children.Count == 1 && _rootNode.Children[0] is MeshContent)
                {
                    var absXform = _rootNode.Children[0].AbsoluteTransform;
                    _rootNode           = _rootNode.Children[0];
                    _rootNode.Identity  = _identity;
                    _rootNode.Transform = absXform;
                }

                _scene.Clear();
            }

            return(_rootNode);
        }
Esempio n. 35
0
        /// <summary>
        /// Called by the XNA Framework when importing a .wmv file to be used as a game asset. This is the method called by the XNA Framework when an asset is to be imported into an object that can be recognized by the Content Pipeline.
        /// </summary>
        /// <param name="filename">Name of a game asset file.</param>
        /// <param name="context">Contains information for importing a game asset, such as a logger interface.</param>
        /// <returns>Resulting game asset.</returns>
        public override VideoContent Import(string filename, ContentImporterContext context)
        {
            var content = new VideoContent(filename);

            return(content);
        }
Esempio n. 36
0
        /// <summary>
        /// Called by the XNA Framework when importing a texture file to be used as a game asset. This is the method called by the XNA Framework when an asset is to be imported into an object that can be recognized by the Content Pipeline.
        /// </summary>
        /// <param name="filename">Name of a game asset file.</param>
        /// <param name="context">Contains information for importing a game asset, such as a logger interface.</param>
        /// <returns>Resulting game asset.</returns>
        public override TextureContent Import(string filename, ContentImporterContext context)
        {
            var ext = Path.GetExtension(filename).ToLower();

            // Special case for loading some formats
            switch (ext)
            {
            case ".dds":
                return(DdsLoader.Import(filename, context));

            case ".bmp":
                return(LoadImage(filename));
            }

            var output = new Texture2DContent {
                Identity = new ContentIdentity(filename)
            };

            FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
            var fBitmap = FreeImage.LoadEx(filename, FREE_IMAGE_LOAD_FLAGS.DEFAULT, ref format);

            //if freeimage can not recognize the image type
            if (format == FREE_IMAGE_FORMAT.FIF_UNKNOWN)
            {
                throw new ContentLoadException("TextureImporter failed to load '" + filename + "'");
            }
            //if freeimage can recognize the file headers but can't read its contents
            else if (fBitmap.IsNull)
            {
                throw new InvalidContentException("TextureImporter couldn't understand the contents of '" + filename + "'", output.Identity);
            }
            BitmapContent face   = null;
            var           height = (int)FreeImage.GetHeight(fBitmap);
            var           width  = (int)FreeImage.GetWidth(fBitmap);
            //uint bpp = FreeImage.GetBPP(fBitmap);
            var imageType = FreeImage.GetImageType(fBitmap);

            // Swizzle channels and expand to include an alpha channel
            fBitmap = ConvertAndSwapChannels(fBitmap, imageType);

            // The bits per pixel and image type may have changed
            uint bpp = FreeImage.GetBPP(fBitmap);

            imageType = FreeImage.GetImageType(fBitmap);
            var pitch     = (int)FreeImage.GetPitch(fBitmap);
            var redMask   = FreeImage.GetRedMask(fBitmap);
            var greenMask = FreeImage.GetGreenMask(fBitmap);
            var blueMask  = FreeImage.GetBlueMask(fBitmap);

            // Create the byte array for the data
            byte[] bytes = new byte[((width * height * bpp - 1) / 8) + 1];

            //Converts the pixel data to bytes, do not try to use this call to switch the color channels because that only works for 16bpp bitmaps
            FreeImage.ConvertToRawBits(bytes, fBitmap, pitch, bpp, redMask, greenMask, blueMask, true);
            // Create the Pixel bitmap content depending on the image type
            switch (imageType)
            {
            //case FREE_IMAGE_TYPE.FIT_BITMAP:
            default:
                face = new PixelBitmapContent <Color>(width, height);
                break;

            case FREE_IMAGE_TYPE.FIT_RGBA16:
                face = new PixelBitmapContent <Rgba64>(width, height);
                break;

            case FREE_IMAGE_TYPE.FIT_RGBAF:
                face = new PixelBitmapContent <Vector4>(width, height);
                break;
            }
            FreeImage.UnloadEx(ref fBitmap);

            face.SetPixelData(bytes);
            output.Faces[0].Add(face);
            return(output);
        }
Esempio n. 37
0
        /// <summary>
        /// Called by the XNA Framework when importing an ogg audio file to be used as a game asset. This is the method called by the XNA Framework when an asset is to be imported into an object that can be recognized by the Content Pipeline.
        /// </summary>
        /// <param name="filename">Name of a game asset file.</param>
        /// <param name="context">Contains information for importing a game asset, such as a logger interface.</param>
        /// <returns>Resulting game asset.</returns>
        public override AudioContent Import(string filename, ContentImporterContext context)
        {
            var content = new AudioContent(filename, AudioFileType.Wav);

            return(content);
        }
 public ConsoleEffectCompilerOutput(ContentImporterContext context)
 {
     this.context = context;
 }
Esempio n. 39
0
 /// <summary>
 /// Called by the XNA Framework when importing an intermediate file to be used as a game
 /// asset. This is the method called by the XNA Framework when an asset is to be imported
 /// into an object that can be recognized by the Content Pipeline.
 /// </summary>
 /// <param name="filename">Name of a game asset file.</param>
 /// <param name="context">Contains information for importing a game asset, such as a logger interface.</param>
 /// <returns>The imported game asset.</returns>
 public override object Import(string filename, ContentImporterContext context)
 {
     using (var reader = XmlReader.Create(filename))
         return(IntermediateSerializer.Deserialize <object>(reader, filename));
 }
Esempio n. 40
0
        static internal TextureContent Import(string filename, ContentImporterContext context)
        {
            var            identity = new ContentIdentity(filename);
            TextureContent output   = null;

            using (var reader = new BinaryReader(new FileStream(filename, FileMode.Open, FileAccess.Read)))
            {
                // Read signature ("DDS ")
                var valid = reader.ReadByte() == 0x44;
                valid = valid && reader.ReadByte() == 0x44;
                valid = valid && reader.ReadByte() == 0x53;
                valid = valid && reader.ReadByte() == 0x20;
                if (!valid)
                {
                    throw new ContentLoadException("Invalid file signature");
                }

                var header = new DdsHeader();

                // Read DDS_HEADER
                header.dwSize = reader.ReadUInt32();
                if (header.dwSize != 124)
                {
                    throw new ContentLoadException("Invalid DDS_HEADER dwSize value");
                }
                header.dwFlags             = (Ddsd)reader.ReadUInt32();
                header.dwHeight            = reader.ReadUInt32();
                header.dwWidth             = reader.ReadUInt32();
                header.dwPitchOrLinearSize = reader.ReadUInt32();
                header.dwDepth             = reader.ReadUInt32();
                header.dwMipMapCount       = reader.ReadUInt32();
                // The next 11 DWORDs are reserved and unused
                for (int i = 0; i < 11; ++i)
                {
                    reader.ReadUInt32();
                }
                // Read DDS_PIXELFORMAT
                header.ddspf.dwSize = reader.ReadUInt32();
                if (header.ddspf.dwSize != 32)
                {
                    throw new ContentLoadException("Invalid DDS_PIXELFORMAT dwSize value");
                }
                header.ddspf.dwFlags       = (Ddpf)reader.ReadUInt32();
                header.ddspf.dwFourCC      = (FourCC)reader.ReadUInt32();
                header.ddspf.dwRgbBitCount = reader.ReadUInt32();
                header.ddspf.dwRBitMask    = reader.ReadUInt32();
                header.ddspf.dwGBitMask    = reader.ReadUInt32();
                header.ddspf.dwBBitMask    = reader.ReadUInt32();
                header.ddspf.dwABitMask    = reader.ReadUInt32();
                // Continue reading DDS_HEADER
                header.dwCaps  = (DdsCaps)reader.ReadUInt32();
                header.dwCaps2 = (DdsCaps2)reader.ReadUInt32();
                // dwCaps3 unused
                reader.ReadUInt32();
                // dwCaps4 unused
                reader.ReadUInt32();
                // dwReserved2 unused
                reader.ReadUInt32();

                // Check for the existence of the DDS_HEADER_DXT10 struct next
                if (header.ddspf.dwFlags == Ddpf.FourCC && header.ddspf.dwFourCC == FourCC.Dx10)
                {
                    throw new ContentLoadException("Unsupported DDS_HEADER_DXT10 struct found");
                }

                int faceCount   = 1;
                int mipMapCount = (int)(header.dwCaps.HasFlag(DdsCaps.MipMap) ? header.dwMipMapCount : 1);
                if (header.dwCaps.HasFlag(DdsCaps.Complex))
                {
                    if (header.dwCaps2.HasFlag(DdsCaps2.Cubemap))
                    {
                        if (!header.dwCaps2.HasFlag(DdsCaps2.CubemapAllFaces))
                        {
                            throw new ContentLoadException("Incomplete cubemap in DDS file");
                        }
                        faceCount = 6;
                        output    = new TextureCubeContent()
                        {
                            Identity = identity
                        };
                    }
                    else
                    {
                        output = new Texture2DContent()
                        {
                            Identity = identity
                        };
                    }
                }
                else
                {
                    output = new Texture2DContent()
                    {
                        Identity = identity
                    };
                }

                bool rbSwap;
                var  format = GetSurfaceFormat(ref header.ddspf, out rbSwap);

                for (int f = 0; f < faceCount; ++f)
                {
                    var w       = (int)header.dwWidth;
                    var h       = (int)header.dwHeight;
                    var mipMaps = new MipmapChain();
                    for (int m = 0; m < mipMapCount; ++m)
                    {
                        var content   = CreateBitmapContent(format, w, h);
                        var byteCount = GetBitmapSize(format, w, h);
                        var bytes     = reader.ReadBytes(byteCount);
                        content.SetPixelData(bytes);
                        mipMaps.Add(content);
                        w = MathHelper.Max(1, w / 2);
                        h = MathHelper.Max(1, h / 2);
                    }
                    output.Faces[f] = mipMaps;
                }
            }

            return(output);
        }
Esempio n. 41
0
        public override NodeContent Import(string filename, ContentImporterContext context)
        {
            var importer = new OpenAssetImporter();

            return(importer.Import(filename, context));
        }
Esempio n. 42
0
 /// <summary>
 /// Called by the XNA Framework when importing a .wav audio file to be used as a game asset. This is the method called by the XNA Framework when an asset is to be imported into an object that can be recognized by the Content Pipeline.
 /// </summary>
 /// <param name="filename">Name of a game asset file.</param>
 /// <param name="context">Contains information for importing a game asset, such as a logger interface.</param>
 /// <returns>Resulting game asset.</returns>
 public override AudioContent Import(string filename, ContentImporterContext context)
 {
     throw new NotImplementedException();
 }
Esempio n. 43
0
 public abstract T Import(string filename, ContentImporterContext context);
Esempio n. 44
0
 object IContentImporter.Import(string filename, ContentImporterContext context)
 {
     return(Import(filename, context));
 }
Esempio n. 45
0
        static internal TextureContent Import(string filename, ContentImporterContext context)
        {
            var identity = new ContentIdentity(filename);
            TextureContent output = null;

            using (var reader = new BinaryReader(new FileStream(filename, FileMode.Open, FileAccess.Read)))
            {
                // Read signature ("DDS ")
                var valid = reader.ReadByte() == 0x44;
                valid = valid && reader.ReadByte() == 0x44;
                valid = valid && reader.ReadByte() == 0x53;
                valid = valid && reader.ReadByte() == 0x20;
                if (!valid)
                    throw new ContentLoadException("Invalid file signature");

                var header = new DdsHeader();

                // Read DDS_HEADER
                header.dwSize = reader.ReadUInt32();
                if (header.dwSize != 124)
                    throw new ContentLoadException("Invalid DDS_HEADER dwSize value");
                header.dwFlags = (Ddsd)reader.ReadUInt32();
                header.dwHeight = reader.ReadUInt32();
                header.dwWidth = reader.ReadUInt32();
                header.dwPitchOrLinearSize = reader.ReadUInt32();
                header.dwDepth = reader.ReadUInt32();
                header.dwMipMapCount = reader.ReadUInt32();
                // The next 11 DWORDs are reserved and unused
                for (int i = 0; i < 11; ++i)
                    reader.ReadUInt32();
                // Read DDS_PIXELFORMAT
                header.ddspf.dwSize = reader.ReadUInt32();
                if (header.ddspf.dwSize != 32)
                    throw new ContentLoadException("Invalid DDS_PIXELFORMAT dwSize value");
                header.ddspf.dwFlags = (Ddpf)reader.ReadUInt32();
                header.ddspf.dwFourCC = (FourCC)reader.ReadUInt32();
                header.ddspf.dwRgbBitCount = reader.ReadUInt32();
                header.ddspf.dwRBitMask = reader.ReadUInt32();
                header.ddspf.dwGBitMask = reader.ReadUInt32();
                header.ddspf.dwBBitMask = reader.ReadUInt32();
                header.ddspf.dwABitMask = reader.ReadUInt32();
                // Continue reading DDS_HEADER
                header.dwCaps = (DdsCaps)reader.ReadUInt32();
                header.dwCaps2 = (DdsCaps2)reader.ReadUInt32();
                // dwCaps3 unused
                reader.ReadUInt32();
                // dwCaps4 unused
                reader.ReadUInt32();
                // dwReserved2 unused
                reader.ReadUInt32();

                // Check for the existence of the DDS_HEADER_DXT10 struct next
                if (header.ddspf.dwFlags == Ddpf.FourCC && header.ddspf.dwFourCC == FourCC.Dx10)
                {
                    throw new ContentLoadException("Unsupported DDS_HEADER_DXT10 struct found");
                }

                int faceCount = 1;
                int mipMapCount = (int)(header.dwCaps.HasFlag(DdsCaps.MipMap) ? header.dwMipMapCount : 1);
                if (header.dwCaps.HasFlag(DdsCaps.Complex))
                {
                    if (header.dwCaps2.HasFlag(DdsCaps2.Cubemap))
                    {
                        if (!header.dwCaps2.HasFlag(DdsCaps2.CubemapAllFaces))
                            throw new ContentLoadException("Incomplete cubemap in DDS file");
                        faceCount = 6;
                        output = new TextureCubeContent() { Identity = identity };
                    }
                    else
                    {
                        output = new Texture2DContent() { Identity = identity };
                    }
                }
                else
                {
                    output = new Texture2DContent() { Identity = identity };
                }

                bool rbSwap;
                var format = GetSurfaceFormat(ref header.ddspf, out rbSwap);

                for (int f = 0; f < faceCount; ++f)
                {
                    var w = (int)header.dwWidth;
                    var h = (int)header.dwHeight;
                    var mipMaps = new MipmapChain();
                    for (int m = 0; m < mipMapCount; ++m)
                    {
                        var content = CreateBitmapContent(format, w, h);
                        var byteCount = GetBitmapSize(format, w, h);
                        var bytes = reader.ReadBytes(byteCount);
                        content.SetPixelData(bytes);
                        mipMaps.Add(content);
                        w = MathHelper.Max(1, w / 2);
                        h = MathHelper.Max(1, h / 2);
                    }
                    output.Faces[f] = mipMaps;
                }
            }

            return output;
        }
Esempio n. 46
0
        /// <summary>
        /// Called by the XNA Framework when importing a .spritefont file to be used as a game asset. This is the method called by the XNA Framework when an asset is to be imported into an object that can be recognized by the Content Pipeline.
        /// </summary>
        /// <param name="filename">Name of a game asset file.</param>
        /// <param name="context">Contains information for importing a game asset, such as a logger interface.</param>
        /// <returns>Resulting game asset.</returns>
        public override FontDescription Import(string filename, ContentImporterContext context)
        {
            var xmldoc = XElement.Load(filename, LoadOptions.PreserveWhitespace);

            xmldoc = xmldoc.Element("Asset");

            var fontName          = xmldoc.Element("FontName").Value;
            var fontSize          = float.Parse(xmldoc.Element("Size").Value);
            var spacing           = float.Parse(xmldoc.Element("Spacing").Value);
            var useKerning        = false;
            var useKerningElement = xmldoc.Element("UseKerning");

            if (useKerningElement != null)
            {
                useKerning = bool.Parse(useKerningElement.Value);
            }

            FontDescriptionStyle style = FontDescriptionStyle.Regular;
            var styleElement           = xmldoc.Element("Style");

            if (styleElement != null)
            {
                var styleVal = styleElement.Value;

                if (styleVal.Contains("Bold") && styleVal.Contains("Italic"))
                {
                    style = FontDescriptionStyle.Bold | FontDescriptionStyle.Italic;
                }
                else
                {
                    style = (FontDescriptionStyle)Enum.Parse(typeof(FontDescriptionStyle), styleVal, false);
                }
            }

            char?defaultCharacter = null;
            var  defChar          = xmldoc.Element("DefaultCharacter");

            if (defChar != null)
            {
                defaultCharacter = defChar.Value[0];
            }

            var characterRegions = new List <CharacterRegion> ();

            foreach (var region in xmldoc.Descendants("CharacterRegion"))
            {
                var Start = (int)region.Element("Start").Value[0];
                var End   = (int)region.Element("End").Value[0];

                characterRegions.Add(new CharacterRegion((char)Start, (char)End));
            }

            var characters = new CharacterCollection();

            foreach (var r in characterRegions)
            {
                foreach (var c in r.Characters)
                {
                    characters.Add(c);
                }
            }

            var fontDescription = new FontDescription(fontName, fontSize, spacing, style, useKerning);

            fontDescription.Characters       = characters;
            fontDescription.DefaultCharacter = defaultCharacter;
            fontDescription.Identity         = new ContentIdentity(filename);
            return(fontDescription);
        }
Esempio n. 47
0
        public MapContent(XmlDocument document, ContentImporterContext context)
        {
            XmlNode mapNode = document["map"];

            Version = mapNode.Attributes["version"].Value;
            Orientation = (Orientation)Enum.Parse(typeof(Orientation), mapNode.Attributes["orientation"].Value, true);
            Width = int.Parse(mapNode.Attributes["width"].Value, CultureInfo.InvariantCulture);
            Height = int.Parse(mapNode.Attributes["height"].Value, CultureInfo.InvariantCulture);
            TileWidth = int.Parse(mapNode.Attributes["tilewidth"].Value, CultureInfo.InvariantCulture);
            TileHeight = int.Parse(mapNode.Attributes["tileheight"].Value, CultureInfo.InvariantCulture);

            XmlNode propertiesNode = document.SelectSingleNode("map/properties");
            if (propertiesNode != null)
            {
                Properties = Property.ReadProperties(propertiesNode, context);
            }

            foreach (XmlNode tileSet in document.SelectNodes("map/tileset"))
            {
                if (tileSet.Attributes["source"] != null)
                {
                    TileSets.Add(new ExternalTileSetContent(tileSet, context));
                }
                else
                {
                    TileSets.Add(new TileSetContent(tileSet, context));
                }
            }

            foreach (XmlNode layerNode in document.SelectNodes("map/layer|map/objectgroup"))
            {
                LayerContent layerContent;

                if (layerNode.Name == "layer")
                {
                    layerContent = new TileLayerContent(layerNode, context);
                }
                else if (layerNode.Name == "objectgroup")
                {
                    layerContent = new MapObjectLayerContent(layerNode, context);
                }
                else
                {
                    throw new Exception("Unknown layer name: " + layerNode.Name);
                }

                // Layer names need to be unique for our lookup system, but Tiled
                // doesn't require unique names.
                string layerName = layerContent.Name;
                int duplicateCount = 2;

                // if a layer already has the same name...
                if (Layers.Find(l => l.Name == layerName) != null)
                {
                    // figure out a layer name that does work
                    do
                    {
                        layerName = string.Format("{0}{1}", layerContent.Name, duplicateCount);
                        duplicateCount++;
                    } while (Layers.Find(l => l.Name == layerName) != null);

                    // log a warning for the user to see
                    context.Logger.LogWarning(string.Empty, new ContentIdentity(), "Renaming layer \"{1}\" to \"{2}\" to make a unique name.", layerContent.Type, layerContent.Name, layerName);

                    // save that name
                    layerContent.Name = layerName;
                }

                Layers.Add(layerContent);
            }
        }
 public ExternalTileSetContent(XmlNode node, ContentImporterContext context)
     : base(node, context)
 {
 }
Esempio n. 49
0
        public override NodeContent Import(string filename, ContentImporterContext context)
        {
            var identity = new ContentIdentity(filename, GetType().Name);
            var importer = new AssimpImporter();

            importer.AttachLogStream(new LogStream((msg, userData) => context.Logger.LogMessage(msg)));
            var scene = importer.ImportFile(filename,
                                            PostProcessSteps.FlipUVs | // So far appears necessary
                                            PostProcessSteps.JoinIdenticalVertices |
                                            PostProcessSteps.Triangulate |
                                            PostProcessSteps.SortByPrimitiveType |
                                            PostProcessSteps.FindInvalidData
                                            );

            var rootNode = new NodeContent
            {
                Name      = scene.RootNode.Name,
                Identity  = identity,
                Transform = ToXna(scene.RootNode.Transform)
            };

            // TODO: Materials
            var materials = new List <MaterialContent>();

            foreach (var sceneMaterial in scene.Materials)
            {
                var diffuse = sceneMaterial.GetTexture(TextureType.Diffuse, 0);

                materials.Add(new BasicMaterialContent()
                {
                    Name     = sceneMaterial.Name,
                    Identity = identity,
                    Texture  = new ExternalReference <TextureContent>(diffuse.FilePath, identity)
                });
            }

            // Meshes
            var meshes = new Dictionary <Mesh, MeshContent>();

            foreach (var sceneMesh in scene.Meshes)
            {
                if (!sceneMesh.HasVertices)
                {
                    continue;
                }

                var mesh = new MeshContent
                {
                    Name = sceneMesh.Name
                };

                // Position vertices are shared at the mesh level
                foreach (var vert in sceneMesh.Vertices)
                {
                    mesh.Positions.Add(new Vector3(vert.X, vert.Y, vert.Z));
                }

                var geom = new GeometryContent
                {
                    Name = string.Empty,
                    //Material = materials[sceneMesh.MaterialIndex]
                };

                // Geometry vertices reference 1:1 with the MeshContent parent,
                // no indirection is necessary.
                geom.Vertices.Positions.AddRange(mesh.Positions);
                geom.Vertices.AddRange(Enumerable.Range(0, sceneMesh.VertexCount));
                geom.Indices.AddRange(sceneMesh.GetIntIndices());

                // Individual channels go here
                if (sceneMesh.HasNormals)
                {
                    geom.Vertices.Channels.Add(VertexChannelNames.Normal(), ToXna(sceneMesh.Normals));
                }

                for (var i = 0; i < sceneMesh.TextureCoordsChannelCount; i++)
                {
                    geom.Vertices.Channels.Add(VertexChannelNames.TextureCoordinate(i),
                                               ToXnaVector2(sceneMesh.GetTextureCoords(i)));
                }

                mesh.Geometry.Add(geom);
                rootNode.Children.Add(mesh);
                meshes.Add(sceneMesh, mesh);
            }

            // Bones
            var bones          = new Dictionary <Node, BoneContent>();
            var hierarchyNodes = scene.RootNode.Children.SelectDeep(n => n.Children).ToList();

            foreach (var node in hierarchyNodes)
            {
                var bone = new BoneContent
                {
                    Name      = node.Name,
                    Transform = Matrix.Transpose(ToXna(node.Transform))
                };

                if (node.Parent == scene.RootNode)
                {
                    rootNode.Children.Add(bone);
                }
                else
                {
                    var parent = bones[node.Parent];
                    parent.Children.Add(bone);
                }

                // Copy the bone's name to the MeshContent - this appears to be
                // the way it comes out of XNA's FBXImporter.
                foreach (var meshIndex in node.MeshIndices)
                {
                    meshes[scene.Meshes[meshIndex]].Name = node.Name;
                }

                bones.Add(node, bone);
            }

            return(rootNode);
        }