Example #1
0
        internal ObjectLayer(ContentReader reader, ObjectRegistry registry)
            : base(reader)
        {
            _registry = registry;
            _objects = new List<ObjectInstance>();

            int objCount = reader.ReadInt32();
            for (int i = 0; i < objCount; i++) {
                int id = reader.ReadInt32();
                int dx = reader.ReadInt32();
                int dy = reader.ReadInt32();
                float rotation = reader.ReadSingle();
                float scaleX = reader.ReadSingle();
                float scaleY = reader.ReadSingle();

                PropertyCollection properties = new PropertyCollection(reader);

                _objects.Add(new ObjectInstance(_registry.GetObjectPool(id), id, dx, dy) {
                    Rotation = rotation,
                    ScaleX = scaleX,
                    ScaleY = scaleY,
                    Properties = properties,
                });
            }
        }
Example #2
0
        public static VGFontData Deserialize(ContentReader reader)
        {
            var data = new VGFontData
            {
                FillRule = (VGFillRule)reader.ReadByte(),
                EmSquareSize = reader.ReadSingle(),
                LeadingSize = reader.ReadSingle(),
                Extents = reader.ReadVector4(),
                Vertices = new StencilVertex[reader.ReadInt32()],
                Glyphs = new VGFontData.GlyphInfo[reader.ReadInt32()]
            };

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

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

            data.Kerning = VGKerningTable.Deserialize(reader);
            return data;
        }
Example #3
0
 /// <summary>
 /// Initializes a new instance of the Wall class.
 /// Important: SetFromToVectors must be called afterwards!
 /// </summary>
 /// <param name="reader">The Content Type Reader.</param>
 public Wall(ContentReader reader)
 {
     fromIndex = reader.ReadInt32();
       toIndex = reader.ReadInt32();
       height = reader.ReadSingle();
       wallTexture = reader.ReadExternalReference<Texture2D>();
 }
		/// <summary></summary><param name="reader"></param>
		public ParticleSystemCompiledShaderData(ContentReader reader)
		{
			this.CompressedShaderCode = reader.ReadBytes(reader.ReadInt32());
			this.ColourSamplerIndex = reader.ReadInt32();
			this.UserSamplerIndex = reader.ReadInt32();
			this.LifeSamplerIndex = reader.ReadInt32();
		}
 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);
     }
 }
Example #6
0
        internal TileSet(ContentReader reader)
            : this()
        {
            _manager = reader.ContentManager;

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

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

            Properties = new PropertyCollection(reader);

            int tileCount = reader.ReadInt32();
            for (int i = 0; i < tileCount; i++) {
                int tileId = reader.ReadInt32();
                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);
        }
Example #7
0
        private void ReadBones(ContentReader input)
        {
            ModelBone[] bones = new ModelBone[input.ReadInt32()];

            for (int i = 0; i < bones.Length; i++)
            {
                string name = input.ReadObject<string>();
                Matrix transform = input.ReadMatrix();
                bones[i] = new ModelBone(i, name, transform);
            }

            this.bones = new ModelBoneCollection(bones);

            foreach (ModelBone bone in bones)
            {
                ModelBone newParent = this.ReadBoneReference(input);
                int size = input.ReadInt32();
                ModelBone[] newChildren = new ModelBone[size];
                for (int j = 0; j < size; j++)
                {
                    newChildren[j] = this.ReadBoneReference(input);
                }
                bone.SetParentChildren(newParent, newChildren);
            }
        }
 internal OgmoLayerSettings(ContentReader reader)
 {
     this.GridColor = reader.ReadColor();
     this.GridDrawSize = reader.ReadInt32();
     this.GridSize = reader.ReadInt32();
     this.Name = reader.ReadString();
 }
Example #9
0
        /// <summary>
        /// Initializes a new instance of the Tower class.
        /// </summary>
        /// <param name="reader">The Content Reader for Castle XML Files</param>
        public Tower(ContentReader reader)
        {
            id = reader.ReadInt32();
              hasCannon = reader.ReadBoolean();
              var position = reader.ReadObject<Vector2>();
              x = (int)position.X;
              y = (int)position.Y;
              height = reader.ReadSingle();
              corners = reader.ReadInt32();
              radius = reader.ReadSingle();
              coverRadius = reader.ReadSingle();
              coverHeight = reader.ReadSingle();
              viewDirection = new Vector3(x, coverHeight + 2, y + 1);

              wallTexture = reader.ReadExternalReference<Texture2D>();
              coverTexture = reader.ReadExternalReference<Texture2D>();

              ////InitTowerGraphics();

              if (HasCannon)
              {
            hasCannon = true;
            cannon = new Cannon(X, coverHeight, Y, null);
              }
        }
 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();
 }
 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();
 }
Example #12
0
        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();
        }
Example #13
0
        internal ObjectLayer(ContentReader reader, ObjectRegistry registry)
            : base(reader)
        {
            _registry = registry;
            _objects = new List<ObjectInstance>();

            int objCount = reader.ReadInt32();
            for (int i = 0; i < objCount; i++) {
                int dx = reader.ReadInt32();
                int dy = reader.ReadInt32();
                int id = reader.ReadInt16();

                _objects.Add(new ObjectInstance(_registry.GetObjectPool(id), id, dx, dy));
            }
        }
Example #14
0
        public XACTPatch(ContentReader input)
        {
            try
            {
                input.ReadByte();
                char[] header = input.ReadChars(4);
                if ( string.Compare( new string(header), "S**T" ) != 0 )
                    throw new Exception( "Caught Exception: Binary not in S**T format!" );
                int count = input.ReadInt32();
                if ( count > 128 ) count = 128; // Cap the maximum number of instruments
                for ( uint i = 0; i < count; ++i )
                {
                    _InstrumentInfo info = new _InstrumentInfo();
                    info.Name = input.ReadString();

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

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

                    m_Instruments[patchNumber] = info;
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Example #15
0
        internal TileLayer(ContentReader reader, TileRegistry registry)
            : base(reader)
        {
            _registry = registry;

            TileWidth = reader.ReadInt16();
            TileHeight = reader.ReadInt16();
            Width = reader.ReadInt16();
            Height = reader.ReadInt16();

            _tiles = new TileGrid(Width, Height);

            int stackCount = reader.ReadInt32();
            for (int i = 0; i < stackCount; i++) {
                int dx = reader.ReadInt16();
                int dy = reader.ReadInt16();

                int tcount = reader.ReadInt16();
                Tile[] st = new Tile[tcount];

                for (int j = 0; j < tcount; j++) {
                    st[j] = _registry[reader.ReadInt16()];
                }

                _tiles[dx, dy] = new TileStack(st);
            }
        }
        /// <summary>
        /// Constructor reads instanced model data from our custom XNB format.
        /// </summary>
        internal InstancedModelPart( ContentReader input, GraphicsDevice graphicsDevice )
        {
            this.graphicsDevice = graphicsDevice;

              // Load the model data.
              indexCount = input.ReadInt32();
              vertexCount = input.ReadInt32();
              vertexStride = input.ReadInt32();

              vertexDeclaration = input.ReadObject<VertexDeclaration>();
              vertexBuffer = input.ReadObject<VertexBuffer>();
              indexBuffer = input.ReadObject<IndexBuffer>();

              input.ReadSharedResource<Effect>( delegate( Effect value )
              {
            effect = value;

            // accessors
            EffectParameterColor = effect.Parameters["Color"];
            EffectParameterDiffuseMap = effect.Parameters["DiffuseMap"];
            EffectParameterSpecularPower = effect.Parameters["SpecularPower"];

            effectParameterView = effect.Parameters["View"];
            effectParameterProjection = effect.Parameters["Projection"];
            effectParameterEye = effect.Parameters["Eye"];
            effectParameterVertexCount = effect.Parameters["VertexCount"];
            effectParameterInstanceTransforms = effect.Parameters["InstanceTransforms"];
              } );

              // Work out how many shader instances we can fit into a single batch.
              int indexOverflowLimit = ushort.MaxValue / vertexCount;

              maxInstances = Math.Min( indexOverflowLimit, MaxShaderMatrices );

              // On Xbox, we must replicate several copies of our index buffer data for
              // the VFetch instancing technique. We could alternatively precompute this
              // in the content processor, but that would bloat the size of the XNB file.
              // It is more efficient to generate the repeated values at load time.
              //
              // We also require replicated index data for the Windows ShaderInstancing
              // technique, but this is computed lazily on Windows, so as to avoid
              // bloating the index buffer if it turns out that we only ever use the
              // HardwareInstancingTechnique (which does not require any repeated data).

              ReplicateIndexData();
        }
Example #17
0
        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;
                }
            }
        }
Example #18
0
 private static VertexDeclaration[] ReadVertexDeclarations(ContentReader input)
 {
     int length = input.ReadInt32();
     VertexDeclaration[] declarationArray = new VertexDeclaration[length];
     for (int i = 0; i < length; i++)
     {
         declarationArray[i] = input.ReadObject<VertexDeclaration>();
     }
     return declarationArray;
 }
Example #19
0
        public Terrain( ContentReader input)
        {
            m_xLength = input.ReadInt32();
            m_zLength = input.ReadInt32();
            m_objectMat = Matrix.Identity;

            m_verts = new VertexPositionNormalTexture[m_xLength * m_zLength];
            int i = 0;
            for (int x = 0; x < m_xLength; x++) {
                for (int z = 0; z < m_zLength; z++) {
                    Vector3 point = input.ReadVector3();
                    Vector2 texCoord = new Vector2(x, z);
                    m_verts[i++] = new VertexPositionNormalTexture(point, Vector3.Up, texCoord);
                }
            }
            GenerateIndices();
            VertexUtils.GenerateNormalsForTriangleStrip( m_verts, m_indices );
            CreateRenderData();
        }
        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));
        }
Example #21
0
        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();
        }
Example #22
0
        internal InstancedModel( ContentReader input )
        {
            graphicsDevice = RenderHelper.GetGraphicsDevice( input );

              int partCount = input.ReadInt32();

              for ( int i = 0; i < partCount; i++ )
              {
            modelParts.Add( new InstancedModelPart( this, input, graphicsDevice ) );
              }

              Tag = input.ReadObject<object>();
        }
Example #23
0
        internal Layer(ContentReader reader)
        {
            ScaleX = 1f;
            ScaleY = 1f;

            Id = reader.ReadInt32();
            Name = reader.ReadString();
            Visible = reader.ReadBoolean();
            Opacity = reader.ReadSingle();
            int rasterMode = reader.ReadInt16();

            Properties = new PropertyCollection(reader);
        }
 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));
     }
 }
Example #25
0
        private void ReadAnimations(ContentReader input)
        {
            int numAnimationClips = input.ReadInt32();
            Dictionary<string, AnimationClip> animationClipDictionary =
                new Dictionary<string, AnimationClip>();

            // Read all animation clips
            for (int i = 0; i < numAnimationClips; i++)
            {
                input.ReadSharedResource<AnimationClip>(
                    delegate(AnimationClip animationClip) { animationClipDictionary.Add(animationClip.Name, animationClip); });
            }

            animationClips = new AnimationClipDictionary(animationClipDictionary);
        }
Example #26
0
        internal InstancedModelPart( InstancedModel owner, ContentReader input,
            GraphicsDevice graphicsDevice)
        {
            this.owner = owner;

              indexCount = input.ReadInt32();
              vertexCount = input.ReadInt32();
              vertexStride = input.ReadInt32();

              vertexDeclaration = input.ReadObject<VertexDeclaration>();
              vertexBuffer = input.ReadObject<VertexBuffer>();
              indexBuffer = input.ReadObject<IndexBuffer>();

              input.ReadSharedResource<Effect>( delegate( Effect value )
              {
            Effect = value;
            effectVertexCountParam = Effect.Parameters["VertexCount"];
            effectViewParam = Effect.Parameters["View"];
            effectProjectionParam = Effect.Parameters["Projection"];
            effectEyeParam = Effect.Parameters["EyePosition"];
              } );

              originalVertexDeclaration = vertexDeclaration.GetVertexElements();
        }
 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();
 }
        protected internal override SkinnedEffect Read(
            ContentReader input,
            SkinnedEffect existingInstance
            )
        {
            SkinnedEffect effect = new SkinnedEffect(input.GraphicsDevice);

            effect.Texture          = input.ReadExternalReference <Texture>() as Texture2D;
            effect.WeightsPerVertex = input.ReadInt32();
            effect.DiffuseColor     = input.ReadVector3();
            effect.EmissiveColor    = input.ReadVector3();
            effect.SpecularColor    = input.ReadVector3();
            effect.SpecularPower    = input.ReadSingle();
            effect.Alpha            = input.ReadSingle();
            return(effect);
        }
Example #29
0
        protected internal override Texture3D Read(
            ContentReader reader,
            Texture3D existingInstance
            )
        {
            Texture3D texture = null;

            SurfaceFormat format     = (SurfaceFormat)reader.ReadInt32();
            int           width      = reader.ReadInt32();
            int           height     = reader.ReadInt32();
            int           depth      = reader.ReadInt32();
            int           levelCount = reader.ReadInt32();

            if (existingInstance == null)
            {
                texture = new Texture3D(
                    reader.GraphicsDevice,
                    width,
                    height,
                    depth,
                    levelCount > 1,
                    format
                    );
            }
            else
            {
                texture = existingInstance;
            }

            for (int i = 0; i < levelCount; i += 1)
            {
                int    dataSize = reader.ReadInt32();
                byte[] data     = reader.ReadBytes(dataSize);
                texture.SetData(
                    i,
                    0,
                    0,
                    width,
                    height,
                    0,
                    depth,
                    data,
                    0,
                    dataSize
                    );

                // Calculate dimensions of next mip level.
                width  = Math.Max(width >> 1, 1);
                height = Math.Max(height >> 1, 1);
                depth  = Math.Max(depth >> 1, 1);
            }

            return(texture);
        }
        protected internal override Dictionary <TKey, TValue> Read(ContentReader input, Dictionary <TKey, TValue> existingInstance)
        {
            int count = input.ReadInt32();
            Dictionary <TKey, TValue> dictionary = existingInstance;

            if (dictionary == null)
            {
                dictionary = new Dictionary <TKey, TValue>();
            }
            for (int i = 0; i < count; i++)
            {
                TKey   key;
                TValue value;

#if WINRT
                if (keyType.GetTypeInfo().IsValueType)
#else
                if (keyType.IsValueType)
#endif
                {
                    key = input.ReadObject <TKey>(keyReader);
                }
                else
                {
                    int readerType = input.ReadByte();
                    key = input.ReadObject <TKey>(input.TypeReaders[readerType - 1]);
                }

#if WINRT
                if (valueType.GetTypeInfo().IsValueType)
#else
                if (valueType.IsValueType)
#endif
                {
                    value = input.ReadObject <TValue>(valueReader);
                }
                else
                {
                    int readerType = input.ReadByte();
                    value = input.ReadObject <TValue>(input.TypeReaders[readerType - 1]);
                }

                dictionary.Add(key, value);
            }
            return(dictionary);
        }
        /// <summary>
        /// Constructor reads instanced model data from our custom XNB format.
        /// </summary>
        internal InstancedModel( ContentReader input )
        {
            // Look up our graphics device.
              graphicsDevice = GetGraphicsDevice( input );

              readOnlyParts = new ReadOnlyCollection<InstancedModelPart>( modelParts );

              // Load the model data.
              int partCount = input.ReadInt32();

              for ( int i = 0; i < partCount; i++ )
              {
            modelParts.Add( new InstancedModelPart( input, graphicsDevice ) );
              }

              SetInstancingTechnique( InstancingTechnique.DiffuseColor );
        }
 internal OgmoObjectLayer(ContentReader reader, OgmoLevel level)
     : base(reader)
 {
     int objectCount = reader.ReadInt32();
     if (objectCount > 0)
     {
         for (int i = 0; i < objectCount; i++)
         {
             OgmoObject obj = new OgmoObject(reader);
             if(obj != null)
             if (objects.ContainsKey(obj.Name))
                 objects[obj.Name].Add(obj);
             else
                 objects.Add(obj.Name, new List<OgmoObject>() { obj });
             allObjects.Add(obj);
         }
     }
 }
Example #33
0
        protected internal override SpriteFont Read(ContentReader input, SpriteFont existingInstance)
        {
            Texture2D texture = input.ReadObject <Texture2D>();

            texture.IsSpriteFontTexture = true;
            List <Rectangle> glyphs         = input.ReadObject <List <Rectangle> >();
            List <Rectangle> cropping       = input.ReadObject <List <Rectangle> >();
            List <char>      charMap        = input.ReadObject <List <char> >();
            int            lineSpacing      = input.ReadInt32();
            float          spacing          = input.ReadSingle();
            List <Vector3> kerning          = input.ReadObject <List <Vector3> >();
            char?          defaultCharacter = null;

            if (input.ReadBoolean())
            {
                defaultCharacter = new char?(input.ReadChar());
            }
            return(new SpriteFont(texture, glyphs, cropping, charMap, lineSpacing, spacing, kerning, defaultCharacter));
        }
Example #34
0
        protected internal override IndexBuffer Read(ContentReader input, IndexBuffer existingInstance)
        {
            IndexBuffer indexBuffer = existingInstance;

            bool sixteenBits = input.ReadBoolean();
            int  dataSize    = input.ReadInt32();

            byte[] data = input.ReadBytes(dataSize);

            if (indexBuffer == null)
            {
                indexBuffer = new IndexBuffer(input.GraphicsDevice,
                                              sixteenBits ? IndexElementSize.SixteenBits : IndexElementSize.ThirtyTwoBits,
                                              dataSize / (sixteenBits ? 2 : 4), BufferUsage.None);
            }

            indexBuffer.SetData(data);
            return(indexBuffer);
        }
Example #35
0
        protected internal override List <T> Read(ContentReader input, List <T> existingInstance)
        {
            int      capacity = input.ReadInt32();
            List <T> list     = existingInstance ?? new List <T>(capacity);

            for (int index = 0; index < capacity; ++index)
            {
                if (typeof(T).IsValueType)
                {
                    list.Add(input.ReadObject <T>(this.elementReader));
                }
                else
                {
                    int num = (int)input.ReadByte();
                    list.Add(input.ReadObject <T>(input.TypeReaders[num - 1]));
                }
            }
            return(list);
        }
        protected internal override Dictionary <TKey, TValue> Read(ContentReader input, Dictionary <TKey, TValue> existingInstance)
        {
            int count = input.ReadInt32();
            Dictionary <TKey, TValue> dictionary = existingInstance;

            if (dictionary == null)
            {
                dictionary = new Dictionary <TKey, TValue>(count);
            }
            else
            {
                dictionary.Clear();
            }

            for (int i = 0; i < count; i++)
            {
                TKey   key;
                TValue value;

                if (ReflectionHelpers.IsValueType(keyType))
                {
                    key = input.ReadObject <TKey>(keyReader);
                }
                else
                {
                    var readerType = input.Read7BitEncodedInt();
                    key = readerType > 0 ? input.ReadObject <TKey>(input.TypeReaders[readerType - 1]) : default(TKey);
                }

                if (ReflectionHelpers.IsValueType(valueType))
                {
                    value = input.ReadObject <TValue>(valueReader);
                }
                else
                {
                    var readerType = input.Read7BitEncodedInt();
                    value = readerType > 0 ? input.ReadObject <TValue>(input.TypeReaders[readerType - 1]) : default(TValue);
                }

                dictionary.Add(key, value);
            }
            return(dictionary);
        }
Example #37
0
        protected internal override Song Read(ContentReader input, Song existingInstance)
        {
            string path = input.ReadString();

            path = Path.Combine(input.ContentManager.RootDirectory, path);
            path = FileHelpers.NormalizeFilePathSeparators(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.ReadInt32();

            return(new Song(path, durationMs));
        }
Example #38
0
        protected internal override VertexDeclaration Read(ContentReader reader, VertexDeclaration existingInstance)
        {
            int vertexStride = reader.ReadInt32();
            int length       = reader.ReadInt32();

            VertexElement[] vertexElementArray = new VertexElement[length];
            for (int index = 0; index < length; ++index)
            {
                int offset = reader.ReadInt32();
                VertexElementFormat elementFormat = (VertexElementFormat)reader.ReadInt32();
                VertexElementUsage  elementUsage  = (VertexElementUsage)reader.ReadInt32();
                int usageIndex = reader.ReadInt32();
                vertexElementArray[index] = new VertexElement(offset, elementFormat, elementUsage, usageIndex);
            }
            return(new VertexDeclaration(vertexStride, vertexElementArray));
        }
Example #39
0
        /// <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;
        }
        protected internal override VertexDeclaration Read(ContentReader reader, VertexDeclaration existingInstance)
        {
            var vertexStride = reader.ReadInt32();
            var elementCount = reader.ReadInt32();

            VertexElement[] elements = new VertexElement[elementCount];
            for (int i = 0; i < elementCount; ++i)
            {
                var offset        = reader.ReadInt32();
                var elementFormat = (VertexElementFormat)reader.ReadInt32();
                var elementUsage  = (VertexElementUsage)reader.ReadInt32();
                var usageIndex    = reader.ReadInt32();
                elements[i] = new VertexElement(offset, elementFormat, elementUsage, usageIndex);
            }

            return(VertexDeclaration.GetOrCreate(vertexStride, elements));
        }
        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);
        }
Example #42
0
        protected internal override List <T> Read(ContentReader input, List <T> existingInstance)
        {
            int      count = input.ReadInt32();
            List <T> list  = existingInstance;

            if (list == null)
            {
                list = new List <T>(count);
            }
            for (int i = 0; i < count; i++)
            {
                if (ReflectionHelpers.IsValueType(typeof(T)))
                {
                    list.Add(input.ReadObject <T>(elementReader));
                }
                else
                {
                    var readerType = input.Read7BitEncodedInt();
                    list.Add(readerType > 0 ? input.ReadObject <T>(input.TypeReaders[readerType - 1]) : default(T));
                }
            }
            return(list);
        }
Example #43
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));
        }
Example #44
0
        protected internal override T[] Read(ContentReader input, T[] existingInstance)
        {
            int count = input.ReadInt32();

            T[] array = existingInstance;
            if (array == null)
            {
                array = new T[count];
            }
            for (int i = 0; i < count; i++)
            {
                Type objectType = typeof(T);
                if (objectType.IsValueType)
                {
                    array[i] = input.ReadObject <T>(elementReader);
                }
                else
                {
                    int readerType = input.ReadByte();
                    array[i] = input.ReadObject <T>(input.TypeReaders[readerType - 1]);
                }
            }
            return(array);
        }
Example #45
0
        protected internal override Texture3D Read(ContentReader reader, Texture3D existingInstance)
        {
            SurfaceFormat format    = (SurfaceFormat)reader.ReadInt32();
            int           num1      = reader.ReadInt32();
            int           num2      = reader.ReadInt32();
            int           num3      = reader.ReadInt32();
            int           num4      = reader.ReadInt32();
            Texture3D     texture3D = new Texture3D(reader.GraphicsDevice, num1, num2, num3, num4 > 1, format);

            for (int level = 0; level < num4; ++level)
            {
                int    num5 = reader.ReadInt32();
                byte[] data = reader.ReadBytes(num5);
                texture3D.SetData <byte>(level, 0, 0, num1, num2, 0, num3, data, 0, num5);
                num1 = Math.Max(num1 >> 1, 1);
                num2 = Math.Max(num2 >> 1, 1);
                num3 = Math.Max(num3 >> 1, 1);
            }
            return(texture3D);
        }
Example #46
0
        protected internal override Texture3D Read(ContentReader reader, Texture3D existingInstance)
        {
            Texture3D texture = null;

            SurfaceFormat format = (SurfaceFormat)reader.ReadInt32();
            int width = reader.ReadInt32();
            int height = reader.ReadInt32();
            int depth = reader.ReadInt32();
            int levelCount = reader.ReadInt32();

            if (existingInstance == null)
                texture = new Texture3D(reader.GetGraphicsDevice(), width, height, depth, levelCount > 1, format);
            else
                texture = existingInstance;

#if OPENGL
            Threading.BlockOnUIThread(() =>
            {
#endif
                for (int i = 0; i < levelCount; i++)
                {
                    int dataSize = reader.ReadInt32();
                    byte[] data = ContentManager.ScratchBufferPool.Get(dataSize);
                    reader.Read(data, 0, dataSize);
                    texture.SetData(i, 0, 0, width, height, 0, depth, data, 0, dataSize);

                    // Calculate dimensions of next mip level.
                    width = Math.Max(width >> 1, 1);
                    height = Math.Max(height >> 1, 1);
                    depth = Math.Max(depth >> 1, 1);

                    ContentManager.ScratchBufferPool.Return(data);
                }
#if OPENGL
            });
#endif

            return texture;
        }
Example #47
0
        protected internal override Texture2D Read(ContentReader reader, Texture2D existingInstance)
        {
            SurfaceFormat surfaceFormat;

            if (reader.version < 5)
            {
                switch ((SurfaceFormat_Legacy)reader.ReadInt32())
                {
                case SurfaceFormat_Legacy.Color:
                    surfaceFormat = SurfaceFormat.Color;
                    break;

                case SurfaceFormat_Legacy.Dxt1:
                    surfaceFormat = SurfaceFormat.Dxt1;
                    break;

                case SurfaceFormat_Legacy.Dxt3:
                    surfaceFormat = SurfaceFormat.Dxt3;
                    break;

                case SurfaceFormat_Legacy.Dxt5:
                    surfaceFormat = SurfaceFormat.Dxt5;
                    break;

                default:
                    throw new NotImplementedException();
                }
            }
            else
            {
                surfaceFormat = (SurfaceFormat)reader.ReadInt32();
            }
            int width1  = reader.ReadInt32();
            int height1 = reader.ReadInt32();
            int num1    = reader.ReadInt32();
            int num2    = num1;

            if (num1 > 1 && !GraphicsCapabilities.NonPowerOfTwo && (!MathHelper.IsPowerOfTwo(width1) || !MathHelper.IsPowerOfTwo(height1)))
            {
                num2 = 1;
            }
            SurfaceFormat format = surfaceFormat;

            if (surfaceFormat == SurfaceFormat.NormalizedByte4)
            {
                format = SurfaceFormat.Color;
            }
            if (!GraphicsExtensions.UseDxtCompression)
            {
                switch (surfaceFormat)
                {
                case SurfaceFormat.Dxt1:
                case SurfaceFormat.Dxt3:
                case SurfaceFormat.Dxt5:
                    format = SurfaceFormat.Color;
                    break;
                }
            }
            Texture2D texture2D = existingInstance != null ? existingInstance : new Texture2D(reader.GraphicsDevice, width1, height1, num2 > 1, format);

            for (int level = 0; level < num1; ++level)
            {
                int    count    = reader.ReadInt32();
                byte[] numArray = reader.ReadBytes(count);
                int    width2   = width1 >> level;
                int    height2  = height1 >> level;
                if (level < num2)
                {
                    if (!GraphicsExtensions.UseDxtCompression)
                    {
                        switch (surfaceFormat)
                        {
                        case SurfaceFormat.Dxt1:
                            numArray = DxtUtil.DecompressDxt1(numArray, width2, height2);
                            break;

                        case SurfaceFormat.Dxt3:
                            numArray = DxtUtil.DecompressDxt3(numArray, width2, height2);
                            break;

                        case SurfaceFormat.Dxt5:
                            numArray = DxtUtil.DecompressDxt5(numArray, width2, height2);
                            break;
                        }
                    }
                    switch (surfaceFormat)
                    {
                    case SurfaceFormat.Bgra5551:
                        int startIndex1 = 0;
                        for (int index1 = 0; index1 < height2; ++index1)
                        {
                            for (int index2 = 0; index2 < width2; ++index2)
                            {
                                ushort num3 = BitConverter.ToUInt16(numArray, startIndex1);
                                ushort num4 = (ushort)(((int)num3 & (int)short.MaxValue) << 1 | ((int)num3 & 32768) >> 15);
                                numArray[startIndex1]     = (byte)num4;
                                numArray[startIndex1 + 1] = (byte)((uint)num4 >> 8);
                                startIndex1 += 2;
                            }
                        }
                        break;

                    case SurfaceFormat.Bgra4444:
                        int startIndex2 = 0;
                        for (int index1 = 0; index1 < height2; ++index1)
                        {
                            for (int index2 = 0; index2 < width2; ++index2)
                            {
                                ushort num3 = BitConverter.ToUInt16(numArray, startIndex2);
                                ushort num4 = (ushort)(((int)num3 & 4095) << 4 | ((int)num3 & 61440) >> 12);
                                numArray[startIndex2]     = (byte)num4;
                                numArray[startIndex2 + 1] = (byte)((uint)num4 >> 8);
                                startIndex2 += 2;
                            }
                        }
                        break;

                    case SurfaceFormat.NormalizedByte4:
                        int num5 = GraphicsExtensions.Size(surfaceFormat);
                        int num6 = width2 * num5;
                        for (int index1 = 0; index1 < height2; ++index1)
                        {
                            for (int index2 = 0; index2 < width2; ++index2)
                            {
                                int num3 = BitConverter.ToInt32(numArray, index1 * num6 + index2 * num5);
                                numArray[index1 * num6 + index2 * 4]     = (byte)(num3 >> 16 & (int)byte.MaxValue);
                                numArray[index1 * num6 + index2 * 4 + 1] = (byte)(num3 >> 8 & (int)byte.MaxValue);
                                numArray[index1 * num6 + index2 * 4 + 2] = (byte)(num3 & (int)byte.MaxValue);
                                numArray[index1 * num6 + index2 * 4 + 3] = (byte)(num3 >> 24 & (int)byte.MaxValue);
                            }
                        }
                        break;
                    }
                    texture2D.SetData <byte>(level, new Rectangle?(), numArray, 0, numArray.Length);
                }
            }
            return(texture2D);
        }
Example #48
0
        protected internal override SoundEffect Read(
            ContentReader input,
            SoundEffect existingInstance
            )
        {
            /* Swap endian - this is one of the very few places requiring this!
             * Note: This only affects the fmt chunk that's glued into the file.
             */
            bool se = input.platform == 'x';

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

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

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

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

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

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

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

            return(new SoundEffect(
                       input.AssetName,
                       data,
                       0,
                       data.Length,
                       extra,
                       wFormatTag,
                       nChannels,
                       nSamplesPerSec,
                       nAvgBytesPerSec,
                       nBlockAlign,
                       wBitsPerSample,
                       loopStart,
                       loopLength
                       ));
        }
Example #49
0
        protected internal override Texture2D Read(ContentReader reader, Texture2D existingInstance)
		{
			Texture2D texture = null;

            var surfaceFormat = (SurfaceFormat)reader.ReadInt32();
            int width = reader.ReadInt32();
            int height = reader.ReadInt32();
            int levelCount = reader.ReadInt32();
            int levelCountOutput = levelCount;

            // If the system does not fully support Power of Two textures,
            // skip any mip maps supplied with any non PoT textures.
            if (levelCount > 1 && !reader.GraphicsDevice.GraphicsCapabilities.SupportsNonPowerOfTwo &&
                (!MathHelper.IsPowerOfTwo(width) || !MathHelper.IsPowerOfTwo(height)))
            {
                levelCountOutput = 1;
                System.Diagnostics.Debug.WriteLine(
                    "Device does not support non Power of Two textures. Skipping mipmaps.");
            }

			SurfaceFormat convertedFormat = surfaceFormat;
			switch (surfaceFormat)
			{
				case SurfaceFormat.Dxt1:
				case SurfaceFormat.Dxt1a:
					if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsDxt1)
						convertedFormat = SurfaceFormat.Color;
					break;
				case SurfaceFormat.Dxt1SRgb:
					if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsDxt1)
						convertedFormat = SurfaceFormat.ColorSRgb;
					break;
				case SurfaceFormat.Dxt3:
				case SurfaceFormat.Dxt5:
					if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsS3tc)
						convertedFormat = SurfaceFormat.Color;
					break;
				case SurfaceFormat.Dxt3SRgb:
				case SurfaceFormat.Dxt5SRgb:
					if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsS3tc)
						convertedFormat = SurfaceFormat.ColorSRgb;
					break;
				case SurfaceFormat.NormalizedByte4:
					convertedFormat = SurfaceFormat.Color;
					break;
			}
			
            texture = existingInstance ?? new Texture2D(reader.GraphicsDevice, width, height, levelCountOutput > 1, convertedFormat);
#if OPENGL
            Threading.BlockOnUIThread(() =>
            {
#endif
                for (int level = 0; level < levelCount; level++)
			    {
				    var levelDataSizeInBytes = reader.ReadInt32();
                    var levelData = reader.ContentManager.GetScratchBuffer(levelDataSizeInBytes);
                    reader.Read(levelData, 0, levelDataSizeInBytes);
                    int levelWidth = width >> level;
                    int levelHeight = height >> level;

                    if (level >= levelCountOutput)
                        continue;

				    //Convert the image data if required
				    switch (surfaceFormat)
				    {
					    case SurfaceFormat.Dxt1:
                        case SurfaceFormat.Dxt1SRgb:
                        case SurfaceFormat.Dxt1a:
				            if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsDxt1 && convertedFormat == SurfaceFormat.Color)
				            {
				                levelData = DxtUtil.DecompressDxt1(levelData, levelWidth, levelHeight);
				                levelDataSizeInBytes = levelData.Length;
				            }
				            break;
					    case SurfaceFormat.Dxt3:
					    case SurfaceFormat.Dxt3SRgb:
                            if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsS3tc)
				                if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsS3tc &&
				                    convertedFormat == SurfaceFormat.Color)
				                {
				                    levelData = DxtUtil.DecompressDxt3(levelData, levelWidth, levelHeight);
                                    levelDataSizeInBytes = levelData.Length;
                                }
				            break;
					    case SurfaceFormat.Dxt5:
					    case SurfaceFormat.Dxt5SRgb:
                            if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsS3tc)
				                if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsS3tc &&
				                    convertedFormat == SurfaceFormat.Color)
				                {
				                    levelData = DxtUtil.DecompressDxt5(levelData, levelWidth, levelHeight);
                                    levelDataSizeInBytes = levelData.Length;
                                }
				            break;
                        case SurfaceFormat.Bgra5551:
                            {
#if OPENGL
                                // Shift the channels to suit OpenGL
                                int offset = 0;
                                for (int y = 0; y < levelHeight; y++)
                                {
                                    for (int x = 0; x < levelWidth; x++)
                                    {
                                        ushort pixel = BitConverter.ToUInt16(levelData, offset);
                                        pixel = (ushort)(((pixel & 0x7FFF) << 1) | ((pixel & 0x8000) >> 15));
                                        levelData[offset] = (byte)(pixel);
                                        levelData[offset + 1] = (byte)(pixel >> 8);
                                        offset += 2;
                                    }
                                }
#endif
                            }
                            break;
					    case SurfaceFormat.Bgra4444:
						    {
#if OPENGL
                                // Shift the channels to suit OpenGL
							    int offset = 0;
							    for (int y = 0; y < levelHeight; y++)
							    {
								    for (int x = 0; x < levelWidth; x++)
								    {
									    ushort pixel = BitConverter.ToUInt16(levelData, offset);
									    pixel = (ushort)(((pixel & 0x0FFF) << 4) | ((pixel & 0xF000) >> 12));
									    levelData[offset] = (byte)(pixel);
									    levelData[offset + 1] = (byte)(pixel >> 8);
									    offset += 2;
								    }
							    }
#endif
						    }
						    break;
					    case SurfaceFormat.NormalizedByte4:
						    {
							    int bytesPerPixel = surfaceFormat.GetSize();
							    int pitch = levelWidth * bytesPerPixel;
							    for (int y = 0; y < levelHeight; y++)
							    {
								    for (int x = 0; x < levelWidth; x++)
								    {
									    int color = BitConverter.ToInt32(levelData, y * pitch + x * bytesPerPixel);
									    levelData[y * pitch + x * 4] = (byte)(((color >> 16) & 0xff)); //R:=W
									    levelData[y * pitch + x * 4 + 1] = (byte)(((color >> 8) & 0xff)); //G:=V
									    levelData[y * pitch + x * 4 + 2] = (byte)(((color) & 0xff)); //B:=U
									    levelData[y * pitch + x * 4 + 3] = (byte)(((color >> 24) & 0xff)); //A:=Q
								    }
							    }
						    }
						    break;
				    }
				
                    texture.SetData(level, null, levelData, 0, levelDataSizeInBytes);
			    }
#if OPENGL
            });
#endif
        			
			return texture;
		}
        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);
        }
Example #51
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);
        }
Example #52
0
        protected internal override Model Read(ContentReader reader, Model existingInstance)
        {
            List <ModelBone> bones     = new List <ModelBone>();
            uint             boneCount = reader.ReadUInt32();

            for (uint index = 0U; index < boneCount; ++index)
            {
                string    str       = reader.ReadObject <string>();
                Matrix    matrix    = reader.ReadMatrix();
                ModelBone modelBone = new ModelBone()
                {
                    Transform = matrix,
                    Index     = (int)index,
                    Name      = str
                };
                bones.Add(modelBone);
            }
            for (int index1 = 0; (long)index1 < (long)boneCount; ++index1)
            {
                ModelBone modelBone = bones[index1];
                int       index2    = ModelReader.ReadBoneReference(reader, boneCount);
                if (index2 != -1)
                {
                    modelBone.Parent = bones[index2];
                }
                uint num = reader.ReadUInt32();
                if ((int)num != 0)
                {
                    for (uint index3 = 0U; index3 < num; ++index3)
                    {
                        int index4 = ModelReader.ReadBoneReference(reader, boneCount);
                        if (index4 != -1)
                        {
                            modelBone.AddChild(bones[index4]);
                        }
                    }
                }
            }
            List <ModelMesh> meshes = new List <ModelMesh>();
            int num1 = reader.ReadInt32();

            for (int index1 = 0; index1 < num1; ++index1)
            {
                string         str            = reader.ReadObject <string>();
                int            index2         = ModelReader.ReadBoneReference(reader, boneCount);
                BoundingSphere boundingSphere = reader.ReadBoundingSphere();
                reader.ReadObject <object>();
                int num2 = reader.ReadInt32();
                List <ModelMeshPart> parts = new List <ModelMeshPart>();
                for (uint index3 = 0U; (long)index3 < (long)num2; ++index3)
                {
                    ModelMeshPart modelMeshPart = existingInstance == null ? new ModelMeshPart() : ((ReadOnlyCollection <ModelMesh>)existingInstance.Meshes)[index1].MeshParts[(int)index3];
                    modelMeshPart.VertexOffset   = reader.ReadInt32();
                    modelMeshPart.NumVertices    = reader.ReadInt32();
                    modelMeshPart.StartIndex     = reader.ReadInt32();
                    modelMeshPart.PrimitiveCount = reader.ReadInt32();
                    modelMeshPart.Tag            = reader.ReadObject <object>();
                    parts.Add(modelMeshPart);
                    int jj = (int)index3;
                    reader.ReadSharedResource <VertexBuffer>((Action <VertexBuffer>)(v => parts[jj].VertexBuffer = v));
                    reader.ReadSharedResource <IndexBuffer>((Action <IndexBuffer>)(v => parts[jj].IndexBuffer    = v));
                    reader.ReadSharedResource <Effect>((Action <Effect>)(v => parts[jj].Effect = v));
                }
                if (existingInstance == null)
                {
                    ModelMesh mesh = new ModelMesh(reader.GraphicsDevice, parts);
                    mesh.Name       = str;
                    mesh.ParentBone = bones[index2];
                    mesh.ParentBone.AddMesh(mesh);
                    mesh.BoundingSphere = boundingSphere;
                    meshes.Add(mesh);
                }
            }
            if (existingInstance != null)
            {
                ModelReader.ReadBoneReference(reader, boneCount);
                reader.ReadObject <object>();
                return(existingInstance);
            }
            else
            {
                int   index = ModelReader.ReadBoneReference(reader, boneCount);
                Model model = new Model(reader.GraphicsDevice, bones, meshes);
                model.Root = bones[index];
                model.BuildHierarchy();
                model.Tag = reader.ReadObject <object>();
                return(model);
            }
        }
Example #53
0
        protected internal override Texture2D Read(ContentReader reader, Texture2D existingInstance)
        {
            Texture2D texture = null;

            SurfaceFormat surfaceFormat;

            if (reader.version < 5)
            {
                SurfaceFormatLegacy legacyFormat = (SurfaceFormatLegacy)reader.ReadInt32();
                switch (legacyFormat)
                {
                case SurfaceFormatLegacy.Dxt1:
                    surfaceFormat = SurfaceFormat.Dxt1;
                    break;

                case SurfaceFormatLegacy.Dxt3:
                    surfaceFormat = SurfaceFormat.Dxt3;
                    break;

                case SurfaceFormatLegacy.Dxt5:
                    surfaceFormat = SurfaceFormat.Dxt5;
                    break;

                case SurfaceFormatLegacy.Color:
                    surfaceFormat = SurfaceFormat.Color;
                    break;

                default:
                    throw new NotSupportedException("Unsupported legacy surface format.");
                }
            }
            else
            {
                surfaceFormat = (SurfaceFormat)reader.ReadInt32();
            }

            int width            = (reader.ReadInt32());
            int height           = (reader.ReadInt32());
            int levelCount       = (reader.ReadInt32());
            int levelCountOutput = levelCount;

            // If the system does not fully support Power of Two textures,
            // skip any mip maps supplied with any non PoT textures.
            if (levelCount > 1 && !reader.GraphicsDevice.GraphicsCapabilities.SupportsNonPowerOfTwo &&
                (!MathHelper.IsPowerOfTwo(width) || !MathHelper.IsPowerOfTwo(height)))
            {
                levelCountOutput = 1;
                System.Diagnostics.Debug.WriteLine(
                    "Device does not support non Power of Two textures. Skipping mipmaps.");
            }

            SurfaceFormat convertedFormat = surfaceFormat;

            switch (surfaceFormat)
            {
#if IOS
            // At the moment. If a DXT Texture comes in on iOS, it's really a PVR compressed
            // texture. We need to use this hack until the content pipeline is implemented.
            // For now DXT5 means we're using 4bpp PVRCompression and DXT3 means 2bpp. Look at
            // PvrtcBitmapContent.cs for more information.:
            case SurfaceFormat.Dxt3:
                convertedFormat = SurfaceFormat.RgbaPvrtc2Bpp;
                break;

            case SurfaceFormat.Dxt5:
                convertedFormat = SurfaceFormat.RgbaPvrtc4Bpp;
                break;
#else
            case SurfaceFormat.Dxt1:
            case SurfaceFormat.Dxt1a:
                if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsDxt1)
                {
                    convertedFormat = SurfaceFormat.Color;
                }
                break;

            case SurfaceFormat.Dxt3:
            case SurfaceFormat.Dxt5:
                if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsS3tc)
                {
                    convertedFormat = SurfaceFormat.Color;
                }
                break;
#endif
            case SurfaceFormat.NormalizedByte4:
                convertedFormat = SurfaceFormat.Color;
                break;
            }

            if (existingInstance == null)
            {
                texture = new Texture2D(reader.GraphicsDevice, width, height, levelCountOutput > 1, convertedFormat);
            }
            else
            {
                texture = existingInstance;
            }

            for (int level = 0; level < levelCount; level++)
            {
                int    levelDataSizeInBytes = (reader.ReadInt32());
                byte[] levelData            = reader.ReadBytes(levelDataSizeInBytes);
                int    levelWidth           = width >> level;
                int    levelHeight          = height >> level;

                if (level >= levelCountOutput)
                {
                    continue;
                }

                //Convert the image data if required
                switch (surfaceFormat)
                {
#if !IOS
                case SurfaceFormat.Dxt1:
                case SurfaceFormat.Dxt1a:
                    if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsDxt1)
                    {
                        levelData = DxtUtil.DecompressDxt1(levelData, levelWidth, levelHeight);
                    }
                    break;

                case SurfaceFormat.Dxt3:
                    if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsS3tc)
                    {
                        levelData = DxtUtil.DecompressDxt3(levelData, levelWidth, levelHeight);
                    }
                    break;

                case SurfaceFormat.Dxt5:
                    if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsS3tc)
                    {
                        levelData = DxtUtil.DecompressDxt5(levelData, levelWidth, levelHeight);
                    }
                    break;
#endif
                case SurfaceFormat.Bgr565:
                {
                    /*
                     * // BGR -> BGR
                     * int offset = 0;
                     * for (int y = 0; y < levelHeight; y++)
                     * {
                     *      for (int x = 0; x < levelWidth; x++)
                     *      {
                     *              ushort pixel = BitConverter.ToUInt16(levelData, offset);
                     *              pixel = (ushort)(((pixel & 0x0FFF) << 4) | ((pixel & 0xF000) >> 12));
                     *              levelData[offset] = (byte)(pixel);
                     *              levelData[offset + 1] = (byte)(pixel >> 8);
                     *              offset += 2;
                     *      }
                     * }
                     */
                }
                break;

                case SurfaceFormat.Bgra5551:
                {
#if OPENGL
                    // Shift the channels to suit OPENGL
                    int offset = 0;
                    for (int y = 0; y < levelHeight; y++)
                    {
                        for (int x = 0; x < levelWidth; x++)
                        {
                            ushort pixel = BitConverter.ToUInt16(levelData, offset);
                            pixel                 = (ushort)(((pixel & 0x7FFF) << 1) | ((pixel & 0x8000) >> 15));
                            levelData[offset]     = (byte)(pixel);
                            levelData[offset + 1] = (byte)(pixel >> 8);
                            offset               += 2;
                        }
                    }
#endif
                }
                break;

                case SurfaceFormat.Bgra4444:
                {
#if OPENGL
                    // Shift the channels to suit OPENGL
                    int offset = 0;
                    for (int y = 0; y < levelHeight; y++)
                    {
                        for (int x = 0; x < levelWidth; x++)
                        {
                            ushort pixel = BitConverter.ToUInt16(levelData, offset);
                            pixel                 = (ushort)(((pixel & 0x0FFF) << 4) | ((pixel & 0xF000) >> 12));
                            levelData[offset]     = (byte)(pixel);
                            levelData[offset + 1] = (byte)(pixel >> 8);
                            offset               += 2;
                        }
                    }
#endif
                }
                break;

                case SurfaceFormat.NormalizedByte4:
                {
                    int bytesPerPixel = surfaceFormat.GetSize();
                    int pitch         = levelWidth * bytesPerPixel;
                    for (int y = 0; y < levelHeight; y++)
                    {
                        for (int x = 0; x < levelWidth; x++)
                        {
                            int color = BitConverter.ToInt32(levelData, y * pitch + x * bytesPerPixel);
                            levelData[y * pitch + x * 4]     = (byte)(((color >> 16) & 0xff));                                       //R:=W
                            levelData[y * pitch + x * 4 + 1] = (byte)(((color >> 8) & 0xff));                                        //G:=V
                            levelData[y * pitch + x * 4 + 2] = (byte)(((color) & 0xff));                                             //B:=U
                            levelData[y * pitch + x * 4 + 3] = (byte)(((color >> 24) & 0xff));                                       //A:=Q
                        }
                    }
                }
                break;
                }

                texture.SetData(level, null, levelData, 0, levelData.Length);
            }

            return(texture);
        }
 protected internal override int Read(ContentReader input, int existingInstance)
 {
     return(input.ReadInt32());
 }
Example #55
0
        protected internal override Texture2D Read(
            ContentReader reader,
            Texture2D existingInstance
            )
        {
            Texture2D texture = null;

            SurfaceFormat surfaceFormat;

            if (reader.version < 5)
            {
                /* These integer values are based on the enum values
                 * from previous XNA versions.
                 * -flibit
                 */
                int legacyFormat = reader.ReadInt32();
                if (legacyFormat == 1)
                {
                    surfaceFormat = SurfaceFormat.ColorBgraEXT;
                }
                else if (legacyFormat == 28)
                {
                    surfaceFormat = SurfaceFormat.Dxt1;
                }
                else if (legacyFormat == 30)
                {
                    surfaceFormat = SurfaceFormat.Dxt3;
                }
                else if (legacyFormat == 32)
                {
                    surfaceFormat = SurfaceFormat.Dxt5;
                }
                else
                {
                    throw new NotSupportedException(
                              "Unsupported legacy surface format."
                              );
                }
            }
            else
            {
                surfaceFormat = (SurfaceFormat)reader.ReadInt32();
            }
            int width            = reader.ReadInt32();
            int height           = reader.ReadInt32();
            int levelCount       = reader.ReadInt32();
            int levelCountOutput = levelCount;

            // Check to see if we need to convert the surface data
            SurfaceFormat convertedFormat = surfaceFormat;

            if (surfaceFormat == SurfaceFormat.Dxt1 &&
                !reader.GraphicsDevice.GLDevice.SupportsDxt1)
            {
                convertedFormat = SurfaceFormat.Color;
            }
            else if ((surfaceFormat == SurfaceFormat.Dxt3 ||
                      surfaceFormat == SurfaceFormat.Dxt5) &&
                     !reader.GraphicsDevice.GLDevice.SupportsS3tc)
            {
                convertedFormat = SurfaceFormat.Color;
            }

            // Check for duplicate instances
            if (existingInstance == null)
            {
                texture = new Texture2D(
                    reader.GraphicsDevice,
                    width,
                    height,
                    levelCountOutput > 1,
                    convertedFormat
                    );
            }
            else
            {
                texture = existingInstance;
            }

            for (int level = 0; level < levelCount; level += 1)
            {
                int    levelDataSizeInBytes = reader.ReadInt32();
                byte[] levelData            = null;      // Don't assign this quite yet...
                int    levelWidth           = width >> level;
                int    levelHeight          = height >> level;
                if (level >= levelCountOutput)
                {
                    continue;
                }

                // Swap the image data if required.
                if (reader.platform == 'x')
                {
                    if (surfaceFormat == SurfaceFormat.Color ||
                        surfaceFormat == SurfaceFormat.ColorBgraEXT)
                    {
                        if (levelData == null)
                        {
                            levelData = reader.ReadBytes(levelDataSizeInBytes);
                        }
                        levelData = X360TexUtil.SwapColor(
                            levelData
                            );
                    }
                    else if (surfaceFormat == SurfaceFormat.Dxt1)
                    {
                        if (levelData == null)
                        {
                            levelData = reader.ReadBytes(levelDataSizeInBytes);
                        }
                        levelData = X360TexUtil.SwapDxt1(
                            levelData,
                            levelWidth,
                            levelHeight
                            );
                    }
                    else if (surfaceFormat == SurfaceFormat.Dxt3)
                    {
                        if (levelData == null)
                        {
                            levelData = reader.ReadBytes(levelDataSizeInBytes);
                        }
                        levelData = X360TexUtil.SwapDxt3(
                            levelData,
                            levelWidth,
                            levelHeight
                            );
                    }
                    else if (surfaceFormat == SurfaceFormat.Dxt5)
                    {
                        if (levelData == null)
                        {
                            levelData = reader.ReadBytes(levelDataSizeInBytes);
                        }
                        levelData = X360TexUtil.SwapDxt5(
                            levelData,
                            levelWidth,
                            levelHeight
                            );
                    }
                }

                // Convert the image data if required
                if (surfaceFormat == SurfaceFormat.Dxt1 &&
                    !reader.GraphicsDevice.GLDevice.SupportsDxt1)
                {
                    if (levelData == null)
                    {
                        levelData = reader.ReadBytes(levelDataSizeInBytes);
                    }
                    levelData = DxtUtil.DecompressDxt1(
                        levelData,
                        levelWidth,
                        levelHeight
                        );
                }
                else if (surfaceFormat == SurfaceFormat.Dxt3 &&
                         !reader.GraphicsDevice.GLDevice.SupportsS3tc)
                {
                    if (levelData == null)
                    {
                        levelData = reader.ReadBytes(levelDataSizeInBytes);
                    }
                    levelData = DxtUtil.DecompressDxt3(
                        levelData,
                        levelWidth,
                        levelHeight
                        );
                }
                else if (surfaceFormat == SurfaceFormat.Dxt5 &&
                         !reader.GraphicsDevice.GLDevice.SupportsS3tc)
                {
                    if (levelData == null)
                    {
                        levelData = reader.ReadBytes(levelDataSizeInBytes);
                    }
                    levelData = DxtUtil.DecompressDxt5(
                        levelData,
                        levelWidth,
                        levelHeight
                        );
                }

                if (levelData == null &&
                    reader.BaseStream.GetType() != typeof(System.IO.MemoryStream))
                {
                    /* If the ContentReader is not backed by a
                     * MemoryStream, we have to read the data in.
                     */
                    levelData = reader.ReadBytes(levelDataSizeInBytes);
                }
                if (levelData != null)
                {
                    /* If we had to convert the data, or get the data from a
                     * non-MemoryStream, we set the data with our levelData
                     * reference.
                     */
                    texture.SetData(level, null, levelData, 0, levelData.Length);
                }
                else
                {
                    /* Ideally, we didn't have to perform any conversion or
                     * unnecessary reading. Just throw the buffer directly
                     * into SetData, skipping a redundant byte[] copy.
                     */
                    texture.SetData <byte>(
                        level,
                        null,
                        (((System.IO.MemoryStream)(reader.BaseStream)).GetBuffer()),
                        (int)reader.BaseStream.Position,
                        levelDataSizeInBytes
                        );
                    reader.BaseStream.Seek(
                        levelDataSizeInBytes,
                        System.IO.SeekOrigin.Current
                        );
                }
            }

            return(texture);
        }
Example #56
0
        protected internal override Texture2D Read(
            ContentReader reader,
            Texture2D existingInstance
            )
        {
            Texture2D texture = null;

            SurfaceFormat surfaceFormat;

            if (reader.version < 5)
            {
                SurfaceFormat_Legacy legacyFormat =
                    (SurfaceFormat_Legacy)reader.ReadInt32();
                switch (legacyFormat)
                {
                case SurfaceFormat_Legacy.Dxt1:
                    surfaceFormat = SurfaceFormat.Dxt1;
                    break;

                case SurfaceFormat_Legacy.Dxt3:
                    surfaceFormat = SurfaceFormat.Dxt3;
                    break;

                case SurfaceFormat_Legacy.Dxt5:
                    surfaceFormat = SurfaceFormat.Dxt5;
                    break;

                case SurfaceFormat_Legacy.Color:
                    surfaceFormat = SurfaceFormat.Color;
                    break;

                default:
                    throw new NotSupportedException(
                              "Unsupported legacy surface format."
                              );
                }
            }
            else
            {
                surfaceFormat = (SurfaceFormat)reader.ReadInt32();
            }
            int           width            = reader.ReadInt32();
            int           height           = reader.ReadInt32();
            int           levelCount       = reader.ReadInt32();
            int           levelCountOutput = levelCount;
            SurfaceFormat convertedFormat  = surfaceFormat;

            switch (surfaceFormat)
            {
            case SurfaceFormat.Dxt1:
                if (!OpenGLDevice.Instance.SupportsDxt1)
                {
                    convertedFormat = SurfaceFormat.Color;
                }
                break;

            case SurfaceFormat.Dxt3:
            case SurfaceFormat.Dxt5:
                if (!OpenGLDevice.Instance.SupportsS3tc)
                {
                    convertedFormat = SurfaceFormat.Color;
                }
                break;

            case SurfaceFormat.NormalizedByte4:
                convertedFormat = SurfaceFormat.Color;
                break;
            }
            if (existingInstance == null)
            {
                texture = new Texture2D(
                    reader.GraphicsDevice,
                    width,
                    height,
                    levelCountOutput > 1,
                    convertedFormat
                    );
            }
            else
            {
                texture = existingInstance;
            }

            for (int level = 0; level < levelCount; level += 1)
            {
                int    levelDataSizeInBytes = (reader.ReadInt32());
                byte[] levelData            = null;      // Don't assign this quite yet...
                int    levelWidth           = width >> level;
                int    levelHeight          = height >> level;
                if (level >= levelCountOutput)
                {
                    continue;
                }
                // Convert the image data if required
                switch (surfaceFormat)
                {
                case SurfaceFormat.Dxt1:
                    if (!OpenGLDevice.Instance.SupportsDxt1)
                    {
                        levelData = reader.ReadBytes(levelDataSizeInBytes);
                        levelData = DxtUtil.DecompressDxt1(
                            levelData,
                            levelWidth,
                            levelHeight
                            );
                    }
                    break;

                case SurfaceFormat.Dxt3:
                    if (!OpenGLDevice.Instance.SupportsS3tc)
                    {
                        levelData = reader.ReadBytes(levelDataSizeInBytes);
                        levelData = DxtUtil.DecompressDxt3(
                            levelData,
                            levelWidth,
                            levelHeight
                            );
                    }
                    break;

                case SurfaceFormat.Dxt5:
                    if (!OpenGLDevice.Instance.SupportsS3tc)
                    {
                        levelData = reader.ReadBytes(levelDataSizeInBytes);
                        levelData = DxtUtil.DecompressDxt5(
                            levelData,
                            levelWidth,
                            levelHeight
                            );
                    }
                    break;

                case SurfaceFormat.Bgr565:
                {
                    levelData = reader.ReadBytes(levelDataSizeInBytes);
                }
                break;

                case SurfaceFormat.Bgra5551:
                {
                    levelData = reader.ReadBytes(levelDataSizeInBytes);
                    // Shift the channels to suit OPENGL
                    int offset = 0;
                    for (int y = 0; y < levelHeight; y += 1)
                    {
                        for (int x = 0; x < levelWidth; x += 1)
                        {
                            ushort pixel = BitConverter.ToUInt16(
                                levelData,
                                offset
                                );
                            pixel = (ushort)(
                                ((pixel & 0x7FFF) << 1) |
                                ((pixel & 0x8000) >> 15)
                                );
                            levelData[offset] =
                                (byte)(pixel);
                            levelData[offset + 1] =
                                (byte)(pixel >> 8);
                            offset += 2;
                        }
                    }
                }
                break;

                case SurfaceFormat.Bgra4444:
                {
                    levelData = reader.ReadBytes(levelDataSizeInBytes);
                    // Shift the channels to suit OPENGL
                    int offset = 0;
                    for (int y = 0; y < levelHeight; y += 1)
                    {
                        for (int x = 0; x < levelWidth; x += 1)
                        {
                            ushort pixel = BitConverter.ToUInt16(
                                levelData,
                                offset
                                );
                            pixel = (ushort)(
                                ((pixel & 0x0FFF) << 4) |
                                ((pixel & 0xF000) >> 12)
                                );
                            levelData[offset] =
                                (byte)(pixel);
                            levelData[offset + 1] =
                                (byte)(pixel >> 8);
                            offset += 2;
                        }
                    }
                }
                break;

                case SurfaceFormat.NormalizedByte4:
                {
                    levelData = reader.ReadBytes(levelDataSizeInBytes);
                    int bytesPerPixel = 4;                             // According to Texture.GetFormatSize()
                    int pitch         = levelWidth * bytesPerPixel;
                    for (int y = 0; y < levelHeight; y += 1)
                    {
                        for (int x = 0; x < levelWidth; x += 1)
                        {
                            int color = BitConverter.ToInt32(
                                levelData,
                                y * pitch + x * bytesPerPixel
                                );
                            // R:=W
                            levelData[y * pitch + x * 4] =
                                (byte)(((color >> 16) & 0xff));
                            // G:=V
                            levelData[y * pitch + x * 4 + 1] =
                                (byte)(((color >> 8) & 0xff));
                            // B:=U
                            levelData[y * pitch + x * 4 + 2] =
                                (byte)(((color) & 0xff));
                            // A:=Q
                            levelData[y * pitch + x * 4 + 3] =
                                (byte)(((color >> 24) & 0xff));
                        }
                    }
                }
                break;
                }

                if (levelData == null &&
                    reader.BaseStream.GetType() != typeof(System.IO.MemoryStream))
                {
                    /* If the ContentReader is not backed by a
                     * MemoryStream, we have to read the data in.
                     */
                    levelData = reader.ReadBytes(levelDataSizeInBytes);
                }
                if (levelData != null)
                {
                    /* If we had to convert the data, or get the data from a
                     * non-MemoryStream, we set the data with our levelData
                     * reference.
                     */
                    texture.SetData(level, null, levelData, 0, levelData.Length);
                }
                else
                {
                    /* Ideally, we didn't have to perform any conversion or
                     * unnecessary reading. Just throw the buffer directly
                     * into SetData, skipping a redundant byte[] copy.
                     */
                    texture.SetData <byte>(
                        level,
                        null,
                        (((System.IO.MemoryStream)(reader.BaseStream)).GetBuffer()),
                        (int)reader.BaseStream.Position,
                        levelDataSizeInBytes
                        );
                    reader.BaseStream.Seek(
                        levelDataSizeInBytes,
                        System.IO.SeekOrigin.Current
                        );
                }
            }

            return(texture);
        }
Example #57
0
        protected internal override Model Read(ContentReader reader, Model existingInstance)
        {
            // Read the bone names and transforms.
            uint             boneCount = reader.ReadUInt32();
            List <ModelBone> bones     = new List <ModelBone>((int)boneCount);

            for (uint i = 0; i < boneCount; i += 1)
            {
                string    name   = reader.ReadObject <string>();
                Matrix    matrix = reader.ReadMatrix();
                ModelBone bone   = new ModelBone {
                    Transform = matrix,
                    Index     = (int)i,
                    Name      = name
                };
                bones.Add(bone);
            }
            // Read the bone hierarchy.
            for (int i = 0; i < boneCount; i += 1)
            {
                ModelBone bone = bones[i];
                // Read the parent bone reference.
                int parentIndex = ReadBoneReference(reader, boneCount);
                if (parentIndex != -1)
                {
                    bone.Parent = bones[parentIndex];
                }
                // Read the child bone references.
                uint childCount = reader.ReadUInt32();
                if (childCount != 0)
                {
                    for (uint j = 0; j < childCount; j += 1)
                    {
                        int childIndex = ReadBoneReference(reader, boneCount);
                        if (childIndex != -1)
                        {
                            bone.AddChild(bones[childIndex]);
                        }
                    }
                }
            }

            List <ModelMesh> meshes = new List <ModelMesh>();

            // Read the mesh data.
            int meshCount = reader.ReadInt32();

            for (int i = 0; i < meshCount; i += 1)
            {
                string         name            = reader.ReadObject <string>();
                int            parentBoneIndex = ReadBoneReference(reader, boneCount);
                BoundingSphere boundingSphere  = reader.ReadBoundingSphere();

                // Tag
                object meshTag = reader.ReadObject <object>();

                // Read the mesh part data.
                int partCount = reader.ReadInt32();

                List <ModelMeshPart> parts = new List <ModelMeshPart>(partCount);

                for (uint j = 0; j < partCount; j += 1)
                {
                    ModelMeshPart part;
                    if (existingInstance != null)
                    {
                        part = existingInstance.Meshes[i].MeshParts[(int)j];
                    }
                    else
                    {
                        part = new ModelMeshPart();
                    }

                    part.VertexOffset   = reader.ReadInt32();
                    part.NumVertices    = reader.ReadInt32();
                    part.StartIndex     = reader.ReadInt32();
                    part.PrimitiveCount = reader.ReadInt32();

                    // Tag
                    part.Tag = reader.ReadObject <object>();

                    parts.Add(part);

                    int jj = (int)j;
                    reader.ReadSharedResource <VertexBuffer>(
                        delegate(VertexBuffer v)
                    {
                        parts[jj].VertexBuffer = v;
                    }
                        );
                    reader.ReadSharedResource <IndexBuffer>(
                        delegate(IndexBuffer v)
                    {
                        parts[jj].IndexBuffer = v;
                    }
                        );
                    reader.ReadSharedResource <Effect>(
                        delegate(Effect v)
                    {
                        parts[jj].Effect = v;
                    }
                        );
                }
                if (existingInstance != null)
                {
                    continue;
                }
                ModelMesh mesh = new ModelMesh(reader.GraphicsDevice, parts);
                mesh.Tag        = meshTag;
                mesh.Name       = name;
                mesh.ParentBone = bones[parentBoneIndex];
                mesh.ParentBone.AddMesh(mesh);
                mesh.BoundingSphere = boundingSphere;
                meshes.Add(mesh);
            }
            if (existingInstance != null)
            {
                // Read past remaining data and return existing instance
                ReadBoneReference(reader, boneCount);
                reader.ReadObject <object>();
                return(existingInstance);
            }
            // Read the final pieces of model data.
            int   rootBoneIndex = ReadBoneReference(reader, boneCount);
            Model model         = new Model(reader.GraphicsDevice, bones, meshes);

            model.Root = bones[rootBoneIndex];
            model.BuildHierarchy();
            // Tag?
            model.Tag = reader.ReadObject <object>();
            return(model);
        }
Example #58
0
        protected internal override Texture2D Read(
            ContentReader reader,
            Texture2D existingInstance
            )
        {
            Texture2D texture = null;

            SurfaceFormat surfaceFormat;

            if (reader.version < 5)
            {
                /* These integer values are based on the enum values
                 * from previous XNA versions.
                 * -flibit
                 */
                int legacyFormat = reader.ReadInt32();
                if (legacyFormat == 1)
                {
                    surfaceFormat = SurfaceFormat.ColorBgraEXT;
                }
                else if (legacyFormat == 28)
                {
                    surfaceFormat = SurfaceFormat.Dxt1;
                }
                else if (legacyFormat == 30)
                {
                    surfaceFormat = SurfaceFormat.Dxt3;
                }
                else if (legacyFormat == 32)
                {
                    surfaceFormat = SurfaceFormat.Dxt5;
                }
                else
                {
                    throw new NotSupportedException(
                              "Unsupported legacy surface format."
                              );
                }
            }
            else
            {
                surfaceFormat = (SurfaceFormat)reader.ReadInt32();
            }
            int width            = reader.ReadInt32();
            int height           = reader.ReadInt32();
            int levelCount       = reader.ReadInt32();
            int levelCountOutput = levelCount;

            GraphicsDevice device = reader.ContentManager.GetGraphicsDevice();

            // Check to see if we need to convert the surface data
            SurfaceFormat convertedFormat = surfaceFormat;

            if (surfaceFormat == SurfaceFormat.Dxt1 &&
                !device.GLDevice.SupportsDxt1)
            {
                convertedFormat = SurfaceFormat.Color;
            }
            else if ((surfaceFormat == SurfaceFormat.Dxt3 ||
                      surfaceFormat == SurfaceFormat.Dxt5) &&
                     !device.GLDevice.SupportsS3tc)
            {
                convertedFormat = SurfaceFormat.Color;
            }

            // Check for duplicate instances
            if (existingInstance == null)
            {
                texture = new Texture2D(
                    device,
                    width,
                    height,
                    levelCountOutput > 1,
                    convertedFormat
                    );
            }
            else
            {
                texture = existingInstance;
            }

            for (int level = 0; level < levelCount; level += 1)
            {
                int    levelDataSizeInBytes = reader.ReadInt32();
                byte[] levelData            = null;      // Don't assign this quite yet...
                int    levelWidth           = width >> level;
                int    levelHeight          = height >> level;
                if (level >= levelCountOutput)
                {
                    continue;
                }

                // Swap the image data if required.
                if (reader.platform == 'x')
                {
                    if (surfaceFormat == SurfaceFormat.Color ||
                        surfaceFormat == SurfaceFormat.ColorBgraEXT)
                    {
                        levelData = X360TexUtil.SwapColor(
                            reader.ReadBytes(levelDataSizeInBytes)
                            );
                        levelDataSizeInBytes = levelData.Length;
                    }
                    else if (surfaceFormat == SurfaceFormat.Dxt1)
                    {
                        levelData = X360TexUtil.SwapDxt1(
                            reader.ReadBytes(levelDataSizeInBytes),
                            levelWidth,
                            levelHeight
                            );
                        levelDataSizeInBytes = levelData.Length;
                    }
                    else if (surfaceFormat == SurfaceFormat.Dxt3)
                    {
                        levelData = X360TexUtil.SwapDxt3(
                            reader.ReadBytes(levelDataSizeInBytes),
                            levelWidth,
                            levelHeight
                            );
                        levelDataSizeInBytes = levelData.Length;
                    }
                    else if (surfaceFormat == SurfaceFormat.Dxt5)
                    {
                        levelData = X360TexUtil.SwapDxt5(
                            reader.ReadBytes(levelDataSizeInBytes),
                            levelWidth,
                            levelHeight
                            );
                        levelDataSizeInBytes = levelData.Length;
                    }
                }

                // Convert the image data if required
                if (convertedFormat != surfaceFormat)
                {
                    // May already be read in by 'x' conversion
                    if (levelData == null)
                    {
                        levelData = reader.ReadBytes(levelDataSizeInBytes);
                    }
                    if (surfaceFormat == SurfaceFormat.Dxt1)
                    {
                        levelData = DxtUtil.DecompressDxt1(
                            levelData,
                            levelWidth,
                            levelHeight
                            );
                    }
                    else if (surfaceFormat == SurfaceFormat.Dxt3)
                    {
                        levelData = DxtUtil.DecompressDxt3(
                            levelData,
                            levelWidth,
                            levelHeight
                            );
                    }
                    else if (surfaceFormat == SurfaceFormat.Dxt5)
                    {
                        levelData = DxtUtil.DecompressDxt5(
                            levelData,
                            levelWidth,
                            levelHeight
                            );
                    }
                    levelDataSizeInBytes = levelData.Length;
                }

                int levelDataByteOffset = 0;
                if (levelData == null)
                {
                    if (reader.BaseStream is MemoryStream &&
                        ((MemoryStream)reader.BaseStream).TryGetBuffer(out levelData))
                    {
                        /* Ideally, we didn't have to perform any conversion or
                         * unnecessary reading. Just throw the buffer directly
                         * into SetData, skipping a redundant byte[] copy.
                         */
                        levelDataByteOffset = (int)reader.BaseStream.Seek(0, SeekOrigin.Current);
                        reader.BaseStream.Seek(
                            levelDataSizeInBytes,
                            SeekOrigin.Current
                            );
                    }
                    else
                    {
                        /* If we don't have to perform any conversion and
                         * the ContentReader is not backed by a MemoryStream
                         * with a public buffer, we have to read the data in.
                         */
                        levelData = reader.ReadBytes(levelDataSizeInBytes);
                    }
                }
                texture.SetData(
                    level,
                    null,
                    levelData,
                    levelDataByteOffset,
                    levelDataSizeInBytes
                    );
            }

            return(texture);
        }
Example #59
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);
        }
Example #60
0
        protected internal override Texture2D Read(ContentReader reader, Texture2D existingInstance)
        {
            SurfaceFormat surfaceFormat;

            if (reader.version < 5)
            {
                switch ((SurfaceFormat_Legacy)reader.ReadInt32())
                {
                case SurfaceFormat_Legacy.Color:
                    surfaceFormat = SurfaceFormat.Color;
                    break;

                case SurfaceFormat_Legacy.Dxt1:
                    surfaceFormat = SurfaceFormat.Dxt1;
                    break;

                case SurfaceFormat_Legacy.Dxt3:
                    surfaceFormat = SurfaceFormat.Dxt3;
                    break;

                case SurfaceFormat_Legacy.Dxt5:
                    surfaceFormat = SurfaceFormat.Dxt5;
                    break;

                default:
                    throw new NotImplementedException();
                }
            }
            else
            {
                surfaceFormat = (SurfaceFormat)reader.ReadInt32();
            }
            int           width  = reader.ReadInt32();
            int           height = reader.ReadInt32();
            int           num1   = reader.ReadInt32();
            SurfaceFormat format = surfaceFormat;

            if (surfaceFormat == SurfaceFormat.NormalizedByte4)
            {
                format = SurfaceFormat.Color;
            }
            Texture2D texture2D = existingInstance != null ? existingInstance : new Texture2D(reader.GraphicsDevice, width, height, num1 > 1, format);

            for (int level = 0; level < num1; ++level)
            {
                int    count = reader.ReadInt32();
                byte[] data  = reader.ReadBytes(count);
                int    num2  = width >> level;
                int    num3  = height >> level;
                switch (surfaceFormat)
                {
                case SurfaceFormat.Bgra4444:
                    int startIndex = 0;
                    for (int index1 = 0; index1 < num3; ++index1)
                    {
                        for (int index2 = 0; index2 < num2; ++index2)
                        {
                            ushort num4 = BitConverter.ToUInt16(data, startIndex);
                            ushort num5 = (ushort)(((int)num4 & 4095) << 4 | ((int)num4 & 61440) >> 12);
                            data[startIndex]     = (byte)num5;
                            data[startIndex + 1] = (byte)((uint)num5 >> 8);
                            startIndex          += 2;
                        }
                    }
                    break;

                case SurfaceFormat.NormalizedByte4:
                    int num6 = GraphicsExtensions.Size(surfaceFormat);
                    int num7 = num2 * num6;
                    for (int index1 = 0; index1 < num3; ++index1)
                    {
                        for (int index2 = 0; index2 < num2; ++index2)
                        {
                            int num4 = BitConverter.ToInt32(data, index1 * num7 + index2 * num6);
                            data[index1 * num7 + index2 * 4]     = (byte)(num4 >> 16 & (int)byte.MaxValue);
                            data[index1 * num7 + index2 * 4 + 1] = (byte)(num4 >> 8 & (int)byte.MaxValue);
                            data[index1 * num7 + index2 * 4 + 2] = (byte)(num4 & (int)byte.MaxValue);
                            data[index1 * num7 + index2 * 4 + 3] = (byte)(num4 >> 24 & (int)byte.MaxValue);
                        }
                    }
                    break;
                }
                texture2D.SetData <byte>(level, new Rectangle?(), data, 0, data.Length);
            }
            return(texture2D);
        }