コード例 #1
0
 internal OgmoTileset(ContentReader reader)
 {
     this.Name = reader.ReadString();
     this.Texture = reader.ReadExternalReference<Texture2D>();
     this.TextureFile = reader.ReadString();
     this.TileHeight = reader.ReadInt32();
     this.TileWidth = reader.ReadInt32();
     if (this.Texture != null)
         this.CreateSources();
 }
コード例 #2
0
ファイル: EntityGraphics.cs プロジェクト: cpetosky/o2d-lib
        public EntityGraphics(ContentReader reader)
        {
            id = reader.ReadInt32();
            width = reader.ReadInt32();
            height = reader.ReadInt32();
            frames = reader.ReadInt32();
            image = reader.ReadString();

            texture = reader.ContentManager.Load<Texture2D>(@"gfx\entities\" + image);

            modes = new string[texture.Height / height];
            for (int i = 0; i < modes.Length; ++i)
                modes[i] = reader.ReadString();
        }
コード例 #3
0
ファイル: XACTPatch.cs プロジェクト: verngutz/Automatone
        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);
            }
        }
コード例 #4
0
 internal OgmoGridLayer(ContentReader reader, OgmoLevel level)
     : base(reader)
 {
     OgmoGridLayerSettings settings = level.Project.GetLayerSettings<OgmoGridLayerSettings>(this.Name);
     if (settings.ExportAsObjects)
     {
         rectData = new List<Rectangle>();
         int objectCount = reader.ReadInt32();
         if (objectCount > 0)
         {
             for (int i = 0; i < objectCount; i++)
             {
                 Rectangle rect = Rectangle.Empty;
                 rect.X = reader.ReadInt32();
                 rect.Y = reader.ReadInt32();
                 rect.Width = reader.ReadInt32();
                 rect.Height = reader.ReadInt32();
                 rectData.Add(rect);
             }
         }
     }
     else
     {
         byte[] data = Convert.FromBase64String(reader.ReadString());
         string stringData = System.Text.Encoding.UTF8.GetString(data, 0, data.Length);
         int tx = level.Width / settings.GridSize;
         int ty = level.Height / settings.GridSize;
         rawData = new int[tx, ty];
         for (int y = 0; y < ty; y++)
             for (int x = 0; x < tx; x++)
                 rawData[x, y] = int.Parse(stringData[y * tx + x].ToString(), CultureInfo.InvariantCulture);
     }
 }
 internal OgmoLayerSettings(ContentReader reader)
 {
     this.GridColor = reader.ReadColor();
     this.GridDrawSize = reader.ReadInt32();
     this.GridSize = reader.ReadInt32();
     this.Name = reader.ReadString();
 }
コード例 #6
0
ファイル: Tileset.cs プロジェクト: JuliaABurch/Treefrog
        internal Tileset(ContentReader reader)
            : this()
        {
            _manager = reader.ContentManager;

            int version = reader.ReadInt16();
            int id = reader.ReadInt16();

            TileWidth = reader.ReadInt16();
            TileHeight = reader.ReadInt16();
            string texAsset = reader.ReadString();

            Properties = new PropertyCollection(reader);

            int tileCount = reader.ReadInt16();
            for (int i = 0; i < tileCount; i++) {
                int tileId = reader.ReadInt16();
                int tileX = reader.ReadInt16();
                int tileY = reader.ReadInt16();

                Tile tile = new Tile(tileId, this, tileX, tileY)
                {
                    Properties = new PropertyCollection(reader),
                };
                _tiles.Add(tileId, tile);
            }

            _texture = _manager.Load<Texture2D>(texAsset);
        }
コード例 #7
0
ファイル: Level.cs プロジェクト: JuliaABurch/Treefrog
        internal Level(ContentReader reader)
            : this()
        {
            int version = reader.ReadInt16();

            int tileWidth = reader.ReadInt16();
            int tileHeight = reader.ReadInt16();
            int width = reader.ReadInt16();
            int height = reader.ReadInt16();

            Width = tileWidth * width;
            Height = tileHeight * height;

            Properties = new PropertyCollection(reader);

            int tilesetCount = reader.ReadInt32();
            for (int i = 0; i < tilesetCount; i++) {
                string asset = reader.ReadString();
                Tileset tileset = reader.ContentManager.Load<Tileset>(asset);

                _tileRegistry.Add(tileset);
            }

            int objectPoolCount = reader.ReadInt32();
            for (int i = 0; i < objectPoolCount; i++) {
                string asset = reader.ReadString();
                ObjectPool pool = reader.ContentManager.Load<ObjectPool>(asset);

                _objectRegistry.Add(pool);
            }

            int layerCount = reader.ReadInt16();
            for (int i = 0; i < layerCount; i++) {
                string type = reader.ReadString();

                switch (type) {
                    case "TILE":
                        _layers.Add(new TileLayer(reader, _tileRegistry));
                        break;
                    case "OBJE":
                        _layers.Add(new ObjectLayer(reader, _objectRegistry));
                        break;
                }
            }
        }
 internal OgmoProjectSettings(ContentReader reader)
 {
     this.Height = reader.ReadInt32();
     this.MaxHeight = reader.ReadInt32();
     this.MaxWidth = reader.ReadInt32();
     this.MinHeight = reader.ReadInt32();
     this.MinWidth = reader.ReadInt32();
     this.Width = reader.ReadInt32();
     this.WorkingDirectory = reader.ReadString();
 }
コード例 #9
0
        internal static AnimationClip Read(ContentReader input)
        {
            string animationName = input.ReadString();
            TimeSpan animationDuration = input.ReadObject<TimeSpan>();

            // Read animation clip channels
            Dictionary<string, AnimationChannel> animationChannelDictionary =
                new Dictionary<string, AnimationChannel>();

            int numAnimationChannels = input.ReadInt32();
            for (int i = 0; i < numAnimationChannels; i++)
            {
                string channelName = input.ReadString();

                // Read animation channel keyframes
                int numChannelKeyframes = input.ReadInt32();
                List<AnimationChannelKeyframe> keyframeList =
                    new List<AnimationChannelKeyframe>(numChannelKeyframes);

                for (int j = 0; j < numChannelKeyframes; j++)
                {
                    TimeSpan keyframeTime = input.ReadObject<TimeSpan>();

                    // Read keyframe pose
                    Pose keyframePose;
                    keyframePose.Translation = input.ReadVector3();
                    keyframePose.Orientation = input.ReadQuaternion();
                    keyframePose.Scale = input.ReadVector3();

                    keyframeList.Add(new AnimationChannelKeyframe(keyframeTime, keyframePose));
                }

                AnimationChannel animationChannel = new AnimationChannel(keyframeList);

                // Add the animation channel to the dictionary
                animationChannelDictionary.Add(channelName, animationChannel);
            }

            return
                new AnimationClip(animationName, animationDuration,
                    new AnimationChannelDictionary(animationChannelDictionary));
        }
コード例 #10
0
ファイル: ContentUtil.cs プロジェクト: sgdc/sgdc-old
 public static void DeveloperID(ref Dictionary<string, object> devTypes, ContentReader reader, object obj)
 {
     if (reader.ReadBoolean())
     {
         string key = reader.ReadString();
         if (devTypes != null)
         {
             devTypes.Add(key, obj);
         }
     }
 }
コード例 #11
0
ファイル: Layer.cs プロジェクト: JuliaABurch/Treefrog
        internal Layer(ContentReader reader)
        {
            ScaleX = 1f;
            ScaleY = 1f;

            Id = reader.ReadInt16();
            Name = reader.ReadString();
            Visible = reader.ReadBoolean();
            Opacity = reader.ReadSingle();
            Properties = new PropertyCollection(reader);
        }
コード例 #12
0
 internal OgmoTile(ContentReader reader, OgmoTileLayer layer)
 {
     this.Height = reader.ReadInt32();
     this.Position = reader.ReadVector2();
     this.SourceIndex = reader.ReadInt32();
     Vector2 offset = reader.ReadVector2();
     Point point = new Point((int)offset.X, (int)offset.Y);
     this.TextureOffset = point;
     string tilesetName = reader.ReadString();
     this.Tileset = layer.GetTileset(tilesetName);
     this.Width = reader.ReadInt32();
 }
コード例 #13
0
ファイル: Palette.cs プロジェクト: cpetosky/o2d-lib
        public Palette(ContentReader reader, GraphicsDevice graphicsDevice)
        {
            this.graphicsDevice = graphicsDevice;
            id = reader.ReadInt32();
            name = reader.ReadString();
            int size = reader.ReadInt32();

            tileInfos = new List<TileInfo>(size);

            for (int i = 0; i < size; ++i) {
                tileInfos.Add(new TileInfo(
                    i,
                    reader.ReadString(),
                    reader.ReadInt32(),
                    (TileAccess)reader.ReadInt32(),
                    reader.ContentManager
                ));
            }

            RegenerateTextures();
        }
コード例 #14
0
ファイル: Level.cs プロジェクト: Elof3/Treefrog
        internal Level(ContentReader reader)
            : this()
        {
            string levelName = reader.ReadString();

            int originX = reader.ReadInt32();
            int originY = reader.ReadInt32();
            Width = reader.ReadInt32();
            Height = reader.ReadInt32();

            Properties = new PropertyCollection(reader);

            int tilesetCount = reader.ReadInt32();
            for (int i = 0; i < tilesetCount; i++) {
                TileSet tileset = new TileSet(reader);
                _tileRegistry.Add(tileset);
            }

            int objectPoolCount = reader.ReadInt32();
            for (int i = 0; i < objectPoolCount; i++) {
                //string asset = reader.ReadString();
                //ObjectPool pool = reader.ContentManager.Load<ObjectPool>(asset);
                ObjectPool pool = new ObjectPool(reader);
                _objectRegistry.Add(pool);
            }

            int layerCount = reader.ReadInt32();
            for (int i = 0; i < layerCount; i++) {
                string type = reader.ReadString();

                switch (type) {
                    case "TILE":
                        _layers.Add(new TileLayer(reader, _tileRegistry));
                        break;
                    case "OBJE":
                        _layers.Add(new ObjectLayer(reader, _objectRegistry));
                        break;
                }
            }
        }
コード例 #15
0
        internal ContentTypeReader[] LoadAssetReaders(ContentReader reader)
        {
            /* The first content byte i read tells me the number of
             * content readers in this XNB file.
             */
            int numberOfReaders = reader.Read7BitEncodedInt();

            ContentTypeReader[] newReaders      = new ContentTypeReader[numberOfReaders];
            BitArray            needsInitialize = new BitArray(numberOfReaders);

            /* Lock until we're done allocating and initializing any new
             * content type readers... this ensures we can load content
             * from multiple threads and still cache the readers.
             */
            lock (locker)
            {
                /* 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 += 1)
                {
                    /* This string tells us what reader we
                     * need to decode the following data.
                     */
                    string            originalReaderTypeString = reader.ReadString();
                    bool              needsInit  = false;
                    ContentTypeReader typeReader = GetReaderByTypeName(originalReaderTypeString, out needsInit);
                    newReaders[i]      = typeReader;
                    needsInitialize[i] = needsInit;

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

                // Initialize any new readers.
                for (int i = 0; i < newReaders.Length; i += 1)
                {
                    if (needsInitialize.Get(i))
                    {
                        newReaders[i].Initialize(this);
                    }
                }
            }             // lock (locker)

            return(newReaders);
        }
コード例 #16
0
ファイル: ObjectPool.cs プロジェクト: Elof3/Treefrog
        internal ObjectPool(ContentReader reader)
            : this()
        {
            _manager = reader.ContentManager;

            //int version = reader.ReadInt16();
            int id = reader.ReadInt32();
            string texAsset = reader.ReadString();

            Properties = new PropertyCollection(reader);

            int objCount = reader.ReadInt32();
            for (int i = 0; i < objCount; i++) {
                int objId = reader.ReadInt32();
                string name = reader.ReadString();

                ObjectClass objClass = new ObjectClass(this, objId, name) {
                    Origin = new Point(reader.ReadInt32(), reader.ReadInt32()),
                    MaskBounds = new Rectangle(reader.ReadInt32(), reader.ReadInt32(), reader.ReadInt32(), reader.ReadInt32()),
                    TexRotated = reader.ReadBoolean(),
                    TexX = reader.ReadInt32(),
                    TexY = reader.ReadInt32(),
                    TexWidth = reader.ReadInt32(),
                    TexHeight = reader.ReadInt32(),
                    TexOriginalWidth = reader.ReadInt32(),
                    TexOriginalHeight = reader.ReadInt32(),
                    TexOffsetX = reader.ReadInt32(),
                    TexOffsetY = reader.ReadInt32(),
                    Properties = new PropertyCollection(reader),
                };

                _objects.Add(objId, objClass);
            }

            _texture = _manager.Load<Texture2D>(texAsset);
        }
コード例 #17
0
ファイル: SongReader.cs プロジェクト: conankzhang/fez
        protected internal override Song Read(ContentReader input, Song existingInstance)
        {
            string fileName = input.ReadString();

            if (!string.IsNullOrEmpty(fileName))
            {
                char   newChar     = Path.DirectorySeparatorChar;
                string relativeUri = fileName.Replace('\\', newChar);
                string path2       = new Uri(new Uri("file:///" + input.AssetName.Replace('\\', newChar)), relativeUri).LocalPath.Substring(1);
                fileName = Path.Combine(input.ContentManager.RootDirectoryFullPath, path2);
            }
            int durationMS = input.ReadObject <int>();

            return(new Song(fileName, durationMS));
        }
コード例 #18
0
ファイル: SongReader.cs プロジェクト: q4a/OpenC1
        protected internal override Song Read(ContentReader input, Song existingInstance)
        {
            var path = input.ReadString();

            if (!String.IsNullOrEmpty(path))
            {
                // Add the ContentManager's RootDirectory
                var dirPath = Path.Combine(input.ContentManager.RootDirectoryFullPath, input.AssetName);

                // Resolve the relative path
                path = FileHelpers.ResolveRelativePath(dirPath, path);
            }

            var durationMs = input.ReadObject <int>();

            return(new Song(path, durationMs));
        }
 internal static OgmoLayer Read(ContentReader reader, OgmoLevel level)
 {
     OgmoLayer layer = null;
     string type = reader.ReadString();
     switch (type)
     {
         case "g":
             layer = new OgmoGridLayer(reader, level);
             break;
         case "t":
             layer = new OgmoTileLayer(reader, level);
             break;
         case "o":
             layer = new OgmoObjectLayer(reader, level);
             break;
     }
     return layer;
 }
 internal static OgmoLayerSettings Read(ContentReader reader)
 {
     OgmoLayerSettings layerSettings = null;
     string settingsType = reader.ReadString();
     switch (settingsType)
     {
         case "g":
             layerSettings = new OgmoGridLayerSettings(reader);
             break;
         case "o":
             layerSettings = new OgmoObjectLayerSettings(reader);
             break;
         case "t":
             layerSettings = new OgmoTileLayerSettings(reader);
             break;
     }
     return layerSettings;
 }
コード例 #21
0
ファイル: ObjectPool.cs プロジェクト: JuliaABurch/Treefrog
        internal ObjectPool(ContentReader reader)
            : this()
        {
            _manager = reader.ContentManager;

            int version = reader.ReadInt16();
            int id = reader.ReadInt16();

            Properties = new PropertyCollection(reader);

            int objCount = reader.ReadInt16();
            for (int i = 0; i < objCount; i++) {
                int objId = reader.ReadInt16();
                string name = reader.ReadString();

                ObjectClass objClass = new ObjectClass(this, objId, name);
                _objects.Add(objId, objClass);
            }
        }
コード例 #22
0
ファイル: SongReader.cs プロジェクト: lovelife/MonoGame
        protected internal override Song Read(ContentReader input, Song existingInstance)
        {
            string path = input.ReadString();

            path = Path.Combine(input.ContentManager.RootDirectory, path);
            path = TitleContainer.GetFilename(path);

            /* The path string includes the ".wma" extension. Let's see if this
             * file exists in a format we actually support...
             */
            path = Normalize(Path.GetFileNameWithoutExtension(path));
            if (String.IsNullOrEmpty(path))
            {
                throw new ContentLoadException();
            }

            int durationMs = input.ReadObject <int>();

            return(new Song(path, durationMs));
        }
 internal static OgmoValueTemplate Read(ContentReader reader)
 {
     OgmoValueTemplate value = null;
     string valueType = reader.ReadString();
     switch (valueType)
     {
         case "b":
             value = new OgmoBooleanValueTemplate(reader);
             break;
         case "i":
             value = new OgmoIntegerValueTemplate(reader);
             break;
         case "n":
             value = new OgmoNumberValueTemplate(reader);
             break;
         case "s":
             value = new OgmoStringValueTemplate(reader);
             break;
     }
     return value;
 }
コード例 #24
0
 internal OgmoTileLayer(ContentReader reader, OgmoLevel level) 
     : base(reader)
 {            
     this.TileHeight = reader.ReadInt32();
     this.TileWidth = reader.ReadInt32();
     int tilesetCount = reader.ReadInt32();
     if (tilesetCount > 0)
     {
         for (int i = 0; i < tilesetCount; i++)
         {
             string tilesetName = reader.ReadString();
             OgmoTileset tileset = level.Project.GetTileset(tilesetName);
             tilesets.Add(tileset.Name, tileset);
         }
     }
     int tileCount = reader.ReadInt32();
     if (tileCount > 0)
     {
         for (int i = 0; i < tileCount; i++)
             tiles.Add(new OgmoTile(reader, this));
     }
 }
コード例 #25
0
ファイル: Castle.cs プロジェクト: urmuelle/MonoGameBallerburg
        /// <summary>
        /// Initializes a new instance of the <see cref="Castle"/> class.
        /// </summary>
        /// <param name="reader">The castle content reader</param>
        public Castle(ContentReader reader)
        {
            this.id = 0;

              if (reader == null)
              {
            throw new ArgumentNullException("reader");
              }

              this.name = reader.ReadString();
              this.price = reader.ReadInt32();

              var tempTowers = reader.ReadObject<Tower[]>();

              var sumX = 0.0f;
              var sumZ = 0.0f;

              this.towers = new Collection<Tower>();
              foreach (Tower t in tempTowers)
              {
            sumX += t.X;
            sumZ += t.Y;
            this.towers.Add(t);
              }

              this.walls = new List<Wall>();
              var tempWalls = reader.ReadObject<Wall[]>();
              foreach (var w in tempWalls)
              {
            w.SetFromToVectors(
            new Vector3(this.towers[w.FromIndex].X, 0.0f, this.towers[w.FromIndex].Y),
            new Vector3(this.towers[w.ToIndex].X, 0.0f, this.towers[w.ToIndex].Y));

            this.walls.Add(w);
              }

              this.center = new Vector3(sumX / this.towers.Count, 0.0f, sumZ / this.towers.Count);
              this.currentTower = 0;
        }
コード例 #26
0
        internal static ContentTypeReader[] ReadTypeManifest(int typeCount, ContentReader contentReader)
        {
            ContentTypeReader[]      readers        = new ContentTypeReader[typeCount];
            List <ContentTypeReader> newTypeReaders = null;

            try
            {
                for (int i = 0; i < typeCount; i++)
                {
                    string typename = contentReader.ReadString();
                    if (typename.Contains("PublicKey"))
                    {
                        typename = typename.Split(new char[] { '[', '[' })[0] + "[" + typename.Split(new char[] { '[', '[' })[2].Split(',')[0] + "]"; //FIXME: Fix for cross-assembly reference problem. Maybe bad solution. Problem: tried to load type from msxna assembly.
                    }
                    ContentTypeReader reader = GetTypeReader(typename, contentReader, ref newTypeReaders);
                    if (contentReader.ReadInt32() != reader.TypeVersion)
                    {
                        throw new ContentLoadException("Bad XNB TypeVersion");
                    }
                    readers[i] = reader;
                }
                if (newTypeReaders != null)
                {
                    ContentTypeReaderManager manager = new ContentTypeReaderManager(contentReader);
                    foreach (ContentTypeReader reader2 in newTypeReaders)
                    {
                        reader2.Initialize(manager);
                    }
                }
                return(readers);
            }
            catch
            {
                RollbackAddReaders(newTypeReaders);
                throw;
            }
            return(readers);
        }
コード例 #27
0
        protected internal override Song Read(ContentReader input, Song existingInstance)
        {
            string path = MonoGame.Utilities.FileHelpers.ResolveRelativePath(
                Path.Combine(
                    input.ContentManager.RootDirectoryFullPath,
                    input.AssetName
                    ),
                input.ReadString()
                );

            /* The path string includes the ".wma" extension. Let's see if this
             * file exists in a format we actually support...
             */
            path = Normalize(path.Substring(0, path.Length - 4));
            if (String.IsNullOrEmpty(path))
            {
                throw new ContentLoadException();
            }

            int durationMs = input.ReadInt32();

            return(new Song(path, durationMs));
        }
コード例 #28
0
        protected internal override Song Read(ContentReader input, Song existingInstance)
        {
#if !PORTABLE
            var path = input.ReadString();

            if (!String.IsNullOrEmpty(path))
            {
#if WINRT
                const char notSeparator = '/';
                const char separator    = '\\';
#else
                const char notSeparator = '\\';
                var        separator    = Path.DirectorySeparatorChar;
#endif
                path = path.Replace(notSeparator, separator);

                // Get a uri for the asset path using the file:// schema and no host
                var src = new Uri("file:///" + input.AssetName.Replace(notSeparator, separator));

                // Add the relative path to the external reference
                var dst = new Uri(src, path);

                // The uri now contains the path to the external reference within the content manager
                // Get the local path and skip the first character (the path separator)
                path = dst.LocalPath.Substring(1);

                // Adds the ContentManager's RootDirectory
                path = Path.Combine(input.ContentManager.RootDirectoryFullPath, path);
            }

            var durationMs = input.ReadObject <int>();

            return(new Song(path, durationMs));
#else
            return(null);
#endif
        }
コード例 #29
0
        internal static SkinnedModelBone Read(ContentReader input)
        {
            // Read bone data
            ushort index = input.ReadUInt16();
            string name = input.ReadString();

            // Read bind pose
            Pose bindPose;
            bindPose.Translation = input.ReadVector3();
            bindPose.Orientation = input.ReadQuaternion();
            bindPose.Scale = input.ReadVector3();

            Matrix inverseBindPoseTransform = input.ReadMatrix();
            SkinnedModelBone skinnedBone =
                new SkinnedModelBone(index, name, bindPose, inverseBindPoseTransform);

            // Read bone parent
            input.ReadSharedResource<SkinnedModelBone>(
                delegate(SkinnedModelBone parentBone) { skinnedBone.parent = parentBone; });

            // Read bone children
            int numChildren = input.ReadInt32();
            List<SkinnedModelBone> childrenList = new List<SkinnedModelBone>(numChildren);
            for (int i = 0; i < numChildren; i++)
            {
                input.ReadSharedResource<SkinnedModelBone>(
                    delegate(SkinnedModelBone childBone) { childrenList.Add(childBone); });
            }
            skinnedBone.children = new SkinnedModelBoneCollection(childrenList);

            return skinnedBone;
        }
 internal OgmoValueTemplate(ContentReader reader)
 {
     this.Name = reader.ReadString();
 }
コード例 #31
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;
        }
コード例 #32
0
ファイル: Map.cs プロジェクト: GarethIW/LDEngine
        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);
            }
        }
コード例 #33
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);
        }
コード例 #34
0
        private void loadMD3Data(ContentReader input, MD3Object m)
        {
            //load meshes
            m.meshes = new List<MD3SubMeshes>();
            int part = input.ReadInt32();
            if (part == 0)
                m.part = TMD3Part.HEAD;
            else if (part == 1)
                m.part = TMD3Part.LOWER;
            else
                m.part = TMD3Part.UPPER;

            m.num_frames = input.ReadInt32();
            int sub_meshes_count = input.ReadInt32();
            for (int i = 0; i < sub_meshes_count; ++i)
            {
                MD3SubMeshes sub_mesh = new MD3SubMeshes();
                sub_mesh.indices = new List<int>();
                sub_mesh.vertices = new List<Vector3>();
                sub_mesh.normals = new List<Vector3>();
                sub_mesh.text_coord = new List<Vector2>();
                sub_mesh.skins = new List<string>();
                sub_mesh.meshinfo.strName = input.ReadString();
                input.ReadObject<List<int>>(sub_mesh.indices);
                input.ReadObject<List<Vector3>>(sub_mesh.vertices);
                input.ReadObject<List<Vector3>>(sub_mesh.normals);
                input.ReadObject<List<Vector2>>(sub_mesh.text_coord);
                m.meshes.Add(sub_mesh);
            }

            //load tags
            m.tags = new List<MD3tag>();
            int tags_count = input.ReadInt32();
            for (int i = 0; i < tags_count; ++i)
            {
                MD3tag tag = new MD3tag();
                tag.strName = input.ReadString();
                tag.vPosition = input.ReadVector3();
                tag.rotation = input.ReadMatrix();
                m.tags.Add(tag);
            }
            //load bounding_boxes
            m.bounding_boxes = new List<BoundingBox>();
            int bb_count = input.ReadInt32();
            for (int i = 0; i < bb_count; ++i)
            {
                BoundingBox bb = new BoundingBox();
                bb.Min = input.ReadVector3();
                bb.Max = input.ReadVector3();
                m.bounding_boxes.Add(bb);
            }
        }
コード例 #35
0
ファイル: Map.cs プロジェクト: Wydra/WickedEngine
        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);
            }
        }
コード例 #36
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);
        }
コード例 #37
0
        internal ContentTypeReader[] LoadAssetReaders()
        {
#pragma warning disable 0219, 0649
            // Trick to prevent the linker removing the code, but not actually execute the code
            if (falseflag)
            {
                // 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
                var hByteReader              = new ByteReader();
                var hSByteReader             = new SByteReader();
                var hDateTimeReader          = new DateTimeReader();
                var hDecimalReader           = new DecimalReader();
                var hBoundingSphereReader    = new BoundingSphereReader();
                var hBoundingFrustumReader   = new BoundingFrustumReader();
                var hRayReader               = new RayReader();
                var hCharListReader          = new ListReader <Char>();
                var hRectangleListReader     = new ListReader <Rectangle>();
                var hRectangleArrayReader    = new ArrayReader <Rectangle>();
                var hVector3ListReader       = new ListReader <Vector3>();
                var hStringListReader        = new ListReader <StringReader>();
                var hIntListReader           = new ListReader <Int32>();
                var hSpriteFontReader        = new SpriteFontReader();
                var hTexture2DReader         = new Texture2DReader();
                var hCharReader              = new CharReader();
                var hRectangleReader         = new RectangleReader();
                var hStringReader            = new StringReader();
                var hVector2Reader           = new Vector2Reader();
                var hVector3Reader           = new Vector3Reader();
                var hVector4Reader           = new Vector4Reader();
                var hCurveReader             = new CurveReader();
                var hIndexBufferReader       = new IndexBufferReader();
                var hBoundingBoxReader       = new BoundingBoxReader();
                var hMatrixReader            = new MatrixReader();
                var hBasicEffectReader       = new BasicEffectReader();
                var hVertexBufferReader      = new VertexBufferReader();
                var hAlphaTestEffectReader   = new AlphaTestEffectReader();
                var hEnumSpriteEffectsReader = new EnumReader <Graphics.SpriteEffects>();
                var hArrayFloatReader        = new ArrayReader <float>();
                var hArrayVector2Reader      = new ArrayReader <Vector2>();
                var hListVector2Reader       = new ListReader <Vector2>();
                var hArrayMatrixReader       = new ArrayReader <Matrix>();
                var hEnumBlendReader         = new EnumReader <Graphics.Blend>();
                var hNullableRectReader      = new NullableReader <Rectangle>();
                var hEffectMaterialReader    = new EffectMaterialReader();
                var hExternalReferenceReader = new ExternalReferenceReader();
                var hSoundEffectReader       = new SoundEffectReader();
                var hSongReader              = new SongReader();
            }
#pragma warning restore 0219, 0649

            int numberOfReaders;

            // The first content byte i read tells me the number of content readers in this XNB file
            numberOfReaders = _reader.Read7BitEncodedInt();
            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();

                Func <ContentTypeReader> readerFunc;
                if (typeCreators.TryGetValue(originalReaderTypeString, out readerFunc))
                {
                    contentReaders[i] = readerFunc();
                }
                else
                {
                    //System.Diagnostics.Debug.WriteLine(originalReaderTypeString);

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

                    readerTypeString = PrepareType(readerTypeString);

                    var l_readerType = Type.GetType(readerTypeString);
                    if (l_readerType != null)
                    {
                        try
                        {
                            contentReaders[i] = l_readerType.GetDefaultConstructor().Invoke(null) as ContentTypeReader;
                        }
                        catch (TargetInvocationException ex)
                        {
                            // If you are getting here, the Mono runtime is most likely not able to JIT the type.
                            // In particular, MonoTouch needs help instantiating types that are only defined in strings in Xnb files.
                            throw new InvalidOperationException(
                                      "Failed to get default constructor for ContentTypeReader. To work around, add a creation function to ContentTypeReaderManager.AddTypeCreator() " +
                                      "with the following failed type string: " + originalReaderTypeString);
                        }
                    }
                    else
                    {
                        throw new ContentLoadException(
                                  "Could not find ContentTypeReader Type. Please ensure the name of the Assembly that contains the Type matches the assembly in the full type name: " +
                                  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);
        }
コード例 #38
0
        internal ContentTypeReader[] LoadAssetReaders()
        {
#pragma warning disable 0219, 0649
            // Trick to prevent the linker removing the code, but not actually execute the code
            if (falseflag)
            {
                // 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
                var hByteReader            = new ByteReader();
                var hSByteReader           = new SByteReader();
                var hDateTimeReader        = new DateTimeReader();
                var hDecimalReader         = new DecimalReader();
                var hBoundingSphereReader  = new BoundingSphereReader();
                var hBoundingFrustumReader = new BoundingFrustumReader();
                var hRayReader             = new RayReader();
                var hCharListReader        = new ListReader <Char>();
                var hRectangleListReader   = new ListReader <Rectangle>();
                var hVector3ListReader     = new ListReader <Vector3>();
                var hStringListReader      = new ListReader <StringReader>();
                var hSpriteFontReader      = new SpriteFontReader();
                var hTexture2DReader       = new Texture2DReader();
                var hCharReader            = new CharReader();
                var hRectangleReader       = new RectangleReader();
                var hStringReader          = new StringReader();
                var hVector2Reader         = new Vector2Reader();
                var hVector3Reader         = new Vector3Reader();
                var hVector4Reader         = new Vector4Reader();
                var hCurveReader           = new CurveReader();
                var hIndexBufferReader     = new IndexBufferReader();
                var hBoundingBoxReader     = new BoundingBoxReader();
                var hMatrixReader          = new MatrixReader();
                var hBasicEffectReader     = new BasicEffectReader();
                var hVertexBufferReader    = new VertexBufferReader();
                var hAlphaTestEffectReader = new AlphaTestEffectReader();
            }
#pragma warning restore 0219, 0649

            int numberOfReaders;

            // The first content byte i read tells me the number of content readers in this XNB file
            numberOfReaders = _reader.Read7BitEncodedInt();
            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);
        }
コード例 #39
0
		internal ContentTypeReader[] LoadAssetReaders(ContentReader reader)
        {
#pragma warning disable 0219, 0649
            // Trick to prevent the linker removing the code, but not actually execute the code
            if (falseflag)
            {
                // 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
                var hByteReader = new ByteReader();
                var hSByteReader = new SByteReader();
                var hDateTimeReader = new DateTimeReader();
                var hDecimalReader = new DecimalReader();
                var hBoundingSphereReader = new BoundingSphereReader();
                var hBoundingFrustumReader = new BoundingFrustumReader();
                var hRayReader = new RayReader();
                var hCharListReader = new ListReader<Char>();
                var hRectangleListReader = new ListReader<Rectangle>();
                var hRectangleArrayReader = new ArrayReader<Rectangle>();
                var hVector3ListReader = new ListReader<Vector3>();
                var hStringListReader = new ListReader<StringReader>();
				var hIntListReader = new ListReader<Int32>();
                var hSpriteFontReader = new SpriteFontReader();
                var hTexture2DReader = new Texture2DReader();
                var hCharReader = new CharReader();
                var hRectangleReader = new RectangleReader();
                var hStringReader = new StringReader();
                var hVector2Reader = new Vector2Reader();
                var hVector3Reader = new Vector3Reader();
                var hVector4Reader = new Vector4Reader();
                var hCurveReader = new CurveReader();
                var hIndexBufferReader = new IndexBufferReader();
                var hBoundingBoxReader = new BoundingBoxReader();
                var hMatrixReader = new MatrixReader();
                var hBasicEffectReader = new BasicEffectReader();
                var hVertexBufferReader = new VertexBufferReader();
                var hAlphaTestEffectReader = new AlphaTestEffectReader();
                var hEnumSpriteEffectsReader = new EnumReader<Graphics.SpriteEffects>();
                var hArrayFloatReader = new ArrayReader<float>();
                var hArrayVector2Reader = new ArrayReader<Vector2>();
                var hListVector2Reader = new ListReader<Vector2>();
                var hArrayMatrixReader = new ArrayReader<Matrix>();
                var hEnumBlendReader = new EnumReader<Graphics.Blend>();
                var hNullableRectReader = new NullableReader<Rectangle>();
				var hEffectMaterialReader = new EffectMaterialReader();
				var hExternalReferenceReader = new ExternalReferenceReader();
                var hSoundEffectReader = new SoundEffectReader();
                var hSongReader = new SongReader();
                var hModelReader = new ModelReader();
                var hInt32Reader = new Int32Reader();

                // At the moment the Video class doesn't exist
                // on all platforms... Allow it to compile anyway.
#if ANDROID || IOS || MONOMAC || (WINDOWS && !OPENGL) || (WINRT && !WINDOWS_PHONE)
                var hVideoReader = new VideoReader();
#endif
            }
#pragma warning restore 0219, 0649

		    // The first content byte i read tells me the number of content readers in this XNB file
            var numberOfReaders = reader.Read7BitEncodedInt();
            var contentReaders = new ContentTypeReader[numberOfReaders];
            var needsInitialize = new BitArray(numberOfReaders);
            _contentReaders = new Dictionary<Type, ContentTypeReader>(numberOfReaders);

            // Lock until we're done allocating and initializing any new
            // content type readers...  this ensures we can load content
            // from multiple threads and still cache the readers.
            lock (_locker)
            {
                // 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 (var 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();

                    Func<ContentTypeReader> readerFunc;
                    if (typeCreators.TryGetValue(originalReaderTypeString, out readerFunc))
                    {
                        contentReaders[i] = readerFunc();
                        needsInitialize[i] = true;
                    }
                    else
                    {
                        //System.Diagnostics.Debug.WriteLine(originalReaderTypeString);

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

                        readerTypeString = PrepareType(readerTypeString);

                        var l_readerType = Type.GetType(readerTypeString);
                        if (l_readerType != null)
                        {
                            ContentTypeReader typeReader;
                            if (!_contentReadersCache.TryGetValue(l_readerType, out typeReader))
                            {
                                try
                                {
                                    typeReader = l_readerType.GetDefaultConstructor().Invoke(null) as ContentTypeReader;
                                }
                                catch (TargetInvocationException ex)
                                {
                                    // If you are getting here, the Mono runtime is most likely not able to JIT the type.
                                    // In particular, MonoTouch needs help instantiating types that are only defined in strings in Xnb files. 
                                    throw new InvalidOperationException(
                                        "Failed to get default constructor for ContentTypeReader. To work around, add a creation function to ContentTypeReaderManager.AddTypeCreator() " +
                                        "with the following failed type string: " + originalReaderTypeString, ex);
                                }

                                needsInitialize[i] = true;

                                _contentReadersCache.Add(l_readerType, typeReader);
                            }

                            contentReaders[i] = typeReader;
                        }
                        else
                            throw new ContentLoadException(
                                    "Could not find ContentTypeReader Type. Please ensure the name of the Assembly that contains the Type matches the assembly in the full type name: " +
                                    originalReaderTypeString + " (" + readerTypeString + ")");
                    }

                    var targetType = contentReaders[i].TargetType;
                    if (targetType != null)
                      _contentReaders.Add(targetType, contentReaders[i]);

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

                // Initialize any new readers.
                for (var i = 0; i < contentReaders.Length; i++)
                {
                    if (needsInitialize.Get(i))
                        contentReaders[i].Initialize(this);
                }

            } // lock (_locker)

		    return contentReaders;
        }
コード例 #40
0
        internal ContentTypeReader[] LoadAssetReaders(ContentReader reader)
        {
#pragma warning disable 0219, 0649

            /* Trick to prevent the linker removing the code, but not actually execute the code
             * FIXME: Do we really need this in FNA?
             */
            if (falseflag)
            {
                /* 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
                 */
                ByteReader                hByteReader            = new ByteReader();
                SByteReader               hSByteReader           = new SByteReader();
                DateTimeReader            hDateTimeReader        = new DateTimeReader();
                DecimalReader             hDecimalReader         = new DecimalReader();
                BoundingSphereReader      hBoundingSphereReader  = new BoundingSphereReader();
                BoundingFrustumReader     hBoundingFrustumReader = new BoundingFrustumReader();
                RayReader                 hRayReader             = new RayReader();
                ListReader <char>         hCharListReader        = new ListReader <Char>();
                ListReader <Rectangle>    hRectangleListReader   = new ListReader <Rectangle>();
                ArrayReader <Rectangle>   hRectangleArrayReader  = new ArrayReader <Rectangle>();
                ListReader <Vector3>      hVector3ListReader     = new ListReader <Vector3>();
                ListReader <StringReader> hStringListReader      = new ListReader <StringReader>();
                ListReader <int>          hIntListReader         = new ListReader <Int32>();
                SpriteFontReader          hSpriteFontReader      = new SpriteFontReader();
                Texture2DReader           hTexture2DReader       = new Texture2DReader();
                CharReader                hCharReader            = new CharReader();
                RectangleReader           hRectangleReader       = new RectangleReader();
                StringReader              hStringReader          = new StringReader();
                Vector2Reader             hVector2Reader         = new Vector2Reader();
                Vector3Reader             hVector3Reader         = new Vector3Reader();
                Vector4Reader             hVector4Reader         = new Vector4Reader();
                CurveReader               hCurveReader           = new CurveReader();
                IndexBufferReader         hIndexBufferReader     = new IndexBufferReader();
                BoundingBoxReader         hBoundingBoxReader     = new BoundingBoxReader();
                MatrixReader              hMatrixReader          = new MatrixReader();
                BasicEffectReader         hBasicEffectReader     = new BasicEffectReader();
                VertexBufferReader        hVertexBufferReader    = new VertexBufferReader();
                AlphaTestEffectReader     hAlphaTestEffectReader = new AlphaTestEffectReader();
                EnumReader <Microsoft.Xna.Framework.Graphics.SpriteEffects> hEnumSpriteEffectsReader = new EnumReader <Graphics.SpriteEffects>();
                ArrayReader <float>   hArrayFloatReader   = new ArrayReader <float>();
                ArrayReader <Vector2> hArrayVector2Reader = new ArrayReader <Vector2>();
                ListReader <Vector2>  hListVector2Reader  = new ListReader <Vector2>();
                ArrayReader <Matrix>  hArrayMatrixReader  = new ArrayReader <Matrix>();
                EnumReader <Microsoft.Xna.Framework.Graphics.Blend> hEnumBlendReader = new EnumReader <Graphics.Blend>();
                NullableReader <Rectangle> hNullableRectReader      = new NullableReader <Rectangle>();
                EffectMaterialReader       hEffectMaterialReader    = new EffectMaterialReader();
                ExternalReferenceReader    hExternalReferenceReader = new ExternalReferenceReader();
                SoundEffectReader          hSoundEffectReader       = new SoundEffectReader();
                SongReader  hSongReader  = new SongReader();
                ModelReader hModelReader = new ModelReader();
                Int32Reader hInt32Reader = new Int32Reader();
            }
#pragma warning restore 0219, 0649

            /* The first content byte i read tells me the number of
             * content readers in this XNB file.
             */
            int numberOfReaders                 = reader.Read7BitEncodedInt();
            ContentTypeReader[] newReaders      = new ContentTypeReader[numberOfReaders];
            BitArray            needsInitialize = new BitArray(numberOfReaders);
            contentReaders = new Dictionary <Type, ContentTypeReader>(numberOfReaders);

            /* Lock until we're done allocating and initializing any new
             * content type readers... this ensures we can load content
             * from multiple threads and still cache the readers.
             */
            lock (locker)
            {
                /* 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 += 1)
                {
                    /* This string tells us what reader we
                     * need to decode the following data.
                     */
                    string originalReaderTypeString = reader.ReadString();

                    Func <ContentTypeReader> readerFunc;
                    if (typeCreators.TryGetValue(originalReaderTypeString, out readerFunc))
                    {
                        newReaders[i]      = readerFunc();
                        needsInitialize[i] = true;
                    }
                    else
                    {
                        // Need to resolve namespace differences
                        string readerTypeString = originalReaderTypeString;
                        readerTypeString = PrepareType(readerTypeString);

                        Type l_readerType = Type.GetType(readerTypeString);
                        if (l_readerType != null)
                        {
                            ContentTypeReader typeReader;
                            if (!contentReadersCache.TryGetValue(l_readerType, out typeReader))
                            {
                                try
                                {
                                    typeReader = l_readerType.GetDefaultConstructor().Invoke(null) as ContentTypeReader;
                                }
                                catch (TargetInvocationException ex)
                                {
                                    /* If you are getting here, the Mono runtime
                                     * is most likely not able to JIT the type.
                                     * In particular, MonoTouch needs help
                                     * instantiating types that are only defined
                                     * in strings in Xnb files.
                                     */
                                    throw new InvalidOperationException(
                                              "Failed to get default constructor for ContentTypeReader. " +
                                              "To work around, add a creation function to ContentTypeReaderManager.AddTypeCreator() " +
                                              "with the following failed type string: " + originalReaderTypeString,
                                              ex
                                              );
                                }

                                needsInitialize[i] = true;

                                contentReadersCache.Add(l_readerType, typeReader);
                            }

                            newReaders[i] = typeReader;
                        }
                        else
                        {
                            throw new ContentLoadException(
                                      "Could not find ContentTypeReader Type. " +
                                      "Please ensure the name of the Assembly that " +
                                      "contains the Type matches the assembly in the full type name: " +
                                      originalReaderTypeString + " (" + readerTypeString + ")"
                                      );
                        }
                    }

                    contentReaders.Add(newReaders[i].TargetType, newReaders[i]);

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

                // Initialize any new readers.
                for (int i = 0; i < newReaders.Length; i += 1)
                {
                    if (needsInitialize.Get(i))
                    {
                        newReaders[i].Initialize(this);
                    }
                }
            }             // lock (locker)

            return(newReaders);
        }
コード例 #41
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 &&
                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)
            {
                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);
        }
コード例 #42
0
 protected internal override string Read(ContentReader input, string existingInstance)
 {
     return(input.ReadString());
 }
コード例 #43
0
        internal ContentTypeReader[] LoadAssetReaders(ContentReader reader)
        {
            #pragma warning disable 0219, 0649
            /* Trick to prevent the linker removing the code, but not actually execute the code
             * FIXME: Do we really need this in FNA?
             */
            if (falseflag)
            {
                /* 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
                 */
                ByteReader hByteReader = new ByteReader();
                SByteReader hSByteReader = new SByteReader();
                DateTimeReader hDateTimeReader = new DateTimeReader();
                DecimalReader hDecimalReader = new DecimalReader();
                BoundingSphereReader hBoundingSphereReader = new BoundingSphereReader();
                BoundingFrustumReader hBoundingFrustumReader = new BoundingFrustumReader();
                RayReader hRayReader = new RayReader();
                ListReader<char> hCharListReader = new ListReader<Char>();
                ListReader<Rectangle> hRectangleListReader = new ListReader<Rectangle>();
                ArrayReader<Rectangle> hRectangleArrayReader = new ArrayReader<Rectangle>();
                ListReader<Vector3> hVector3ListReader = new ListReader<Vector3>();
                ListReader<StringReader> hStringListReader = new ListReader<StringReader>();
                ListReader<int> hIntListReader = new ListReader<Int32>();
                SpriteFontReader hSpriteFontReader = new SpriteFontReader();
                Texture2DReader hTexture2DReader = new Texture2DReader();
                CharReader hCharReader = new CharReader();
                RectangleReader hRectangleReader = new RectangleReader();
                StringReader hStringReader = new StringReader();
                Vector2Reader hVector2Reader = new Vector2Reader();
                Vector3Reader hVector3Reader = new Vector3Reader();
                Vector4Reader hVector4Reader = new Vector4Reader();
                CurveReader hCurveReader = new CurveReader();
                IndexBufferReader hIndexBufferReader = new IndexBufferReader();
                BoundingBoxReader hBoundingBoxReader = new BoundingBoxReader();
                MatrixReader hMatrixReader = new MatrixReader();
                BasicEffectReader hBasicEffectReader = new BasicEffectReader();
                VertexBufferReader hVertexBufferReader = new VertexBufferReader();
                AlphaTestEffectReader hAlphaTestEffectReader = new AlphaTestEffectReader();
                EnumReader<Microsoft.Xna.Framework.Graphics.SpriteEffects> hEnumSpriteEffectsReader = new EnumReader<Graphics.SpriteEffects>();
                ArrayReader<float> hArrayFloatReader = new ArrayReader<float>();
                ArrayReader<Vector2> hArrayVector2Reader = new ArrayReader<Vector2>();
                ListReader<Vector2> hListVector2Reader = new ListReader<Vector2>();
                ArrayReader<Matrix> hArrayMatrixReader = new ArrayReader<Matrix>();
                EnumReader<Microsoft.Xna.Framework.Graphics.Blend> hEnumBlendReader = new EnumReader<Graphics.Blend>();
                NullableReader<Rectangle> hNullableRectReader = new NullableReader<Rectangle>();
                EffectMaterialReader hEffectMaterialReader = new EffectMaterialReader();
                ExternalReferenceReader hExternalReferenceReader = new ExternalReferenceReader();
                SoundEffectReader hSoundEffectReader = new SoundEffectReader();
                SongReader hSongReader = new SongReader();
            }
            #pragma warning restore 0219, 0649

            /* The first content byte i read tells me the number of
             * content readers in this XNB file.
             */
            int numberOfReaders = reader.Read7BitEncodedInt();
            ContentTypeReader[] newReaders = new ContentTypeReader[numberOfReaders];
            BitArray needsInitialize = new BitArray(numberOfReaders);
            contentReaders = new Dictionary<Type, ContentTypeReader>(numberOfReaders);

            /* Lock until we're done allocating and initializing any new
             * content type readers... this ensures we can load content
             * from multiple threads and still cache the readers.
             */
            lock (locker)
            {
                /* 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 += 1)
                {
                    /* This string tells us what reader we
                     * need to decode the following data.
                     */
                    string originalReaderTypeString = reader.ReadString();

                    Func<ContentTypeReader> readerFunc;
                    if (typeCreators.TryGetValue(originalReaderTypeString, out readerFunc))
                    {
                        newReaders[i] = readerFunc();
                        needsInitialize[i] = true;
                    }
                    else
                    {
                        // Need to resolve namespace differences
                        string readerTypeString = originalReaderTypeString;
                        readerTypeString = PrepareType(readerTypeString);

                        Type l_readerType = Type.GetType(readerTypeString);
                        if (l_readerType != null)
                        {
                            ContentTypeReader typeReader;
                            if (!contentReadersCache.TryGetValue(l_readerType, out typeReader))
                            {
                                try
                                {
                                    typeReader = l_readerType.GetDefaultConstructor().Invoke(null) as ContentTypeReader;
                                }
                                catch (TargetInvocationException ex)
                                {
                                    /* If you are getting here, the Mono runtime
                                     * is most likely not able to JIT the type.
                                     * In particular, MonoTouch needs help
                                     * instantiating types that are only defined
                                     * in strings in Xnb files.
                                     */
                                    throw new InvalidOperationException(
                                        "Failed to get default constructor for ContentTypeReader. " +
                                        "To work around, add a creation function to ContentTypeReaderManager.AddTypeCreator() " +
                                        "with the following failed type string: " + originalReaderTypeString,
                                        ex
                                    );
                                }

                                needsInitialize[i] = true;

                                contentReadersCache.Add(l_readerType, typeReader);
                            }

                            newReaders[i] = typeReader;
                        }
                        else
                        {
                            throw new ContentLoadException(
                                    "Could not find ContentTypeReader Type. " +
                                    "Please ensure the name of the Assembly that " +
                                    "contains the Type matches the assembly in the full type name: " +
                                    originalReaderTypeString + " (" + readerTypeString + ")"
                            );
                        }
                    }

                    contentReaders.Add(newReaders[i].TargetType, newReaders[i]);

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

                // Initialize any new readers.
                for (int i = 0; i < newReaders.Length; i += 1)
                {
                    if (needsInitialize.Get(i))
                    {
                        newReaders[i].Initialize(this);
                    }
                }
            } // lock (locker)

            return newReaders;
        }
コード例 #44
0
        internal ContentTypeReader[] LoadAssetReaders(ContentReader reader)
        {
#pragma warning disable 0219, 0649
            // Trick to prevent the linker removing the code, but not actually execute the code
            if (falseflag)
            {
                // 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
                var hByteReader              = new ByteReader();
                var hSByteReader             = new SByteReader();
                var hDateTimeReader          = new DateTimeReader();
                var hDecimalReader           = new DecimalReader();
                var hBoundingSphereReader    = new BoundingSphereReader();
                var hBoundingFrustumReader   = new BoundingFrustumReader();
                var hRayReader               = new RayReader();
                var hCharListReader          = new ListReader <Char>();
                var hRectangleListReader     = new ListReader <Rectangle>();
                var hRectangleArrayReader    = new ArrayReader <Rectangle>();
                var hVector3ListReader       = new ListReader <Vector3>();
                var hStringListReader        = new ListReader <StringReader>();
                var hIntListReader           = new ListReader <Int32>();
                var hSpriteFontReader        = new SpriteFontReader();
                var hTexture2DReader         = new Texture2DReader();
                var hCharReader              = new CharReader();
                var hRectangleReader         = new RectangleReader();
                var hStringReader            = new StringReader();
                var hVector2Reader           = new Vector2Reader();
                var hVector3Reader           = new Vector3Reader();
                var hVector4Reader           = new Vector4Reader();
                var hCurveReader             = new CurveReader();
                var hIndexBufferReader       = new IndexBufferReader();
                var hBoundingBoxReader       = new BoundingBoxReader();
                var hMatrixReader            = new MatrixReader();
                var hBasicEffectReader       = new BasicEffectReader();
                var hVertexBufferReader      = new VertexBufferReader();
                var hAlphaTestEffectReader   = new AlphaTestEffectReader();
                var hEnumSpriteEffectsReader = new EnumReader <Graphics.SpriteEffects>();
                var hArrayFloatReader        = new ArrayReader <float>();
                var hArrayVector2Reader      = new ArrayReader <Vector2>();
                var hListVector2Reader       = new ListReader <Vector2>();
                var hArrayMatrixReader       = new ArrayReader <Matrix>();
                var hEnumBlendReader         = new EnumReader <Graphics.Blend>();
                var hNullableRectReader      = new NullableReader <Rectangle>();
                var hEffectMaterialReader    = new EffectMaterialReader();
                var hExternalReferenceReader = new ExternalReferenceReader();
                var hSoundEffectReader       = new SoundEffectReader();
                var hSongReader              = new SongReader();
                var hModelReader             = new ModelReader();
                var hInt32Reader             = new Int32Reader();
                var hEffectReader            = new EffectReader();
                var hSingleReader            = new SingleReader();

                // At the moment the Video class doesn't exist
                // on all platforms... Allow it to compile anyway.
#if ANDROID || (IOS && !TVOS) || MONOMAC || (WINDOWS && !OPENGL) || WINDOWS_UAP
                var hVideoReader = new VideoReader();
#endif
            }
#pragma warning restore 0219, 0649

            // The first content byte i read tells me the number of content readers in this XNB file
            var numberOfReaders = reader.Read7BitEncodedInt();
            var contentReaders  = new ContentTypeReader[numberOfReaders];
            var needsInitialize = new BitArray(numberOfReaders);
            _contentReaders = new Dictionary <Type, ContentTypeReader>(numberOfReaders);

            // Lock until we're done allocating and initializing any new
            // content type readers...  this ensures we can load content
            // from multiple threads and still cache the readers.
            lock (_locker)
            {
                // 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 (var 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();

                    Func <ContentTypeReader> readerFunc;
                    if (typeCreators.TryGetValue(originalReaderTypeString, out readerFunc))
                    {
                        contentReaders[i]  = readerFunc();
                        needsInitialize[i] = true;
                    }
                    else
                    {
                        //System.Diagnostics.Debug.WriteLine(originalReaderTypeString);

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

                        readerTypeString = PrepareType(readerTypeString);

                        var l_readerType = Type.GetType(readerTypeString);
                        if (l_readerType != null)
                        {
                            ContentTypeReader typeReader;
                            if (!_contentReadersCache.TryGetValue(l_readerType, out typeReader))
                            {
                                try
                                {
                                    typeReader = l_readerType.GetDefaultConstructor().Invoke(null) as ContentTypeReader;
                                }
                                catch (TargetInvocationException ex)
                                {
                                    // If you are getting here, the Mono runtime is most likely not able to JIT the type.
                                    // In particular, MonoTouch needs help instantiating types that are only defined in strings in Xnb files.
                                    throw new InvalidOperationException(
                                              "Failed to get default constructor for ContentTypeReader. To work around, add a creation function to ContentTypeReaderManager.AddTypeCreator() " +
                                              "with the following failed type string: " + originalReaderTypeString, ex);
                                }

                                needsInitialize[i] = true;

                                _contentReadersCache.Add(l_readerType, typeReader);
                            }

                            contentReaders[i] = typeReader;
                        }
                        else
                        {
                            throw new ContentLoadException(
                                      "Could not find ContentTypeReader Type. Please ensure the name of the Assembly that contains the Type matches the assembly in the full type name: " +
                                      originalReaderTypeString + " (" + readerTypeString + ")");
                        }
                    }

                    var targetType = contentReaders[i].TargetType;
                    if (targetType != null)
                    {
                        if (!_contentReaders.ContainsKey(targetType))
                        {
                            _contentReaders.Add(targetType, contentReaders[i]);
                        }
                    }

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

                // Initialize any new readers.
                for (var i = 0; i < contentReaders.Length; i++)
                {
                    if (needsInitialize.Get(i))
                    {
                        contentReaders[i].Initialize(this);
                    }
                }
            } // lock (_locker)

            return(contentReaders);
        }
コード例 #45
0
 private void loadTextures(ContentReader input, int textures_count)
 {
     list_textures = new Dictionary<string, Texture>();
     for (int i = 0; i < textures_count; ++i)
     {
         string key = input.ReadString();
         Texture texture = input.ReadExternalReference<Texture>();
         list_textures.Add(key, texture);
     }
 }