ReadUInt32() private method

private ReadUInt32 ( ) : uint
return uint
        internal override void Read(BinaryReader reader)
        {
            Version = reader.ReadUInt16();
            VersionNeededToExtract = reader.ReadUInt16();
            Flags = (HeaderFlags) reader.ReadUInt16();
            CompressionMethod = (ZipCompressionMethod) reader.ReadUInt16();
            LastModifiedTime = reader.ReadUInt16();
            LastModifiedDate = reader.ReadUInt16();
            Crc = reader.ReadUInt32();
            CompressedSize = reader.ReadUInt32();
            UncompressedSize = reader.ReadUInt32();
            ushort nameLength = reader.ReadUInt16();
            ushort extraLength = reader.ReadUInt16();
            ushort commentLength = reader.ReadUInt16();
            DiskNumberStart = reader.ReadUInt16();
            InternalFileAttributes = reader.ReadUInt16();
            ExternalFileAttributes = reader.ReadUInt32();
            RelativeOffsetOfEntryHeader = reader.ReadUInt32();

            byte[] name = reader.ReadBytes(nameLength);
            Name = DecodeString(name);
            byte[] extra = reader.ReadBytes(extraLength);
            byte[] comment = reader.ReadBytes(commentLength);
            Comment = DecodeString(comment);
            LoadExtra(extra);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Creates a new FAR3Archive instance from a path.
        /// </summary>
        /// <param name="Path">The path to the archive.</param>
        public FAR3Archive(string Path)
        {
            m_ArchivePath = Path;

            if (isReadingSomething == false)
            {
                isReadingSomething = true;

                try
                {
                    m_Reader = new BinaryReader(File.Open(Path, FileMode.Open, FileAccess.Read, FileShare.Read));
                }
                catch (Exception)
                {
                    throw new FAR3Exception("Could not open the specified archive - " + Path + "! (FAR3Archive())");
                }

                string Header = Encoding.ASCII.GetString(m_Reader.ReadBytes(8));
                uint Version = m_Reader.ReadUInt32();

                if ((Header != "FAR!byAZ") || (Version != 3))
                {
                    throw new FAR3Exception("Archive wasn't a valid FAR V.3 archive! (FAR3Archive())");
                }

                uint ManifestOffset = m_Reader.ReadUInt32();
                m_ManifestOffset = ManifestOffset;

                m_Reader.BaseStream.Seek(ManifestOffset, SeekOrigin.Begin);

                uint NumFiles = m_Reader.ReadUInt32();

                for (int i = 0; i < NumFiles; i++)
                {
                    Far3Entry Entry = new Far3Entry();
                    Entry.DecompressedFileSize = m_Reader.ReadUInt32();
                    byte[] Dummy = m_Reader.ReadBytes(3);
                    Entry.CompressedFileSize = (uint)((Dummy[0] << 0) | (Dummy[1] << 8) | (Dummy[2]) << 16);
                    Entry.DataType = m_Reader.ReadByte();
                    Entry.DataOffset = m_Reader.ReadUInt32();
                    //Entry.HasFilename = m_Reader.ReadUInt16();
                    Entry.IsCompressed = m_Reader.ReadByte();
                    Entry.AccessNumber = m_Reader.ReadByte();
                    Entry.FilenameLength = m_Reader.ReadUInt16();
                    Entry.TypeID = m_Reader.ReadUInt32();
                    Entry.FileID = m_Reader.ReadUInt32();
                    Entry.Filename = Encoding.ASCII.GetString(m_Reader.ReadBytes(Entry.FilenameLength));

                    if (!m_Entries.ContainsKey(Entry.Filename))
                        m_Entries.Add(Entry.Filename, Entry);
                    m_EntriesList.Add(Entry);

                    m_EntryByID.Add(Entry.FileID, Entry); //isn't this a bad idea? i have a feeling this is a bad idea...
                }

                //Keep the stream open, it helps peformance.
                //m_Reader.Close();
                isReadingSomething = false;
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Reads a *.anim file into this Anim instance.
        /// </summary>
        /// <param name="FileData">The filedata for the *.anim file.</param>
        public Anim(byte[] FileData)
        {
            MemoryStream MemStream = new MemoryStream(FileData);
            BinaryReader Reader = new BinaryReader(MemStream);

            m_Version = Endian.SwapUInt32(Reader.ReadUInt32());
            m_Name = Encoding.ASCII.GetString(Reader.ReadBytes(Endian.SwapInt16(Reader.ReadInt16())));
            m_Duration = Reader.ReadSingle() / 1000; //Why does this have to be divided by 1000? o_O
            m_Distance = Reader.ReadSingle();
            m_IsMoving = Reader.ReadByte();

            m_NumTranslations = Endian.SwapUInt32(Reader.ReadUInt32());
            m_TranslationsTableOffset = Reader.BaseStream.Position;

            Reader.BaseStream.Seek(m_TranslationsTableOffset + 12 * m_NumTranslations, SeekOrigin.Begin);

            m_NumRotations = Endian.SwapUInt32(Reader.ReadUInt32());
            m_RotationsTableOffset = Reader.BaseStream.Position;

            Reader.BaseStream.Seek(m_RotationsTableOffset + 16 * m_NumRotations, SeekOrigin.Begin);

            m_MotionCount = Endian.SwapUInt32(Reader.ReadUInt32());

            for (int i = 0; i < m_MotionCount; i++)
                m_Motions.Add(ReadMotion(Reader));
        }
Ejemplo n.º 4
0
 public BAR(Stream file)
 {
     if (!file.CanRead || !file.CanSeek)
     {
         throw new NotSupportedException("Cannot read or seek in stream");
     }
     using (var br = new BinaryReader(file))
     {
         if (file.Length < 16 || br.ReadUInt32() != 0x01524142)
         {
             throw new InvalidDataException("Invalid signature");
         }
         int fileC = br.ReadInt32();
         fileList = new List<BARFile>(fileC);
         Debug.WriteLine("Loading BAR with " + fileC + " files");
         file.Position = 16;
         for (int i = 0; i < fileC; i++)
         {
             var bf = new BARFile();
             bf.type = br.ReadUInt32();
             {
                 byte[] b = br.ReadBytes(4);
                 Buffer.BlockCopy(b, 0, bf._id, 0, 4);
             }
             long lpos = file.Position + 8;
             uint pos = br.ReadUInt32();
             int len = br.ReadInt32();
             file.Position = pos;
             bf.data = br.ReadBytes(len);
             fileList.Add(bf);
             file.Position = lpos;
         }
     }
     //BinaryReader should close file
 }
 public bool Load(string path)
 {
     using (FileStream fs = new FileStream(path, FileMode.Open))
     {
         using (BinaryReader reader = new BinaryReader(fs))
         {
             for (int i = 0; i < 8; ++i)
             {
                 reader.ReadBytes(4);
             }
             uint count = reader.ReadUInt32();
             uint offset = reader.ReadUInt32();
             fs.Position = (long)offset;
             try
             {
                 for (int i = 0; i < count; ++i)
                 {
                     ulong ext = reader.ReadUInt64();
                     ulong fpath = reader.ReadUInt64();
                     uint language = reader.ReadUInt32();
                     reader.ReadBytes(4);
                     uint id = reader.ReadUInt32();
                     reader.ReadBytes(4);
                     this.Add(ext, fpath, language, id);
                 }
             }
             catch (Exception)
             {
                 return false;
             }
         }
     }
     return true;
 }
Ejemplo n.º 6
0
        public void RecvAuthRsp(BinaryReader s)
        {
            Console.WriteLine("SessionClient.RecvAuthRsp");

            UInt32 sessionId;
            UInt32 sessionStatus;

            sessionId = s.ReadUInt32();
            sessionStatus = s.ReadUInt32();

            if (sessionStatus != 0)
            {
                Console.WriteLine("Session Authentication Failed: {0}", sessionStatus);
                listener.OnSessionOperationFail("Session Authentication Failed");
                return;
            }
            else if (sessionId != this.sessionId)
            {
                Console.WriteLine("Session Authentication Failed:" + sessionId + "!=" + this.sessionId);
                listener.OnSessionOperationFail("Session Authentication Failed");
                return;
            }

            listener.OnSessionAuthenticationSuccess();
        }
Ejemplo n.º 7
0
        internal Steam2ChecksumData( byte[] blob )
        {
            maps = new List<ChecksumMapEntry>();
            checksums = new Dictionary<uint, int>();

            data = blob;

            using ( MemoryStream ms = new MemoryStream( data ) )
            {
                using ( BinaryReader br = new BinaryReader( ms ) )
                {
                    // we don't care about the first two, always the same
                    br.ReadBytes( 8 );

                    itemCount = br.ReadUInt32();
                    checksumCount = br.ReadUInt32();

                    uint count;
                    uint start = 0;
                    for ( int i = 0 ; i < itemCount ; i++ )
                    {
                        count = br.ReadUInt32();
                        start = br.ReadUInt32();
                        maps.Add( new ChecksumMapEntry( count, start ) );
                    }

                    for ( uint i = 0 ; i < checksumCount ; i++ )
                    {
                        long pos = br.BaseStream.Position;
                        checksums[ i ] = br.ReadInt32();
                    }
                }
            }
        }
Ejemplo n.º 8
0
        public FAR1Archive(string Path)
        {
            m_Path = Path;
            m_Reader = new BinaryReader(File.Open(Path, FileMode.Open));

            string Header = Encoding.ASCII.GetString(m_Reader.ReadBytes(8));
            uint Version = m_Reader.ReadUInt32();

            if ((Header != "FAR!byAZ") || (Version != 1))
            {
                throw(new Exception("Archive wasn't a valid FAR V.1 archive!"));
            }

            m_ManifestOffset = m_Reader.ReadUInt32();
            m_Reader.BaseStream.Seek(m_ManifestOffset, SeekOrigin.Begin);

            m_NumFiles = m_Reader.ReadUInt32();
            
            for (int i = 0; i < m_NumFiles; i++)
            {
                FarEntry Entry = new FarEntry();
                Entry.DataLength = m_Reader.ReadInt32();
                Entry.DataLength2 = m_Reader.ReadInt32();
                Entry.DataOffset = m_Reader.ReadInt32();
                Entry.FilenameLength = m_Reader.ReadInt16();
                Entry.Filename = Encoding.ASCII.GetString(m_Reader.ReadBytes(Entry.FilenameLength));

                m_Entries.Add(Entry);
            }

            m_Reader.Close();
        }
Ejemplo n.º 9
0
        // 1ST TIER FUNCTIONS

        Index GetIndex(BinaryReader binReader)
        {
            Index getIndex = new Index
            {
                zone = (Zone) binReader.ReadUInt32(),
                unknown02 = binReader.ReadUInt32(),
                unknown03 = binReader.ReadUInt32(),
                unknown04 = binReader.ReadUInt32()
            };
            binReader.ReadBytes(12); // nulls
            getIndex.triangle = GetTriangles(binReader);
            binReader.ReadBytes(8); // nulls
            getIndex.triangles = binReader.ReadUInt16();
            getIndex.positions = binReader.ReadUInt16();
            getIndex.unknown05 = binReader.ReadUInt16();
            binReader.ReadBytes(8); // nulls
            getIndex.diffuse = GetString(binReader);
            getIndex.normal = GetString(binReader);
            getIndex.glow = GetString(binReader);
            getIndex.specular = GetString(binReader);
            getIndex.light = GetString(binReader);
            binReader.ReadBytes(38); // nulls
            binReader.ReadBytes(8);// Another 8 nulls... this shouldnt be according to old code

            return getIndex;
        }
Ejemplo n.º 10
0
        public Binding(byte[] FileData)
        {
            MemoryStream MemStream = new MemoryStream(FileData);
            BinaryReader Reader = new BinaryReader(MemStream);

            m_Version = Endian.SwapUInt32(Reader.ReadUInt32());

            byte StrLength = Reader.ReadByte();
            string m_BoneName = Encoding.ASCII.GetString(Reader.ReadBytes(StrLength));

            //Should be 8.
            uint MeshAssetIDSize = Endian.SwapUInt32(Reader.ReadUInt32());

            //AssetID prefix, typical useless Maxis value...
            Reader.ReadUInt32();

            m_MeshAssetID = Endian.SwapUInt64(Reader.ReadUInt64());

            //Should be 8.
            uint TextureAssetIDSize = Endian.SwapUInt32(Reader.ReadUInt32());

            //AssetID prefix, typical useless Maxis value...
            Reader.ReadUInt32();

            m_TextureAssetID = Endian.SwapUInt64(Reader.ReadUInt64());
        }
Ejemplo n.º 11
0
        public IEnumerable<Packet> ReadPackets(string file)
        {
            using (var gr = new BinaryReader(new FileStream(file, FileMode.Open, FileAccess.Read), Encoding.ASCII))
            {
                gr.ReadBytes(3); // PKT
                gr.ReadBytes(2); // 0x02, 0x02
                gr.ReadByte(); // 0x06
                Build = gr.ReadUInt16(); // build
                gr.ReadBytes(4); // client locale
                gr.ReadBytes(20); // packet key
                gr.ReadBytes(64); // realm name

                var packets = new List<Packet>();
                while (gr.PeekChar() >= 0)
                {
                    Direction direction = gr.ReadByte() == 0xff ? Direction.Server : Direction.Client;
                    uint unixtime = gr.ReadUInt32();
                    uint tickcount = gr.ReadUInt32();
                    uint size = gr.ReadUInt32();
                    OpCodes opcode = (direction == Direction.Client) ? (OpCodes)gr.ReadUInt32() : (OpCodes)gr.ReadUInt16();
                    byte[] data = gr.ReadBytes((int)size - ((direction == Direction.Client) ? 4 : 2));

                    packets.Add(new Packet(direction, opcode, data, unixtime, tickcount));
                }
                return packets;
            }
        }
Ejemplo n.º 12
0
        public IPHeader(ArraySegment<byte> buffer)
        {

            using (var memoryStream = new MemoryStream(buffer.Array, buffer.Offset, buffer.Count))
            {
                using (var binaryReader = new BinaryReader(memoryStream))
                {
                    var versionAndHeaderLength = binaryReader.ReadByte();
                    var differentiatedServices = binaryReader.ReadByte();

                    DifferentiatedServices = (byte)(differentiatedServices >> 2);
                    CongestionNotification = (byte)(differentiatedServices & 0x03);

                    TotalLength = (ushort) IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());
                    Debug.Assert(TotalLength >= 20, "Invalid IP packet Total Lenght");
                    Identification = (ushort) IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

                    _flagsAndOffset = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

                    Ttl = binaryReader.ReadByte();

                    _protocol = binaryReader.ReadByte();

                    Checksum = IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

                    SourceAddress = new IPAddress(binaryReader.ReadUInt32());
                    DestinationAddress = new IPAddress(binaryReader.ReadUInt32());

                    HeaderLength = (versionAndHeaderLength & 0x0f) * 4;
                }
            }

            Raw = buffer;
            Data = new ArraySegment<byte>(buffer.Array, buffer.Offset + HeaderLength, MessageLength);
        }
Ejemplo n.º 13
0
 void Parse(Stream s)
 {
     BinaryReader br = new BinaryReader(s);
     unknown1 = br.ReadUInt32();
     data = br.ReadBytes(2 * br.ReadInt32());
     unknown2 = br.ReadUInt32();
 }
Ejemplo n.º 14
0
 public MpqBlock(BinaryReader br, uint HeaderOffset)
 {
     FilePos = br.ReadUInt32() + HeaderOffset;
     CompressedSize = br.ReadUInt32();
     FileSize = br.ReadUInt32();
     Flags = (MpqFileFlags)br.ReadUInt32();
 }
Ejemplo n.º 15
0
 private void PlayerInfo(BinaryReader gr)
 {
     AppendFormatLine("FreePoints: {0}", gr.ReadUInt32());
     var speccount=gr.ReadByte();
     AppendFormatLine("SpectsCount: {0}", speccount);
     AppendFormatLine("ActiveSpec: {0}", gr.ReadByte());
     if (speccount > 0)
     {
         for (int id = 0; id < 1; id++)
         {
             var talidcount = gr.ReadByte();
             AppendFormatLine("TalentIDCount: {0}", talidcount);
             for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 12; j++)
               {
                   AppendFormatLine("TalentID {0}", gr.ReadUInt32());
                     AppendFormatLine("CurRanc: {0}", gr.ReadByte());
                 }
             }
             var GLYPHMAX = gr.ReadByte();
             AppendFormatLine("GLYPHMAX: {0}", GLYPHMAX);
           for (int g = 0; g < GLYPHMAX; g++)
             {
                 AppendFormatLine("GLYPID: {0}", gr.ReadUInt16());
             }
         }
     }
 }
Ejemplo n.º 16
0
        public static void ReadBlendomatic(FileStream file)
        {
            BinaryReader reader = new BinaryReader(file);

            NumberOfBlendingModes = reader.ReadUInt32();
            NumberOfTiles = reader.ReadUInt32();

            BlendingModes = new Dictionary<byte, BlendingMode>();

            Console.WriteLine("Number of blending modes: " + NumberOfBlendingModes);
            Console.WriteLine("Number of tiles: " + NumberOfTiles);

            for (var i = 0; i < NumberOfBlendingModes; i++ )
            {
                BlendingMode mode;
                mode.TileSize = reader.ReadUInt32();
                mode.Tiles = new Dictionary<byte, byte[]>();

                var TileFlags = reader.ReadBytes(31); // all 1 wtf

                reader.ReadBytes((int)mode.TileSize * 4);
                for (var j = 0; j < NumberOfTiles; j++)
                {
                    mode.Tiles[(byte)j] = reader.ReadBytes((int)mode.TileSize);
                }

                BlendingModes[(byte)i] = mode;
            }
        }
Ejemplo n.º 17
0
        public override void Read(BinaryReader reader, Resource resource)
        {
            reader.BaseStream.Position = this.Offset;

            CRC32 = reader.ReadUInt32();

            var size = reader.ReadUInt16();
            int headerSize = 4 + 2;

            for (var i = 0; i < size; i++)
            {
                var entry = new NameEntry
                {
                    Name = reader.ReadNullTermString(Encoding.UTF8),
                    CRC32 = reader.ReadUInt32(),
                };

                Names.Add(entry);

                headerSize += entry.Name.Length + 1 + 4; // string length + null byte + 4 bytes
            }

            Data = reader.ReadBytes((int)this.Size - headerSize);

            if (Crc32.Compute(Data) != CRC32)
            {
                throw new InvalidDataException("CRC32 mismatch for read data.");
            }
        }
Ejemplo n.º 18
0
        public void Load(string destinationDirectory, string resourceName, BinaryReader binaryReader)
        {
            var start = binaryReader.BaseStream.Position;
            uint totalLength = binaryReader.ReadUInt32();
            var container = new string(binaryReader.ReadChars(4));

            switch (container) {
                case "FORM":
                case "RIFF":
                    uint length = binaryReader.ReadUInt32(); // this is probably not really a length, with values like 0xcccccccc
                    var header = new string(binaryReader.ReadChars(4));
                    switch (header) {
                        case "XMID":
                        case "XDIR":
                            new XMidiLoader().Load(destinationDirectory, resourceName, binaryReader, totalLength);
                            break;
                        case "WAVE":
                            break;
                    }
                    break;
                default:
                    // Possibly a WAV but without a header
                    binaryReader.BaseStream.Seek(start, SeekOrigin.Begin);
                    new WaveLoader().Load(destinationDirectory, resourceName, binaryReader, (int)totalLength, true);
                    break;
            }
        }
Ejemplo n.º 19
0
        public uint PacketNumber = 0;   // if we detect any changes, update the packet number

		/// <summary>
		/// Searches xbox memory for XInputGetState(). Average execution time of 15ms.
		/// </summary>
		/// <returns></returns>
		uint GetXInputGetStateAddress()
		{
			// assumes everything we need is in header...why would they put it elsewhere???

			// buffer to store our xbe header
            byte[] xbeh = Xbox.GetMemory(0x10000, (uint)0x1000);
            BinaryReader header = new BinaryReader(new System.IO.MemoryStream(xbeh));

			header.BaseStream.Position = 0x11C;
			uint SegmentCount = header.ReadUInt32();                //gets segment count
			uint SegmentBase = header.ReadUInt32() - 0x10000;       //gets base address of segment info table

			//loops through each segment
			for (int i = 0; i < SegmentCount; i++)
			{
				header.BaseStream.Position = (uint)(SegmentBase + i * 56) + 4;
				uint SegAddress = header.ReadUInt32();
				uint SegSize = header.ReadUInt32();
				header.BaseStream.Position += 8;
				header.BaseStream.Position = header.ReadUInt32() - 0x10000;
				string SegName = System.Text.ASCIIEncoding.ASCII.GetString(header.ReadBytes(3));

				if (SegName.Equals("XPP"))
				{
					//dumps xpp segment
                    byte[] SegDump = Xbox.GetMemory(SegAddress, SegSize);

					//searches for xinputgetstate function
					for (int j = 0; j < SegSize; j++)
						if ((BitConverter.ToUInt64(SegDump, j) & 0xFFFFFFFFFFFF) == 0x000015FFDB335653)
							return (uint)(SegAddress + j);
				}
			}
			throw new Exception("Unable to find XInputGetState() in memory, you must manually specify this address instead if you wish to initialize a controller hook.");
		}
Ejemplo n.º 20
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        public override void Parse( Stream input )
        {
            BinaryReader br = new BinaryReader( input );

            _MatrixX = br.ReadByte();
            _MatrixY = br.ReadByte();
            _DivisorFLOAT = br.ReadUInt32();
            _BiasFLOAT = br.ReadUInt32();
            _MatrixValues = new List<uint>();
            for ( int i = 0; i < ( _MatrixX * _MatrixY ); i++ )
            {
                UInt32 a = br.ReadUInt32();
                _MatrixValues.Add( a );
            }
            _DefaultColor = new Rgba( this.Version );
            _DefaultColor.Parse( input );
            BitStream bits = new BitStream( input );

            uint reserved = bits.GetBits( 6 );
            if ( 0 != reserved )
            {
                throw new SwfFormatException( "ConvolutionFilter uses reserved bits" );
            }

            _Clamp = ( 0 != bits.GetBits( 1 ) );
            _PreserveAlpha = ( 0 != bits.GetBits( 1 ) );
        }
        public PacketParser(Stream file)
        {
            var reader = new BinaryReader(file);
            Console.WriteLine("Reading packets!");

            while (file.Position != file.Length)
            {
                var packetOpcode = reader.ReadUInt32();
                var packetLength = reader.ReadUInt32();
                var packetTimestamp = reader.ReadUInt32();
                var packetType = reader.ReadByte();

                //Console.WriteLine("Opcode: 0x{0:X4}, Length: {1}", packetOpcode, packetLength);
                var packetBuffer = new byte[packetLength];
                for (var i = 0; i < packetLength; ++i)
                {
                    packetBuffer[i] = reader.ReadByte();
                }

                // ReSharper disable once ObjectCreationAsStatement
                // Handle the packet
                var p = new Packet(packetOpcode, packetLength, packetTimestamp, packetType, packetBuffer);
            }

            // Prevent exit.
            Console.ReadLine();
        }
Ejemplo n.º 22
0
Archivo: PACK.cs Proyecto: MetLob/tinke
        public static sFolder Unpack(string file, IPluginHost pluginHost)
        {
            BinaryReader br = new BinaryReader(File.OpenRead(file));
            sFolder unpacked = new sFolder();
            unpacked.files = new List<sFile>();

            uint num_files = (br.ReadUInt32() / 0x04) - 1;
            br.ReadUInt32(); // Pointer table
            for (int i = 0; i < num_files; i++)
            {
                uint startOffset = br.ReadUInt32();
                long currPos = br.BaseStream.Position;
                br.BaseStream.Position = startOffset;

                sFile newFile = new sFile();
                newFile.name = "File " + (i + 1).ToString("X") + ".bin";
                newFile.offset = startOffset + 4;
                newFile.path = file;
                newFile.size = br.ReadUInt32();

                br.BaseStream.Position = currPos;
                unpacked.files.Add(newFile);
            }

            br.Close();
            return unpacked;
        }
Ejemplo n.º 23
0
 public CasHeader(BinaryReader b)
 {
     this.magic = b.ReadUInt32();
     this.sha1 = b.ReadBytes(20);
     this.size = b.ReadUInt32();
     this._null = b.ReadUInt32();
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Opens an existing FAR archive.
        /// </summary>
        /// <param name="Path">The path to the archive.</param>
        public FARArchive(string Path)
        {
            m_Reader = new BinaryReader(File.Open(Path, FileMode.Open, FileAccess.Read));
            m_FarEntries = new List<FarEntry>();

            string Header = Encoding.ASCII.GetString(m_Reader.ReadBytes(8));
            uint Version = m_Reader.ReadUInt32();

            if ((Header != "FAR!byAZ") || (Version != 1))
            {
                MessageBox.Show("Archive wasn't a valid FAR V.1 archive!");
                return;
            }

            uint ManifestOffset = m_Reader.ReadUInt32();
            m_ManifestOffset = ManifestOffset;

            m_Reader.BaseStream.Seek(ManifestOffset, SeekOrigin.Begin);

            uint NumFiles = m_Reader.ReadUInt32();

            for (int i = 0; i < NumFiles; i++)
            {
                FarEntry Entry = new FarEntry();
                Entry.DataLength = m_Reader.ReadInt32();
                Entry.DataLength2 = m_Reader.ReadInt32();
                Entry.DataOffset = m_Reader.ReadInt32();
                Entry.FilenameLength = m_Reader.ReadInt16();
                Entry.Filename = Encoding.ASCII.GetString(m_Reader.ReadBytes(Entry.FilenameLength));

                m_FarEntries.Add(Entry);
            }

            //Reader.Close();
        }
Ejemplo n.º 25
0
        public InstallShieldPackage(string filename, int priority)
        {
            this.priority = priority;
            s = FileSystem.Open(filename);

            // Parse package header
            BinaryReader reader = new BinaryReader(s);
            uint signature = reader.ReadUInt32();
            if (signature != 0x8C655D13)
                throw new InvalidDataException("Not an Installshield package");

            reader.ReadBytes(8);
            /*var FileCount = */reader.ReadUInt16();
            reader.ReadBytes(4);
            /*var ArchiveSize = */reader.ReadUInt32();
            reader.ReadBytes(19);
            var TOCAddress = reader.ReadInt32();
            reader.ReadBytes(4);
            var DirCount = reader.ReadUInt16();

            // Parse the directory list
            s.Seek(TOCAddress, SeekOrigin.Begin);
            BinaryReader TOCreader = new BinaryReader(s);
            for (var i = 0; i < DirCount; i++)
                ParseDirectory(TOCreader);
        }
Ejemplo n.º 26
0
        public static CpuArchitectures GetPEArchitecture(string pFilePath)
        {
            ushort architecture = 0;

            ushort[] coffHeader = new ushort[10];

            using (FileStream fStream = new FileStream(pFilePath, FileMode.Open, FileAccess.Read))
            {
                using (BinaryReader bReader = new BinaryReader(fStream))
                {
                    if (bReader.ReadUInt16() == 23117) //check the MZ signature
                    {
                        fStream.Seek(0x3A, SeekOrigin.Current); // Go to the location of the location of the NT header
                        fStream.Seek(bReader.ReadUInt32(), SeekOrigin.Begin); // seek to the start of the NT header.
                        if (bReader.ReadUInt32() == 17744) //check the PE\0\0 signature.
                        {
                            for (int i = 0; i < 10; i++) // Read COFF Header
                                coffHeader[i] = bReader.ReadUInt16();
                            if (coffHeader[8] > 0) // Read Optional Header
                                architecture = bReader.ReadUInt16();
                        }
                    }
                }
            }

            switch (architecture)
            {
                case 0x20b:
                    return CpuArchitectures.x64;
                case 0x10b:
                    return ((coffHeader[9] & 0x100) == 0) ? CpuArchitectures.AnyCpu : CpuArchitectures.x86;
                default:
                    return CpuArchitectures.Unknown;
            }
        }
Ejemplo n.º 27
0
        public Metadata(BinaryReader reader)
        {
            magic = reader.ReadUInt32();
            if (magic != 0x424A5342)
                return;

            offset = (uint)reader.BaseStream.Position - 4;
            majorVersion = reader.ReadUInt16();
            minorVersion = reader.ReadUInt16();
            reserved = reader.ReadUInt32();
            versionString = readString(reader, reader.ReadInt32());
            flags = reader.ReadUInt16();
            int numStreams = reader.ReadUInt16();
            streams = new DotNetStream[numStreams];
            uint lastOffset = offset;
            for (int i = 0; i < numStreams; i++) {
                uint fileOffset = offset + reader.ReadUInt32();
                uint size = reader.ReadUInt32();
                string name = readAsciizString(reader);
                streams[i] = new DotNetStream(name, fileOffset, size);
                lastOffset = Math.Max(lastOffset, fileOffset + size);
            }
            lastOffset = Math.Max(lastOffset, (uint)reader.BaseStream.Position);
            length = lastOffset - offset;
            headerLength = (uint)reader.BaseStream.Position - offset;
        }
Ejemplo n.º 28
0
        internal override void Read(BinaryReader reader)
        {
            Version = reader.ReadUInt16();
            VersionNeededToExtract = reader.ReadUInt16();
            Flags = (HeaderFlags) reader.ReadUInt16();
            CompressionMethod = (ZipCompressionMethod) reader.ReadUInt16();
            LastModifiedTime = reader.ReadUInt16();
            LastModifiedDate = reader.ReadUInt16();
            Crc = reader.ReadUInt32();
            CompressedSize = reader.ReadUInt32();
            UncompressedSize = reader.ReadUInt32();
            ushort nameLength = reader.ReadUInt16();
            ushort extraLength = reader.ReadUInt16();
            ushort commentLength = reader.ReadUInt16();
            DiskNumberStart = reader.ReadUInt16();
            InternalFileAttributes = reader.ReadUInt16();
            ExternalFileAttributes = reader.ReadUInt32();
            RelativeOffsetOfEntryHeader = reader.ReadUInt32();

            byte[] name = reader.ReadBytes(nameLength);
            Name = DecodeString(name);
            byte[] extra = reader.ReadBytes(extraLength);
            byte[] comment = reader.ReadBytes(commentLength);
            Comment = DecodeString(comment);
            LoadExtra(extra);

            var unicodePathExtra = Extra.FirstOrDefault(u => u.Type == ExtraDataType.UnicodePathExtraField);
            if (unicodePathExtra != null)
            {
                Name = ((ExtraUnicodePathExtraField)unicodePathExtra).UnicodeName;
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        ///     Gets the name of the first model on a CGFX file.
        ///     Returns null if the file doesn't contain any model.
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string getName(MemoryStream data)
        {
            BinaryReader input = new BinaryReader(data);

            cgfxHeader header = new cgfxHeader();
            header.magic = IOUtils.readString(input, 0, 4);
            header.endian = input.ReadUInt16();
            header.length = input.ReadUInt16();
            header.revision = input.ReadUInt32();
            header.fileLength = input.ReadUInt32();
            header.entries = input.ReadUInt32();

            data.Seek(header.length + 8, SeekOrigin.Begin);
            List<dictEntry> models = getDictionary(input);

            if (models.Count > 0)
            {
                data.Seek(models[0].dataOffset + 0xc, SeekOrigin.Begin);
                string name = IOUtils.readString(input, getRelativeOffset(input));
                data.Close();
                return name;
            }
            else
            {
                data.Close();
                return null;
            }
        }
Ejemplo n.º 30
0
        public bool Analyze(Stream patchStream)
        {
            if (patchStream == null) throw new ArgumentNullException();
            if (patchStream.CanSeek == false) throw new ArgumentException();

            Clear();

            var br = new BinaryReader(patchStream);
            // Make sure the magic word is here.
            uint seed = br.ReadUInt32();
            if (seed != MAGIC) {
                return false;
            }

            // Read file count field (note: contains funky bits.)
            uint fileCount = br.ReadUInt32();
            bool md5Mode = ((fileCount & 0x80000000) != 0);

            // Clear the weird bits from the file count.
            fileCount &= 0x00FFFFFF;

            // We only support newer MD5 versions of files.
            if (!md5Mode) return false;

            mPatFileInfo.BlockCount = br.ReadUInt32();
            mPatFileInfo.SourceChecksum = br.ReadBytes(16);
            mPatFileInfo.TargetChecksum = br.ReadBytes(16);
            mPatFileInfo.BodySize = br.ReadUInt32();

            return true;
        }
Ejemplo n.º 31
0
            public override Decimal ReadScalarValue(System.IO.BinaryReader br)
            {
                Decimal d;


                br.ReadInt16(); // wReserved
                byte scale = br.ReadByte();
                byte sign  = br.ReadByte();

                uint u = br.ReadUInt32();

                d  = Convert.ToDecimal(Math.Pow(2, 64)) * u;
                d += br.ReadUInt64();

                if (sign != 0)
                {
                    d = -d;
                }
                d /= (10 << scale);

                this.propertyValue = d;
                return(d);
            }
Ejemplo n.º 32
0
        /// <summary>
        /// Unserializes a BinaryStream into the Attributes of this Instance
        /// </summary>
        /// <param name="reader">The Stream that contains the FileData</param>
        public void Unserialize(System.IO.BinaryReader reader)
        {
            number = reader.ReadInt32();
            uint id = reader.ReadUInt32();

            identity    = (ElementIdentity)id;
            repeat      = reader.ReadInt32();
            blockformat = (SimPe.Plugin.Gmdc.BlockFormat)reader.ReadInt32();
            setformat   = (SimPe.Plugin.Gmdc.SetFormat)reader.ReadInt32();

            GmdcElementValueBase dummy = GetValueInstance();
            int len = reader.ReadInt32() / (4 * dummy.Size);

            data.Clear();
            for (int i = 0; i < len; i++)
            {
                dummy = GetValueInstance();
                dummy.Unserialize(reader);
                data.Add(dummy);
            }

            this.ReadBlock(reader, items);
        }
Ejemplo n.º 33
0
        static List <ArzRecordHeader> readRecordHeadersTable(Stream s, long tableStartOffset, int entries, List <string> stringTable)
        {
            var recordHeadersTable = new List <ArzRecordHeader>();

            s.Seek(tableStartOffset, SeekOrigin.Begin);
            System.IO.BinaryReader reader = new System.IO.BinaryReader(s);
            for (int i = 0; i < entries; i++)
            {
                var recordHeader = new ArzRecordHeader();

                recordHeader.filename = stringTable[reader.ReadInt32()];
                var typeLength = reader.ReadInt32();
                recordHeader.type                 = Encoding.ASCII.GetString(reader.ReadBytes(typeLength));
                recordHeader.dataOffset           = reader.ReadUInt32();
                recordHeader.dataCompressedSize   = reader.ReadInt32();
                recordHeader.dataDecompressedSize = reader.ReadInt32();
                s.Seek(8, SeekOrigin.Current); // There not sure what the next 8 bytes are for

                recordHeadersTable.Add(recordHeader);
            }

            return(recordHeadersTable);
        }
Ejemplo n.º 34
0
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex == -1)
            {
                button3.Enabled = false;
                return;
            }
            numericUpDown1.Enabled = true;
            numericUpDown2.Enabled = true;
            numericUpDown3.Enabled = true;
            numericUpDown4.Enabled = true;
            numericUpDown5.Enabled = true;
            textBox1.Enabled       = true;
            textBox5.Enabled       = true;
            textBox6.Enabled       = true;
            textBox7.Enabled       = true;
            textBox8.Enabled       = true;
            textBox9.Enabled       = true;
            button3.Enabled        = true;
            button2.Enabled        = true;

            if (Form1.IsBW || Form1.IsBW2)
            {
                System.IO.BinaryReader readMap = new System.IO.BinaryReader(File.OpenRead(Form1.workingFolder + @"data\a\0\0\maps" + "\\" + Form1.mapIndex.ToString("D4")));
                readMap.BaseStream.Position = Form1.vbldOffset + 0x4 + listBox1.SelectedIndex * 0x10;
                textBox1.Text        = Convert.ToString(readMap.ReadUInt16());         // Reads X Flag
                numericUpDown2.Value = readMap.ReadInt16();                            // Reads X Tile
                textBox8.Text        = Convert.ToString(readMap.ReadUInt16());         // Reads Y Flag
                numericUpDown3.Value = readMap.ReadInt16();                            // Reads Y Tile
                textBox9.Text        = Convert.ToString(readMap.ReadUInt16());         // Reads Z Flag
                numericUpDown4.Value = readMap.ReadInt16();                            // Reads Z Tile
                readMap.BaseStream.Position++;
                numericUpDown5.Value = readMap.ReadByte();                             // Reads Rotation
                numericUpDown1.Value = (readMap.ReadByte() << 8) + readMap.ReadByte(); // Reads Model ID
                readMap.Close();
                dataGridView1.Rows[(Int16)(((int)(numericUpDown4.Value) ^ 0xFFFF) + 17)].Cells[(int)(numericUpDown2.Value + 17)].Selected = true;
            }
            else
            {
                System.IO.BinaryReader read = new System.IO.BinaryReader(File.OpenRead(Form1.mapFileName + "\\" + Form1.mapIndex.ToString("D4")));
                if (Form1.gameID == 0x45414441 || Form1.gameID == 0x45415041 || Form1.gameID == 0x53414441 || Form1.gameID == 0x53415041 || Form1.gameID == 0x46414441 || Form1.gameID == 0x46415041 || Form1.gameID == 0x49414441 || Form1.gameID == 0x49415041 || Form1.gameID == 0x44414441 || Form1.gameID == 0x44415041 || Form1.gameID == 0x4A414441 || Form1.gameID == 0x4A415041 || Form1.gameID == 0x4B414441 || Form1.gameID == 0x4B415041 || Form1.gameID == 0x45555043 || Form1.gameID == 0x53555043 || Form1.gameID == 0x46555043 || Form1.gameID == 0x49555043 || Form1.gameID == 0x44555043 || Form1.gameID == 0x4A555043 || Form1.gameID == 0x4B555043)
                {
                    read.BaseStream.Position = 0x10 + Form1.permissionSize + (0x0 + 0x30 * listBox1.SelectedIndex);
                }
                else
                {
                    read.BaseStream.Position = 0x14 + Form1.unknownSize + Form1.permissionSize + (0x0 + 0x30 * listBox1.SelectedIndex);
                }
                numericUpDown1.Value = read.ReadUInt32(); // Reads Model Index
                textBox1.Text        = Convert.ToString(read.ReadUInt16());
                numericUpDown2.Value = read.ReadInt16();  // Reads X Coordinates
                textBox8.Text        = Convert.ToString(read.ReadUInt16());
                numericUpDown3.Value = read.ReadInt16();  // Reads Y Coordinates
                textBox9.Text        = Convert.ToString(read.ReadUInt16());
                numericUpDown4.Value = read.ReadInt16();  // Reads Z Coordinates
                if (Form1.gameID == 0x45414441 || Form1.gameID == 0x45415041 || Form1.gameID == 0x53414441 || Form1.gameID == 0x53415041 || Form1.gameID == 0x46414441 || Form1.gameID == 0x46415041 || Form1.gameID == 0x49414441 || Form1.gameID == 0x49415041 || Form1.gameID == 0x44414441 || Form1.gameID == 0x44415041 || Form1.gameID == 0x4A414441 || Form1.gameID == 0x4A415041 || Form1.gameID == 0x4B414441 || Form1.gameID == 0x4B415041 || Form1.gameID == 0x45555043 || Form1.gameID == 0x53555043 || Form1.gameID == 0x46555043 || Form1.gameID == 0x49555043 || Form1.gameID == 0x44555043 || Form1.gameID == 0x4A555043 || Form1.gameID == 0x4B555043)
                {
                    read.BaseStream.Position = 0x10 + Form1.permissionSize + (0x0 + 0x30 * listBox1.SelectedIndex + 0x1D);
                }
                else
                {
                    read.BaseStream.Position = 0x14 + Form1.unknownSize + Form1.permissionSize + (0x0 + 0x30 * listBox1.SelectedIndex + 0x1D);
                }
                textBox7.Text = Convert.ToString(read.ReadInt16());
                if (Form1.gameID == 0x45414441 || Form1.gameID == 0x45415041 || Form1.gameID == 0x53414441 || Form1.gameID == 0x53415041 || Form1.gameID == 0x46414441 || Form1.gameID == 0x46415041 || Form1.gameID == 0x49414441 || Form1.gameID == 0x49415041 || Form1.gameID == 0x44414441 || Form1.gameID == 0x44415041 || Form1.gameID == 0x4A414441 || Form1.gameID == 0x4A415041 || Form1.gameID == 0x4B414441 || Form1.gameID == 0x4B415041 || Form1.gameID == 0x45555043 || Form1.gameID == 0x53555043 || Form1.gameID == 0x46555043 || Form1.gameID == 0x49555043 || Form1.gameID == 0x44555043 || Form1.gameID == 0x4A555043 || Form1.gameID == 0x4B555043)
                {
                    read.BaseStream.Position = 0x10 + Form1.permissionSize + (0x0 + 0x30 * listBox1.SelectedIndex + 0x21);
                }
                else
                {
                    read.BaseStream.Position = 0x14 + Form1.unknownSize + Form1.permissionSize + (0x0 + 0x30 * listBox1.SelectedIndex + 0x21);
                }
                textBox6.Text = Convert.ToString(read.ReadInt16());
                if (Form1.gameID == 0x45414441 || Form1.gameID == 0x45415041 || Form1.gameID == 0x53414441 || Form1.gameID == 0x53415041 || Form1.gameID == 0x46414441 || Form1.gameID == 0x46415041 || Form1.gameID == 0x49414441 || Form1.gameID == 0x49415041 || Form1.gameID == 0x44414441 || Form1.gameID == 0x44415041 || Form1.gameID == 0x4A414441 || Form1.gameID == 0x4A415041 || Form1.gameID == 0x4B414441 || Form1.gameID == 0x4B415041 || Form1.gameID == 0x45555043 || Form1.gameID == 0x53555043 || Form1.gameID == 0x46555043 || Form1.gameID == 0x49555043 || Form1.gameID == 0x44555043 || Form1.gameID == 0x4A555043 || Form1.gameID == 0x4B555043)
                {
                    read.BaseStream.Position = 0x10 + Form1.permissionSize + (0x0 + 0x30 * listBox1.SelectedIndex + 0x25);
                }
                else
                {
                    read.BaseStream.Position = 0x14 + Form1.unknownSize + Form1.permissionSize + (0x0 + 0x30 * listBox1.SelectedIndex + 0x25);
                }
                textBox5.Text = Convert.ToString(read.ReadInt16());
                read.Close();
                dataGridView1.Rows[Convert.ToInt32(numericUpDown4.Value + 17)].Cells[Convert.ToInt32(numericUpDown2.Value + 17)].Selected = true;
            }
        }
Ejemplo n.º 35
0
        public void Read(System.IO.BinaryReader br)
        {
            ByteOrder        = br.ReadUInt16();
            Version          = br.ReadUInt16();
            SystemIdentifier = br.ReadUInt32();
            CLSID            = new Guid(br.ReadBytes(16));
            NumPropertySets  = br.ReadUInt32();
            FMTID0           = new Guid(br.ReadBytes(16));
            Offset0          = br.ReadUInt32();

            if (NumPropertySets == 2)
            {
                FMTID1  = new Guid(br.ReadBytes(16));
                Offset1 = br.ReadUInt32();
            }

            PropertySet0               = new PropertySet();
            PropertySet0.Size          = br.ReadUInt32();
            PropertySet0.NumProperties = br.ReadUInt32();


            // Read property offsets (P0)
            for (int i = 0; i < PropertySet0.NumProperties; i++)
            {
                PropertyIdentifierAndOffset pio = new PropertyIdentifierAndOffset();
                pio.PropertyIdentifier = br.ReadUInt32();
                pio.Offset             = br.ReadUInt32();
                PropertySet0.PropertyIdentifierAndOffsets.Add(pio);
            }

            PropertySet0.LoadContext((int)Offset0, br);  //Read CodePage, Locale

            // Read properties (P0)
            for (int i = 0; i < PropertySet0.NumProperties; i++)
            {
                br.BaseStream.Seek(Offset0 + PropertySet0.PropertyIdentifierAndOffsets[i].Offset, System.IO.SeekOrigin.Begin);
                PropertySet0.Properties.Add(ReadProperty(PropertySet0.PropertyIdentifierAndOffsets[i].PropertyIdentifier, PropertySet0.PropertyContext.CodePage, br));
            }

            if (NumPropertySets == 2)
            {
                br.BaseStream.Seek(Offset1, System.IO.SeekOrigin.Begin);
                PropertySet1               = new PropertySet();
                PropertySet1.Size          = br.ReadUInt32();
                PropertySet1.NumProperties = br.ReadUInt32();

                // Read property offsets
                for (int i = 0; i < PropertySet1.NumProperties; i++)
                {
                    PropertyIdentifierAndOffset pio = new PropertyIdentifierAndOffset();
                    pio.PropertyIdentifier = br.ReadUInt32();
                    pio.Offset             = br.ReadUInt32();
                    PropertySet1.PropertyIdentifierAndOffsets.Add(pio);
                }

                PropertySet1.LoadContext((int)Offset1, br);

                // Read properties
                for (int i = 0; i < PropertySet1.NumProperties; i++)
                {
                    br.BaseStream.Seek(Offset1 + PropertySet1.PropertyIdentifierAndOffsets[i].Offset, System.IO.SeekOrigin.Begin);
                    PropertySet1.Properties.Add(ReadProperty(PropertySet1.PropertyIdentifierAndOffsets[i].PropertyIdentifier, PropertySet1.PropertyContext.CodePage, br));
                }
            }
        }
Ejemplo n.º 36
0
        public static ParsedObjectFile ParseObjectFile(string ObjectFilePath)
        {
            ParsedObjectFile Result = null;

            // Fixed structure sizes
            int SizeofCOFFFileHeader   = 20;
            int SizeofSectionHeader    = 40;
            int SizeofSymbolTableEntry = 18;
            int SizeofRelocationEntry  = 10;

            // Open the object file for reading
            using (FileStream FileStream = System.IO.File.OpenRead(ObjectFilePath))
            {
                long FileLength = FileStream.Length;

                if (FileLength < SizeofCOFFFileHeader)
                {
                    // You cannot parse the COFF header if the file is not big enough to contain a COFF header.
                    throw new Exception("ObjectFile is too small to store a COFF header.");
                }

                // Open a BinaryReader object for the object file
                using (BinaryReader BinaryReader = new System.IO.BinaryReader(FileStream))
                {
                    // Parse the COFF header
                    COFF.HEADER CoffHeader = new COFF.HEADER(BinaryReader);

                    if (CoffHeader.SizeOfOptionalHeader != 0)
                    {
                        // Per the PECOFF specification, an object file does not have an optional header
                        throw new Exception("Coff header indicates the existence of an optional header. An object file cannot have an optional header.");
                    }

                    if (CoffHeader.PointerToSymbolTable == 0)
                    {
                        throw new Exception("An object file is supposed to have a symbol table.");
                    }

                    if (FileLength < ((CoffHeader.NumberOfSections * SizeofSectionHeader) + SizeofCOFFFileHeader))
                    {
                        // The object file isn't big enough to store the number of sections present.
                        throw new Exception("ObjectFile is too small to store section header data.");
                    }

                    // A string collection used to store section header names. This collection is referenced while
                    // parsing the symbol table entries whose name is the same as the section header. In this case,
                    // the symbol entry will have a particular auxiliary symbol table entry.
                    System.Collections.Specialized.StringCollection SectionHeaderNames = new System.Collections.Specialized.StringCollection();

                    // Correlate the processor type to the relocation type. There are more relocation type defined
                    // in the PECOFF specification, but I don't expect those to be present. In that case, relocation
                    // entries default to X86RelocationType.
                    COFF.SECTION_HEADER[] SectionHeaders = new COFF.SECTION_HEADER[CoffHeader.NumberOfSections];

                    // Parse section headers
                    for (int i = 0; i < CoffHeader.NumberOfSections; i++)
                    {
                        SectionHeaders[i] = new COFF.SECTION_HEADER(BinaryReader);

                        // Add the section name to the string collection. This will be referenced during symbol table parsing.
                        SectionHeaderNames.Add(SectionHeaders[i].Name);

                        // Save the current filestream position. We are about to jump out of place.
                        long SavedFilePosition = FileStream.Position;

                        // Check to see if the raw data points beyond the actual file size
                        if ((SectionHeaders[i].PointerToRawData + SectionHeaders[i].SizeOfRawData) > FileLength)
                        {
                            throw new Exception("Section header's raw data exceeds the size of the object file.");
                        }
                        else
                        {
                            // Read the raw data into a byte array
                            FileStream.Seek(SectionHeaders[i].PointerToRawData, SeekOrigin.Begin);
                            SectionHeaders[i].RawData = BinaryReader.ReadBytes((int)SectionHeaders[i].SizeOfRawData);
                        }

                        // Check to see if the section has a relocation table
                        if ((SectionHeaders[i].PointerToRelocations != 0) && (SectionHeaders[i].NumberOfRelocations != 0))
                        {
                            // Check to see if the relocation entries point beyond the actual file size
                            if ((SectionHeaders[i].PointerToRelocations + (SizeofRelocationEntry * SectionHeaders[i].NumberOfRelocations)) > FileLength)
                            {
                                throw new Exception("(SectionHeaders[i].Name) section header's relocation entries exceeds the soze of the object file.");
                            }

                            FileStream.Seek(SectionHeaders[i].PointerToRelocations, SeekOrigin.Begin);

                            COFF.RelocationEntry[] Relocations = new COFF.RelocationEntry[SectionHeaders[i].NumberOfRelocations];

                            for (int j = 0; j < SectionHeaders[i].NumberOfRelocations; j++)
                            {
                                Relocations[j] = new COFF.RelocationEntry(BinaryReader);
                                // Cast the relocation as its respective type
                                switch (CoffHeader.Machine)
                                {
                                case Machine.I386:
                                    Relocations[j].Type = (COFF.X86RelocationType)Relocations[j].Type;
                                    break;

                                case Machine.AMD64:
                                    Relocations[j].Type = (COFF.AMD64RelocationType)Relocations[j].Type;
                                    break;

                                case Machine.ARMV7:
                                    Relocations[j].Type = (COFF.ARMRelocationType)Relocations[j].Type;
                                    break;

                                case Machine.ARM64:
                                    Relocations[j].Type = (COFF.ARMv8RelocationType)Relocations[j].Type;
                                    break;
                                }
                            }

                            // Add the relocation table entry to the section header
                            SectionHeaders[i].Relocations = Relocations;
                        }

                        // Restore the original filestream pointer
                        FileStream.Seek(SavedFilePosition, SeekOrigin.Begin);
                    }

                    // Retrieve the contents of the COFF string table
                    long SymTableSize      = CoffHeader.NumberOfSymbols * SizeofSymbolTableEntry;
                    long StringTableOffset = CoffHeader.PointerToSymbolTable + SymTableSize;

                    if (StringTableOffset > FileLength)
                    {
                        throw new Exception("The string table points beyond the end of the file.");
                    }

                    FileStream.Seek(StringTableOffset, SeekOrigin.Begin);
                    UInt32 StringTableLength = BinaryReader.ReadUInt32();

                    if (StringTableLength > FileLength)
                    {
                        throw new Exception("The string table's length exceeds the length of the file.");
                    }

                    string StringTable = System.Text.Encoding.UTF8.GetString(BinaryReader.ReadBytes((int)StringTableLength));

                    COFF.SYMBOL_TABLE[] RawSymbolTable = new COFF.SYMBOL_TABLE[CoffHeader.NumberOfSymbols];

                    // Retrieve the symbol table
                    if (FileLength < StringTableOffset)
                    {
                        throw new Exception("Symbol table is larger than the file size.");
                    }

                    FileStream.Seek(CoffHeader.PointerToSymbolTable, SeekOrigin.Begin);
                    int NumberofRegularSymbols = 0;

                    /*
                     *  Go through each symbol table looking for auxiliary symbols to parse
                     *
                     *  Currently supported auxiliary symbol table entry formats:
                     *  1) .file
                     *  2) Entry names that match the name of a section header
                     */

                    for (int i = 0; i < CoffHeader.NumberOfSymbols; i++)
                    {
                        // Parse the symbol tables regardless of whether they are normal or auxiliary symbols
                        RawSymbolTable[i] = new COFF.SYMBOL_TABLE(BinaryReader);

                        if (RawSymbolTable[i].NumberOfAuxSymbols == 0)
                        {
                            // This symbol table entry has no auxiliary symbols
                            NumberofRegularSymbols++;
                        }
                        else if (RawSymbolTable[i].Name == ".file")
                        {
                            long TempPosition = FileStream.Position; // Save filestream position
                            // Retrieve the file name
                            RawSymbolTable[i].AuxSymbols = System.Text.Encoding.UTF8.GetString(BinaryReader.ReadBytes(RawSymbolTable[i].NumberOfAuxSymbols * SizeofSymbolTableEntry)).TrimEnd(((Char)0));
                            FileStream.Seek(TempPosition, SeekOrigin.Begin); // Restore filestream position
                        }
                        else if (SectionHeaderNames.Contains(RawSymbolTable[i].Name))
                        {
                            long TempPosition = FileStream.Position;         // Save filestream position
                            RawSymbolTable[i].AuxSymbols = new COFF.SECTION_DEFINITION(BinaryReader);
                            FileStream.Seek(TempPosition, SeekOrigin.Begin); // Restore filestream position
                        }
                    }

                    // Create an array of symbol table entries without auxiliary table entries
                    COFF.SYMBOL_TABLE[] SymbolTable = new COFF.SYMBOL_TABLE[NumberofRegularSymbols];
                    int k = 0;

                    for (int i = 0; i < CoffHeader.NumberOfSymbols; i++)
                    {
                        SymbolTable[k] = RawSymbolTable[i]; // FYI, the first symbol table entry will never be an aux symbol
                        k++;

                        // Skip over the auxiliary symbols
                        if (RawSymbolTable[i].NumberOfAuxSymbols != 0)
                        {
                            i += RawSymbolTable[i].NumberOfAuxSymbols;
                        }
                    }

                    // Fix the section names if any of them point to the COFF string table
                    for (int i = 0; i < CoffHeader.NumberOfSections; i++)
                    {
                        if ((SectionHeaders[i].Name != null) && (SectionHeaders[i].Name.IndexOf('/') == 0))
                        {
                            string StringTableIndexString = SectionHeaders[i].Name.Substring(1);

                            int StringTableIndex;
                            if (int.TryParse(StringTableIndexString, out StringTableIndex))
                            {
                                StringTableIndex -= 4;

                                if (StringTableIndex > (StringTableLength + 4))
                                {
                                    throw new Exception("String table entry exceeds the bounds of the object file.");
                                }

                                int Length = StringTable.IndexOf(((Char)0), StringTableIndex);
                                SectionHeaders[i].Name = StringTable.Substring(StringTableIndex, Length);
                            }
                        }
                    }

                    // Fix the symbol table names
                    for (int i = 0; i < SymbolTable.Length; i++)
                    {
                        if ((SymbolTable[i].Name != null) && (SymbolTable[i].Name.IndexOf('/') == 0))
                        {
                            string StringTableIndexString = SymbolTable[i].Name.Substring(1);

                            int StringTableIndex;
                            if (int.TryParse(StringTableIndexString, out StringTableIndex))
                            {
                                StringTableIndex -= 4;
                                int Length = StringTable.IndexOf(((Char)0), StringTableIndex) - StringTableIndex;
                                SymbolTable[i].Name = StringTable.Substring(StringTableIndex, Length);
                            }
                        }
                    }

                    // Apply symbol names to the relocation entries
                    // SectionHeaders | Where-Object { _.Relocations } | % {
                    //     _.Relocations | % { _.Name = RawSymbolTable[_.SymbolTableIndex].Name }
                    // }
                    SectionHeaders.Where(h => (h.Relocations != null)).ToList().ForEach(h => h.Relocations.ToList().ForEach(r => r.Name = RawSymbolTable[r.SymbolTableIndex].Name));

                    Result                = new ParsedObjectFile();
                    Result.CoffHeader     = CoffHeader;
                    Result.SectionHeaders = SectionHeaders;
                    Result.SymbolTable    = SymbolTable;
                }
            }

            return(Result);
        }
Ejemplo n.º 37
0
 void IBinary.Read(System.IO.BinaryReader reader)
 {
     this.batteryId = reader.ReadUInt32();
     this.barrelId  = reader.ReadUInt32();
     this.bulletId  = reader.ReadUInt32();
 }
Ejemplo n.º 38
0
        public void Load(System.IO.BinaryReader reader)
        {
            version = reader.ReadByte();
            if (version > VERSION)
            {
                throw new CacheException("Unknown CacheItem Version.", null, version);
            }

            name             = reader.ReadString();
            modelname        = reader.ReadString();
            pfd              = new Packages.PackedFileDescriptor();
            pfd.Type         = reader.ReadUInt32();
            pfd.Group        = reader.ReadUInt32();
            localgroup       = reader.ReadUInt32();
            pfd.LongInstance = reader.ReadUInt64();


            int size = reader.ReadInt32();

            if (size == 0)
            {
                thumb = null;
            }
            else
            {
                byte[]       data = reader.ReadBytes(size);
                MemoryStream ms   = new MemoryStream(data);

                thumb = Image.FromStream(ms);
            }

            objtype = (Data.ObjectTypes)reader.ReadUInt16();
            if (version >= 4)
            {
                objfuncsort = reader.ReadUInt32();
            }
            else
            {
                objfuncsort = (uint)reader.ReadInt16();
            }

            if (version >= 2)
            {
                objname = reader.ReadString();
                use     = reader.ReadBoolean();
            }
            else
            {
                objname = modelname;
                use     = true;
            }

            if (version >= 3)
            {
                oclass = (ObjectClass)reader.ReadByte();
            }
            else
            {
                oclass = ObjectClass.Object;
            }
        }
Ejemplo n.º 39
0
 private void loadGenIV()
 {
     #region Names
     string path;
     if (Form1.gameID == 0x45414441 || Form1.gameID == 0x45415041 || Form1.gameID == 0x53414441 || Form1.gameID == 0x53415041 || Form1.gameID == 0x46414441 || Form1.gameID == 0x46415041 || Form1.gameID == 0x49414441 || Form1.gameID == 0x49415041 || Form1.gameID == 0x44414441 || Form1.gameID == 0x44415041)
     {
         path = Form1.workingFolder + @"data\msgdata\msg\0382";
     }
     else if (Form1.gameID == 0x4A414441 || Form1.gameID == 0x4A415041)
     {
         path = Form1.workingFolder + @"data\msgdata\msg\0374";
     }
     else if (Form1.gameID == 0x4B414441 || Form1.gameID == 0x4B415041)
     {
         path = Form1.workingFolder + @"data\msgdata\msg\0376";
     }
     else if (Form1.gameID == 0x45555043 || Form1.gameID == 0x53555043 || Form1.gameID == 0x46555043 || Form1.gameID == 0x49555043 || Form1.gameID == 0x44555043)
     {
         path = Form1.workingFolder + @"data\msgdata\pl_msg\0433";
     }
     else if (Form1.gameID == 0x4A555043)
     {
         path = Form1.workingFolder + @"data\msgdata\pl_msg\0427";
     }
     else if (Form1.gameID == 0x4A555043)
     {
         path = Form1.workingFolder + @"data\msgdata\pl_msg\0428";
     }
     else if (Form1.gameID == 0x454B5049 || Form1.gameID == 0x45475049 || Form1.gameID == 0x534B5049 || Form1.gameID == 0x53475049 || Form1.gameID == 0x464B5049 || Form1.gameID == 0x46475049 || Form1.gameID == 0x494B5049 || Form1.gameID == 0x49475049 || Form1.gameID == 0x444B5049 || Form1.gameID == 0x44475049)
     {
         path = Form1.workingFolder + @"data\a\0\2\text\0279";
     }
     else if (Form1.gameID == 0x4A4B5049 || Form1.gameID == 0x4A475049)
     {
         path = Form1.workingFolder + @"data\a\0\2\text\0272";
     }
     else
     {
         path = Form1.workingFolder + @"data\a\0\2\text\0274";
     }
     System.IO.BinaryReader readText = new System.IO.BinaryReader(File.OpenRead(path));
     int      stringCount            = (int)readText.ReadUInt16();
     int      initialKey             = (int)readText.ReadUInt16();
     int      key1           = (initialKey * 0x2FD) & 0xFFFF;
     int      key2           = 0;
     int      realKey        = 0;
     bool     specialCharON  = false;
     int[]    currentOffset  = new int[stringCount];
     int[]    currentSize    = new int[stringCount];
     string[] currentPokemon = new string[stringCount];
     int      car            = 0;
     for (int i = 0; i < stringCount; i++) // Reads and stores string offsets and sizes
     {
         key2             = (key1 * (i + 1) & 0xFFFF);
         realKey          = key2 | (key2 << 16);
         currentOffset[i] = ((int)readText.ReadUInt32()) ^ realKey;
         currentSize[i]   = ((int)readText.ReadUInt32()) ^ realKey;
     }
     for (int i = 0; i < stringCount; i++) // Adds new string
     {
         key1 = (0x91BD3 * (i + 1)) & 0xFFFF;
         readText.BaseStream.Position = currentOffset[i];
         string pokemonText = "";
         for (int j = 0; j < currentSize[i]; j++) // Adds new characters to string
         {
             car = ((int)readText.ReadUInt16()) ^ key1;
             #region Special Characters
             if (car == 0xE000 || car == 0x25BC || car == 0x25BD || car == 0xFFFE || car == 0xFFFF)
             {
                 if (car == 0xE000)
                 {
                     pokemonText += @"\n";
                 }
                 if (car == 0x25BC)
                 {
                     pokemonText += @"\r";
                 }
                 if (car == 0x25BD)
                 {
                     pokemonText += @"\f";
                 }
                 if (car == 0xFFFE)
                 {
                     pokemonText  += @"\v";
                     specialCharON = true;
                 }
                 if (car == 0xFFFF)
                 {
                     pokemonText += "";
                 }
             }
             #endregion
             else
             {
                 if (specialCharON == true)
                 {
                     pokemonText  += car.ToString("X4");
                     specialCharON = false;
                 }
                 else
                 {
                     string character = getChar.GetString(car.ToString("X4"));
                     pokemonText += character;
                     if (character == null)
                     {
                         pokemonText += @"\x" + car.ToString("X4");
                     }
                 }
             }
             key1 += 0x493D;
             key1 &= 0xFFFF;
         }
         comboBox1.Items.Add(pokemonText);
     }
     readText.Close();
     #endregion
     comboBox1.SelectedIndex = Form1.wildIndex;
 }
Ejemplo n.º 40
0
        public void ParseDat(string path)
        {
            string FileName = path;

            using (System.IO.BinaryReader BinaryReader = new System.IO.BinaryReader(System.IO.File.OpenRead(FileName)))
            {
                uint DatVersion      = BinaryReader.ReadUInt32();
                int  ItemCount       = BinaryReader.ReadUInt16();
                int  OutfitCount     = BinaryReader.ReadUInt16();
                int  EffectCount     = BinaryReader.ReadUInt16();
                int  ProjectileCount = BinaryReader.ReadUInt16();
                int  MaxID           = ItemCount + OutfitCount + EffectCount + ProjectileCount;
                Objects = new List <ItemData>(MaxID);
                int ID   = 100;
                DAT Flag = 0;

                while (ID < MaxID)
                {
                    ItemData CurrentObject = new ItemData();
                    CurrentObject.ID = ID;
                    do
                    {
                        Flag = (DAT)BinaryReader.ReadByte();
                        switch (Flag)
                        {
                        case DAT.IsGround:
                            CurrentObject.IsGround  = true;
                            CurrentObject.Waypoints = BinaryReader.ReadUInt16();
                            break;

                        case DAT.TopOrder1:
                            CurrentObject.TopOrder1 = true;
                            break;

                        case DAT.TopOrder2:
                            CurrentObject.TopOrder2 = true;
                            break;

                        case DAT.TopOrder3:
                            CurrentObject.TopOrder3 = true;
                            break;

                        case DAT.IsContainer:
                            CurrentObject.IsContainer = true;
                            break;

                        case DAT.IsStackable:
                            CurrentObject.IsStackable = true;
                            break;

                        case DAT.IsUsable:
                            CurrentObject.isUseAble = true;
                            break;

                        case DAT.IsCorpse:
                            CurrentObject.IsCorpse = true;
                            break;

                        case DAT.IsMultiUse:
                            CurrentObject.isMultiUse = true;
                            break;

                        case DAT.IsWritable:
                            CurrentObject.isWriteable   = true;
                            CurrentObject.MaxTextLength = BinaryReader.ReadUInt16();
                            break;

                        case DAT.IsReadable:
                            CurrentObject.isWriteableOnce = true;
                            CurrentObject.MaxTextLength   = BinaryReader.ReadUInt16();
                            break;

                        case DAT.IsFluidContainer:
                            CurrentObject.isLiquidContainer = true;
                            break;

                        case DAT.IsSplash:
                            CurrentObject.isLiquidPool = true;
                            break;

                        case DAT.Blocking:
                            CurrentObject.Blocking = true;
                            break;

                        case DAT.IsImmovable:
                            CurrentObject.isUnmoveable = true;
                            break;

                        case DAT.BlocksMissiles:
                            CurrentObject.BlocksMissiles = true;
                            break;

                        case DAT.BlocksPath:
                            CurrentObject.BlocksPath = true;
                            break;

                        case DAT.noMovmentAction:
                            CurrentObject.noMovmentAction = true;
                            break;

                        case DAT.IsPickupable:
                            CurrentObject.isTakeable = true;
                            break;

                        case DAT.IsHangable:
                            CurrentObject.isHangable = true;
                            break;

                        case DAT.IsHangableHorizontal:
                            CurrentObject.isHookSouth = true;
                            break;

                        case DAT.IsHangableVertical:
                            CurrentObject.isHookEast = true;
                            break;

                        case DAT.IsRotatable:
                            CurrentObject.isRotateable = true;
                            break;

                        case DAT.IsLightSource:
                            CurrentObject.isLight    = true;
                            CurrentObject.Brightness = BinaryReader.ReadUInt16();
                            CurrentObject.LightColor = BinaryReader.ReadUInt16();
                            break;

                        case DAT.Flag_DontHide:
                            CurrentObject.isDontHide = true;
                            break;

                        case DAT.Flag_Translucent:
                            CurrentObject.isTranslucent = true;
                            break;

                        case DAT.Flag_Shift:
                            CurrentObject.isDisplaced   = true;
                            CurrentObject.DisplacementX = BinaryReader.ReadUInt16();
                            CurrentObject.DisplacementY = BinaryReader.ReadUInt16();
                            break;

                        case DAT.Flag_Height:
                            CurrentObject.isHeight  = true;
                            CurrentObject.Elevation = BinaryReader.ReadUInt16();
                            break;

                        case DAT.Flag_LyingObject:
                            CurrentObject.isLyingObject = true;
                            break;

                        case DAT.Flag_AnimateAlways:
                            CurrentObject.isAnimateAlways = true;
                            break;

                        case DAT.Flag_Automap:
                            CurrentObject.isAutomap      = true;
                            CurrentObject.isAutomapColor = BinaryReader.ReadUInt16();
                            break;

                        case DAT.Flag_LensHelp:
                            CurrentObject.isLensHelp = true;
                            CurrentObject.LensHelp   = BinaryReader.ReadUInt16();
                            break;

                        case DAT.Flag_FullBank:
                            CurrentObject.isFullBank = true;
                            break;

                        case DAT.Flag_IgnoreLook:
                            CurrentObject.isIgnoreLook = true;
                            break;

                        case DAT.Flag_Clothes:
                            CurrentObject.isCloth   = true;
                            CurrentObject.ClothSlot = BinaryReader.ReadUInt16();
                            break;

                        case DAT.Flag_DefaultAction:
                            CurrentObject.DefaultAction = true;
                            int Action = BinaryReader.ReadUInt16();
                            break;

                        case DAT.Flag_Market:
                            CurrentObject.isMarket       = true;
                            CurrentObject.MarketCategory = (MarketCategory)BinaryReader.ReadUInt16();
                            CurrentObject.MarketTradeAs  = BinaryReader.ReadUInt16();
                            CurrentObject.MarketShowAs   = BinaryReader.ReadUInt16();
                            int MarketNameLength = BinaryReader.ReadUInt16();
                            CurrentObject.MarketName = System.Text.Encoding.GetEncoding("iso-8859-1").GetString(BinaryReader.ReadBytes(MarketNameLength));
                            CurrentObject.MarketRestrictProfession = BinaryReader.ReadUInt16();
                            CurrentObject.MarketRestrictLevel      = BinaryReader.ReadUInt16();
                            break;

                        case DAT.BreakFlag:

                            break;

                        default:
                            break;
                        }
                    } while ((byte)Flag != 255);
                    int FrameGroupCount = (ID > ItemCount && ID <= (ItemCount + OutfitCount)) ? BinaryReader.ReadByte() : 1;
                    for (int k = 0; k < FrameGroupCount; k++)
                    {
                        int FrameGroupID = (ID > ItemCount && ID <= (ItemCount + OutfitCount)) ? BinaryReader.ReadByte() : 0;

                        CurrentObject.Width  = BinaryReader.ReadByte();
                        CurrentObject.Height = BinaryReader.ReadByte();
                        if (CurrentObject.Width > 1 | CurrentObject.Height > 1)
                        {
                            CurrentObject.ExactSize = BinaryReader.ReadByte();
                        }

                        CurrentObject.Layers        = BinaryReader.ReadByte();
                        CurrentObject.PatternWidth  = BinaryReader.ReadByte();
                        CurrentObject.PatternHeight = BinaryReader.ReadByte();
                        CurrentObject.PatternDepth  = BinaryReader.ReadByte();
                        CurrentObject.Phases        = BinaryReader.ReadByte();
                        if (CurrentObject.Phases > 1)
                        {
                            int  loc8     = 0;
                            byte unkNown  = BinaryReader.ReadByte();
                            int  unknown1 = BinaryReader.ReadInt32();
                            byte unkNown2 = BinaryReader.ReadByte();
                            while (loc8 < CurrentObject.Phases)
                            {
                                int unknown3 = BinaryReader.ReadInt32();
                                int unknown4 = BinaryReader.ReadInt32();

                                loc8 += 1;
                            }
                        }
                        int numSpr = CurrentObject.Width * CurrentObject.Height;
                        numSpr *= CurrentObject.Layers * CurrentObject.PatternWidth;
                        numSpr *= CurrentObject.PatternHeight * CurrentObject.PatternDepth;
                        numSpr *= CurrentObject.Phases;

                        CurrentObject.NumberOfSprites = numSpr;

                        CurrentObject.Sprites = (int[])Array.CreateInstance(typeof(int), CurrentObject.NumberOfSprites);
                        for (int i = 0; i <= CurrentObject.NumberOfSprites - 1; i++)
                        {
                            CurrentObject.Sprites[i] = BinaryReader.ReadInt32();
                        }
                    }
                    ID++;
                    Objects.Add(CurrentObject);
                }
            }
        }
        /// <summary>
        /// Adds the data contained in the array to the body of the message
        /// </summary>
        /// <param name="data">Data to be added</param>
        /// <param name="offset">0-based index where data to be added starts in array</param>
        /// <returns>The number of unread bytes (bytes which belongs to an another message)</returns>
        protected override int AddData(byte[] data, int offset, int pDataLength)
        {
            int dataLength = pDataLength - offset;
            int length     = -1;

            _modulus = 0;
            if (dataLength + _count > _header.Size)
            {
                length   = _header.Size - _count;
                _modulus = dataLength - length;
            }
            else
            {
                length = dataLength;
                if (dataLength + _count == _header.Size)
                {
                    // The telegram is complete by now
                    _modulus = 0;
                }
                else
                {
                    // The telegram is not complete yet
                    length   = dataLength;
                    _modulus = -1;
                }
            }
            Array.Copy(data, offset, _body, _count, length);
            _count += length;
            if (_modulus >= 0)
            {
                // Message is completed
                _completed = true;
            }

            if (_completed)
            {
                System.IO.BinaryReader br = new System.IO.BinaryReader(new System.IO.MemoryStream(_body, _body.Length - 5, 5));
                _crc     = br.ReadUInt32();
                _endChar = br.ReadByte();
                br.Close();

                uint uiCalcCRC = CalculateCRC32(_body, _body.Length - 5);

                if (uiCalcCRC == _crc)
                {
                    _bCorrect = true;
                    try
                    {
                        // 27/09/2016
//						if ( _nEncryptionOption == 1 )
//							_bUseNewKey = true;
//						else
//							_bUseNewKey = false;
                        TransformReceivedBody();
                    }
                    catch
                    {
                        // 27/09/2016
//						if ( _nEncryptionOption == 2 )
//						{
//							try
//							{
//								_bUseNewKey = true;
//								TransformReceivedBody();
//							}
//							catch
//							{
//								_bCorrect = false;
//							}
//						}
//						else
                        _bCorrect = false;
                    }
                }
            }

            return(_modulus);
        }
    public void RenderOnGUI()
    {
        GUILayout.BeginArea(new Rect(Screen.width - 200, 0, 200, Screen.height));
        GUILayout.Label("Variables:");
        GUILayout.Label("m_RemoteSteamId: " + m_RemoteSteamId);
        GUILayout.EndArea();

        GUILayout.BeginVertical("box");
        m_ScrollPos = GUILayout.BeginScrollView(m_ScrollPos, GUILayout.Width(Screen.width - 215), GUILayout.Height(Screen.height - 33));

        if (!m_RemoteSteamId.IsValid())
        {
            GUILayout.Label("Please fill m_RemoteSteamId with a valid 64bit SteamId to use SteamNetworkingTest.");
            GUILayout.Label("Alternatively it will be filled automatically when a session request is recieved.");
            GUILayout.EndScrollView();
            GUILayout.EndVertical();
            return;
        }

        // Session-less connection functions
        if (GUILayout.Button("SendP2PPacket(m_RemoteSteamId, bytes, (uint)bytes.Length, EP2PSend.k_EP2PSendReliable)"))
        {
            byte[] bytes = new byte[4];
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes))
                using (System.IO.BinaryWriter b = new System.IO.BinaryWriter(ms)) {
                    b.Write((uint)MsgType.Ping);
                }
            bool ret = SteamNetworking.SendP2PPacket(m_RemoteSteamId, bytes, (uint)bytes.Length, EP2PSend.k_EP2PSendReliable);
            print("SteamNetworking.SendP2PPacket(" + m_RemoteSteamId + ", " + bytes + ", " + (uint)bytes.Length + ", " + EP2PSend.k_EP2PSendReliable + ") : " + ret);
        }

        {
            uint MsgSize;
            bool ret = SteamNetworking.IsP2PPacketAvailable(out MsgSize);
            GUILayout.Label("IsP2PPacketAvailable(out MsgSize) : " + ret + " -- " + MsgSize);

            GUI.enabled = ret;

            if (GUILayout.Button("ReadP2PPacket(bytes, MsgSize, out newMsgSize, out SteamIdRemote)"))
            {
                byte[]   bytes = new byte[MsgSize];
                uint     newMsgSize;
                CSteamID SteamIdRemote;
                ret = SteamNetworking.ReadP2PPacket(bytes, MsgSize, out newMsgSize, out SteamIdRemote);

                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes))
                    using (System.IO.BinaryReader b = new System.IO.BinaryReader(ms)) {
                        MsgType msgtype = (MsgType)b.ReadUInt32();
                        // switch statement here depending on the msgtype
                        print("SteamNetworking.ReadP2PPacket(bytes, " + MsgSize + ", out newMsgSize, out SteamIdRemote) - " + ret + " -- " + newMsgSize + " -- " + SteamIdRemote + " -- " + msgtype);
                    }
            }

            GUI.enabled = true;
        }

        //SteamNetworking.AcceptP2PSessionWithUser() // Only called from within P2PSessionRequest Callback!

        if (GUILayout.Button("CloseP2PSessionWithUser(m_RemoteSteamId)"))
        {
            bool ret = SteamNetworking.CloseP2PSessionWithUser(m_RemoteSteamId);
            print("SteamNetworking.CloseP2PSessionWithUser(" + m_RemoteSteamId + ") : " + ret);
        }

        if (GUILayout.Button("CloseP2PChannelWithUser(m_RemoteSteamId, 0)"))
        {
            bool ret = SteamNetworking.CloseP2PChannelWithUser(m_RemoteSteamId, 0);
            print("SteamNetworking.CloseP2PChannelWithUser(" + m_RemoteSteamId + ", " + 0 + ") : " + ret);
        }

        {
            P2PSessionState_t ConnectionState;
            bool ret = SteamNetworking.GetP2PSessionState(m_RemoteSteamId, out ConnectionState);
            GUILayout.Label("GetP2PSessionState(m_RemoteSteamId, out ConnectionState) : " + ret + " -- " + ConnectionState);
        }

        if (GUILayout.Button("AllowP2PPacketRelay(true)"))
        {
            bool ret = SteamNetworking.AllowP2PPacketRelay(true);
            print("SteamNetworking.AllowP2PPacketRelay(" + true + ") : " + ret);
        }

        // LISTEN / CONNECT style interface functions
        //SteamNetworking.CreateListenSocket() // TODO

        //SteamNetworking.CreateP2PConnectionSocket() // TODO

        //SteamNetworking.CreateConnectionSocket() // TODO

        //SteamNetworking.DestroySocket() // TODO

        //SteamNetworking.DestroyListenSocket() // TODO

        //SteamNetworking.SendDataOnSocket() // TODO

        //SteamNetworking.IsDataAvailableOnSocket() // TODO

        //SteamNetworking.RetrieveDataFromSocket() // TODO

        //SteamNetworking.IsDataAvailable() // TODO

        //SteamNetworking.RetrieveData() // TODO

        //SteamNetworking.GetSocketInfo() // TODO

        //SteamNetworking.GetListenSocketInfo() // TODO

        //SteamNetworking.GetSocketConnectionType() // TODO

        //SteamNetworking.GetMaxPacketSize() // TODO

        GUILayout.EndScrollView();
        GUILayout.EndVertical();
    }
Ejemplo n.º 43
0
 /// <summary>
 ///     Reads the unsigned integer.
 /// </summary>
 /// <returns>The unsigned integer.</returns>
 public uint ReadUInt32()
 {
     return(_binaryReader.ReadUInt32());
 }
Ejemplo n.º 44
0
    public void RenderOnGUI()
    {
        GUILayout.BeginArea(new Rect(Screen.width - 200, 0, 200, Screen.height));
        GUILayout.Label("Variables:");
        GUILayout.Label("m_RemoteSteamId: " + m_RemoteSteamId);
        GUILayout.EndArea();

        if (!m_RemoteSteamId.IsValid())
        {
            GUILayout.Label("Please fill m_RemoteSteamId with a valid 64bit SteamId to use SteamNetworkingTest.");
            GUILayout.Label("Alternatively it will be filled automatically when a session request is recieved.");
            return;
        }

        // Session-less connection functions

        if (GUILayout.Button("SendP2PPacket(m_RemoteSteamId, bytes, (uint)bytes.Length, EP2PSend.k_EP2PSendReliable)"))
        {
            byte[] bytes = new byte[4];
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes))
                using (System.IO.BinaryWriter b = new System.IO.BinaryWriter(ms)) {
                    b.Write((uint)MsgType.Ping);
                }
            bool ret = SteamNetworking.SendP2PPacket(m_RemoteSteamId, bytes, (uint)bytes.Length, EP2PSend.k_EP2PSendReliable);
            print("SteamNetworking.SendP2PPacket(" + m_RemoteSteamId + ", bytes, " + bytes.Length + ", EP2PSend.k_EP2PSendReliable) - " + ret);
        }

        {
            uint MsgSize;
            bool ret = SteamNetworking.IsP2PPacketAvailable(out MsgSize);
            GUILayout.Label("IsP2PPacketAvailable(out MsgSize) : " + ret + " -- " + MsgSize);

            GUI.enabled = ret;

            if (GUILayout.Button("ReadP2PPacket(bytes, MsgSize, out newMsgSize, out SteamIdRemote)"))
            {
                byte[]   bytes = new byte[MsgSize];
                uint     newMsgSize;
                CSteamID SteamIdRemote;
                ret = SteamNetworking.ReadP2PPacket(bytes, MsgSize, out newMsgSize, out SteamIdRemote);

                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes))
                    using (System.IO.BinaryReader b = new System.IO.BinaryReader(ms)) {
                        MsgType msgtype = (MsgType)b.ReadUInt32();
                        // switch statement here depending on the msgtype
                        print("SteamNetworking.ReadP2PPacket(bytes, " + MsgSize + ", out newMsgSize, out SteamIdRemote) - " + ret + " -- " + newMsgSize + " -- " + SteamIdRemote + " -- " + msgtype);
                    }
            }

            GUI.enabled = true;
        }

        // bool AcceptP2PSessionWithUser(CSteamID steamIDRemote) // Only called from within P2PSessionRequest Callback!

        if (GUILayout.Button("CloseP2PSessionWithUser(m_RemoteSteamId)"))
        {
            bool ret = SteamNetworking.CloseP2PSessionWithUser(m_RemoteSteamId);
            print("SteamNetworking.CloseP2PSessionWithUser(" + m_RemoteSteamId + ") - " + ret);
        }

        if (GUILayout.Button("CloseP2PChannelWithUser(m_RemoteSteamId, 0)"))
        {
            bool ret = SteamNetworking.CloseP2PChannelWithUser(m_RemoteSteamId, 0);
            print("SteamNetworking.CloseP2PChannelWithUser(" + m_RemoteSteamId + ", 0) - " + ret);
        }

        {
            P2PSessionState_t ConnectionState;
            bool ret = SteamNetworking.GetP2PSessionState(m_RemoteSteamId, out ConnectionState);
            GUILayout.Label("GetP2PSessionState(m_RemoteSteamId, out ConnectionState) : " + ret + " -- " + ConnectionState.m_bConnectionActive + " -- " + ConnectionState.m_bConnecting + " -- " + ConnectionState.m_eP2PSessionError + " -- " + ConnectionState.m_bUsingRelay + " -- " + ConnectionState.m_nBytesQueuedForSend + " -- " + ConnectionState.m_nPacketsQueuedForSend + " -- " + ConnectionState.m_nRemoteIP + " -- " + ConnectionState.m_nRemotePort);
        }

        if (GUILayout.Button("AllowP2PPacketRelay(true)"))
        {
            bool ret = SteamNetworking.AllowP2PPacketRelay(true);
            print("SteamNetworking.AllowP2PPacketRelay(true) - " + ret);
        }

        // LISTEN / CONNECT style interface functions
    }
Ejemplo n.º 45
0
        /// <summary>
        /// (INCOMPLETE) Retrieve file information for a RAR file
        /// </summary>
        /// TODO: Write the rest of this RAR file handling
        public void GetRarFileInfo()
        {
            if (!File.Exists(this.Filename))
            {
                return;
            }

            BinaryReader br = new BinaryReader(Utilities.TryOpenRead(this.Filename));

            // Check for the signature first (Skipping the SFX Module)
            byte[] signature = br.ReadBytes(8);
            int    startpos  = 0;

            while (startpos < Constants.MibiByte && !signature.StartsWith(Constants.RarSignature, exact: true) && !signature.StartsWith(Constants.RarFiveSignature, exact: true))
            {
                startpos++;
                br.BaseStream.Position = startpos;
                signature = br.ReadBytes(8);
            }
            if (!signature.StartsWith(Constants.RarSignature, exact: true) && !signature.StartsWith(Constants.RarFiveSignature, exact: true))
            {
                return;
            }

            CoreRarArchive cra = new CoreRarArchive();

            if (startpos > 0)
            {
                br.BaseStream.Position = 0;
                cra.SFX = br.ReadBytes(startpos);
            }

            // Get all archive header information
            cra.HeaderCRC32 = br.ReadUInt32();
            cra.HeaderSize  = br.ReadUInt32();
            uint headerType = br.ReadUInt32();

            // Special encryption information
            bool hasEncryptionHeader = false;

            // If it's encrypted
            if (headerType == (uint)RarHeaderType.ArchiveEncryption)
            {
                hasEncryptionHeader       = true;
                cra.EncryptionHeaderCRC32 = cra.HeaderCRC32;
                cra.EncryptionHeaderSize  = cra.HeaderSize;
                cra.EncryptionHeaderFlags = (RarHeaderFlags)br.ReadUInt32();
                cra.EncryptionVersion     = br.ReadUInt32();
                cra.EncryptionFlags       = br.ReadUInt32();
                cra.KDFCount   = br.ReadByte();
                cra.Salt       = br.ReadBytes(16);
                cra.CheckValue = br.ReadBytes(12);

                cra.HeaderCRC32 = br.ReadUInt32();
                cra.HeaderSize  = br.ReadUInt32();
                headerType      = br.ReadUInt32();
            }

            cra.HeaderFlags = (RarHeaderFlags)br.ReadUInt32();
            if ((cra.HeaderFlags & RarHeaderFlags.ExtraAreaPresent) != 0)
            {
                cra.ExtraAreaSize = br.ReadUInt32();
            }
            cra.ArchiveFlags = (RarArchiveFlags)br.ReadUInt32();
            if ((cra.ArchiveFlags & RarArchiveFlags.VolumeNumberField) != 0)
            {
                cra.VolumeNumber = br.ReadUInt32();
            }
            if (((cra.HeaderFlags & RarHeaderFlags.ExtraAreaPresent) != 0) && cra.ExtraAreaSize != 0)
            {
                cra.ExtraArea = br.ReadBytes((int)cra.ExtraAreaSize);
            }

            // Archive Comment Service Header

            // Now for file headers
            for (; ;)
            {
                CoreRarArchiveEntry crae = new CoreRarArchiveEntry();
                crae.HeaderCRC32 = br.ReadUInt32();
                crae.HeaderSize  = br.ReadUInt32();
                crae.HeaderType  = (RarHeaderType)br.ReadUInt32();

                if (crae.HeaderType == RarHeaderType.EndOfArchive)
                {
                    break;
                }

                crae.HeaderFlags = (RarHeaderFlags)br.ReadUInt32();
                if ((crae.HeaderFlags & RarHeaderFlags.ExtraAreaPresent) != 0)
                {
                    crae.ExtraAreaSize = br.ReadUInt32();
                }
                if ((crae.HeaderFlags & RarHeaderFlags.DataAreaPresent) != 0)
                {
                    crae.DataAreaSize = br.ReadUInt32();
                }
                crae.FileFlags    = (RarFileFlags)br.ReadUInt32();
                crae.UnpackedSize = br.ReadUInt32();
                if ((crae.FileFlags & RarFileFlags.UnpackedSizeUnknown) != 0)
                {
                    crae.UnpackedSize = 0;
                }
                crae.Attributes             = br.ReadUInt32();
                crae.mtime                  = br.ReadUInt32();
                crae.DataCRC32              = br.ReadUInt32();
                crae.CompressionInformation = br.ReadUInt32();
                crae.HostOS                 = br.ReadUInt32();
                crae.NameLength             = br.ReadUInt32();
                crae.Name = br.ReadBytes((int)crae.NameLength);
                if ((crae.HeaderFlags & RarHeaderFlags.ExtraAreaPresent) != 0)
                {
                    uint extraSize = br.ReadUInt32();
                    switch (br.ReadUInt32())               // Extra Area Type
                    {
                    case 0x01:                             // File encryption information
                        crae.EncryptionSize  = extraSize;
                        crae.EncryptionFlags = (RarEncryptionFlags)br.ReadUInt32();
                        crae.KDFCount        = br.ReadByte();
                        crae.Salt            = br.ReadBytes(16);
                        crae.IV         = br.ReadBytes(16);
                        crae.CheckValue = br.ReadBytes(12);
                        break;

                    case 0x02:                             // File data hash
                        crae.HashSize = extraSize;
                        crae.HashType = br.ReadUInt32();
                        crae.HashData = br.ReadBytes(32);
                        break;

                    case 0x03:                             // High precision file time
                        crae.TimeSize  = extraSize;
                        crae.TimeFlags = (RarTimeFlags)br.ReadUInt32();
                        if ((crae.TimeFlags & RarTimeFlags.TimeInUnixFormat) != 0)
                        {
                            if ((crae.TimeFlags & RarTimeFlags.ModificationTimePresent) != 0)
                            {
                                crae.TimeMtime64 = br.ReadUInt64();
                            }
                            if ((crae.TimeFlags & RarTimeFlags.CreationTimePresent) != 0)
                            {
                                crae.TimeCtime64 = br.ReadUInt64();
                            }
                            if ((crae.TimeFlags & RarTimeFlags.LastAccessTimePresent) != 0)
                            {
                                crae.TimeLtime64 = br.ReadUInt64();
                            }
                        }
                        else
                        {
                            if ((crae.TimeFlags & RarTimeFlags.ModificationTimePresent) != 0)
                            {
                                crae.TimeMtime = br.ReadUInt32();
                            }
                            if ((crae.TimeFlags & RarTimeFlags.CreationTimePresent) != 0)
                            {
                                crae.TimeCtime = br.ReadUInt32();
                            }
                            if ((crae.TimeFlags & RarTimeFlags.LastAccessTimePresent) != 0)
                            {
                                crae.TimeLtime = br.ReadUInt32();
                            }
                        }
                        break;

                    case 0x04:                             // File version number
                        crae.VersionSize = extraSize;
                        /* crae.VersionFlags = */
                        br.ReadUInt32();
                        crae.VersionNumber = br.ReadUInt32();
                        break;

                    case 0x05:                             // File system redirection
                        crae.RedirectionSize       = extraSize;
                        crae.RedirectionType       = (RarRedirectionType)br.ReadUInt32();
                        crae.RedirectionFlags      = br.ReadUInt32();
                        crae.RedirectionNameLength = br.ReadUInt32();
                        crae.RedirectionName       = br.ReadBytes((int)crae.RedirectionNameLength);
                        break;

                    case 0x06:                             // Unix owner and group information
                        crae.UnixOwnerSize  = extraSize;
                        crae.UnixOwnerFlags = (RarUnixOwnerRecordFlags)br.ReadUInt32();
                        if ((crae.UnixOwnerFlags & RarUnixOwnerRecordFlags.UserNameStringIsPresent) != 0)
                        {
                            crae.UnixOwnerUserNameLength = br.ReadUInt32();
                            crae.UnixOwnerUserName       = br.ReadBytes((int)crae.UnixOwnerUserNameLength);
                        }
                        if ((crae.UnixOwnerFlags & RarUnixOwnerRecordFlags.GroupNameStringIsPresent) != 0)
                        {
                            crae.UnixOwnerGroupNameLength = br.ReadUInt32();
                            crae.UnixOwnerGroupName       = br.ReadBytes((int)crae.UnixOwnerGroupNameLength);
                        }
                        if ((crae.UnixOwnerFlags & RarUnixOwnerRecordFlags.NumericUserIdIsPresent) != 0)
                        {
                            crae.UnixOwnerUserId = br.ReadUInt32();
                        }
                        if ((crae.UnixOwnerFlags & RarUnixOwnerRecordFlags.NumericGroupIdIsPresent) != 0)
                        {
                            crae.UnixOwnerGroupId = br.ReadUInt32();
                        }
                        break;

                    case 0x07:                             // Service header data array

                        break;
                    }
                }
                if ((crae.HeaderFlags & RarHeaderFlags.DataAreaPresent) != 0)
                {
                    crae.DataArea = br.ReadBytes((int)crae.DataAreaSize);
                }
            }
        }
Ejemplo n.º 46
0
        public BMPImage LoadBMP(System.IO.BinaryReader aReader)
        {
            BMPImage bmp = new BMPImage();

            if (!ReadFileHeader(aReader, ref bmp.header))
            {
                Debug.LogError("Not a BMP file");
                return(null);
            }
            if (!ReadInfoHeader(aReader, ref bmp.info))
            {
                Debug.LogError("Unsupported header format");
                return(null);
            }
            if (bmp.info.compressionMethod != BMPComressionMode.BI_RGB &&
                bmp.info.compressionMethod != BMPComressionMode.BI_BITFIELDS &&
                bmp.info.compressionMethod != BMPComressionMode.BI_ALPHABITFIELDS &&
                bmp.info.compressionMethod != BMPComressionMode.BI_RLE4 &&
                bmp.info.compressionMethod != BMPComressionMode.BI_RLE8
                )
            {
                Debug.LogError("Unsupported image format: " + bmp.info.compressionMethod);
                return(null);
            }
            long offset = 14 + bmp.info.size;

            aReader.BaseStream.Seek(offset, SeekOrigin.Begin);
            if (bmp.info.nBitsPerPixel < 24)
            {
                bmp.rMask = 0x00007C00;
                bmp.gMask = 0x000003E0;
                bmp.bMask = 0x0000001F;
            }

            if (bmp.info.compressionMethod == BMPComressionMode.BI_BITFIELDS || bmp.info.compressionMethod == BMPComressionMode.BI_ALPHABITFIELDS)
            {
                bmp.rMask = aReader.ReadUInt32();
                bmp.gMask = aReader.ReadUInt32();
                bmp.bMask = aReader.ReadUInt32();
            }
            if (ForceAlphaReadWhenPossible)
            {
                bmp.aMask = GetMask(bmp.info.nBitsPerPixel) ^ (bmp.rMask | bmp.gMask | bmp.bMask);
            }

            if (bmp.info.compressionMethod == BMPComressionMode.BI_ALPHABITFIELDS)
            {
                bmp.aMask = aReader.ReadUInt32();
            }

            if (bmp.info.nPaletteColors > 0 || bmp.info.nBitsPerPixel <= 8)
            {
                bmp.palette = ReadPalette(aReader, bmp, ReadPaletteAlpha || ForceAlphaReadWhenPossible);
            }


            aReader.BaseStream.Seek(bmp.header.offset, SeekOrigin.Begin);
            bool uncompressed = bmp.info.compressionMethod == BMPComressionMode.BI_RGB ||
                                bmp.info.compressionMethod == BMPComressionMode.BI_BITFIELDS ||
                                bmp.info.compressionMethod == BMPComressionMode.BI_ALPHABITFIELDS;

            if (bmp.info.nBitsPerPixel == 32 && uncompressed)
            {
                Read32BitImage(aReader, bmp);
            }
            else if (bmp.info.nBitsPerPixel == 24 && uncompressed)
            {
                Read24BitImage(aReader, bmp);
            }
            else if (bmp.info.nBitsPerPixel == 16 && uncompressed)
            {
                Read16BitImage(aReader, bmp);
            }
            else if (bmp.info.compressionMethod == BMPComressionMode.BI_RLE4 && bmp.info.nBitsPerPixel == 4 && bmp.palette != null)
            {
                ReadIndexedImageRLE4(aReader, bmp);
            }
            else if (bmp.info.compressionMethod == BMPComressionMode.BI_RLE8 && bmp.info.nBitsPerPixel == 8 && bmp.palette != null)
            {
                ReadIndexedImageRLE8(aReader, bmp);
            }
            else if (uncompressed && bmp.info.nBitsPerPixel <= 8 && bmp.palette != null)
            {
                ReadIndexedImage(aReader, bmp);
            }
            else
            {
                Debug.LogError("Unsupported file format: " + bmp.info.compressionMethod + " BPP: " + bmp.info.nBitsPerPixel);
                return(null);
            }
            return(bmp);
        }
Ejemplo n.º 47
0
        public static string VersionResourceToXml(IntPtr versionRsrc)
        {
            var shortArray = new short[1];

            Marshal.Copy(versionRsrc, shortArray, 0, 1);
            int size = shortArray[0];

            var entireResourceBytes = new byte[size];

            Marshal.Copy(versionRsrc, entireResourceBytes, 0, entireResourceBytes.Length);

            var memoryStream = new System.IO.MemoryStream(entireResourceBytes);
            var reader       = new System.IO.BinaryReader(memoryStream, Encoding.Unicode);

            XmlDocument doc = new XmlDocument();

            using (XmlWriter xw = doc.CreateNavigator().AppendChild())
            {
                xw.WriteStartDocument();
                xw.WriteStartElement("VersionResource");
                xw.WriteAttributeString("Size", size.ToString());

                //0x28 is the start of the VS_FIXEDFILEINFO
                reader.BaseStream.Seek(0x28, System.IO.SeekOrigin.Begin);
                //skip the first two dwords of VS_FIXEDFILEINFO.
                reader.BaseStream.Seek(0x8, System.IO.SeekOrigin.Current);

                xw.WriteStartElement("VS_FIXEDFILEINFO");
                xw.WriteAttributeString("FileVersionMS", String.Format("{0:x8}", reader.ReadUInt32()));
                xw.WriteAttributeString("FileVersionLS", String.Format("{0:x8}", reader.ReadUInt32()));
                xw.WriteAttributeString("ProductVersionMS", String.Format("{0:x8}", reader.ReadUInt32()));
                xw.WriteAttributeString("ProductVersionLS", String.Format("{0:x8}", reader.ReadUInt32()));
                xw.WriteEndElement();

                long l;
                l = reader.ReadUInt32(); //((DWORD)0x0000003F);   //VS_FFI_FILEFLAGSMASK  (EDMAURER) really? all these bits are valid?
                l = reader.ReadUInt32(); //((DWORD)0);    //file flags
                l = reader.ReadUInt32(); //((DWORD)0x00000004);   //VOS__WINDOWS32
                l = reader.ReadUInt32(); //((DWORD)this.FileType);
                l = reader.ReadUInt32(); //((DWORD)0);    //file subtype
                l = reader.ReadUInt32(); //((DWORD)0);    //date most sig
                l = reader.ReadUInt32(); //((DWORD)0);    //date least sig

                //VS_VERSIONINFO can have zero or one VarFileInfo
                //and zero or one StringFileInfo
                while (reader.BaseStream.Position < size)
                {
                    ushort us;
                    string s;

                    ushort length = reader.ReadUInt16();
                    us = reader.ReadUInt16();    //0
                    us = reader.ReadUInt16();    //1
                    //must decide if this is a VarFileInfo or a StringFileInfo

                    s = ReadString(reader);
                    reader.BaseStream.Position = (reader.BaseStream.Position + 3) & ~3; //round up to 32bit boundary

                    IEnumerable <Tuple <string, string> > keyValPairs;
                    if (s == "VarFileInfo")
                    {
                        ReadVarFileInfo(reader);
                    }
                    else if (s == "StringFileInfo")
                    {
                        keyValPairs = ReadStringFileInfo(reader, length);
                        foreach (var pair in keyValPairs)
                        {
                            xw.WriteStartElement("KeyValuePair");
                            xw.WriteAttributeString("Key", pair.Item1.TrimEnd(new char[] { '\0' }));
                            xw.WriteAttributeString("Value", pair.Item2.TrimEnd(new char[] { '\0' }));
                            xw.WriteEndElement();
                        }
                    }
                }

                xw.WriteEndElement();
                xw.WriteEndDocument();
            }
            var sw = new System.IO.StringWriter(System.Globalization.CultureInfo.InvariantCulture);

            doc.Save(sw);
            return(sw.ToString());
        }
Ejemplo n.º 48
0
        public static SteamGameServerQueryEndPoint[] GetServerList(string gamename,
                                                                   Action <SteamGameServerQueryEndPoint> itemGenerated)
        {
            // https://developer.valvesoftware.com/wiki/Master_Server_Query_Protocol

            var queryEndPoints = new List <SteamGameServerQueryEndPoint>(5000);

            var addressBytes = new byte[4];
            var portBytes    = new byte[2];


            var dnsEntry = System.Net.Dns.GetHostEntry("hl2master.steampowered.com");

            //var ip = dnsEntry.AddressList.Length > 1 ? dnsEntry.AddressList[1] : dnsEntry.AddressList[0];
            foreach (var ip in dnsEntry.AddressList)
            {
                Debug.WriteLine($"Read from  {ip}");
                var        roundtrips   = 0;
                IPEndPoint lastEndPoint = new IPEndPoint(0, 0);
                queryEndPoints.Clear();

                using (System.Net.Sockets.UdpClient udp = new System.Net.Sockets.UdpClient())
                {
                    queryEndPoints.Clear();
                    var hasErros = false;

                    //udp.Connect("208.64.200.52", 27011);
                    while (true)
                    {
                        byte[] buffer = null;
                        try
                        {
                            udp.Connect(ip, 27011);
                            string request = "1ÿ";
                            request += lastEndPoint + "\0";
                            request += "\\gamedir\\" + gamename;
                            //request += "\\empty\\0";

#if DEBUG //request += @"\name_match\*EUTW*";
#endif

                            request += "\0";

                            var bytes = CharEncoding.GetBytes(request);

                            //udp.Connect("146.66.155.8", 27019);
                            IPEndPoint endp = udp.Client.RemoteEndPoint as IPEndPoint;
                            udp.Client.ReceiveTimeout = 900;

                            var sendlen = udp.Send(bytes, bytes.Length);
#if DEBUG
                            if (sendlen != bytes.Length)
                            {
                                Trace.WriteLine("IServerRepository.GetServerList - sendlen != bytes.Length");
                            }
#endif

                            roundtrips++;
                            buffer = udp.Receive(ref endp);
                        }
                        catch (System.Net.Sockets.SocketException)
                        {
                            //hasErros = true;
                            break;
                        }
                        catch (TimeoutException)
                        {
                            hasErros = true;
                            break;
                        }
                        catch (ObjectDisposedException)
                        {
                            hasErros = true;
                            break;
                        }

                        using (var mem = new System.IO.MemoryStream(buffer, false))
                            using (var br = new System.IO.BinaryReader(mem, Encoding.UTF8))
                            {
                                var i = br.ReadUInt32();
                                i = br.ReadUInt16();

                                while (mem.Position < mem.Length)
                                {
                                    addressBytes[0] = br.ReadByte();
                                    addressBytes[1] = br.ReadByte();
                                    addressBytes[2] = br.ReadByte();
                                    addressBytes[3] = br.ReadByte();

                                    portBytes[0] = br.ReadByte();
                                    portBytes[1] = br.ReadByte();

                                    int port = portBytes[0] << 8 | portBytes[1];


                                    if (addressBytes.All(b => b == 0))
                                    {
                                        break;
                                    }

                                    lastEndPoint = new IPEndPoint(new IPAddress(addressBytes), port);

                                    var item = new SteamGameServerQueryEndPoint();
                                    item.Host      = lastEndPoint.Address;
                                    item.QueryPort = lastEndPoint.Port;
                                    queryEndPoints.Add(item);
                                    if (itemGenerated != null)
                                    {
                                        itemGenerated(item);
                                    }
                                }

                                Debug.WriteLine("RoundTrips {0} - {1}", roundtrips, lastEndPoint.ToString());

                                if (addressBytes.All(b => b == 0))
                                {
                                    break;
                                }
                            }
                    }
                    if (!hasErros)
                    {
                        break;
                    }
                }
            }

            return(queryEndPoints.Distinct(new SteamGameServerQueryEndPointComparer()).ToArray());
        }
Ejemplo n.º 49
0
        internal override void Read(System.IO.BinaryReader reader, BinaryReadInfo readInfo)
        {
            uint length = reader.ReadUInt32();

            ID = reader.ReadUInt32();
            uint numSections = reader.ReadUInt32();

            string componentName = null;
            bool   canResize     = false;
            bool   canFlip       = false;
            double minSize       = ComponentHelper.GridSize;
            List <ComponentProperty>          properties          = new List <ComponentProperty>();
            List <ConnectionGroup>            connections         = new List <ConnectionGroup>();
            List <RenderDescription>          renderDescriptions  = new List <RenderDescription>();
            List <Conditional <FlagOptions> > flagOptions         = new List <Conditional <FlagOptions> >();
            ComponentDescriptionMetadata      descriptionMetadata = new ComponentDescriptionMetadata();
            uint?iconResourceId = null;

            for (uint sectionCounter = 0; sectionCounter < numSections; sectionCounter++)
            {
                ushort sectionType   = reader.ReadUInt16();
                uint   sectionLength = reader.ReadUInt32();

                #region Metadata
                if (sectionType == (uint)BinaryConstants.ComponentSectionType.Metadata)
                {
                    componentName              = reader.ReadString();
                    canResize                  = reader.ReadBoolean();
                    canFlip                    = reader.ReadBoolean();
                    minSize                    = reader.ReadDouble();
                    descriptionMetadata.Type   = String.Format("Binary r{0} (*.cdcom)", readInfo.FormatVersion);
                    descriptionMetadata.GUID   = new Guid(reader.ReadBytes(16));
                    descriptionMetadata.Author = reader.ReadString();
                    if (readInfo.IsSignatureValid && readInfo.Certificate != null && readInfo.IsCertificateTrusted)
                    {
                        descriptionMetadata.Author = readInfo.Certificate.GetNameInfo(X509NameType.EmailName, false);
                    }
                    descriptionMetadata.Version = new Version(reader.ReadUInt16(), reader.ReadUInt16());
                    descriptionMetadata.AdditionalInformation          = reader.ReadString();
                    descriptionMetadata.ImplementSet                   = reader.ReadString();
                    descriptionMetadata.ImplementItem                  = reader.ReadString();
                    descriptionMetadata.Signature.IsHashValid          = readInfo.IsSignatureValid;
                    descriptionMetadata.Signature.Certificate          = readInfo.Certificate;
                    descriptionMetadata.Signature.IsCertificateTrusted = readInfo.IsCertificateTrusted;
                    int iconResource = reader.ReadInt32();
                    if (iconResource != -1)
                    {
                        iconResourceId = (uint)iconResource;
                    }
                    long created = reader.ReadInt64();
                }
                #endregion
                #region Flags
                else if (sectionType == (uint)BinaryConstants.ComponentSectionType.Flags)
                {
                    uint numFlagGroups = reader.ReadUInt32();
                    for (uint j = 0; j < numFlagGroups; j++)
                    {
                        IConditionTreeItem conditions;
                        if (readInfo.FormatVersion > 1)
                        {
                            conditions = reader.ReadConditionTree();
                        }
                        else
                        {
                            conditions = reader.ReadConditionCollection();
                        }

                        FlagOptions value = (FlagOptions)reader.ReadUInt32();
                        flagOptions.Add(new Conditional <FlagOptions>(value, conditions));
                    }
                }
                #endregion
                #region Properties
                else if (sectionType == (uint)BinaryConstants.ComponentSectionType.Properties)
                {
                    uint numProperties = reader.ReadUInt32();
                    for (uint j = 0; j < numProperties; j++)
                    {
                        string        propertyName   = reader.ReadString();
                        string        serializedName = reader.ReadString();
                        string        displayName    = reader.ReadString();
                        BinaryType    propType;
                        object        rawDefaultValue = reader.ReadType(out propType);
                        PropertyUnion defaultValue    = propType.ToPropertyUnion(rawDefaultValue);
                        string[]      enumOptions     = null;
                        if (propType == BinaryType.Enum)
                        {
                            enumOptions = new string[reader.ReadInt32()];
                            for (int k = 0; k < enumOptions.Length; k++)
                            {
                                enumOptions[k] = reader.ReadString();
                            }
                        }

                        // Format rules
                        List <ComponentPropertyFormat> formatRules = new List <ComponentPropertyFormat>();
                        uint numFormatRules = reader.ReadUInt32();
                        for (uint k = 0; k < numFormatRules; k++)
                        {
                            IConditionTreeItem conditions;
                            if (readInfo.FormatVersion > 1)
                            {
                                conditions = reader.ReadConditionTree();
                            }
                            else
                            {
                                conditions = reader.ReadConditionCollection();
                            }
                            string formatRule = reader.ReadString();
                            formatRules.Add(new ComponentPropertyFormat(formatRule, conditions));
                        }

                        // Other conditions
                        uint numOtherConditions = reader.ReadUInt32();
                        Dictionary <PropertyOtherConditionType, IConditionTreeItem> otherConditions = new Dictionary <PropertyOtherConditionType, IConditionTreeItem>((int)numOtherConditions);
                        for (uint k = 0; k < numOtherConditions; k++)
                        {
                            uint uintConditionType = reader.ReadUInt32();
                            IConditionTreeItem conditions;
                            if (readInfo.FormatVersion > 1)
                            {
                                conditions = reader.ReadConditionTree();
                            }
                            else
                            {
                                conditions = reader.ReadConditionCollection();
                            }
                            PropertyOtherConditionType conditionType = (PropertyOtherConditionType)uintConditionType;
                            otherConditions.Add(conditionType, conditions);
                        }

                        properties.Add(new ComponentProperty(propertyName, serializedName, displayName, BinaryIOExtentions.BinaryTypeToPropertyType(propType), defaultValue, formatRules.ToArray(), otherConditions, enumOptions));
                    }
                }
                #endregion
                #region Configurations
                else if (sectionType == (uint)BinaryConstants.ComponentSectionType.Configurations)
                {
                    uint numConfigurations = reader.ReadUInt32();
                    for (int j = 0; j < numConfigurations; j++)
                    {
                        string configurationName  = reader.ReadString();
                        string implementationName = reader.ReadString();

                        int numSetters = reader.ReadInt32();
                        var setters    = new Dictionary <string, PropertyUnion>(numSetters);
                        for (int k = 0; k < numSetters; k++)
                        {
                            BinaryType tempType;
                            string     name        = reader.ReadString();
                            var        setterValue = reader.ReadType(out tempType);
                            setters.Add(name, tempType.ToPropertyUnion(setterValue));
                        }

                        int iconID = reader.ReadInt32();

                        var configuration = new ComponentConfiguration(implementationName, configurationName, setters);
                        descriptionMetadata.Configurations.Add(configuration);

                        if (iconID != -1)
                        {
                            iconResources.Add(configuration, (uint)iconID);
                        }
                    }
                }
                #endregion
                #region Connections
                else if (sectionType == (uint)BinaryConstants.ComponentSectionType.Connections)
                {
                    uint numConnectionGroups = reader.ReadUInt32();
                    List <ConnectionGroup> connectionGroups = new List <ConnectionGroup>();
                    for (int j = 0; j < numConnectionGroups; j++)
                    {
                        IConditionTreeItem conditions;
                        if (readInfo.FormatVersion > 1)
                        {
                            conditions = reader.ReadConditionTree();
                        }
                        else
                        {
                            conditions = reader.ReadConditionCollection();
                        }

                        List <ConnectionDescription> tConnections = new List <ConnectionDescription>();
                        uint numConnections = reader.ReadUInt32();
                        for (uint k = 0; k < numConnections; k++)
                        {
                            tConnections.Add(new ConnectionDescription(reader.ReadComponentPoint(), reader.ReadComponentPoint(), (ConnectionEdge)reader.ReadInt32(), reader.ReadString()));
                        }

                        connections.Add(new ConnectionGroup(conditions, tConnections.ToArray()));
                    }
                }
                #endregion
                #region Render
                else if (sectionType == (uint)BinaryConstants.ComponentSectionType.Render)
                {
                    uint numRenderGroups = reader.ReadUInt32();
                    for (uint j = 0; j < numRenderGroups; j++)
                    {
                        IConditionTreeItem conditions;
                        if (readInfo.FormatVersion > 1)
                        {
                            conditions = reader.ReadConditionTree();
                        }
                        else
                        {
                            conditions = reader.ReadConditionCollection();
                        }

                        int numRenderCommands = (int)reader.ReadUInt32();
                        List <IRenderCommand> renderCommands = new List <IRenderCommand>(numRenderCommands);
                        for (int k = 0; k < numRenderCommands; k++)
                        {
                            RenderCommandType commandType = (RenderCommandType)reader.ReadUInt32();
                            switch (commandType)
                            {
                            case RenderCommandType.Line:
                            {
                                ComponentPoint start     = reader.ReadComponentPoint();
                                ComponentPoint end       = reader.ReadComponentPoint();
                                double         thickness = reader.ReadDouble();
                                renderCommands.Add(new Line(start, end, thickness));
                            }
                                continue;

                            case RenderCommandType.Rect:
                            {
                                ComponentPoint location  = reader.ReadComponentPoint();
                                double         width     = reader.ReadDouble();
                                double         height    = reader.ReadDouble();
                                double         thickness = reader.ReadDouble();
                                bool           fill      = (reader.ReadUInt32() == 0 ? false : true);
                                renderCommands.Add(new Rectangle(location, width, height, thickness, fill));
                            }
                                continue;

                            case RenderCommandType.Ellipse:
                            {
                                ComponentPoint centre    = reader.ReadComponentPoint();
                                double         radiusX   = reader.ReadDouble();
                                double         radiusY   = reader.ReadDouble();
                                double         thickness = reader.ReadDouble();
                                bool           fill      = (reader.ReadUInt32() == 0 ? false : true);
                                renderCommands.Add(new Ellipse(centre, radiusX, radiusY, thickness, fill));
                            }
                                continue;

                            case RenderCommandType.Path:
                            {
                                ComponentPoint start     = reader.ReadComponentPoint();
                                double         thickness = reader.ReadDouble();
                                bool           fill      = (reader.ReadUInt32() == 0 ? false : true);

                                int numCommands = reader.ReadInt32();
                                List <IPathCommand> pathCommands = new List <IPathCommand>(numCommands);
                                for (int l = 0; l < numCommands; l++)
                                {
                                    CommandType  pType      = (CommandType)reader.ReadInt32();
                                    IPathCommand theCommand = null;
                                    switch (pType)
                                    {
                                    case CommandType.MoveTo:
                                        theCommand = new MoveTo();
                                        break;

                                    case CommandType.LineTo:
                                        theCommand = new LineTo();
                                        break;

                                    case CommandType.CurveTo:
                                        theCommand = new CurveTo();
                                        break;

                                    case CommandType.EllipticalArcTo:
                                        theCommand = new EllipticalArcTo();
                                        break;

                                    case CommandType.QuadraticBeizerCurveTo:
                                        theCommand = new QuadraticBeizerCurveTo();
                                        break;

                                    case CommandType.SmoothCurveTo:
                                        theCommand = new SmoothCurveTo();
                                        break;

                                    case CommandType.SmoothQuadraticBeizerCurveTo:
                                        theCommand = new SmoothQuadraticBeizerCurveTo();
                                        break;

                                    default:
                                        theCommand = new ClosePath();
                                        break;
                                    }
                                    theCommand.Read(reader);
                                    pathCommands.Add(theCommand);
                                }

                                renderCommands.Add(new RenderPath(start, thickness, fill, pathCommands));
                            }
                                continue;

                            case RenderCommandType.Text:
                            {
                                byte           formattedTextVersion = reader.ReadByte();
                                ComponentPoint location             = reader.ReadComponentPoint();
                                TextAlignment  alignment            = (TextAlignment)reader.ReadUInt32();

                                uint           numTextRuns = reader.ReadUInt32();
                                List <TextRun> textRuns    = new List <TextRun>((int)numTextRuns);
                                for (uint l = 0; l < numTextRuns; l++)
                                {
                                    TextRunFormattingType formattingType = (TextRunFormattingType)reader.ReadUInt32();
                                    double runSize = reader.ReadDouble();
                                    string runText = reader.ReadString();
                                    textRuns.Add(new TextRun(runText, new TextRunFormatting(formattingType, runSize)));
                                }

                                renderCommands.Add(new Text(location, alignment, textRuns));
                            }
                                continue;
                            }
                        }

                        renderDescriptions.Add(new RenderDescription(conditions, renderCommands.ToArray()));
                    }
                }
                #endregion
                #region Skip
                else
                {
                    // Unknown type - skip
                    reader.BaseStream.Seek(sectionLength, SeekOrigin.Current);
                }
                #endregion
            }

            ComponentDescription = new ComponentDescription(ID.ToString(), componentName, canResize, canFlip, minSize, properties.ToArray(), connections.ToArray(), renderDescriptions.ToArray(), flagOptions.ToArray(), descriptionMetadata);

            if (iconResourceId.HasValue)
            {
                mainIconResource = iconResourceId.Value;
            }
        }
Ejemplo n.º 50
0
        public SkinnedModel loadFromFile(string filename)
        {
            Info.print("Loading IQM model {0}", filename);

            if (File.Exists(filename) == false)
            {
                Warn.print("Cannot find file {0}", filename);
                return(null);
            }

            V3N3T2B4W4[] vertexData;
            ushort[]     triangleIndexes;

            IQMHeader myHeader;

            byte[]        myTexts;
            List <String> myComments = new List <String>();

            iqmvertexarray[] myVertArrays;
            iqmjoint[]       myJoints;
            iqmpose[]        myPoses;
            iqmanim[]        myAnimataions;
            iqmbounds[]      myBounds;
            iqmmesh[]        meshData;
            ushort[]         myFrameData;

            SkinnedModel sm = new SkinnedModel();

            System.IO.FileStream   stream = null;
            System.IO.BinaryReader reader = null;
            try
            {
                // Open the specified file as a stream and create a reader
                stream = new System.IO.FileStream(filename, FileMode.Open, FileAccess.Read);
                reader = new System.IO.BinaryReader(stream);

                myHeader.magic   = reader.ReadChars(16);
                myHeader.version = reader.ReadUInt32();
                if (myHeader.version != 2)
                {
                    return(null);
                }
                myHeader.filesize          = reader.ReadUInt32();
                myHeader.flags             = reader.ReadUInt32();
                myHeader.num_text          = reader.ReadUInt32();
                myHeader.ofs_text          = reader.ReadUInt32();
                myHeader.num_meshes        = reader.ReadUInt32();
                myHeader.ofs_meshes        = reader.ReadUInt32();
                myHeader.num_vertexarrays  = reader.ReadUInt32();
                myHeader.num_vertexes      = reader.ReadUInt32();
                myHeader.ofs_vertexarrays  = reader.ReadUInt32();
                myHeader.num_triangles     = reader.ReadUInt32();
                myHeader.ofs_triangles     = reader.ReadUInt32();
                myHeader.ofs_adjacency     = reader.ReadUInt32();
                myHeader.num_joints        = reader.ReadUInt32();
                myHeader.ofs_joints        = reader.ReadUInt32();
                myHeader.num_poses         = reader.ReadUInt32();
                myHeader.ofs_poses         = reader.ReadUInt32();
                myHeader.num_anims         = reader.ReadUInt32();
                myHeader.ofs_anims         = reader.ReadUInt32();
                myHeader.num_frames        = reader.ReadUInt32();
                myHeader.num_framechannels = reader.ReadUInt32();
                myHeader.ofs_frames        = reader.ReadUInt32();
                myHeader.ofs_bounds        = reader.ReadUInt32();
                myHeader.num_comment       = reader.ReadUInt32();
                myHeader.ofs_comment       = reader.ReadUInt32();
                myHeader.num_extensions    = reader.ReadUInt32();
                myHeader.ofs_extensions    = reader.ReadUInt32();

                boneCount = (int)myHeader.num_joints;

                //read text
                myTexts = new byte[myHeader.num_text];
                stream.Seek(myHeader.ofs_text, SeekOrigin.Begin);
                for (int i = 0; i < myHeader.num_text; i++)
                {
                    myTexts[i] = reader.ReadByte();
                }

                #region read geometry

                //create geometry fields
                for (int m = 0; m < myHeader.num_meshes; m++)
                {
                    sm.myMeshes.Add(new Mesh());
                }

                //read the mesh data
                meshData = new iqmmesh[myHeader.num_meshes];
                stream.Seek(myHeader.ofs_meshes, SeekOrigin.Begin);
                for (int i = 0; i < myHeader.num_meshes; i++)
                {
                    iqmmesh temp = new iqmmesh();
                    UInt32  n    = reader.ReadUInt32();
                    temp.name     = readNullTerminated(myTexts, n);
                    n             = reader.ReadUInt32();
                    temp.material = readNullTerminated(myTexts, n);
                    String fn = System.IO.Path.GetFileName(temp.material);
                    fn = System.IO.Path.ChangeExtension(fn, ".png");

                    String dir = System.IO.Path.GetDirectoryName(filename);
                    fn = System.IO.Path.Combine(dir, fn);

                    TextureDescriptor td  = new TextureDescriptor(fn);
                    Texture           tex = myResourceManager.getResource(td) as Texture;
                    Material          m   = new Material(temp.material);
                    m.addAttribute(new TextureAttribute("diffuseMap", tex));
                    m.myFeatures |= Material.Feature.Lighting;
                    m.myFeatures |= Material.Feature.DiffuseMap;

                    sm.myMeshes[i].material = m;

                    temp.first_vertex   = reader.ReadUInt32();
                    temp.num_vertexes   = reader.ReadUInt32();
                    temp.first_triangle = reader.ReadUInt32();
                    temp.num_triangles  = reader.ReadUInt32();
                    meshData[i]         = temp;
                }

                //read vertex arrays
                myVertArrays = new iqmvertexarray[myHeader.num_vertexarrays];
                stream.Seek(myHeader.ofs_vertexarrays, SeekOrigin.Begin);
                for (int i = 0; i < myHeader.num_vertexarrays; i++)
                {
                    iqmvertexarray temp = new iqmvertexarray();
                    temp.type       = (VertexArrayType)reader.ReadUInt32();
                    temp.flags      = reader.ReadUInt32();
                    temp.format     = (VertexArrayFormat)reader.ReadUInt32();
                    temp.size       = reader.ReadUInt32();
                    temp.offset     = reader.ReadUInt32();
                    myVertArrays[i] = temp;
                }

                //read the vertex data
                vertexData = new V3N3T2B4W4[myHeader.num_vertexes];
                for (int i = 0; i < myHeader.num_vertexarrays; i++)
                {
                    iqmvertexarray va = myVertArrays[i];
                    switch (va.type)
                    {
                    case VertexArrayType.IQM_POSITION:
                    {
                        stream.Seek(va.offset, SeekOrigin.Begin);
                        for (int j = 0; j < myHeader.num_vertexes; j++)
                        {
                            Vector3 temp = new Vector3();
                            temp.X = reader.ReadSingle();
                            temp.Y = reader.ReadSingle();
                            temp.Z = reader.ReadSingle();
                            vertexData[j].Position = temp;
                        }
                        break;
                    }

                    case VertexArrayType.IQM_TEXCOORD:
                    {
                        stream.Seek(va.offset, SeekOrigin.Begin);
                        for (int j = 0; j < myHeader.num_vertexes; j++)
                        {
                            Vector2 temp = new Vector2();
                            temp.X = reader.ReadSingle();
                            temp.Y = reader.ReadSingle();
                            vertexData[j].TexCoord = temp;
                        }
                        break;
                    }

                    case VertexArrayType.IQM_NORMAL:
                    {
                        stream.Seek(va.offset, SeekOrigin.Begin);
                        for (int j = 0; j < myHeader.num_vertexes; j++)
                        {
                            Vector3 temp = new Vector3();
                            temp.X = reader.ReadSingle();
                            temp.Y = reader.ReadSingle();
                            temp.Z = reader.ReadSingle();
                            vertexData[j].Normal = temp;
                        }
                        break;
                    }

                    case VertexArrayType.IQM_BLENDINDEXES:
                    {
                        stream.Seek(va.offset, SeekOrigin.Begin);
                        for (int j = 0; j < myHeader.num_vertexes; j++)
                        {
                            Vector4 temp = new Vector4();
                            temp.X = (float)reader.ReadByte();
                            temp.Y = (float)reader.ReadByte();
                            temp.Z = (float)reader.ReadByte();
                            temp.W = (float)reader.ReadByte();
                            vertexData[j].BoneId = temp;
                        }
                        break;
                    }

                    case VertexArrayType.IQM_BLENDWEIGHTS:
                    {
                        stream.Seek(va.offset, SeekOrigin.Begin);
                        for (int j = 0; j < myHeader.num_vertexes; j++)
                        {
                            Vector4 temp = new Vector4();
                            temp.X = ((float)reader.ReadByte()) / 255.0f;
                            temp.Y = ((float)reader.ReadByte()) / 255.0f;
                            temp.Z = ((float)reader.ReadByte()) / 255.0f;
                            temp.W = ((float)reader.ReadByte()) / 255.0f;
                            vertexData[j].BoneWeight = temp;
                        }
                        break;
                    }
                    }
                }

                //read triangles indexes
                triangleIndexes = new ushort[myHeader.num_triangles * 3];
                stream.Seek(myHeader.ofs_triangles, SeekOrigin.Begin);
                for (int i = 0; i < myHeader.num_triangles * 3; i++)
                {
                    triangleIndexes[i] = (ushort)reader.ReadUInt32();
                }
                #endregion

                #region read animation data
                //read joints
                myJoints = new iqmjoint[myHeader.num_joints];
                stream.Seek(myHeader.ofs_joints, SeekOrigin.Begin);
                for (int i = 0; i < myHeader.num_joints; i++)
                {
                    iqmjoint temp = new iqmjoint();
                    UInt32   n    = reader.ReadUInt32();
                    temp.name        = readNullTerminated(myTexts, n);
                    temp.parent      = reader.ReadInt32();
                    temp.translate   = new Vector3();
                    temp.translate.X = reader.ReadSingle();
                    temp.translate.Y = reader.ReadSingle();
                    temp.translate.Z = reader.ReadSingle();
                    temp.rotate      = new Quaternion();
                    temp.rotate.X    = reader.ReadSingle();
                    temp.rotate.Y    = reader.ReadSingle();
                    temp.rotate.Z    = reader.ReadSingle();
                    temp.rotate.W    = reader.ReadSingle();
                    temp.rotate.Normalize();
                    temp.scale   = new Vector3();
                    temp.scale.X = reader.ReadSingle();
                    temp.scale.Y = reader.ReadSingle();
                    temp.scale.Z = reader.ReadSingle();
                    myJoints[i]  = temp;
                }

                //read poses
                myPoses = new iqmpose[myHeader.num_poses];
                stream.Seek(myHeader.ofs_poses, SeekOrigin.Begin);
                for (int i = 0; i < myHeader.num_poses; i++)
                {
                    iqmpose temp = new iqmpose();
                    temp.parent      = reader.ReadInt32();
                    temp.channelmask = reader.ReadUInt32();

                    temp.channeloffset = new float[10];
                    for (int j = 0; j < 10; j++)
                    {
                        temp.channeloffset[j] = reader.ReadSingle();
                    }

                    temp.channelscale = new float[10];
                    for (int j = 0; j < 10; j++)
                    {
                        temp.channelscale[j] = reader.ReadSingle();
                    }

                    myPoses[i] = temp;
                }

                //read animations
                myAnimataions = new iqmanim[myHeader.num_anims];
                stream.Seek(myHeader.ofs_anims, SeekOrigin.Begin);
                for (int i = 0; i < myHeader.num_anims; i++)
                {
                    iqmanim temp = new iqmanim();
                    UInt32  n    = reader.ReadUInt32();
                    temp.name        = readNullTerminated(myTexts, n);
                    temp.first_frame = reader.ReadUInt32();
                    temp.num_frames  = reader.ReadUInt32();
                    temp.framerate   = reader.ReadSingle();
                    temp.flags       = reader.ReadUInt32();
                    myAnimataions[i] = temp;


                    Animation a = new Animation();
                    a.name = temp.name;
                    a.fps  = temp.framerate;
                    a.loop = true;
                    sm.animations.Add(a.name, a);
                }

                //read frame data
                myFrameData = new ushort[myHeader.num_frames * myHeader.num_framechannels];
                stream.Seek(myHeader.ofs_frames, SeekOrigin.Begin);
                for (int i = 0; i < myHeader.num_frames * myHeader.num_framechannels; i++)
                {
                    myFrameData[i] = reader.ReadUInt16();
                }

                #endregion

                //read bounds
                myBounds = new iqmbounds[myHeader.num_frames];
                stream.Seek(myHeader.ofs_bounds, SeekOrigin.Begin);
                for (int i = 0; i < myHeader.num_frames; i++)
                {
                    iqmbounds temp = new iqmbounds();
                    temp.bbmins    = new float[3];
                    temp.bbmaxs    = new float[3];
                    temp.bbmins[0] = reader.ReadSingle();
                    temp.bbmins[1] = reader.ReadSingle();
                    temp.bbmins[2] = reader.ReadSingle();
                    temp.bbmaxs[0] = reader.ReadSingle();
                    temp.bbmaxs[1] = reader.ReadSingle();
                    temp.bbmaxs[2] = reader.ReadSingle();
                    temp.xyradius  = reader.ReadSingle();
                    temp.radius    = reader.ReadSingle();

                    if (i == 0)
                    {
                        sm.size = temp.radius;
                    }
                }

                //read comments
                stream.Seek(myHeader.ofs_comment, SeekOrigin.Begin);
                int charRead = 0;
                while (charRead < myHeader.num_comment)
                {
                    char   c = reader.ReadChar(); charRead++;
                    string s = "";
                    while (c != '\0')
                    {
                        s += c;
                        c  = reader.ReadChar(); charRead++;
                    }

                    myComments.Add(s);
                }

                //read extensions
                //TODO

                //setup the bone data
                Matrix4[] baseframe        = new Matrix4[myHeader.num_joints];
                Matrix4[] inversebaseframe = new Matrix4[myHeader.num_joints];
                for (int i = 0; i < (int)myHeader.num_joints; i++)
                {
                    iqmjoint joint = myJoints[i];
                    Matrix4  r, t, s;
                    r                   = Matrix4.CreateFromQuaternion(joint.rotate);
                    t                   = Matrix4.CreateTranslation(joint.translate);
                    s                   = Matrix4.CreateScale(joint.scale);
                    baseframe[i]        = s * r * t;
                    inversebaseframe[i] = baseframe[i].Inverted();
                    if (joint.parent >= 0)
                    {
                        baseframe[i]        = baseframe[i] * baseframe[joint.parent];
                        inversebaseframe[i] = inversebaseframe[joint.parent] * inversebaseframe[i];
                    }

                    Bone b = new Bone();
                    b.myName            = myJoints[i].name;
                    b.myParent          = myJoints[i].parent;
                    b.myWorldBindMatrix = baseframe[i];
                    sm.skeleton.myBones.Add(b);
                }

                Matrix4[] absMatrix = new Matrix4[myHeader.num_frames * myHeader.num_poses];
                int       count     = 0;
                for (int i = 0; i < myHeader.num_frames; i++)
                {
                    for (int j = 0; j < myHeader.num_poses; j++)
                    {
                        iqmpose    p         = myPoses[j];
                        Quaternion rotate    = new Quaternion();
                        Vector3    translate = new Vector3();
                        Vector3    scale     = new Vector3();
                        translate.X = p.channeloffset[0]; if ((p.channelmask & 0x01) != 0)
                        {
                            translate.X += myFrameData[count++] * p.channelscale[0];
                        }
                        translate.Y = p.channeloffset[1]; if ((p.channelmask & 0x02) != 0)
                        {
                            translate.Y += myFrameData[count++] * p.channelscale[1];
                        }
                        translate.Z = p.channeloffset[2]; if ((p.channelmask & 0x04) != 0)
                        {
                            translate.Z += myFrameData[count++] * p.channelscale[2];
                        }
                        rotate.X = p.channeloffset[3]; if ((p.channelmask & 0x08) != 0)
                        {
                            rotate.X += myFrameData[count++] * p.channelscale[3];
                        }
                        rotate.Y = p.channeloffset[4]; if ((p.channelmask & 0x10) != 0)
                        {
                            rotate.Y += myFrameData[count++] * p.channelscale[4];
                        }
                        rotate.Z = p.channeloffset[5]; if ((p.channelmask & 0x20) != 0)
                        {
                            rotate.Z += myFrameData[count++] * p.channelscale[5];
                        }
                        rotate.W = p.channeloffset[6]; if ((p.channelmask & 0x40) != 0)
                        {
                            rotate.W += myFrameData[count++] * p.channelscale[6];
                        }
                        scale.X = p.channeloffset[7]; if ((p.channelmask & 0x80) != 0)
                        {
                            scale.X += myFrameData[count++] * p.channelscale[7];
                        }
                        scale.Y = p.channeloffset[8]; if ((p.channelmask & 0x100) != 0)
                        {
                            scale.Y += myFrameData[count++] * p.channelscale[8];
                        }
                        scale.Z = p.channeloffset[9]; if ((p.channelmask & 0x200) != 0)
                        {
                            scale.Z += myFrameData[count++] * p.channelscale[9];
                        }
                        // Concatenate each pose with the inverse base pose to avoid doing this at animation time.
                        // If the joint has a parent, then it needs to be pre-concatenated with its parent's base pose.
                        // Thus it all negates at animation time like so:
                        //   (parentPose * parentInverseBasePose) * (parentBasePose * childPose * childInverseBasePose) =>
                        //   parentPose * (parentInverseBasePose * parentBasePose) * childPose * childInverseBasePose =>
                        //   parentPose * childPose * childInverseBasePose
                        rotate.Normalize();
                        Matrix4 r, t, s;
                        r = Matrix4.CreateFromQuaternion(rotate);
                        t = Matrix4.CreateTranslation(translate);
                        s = Matrix4.CreateScale(scale);
                        Matrix4 pose = s * r * t;
                        if (p.parent >= 0)
                        {
                            Matrix4 parent     = baseframe[p.parent];
                            Matrix4 inv        = inversebaseframe[j];
                            Matrix4 parentPose = absMatrix[i * myHeader.num_poses + p.parent];
                            absMatrix[i * myHeader.num_poses + j] = inv * pose * parent * parentPose;
                        }
                        else
                        {
                            Matrix4 inv = inversebaseframe[j];
                            absMatrix[i * myHeader.num_poses + j] = inv * pose;
                        }
                    }
                }

                Vector4[] boneData = new Vector4[myHeader.num_frames * myHeader.num_poses * 4];
                int       next     = 0;
                for (int i = 0; i < myHeader.num_frames * myHeader.num_poses; i++)
                {
                    boneData[next++] = absMatrix[i].Row0;
                    boneData[next++] = absMatrix[i].Row1;
                    boneData[next++] = absMatrix[i].Row2;
                    boneData[next++] = absMatrix[i].Row3;
                }

                //setup the buffers
                sm.myBindings = V3N3T2B4W4.bindings();
                VertexBufferObject vbo = new VertexBufferObject(BufferUsageHint.StaticDraw);
                vbo.setData(vertexData);
                sm.myVbos.Add(vbo);

                List <ushort> indexes    = new List <ushort>();
                int           indexCount = 0;
                for (int m = 0; m < sm.myMeshes.Count; m++)
                {
                    Mesh mesh = sm.myMeshes[m];
                    mesh.primativeType = PrimitiveType.Triangles;
                    mesh.indexBase     = indexCount;

                    for (int t = 0; t < meshData[m].num_triangles; t++)
                    {
                        //swap the order the indicies since we want counter clockwise triangles instead of clockwise
                        indexes.Add(triangleIndexes[meshData[m].first_triangle * 3 + (t * 3) + 0]);
                        indexes.Add(triangleIndexes[meshData[m].first_triangle * 3 + (t * 3) + 2]);
                        indexes.Add(triangleIndexes[meshData[m].first_triangle * 3 + (t * 3) + 1]);
                        indexCount += 3;
                    }

                    mesh.indexCount = indexCount - mesh.indexBase;
                }

                sm.myIbo.setData(indexes);

                //upload the frame data
                sm.myFrames.setData(boneData);

                return(sm);
            }
            catch (Exception ex)
            {
                throw new Exception("Error while loading IQM model from definition file ( " + filename + " ).", ex);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
            }
        }
Ejemplo n.º 51
0
        public override IEnumerable <Tone> ImportToneFile(string fileName)
        {
            string      ext    = System.IO.Path.GetExtension(fileName);
            var         Option = new Option();
            List <Tone> tones  = new List <Tone>();

            try
            {
                switch (ext.ToUpper(CultureInfo.InvariantCulture))
                {
                case ".WOPL":
                {
                    using (var file = new System.IO.BinaryReader(new System.IO.FileStream(fileName, System.IO.FileMode.Open)))
                    {
                        file.BaseStream.Seek(0x11, System.IO.SeekOrigin.Begin);
                        {
                            var val = file.ReadByte();
                            //if ((val & 1) != 0)
                            //    tone.AMD = 1;
                            //if ((val & 2) != 0)
                            //    tone.VIB = 1;
                        }

                        file.BaseStream.Seek(0x57, System.IO.SeekOrigin.Begin);
                        for (int i = 0; i < 128; i++)
                        {
                            Tone tone1 = new Tone();
                            Tone tone2 = new Tone();
                            tone1.Number = i * 2;
                            tone2.Number = i * 2 + 1;

                            //32
                            var name = Encoding.ASCII.GetString(file.ReadBytes(32));
                            var nidx = name.IndexOf('\0');
                            if (nidx >= 0)
                            {
                                name = name.Substring(0, nidx);
                            }
                            if (name != null && name.Length != 0)
                            {
                                tone1.Name = name;
                                tone2.Name = name + "(2nd)";
                            }
                            //2
                            tone1.KeyShift = YMF262.ReadInt16Big(file);
                            //2
                            tone2.KeyShift = YMF262.ReadInt16Big(file);

                            //1
                            file.ReadByte();            //MIDI Velocity offset
                            //1
                            tone2.PitchShift = file.ReadSByte();

                            //1
                            //DrumTimbres[i].BaseNote = (NoteNames)file.ReadByte();
                            file.ReadByte();
                            //1
                            var opmode = file.ReadByte();

                            if (opmode == 0)                //2OP
                            {
                                setRegisters(file, tone1, null);
                                tones.Add(tone1);
                            }
                            else if (opmode == 1)           //4OP
                            {
                                setRegisters(file, tone1, tone2);
                                tone1.CNT    = (tone1.CNT << 1 | tone2.CNT) + 2;
                                tone1.FB2    = tone2.FB;
                                tone1.aOp[2] = tone2.aOp[0];
                                tone1.aOp[3] = tone2.aOp[1];
                                tones.Add(tone1);
                            }
                            else if (opmode == 3)
                            {
                                setRegisters(file, tone1, tone2);
                                tones.Add(tone1);
                                tones.Add(tone2);
                            }
                            else if ((opmode & 4) == 4)
                            {
                                //empty
                            }
                            else
                            {
                                // System.Windows.Forms.MessageBox.Show("Unsupported op mode " + opmode);
                            }
                        }

                        for (int i = 0; i < 128; i++)
                        {
                            Tone tone1 = new Tone();
                            Tone tone2 = new Tone();
                            tone1.Number = i * 2 + 256;
                            tone2.Number = i * 2 + 256 + 1;

                            //32
                            var name = Encoding.ASCII.GetString(file.ReadBytes(32));
                            var nidx = name.IndexOf('\0');
                            if (nidx >= 0)
                            {
                                name = name.Substring(0, nidx);
                            }
                            if (name != null && name.Length != 0)
                            {
                                tone1.Name = name;
                                tone2.Name = name + "(2nd)";
                            }
                            else
                            {
                                tone1.Name = tone1.Number.ToString();
                                tone2.Name = tone2.Number.ToString();
                            }

                            //2
                            tone1.KeyShift = ReadInt16Big(file);
                            //2
                            tone2.KeyShift = ReadInt16Big(file);

                            //1
                            file.ReadByte();            //MIDI Velocity offset
                            //1
                            tone2.PitchShift = file.ReadSByte();

                            //1
                            //TODO: Drum
                            //DrumTimbres[i].BaseNote = (NoteNames)file.ReadByte();
                            file.ReadByte();
                            //1
                            var opmode = file.ReadByte();

                            if (opmode == 0)                //2OP
                            {
                                setRegisters(file, tone1, null);
                                tones.Add(tone1);
                            }
                            else if (opmode == 1)           //4OP
                            {
                                setRegisters(file, tone1, tone2);
                                tone1.CNT    = (tone1.CNT << 1 | tone2.CNT) + 2;
                                tone1.aOp[2] = tone2.aOp[0];
                                tone1.aOp[3] = tone2.aOp[1];
                                tones.Add(tone1);
                            }
                            else if (opmode == 3)
                            {
                                setRegisters(file, tone1, tone2);
                                tones.Add(tone1);
                                tones.Add(tone2);
                            }
                            else if ((opmode & 4) == 4)
                            {
                                //empty
                            }
                            else
                            {
                                // System.Windows.Forms.MessageBox.Show("Unsupported op mode " + opmode);
                            }
                        }
                    }
                }
                break;

                case ".OPL":
                {
                    List <Head> list          = new List <Head>();
                    byte        maxBankNumber = 0;

                    using (var file = new System.IO.BinaryReader(new System.IO.FileStream(fileName, System.IO.FileMode.Open)))
                    {
                        while (true)
                        {
                            //read head
                            Head p = new Head();
                            p.Patch  = file.ReadByte();
                            p.Bank   = file.ReadByte();
                            p.Offset = file.ReadUInt32();

                            if (p.Patch == 0xff && p.Bank == 0xff)
                            {
                                break;
                            }

                            if ((p.Bank != 0x7F) && (p.Bank > maxBankNumber))
                            {
                                maxBankNumber = p.Bank;
                            }

                            list.Add(p);
                        }
                        ;

                        for (int i = 0; i < list.Count; i++)
                        {
                            var p = list[i];
                            file.BaseStream.Seek(p.Offset, System.IO.SeekOrigin.Begin);

                            bool isPerc    = (p.Bank == 0x7F);
                            int  gmPatchId = isPerc ? p.Patch : (p.Patch + (p.Bank * 128));

                            ushort insLen = file.ReadUInt16();
                            insLen -= 2;

                            byte[] idata = new byte[24];
                            if (insLen < 24)
                            {
                                idata = file.ReadBytes(insLen);
                            }
                            else
                            {
                                idata = file.ReadBytes(24);
                                file.BaseStream.Seek(insLen - 24, System.IO.SeekOrigin.Current);
                            }

                            //var tim = Timbres[p.Patch + (isPerc ? 128 : 0)];
                            Tone tone = new Tone();
                            tone.Number = i;
                            tone.Name   = i.ToString();

                            //ins.percNoteNum = (isPerc) ? idata[0] : 0;
                            //ins.note_offset1 = (isPerc) ? 0 : idata[0];
                            //if (isPerc)
                            //{
                            //    var t = DrumTimbres[p.Patch];
                            //    t.BaseNote = (NoteNames)idata[0];
                            //    t.TimbreNumber = (ProgramAssignmentNumber)(p.Patch + 128);
                            //}

                            tone.aOp[0].AM  = (byte)((idata[1] >> 7) & 0x1);
                            tone.aOp[0].VIB = (byte)((idata[1] >> 6) & 0x1);
                            tone.aOp[0].EG  = (byte)((idata[1] >> 5) & 0x1);
                            tone.aOp[0].KSR = (byte)((idata[1] >> 4) & 0x1);
                            tone.aOp[0].ML  = (byte)((idata[1]) & 0xf);

                            tone.aOp[0].KS = (byte)((idata[2] >> 6) & 0x03);
                            tone.aOp[0].TL = (byte)((idata[2]) & 0x3f);

                            tone.aOp[0].AR = (byte)((idata[3] >> 4) & 0x0f);
                            tone.aOp[0].DR = (byte)((idata[3]) & 0x0f);

                            tone.aOp[0].SL = (byte)((idata[4] >> 4) & 0x0f);
                            tone.aOp[0].SR = -1;
                            tone.aOp[0].RR = (byte)((idata[4]) & 0x0f);

                            tone.aOp[0].WS = (byte)((idata[5]) & 0x07);

                            tone.aOp[1].AM  = (byte)((idata[7] >> 7) & 0x1);
                            tone.aOp[1].VIB = (byte)((idata[7] >> 6) & 0x1);
                            tone.aOp[1].EG  = (byte)((idata[7] >> 5) & 0x1);
                            tone.aOp[1].KSR = (byte)((idata[7] >> 4) & 0x1);
                            tone.aOp[1].ML  = (byte)((idata[7]) & 0xf);

                            tone.aOp[1].KS = (byte)((idata[8] >> 6) & 0x03);
                            tone.aOp[1].TL = (byte)((idata[8]) & 0x3f);

                            tone.aOp[1].AR = (byte)((idata[9] >> 4) & 0x0f);
                            tone.aOp[1].DR = (byte)((idata[9]) & 0x0f);

                            tone.aOp[1].SL = (byte)((idata[10] >> 4) & 0x0f);
                            tone.aOp[1].SR = -1;
                            tone.aOp[1].RR = (byte)((idata[10]) & 0x0f);

                            tone.aOp[1].WS = (byte)((idata[11]) & 0x07);

                            tone.CNT = (byte)((idata[6]) & 0x01);
                            tone.FB  = (byte)((idata[6] >> 1) & 0x07);

                            tones.Add(tone);
                        }
                    }
                }
                break;

                default:
                    return(base.ImportToneFile(fileName));
                }
            }
            catch (Exception ex)
            {
                if (ex.GetType() == typeof(Exception))
                {
                    throw;
                }
                else if (ex.GetType() == typeof(SystemException))
                {
                    throw;
                }

                MessageBox.Show(Resources.FailedLoadFile + "\r\n" + ex.Message);
            }
            return(tones);
        }
Ejemplo n.º 52
0
        /// <summary>
        /// Loads a database schema
        /// </summary>
        /// <param name="reader">binary reader</param>
        /// <returns></returns>
        public static DbSchemaConfig Load(io.BinaryReader reader)
        {
            var schema = new DbSchemaConfig()
            {
                Flags       = (DbSchemaConfigType)reader.ReadUInt32(),
                Version     = reader.BinaryRead(),
                Description = reader.BinaryRead(),
                Name        = reader.BinaryRead(),

                PageSize = reader.ReadInt32(),
                _tables  = new Dictionary <string, DbTable>()
                           //Tables = new List<DbTable>()
            };

            //tables
            var pageCount = reader.ReadInt32();

            for (var t = 0; t < pageCount; t++)
            {
                var table = new DbTable()
                {
                    Name          = reader.BinaryRead(),
                    FileName      = reader.BinaryRead(),
                    Generate      = reader.ReadBoolean(),
                    Multikey      = reader.ReadBoolean(),
                    Rows          = reader.ReadInt32(),
                    RowMask       = reader.ReadUInt64(),
                    RowMaskLength = reader.ReadInt32(),
                    Pager         = DbTablePager.Load(reader),
                    Count         = reader.ReadInt32(),
                    _columns      = new Dictionary <string, DbColumn>()
                };
                //read columns
                var columnNameList = new List <string>();

                for (var c = 0; c < table.Count; c++)
                {
                    var col = new DbColumn()
                    {
                        Indexer = reader.BinaryRead(),
                        Unique  = reader.ReadBoolean(),
                        Name    = reader.BinaryRead(),
                        Index   = reader.ReadInt32(),
                        Type    = reader.BinaryRead(),
                        Key     = reader.ReadBoolean(),
                        Indexed = reader.ReadBoolean(),
                        //
                        NodePages = reader.ReadInt32(),
                        ItemPages = reader.ReadInt32()
                    };
                    if (!table.Add(col))
                    {
                        throw new ArgumentException($"duplicated column: {col.Name} on table {table.Name}");
                    }
                    columnNameList.Add(col.Name);
                }

                //check count
                if (table.Count != table.Columns.Count())
                {
                    throw new ArgumentException($"invalid table count on: {table.Name}");
                }
                table._columnNameList = columnNameList.ToArray();

                //get key
                table.Keys = table.Columns.Where(c => c.Key).ToArray();

                var keyCount = table.Keys.Length;
                if (table.Multikey)
                {
                    //must have more than one key
                    table.Key = null;
                    if (keyCount < 2)
                    {
                        throw new ArgumentException($"table: {table} is multi-key and has less than 2 keys");
                    }
                }
                else
                {
                    //must have just one key
                    if (keyCount != 1)
                    {
                        throw new ArgumentException($"table: {table} must have one key");
                    }
                    table.Key = table.Keys[0];
                }
                //schema.Tables.Add(table);
                schema._tables.Add(table.Name, table);
            }
            return(schema);
        }
Ejemplo n.º 53
0
            public IEnumerable <ISOSpatialRow> Read(string fileName, ISOTime templateTime)
            {
                if (templateTime == null)
                {
                    yield break;
                }

                if (!File.Exists(fileName))
                {
                    yield break;
                }

                using (var binaryReader = new System.IO.BinaryReader(File.Open(fileName, FileMode.Open)))
                {
                    while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length)
                    {
                        ISOPosition templatePosition = templateTime.Positions.FirstOrDefault();

                        var record = new ISOSpatialRow {
                            TimeStart = GetStartTime(templateTime, binaryReader)
                        };

                        if (templatePosition != null)
                        {
                            //North and East are required binary data
                            record.NorthPosition = ReadInt32((double?)templatePosition.PositionNorth, templatePosition.HasPositionNorth, binaryReader).GetValueOrDefault(0);
                            record.EastPosition  = ReadInt32((double?)templatePosition.PositionEast, templatePosition.HasPositionEast, binaryReader).GetValueOrDefault(0);

                            if (templatePosition.HasPositionUp) //Optional position attributes will be included in the binary only if a corresponding attribute is present in the PTN element
                            {
                                record.Elevation = ReadInt32(templatePosition.PositionUp, templatePosition.HasPositionUp, binaryReader);
                            }

                            //Position status is required
                            record.PositionStatus = ReadByte((byte?)templatePosition.PositionStatus, templatePosition.HasPositionStatus, binaryReader);

                            if (templatePosition.HasPDOP)
                            {
                                record.PDOP = ReadUShort((double?)templatePosition.PDOP, templatePosition.HasPDOP, binaryReader);
                            }

                            if (templatePosition.HasHDOP)
                            {
                                record.HDOP = ReadUShort((double?)templatePosition.HDOP, templatePosition.HasHDOP, binaryReader);
                            }

                            if (templatePosition.HasNumberOfSatellites)
                            {
                                record.NumberOfSatellites = ReadByte(templatePosition.NumberOfSatellites, templatePosition.HasNumberOfSatellites, binaryReader);
                            }

                            if (templatePosition.HasGpsUtcTime)
                            {
                                if (templatePosition.GpsUtcTime.HasValue)
                                {
                                    record.GpsUtcTime = Convert.ToUInt32(templatePosition.GpsUtcTime.Value);
                                }
                                else
                                {
                                    record.GpsUtcTime = binaryReader.ReadUInt32();
                                }
                            }

                            if (templatePosition.HasGpsUtcDate)
                            {
                                if (templatePosition.GpsUtcDate.HasValue)
                                {
                                    record.GpsUtcDate = (ushort)templatePosition.GpsUtcDate.Value;
                                }
                                else
                                {
                                    record.GpsUtcDate = binaryReader.ReadUInt16();
                                }
                            }

                            if (record.GpsUtcDate != null && record.GpsUtcTime != null)
                            {
                                record.GpsUtcDateTime = _firstDayOf1980.AddDays((double)record.GpsUtcDate).AddMilliseconds((double)record.GpsUtcTime);
                            }
                        }

                        var numberOfDLVs = binaryReader.ReadByte();
                        record.SpatialValues = new List <SpatialValue>();

                        //Read DLVs out of the TLG.bin
                        for (int i = 0; i < numberOfDLVs; i++)
                        {
                            var order = binaryReader.ReadByte();
                            var value = binaryReader.ReadInt32();

                            record.SpatialValues.Add(CreateSpatialValue(templateTime, order, value));
                        }

                        //Add any fixed values from the TLG.xml
                        foreach (ISODataLogValue fixedValue in templateTime.DataLogValues.Where(dlv => dlv.ProcessDataValue.HasValue && !EnumeratedMeterFactory.IsCondensedMeter(dlv.ProcessDataDDI.AsInt32DDI())))
                        {
                            byte order = (byte)templateTime.DataLogValues.IndexOf(fixedValue);
                            if (record.SpatialValues.Any(s => s.Id == order)) //Check to ensure the binary data didn't already write this value
                            {
                                //Per the spec, any fixed value in the XML applies to all rows; as such, replace what was read from the binary
                                SpatialValue matchingValue = record.SpatialValues.Single(s => s.Id == order);
                                matchingValue.DataLogValue = fixedValue;
                            }
                        }

                        yield return(record);
                    }
                }
            }
Ejemplo n.º 54
0
        internal byte[] DecryptInternal(string password, byte[] encryptionInfo, byte[] encryptedPackage)
        {
            #region Parse the encryption info data

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(encryptionInfo))
            {
                System.IO.BinaryReader reader = new System.IO.BinaryReader(ms);

                versionMajor = reader.ReadUInt16();
                versionMinor = reader.ReadUInt16();

                encryptionFlags = (EncryptionFlags)reader.ReadUInt32();
                if (encryptionFlags == EncryptionFlags.fExternal)
                {
                    throw new Exception("An external cryptographic provider is not supported");
                }

                // Encryption header
                uint headerLength = reader.ReadUInt32();
                int  skipFlags    = reader.ReadInt32(); headerLength -= 4;
                sizeExtra    = reader.ReadUInt32(); headerLength -= 4;
                algId        = (AlgId)reader.ReadUInt32(); headerLength -= 4;
                algHashId    = (AlgHashId)reader.ReadUInt32(); headerLength -= 4;
                keySize      = reader.ReadInt32(); headerLength -= 4;
                providerType = (ProviderType)reader.ReadUInt32(); headerLength -= 4;
                reader.ReadUInt32(); headerLength -= 4;                                                                   // Reserved 1
                reader.ReadUInt32(); headerLength -= 4;                                                                   // Reserved 2
                CSPName = System.Text.UnicodeEncoding.Unicode.GetString(reader.ReadBytes((int)headerLength));

                // Encryption verifier
                saltSize              = reader.ReadInt32();
                salt                  = reader.ReadBytes(saltSize);
                encryptedVerifier     = reader.ReadBytes(0x10);
                verifierHashSize      = reader.ReadInt32();
                encryptedVerifierHash = reader.ReadBytes(providerType == ProviderType.RC4 ? 0x14 : 0x20);
            }

            #endregion

            #region Encryption key generation

            Console.WriteLine("Encryption key generation");
            byte[] encryptionKey = GeneratePasswordHashUsingSHA1(password);
            if (encryptionKey == null)
            {
                return(null);
            }

            #endregion

            #region Password verification

            Console.WriteLine("Password verification");
            if (PasswordVerifier(encryptionKey))
            {
                Console.WriteLine("Password verification succeeded");
            }
            else
            {
                Console.WriteLine("Password verification failed");
                throw new InvalidPasswordException("The password is not valid");
            }

            #endregion

            #region Decrypt

            // First 8 bytes hold the size of the stream
            long length = BitConverter.ToInt64(encryptedPackage, 0);

            // Decrypt the stream using the generated and validated key
            Console.WriteLine("Decrypt the stream using the generated and validated key");
            encryptedPackage = AESDecrypt(encryptedPackage, 8, encryptedPackage.Length - 8, encryptionKey);

            // !! IMPORTANT !! Make sure the final array is the correct size
            // Failure to do this will cause an error when the decrypted stream
            // is opened by the System.IO.Packaging.Package.Open() method.

            byte[] result = encryptedPackage;

            if (encryptedPackage.Length > length)
            {
                result = new byte[length];
                Array.Copy(encryptedPackage, result, result.Length);
            }

            //using (System.IO.FileStream fs = new System.IO.FileStream(@"c:\x.zip", System.IO.FileMode.Create))
            //{
            //    fs.Write(result, 0, result.Length);
            //}

            return(result);

            #endregion
        }
Ejemplo n.º 55
0
 private void Form4_2_Load(object sender, EventArgs e)
 {
     #region Map Names
     string path;
     int    mainKey = 31881;
     if (Form1.IsBW)
     {
         path = "0089";
     }
     else if (Form1.IsBW2)
     {
         path = "0109";
     }
     else
     {
         loadGenIV();
         return;
     }
     System.IO.BinaryReader readText = new System.IO.BinaryReader(File.OpenRead(Form1.workingFolder + @"data\a\0\0\texts\" + path));
     int    nameSections             = readText.ReadUInt16();
     uint[] sectionOffset            = new uint[3];
     uint[] sectionSize = new uint[3];
     int    nameCount   = readText.ReadUInt16();
     int    stringOffset;
     int    stringSize;
     int[]  stringUnknown = new int[3];
     sectionSize[0] = readText.ReadUInt32();
     readText.ReadUInt32();
     int key;
     for (int i = 0; i < nameSections; i++)
     {
         sectionOffset[i] = readText.ReadUInt32();
     }
     for (int j = 0; j < nameCount; j++)
     {
         #region Layer 1
         readText.BaseStream.Position = sectionOffset[0];
         sectionSize[0] = readText.ReadUInt32();
         readText.BaseStream.Position += j * 8;
         stringOffset                 = (int)readText.ReadUInt32();
         stringSize                   = readText.ReadUInt16();
         stringUnknown[0]             = readText.ReadUInt16();
         readText.BaseStream.Position = sectionOffset[0] + stringOffset;
         UInt16[] encodedString = new UInt16[stringSize];
         UInt16[] decodedString = new UInt16[stringSize];
         string   pokemonText   = "";
         key = mainKey;
         for (int k = 0; k < stringSize; k++)
         {
             int car = Convert.ToUInt16(readText.ReadUInt16() ^ key);
             if (car == 0xFFFF)
             {
             }
             else if (car == 0xF100)
             {
                 pokemonText += @"\xF100";
             }
             else if (car == 0xFFFE)
             {
                 pokemonText += @"\n";
             }
             else if (car > 20 && car <= 0xFFF0 && car != 0xF000 && Char.GetUnicodeCategory(Convert.ToChar(car)) != UnicodeCategory.OtherNotAssigned)
             {
                 pokemonText += Convert.ToChar(car);
             }
             else
             {
                 pokemonText += @"\x" + car.ToString("X4");
             }
             key = ((key << 3) | (key >> 13)) & 0xFFFF;
         }
         #endregion
         comboBox1.Items.Add(pokemonText);
         mainKey += 0x2983;
         if (mainKey > 0xFFFF)
         {
             mainKey -= 0x10000;
         }
     }
     readText.Close();
     #endregion
     comboBox1.SelectedIndex = Form1.wildIndex;
 }
Ejemplo n.º 56
0
            public override uint ReadScalarValue(System.IO.BinaryReader br)
            {
                var r = br.ReadUInt32();

                return(r);
            }
Ejemplo n.º 57
0
        private static void loadWindowsBitmap(System.IO.BinaryReader reader, bool convertFromIndexed, out byte[] pixels, out int width, out int height, out bool is8bit)
        {
            const string errorMessage = "This is not a valid Windows bitmap";

            is8bit = false;

            uint startingPosition = (uint)reader.BaseStream.Position;

            ushort header = reader.ReadUInt16();

            if (header != 19778)
            {
                throw new Resource.InvalidResourceFileFormat(errorMessage);
            }

            uint size = reader.ReadUInt32();

            reader.ReadUInt16();
            reader.ReadUInt16();
            uint pixelOffset = reader.ReadUInt32();

            // info header
            reader.ReadUInt32();
            width  = reader.ReadInt32();
            height = reader.ReadInt32();
            reader.ReadUInt16();
            ushort bitsPerPixel = reader.ReadUInt16();

            if (bitsPerPixel != 24 && bitsPerPixel != 8)
            {
                throw new Resource.InvalidResourceFileFormat("Only 24-bit or 8-bit grayscale bitmaps supported");
            }

            Color[] palette = null;
            if (bitsPerPixel == 8)
            {
                // we need to read palette info
                reader.BaseStream.Seek(4 * 4, SeekOrigin.Current);
                int paletteSize = reader.ReadInt32();
                if (paletteSize == 0)
                {
                    paletteSize = 256;
                }

                reader.BaseStream.Seek(4, SeekOrigin.Current);

                // now read the palette
                palette = new Color[paletteSize];
                for (int i = 0; i < paletteSize; i++)
                {
                    palette[i].R = reader.ReadByte();
                    palette[i].G = reader.ReadByte();
                    palette[i].B = reader.ReadByte();
                    palette[i].A = 255;

                    reader.ReadByte();
                }

                if (convertFromIndexed == false)
                {
                    is8bit = true;
                }
            }

            // pixels
            reader.BaseStream.Seek(startingPosition + pixelOffset, System.IO.SeekOrigin.Begin);
            pixels = new byte[width * height * 4];

            int padding = (4 - width * bitsPerPixel / 8 % 4) % 4;

            for (int y = height - 1; y >= 0; y--)
            //for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    int currentPixel = (y * width + x) * 4;

                    if (bitsPerPixel == 24)
                    {
                        byte r, g, b;
                        b = reader.ReadByte();
                        g = reader.ReadByte();
                        r = reader.ReadByte();

                        pixels[currentPixel + 0] = r;
                        pixels[currentPixel + 1] = g;
                        pixels[currentPixel + 2] = b;
                        pixels[currentPixel + 3] = 255;
                    }
                    else if (bitsPerPixel == 8)
                    {
                        byte pixel = reader.ReadByte();

                        pixels[currentPixel + 3] = 255;
                        if (convertFromIndexed)
                        {
                            pixels[currentPixel + 2] = palette[pixel].B;
                            pixels[currentPixel + 1] = palette[pixel].G;
                            pixels[currentPixel + 0] = palette[pixel].R;
                        }
                        else
                        {
                            pixels[currentPixel + 2] = pixel;
                            pixels[currentPixel + 1] = pixel;
                            pixels[currentPixel + 0] = pixel;
                        }
                    }
                    else
                    {
                        // are there even any grayscale bitmaps?
                        byte pixel = reader.ReadByte();

                        pixels[currentPixel + 3] = 255;
                        pixels[currentPixel + 2] = pixel;
                        pixels[currentPixel + 1] = pixel;
                        pixels[currentPixel + 0] = pixel;
                    }
                }

                // skip any extra bytes
                reader.ReadBytes(padding);
            }
        }
Ejemplo n.º 58
0
        /// <summary>
        /// Read a SWAR file and return a SWAR structure
        /// </summary>
        /// <param name="path">File to read</param>
        /// <returns>Structure of the file</returns>
        public static sSWAR Read(string path)
        {
            System.IO.FileStream   fs = null;
            System.IO.BinaryReader br = null;

            sSWAR swar = new sSWAR();

            try
            {
                fs = new System.IO.FileStream(path, System.IO.FileMode.Open);
                br = new System.IO.BinaryReader(fs);

                // Common header
                swar.header.type      = Encoding.ASCII.GetChars(br.ReadBytes(4));
                swar.header.magic     = br.ReadUInt32();
                swar.header.nFileSize = br.ReadUInt32();
                swar.header.nSize     = br.ReadUInt16();
                swar.header.nBlock    = br.ReadUInt16();

                // DATA section
                swar.data.type     = Encoding.ASCII.GetChars(br.ReadBytes(4));
                swar.data.nSize    = br.ReadUInt32();
                swar.data.reserved = new uint[8];
                for (int i = 0; i < 8; i++)
                {
                    swar.data.reserved[i] = br.ReadUInt32();
                }
                swar.data.nSample = br.ReadUInt32();

                swar.data.nOffset = new uint[swar.data.nSample];
                for (int i = 0; i < swar.data.nSample; i++)
                {
                    swar.data.nOffset[i] = br.ReadUInt32();
                }

                swar.data.samples = new sSWAR.Data.Sample[swar.data.nSample];

                for (uint i = 0; i < swar.data.nSample; i++)
                {
                    // INFO structure
                    swar.data.samples[i].info.nWaveType   = br.ReadByte();
                    swar.data.samples[i].info.bLoop       = br.ReadByte();
                    swar.data.samples[i].info.nSampleRate = br.ReadUInt16();
                    swar.data.samples[i].info.nTime       = br.ReadUInt16();
                    swar.data.samples[i].info.nLoopOffset = br.ReadUInt16();
                    swar.data.samples[i].info.nNonLoopLen = br.ReadUInt32();

                    // Calculation of data size
                    if (i < swar.data.nOffset.Length - 1)
                    {
                        swar.data.samples[i].data = new byte[swar.data.nOffset[i + 1] - swar.data.nOffset[i] - /*SWAVInfo size ->*/ 12];
                    }
                    else
                    {
                        swar.data.samples[i].data = new byte[br.BaseStream.Length - swar.data.nOffset[i] - /*SWAVInfo size ->*/ 12];
                    }

                    // Read DATA
                    for (uint j = 0; j < swar.data.samples[i].data.Length; j++)
                    {
                        swar.data.samples[i].data[j] = br.ReadByte();
                    }
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message.ToString());
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
                if (br != null)
                {
                    br.Close();
                }
            }

            return(swar);
        }
Ejemplo n.º 59
0
            public IEnumerable <ISOSpatialRow> Read(string fileName, ISOTime templateTime)
            {
                if (templateTime == null)
                {
                    yield break;
                }

                if (!File.Exists(fileName))
                {
                    yield break;
                }

                using (var binaryReader = new System.IO.BinaryReader(File.Open(fileName, FileMode.Open)))
                {
                    while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length)
                    {
                        ISOPosition templatePosition = templateTime.Positions.FirstOrDefault();

                        var record = new ISOSpatialRow {
                            TimeStart = GetStartTime(templateTime, binaryReader)
                        };

                        if (templatePosition != null)
                        {
                            //North and East are required binary data
                            record.NorthPosition = ReadInt32((double?)templatePosition.PositionNorth, templatePosition.HasPositionNorth, binaryReader).GetValueOrDefault(0);
                            record.EastPosition  = ReadInt32((double?)templatePosition.PositionEast, templatePosition.HasPositionEast, binaryReader).GetValueOrDefault(0);

                            if (templatePosition.HasPositionUp) //Optional position attributes will be included in the binary only if a corresponding attribute is present in the PTN element
                            {
                                record.Elevation = ReadInt32(templatePosition.PositionUp, templatePosition.HasPositionUp, binaryReader);
                            }

                            //Position status is required
                            record.PositionStatus = ReadByte((byte?)templatePosition.PositionStatus, templatePosition.HasPositionStatus, binaryReader);

                            if (templatePosition.HasPDOP)
                            {
                                record.PDOP = ReadUShort((double?)templatePosition.PDOP, templatePosition.HasPDOP, binaryReader);
                            }

                            if (templatePosition.HasHDOP)
                            {
                                record.HDOP = ReadUShort((double?)templatePosition.HDOP, templatePosition.HasHDOP, binaryReader);
                            }

                            if (templatePosition.HasNumberOfSatellites)
                            {
                                record.NumberOfSatellites = ReadByte(templatePosition.NumberOfSatellites, templatePosition.HasNumberOfSatellites, binaryReader);
                            }

                            if (templatePosition.HasGpsUtcTime)
                            {
                                if (templatePosition.GpsUtcTime.HasValue)
                                {
                                    record.GpsUtcTime = Convert.ToUInt32(templatePosition.GpsUtcTime.Value);
                                }
                                else
                                {
                                    record.GpsUtcTime = binaryReader.ReadUInt32();
                                }
                            }

                            if (templatePosition.HasGpsUtcDate)
                            {
                                if (templatePosition.GpsUtcDate.HasValue)
                                {
                                    record.GpsUtcDate = (ushort)templatePosition.GpsUtcDate.Value;
                                }
                                else
                                {
                                    record.GpsUtcDate = binaryReader.ReadUInt16();
                                }
                            }

                            if (record.GpsUtcDate != null && record.GpsUtcTime != null)
                            {
                                record.GpsUtcDateTime = _firstDayOf1980.AddDays((double)record.GpsUtcDate).AddMilliseconds((double)record.GpsUtcTime);
                            }
                        }

                        var numberOfDLVs = binaryReader.ReadByte();
                        record.SpatialValues = new List <SpatialValue>();

                        for (int i = 0; i < numberOfDLVs; i++)
                        {
                            var order = binaryReader.ReadByte();
                            var value = binaryReader.ReadInt32();

                            record.SpatialValues.Add(CreateSpatialValue(templateTime, order, value));
                        }

                        yield return(record);
                    }
                }
            }
        public static void DDSToTexture(GameDatabase.TextureInfo texture, bool inPlace, Vector2 size, string cache = null, bool mipmaps = false)
        {
            /**
             * Kopernicus Planetary System Modifier
             * ====================================
             * Created by: BryceSchroeder and Teknoman117 (aka. Nathaniel R. Lewis)
             * Maintained by: Thomas P., NathanKell and KillAshley
             * Additional Content by: Gravitasi, aftokino, KCreator, Padishar, Kragrathea, OvenProofMars, zengei, MrHappyFace
             * -------------------------------------------------------------
             * This library is free software; you can redistribute it and/or
             * modify it under the terms of the GNU Lesser General Public
             * License as published by the Free Software Foundation; either
             * version 3 of the License, or (at your option) any later version.
             *
             * This library is distributed in the hope that it will be useful,
             * but WITHOUT ANY WARRANTY; without even the implied warranty of
             * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
             * Lesser General Public License for more details.
             *
             * You should have received a copy of the GNU Lesser General Public
             * License along with this library; if not, write to the Free Software
             * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
             * MA 02110-1301  USA
             *
             * This library is intended to be used as a plugin for Kerbal Space Program
             * which is copyright 2011-2015 Squad. Your usage of Kerbal Space Program
             * itself is governed by the terms of its EULA, not the license above.
             *
             * https://kerbalspaceprogram.com
             */
            // Borrowed from stock KSP 1.0 DDS loader (hi Mike!)
            // Also borrowed the extra bits from Sarbian.
            byte[] buffer = System.IO.File.ReadAllBytes(texture.file.fullPath);
            System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(new System.IO.MemoryStream(buffer));
            uint num = binaryReader.ReadUInt32();

            if (num == DDSHeaders.DDSValues.uintMagic)
            {
                DDSHeaders.DDSHeader dDSHeader = new DDSHeaders.DDSHeader(binaryReader);

                if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDX10)
                {
                    new DDSHeaders.DDSHeaderDX10(binaryReader);
                }
                bool alpha      = (dDSHeader.dwFlags & 0x00000002) != 0;
                bool fourcc     = (dDSHeader.dwFlags & 0x00000004) != 0;
                bool rgb        = (dDSHeader.dwFlags & 0x00000040) != 0;
                bool alphapixel = (dDSHeader.dwFlags & 0x00000001) != 0;
                bool luminance  = (dDSHeader.dwFlags & 0x00020000) != 0;
                bool rgb888     = dDSHeader.ddspf.dwRBitMask == 0x000000ff && dDSHeader.ddspf.dwGBitMask == 0x0000ff00 && dDSHeader.ddspf.dwBBitMask == 0x00ff0000;
                //bool bgr888 = dDSHeader.ddspf.dwRBitMask == 0x00ff0000 && dDSHeader.ddspf.dwGBitMask == 0x0000ff00 && dDSHeader.ddspf.dwBBitMask == 0x000000ff;
                bool rgb565   = dDSHeader.ddspf.dwRBitMask == 0x0000F800 && dDSHeader.ddspf.dwGBitMask == 0x000007E0 && dDSHeader.ddspf.dwBBitMask == 0x0000001F;
                bool argb4444 = dDSHeader.ddspf.dwABitMask == 0x0000f000 && dDSHeader.ddspf.dwRBitMask == 0x00000f00 && dDSHeader.ddspf.dwGBitMask == 0x000000f0 && dDSHeader.ddspf.dwBBitMask == 0x0000000f;
                bool rbga4444 = dDSHeader.ddspf.dwABitMask == 0x0000000f && dDSHeader.ddspf.dwRBitMask == 0x0000f000 && dDSHeader.ddspf.dwGBitMask == 0x000000f0 && dDSHeader.ddspf.dwBBitMask == 0x00000f00;

                bool mipmap      = (dDSHeader.dwCaps & DDSHeaders.DDSPixelFormatCaps.MIPMAP) != (DDSHeaders.DDSPixelFormatCaps) 0u;
                bool isNormalMap = ((dDSHeader.ddspf.dwFlags & 524288u) != 0u || (dDSHeader.ddspf.dwFlags & 2147483648u) != 0u);

                Vector2 newSize = size == default(Vector2) ? new Vector2(dDSHeader.dwWidth, dDSHeader.dwHeight) : size;
                if (fourcc)
                {
                    if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT1)
                    {
                        if (inPlace && !texture.isReadable)
                        {
                            //This is a small hack to re-load the texture, even when it isn't readable. Unfortnately,
                            //we can't control compression, mipmaps, or anything else really, as the texture is still
                            //marked as unreadable. This will update the size and pixel data however.
                            Texture2D tmpTex    = new Texture2D((int)newSize.x, (int)newSize.y, TextureFormat.ARGB32, mipmap);
                            Texture2D tmpTexSrc = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT1, mipmap);
                            tmpTexSrc.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            Color32[] colors = tmpTexSrc.GetPixels32();
                            colors = ResizePixels(colors, tmpTexSrc.width, tmpTexSrc.height, (int)newSize.x, (int)newSize.y);
                            tmpTex.SetPixels32(colors);
                            tmpTex.Apply(false);
                            //size using JPG to force DXT1

                            byte[] file = ImageConversion.EncodeToPNG(tmpTex);//tmpTex.EncodeToJPG();
                            if (cache != null)
                            {
                                Directory.GetParent(cache).Create();
                                System.IO.File.WriteAllBytes(cache, file);
                            }
                            texture.texture.LoadImage(file);

                            GameObject.DestroyImmediate(tmpTex);
                            GameDatabase.DestroyImmediate(tmpTexSrc);
                        }
                        else if (inPlace)
                        {
                            texture.texture.Resize((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.RGB24, mipmap);
                            texture.texture.Compress(false);
                            texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            texture.texture.Apply(false, !texture.isReadable);
                        }
                        else
                        {
                            GameObject.DestroyImmediate(texture.texture);
                            texture.texture = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT1, mipmap);
                            texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            texture.texture.Apply(false, !texture.isReadable);
                        }
                    }
                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT3)
                    {
                        if (inPlace && !texture.isReadable)
                        {
                            //This is a small hack to re-load the texture, even when it isn't readable. Unfortnately,
                            //we can't control compression, mipmaps, or anything else really, as the texture is still
                            //marked as unreadable. This will update the size and pixel data however.
                            Texture2D tmpTex    = new Texture2D((int)newSize.x, (int)newSize.y, TextureFormat.ARGB32, mipmap);
                            Texture2D tmpTexSrc = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, (TextureFormat)11, mipmap);
                            tmpTexSrc.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            Color32[] colors = tmpTexSrc.GetPixels32();
                            colors = ResizePixels(colors, tmpTexSrc.width, tmpTexSrc.height, (int)newSize.x, (int)newSize.y);
                            tmpTex.SetPixels32(colors);
                            tmpTex.Apply(false);
                            //size using JPG to force DXT5
                            byte[] file = ImageConversion.EncodeToPNG(tmpTex);
                            if (cache != null)
                            {
                                Directory.GetParent(cache).Create();
                                System.IO.File.WriteAllBytes(cache, file);
                            }
                            texture.texture.LoadImage(file);

                            GameObject.DestroyImmediate(tmpTex);
                            GameDatabase.DestroyImmediate(tmpTexSrc);
                        }
                        else if (inPlace)
                        {
                            texture.texture.Resize((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, (TextureFormat)11, mipmap);
                            texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            texture.texture.Apply(false, !texture.isReadable);
                        }
                        else
                        {
                            GameObject.DestroyImmediate(texture.texture);
                            texture.texture = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, (TextureFormat)11, mipmap);
                            texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            texture.texture.Apply(false, !texture.isReadable);
                        }
                    }
                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT5)
                    {
                        if (inPlace && !texture.isReadable)
                        {
                            //This is a small hack to re-load the texture, even when it isn't readable. Unfortnately,
                            //we can't control compression, mipmaps, or anything else really, as the texture is still
                            //marked as unreadable. This will update the size and pixel data however.
                            Texture2D tmpTex    = new Texture2D((int)newSize.x, (int)newSize.y, TextureFormat.ARGB32, mipmap);
                            Texture2D tmpTexSrc = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT5, mipmap);
                            tmpTexSrc.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            Color32[] colors = tmpTexSrc.GetPixels32();
                            colors = ResizePixels(colors, tmpTexSrc.width, tmpTexSrc.height, (int)newSize.x, (int)newSize.y);
                            tmpTex.SetPixels32(colors);
                            tmpTex.Apply(false);
                            //size using JPG to force DXT5
                            byte[] file = ImageConversion.EncodeToPNG(tmpTex);
                            if (cache != null)
                            {
                                Directory.GetParent(cache).Create();
                                System.IO.File.WriteAllBytes(cache, file);
                            }
                            texture.texture.LoadImage(file);
                            GameObject.DestroyImmediate(tmpTex);
                            GameDatabase.DestroyImmediate(tmpTexSrc);
                        }
                        else if (inPlace)
                        {
                            texture.texture.Resize((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.ARGB32, mipmap);
                            texture.texture.Compress(false);

                            texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            texture.texture.Apply(false, !texture.isReadable);
                        }
                        else
                        {
                            GameObject.DestroyImmediate(texture.texture);
                            texture.texture = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT5, mipmap);
                            texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            texture.texture.Apply(false, !texture.isReadable);
                        }
                    }
                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT2)
                    {
                        Debug.Log("DXT2 not supported");
                    }
                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT4)
                    {
                        Debug.Log("DXT4 not supported: ");
                    }
                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDX10)
                    {
                        Debug.Log("DX10 dds not supported: ");
                    }
                    else
                    {
                        fourcc = false;
                    }
                }
                if (!fourcc)
                {
                    TextureFormat textureFormat = TextureFormat.ARGB32;
                    bool          ok            = true;
                    if (rgb && (rgb888 /*|| bgr888*/))
                    {
                        // RGB or RGBA format
                        textureFormat = alphapixel
                        ? TextureFormat.RGBA32
                        : TextureFormat.RGB24;
                    }
                    else if (rgb && rgb565)
                    {
                        // Nvidia texconv B5G6R5_UNORM
                        textureFormat = TextureFormat.RGB565;
                    }
                    else if (rgb && alphapixel && argb4444)
                    {
                        // Nvidia texconv B4G4R4A4_UNORM
                        textureFormat = TextureFormat.ARGB4444;
                    }
                    else if (rgb && alphapixel && rbga4444)
                    {
                        textureFormat = TextureFormat.RGBA4444;
                    }
                    else if (!rgb && alpha != luminance)
                    {
                        // A8 format or Luminance 8
                        textureFormat = TextureFormat.Alpha8;
                    }
                    else
                    {
                        ok = false;
                        Debug.Log("Only DXT1, DXT5, A8, RGB24, RGBA32, RGB565, ARGB4444 and RGBA4444 are supported");
                    }
                    if (ok)
                    {
                        if (inPlace && !texture.isReadable)
                        {
                            //This is a small hack to re-load the texture, even when it isn't readable. Unfortnately,
                            //we can't control compression, mipmaps, or anything else really, as the texture is still
                            //marked as unreadable. This will update the size and pixel data however.
                            Texture2D tmpTex    = new Texture2D((int)newSize.x, (int)newSize.y, TextureFormat.ARGB32, mipmap);
                            Texture2D tmpTexSrc = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, textureFormat, mipmap);
                            tmpTexSrc.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            Color32[] colors = tmpTexSrc.GetPixels32();
                            colors = ResizePixels(colors, tmpTexSrc.width, tmpTexSrc.height, (int)newSize.x, (int)newSize.y);
                            tmpTex.SetPixels32(colors);
                            tmpTex.Apply(false);
                            //size using JPG to force alpha-less
                            byte[] file;
                            if (alphapixel)
                            {
                                file = ImageConversion.EncodeToPNG(tmpTex);
                            }
                            else
                            {
                                file = ImageConversion.EncodeToPNG(tmpTex);//file = tmpTex.EncodeToJPG();
                            }
                            if (cache != null)
                            {
                                Directory.GetParent(cache).Create();
                                System.IO.File.WriteAllBytes(cache, file);
                            }
                            texture.texture.LoadImage(file);
                            GameDatabase.DestroyImmediate(tmpTex);
                            GameDatabase.DestroyImmediate(tmpTexSrc);
                        }
                        else if (inPlace)
                        {
                            texture.texture.Resize((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, textureFormat, mipmap);
                            texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            texture.texture.Apply(false, !texture.isReadable);
                        }
                        else
                        {
                            GameDatabase.DestroyImmediate(texture.texture);
                            texture.texture = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, textureFormat, mipmap);
                            texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            texture.texture.Apply(false, !texture.isReadable);
                        }
                    }
                }
            }
            else
            {
                Debug.Log("Bad DDS header.");
            }
        }