public Patch(string patchFile) { using (FileStream fs = new FileStream(patchFile, FileMode.Open, FileAccess.Read)) using (BinaryReader br = new BinaryReader(fs)) { m_PTCH = br.ReadStruct<PTCH>(); //Debug.Assert(m_PTCH.m_magic.FourCC() == "PTCH"); if (m_PTCH.m_magic.FourCC() != "PTCH") throw new InvalidDataException("not PTCH"); m_MD5 = br.ReadStruct<MD5_>(); Debug.Assert(m_MD5.m_magic.FourCC() == "MD5_"); m_XFRM = br.ReadStruct<XFRM>(); Debug.Assert(m_XFRM.m_magic.FourCC() == "XFRM"); m_type = m_XFRM.m_type.FourCC(); switch (m_type) { case "BSD0": m_unpackedSize = br.ReadInt32(); m_compressedDiffStream = new MemoryStream(br.ReadRemaining()); BSDIFFParse(); break; case "COPY": m_compressedDiffStream = new MemoryStream(br.ReadRemaining()); return; default: Debug.Assert(false, String.Format("Unknown patch type: {0}", m_type)); break; } } }
public STLReader(string fileName) { reader = BinaryReaderExtensions.FromFile(fileName); MPQHeader mHdr = reader.ReadStruct<MPQHeader>(); StlHeader sHdr = reader.ReadStruct<StlHeader>(); //StlEntry sEntry = reader.ReadStruct<StlEntry>(); RecordsCount = sHdr.entriesSize / 0x50; m_rows = new byte[RecordsCount][]; for (int i = 0; i < RecordsCount; ++i) m_rows[i] = reader.ReadBytes(0x50); //StringTable = new Dictionary<int, string>(); //if (reader.BaseStream.Position != reader.BaseStream.Length) //{ // while (reader.BaseStream.Position != reader.BaseStream.Length) // { // if (reader.PeekChar() == 0) // { // reader.BaseStream.Position++; // continue; // } // int offset = (int)reader.BaseStream.Position; // StringTable[offset] = reader.ReadStringNull(); // } //} }
public void it_will_read_bool_true() { using (var reader = new BinaryReader(new MemoryStream(new byte[] { 0xA0 }))) { var value = reader.ReadStruct<bool>(); value.Should().BeTrue(); reader.BaseStream.ShouldBeEof(); } }
public void it_will_read_color() { var expected = Color.FromArgb(0x33, 0x66, 0x99, 0xcc); using (var reader = new BinaryReader(new MemoryStream(new[] { expected.A, expected.R, expected.G, expected.B }))) { var color = reader.ReadStruct<Color>(); color.Should().BeOfType<Color>().And.Be(expected); reader.BaseStream.ShouldBeEof(); } }
public void it_will_read_enum_using_alternate_underlying_type() { const LongEnum expected = LongEnum.B; using (var reader = new BinaryReader(new MemoryStream(BitConverter.GetBytes((long)expected)))) { var value = reader.ReadStruct<LongEnum>(); value.Should().BeOfType<LongEnum>().And.Be(expected); reader.BaseStream.ShouldBeEof(); } }
public void it_will_read_nullable_enum() { const IntEnum expected = IntEnum.B; using (var reader = new BinaryReader(new MemoryStream(BitConverter.GetBytes((int)expected)))) { var value = reader.ReadStruct<IntEnum?>(); value.Should().Be(expected); reader.BaseStream.ShouldBeEof(); } }
private IList<WEDTilemap> ReadTilemaps(BinaryReader reader, IEnumerable<WEDOverlay> overlays) { var tilemaps = new List<WEDTilemap>(); foreach (var overlay in overlays) { reader.BaseStream.Seek(overlay.TileOffset, SeekOrigin.Begin); tilemaps.Add(reader.ReadStruct<WEDTilemap>()); } return tilemaps; }
/// <summary> /// Returns an SM2 map texuture /// </summary> public BitmapSource GetTexture(Map map, int detail, UnitSync unitSync) { UnitSync.NativeMethods.RemoveAllArchives(); UnitSync.NativeMethods.AddAllArchives(map.ArchiveName); ProgressChanged(this, new ProgressChangedEventArgs(0, "Extracting map")); var mapName = map.Name + ".smf"; var smfFileData = unitSync.ReadVfsFile("maps\\" + mapName); var reader = new BinaryReader(new MemoryStream(smfFileData)); var smfHeader = reader.ReadStruct<SMFHeader>(); smfHeader.SelfCheck(); var mapWidth = smfHeader.mapx; var mapHeight = smfHeader.mapy; reader.BaseStream.Position = smfHeader.tilesPtr; var mapTileHeader = reader.ReadStruct<MapTileHeader>(); // get the tile files and the number of tiles they contain var tileFiles = new Dictionary<byte[], int>(); for (var i = 0; i < mapTileHeader.numTileFiles; i++) { var numTiles = reader.ReadInt32(); var tileFileData = unitSync.ReadVfsFile("maps\\" + reader.ReadCString()); tileFiles.Add(tileFileData, numTiles); } // get the position of the tiles var mapUnitInTiles = Tiles.TileMipLevel1Size/smfHeader.texelPerSquare; var tilesX = smfHeader.mapx/mapUnitInTiles; var tilesY = smfHeader.mapy/mapUnitInTiles; var tileIndices = new int[tilesX*tilesY]; for (var i = 0; i < tileIndices.Length; i++) { tileIndices[i] = reader.ReadInt32(); } Tiles.ProgressChanged += (s, e) => ProgressChanged(this, e); UnitSync.NativeMethods.RemoveAllArchives(); // load the tiles return Tiles.LoadTiles(tileFiles, tileIndices, tilesX, tilesY, detail); }
/// <summary> /// Returns n SM2 map texuture /// </summary> public Bitmap GetTexture(string mapArchive, string mapName, int detail, out int width, out int height) { if (!mapName.ToLower().EndsWith("smf")) throw new ArgumentException("Invalid map name"); if (!mapArchive.ToLower().EndsWith("sdz") && !mapArchive.ToLower().EndsWith("sd7")) throw new ArgumentException("Invalid map archive"); ProgressChanged(this, new ProgressChangedEventArgs(0, "Extracting map")); var reader = new BinaryReader(new MemoryStream(ExtractFile(mapArchive, "maps\\" + mapName))); var smfHeader = reader.ReadStruct<SMFHeader>(); smfHeader.SelfCheck(); width = smfHeader.mapx; height = smfHeader.mapy; reader.BaseStream.Position = smfHeader.tilesPtr; var mapTileHeader = reader.ReadStruct<MapTileHeader>(); // get the tile files and the number of tiles they contain var tileFiles = new Dictionary<byte[], int>(); for (var i = 0; i < mapTileHeader.numTileFiles; i++) { var numTiles = reader.ReadInt32(); tileFiles.Add(ExtractFile(mapArchive, "maps\\" + reader.ReadCString()), numTiles); } // get the position of the tiles var mapUnitInTiles = Tiles.TileMipLevel1Size/smfHeader.texelPerSquare; var tilesX = smfHeader.mapx/mapUnitInTiles; var tilesY = smfHeader.mapy/mapUnitInTiles; var tileIndices = new int[tilesX*tilesY]; for (var i = 0; i < tileIndices.Length; i++) { tileIndices[i] = reader.ReadInt32(); } Tiles.ProgressChanged += (s, e) => ProgressChanged(this, e); // load the tiles return Tiles.LoadTiles(tileFiles, tileIndices, tilesX, tilesY, detail); }
public void TestMethod1() { using (var fs = new FileStream("l.bin", FileMode.OpenOrCreate)) { var s = new S(); s.hello = 5; s.world = "hgtr"; s.g = new ST() { blub = 155693 }; var bw = new BinaryWriter(fs); bw.Write(s); } using (var fs = new FileStream("l.bin", FileMode.OpenOrCreate)) { var bw = new BinaryReader(fs); var s = bw.ReadStruct<S>(); } }
//грузим конфиг public static void Load() { //MessageBox.Show(15.ToString()); if (cfgFInfo.Exists) { cfgFSize = cfgFInfo.Length; _bValue = true; //MessageBox.Show("file est"); if (cfgFSize != 0) { //MessageBox.Show(cfgFSize.ToString()); //грузим конфиг using (BinaryReader binReader = new BinaryReader(new FileStream(FileName, FileMode.Open))) { GCDBExtensions.Init(); CfgDatas= binReader.ReadStruct<CfgDataStruct>(); ConString = CfgDatas.ConStr; if (CfgDatas.CfgHdr != _ch) { MessageBox.Show("Ошибка при считывании header'а конфиг файла, создаю новый конфиг"); New(); } } } else { MessageBox.Show(cfgFSize.ToString()); New(); } } else { MessageBox.Show("not ok file"); _bValue = false; } }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; DirectoryInfo di = new DirectoryInfo(this.folder_patch); FileInfo[] fi = di.GetFiles("*.pkt", SearchOption.AllDirectories); int count = 0; foreach (FileInfo f in fi) { if (worker.CancellationPending == true) { e.Cancel = true; break; } worker.ReportProgress(count * 100 / fi.Length); FileStream fs = new FileStream(f.FullName, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); int selectedIndex = 0; if (comboBox1.InvokeRequired) this.comboBox1.BeginInvoke(new Action(() => selectedIndex = comboBox1.SelectedIndex)); else selectedIndex = comboBox1.SelectedIndex; PktFileMainHeader MainHeader = new PktFileMainHeader(); MainHeader = br.ReadStruct<PktFileMainHeader>(); byte[] buffer = br.ReadBytes((int)MainHeader.OptionalHeaderLength); if (MainHeader.Signature[0] == 'P' && MainHeader.Signature[1] == 'K' && MainHeader.Signature[2] == 'T' && MainHeader.MajorVersion == 3 && MainHeader.MinorVersion == 1) { UInt32 counts = 0; while (br.BaseStream.Position != br.BaseStream.Length) { try { if (worker.CancellationPending == true) { e.Cancel = true; break; } string direct = Encoding.UTF8.GetString(br.ReadBytes(4)); var direction = (direct == "SMSG" ? Direction.ToServer : Direction.ToClient); uint UnixTime = br.ReadUInt32(); uint tickCount = br.ReadUInt32(); int optionalHeaderLength1 = br.ReadInt32(); byte[] optionalData1 = new byte[optionalHeaderLength1]; int dataLength = br.ReadInt32(); byte[] data = new byte[dataLength]; optionalData1 = br.ReadBytes(optionalHeaderLength1); data = br.ReadBytes(dataLength); MemoryStream mss = new MemoryStream(data); BinaryReader brr = new BinaryReader(mss); uint opcodes = brr.ReadUInt32(); byte[] byteData = new byte[brr.BaseStream.Length - 4]; byteData = brr.ReadBytes((int)(brr.BaseStream.Length - 4)); if (selectedIndex == 0) { if (opcodes == (uint)WoWOpcodes.SMSG_NEW_WORLD) SMSG_NEW_WORLD(new BinaryReader(new MemoryStream(byteData)), f.FullName, counts); } else if (selectedIndex == 1) { if (opcodes == (uint)WoWOpcodes.CMSG_CREATURE_QUERY) CMSG_CREATURE_QUERY(new BinaryReader(new MemoryStream(byteData)), f.FullName, counts); } else if (selectedIndex == 2) { if (opcodes == (uint)WoWOpcodes.SMSG_INIT_WORLD_STATES) SMSG_INIT_WORLD_STATES(new BinaryReader(new MemoryStream(byteData)), f.FullName, counts); } counts++; } catch { } } br.Close(); fs.Close(); count++; } } }
private WEDDescriptor ReadDescriptor(BinaryReader reader) { return reader.ReadStruct<WEDDescriptor>(); }
IEnumerable<string> GetPathList(BinaryReader reader, RiotArchiveHeader header) { var stream = reader.BaseStream; stream.Seek(header.PathListOffset, SeekOrigin.Begin); var pathListInfo = reader.ReadStruct<RiotPathListHeader>(); var stringOffsets = GetStringOffsets(reader, (int)pathListInfo.Length).ToArray(); foreach (var offset in stringOffsets) { stream.Seek(header.PathListOffset + offset.Offset, SeekOrigin.Begin); yield return BinaryReaderTools.GetStaticLengthString(reader, (int)offset.Length); } }
public bool LoadFromVBM(string filename, int vertexIndex, int normalIndex, int texCoord0Index) { //FILE * f = NULL; FileStream f = new FileStream(filename, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(f); //f = fopen(filename, "rb"); //if(f == NULL) //return false; //fseek(f, 0, SEEK_END); //size_t filesize = ftell(f); //fseek(f, 0, SEEK_SET); long filesize = f.Length; //f.Seek(0, SeekOrigin.End); //f.Seek(0, SeekOrigin.Begin); byte[] data = new byte[filesize]; UnmanagedArray<byte> raw_data; f.Read(data, 0, (int)filesize); //f.Close(); f.Seek(0, SeekOrigin.Begin); //VBM_HEADER * header = (VBM_HEADER *)data; VBM_HEADER header = br.ReadStruct<VBM_HEADER>(); //raw_data = data + header.size + header->num_attribs * sizeof(VBM_ATTRIB_HEADER) + header->num_frames * sizeof(VBM_FRAME_HEADER); //{ // long offset = header.size + header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER)) + header.num_frames * Marshal.SizeOf(typeof(VBM_FRAME_HEADER)); // raw_data = new UnmanagedArray<byte>((int)(data.Length - offset)); // for (int i = 0; i < raw_data.Length; i++) // { // raw_data[i] = data[offset+i]; // } //} //VBM_ATTRIB_HEADER * attrib_header = (VBM_ATTRIB_HEADER *)(data + header.size); VBM_ATTRIB_HEADER attrib_header = br.ReadStruct<VBM_ATTRIB_HEADER>(); //VBM_FRAME_HEADER * frame_header = (VBM_FRAME_HEADER *)(data + header.size + header.num_attribs * sizeof(VBM_ATTRIB_HEADER)); { long offset = header.size + header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER)); f.Seek(offset, SeekOrigin.Begin); } VBM_FRAME_HEADER frame_header = br.ReadStruct<VBM_FRAME_HEADER>(); uint total_data_size = 0; //memcpy(&m_header, header, header.size < Marshal.SizeOf(typeof(VBM_HEADER)) ? header.size : Marshal.SizeOf(typeof(VBM_HEADER))); this.m_header = header; //memcpy(m_attrib, attrib_header, header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER))); { long offset = header.size;// +header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER)); f.Seek(offset, SeekOrigin.Begin); } this.m_attrib = new VBM_ATTRIB_HEADER[header.num_attribs]; for (int i = 0; i < header.num_attribs; i++) { this.m_attrib[i] = br.ReadStruct<VBM_ATTRIB_HEADER>(); } //memcpy(m_frame, frame_header, header.num_frames * Marshal.SizeOf(typeof(VBM_FRAME_HEADER))); { long offset = header.size + header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER));// +header.num_frames * Marshal.SizeOf(typeof(VBM_FRAME_HEADER)); f.Seek(offset, SeekOrigin.Begin); } this.m_frame = new VBM_FRAME_HEADER[header.num_frames]; for (int i = 0; i < header.num_frames; i++) { this.m_frame[i] = br.ReadStruct<VBM_FRAME_HEADER>(); } GL.GenVertexArrays(1, m_vao); GL.BindVertexArray(m_vao[0]); GL.GenBuffers(1, m_attribute_buffer); GL.BindBuffer(BufferTarget.ArrayBuffer, m_attribute_buffer[0]); //uint i; for (uint i = 0; i < header.num_attribs; i++) { total_data_size += m_attrib[i].components * sizeof(float) * header.num_vertices; } { long offset = header.size + header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER)) + header.num_frames * Marshal.SizeOf(typeof(VBM_FRAME_HEADER)); raw_data = new UnmanagedArray<byte>((int)total_data_size); for (int i = 0; i < raw_data.Length; i++) { raw_data[i] = data[offset + i]; } } //GL.BufferData(GL_ARRAY_BUFFER, total_data_size, raw_data, GL_STATIC_DRAW); GL.BufferData(BufferTarget.ArrayBuffer, raw_data, BufferUsage.StaticDraw); total_data_size = 0; for (uint i = 0; i < header.num_attribs; i++) { uint attribIndex = i; if (attribIndex == 0) attribIndex = (uint)vertexIndex; else if (attribIndex == 1) attribIndex = (uint)normalIndex; else if (attribIndex == 2) attribIndex = (uint)texCoord0Index; GL.VertexAttribPointer(attribIndex, (int)m_attrib[i].components, m_attrib[i].type, false, 0, new IntPtr(total_data_size)); GL.EnableVertexAttribArray(attribIndex); total_data_size += m_attrib[i].components * sizeof(float) * header.num_vertices; } if (header.num_indices > 0) { GL.GenBuffers(1, m_index_buffer); GL.BindBuffer(BufferTarget.ElementArrayBuffer, m_index_buffer[0]); uint element_size; if (header.indexype == 0x1403) { element_size = sizeof(ushort); } else { element_size = sizeof(uint); } //GL.BufferData(GL_ELEMENT_ARRAY_BUFFER, header.num_indices * element_size, raw_data + total_data_size, GL_STATIC_DRAW); UnmanagedArray<byte> tmp = new UnmanagedArray<byte>((int)(header.num_indices * element_size)); for (int t = 0; t < tmp.Length; t++) { tmp[t] = raw_data[(int)(t + total_data_size)]; } GL.BufferData(BufferTarget.ElementArrayBuffer, tmp, BufferUsage.StaticDraw); tmp.Dispose(); } GL.BindVertexArray(0); if (m_header.num_materials != 0) { m_material = new VBM_MATERIAL[m_header.num_materials]; //memcpy(m_material, raw_data + total_data_size, m_header.num_materials * sizeof(VBM_MATERIAL)); { var offset = header.size + total_data_size; f.Seek(offset, SeekOrigin.Begin); } for (int t = 0; t < m_header.num_materials; t++) { m_material[t] = br.ReadStruct<VBM_MATERIAL>(); } total_data_size += (uint)(m_header.num_materials * Marshal.SizeOf(typeof(VBM_MATERIAL))); m_material_textures = new material_texture[m_header.num_materials]; //memset(m_material_textures, 0, m_header.num_materials * sizeof(*m_material_textures)); { var offset = 0; f.Seek(0, SeekOrigin.Begin); } for (int t = 0; t < m_header.num_materials; t++) { m_material_textures[t] = br.ReadStruct<material_texture>(); } } if (m_header.num_chunks != 0) { m_chunks = new VBM_RENDER_CHUNK[m_header.num_chunks]; //memcpy(m_chunks, raw_data + total_data_size, m_header.num_chunks * sizeof(VBM_RENDER_CHUNK)); { var offset = m_header.size + total_data_size; f.Seek(offset, SeekOrigin.Begin); } for (int t = 0; t < m_header.num_chunks; t++) { m_chunks[t] = br.ReadStruct<VBM_RENDER_CHUNK>(); } //total_data_size += m_header.num_chunks * sizeof(VBM_RENDER_CHUNK); } raw_data.Dispose(); return true; }
IEnumerable<RiotPathListItem> GetStringOffsets(BinaryReader reader, int stringCount) { for (int i = 0; i < stringCount; i++) yield return reader.ReadStruct<RiotPathListItem>(); }
private void BSDIFFParse() { using (MemoryStream ms = RLEUnpack()) using (BinaryReader br = new BinaryReader(ms)) { BSDIFF40 m_BSDIFF40 = br.ReadStruct<BSDIFF40>(); Debug.Assert(m_BSDIFF40.m_magic.FourCC() == "BSDIFF40"); Debug.Assert(m_BSDIFF40.m_ctrlBlockSize > 0 && m_BSDIFF40.m_diffBlockSize > 0); Debug.Assert(m_BSDIFF40.m_sizeAfter == m_PTCH.m_sizeAfter); m_ctrlBlock = br.ReadBytes((int)m_BSDIFF40.m_ctrlBlockSize).ToBinaryReader(); m_diffBlock = new MemoryStream(br.ReadBytes((int)m_BSDIFF40.m_diffBlockSize)); m_extraBlock = new MemoryStream(br.ReadRemaining()); } }
/// <summary> /// Returns an SM2 map texuture /// </summary> public BitmapSource GetTexture(Map map, int detail, UnitSync unitSync) { UnitSync.NativeMethods.RemoveAllArchives(); UnitSync.NativeMethods.AddAllArchives(map.ArchiveName); ProgressChanged(this, new ProgressChangedEventArgs(0, "Extracting map")); var mapDir = UnitSync.NativeMethods.GetMapFileName(UnitSync.NativeMethods.GetMapIndex(map.Name)); var smfFileData = unitSync.ReadVfsFile(mapDir); BinaryReader reader; try { reader = new BinaryReader(new MemoryStream(smfFileData)); } catch (System.ArgumentNullException nullEx) { throw new System.ArgumentNullException("smfFileData", "Unable to read SMF: " + mapDir); } var smfHeader = reader.ReadStruct<SMFHeader>(); smfHeader.SelfCheck(); var mapWidth = smfHeader.mapx; var mapHeight = smfHeader.mapy; reader.BaseStream.Position = smfHeader.tilesPtr; var mapTileHeader = reader.ReadStruct<MapTileHeader>(); // get the tile files and the number of tiles they contain var tileFiles = new Dictionary<byte[], int>(); for (var i = 0; i < mapTileHeader.numTileFiles; i++) { var numTiles = reader.ReadInt32(); var tileFileData = unitSync.ReadVfsFile("maps\\" + reader.ReadCString()); tileFiles.Add(tileFileData, numTiles); } // get the position of the tiles var mapUnitInTiles = Tiles.TileMipLevel1Size/smfHeader.texelPerSquare; var tilesX = smfHeader.mapx/mapUnitInTiles; var tilesY = smfHeader.mapy/mapUnitInTiles; var tileIndices = new int[tilesX*tilesY]; for (var i = 0; i < tileIndices.Length; i++) { tileIndices[i] = reader.ReadInt32(); } Tiles.ProgressChanged += (s, e) => ProgressChanged(this, e); UnitSync.NativeMethods.RemoveAllArchives(); // load the tiles WriteableBitmap ret; try { ret = (WriteableBitmap)Tiles.LoadTiles(tileFiles, tileIndices, tilesX, tilesY, detail); } catch (System.Exception ex) { // some maps (e.g. Glacies) fail to load the tiles properly; use minimap as a fallback //if (map.Texture == null) throw new System.Exception("Unable to load map texture"); //var newBitmap = new Bitmap(GetBitmap(map.Texture), new Size(map.Texture.PixelWidth / 8, map.Texture.PixelHeight / 8)); map.Minimap = unitSync.GetMinimap(map); ret = new WriteableBitmap(ConvertBitmap(map.Minimap)); ret.Freeze(); //ret.Unlock(); } return ret; }
public void it_will_read_struct_with_string_byval() { var expected = new StringStructByval() { First = 0x12345678, Text = Utf8String, Last = 0x76543210 }; var source = new byte[] { 0x78, 0x56, 0x34, 0x12, 0x5e, 0x01, 0xdb, 0x1e, 0xdd, 0x10, 0xb5, 0x03, 0x20, 0x00, 0x5f, 0x01, 0xb7, 0x1e, 0x3c, 0x04, 0x40, 0x04, 0x3a, 0x01, 0xea, 0x00, 0x20, 0x00, 0xc4, 0x00, 0x5a, 0x01, 0x08, 0x01, 0xcd, 0x00, 0x7c, 0x00, 0x2d, 0x00, 0x65, 0x01, 0x2e, 0x21, 0xc7, 0x03, 0x67, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x32, 0x54, 0x76 }; using (var reader = new BinaryReader(new MemoryStream(source))) { var value = reader.ReadStruct<StringStructByval>(); value.Should().Be(expected); reader.BaseStream.ShouldBeEof(); } }
private void LoadBitmap(Stream stream) { ValidateStream(stream); var reader = new BinaryReader(stream); // Read the header. _header = (TGA_HEADER)reader.ReadStruct(typeof(TGA_HEADER)); /*long t = stream.Position; BinaryWriter wr = new BinaryWriter(stream, Encoding.ASCII); if (!header.HasColorMap) { header.colormaplength = 0; header.colormapstart = 0; stream.Position = 0; wr.WriteStruct(header); }*/ // stream.Position = t; if (_header.identsize > 0) { var imageId = reader.ReadBytes(_header.identsize); Debug.WriteLine("Has ImageID: " + Encoding.ASCII.GetString(imageId)); } // Check if we know the image data type. if (!Enum.IsDefined(typeof(TgaPixelFormat), PixelFormat)) throw new Exception("Unknown image data type."); // Check if color map is needed by data type and load it if available. var colorMap = new byte[0]; if (PixelFormat == TgaPixelFormat.Indexed) if (!HasPalette) throw new Exception("No color map is defined."); else colorMap = reader.ReadBytes((PaletteBits / 8) * _header.colormaplength); // Check if file has footer var tempPos = stream.Position; stream.Seek(-26, SeekOrigin.End); var footer = (TGA_FOOTER)reader.ReadStruct(typeof(TGA_FOOTER)); stream.Position = tempPos; _fileVersion = TgaFileVersion.Version1; if (footer.IsValidFooter) _fileVersion = TgaFileVersion.Version2; _bitmap = null; switch (_header.bits) { case 32: _bitmap = new Bitmap(Width, Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); break; case 24: _bitmap = new Bitmap(Width, Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); break; case 16: _bitmap = new Bitmap(Width, Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb555); break; case 8: _bitmap = new Bitmap(Width, Height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); // Load palette from image data. if (HasPalette && PixelFormat == TgaPixelFormat.Indexed) { var bytesPerColor = PaletteBits / 8; for (var i = _header.colormapstart + bytesPerColor - 1; i < colorMap.Length; i += bytesPerColor) { var colorIndex = i/bytesPerColor; if (colorIndex < _bitmap.Palette.Entries.Length) _bitmap.Palette.Entries[colorIndex] = Color.FromArgb(colorMap[i], colorMap[i - 1], colorMap[i - 2]); else throw new Exception("Unexpected length of color palette."); } } else if (PixelFormat == TgaPixelFormat.Greyscale) { // Build a 256 color palette of grey colors. for (var i = 0; i < _bitmap.Palette.Entries.Length; i++) _bitmap.Palette.Entries[i] = Color.FromArgb(i, i, i); } break; } if (_bitmap == null) throw new NotSupportedException("The tga image format is not supported."); ReadPixels(_bitmap, Compressed ? new TruevisionRleReader(reader.BaseStream, _bitmap.PixelFormat) : reader, BottomToTop ); if (_fileVersion == TgaFileVersion.Version2) { if (footer.developerDirectoryOffset > 0) { stream.Seek(footer.developerDirectoryOffset, SeekOrigin.Begin); } if (footer.extensionAreaOffset > 0) { //char[] trimChars = " \0".ToCharArray(); stream.Seek(footer.extensionAreaOffset, SeekOrigin.Begin); var extension = (TGA_EXTENSION)reader.ReadStruct(typeof(TGA_EXTENSION)); // Debug.WriteLine("Generated by software: " + extension.softwareID + " v." + (float)extension.softwareVersionNumber / 100); } var bytesToPreserve = reader.ReadBytes((int)(stream.Length - 26 - stream.Position)); // Debug.WriteLine(System.Text.Encoding.ASCII.GetString(bytesToPreserve)); } }
public static bool ValidateStream(Stream stream, bool fixCommonBugs) { if (stream == null) throw new ArgumentNullException(); if (!stream.CanSeek) throw new ArgumentException("The stream does not support seeking."); if (!stream.CanRead) throw new ArgumentException("The stream does not support reading."); var currentPos = stream.Position; var reader = new BinaryReader(stream, Encoding.ASCII); // Read the header. var header = (TGA_HEADER)reader.ReadStruct(typeof(TGA_HEADER)); if (header.identsize > 0) stream.Seek(header.identsize, SeekOrigin.Current); // Check if we know the image data type. if (!Enum.IsDefined(typeof(TgaPixelFormat), header.PixelFormat)) throw new Exception("Unknown image data type."); // Check if color map is needed by data type and load it if available. if (header.PixelFormat == TgaPixelFormat.Indexed) if (!header.HasColorMap) throw new Exception("No color map is defined."); else reader.ReadBytes((header.colormapbits / 8) * header.colormaplength); if (fixCommonBugs) { fixCommonBugs = false; if (!header.HasColorMap && (header.PixelFormat != TgaPixelFormat.Indexed)) { if (!stream.CanWrite) throw new ArgumentException("Tga header contains a bug but can't be fixed since the stream does not support writing."); if ((header.colormapstart != 0) || (header.colormaplength != 0)) { stream.Position = currentPos; header.colormapstart = 0; header.colormaplength = 0; var wr = new BinaryWriter(stream); wr.WriteStruct(header); fixCommonBugs = true; } } } stream.Position = currentPos; switch (header.bits) { case 32: case 24: case 16: return fixCommonBugs; case 8: // Color palettes are supported. if (header.HasColorMap && (header.PixelFormat == TgaPixelFormat.Indexed)) return fixCommonBugs; // Greyscale is supported. if (header.PixelFormat == TgaPixelFormat.Greyscale) return fixCommonBugs; break; } throw new NotSupportedException("Stream does not appear to be a valid TGA stream."); }
IEnumerable<RiotArchiveFile> GetFiles(BinaryReader reader, RiotArchiveHeader header, string[] paths) { var stream = reader.BaseStream; stream.Seek(header.FilesOffset, SeekOrigin.Begin); var fileListInfo = reader.ReadStruct<RiotFileListHeader>(); for (int i = 0; i < fileListInfo.Length; i++) { var fileInfo = reader.ReadStruct<RiotFileListEntry>(); yield return new RiotArchiveFile(this.FullName, paths[fileInfo.PathListIndex], (int)fileInfo.DataOffset, (int)fileInfo.DataLength); #if DEBUG Debug.Assert(new RiotArchiveFile(paths[fileInfo.PathListIndex]).Hash == fileInfo.Hash); #endif } }
private void BSDIFFParseHeader(BinaryReader br) { m_BSDIFF40 = br.ReadStruct<BSDIFF40>(); Debug.Assert(m_BSDIFF40.m_magic.FourCC() == "BSDIFF40"); Debug.Assert(m_BSDIFF40.m_ctrlBlockSize > 0 && m_BSDIFF40.m_diffBlockSize > 0); Debug.Assert(m_BSDIFF40.m_sizeAfter == m_PTCH.m_sizeAfter); }
public void it_will_read_struct() { var expected = new CustomStruct() { Byte = 0x10, Sbyte = -0x10, UShort = 0x2ABC, Short = -0x2ABC, UInt32 = 0x400ABC00, Int32 = -0x400ABC00, UInt64 = 0x7000000ABC000000, Int64 = -0x7000000ABC000000, Bool = true, Float = 12345.678f, Double = 123456789.123456789d, Decimal = 123456789.123456789m }; //var size = Marshal.SizeOf(expected); //var ptr = Marshal.AllocHGlobal(size); //var expectedBytes = new byte[size]; //Marshal.StructureToPtr(expected, ptr, false); //Marshal.Copy(ptr, expectedBytes, 0, size); //var test = Marshal.PtrToStructure(ptr, expected.GetType()); //expectedBytes.ToList().ForEach(b => Debug.Write("0x" + b.ToString("x2") + ", ")); var source = new byte[] { 0x10, 0xf0, 0x44, 0xd5, 0xbc, 0x2a, 0x00, 0x44, 0xf5, 0xbf, 0x00, 0xbc, 0x0a, 0x40, 0x00, 0x00, 0x00, 0x44, 0xf5, 0xff, 0xff, 0x8f, 0x00, 0x00, 0x00, 0xbc, 0x0a, 0x00, 0x00, 0x70, 0x01, 0x00, 0x00, 0x00, 0xb6, 0xe6, 0x40, 0x46, 0x75, 0x6b, 0x7e, 0x54, 0x34, 0x6f, 0x9d, 0x41, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x15, 0x5f, 0xd0, 0xac, 0x4b, 0x9b, 0xb6, 0x01 }; using (var reader = new BinaryReader(new MemoryStream(source))) { var value = reader.ReadStruct<CustomStruct>(); value.Should().Be(expected); reader.BaseStream.ShouldBeEof(); } //Marshal.FreeHGlobal(ptr); }
private WEDSecondDescriptor ReadSecondaryDescriptor(BinaryReader reader, WEDDescriptor descriptor) { reader.BaseStream.Seek(descriptor.SecondaryDescriptorOffset, SeekOrigin.Begin); return reader.ReadStruct<WEDSecondDescriptor>(); }
private AREDescriptor ReadDescriptor(BinaryReader reader, int descriptorOffset) { reader.BaseStream.Seek(descriptorOffset, SeekOrigin.Begin); return reader.ReadStruct<AREDescriptor>(); }
/// <summary> /// Reads a <see cref="VersionResource"/> object from the current <see cref="Stream"/>. /// </summary> /// <returns> /// A <see cref="VersionResource"/> object. /// </returns> public VersionResource Read() { Stream.Position = 0; var value = new VersionResource(); using (var stream = new SubStream(Stream, 0, Stream.Length, leaveParentOpen: true)) using (var reader = new BinaryReader(stream, Encoding.Default)) { var offset = Stream.Position; var versionInfo = reader.ReadVersionInfo(); var end = offset + versionInfo.Header.Length; // The root element MUST be a "VS_VERSION_INFO" element of binary type. // https://msdn.microsoft.com/en-us/library/windows/desktop/ms647001(v=vs.85).aspx // It contains at most three children - a VS_FIXEDFILEINFO object, a StringFileInfo struct // and a VarFileInfo struct. if (versionInfo.Key != "VS_VERSION_INFO") { throw new VersionResourceFormatException(); } if (versionInfo.Header.Type != VersionDataType.Binary) { throw new VersionResourceFormatException(); } // We know a VS_FIXEDFILEINFO struct is present if the ValueLength > 0 if (versionInfo.Header.ValueLength != 0) { // Read the file info value.FixedFileInfo = reader.ReadStruct<VS_FIXEDFILEINFO>(); reader.Align(); } // Read the children: At most one StringFileInfo and at most one VarFileInfo while (Stream.Position < end) { var childOffset = Stream.Position; var childInfo = reader.ReadVersionInfo(); var childEnd = childOffset + childInfo.Header.Length; switch (childInfo.Key) { case "VarFileInfo": if (childInfo.Header.Type != VersionDataType.Text) { throw new VersionResourceFormatException(); } value.VarFileInfo = ReadVarFileInfo(reader); break; case "StringFileInfo": if (childInfo.Header.Type != VersionDataType.Text) { throw new VersionResourceFormatException(); } value.StringFileInfo = ReadStringFileInfo(reader, childEnd); break; } } return value; } }
public void it_will_throw_when_type_size_exceeds_available_data() { using (var reader = new BinaryReader(new MemoryStream(new byte[] { 0, 1, 2, 3 }))) { Action action = () => reader.ReadStruct<CustomStruct>(); action.ShouldThrow<EndOfStreamException>(); reader.BaseStream.ShouldBeEof(); } }
private static MiniBall[] ReadMiniBalls(BinaryReader reader) { int extraCount = reader.ReadInt16(); var ret = new MiniBall[extraCount]; if (extraCount > 0) { for (int i = 0; i < extraCount; i++) ret[i] = reader.ReadStruct<MiniBall>(); } return ret; }
public bool LoadFromVBM(string filename, int vertexIndex, int normalIndex, int texCoord0Index) { FileStream f = new FileStream(filename, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(f); long filesize = f.Length; byte[] data = new byte[filesize]; UnmanagedArray<byte> raw_data; f.Read(data, 0, (int)filesize); f.Seek(0, SeekOrigin.Begin); VBM_HEADER header = br.ReadStruct<VBM_HEADER>(); VBM_ATTRIB_HEADER attrib_header = br.ReadStruct<VBM_ATTRIB_HEADER>(); { long offset = header.size + header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER)); f.Seek(offset, SeekOrigin.Begin); } VBM_FRAME_HEADER frame_header = br.ReadStruct<VBM_FRAME_HEADER>(); uint total_data_size = 0; this.m_header = header; { long offset = header.size;// +header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER)); f.Seek(offset, SeekOrigin.Begin); } this.m_attrib = new VBM_ATTRIB_HEADER[header.num_attribs]; for (int i = 0; i < header.num_attribs; i++) { this.m_attrib[i] = br.ReadStruct<VBM_ATTRIB_HEADER>(); } { long offset = header.size + header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER));// +header.num_frames * Marshal.SizeOf(typeof(VBM_FRAME_HEADER)); f.Seek(offset, SeekOrigin.Begin); } this.m_frame = new VBM_FRAME_HEADER[header.num_frames]; for (int i = 0; i < header.num_frames; i++) { this.m_frame[i] = br.ReadStruct<VBM_FRAME_HEADER>(); } GL.GenVertexArrays(1, m_vao); GL.BindVertexArray(m_vao[0]); GL.GenBuffers(1, m_attribute_buffer); GL.BindBuffer(BufferTarget.ArrayBuffer, m_attribute_buffer[0]); //uint i; for (uint i = 0; i < header.num_attribs; i++) { total_data_size += m_attrib[i].components * sizeof(float) * header.num_vertices; } { long offset = header.size + header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER)) + header.num_frames * Marshal.SizeOf(typeof(VBM_FRAME_HEADER)); raw_data = new UnmanagedArray<byte>((int)total_data_size); for (int i = 0; i < raw_data.Length; i++) { raw_data[i] = data[offset + i]; } } //GL.BufferData(GL_ARRAY_BUFFER, total_data_size, raw_data, GL_STATIC_DRAW); GL.BufferData(BufferTarget.ArrayBuffer, raw_data, BufferUsage.StaticDraw); total_data_size = 0; for (uint i = 0; i < header.num_attribs; i++) { uint attribIndex = i; if (attribIndex == 0) attribIndex = (uint)vertexIndex; else if (attribIndex == 1) attribIndex = (uint)normalIndex; else if (attribIndex == 2) attribIndex = (uint)texCoord0Index; GL.VertexAttribPointer(attribIndex, (int)m_attrib[i].components, m_attrib[i].type, false, 0, new IntPtr(total_data_size)); GL.EnableVertexAttribArray(attribIndex); total_data_size += m_attrib[i].components * sizeof(float) * header.num_vertices; } if (header.num_indices > 0) { GL.GenBuffers(1, m_index_buffer); GL.BindBuffer(BufferTarget.ElementArrayBuffer, m_index_buffer[0]); uint element_size; if (header.indexype == 0x1403) { element_size = sizeof(ushort); } else { element_size = sizeof(uint); } //GL.BufferData(GL_ELEMENT_ARRAY_BUFFER, header.num_indices * element_size, raw_data + total_data_size, GL_STATIC_DRAW); UnmanagedArray<byte> tmp = new UnmanagedArray<byte>((int)(header.num_indices * element_size)); for (int t = 0; t < tmp.Length; t++) { tmp[t] = raw_data[(int)(t + total_data_size)]; } GL.BufferData(BufferTarget.ElementArrayBuffer, tmp, BufferUsage.StaticDraw); tmp.Dispose(); } GL.BindVertexArray(0); raw_data.Dispose(); return true; }