Exemplo n.º 1
0
 internal void ReadSharedResources()
 {
     if (this.sharedResourceCount <= 0)
     {
         return;
     }
     object[] objArray = new object[this.sharedResourceCount];
     for (int index = 0; index < this.sharedResourceCount; ++index)
     {
         int num = this.Read7BitEncodedInt();
         if (num > 0)
         {
             ContentTypeReader typeReader = this.typeReaders[num - 1];
             objArray[index] = this.ReadObject <object>(typeReader);
         }
         else
         {
             objArray[index] = (object)null;
         }
     }
     foreach (KeyValuePair <int, Action <object> > keyValuePair in this.sharedResourceFixups)
     {
         keyValuePair.Value(objArray[keyValuePair.Key]);
     }
 }
Exemplo n.º 2
0
        public T ReadObject <T>(ContentTypeReader typeReader)
        {
            T result = (T)typeReader.Read(this, default(T));

            RecordDisposable(result);
            return(result);
        }
Exemplo n.º 3
0
 protected internal override void Initialize(ContentTypeReaderManager manager)
 {
     keyType     = typeof(TKey);
     valueType   = typeof(TValue);
     keyReader   = manager.GetTypeReader(keyType);
     valueReader = manager.GetTypeReader(valueType);
 }
Exemplo n.º 4
0
        internal object ReadAsset <T>()
        {
            object result = null;

            typeReaderManager = new ContentTypeReaderManager(this);
            typeReaders       = typeReaderManager.LoadAssetReaders();
            foreach (ContentTypeReader r in typeReaders)
            {
                r.Initialize(typeReaderManager);
            }

            int sharedResourceCount = Read7BitEncodedInt();

            sharedResourceFixups = new List <KeyValuePair <int, Action <object> > >();

            // Read primary object
            int index = Read7BitEncodedInt();

            if (index > 0)
            {
                ContentTypeReader contentReader = typeReaders[index - 1];
                result = ReadObject <T>(contentReader);
            }

            // Read shared resources
            if (sharedResourceCount > 0)
            {
                ReadSharedResources(sharedResourceCount);
            }

            return(result);
        }
Exemplo n.º 5
0
        internal void ReadSharedResources()
        {
            if (sharedResourceCount <= 0)
            {
                return;
            }

            object[] sharedResources = new object[sharedResourceCount];
            for (int i = 0; i < sharedResourceCount; i += 1)
            {
                int index = Read7BitEncodedInt();
                if (index > 0)
                {
                    ContentTypeReader contentReader = typeReaders[index - 1];
                    sharedResources[i] = ReadObject <object>(contentReader);
                }
                else
                {
                    sharedResources[i] = null;
                }
            }
            // Fixup shared resources by calling each registered action
            foreach (KeyValuePair <int, Action <object> > fixup in sharedResourceFixups)
            {
                fixup.Value(sharedResources[fixup.Key]);
            }
        }
Exemplo n.º 6
0
 public T ReadObject <T>(ContentTypeReader typeReader, T existingInstance)
 {
     if (!typeReader.TargetType.IsValueType)
     {
         return((T)ReadObject <object>());
     }
     return((T)typeReader.Read(this, existingInstance));
 }
Exemplo n.º 7
0
        protected internal override void Initialize(ContentTypeReaderManager manager)
        {
#if WEB
            elementReader = manager.GetTypeReader(typeof(T));
#else
            Type readerType = Enum.GetUnderlyingType(typeof(T));
            elementReader = manager.GetTypeReader(readerType);
#endif
        }
Exemplo n.º 8
0
        protected internal override void Initialize(ContentTypeReaderManager manager)
        {
            base.Initialize(manager);

            Type baseType = TargetType.BaseType;

            if (baseType != null && baseType != typeof(object))
            {
                baseTypeReader = manager.GetTypeReader(baseType);
            }

            constructor = TargetType.GetDefaultConstructor();

            const BindingFlags attrs = (
                BindingFlags.NonPublic |
                BindingFlags.Public |
                BindingFlags.Instance |
                BindingFlags.DeclaredOnly
                );

            /* Sometimes, overridden properties of abstract classes can show up even with
             * BindingFlags.DeclaredOnly is passed to GetProperties. Make sure that
             * all properties in this list are defined in this class by comparing
             * its get method with that of its base class. If they're the same
             * Then it's an overridden property.
             */
            PropertyInfo[] properties = TargetType.GetProperties(attrs);
            FieldInfo[]    fields     = TargetType.GetFields(attrs);
            readers = new List <ReadElement>(fields.Length + properties.Length);

            // Gather the properties.
            foreach (PropertyInfo property in properties)
            {
                MethodInfo pm = property.GetGetMethod(true);
                if (pm == null || pm != pm.GetBaseDefinition())
                {
                    continue;
                }

                ReadElement read = GetElementReader(manager, property);
                if (read != null)
                {
                    readers.Add(read);
                }
            }

            // Gather the fields.
            foreach (FieldInfo field in fields)
            {
                ReadElement read = GetElementReader(manager, field);
                if (read != null)
                {
                    readers.Add(read);
                }
            }
        }
Exemplo n.º 9
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();
            CurveReader     hCurveReader     = new CurveReader();

            int numberOfReaders;

            ContentTypeReader[] contentReaders;


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

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

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

                readerTypeString = PrepareType(readerTypeString);

                Type l_readerType = Type.GetType(readerTypeString);

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

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

            return(contentReaders);
        }
Exemplo n.º 10
0
        public T ReadObject <T>(T existingInstance)
        {
            ContentTypeReader typeReader = typeReaderManager.GetTypeReader(typeof(T));

            if (typeReader != null)
            {
                return((T)typeReader.Read(this, existingInstance));
            }
            throw new ContentLoadException(String.Format("Could not read object type " + typeof(T).Name));
        }
Exemplo n.º 11
0
        public T ReadObject <T>(ContentTypeReader typeReader, T existingInstance)
        {
            if (!typeReader.TargetType.IsValueType)
            {
                return((T)ReadObject <object>());
            }
            T result = (T)typeReader.Read(this, existingInstance);

            RecordDisposable(result);
            return(result);
        }
Exemplo n.º 12
0
        public T ReadObject<T>(ContentTypeReader typeReader, T existingInstance)
        {
            if (!ReflectionHelpers.IsValueType(typeReader.TargetType))
                return ReadObject(existingInstance);

            var result = (T)typeReader.Read(this, existingInstance);

            RecordDisposable(result);

            return result;
        }
        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);
        }
Exemplo n.º 14
0
        private T ReadAsset <T>(string assetName, System.IO.Stream assetStream,
                                Action <IDisposable> recordDisposableObject)
        {
            // GG EDIT removed code for loading raw assets like pngs

            // Load a XNB file
            ContentReader            reader      = new ContentReader(this, assetStream, this.graphicsDeviceService.GraphicsDevice);
            ContentTypeReaderManager typeManager = new ContentTypeReaderManager(reader);

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

            System.Diagnostics.Debug.Assert(dummy == 0);

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

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

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

            // GG EDIT added IDisposable recording
            T tresult = (T)result;

            if (tresult is IDisposable)
            {
                if (recordDisposableObject == null)
                {
                    // GG TODO: would call local method here
                }
                else
                {
                    recordDisposableObject((IDisposable)tresult);
                }
            }

            return(tresult);
        }
Exemplo n.º 15
0
        public T ReadObject <T>(ContentTypeReader typeReader, T existingInstance)
        {
#if WINRT
            if (!typeReader.TargetType.GetTypeInfo().IsValueType)
#else
            if (!typeReader.TargetType.IsValueType)
#endif
            { return((T)ReadObject <object>()); }

            var result = (T)typeReader.Read(this, existingInstance);

            RecordDisposable(result);

            return(result);
        }
Exemplo n.º 16
0
        protected internal override void Initialize(ContentTypeReaderManager manager)
        {
            base.Initialize(manager);
            this.manager = manager;
            Type baseType = this.targetType.BaseType;

            if (baseType != (Type)null && baseType != typeof(object))
            {
                this.baseType       = baseType;
                this.baseTypeReader = manager.GetTypeReader(this.baseType);
            }
            this.constructor = ContentExtensions.GetDefaultConstructor(this.targetType);
            this.properties  = ContentExtensions.GetAllProperties(this.targetType);
            this.fields      = ContentExtensions.GetAllFields(this.targetType);
        }
Exemplo n.º 17
0
        protected internal override void Initialize(ContentTypeReaderManager manager)
        {
            base.Initialize(manager);
            this.manager = manager;
            Type type = targetType.BaseType;

            if (type != null && type != typeof(object))
            {
                baseType       = type;
                baseTypeReader = manager.GetTypeReader(baseType);
            }
            constructor = targetType.GetDefaultConstructor();
            properties  = targetType.GetAllProperties();
            fields      = targetType.GetAllFields();
        }
Exemplo n.º 18
0
        protected internal override void Initialize(ContentTypeReaderManager manager)
        {
            base.Initialize(manager);
            this.manager = manager;

            if (targetType.BaseType != null && targetType.BaseType != typeof(object))
            {
                baseType       = targetType.BaseType;
                baseTypeReader = manager.GetTypeReader(baseType);
            }

            BindingFlags attrs = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;

            constructor = targetType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new Type[0], null);
            properties  = targetType.GetProperties(attrs);
            fields      = targetType.GetFields(attrs);
        }
Exemplo n.º 19
0
        private T InnerReadObject <T>(T existingInstance)
        {
            int typeReaderIndex = Read7BitEncodedInt();

            if (typeReaderIndex == 0)
            {
                return(existingInstance);
            }
            if (typeReaderIndex > typeReaders.Length)
            {
                throw new ContentLoadException(
                          "Incorrect type reader index found!"
                          );
            }
            ContentTypeReader typeReader = typeReaders[typeReaderIndex - 1];
            T result = (T)typeReader.Read(this, default(T));

            RecordDisposable(result);
            return(result);
        }
Exemplo n.º 20
0
        public T ReadObject <T>()
        {
            int index = base.Read7BitEncodedInt();

            if (index == 0)
            {
                return(default(T));
            }

            index--;

            if (index >= this.typeReaders.Length)
            {
                throw new Exception();
            }

            ContentTypeReader reader = this.typeReaders[index];

            return(this.ReadObject <T>(reader));
        }
Exemplo n.º 21
0
        protected internal override void Initialize(ContentTypeReaderManager manager)
        {
            base.Initialize(manager);

            var baseType = ReflectionHelpers.GetBaseType(TargetType);

            if (baseType != null && baseType != typeof(object))
            {
                _baseTypeReader = manager.GetTypeReader(baseType);
            }

            _constructor = TargetType.GetDefaultConstructor();

            var properties = TargetType.GetAllProperties();
            var fields     = TargetType.GetAllFields();

            _readers = new List <ReadElement>(fields.Length + properties.Length);

            // Gather the properties.
            foreach (var property in properties)
            {
                var read = GetElementReader(manager, property);
                if (read != null)
                {
                    _readers.Add(read);
                }
            }

            // Gather the fields.
            foreach (var field in fields)
            {
                var read = GetElementReader(manager, field);
                if (read != null)
                {
                    _readers.Add(read);
                }
            }
        }
Exemplo n.º 22
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);
        }
Exemplo n.º 23
0
        protected internal override void Initialize(ContentTypeReaderManager manager)
        {
            base.Initialize(manager);

            Type baseType = TargetType.BaseType;

            if (baseType != null && baseType != typeof(object))
            {
                baseTypeReader = manager.GetTypeReader(baseType);
            }

            constructor = TargetType.GetDefaultConstructor();

            PropertyInfo[] properties = TargetType.GetAllProperties();
            FieldInfo[]    fields     = TargetType.GetAllFields();
            readers = new List <ReadElement>(fields.Length + properties.Length);

            // Gather the properties.
            foreach (PropertyInfo property in properties)
            {
                ReadElement read = GetElementReader(manager, property);
                if (read != null)
                {
                    readers.Add(read);
                }
            }

            // Gather the fields.
            foreach (FieldInfo field in fields)
            {
                ReadElement read = GetElementReader(manager, field);
                if (read != null)
                {
                    readers.Add(read);
                }
            }
        }
Exemplo n.º 24
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;
        }
Exemplo n.º 25
0
        private void Read(object parent, ContentReader input, MemberInfo member)
        {
            PropertyInfo property = member as PropertyInfo;
            FieldInfo    field    = member as FieldInfo;

            if (property != (PropertyInfo)null && (!property.CanWrite || !property.CanRead))
            {
                return;
            }
            if (property != (PropertyInfo)null && property.Name == "Item")
            {
                MethodInfo getMethod = property.GetGetMethod();
                MethodInfo setMethod = property.GetSetMethod();
                if (getMethod != (MethodInfo)null && getMethod.GetParameters().Length > 0 || setMethod != (MethodInfo)null && setMethod.GetParameters().Length > 0)
                {
                    return;
                }
            }
            if (Attribute.GetCustomAttribute(member, typeof(ContentSerializerIgnoreAttribute)) != null)
            {
                return;
            }
            Attribute customAttribute = Attribute.GetCustomAttribute(member, typeof(ContentSerializerAttribute));
            bool      flag            = false;

            if (customAttribute != null)
            {
                flag = (customAttribute as ContentSerializerAttribute).SharedResource;
            }
            else if (property != (PropertyInfo)null)
            {
                foreach (MethodBase methodBase in property.GetAccessors(true))
                {
                    if (!methodBase.IsPublic)
                    {
                        return;
                    }
                }
            }
            else if (!field.IsPublic)
            {
                return;
            }
            Type type;
            ContentTypeReader typeReader = !(property != (PropertyInfo)null) ? this.manager.GetTypeReader(type = field.FieldType) : this.manager.GetTypeReader(type = property.PropertyType);

            if (!flag)
            {
                object childObject = ReflectiveReader <T> .CreateChildObject(property, field);

                object obj = typeReader != null || !(type == typeof(object)) ? input.ReadObject <object>(typeReader, childObject) : input.ReadObject <object>();
                if (property != (PropertyInfo)null)
                {
                    property.SetValue(parent, obj, (object[])null);
                }
                else
                {
                    if (field.IsPrivate && customAttribute == null)
                    {
                        return;
                    }
                    field.SetValue(parent, obj);
                }
            }
            else
            {
                Action <object> fixup = (Action <object>)(value =>
                {
                    if (property != (PropertyInfo)null)
                    {
                        property.SetValue(parent, value, (object[])null);
                    }
                    else
                    {
                        field.SetValue(parent, value);
                    }
                });
                input.ReadSharedResource <object>(fixup);
            }
        }
Exemplo n.º 26
0
 public T ReadRawObject <T>(ContentTypeReader typeReader, T existingInstance)
 {
     return((T)typeReader.Read(this, existingInstance));
 }
        public ContentTypeReader[] LoadAssetReaders(ContentReader reader)
        {
            // Dummy variables required for it to work on iDevices ** DO NOT DELETE **
            // This forces the classes not to be optimized out when deploying to iDevices
            ListReader<Char> hCharListReader = new ListReader<Char>();
            ListReader<Rectangle> hRectangleListReader = new ListReader<Rectangle>();
            ListReader<Vector3> hVector3ListReader = new ListReader<Vector3>();
            ListReader<StringReader> hStringListReader = new ListReader<StringReader>();
            SpriteFontReader hSpriteFontReader = new SpriteFontReader();
            Texture2DReader hTexture2DReader = new Texture2DReader();
            CharReader hCharReader = new CharReader();
            RectangleReader hRectangleReader = new RectangleReader();
            StringReader hStringReader = new StringReader();
            Vector3Reader hVector3Reader = new Vector3Reader();
            int numberOfReaders;
            ContentTypeReader[] contentReaders;

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

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

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

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

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

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

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

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

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

                readerTypeString = PrepareType(readerTypeString);

                Type l_readerType = Type.GetType(readerTypeString);

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

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

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

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

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

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

                readerTypeString = PrepareType(readerTypeString);

                Type l_readerType = Type.GetType(readerTypeString);

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

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

            return contentReaders;
        }
Exemplo n.º 29
0
 public T ReadRawObject <T>(ContentTypeReader typeReader)
 {
     return((T)ReadRawObject <T>(typeReader, default(T)));
 }
		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;
        }
Exemplo n.º 31
0
        protected internal override void Initialize(ContentTypeReaderManager manager)
        {
            Type readerType = typeof(T);

            elementReader = manager.GetTypeReader(readerType);
        }
Exemplo n.º 32
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);
        }
Exemplo n.º 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;
        }
Exemplo n.º 34
0
 public T ReadRawObject <T>(ContentTypeReader typeReader, T existingInstance)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 35
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);
        }
Exemplo n.º 36
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;
        }