Ejemplo n.º 1
0
        public XACTPatch(ContentReader input)
        {
            try
            {
                input.ReadByte();
                char[] header = input.ReadChars(4);
                if ( string.Compare( new string(header), "S**T" ) != 0 )
                    throw new Exception( "Caught Exception: Binary not in S**T format!" );
                int count = input.ReadInt32();
                if ( count > 128 ) count = 128; // Cap the maximum number of instruments
                for ( uint i = 0; i < count; ++i )
                {
                    _InstrumentInfo info = new _InstrumentInfo();
                    info.Name = input.ReadString();

                    byte flags = input.ReadByte();
                    info.Repeat = false; info.StretchRange = false;
                    if ((flags & 0x80) > 0) info.Repeat = true;      //if repeat
                    if ((flags & 0x40) > 0) info.StretchRange = true; //if range
                    int patchNumber = (int)(flags & 0x0F);
                    //info.PatchNumber = (byte)(flags & 0x0F);

                    info.AttackSpeed = input.ReadByte();
                    info.ReleaseSpeed = input.ReadByte();

                    m_Instruments[patchNumber] = info;
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Ejemplo n.º 2
0
        public static VGFontData Deserialize(ContentReader reader)
        {
            var data = new VGFontData
            {
                FillRule = (VGFillRule)reader.ReadByte(),
                EmSquareSize = reader.ReadSingle(),
                LeadingSize = reader.ReadSingle(),
                Extents = reader.ReadVector4(),
                Vertices = new StencilVertex[reader.ReadInt32()],
                Glyphs = new VGFontData.GlyphInfo[reader.ReadInt32()]
            };

            for (int i = 0; i < data.Vertices.Length; i++)
                data.Vertices[i] = StencilVertex.Deserialize(reader);

            for (int i = 0; i < data.Glyphs.Length; i++)
                data.Glyphs[i] = new VGFontData.GlyphInfo
                {
                    Character = reader.ReadChar(),
                    Offset = reader.ReadInt32(),
                    Triangles = reader.ReadInt32(),
                    Escape = new Vector2
                    {
                        X = reader.ReadSingle(),
                        Y = reader.ReadSingle()
                    }
                };

            data.Kerning = VGKerningTable.Deserialize(reader);
            return data;
        }
Ejemplo n.º 3
0
        public ContentTypeReader[] LoadAssetReaders(ContentReader reader)
        {
            int numberOfReaders;
            ContentTypeReader[] contentReaders;

            // The first 4 bytes should be the "XNBw" header. i use that to detect an invalid file
            byte[] headerBuffer = new byte[4];
            reader.Read(headerBuffer, 0, 4);

            string headerString = Encoding.UTF8.GetString(headerBuffer, 0, 4);
            if (string.Compare(headerString, "XNBw", StringComparison.InvariantCultureIgnoreCase) != 0)
            {
                throw new ContentLoadException("Asset does not appear to be a valid XNB file. Did you process your content for Windows?");
            }

            // I think these two bytes are some kind of version number. Either for the XNB file or the type readers
            /*byte version =*/ reader.ReadByte();
            byte compressed = reader.ReadByte();
            // The next int32 is the length of the XNB file
            /*int xnbLength = */reader.ReadInt32();

            if (compressed != 0)
            {
                throw new NotImplementedException("MonoGame cannot read compressed XNB files. Please use the XNB files from the Debug build of your XNA game instead. If someone wants to contribute decompression logic, that would be fantastic.");
            }

            // The next byte i read tells me the number of content readers in this XNB file
            numberOfReaders = reader.ReadByte();
            contentReaders = new ContentTypeReader[numberOfReaders];

            // For each reader in the file, we read out the length of the string which contains the type of the reader,
            // then we read out the string. Finally we instantiate an instance of that reader using reflection
            for (int i = 0; i < numberOfReaders; i++)
            {
                // This string tells us what reader we need to decode the following data
                // string readerTypeString = reader.ReadString();
                string originalReaderTypeString = reader.ReadString();

                // Need to resolve namespace differences
                string readerTypeString = originalReaderTypeString;

                readerTypeString = PrepareType(readerTypeString);

                Type l_readerType = Type.GetType(readerTypeString);

                if (l_readerType != null)
                    contentReaders[i] = (ContentTypeReader)Activator.CreateInstance(l_readerType, true);
                else
                {
                    throw new ContentLoadException("Could not find matching content reader of type " + originalReaderTypeString + " (" + readerTypeString + ")");
                }

                // I think the next 4 bytes refer to the "Version" of the type reader,
                // although it always seems to be zero
                /*int typeReaderVersion =*/ reader.ReadInt32();
            }

            return contentReaders;
        }
Ejemplo n.º 4
0
        internal Map(ContentReader reader)
        {
            // read in the basic map information
            Version = new Version(reader.ReadString());
            Orientation = (Orientation)reader.ReadByte();
            Width = reader.ReadInt32();
            Height = reader.ReadInt32();
            TileWidth = reader.ReadInt32();
            TileHeight = reader.ReadInt32();
            Properties = new PropertyCollection();
            Properties.Read(reader);

            // create a list for our tiles
            List<Tile> tiles = new List<Tile>();
            Tiles = new Collection<Tile>(tiles);

            // read in each tile set
            int numTileSets = reader.ReadInt32();
            for (int i = 0; i < numTileSets; i++)
            {
                // get the id and texture
                int firstId = reader.ReadInt32();
                string tilesetName = reader.ReadString();

                bool collisionSet = reader.ReadBoolean();

                Texture2D texture = reader.ReadExternalReference<Texture2D>();

                // read in each individual tile
                int numTiles = reader.ReadInt32();
                for (int j = 0; j < numTiles; j++)
                {
                    int id = firstId + j;

                    // Read the source rectangle from the file.
                    Rectangle source = reader.ReadObject<Rectangle>();

                    PropertyCollection props = new PropertyCollection();
                    props.Read(reader);

                    // Read in color data for collision purposes
                    // You'll probably want to limit this to just the tilesets that are used for collision
                    // I'm checking for the name of my tileset that contains wall tiles
                    // Color data takes up a fair bit of RAM
                    Color[] collisionData = null;
                    bool[] collisionBitData = null;
                    if (collisionSet)
                    {
                        int numOfBytes = TileWidth * TileHeight;
                        collisionData = new Color[numOfBytes];
                        collisionBitData = new bool[numOfBytes];

                        texture.GetData<Color>(
                            0,
                            source,
                            collisionData,
                            0,
                            numOfBytes
                        );

                        for (int col = 0; col < numOfBytes; col++)
                        {
                            if (collisionData[col].A > 0)
                            {
                                collisionBitData[col] = true;
                            }
                        }
                        collisionData = null;
                    }

                    Tile t = new Tile(texture, source, props, collisionBitData);
                    while (id >= tiles.Count)
                    {
                        tiles.Add(null);
                    }
                    tiles.Insert(id, t);
                }
            }

            // read in all the layers
            List<Layer> layers = new List<Layer>();
            Layers = new Collection<Layer>(layers);
            int numLayers = reader.ReadInt32();
            for (int i = 0; i < numLayers; i++)
            {
                Layer layer = null;

                // read generic layer data
                string type = reader.ReadString();
                string name = reader.ReadString();
                int width = reader.ReadInt32();
                int height = reader.ReadInt32();
                bool visible = reader.ReadBoolean();
                float opacity = reader.ReadSingle();
                PropertyCollection props = new PropertyCollection();
                props.Read(reader);

                // using the type, figure out which object to create
                if (type == "layer")
                {
                    int[] data = reader.ReadObject<int[]>();
                    layer = new TileLayer(name, width, height, visible, opacity, props, this, data);
                }
                else if (type == "objectgroup")
                {
                    List<MapObject> objects = new List<MapObject>();

                    // read in all of our objects
                    int numObjects = reader.ReadInt32();
                    for (int j = 0; j < numObjects; j++)
                    {
                        string objName = reader.ReadString();
                        string objType = reader.ReadString();
                        Rectangle objLoc = reader.ReadObject<Rectangle>();
                        List<Point> objPoints = reader.ReadObject<List<Point>>();
                        PropertyCollection objProps = new PropertyCollection();
                        objProps.Read(reader);

                        objects.Add(new MapObject(objName, objType, objLoc, objPoints, objProps));
                    }

                    layer = new MapObjectLayer(name, width, height, visible, opacity, props, objects);
                }
                else
                {
                    throw new Exception("Invalid type: " + type);
                }

                layers.Add(layer);
                namedLayers.Add(name, layer);
            }
        }
Ejemplo n.º 5
0
        internal Map(ContentReader reader)
        {
            // read in the basic map information
            Version = new Version(reader.ReadString());
            Orientation = (Orientation)reader.ReadByte();
            WidthInTiles = reader.ReadInt32();
            HeightInTiles = reader.ReadInt32();
            TileWidth = reader.ReadInt32();
            TileHeight = reader.ReadInt32();
            Properties = new PropertyCollection(reader);
            bool makeTilesUnique = reader.ReadBoolean();

            // create a list for our tiles
            List<Tile> tiles = new List<Tile>();
            Tiles = new ReadOnlyCollection<Tile>(tiles);

            // read in each tile set
            int numTileSets = reader.ReadInt32();
            for (int i = 0; i < numTileSets; i++)
            {
                // get the id and texture
                int firstId = reader.ReadInt32();
                Texture2D texture = reader.ReadExternalReference<Texture2D>();

                // read in each individual tile
                int numTiles = reader.ReadInt32();
                for (int j = 0; j < numTiles; j++)
                {
                    int id = firstId + j;
                    Rectangle source = reader.ReadObject<Rectangle>();
                    PropertyCollection props = new PropertyCollection(reader);

                    Tile t = new Tile(texture, source, props);
                    while (id >= tiles.Count)
                    {
                        tiles.Add(null);
                    }
                    tiles.Insert(id, t);
                }
            }

            // read in all the layers
            List<Layer> layers = new List<Layer>();
            Layers = new ReadOnlyCollection<Layer>(layers);
            int numLayers = reader.ReadInt32();
            for (int i = 0; i < numLayers; i++)
            {
                Layer layer = null;

                // read generic layer data
                string type = reader.ReadString();
                string name = reader.ReadString();
                int width = reader.ReadInt32();
                int height = reader.ReadInt32();
                bool visible = reader.ReadBoolean();
                float opacity = reader.ReadSingle();
                PropertyCollection props = new PropertyCollection(reader);

                // calculate the default layer depth of the layer
                float layerDepth = 1f - (LayerDepthSpacing * i);

                // using the type, figure out which object to create
                if (type == "layer")
                {
                    uint[] data = reader.ReadObject<uint[]>();
                    layer = new TileLayer(name, width, height, layerDepth, visible, opacity, props, this, data, makeTilesUnique);
                }
                else if (type == "objectgroup")
                {
                    List<MapObject> objects = new List<MapObject>();

                    // read in all of our objects
                    int numObjects = reader.ReadInt32();
                    for (int j = 0; j < numObjects; j++)
                    {
                        string objName = reader.ReadString();
                        string objType = reader.ReadString();
                        Rectangle objLoc = reader.ReadObject<Rectangle>();
                        PropertyCollection objProps = new PropertyCollection(reader);

                        objects.Add(new MapObject(objName, objType, objLoc, objProps));
                    }

                    layer = new MapObjectLayer(name, width, height, layerDepth, visible, opacity, props, objects);

                    // read in the layer's color
                    (layer as MapObjectLayer).Color = reader.ReadColor();
                }
                else
                {
                    throw new Exception("Invalid type: " + type);
                }

                layers.Add(layer);
                namedLayers.Add(name, layer);
            }
        }
        public ContentTypeReader[] LoadAssetReaders(ContentReader reader)
        {
            // Dummy variables required for it to work on iDevices ** DO NOT DELETE **
            // This forces the classes not to be optimized out when deploying to iDevices
            ListReader<Char> hCharListReader = new ListReader<Char>();
            ListReader<Rectangle> hRectangleListReader = new ListReader<Rectangle>();
            ListReader<Vector3> hVector3ListReader = new ListReader<Vector3>();
            ListReader<StringReader> hStringListReader = new ListReader<StringReader>();
            SpriteFontReader hSpriteFontReader = new SpriteFontReader();
            Texture2DReader hTexture2DReader = new Texture2DReader();
            CharReader hCharReader = new CharReader();
            RectangleReader hRectangleReader = new RectangleReader();
            StringReader hStringReader = new StringReader();
            Vector3Reader hVector3Reader = new Vector3Reader();
            int numberOfReaders;
            ContentTypeReader[] contentReaders;

            // The first 4 bytes should be the "XNBw" header. i use that to detect an invalid file
            byte[] headerBuffer = new byte[4];
            reader.Read(headerBuffer, 0, 4);

            string headerString = Encoding.UTF8.GetString(headerBuffer, 0, 4);
            if (string.Compare(headerString, "XNBw", StringComparison.InvariantCultureIgnoreCase) != 0 &&
                string.Compare(headerString, "XNBx", StringComparison.InvariantCultureIgnoreCase) != 0 &&
                string.Compare(headerString, "XNBm", StringComparison.InvariantCultureIgnoreCase) != 0)
                throw new ContentLoadException("Asset does not appear to be a valid XNB file. Did you process your content for Windows?");

            // I think these two bytes are some kind of version number. Either for the XNB file or the type readers
            byte version = reader.ReadByte();

            if(version != 5)
                throw new ContentLoadException("Invalid XNB file version.");

            byte compressed = reader.ReadByte();
            // The next int32 is the length of the XNB file
            int xnbLength = reader.ReadInt32();

            if (compressed != 0 && compressed != 1)
            {
                throw new NotImplementedException("MonoGame cannot read compressed XNB files. Please use the XNB files from the Debug build of your XNA game instead. If someone wants to contribute decompression logic, that would be fantastic.");
            }

            // The next byte i read tells me the number of content readers in this XNB file
            numberOfReaders = reader.ReadByte();
            contentReaders = new ContentTypeReader[numberOfReaders];

            // For each reader in the file, we read out the length of the string which contains the type of the reader,
            // then we read out the string. Finally we instantiate an instance of that reader using reflection
            for (int i = 0; i < numberOfReaders; i++)
            {
                // This string tells us what reader we need to decode the following data
                // string readerTypeString = reader.ReadString();
                string originalReaderTypeString = reader.ReadString();

                // Need to resolve namespace differences
                string readerTypeString = originalReaderTypeString;

                readerTypeString = PrepareType(readerTypeString);

                Type l_readerType = Type.GetType(readerTypeString);

                if(l_readerType !=null)
                    contentReaders[i] = (ContentTypeReader)Activator.CreateInstance(l_readerType,true);
                else
                    throw new ContentLoadException("Could not find matching content reader of type " + originalReaderTypeString + " (" + readerTypeString + ")");

                // I think the next 4 bytes refer to the "Version" of the type reader,
                // although it always seems to be zero
                int typeReaderVersion = reader.ReadInt32();
            }

            return contentReaders;
        }
Ejemplo n.º 7
0
        public ContentTypeReader[] LoadAssetReaders(ContentReader reader)
        {
            // Dummy variables required for it to work on iDevices ** DO NOT DELETE **
            // This forces the classes not to be optimized out when deploying to iDevices
            ListReader<Char> hCharListReader = new ListReader<Char>();
            ListReader<Rectangle> hRectangleListReader = new ListReader<Rectangle>();
            ListReader<Vector3> hVector3ListReader = new ListReader<Vector3>();
            ListReader<StringReader> hStringListReader = new ListReader<StringReader>();
            SpriteFontReader hSpriteFontReader = new SpriteFontReader();
            Texture2DReader hTexture2DReader = new Texture2DReader();
            CharReader hCharReader = new CharReader();
            RectangleReader hRectangleReader = new RectangleReader();
            StringReader hStringReader = new StringReader();
            Vector3Reader hVector3Reader = new Vector3Reader();
            int numberOfReaders;
            ContentTypeReader[] contentReaders;

            // The first content byte i read tells me the number of content readers in this XNB file
            numberOfReaders = reader.ReadByte();
            contentReaders = new ContentTypeReader[numberOfReaders];

            // For each reader in the file, we read out the length of the string which contains the type of the reader,
            // then we read out the string. Finally we instantiate an instance of that reader using reflection
            for (int i = 0; i < numberOfReaders; i++)
            {
                // This string tells us what reader we need to decode the following data
                // string readerTypeString = reader.ReadString();
                string originalReaderTypeString = reader.ReadString();

                // Need to resolve namespace differences
                string readerTypeString = originalReaderTypeString;

                readerTypeString = PrepareType(readerTypeString);

                Type l_readerType = Type.GetType(readerTypeString);

                if(l_readerType !=null)
                    contentReaders[i] = (ContentTypeReader)Activator.CreateInstance(l_readerType,true);
                else
                    throw new ContentLoadException("Could not find matching content reader of type " + originalReaderTypeString + " (" + readerTypeString + ")");

                // I think the next 4 bytes refer to the "Version" of the type reader,
                // although it always seems to be zero
                int typeReaderVersion = reader.ReadInt32();
            }

            return contentReaders;
        }
Ejemplo n.º 8
0
        public T Load <T>(string assetName)
        {
            string originalAssetName = assetName;
            object result            = null;

            if (this.graphicsDeviceService == null)
            {
                this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (this.graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ArgumentException("assetname");
            }

            if (!string.IsNullOrEmpty(_rootDirectory))
            {
                assetName = _rootDirectory + Path.DirectorySeparatorChar + assetName;
            }

            // Check for windows-style directory separator character
            assetName = assetName.Replace('\\', Path.DirectorySeparatorChar);

            // Get the real file name
            if ((typeof(T) == typeof(Texture2D)))
            {
                assetName = Texture2DReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(SpriteFont)))
            {
                assetName = SpriteFontReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(Song)))
            {
                assetName = SongReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(SoundEffect)))
            {
                assetName = SoundEffectReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(Video)))
            {
                assetName = Video.Normalize(assetName);
            }
            if ((typeof(T) == typeof(Effect)))
            {
                assetName = Effect.Normalize(assetName);
            }

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            if (Path.GetExtension(assetName).ToUpper() != ".XNB")
            {
                if ((typeof(T) == typeof(Texture2D)))
                {
                    result = Texture2D.FromFile(graphicsDeviceService.GraphicsDevice, assetName);
                }
                if ((typeof(T) == typeof(SpriteFont)))
                {
                    //result = new SpriteFont(Texture2D.FromFile(graphicsDeviceService.GraphicsDevice,assetName), null, null, null, 0, 0.0f, null, null);
                    throw new NotImplementedException();
                }
                if ((typeof(T) == typeof(Song)))
                {
                    result = new Song(assetName);
                }
                if ((typeof(T) == typeof(SoundEffect)))
                {
                    result = new SoundEffect(assetName);
                }
                if ((typeof(T) == typeof(Video)))
                {
                    result = new Video(assetName);
                }
            }
            else
            {
                // Load a XNB file
                FileStream stream = new FileStream(assetName, FileMode.Open, FileAccess.Read, FileShare.Read);

                ContentReader            reader      = new ContentReader(this, stream, this.graphicsDeviceService.GraphicsDevice);
                ContentTypeReaderManager typeManager = new ContentTypeReaderManager(reader);
                reader.TypeReaders = typeManager.LoadAssetReaders(reader);
                foreach (ContentTypeReader r in reader.TypeReaders)
                {
                    r.Initialize(typeManager);
                }
                // we need to read a byte here for things to work out, not sure why
                reader.ReadByte();

                // Get the 1-based index of the typereader we should use to start decoding with
                int index = reader.ReadByte();
                ContentTypeReader contentReader = reader.TypeReaders[index - 1];
                result = reader.ReadObject <T>(contentReader);

                reader.Close();
                stream.Close();
            }

            if (result == null)
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            return((T)result);
        }
Ejemplo n.º 9
0
        protected internal override SoundEffect Read(
            ContentReader input,
            SoundEffect existingInstance
            )
        {
            /* Swap endian - this is one of the very few places requiring this!
             * Note: This only affects the fmt chunk that's glued into the file.
             */
            bool se = input.platform == 'x';

            // Format block length
            uint formatLength = input.ReadUInt32();

            // WaveFormatEx data
            ushort wFormatTag      = Swap(se, input.ReadUInt16());
            ushort nChannels       = Swap(se, input.ReadUInt16());
            uint   nSamplesPerSec  = Swap(se, input.ReadUInt32());
            uint   nAvgBytesPerSec = Swap(se, input.ReadUInt32());
            ushort nBlockAlign     = Swap(se, input.ReadUInt16());
            ushort wBitsPerSample  = Swap(se, input.ReadUInt16());

            byte[] extra = null;
            if (formatLength > 16)
            {
                ushort cbSize = Swap(se, input.ReadUInt16());

                if (wFormatTag == 0x166 && cbSize == 34)
                {
                    // XMA2 has got some nice extra crap.
                    extra = new byte[34];
                    using (MemoryStream extraStream = new MemoryStream(extra))
                        using (BinaryWriter extraWriter = new BinaryWriter(extraStream))
                        {
                            // See FAudio.FAudioXMA2WaveFormatEx for the layout.
                            extraWriter.Write(Swap(se, input.ReadUInt16()));
                            extraWriter.Write(Swap(se, input.ReadUInt32()));
                            extraWriter.Write(Swap(se, input.ReadUInt32()));
                            extraWriter.Write(Swap(se, input.ReadUInt32()));
                            extraWriter.Write(Swap(se, input.ReadUInt32()));
                            extraWriter.Write(Swap(se, input.ReadUInt32()));
                            extraWriter.Write(Swap(se, input.ReadUInt32()));
                            extraWriter.Write(Swap(se, input.ReadUInt32()));
                            extraWriter.Write(input.ReadByte());
                            extraWriter.Write(input.ReadByte());
                            extraWriter.Write(Swap(se, input.ReadUInt16()));
                        }
                    // Is there any crap that needs skipping? Eh whatever.
                    input.ReadBytes((int)(formatLength - 18 - 34));
                }
                else
                {
                    // Seek past the rest of this crap (cannot seek though!)
                    input.ReadBytes((int)(formatLength - 18));
                }
            }

            // Wavedata
            byte[] data = input.ReadBytes(input.ReadInt32());

            // Loop information
            int loopStart  = input.ReadInt32();
            int loopLength = input.ReadInt32();

            // Sound duration in milliseconds, unused
            input.ReadUInt32();

            return(new SoundEffect(
                       input.AssetName,
                       data,
                       0,
                       data.Length,
                       extra,
                       wFormatTag,
                       nChannels,
                       nSamplesPerSec,
                       nAvgBytesPerSec,
                       nBlockAlign,
                       wBitsPerSample,
                       loopStart,
                       loopLength
                       ));
        }
Ejemplo n.º 10
0
        public T Load <T>(string assetName)
        {
            string originalAssetName = assetName;
            object result            = null;

            if (this.graphicsDeviceService == null)
            {
                this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (this.graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }

            assetName = Path.Combine(_rootDirectory, assetName.Replace('\\', Path.DirectorySeparatorChar));

            // Get the real file name
            if ((typeof(T) == typeof(Texture2D)))
            {
                assetName = Texture2DReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(SpriteFont)))
            {
                assetName = SpriteFontReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(Effect)))
            {
                assetName = Effect.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(Song)))
            {
                assetName = SongReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(SoundEffect)))
            {
                assetName = SoundEffectReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(Video)))
            {
                assetName = Video.Normalize(assetName);
            }
            else
            {
                throw new NotSupportedException("Format not supported");
            }

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            if (Path.GetExtension(assetName).ToUpper() != ".XNB")
            {
                if ((typeof(T) == typeof(Texture2D)))
                {
                    //Basically the same as Texture2D.FromFile but loading from the assets instead of a filePath
                    Stream  assetStream = Game.contextInstance.Assets.Open(assetName);
                    Bitmap  image       = BitmapFactory.DecodeStream(assetStream);
                    ESImage theTexture  = new ESImage(image, graphicsDeviceService.GraphicsDevice.PreferedFilter);
                    result = new Texture2D(theTexture)
                    {
                        Name = Path.GetFileNameWithoutExtension(assetName)
                    };
                }
                if ((typeof(T) == typeof(SpriteFont)))
                {
                    //result = new SpriteFont(Texture2D.FromFile(graphicsDeviceService.GraphicsDevice,assetName), null, null, null, 0, 0.0f, null, null);
                    throw new NotImplementedException();
                }

                if ((typeof(T) == typeof(Song)))
                {
                    result = new Song(assetName);
                }
                if ((typeof(T) == typeof(SoundEffect)))
                {
                    result = new SoundEffect(assetName);
                }
                if ((typeof(T) == typeof(Video)))
                {
                    result = new Video(assetName);
                }
            }
            else
            {
                // Load a XNB file
                //Loads from Assets directory + /assetName
                Stream assetStream = Game.contextInstance.Assets.Open(assetName);

                ContentReader            reader      = new ContentReader(this, assetStream, this.graphicsDeviceService.GraphicsDevice);
                ContentTypeReaderManager typeManager = new ContentTypeReaderManager(reader);
                reader.TypeReaders = typeManager.LoadAssetReaders(reader);
                foreach (ContentTypeReader r in reader.TypeReaders)
                {
                    r.Initialize(typeManager);
                }
                // we need to read a byte here for things to work out, not sure why
                reader.ReadByte();

                // Get the 1-based index of the typereader we should use to start decoding with
                int index = reader.ReadByte();
                ContentTypeReader contentReader = reader.TypeReaders[index - 1];
                result = reader.ReadObject <T>(contentReader);

                reader.Close();
                assetStream.Close();
            }

            if (result == null)
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            return((T)result);
        }
Ejemplo n.º 11
0
        public ContentTypeReader[] LoadAssetReaders(ContentReader reader)
        {
            // Dummy variables required for it to work on iDevices ** DO NOT DELETE **
            // This forces the classes not to be optimized out when deploying to iDevices
            ListReader<Char> hCharListReader = new ListReader<Char>();
            ListReader<Rectangle> hRectangleListReader = new ListReader<Rectangle>();
            ListReader<Vector3> hVector3ListReader = new ListReader<Vector3>();
            ListReader<StringReader> hStringListReader = new ListReader<StringReader>();
            SpriteFontReader hSpriteFontReader = new SpriteFontReader();
            Texture2DReader hTexture2DReader = new Texture2DReader();
            CharReader hCharReader = new CharReader();
            RectangleReader hRectangleReader = new RectangleReader();
            StringReader hStringReader = new StringReader();
            Vector3Reader hVector3Reader = new Vector3Reader();

            int numberOfReaders;
            ContentTypeReader[] contentReaders;

            // The first 4 bytes should be the "XNBw" header. i use that to detect an invalid file
            byte[] headerBuffer = new byte[4];
            reader.Read(headerBuffer, 0, 4);
            string headerString = Encoding.UTF8.GetString(headerBuffer, 0, 4);
            if (string.Compare(headerString, "XNBw", StringComparison.InvariantCultureIgnoreCase) != 0)
                throw new ContentLoadException("Asset does not appear to be a valid XNB file.  Did you process your content for Windows?");

            // I think these two bytes are some kind of version number. Either for the XNB file or the type readers
            byte version = reader.ReadByte();
            byte compressed = reader.ReadByte();
            // The next int32 is the length of the XNB file
            int xnbLength = reader.ReadInt32();

            if (compressed != 0)
            {
                throw new NotImplementedException("MonoGame cannot read compressed XNB files. Please use the XNB files from the Debug build of your XNA game instead. If someone wants to contribute decompression logic, that would be fantastic.");
            }

            // The next byte i read tells me the number of content readers in this XNB file
            numberOfReaders = reader.ReadByte();
            contentReaders = new ContentTypeReader[numberOfReaders];

            // For each reader in the file, we read out the length of the string which contains the type of the reader,
            // then we read out the string. Finally we instantiate an instance of that reader using reflection
            for (int i = 0; i < numberOfReaders; i++)
            {
                // This string tells us what reader we need to decode the following data
                // string readerTypeString = reader.ReadString();
                string originalReaderTypeString = reader.ReadString();

                // Need to resolve namespace differences
                string readerTypeString = originalReaderTypeString;
                /*if(readerTypeString.IndexOf(", Microsoft.Xna.Framework") != -1)
             				{
                    string[] tokens = readerTypeString.Split(new char[] { ',' });
                    readerTypeString = "";
                    for(int j = 0; j < tokens.Length; j++)
             					{
                        if(j != 0)
                            readerTypeString += ",";

                        if(j == 1)
                            readerTypeString += " Microsoft.Xna.Framework";
                        else
                            readerTypeString += tokens[j];
             					}
                    readerTypeString = readerTypeString.Replace(", Microsoft.Xna.Framework", "@");
                }*/

                if(readerTypeString.Contains("PublicKey"))
                {
                    //if (readerTypeString.Contains("[[")) {
                        readerTypeString = readerTypeString.Split(new char[] { '[', '[' })[0] + "[" +
                        readerTypeString.Split(new char[] { '[', '[' })[2].Split(',')[0] + "]";
                    //}
                    //else {
                    //	// If the readerTypeString did not contain "[[" to split the
                    //	// types then we assume it is XNA 4.0 which splits the types
                    //	// by ', '
                    //	readerTypeString = readerTypeString.Split(new char[] { ',', ' '})[0];
                    //
                    //}

                }

                readerTypeString = readerTypeString.Replace("Microsoft.Xna.Framework", "Microsoft.Xna.Framework");
                Type l_readerType = Type.GetType(readerTypeString);

                if(l_readerType !=null)
                    contentReaders[i] = (ContentTypeReader)Activator.CreateInstance(l_readerType,true);
                else
                    throw new ContentLoadException("Could not find matching content reader of type " + originalReaderTypeString);

                // I think the next 4 bytes refer to the "Version" of the type reader,
                // although it always seems to be zero
                int typeReaderVersion = reader.ReadInt32();
            }

            return contentReaders;
        }
Ejemplo n.º 12
0
        public ContentTypeReader[] LoadAssetReaders(ContentReader reader)
        {
            // Dummy variables required for it to work on iDevices ** DO NOT DELETE **
            // This forces the classes not to be optimized out when deploying to iDevices
            ListReader <Char>         hCharListReader      = new ListReader <Char>();
            ListReader <Rectangle>    hRectangleListReader = new ListReader <Rectangle>();
            ListReader <Vector3>      hVector3ListReader   = new ListReader <Vector3>();
            ListReader <StringReader> hStringListReader    = new ListReader <StringReader>();
            SpriteFontReader          hSpriteFontReader    = new SpriteFontReader();
            Texture2DReader           hTexture2DReader     = new Texture2DReader();
            CharReader      hCharReader      = new CharReader();
            RectangleReader hRectangleReader = new RectangleReader();
            StringReader    hStringReader    = new StringReader();
            Vector3Reader   hVector3Reader   = new Vector3Reader();

            int numberOfReaders;

            ContentTypeReader[] contentReaders;

            // The first 4 bytes should be the "XNBw" header. i use that to detect an invalid file
            byte[] headerBuffer = new byte[4];
            reader.Read(headerBuffer, 0, 4);
            string headerString = Encoding.UTF8.GetString(headerBuffer, 0, 4);

            if (string.Compare(headerString, "XNBw", StringComparison.InvariantCultureIgnoreCase) != 0)
            {
                throw new ContentLoadException("Asset does not appear to be a valid XNB file.  Did you process your content for Windows?");
            }

            // I think these two bytes are some kind of version number. Either for the XNB file or the type readers
            byte version    = reader.ReadByte();
            byte compressed = reader.ReadByte();
            // The next int32 is the length of the XNB file
            int xnbLength = reader.ReadInt32();

            if (compressed != 0)
            {
                throw new NotImplementedException("MonoGame cannot read compressed XNB files. Please use the XNB files from the Debug build of your XNA game instead. If someone wants to contribute decompression logic, that would be fantastic.");
            }

            // The next byte i read tells me the number of content readers in this XNB file
            numberOfReaders = reader.ReadByte();
            contentReaders  = new ContentTypeReader[numberOfReaders];

            // For each reader in the file, we read out the length of the string which contains the type of the reader,
            // then we read out the string. Finally we instantiate an instance of that reader using reflection
            for (int i = 0; i < numberOfReaders; i++)
            {
                // This string tells us what reader we need to decode the following data
                // string readerTypeString = reader.ReadString();
                string originalReaderTypeString = reader.ReadString();

                // Need to resolve namespace differences
                string readerTypeString = originalReaderTypeString;

                /*if(readerTypeString.IndexOf(", Microsoft.Xna.Framework") != -1)
                 * {
                 *      string[] tokens = readerTypeString.Split(new char[] { ',' });
                 *      readerTypeString = "";
                 *      for(int j = 0; j < tokens.Length; j++)
                 *      {
                 *              if(j != 0)
                 *                      readerTypeString += ",";
                 *
                 *              if(j == 1)
                 *                      readerTypeString += " Microsoft.Xna.Framework";
                 *              else
                 *                      readerTypeString += tokens[j];
                 *      }
                 *      readerTypeString = readerTypeString.Replace(", Microsoft.Xna.Framework", "@");
                 * }*/

                if (readerTypeString.Contains("PublicKey"))
                {
                    //if (readerTypeString.Contains("[[")) {
                    readerTypeString = readerTypeString.Split(new char[] { '[', '[' })[0] + "[" +
                                       readerTypeString.Split(new char[] { '[', '[' })[2].Split(',')[0] + "]";
                    //}
                    //else {
                    //	// If the readerTypeString did not contain "[[" to split the
                    //	// types then we assume it is XNA 4.0 which splits the types
                    //	// by ', '
                    //	readerTypeString = readerTypeString.Split(new char[] { ',', ' '})[0];
                    //
                    //}
                }

                readerTypeString = readerTypeString.Replace("Microsoft.Xna.Framework", "Microsoft.Xna.Framework");
                Type l_readerType = Type.GetType(readerTypeString);

                if (l_readerType != null)
                {
                    contentReaders[i] = (ContentTypeReader)Activator.CreateInstance(l_readerType, true);
                }
                else
                {
                    throw new ContentLoadException("Could not find matching content reader of type " + originalReaderTypeString);
                }



                // I think the next 4 bytes refer to the "Version" of the type reader,
                // although it always seems to be zero
                int typeReaderVersion = reader.ReadInt32();
            }

            return(contentReaders);
        }
Ejemplo n.º 13
0
 private ModelBone ReadBoneReference(ContentReader input)
 {
     int length = this.bones.Count + 1;
     int count = 0;
     if (length <= 0xff)
     {
         count = input.ReadByte();
     }
     else
     {
         count = input.ReadInt32();
     }
     if (count != 0)
     {
         return this.bones[count - 1];
     }
     return null;
 }
Ejemplo n.º 14
0
        private static int ReadBoneReference(ContentReader reader, uint boneCount)
        {
            uint num = boneCount >= (uint)byte.MaxValue ? reader.ReadUInt32() : (uint)reader.ReadByte();

            if ((int)num != 0)
            {
                return((int)num - 1);
            }
            else
            {
                return(-1);
            }
        }
Ejemplo n.º 15
0
 protected internal override byte Read(ContentReader input, byte existingInstance)
 {
     return(input.ReadByte());
 }
Ejemplo n.º 16
0
 protected internal override Color Read(ContentReader input, Color existingInstance)
 {
     return(new Color((int)input.ReadByte(), (int)input.ReadByte(), (int)input.ReadByte(), (int)input.ReadByte()));
 }