Пример #1
0
        protected override void InternalDeserialize(ref System.IO.BinaryReader reader)
        {
            base.InternalDeserialize(ref reader);

            m_maxvalue = reader.ReadInt16();
            m_minvalue = reader.ReadInt16();
        }
Пример #2
0
 public MavLink4Net.Messages.IMessage Deserialize(System.IO.BinaryReader reader)
 {
     MavLink4Net.Messages.Common.HighLatency2Message message = new MavLink4Net.Messages.Common.HighLatency2Message();
     message.Timestamp      = reader.ReadUInt32();
     message.Latitude       = reader.ReadInt32();
     message.Longitude      = reader.ReadInt32();
     message.CustomMode     = reader.ReadUInt16();
     message.Altitude       = reader.ReadInt16();
     message.TargetAltitude = reader.ReadInt16();
     message.TargetDistance = reader.ReadUInt16();
     message.WpNum          = reader.ReadUInt16();
     message.FailureFlags   = ((MavLink4Net.Messages.Common.HlFailureFlag)(reader.ReadUInt16()));
     message.Type           = ((MavLink4Net.Messages.Common.Type)(reader.ReadByte()));
     message.Autopilot      = ((MavLink4Net.Messages.Common.Autopilot)(reader.ReadByte()));
     message.Heading        = reader.ReadByte();
     message.TargetHeading  = reader.ReadByte();
     message.Throttle       = reader.ReadByte();
     message.Airspeed       = reader.ReadByte();
     message.AirspeedSp     = reader.ReadByte();
     message.Groundspeed    = reader.ReadByte();
     message.Windspeed      = reader.ReadByte();
     message.WindHeading    = reader.ReadByte();
     message.Eph            = reader.ReadByte();
     message.Epv            = reader.ReadByte();
     message.TemperatureAir = reader.ReadSByte();
     message.ClimbRate      = reader.ReadSByte();
     message.Battery        = reader.ReadSByte();
     message.Custom0        = reader.ReadSByte();
     message.Custom1        = reader.ReadSByte();
     message.Custom2        = reader.ReadSByte();
     return(message);
 }
 public MavLink4Net.Messages.IMessage Deserialize(System.IO.BinaryReader reader)
 {
     MavLink4Net.Messages.Common.HighLatencyMessage message = new MavLink4Net.Messages.Common.HighLatencyMessage();
     message.CustomMode       = reader.ReadUInt32();
     message.Latitude         = reader.ReadInt32();
     message.Longitude        = reader.ReadInt32();
     message.Roll             = reader.ReadInt16();
     message.Pitch            = reader.ReadInt16();
     message.Heading          = reader.ReadUInt16();
     message.HeadingSp        = reader.ReadInt16();
     message.AltitudeAmsl     = reader.ReadInt16();
     message.AltitudeSp       = reader.ReadInt16();
     message.WpDistance       = reader.ReadUInt16();
     message.BaseMode         = ((MavLink4Net.Messages.Common.ModeFlag)(reader.ReadByte()));
     message.LandedState      = ((MavLink4Net.Messages.Common.LandedState)(reader.ReadByte()));
     message.Throttle         = reader.ReadSByte();
     message.Airspeed         = reader.ReadByte();
     message.AirspeedSp       = reader.ReadByte();
     message.Groundspeed      = reader.ReadByte();
     message.ClimbRate        = reader.ReadSByte();
     message.GpsNsat          = reader.ReadByte();
     message.GpsFixType       = ((MavLink4Net.Messages.Common.GpsFixType)(reader.ReadByte()));
     message.BatteryRemaining = reader.ReadByte();
     message.Temperature      = reader.ReadSByte();
     message.TemperatureAir   = reader.ReadSByte();
     message.Failsafe         = reader.ReadByte();
     message.WpNum            = reader.ReadByte();
     return(message);
 }
Пример #4
0
 internal AfmRectangle(System.IO.BinaryReader reader)
 {
     this.llX = reader.ReadInt16();
     this.llY = reader.ReadInt16();
     this.urX = reader.ReadInt16();
     this.urY = reader.ReadInt16();
 }
Пример #5
0
        /// <summary>
        /// Unserializes a BinaryStream into the Attributes of this Instance
        /// </summary>
        /// <param name="reader">The Stream that contains the FileData</param>
        public override void Unserialize(System.IO.BinaryReader reader)
        {
            version = reader.ReadUInt32();

            string name = reader.ReadString();
            uint   myid = reader.ReadUInt32();

            ogn.Unserialize(reader);
            ogn.BlockID = myid;

            name = reader.ReadString();
            myid = reader.ReadUInt32();
            sgres.Unserialize(reader);
            sgres.BlockID = myid;

            if (version == 0x0b)
            {
                unknown1 = reader.ReadInt16();
            }

            if ((version == 0x0b) || (version == 0x0c))
            {
                unknown2 = reader.ReadInt16();
                unknown3 = reader.ReadByte();
            }

            int count = reader.ReadInt32();

            data = new IRcolBlock[count];
            for (int i = 0; i < count; i++)
            {
                uint id = reader.ReadUInt32();
                data[i] = Parent.ReadBlock(id, reader);
            }
        }
        public Ole10Native(System.IO.Stream inputStream)
        {
            System.IO.BinaryReader reader = new System.IO.BinaryReader(inputStream);
            totalSize = reader.ReadInt32();
            if (totalSize < 4)
            {
                throw new Exception(
                          String.Format("Invalid total data size: {0}.", totalSize));
            }
            flags1   = reader.ReadInt16();
            label    = ReadString(reader);
            fileName = ReadString(reader);
            flags2   = reader.ReadInt16();
            byte unknown1Len = reader.ReadByte();

            unknown1       = reader.ReadBytes(unknown1Len);
            unknown2       = reader.ReadBytes(3);
            command        = ReadString(reader);
            nativeDataSize = reader.ReadInt32();
            if (nativeDataSize > totalSize || nativeDataSize < 0)
            {
                throw new Exception(
                          String.Format("Invalid native data size: {0}.", nativeDataSize));
            }
            nativeData = reader.ReadBytes(nativeDataSize);
            unknown3   = unknown1.Length > 0 ? reader.ReadInt16() : (short)0;
        }
Пример #7
0
        public void Parse(Header header, byte[] data)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
            {
                using (System.IO.BinaryReader br = new System.IO.BinaryReader(ms))
                {
                    _authCode      = br.ReadInt32();
                    _accountId     = br.ReadUInt32();
                    _userLevel     = br.ReadUInt32();
                    _lastLoginIP   = br.ReadUInt32();
                    _lastLoginTime = br.ReadBytes(26);
                    _sex           = br.ReadByte();

                    _serverList = new Dictionary <string, Server>();
                    for (int i = (int)ms.Position; i < header.Size; i += 32)
                    {
                        Server s = new Server();
                        s.IP        = string.Format("{0}.{1}.{2}.{3}", br.ReadByte(), br.ReadByte(), br.ReadByte(), br.ReadByte());
                        s.Port      = br.ReadInt16();
                        s.Name      = br.ReadBytes(22).NullByteTerminatedString();
                        s.Type      = br.ReadInt16();
                        s.UserCount = br.ReadInt16();
                        _serverList.Add(s.Name, s);
                    }
                }
            }
        }
Пример #8
0
 public PathgridData(System.IO.BinaryReader reader)
 {
     x           = reader.ReadInt32();
     y           = reader.ReadInt32();
     granularity = reader.ReadInt16();
     PointCount  = reader.ReadInt16();
 }
Пример #9
0
 public ClothingRecordData(System.IO.BinaryReader reader)
 {
     clothingPart  = (ClothingType)reader.ReadInt32();
     weight        = reader.ReadSingle();
     value         = reader.ReadInt16();
     enchantPoints = reader.ReadInt16();
 }
Пример #10
0
        public FileHeader(System.IO.BinaryReader br)
        {
            majorVersion  = 0;
            minorVersion  = 0;
            stringCount   = 0;
            infoCount     = 0;
            ruleCount     = 0;
            layoutOptions = new LayoutOptions();

            byte[] magicCode = br.ReadBytes(4);
            if (magicCode[0] != 'K' && magicCode[1] != 'M' && magicCode[2] != 'K' && magicCode[3] != 'L')
            {
                throw new Exception("Invalid KeyMagic keyboard layout file.");
            }

            majorVersion = br.ReadByte();
            minorVersion = br.ReadByte();

            if (majorVersion == 1 && minorVersion > 4)
            {
                throw new Exception("Cannot load this keyboard layout file because this is newer version of keyboard layout file.");
            }

            stringCount = br.ReadInt16();
            if (majorVersion == 1 && minorVersion > 3)
            {
                infoCount = br.ReadInt16();
            }
            ruleCount = br.ReadInt16();

            layoutOptions.trackCaps = br.ReadBoolean();
            layoutOptions.autoBksp  = br.ReadBoolean();
            layoutOptions.eat       = br.ReadBoolean();
            layoutOptions.posBased  = br.ReadBoolean();
        }
Пример #11
0
 protected override void InternalDeserialize(ref System.IO.BinaryReader reader)
 {
     base.InternalDeserialize(ref reader);
     this.m_mountId = (int)reader.ReadInt16();
     this.m_date    = (double)reader.ReadInt32();
     this.m_modelId = reader.ReadInt16();
 }
Пример #12
0
 protected override void InternalDeserialize(ref System.IO.BinaryReader reader)
 {
     base.InternalDeserialize(ref reader);
     this.m_days    = reader.ReadInt16();
     this.m_hours   = reader.ReadInt16();
     this.m_minutes = reader.ReadInt16();
 }
Пример #13
0
        virtual internal protected void Unpack(System.IO.BinaryReader reader)
        {
            BTreeSlotLength      = reader.ReadInt16();
            StoreSegmentSizeInKb = reader.ReadInt64();
            //writer.Write((int)this.DataBlockSize);
            IsDataInKeySegment   = reader.ReadBoolean();
            MaxStoreCount        = reader.ReadInt32();
            MemoryExtenderMode   = reader.ReadBoolean();
            MemoryLimitInPercent = reader.ReadInt16();
            var tst = reader.ReadByte();

            if (tst == 1)
            {
                TrackStoreTypes = true;
            }
            else if (tst == 2)
            {
                TrackStoreTypes = false;
            }
            else
            {
                TrackStoreTypes = null;
            }
            TrashBinType = (TrashBinType)reader.ReadByte();
        }
Пример #14
0
        static public int ReadCodedInt32(System.IO.BinaryReader inFile, string name)
        {
            int val1  = (int)inFile.ReadInt16();
            int val2  = (int)inFile.ReadInt16();
            int value = (val2 * 32768) + val1;

            TracerWriteLine(name + " = " + value);
            return(value);
        }
Пример #15
0
 public override void Deserialize(System.IO.BinaryReader reader)
 {
     base.Deserialize(reader);
     unitID   = reader.ReadInt32();
     unitType = reader.ReadInt16();
     unitKind = (BoardObjectClass)reader.ReadInt16();
     position = new Position();
     position.Deserialize(reader);
 }
Пример #16
0
 public MatchGroup(System.IO.BinaryReader reader)
 {
     vertexCount   = reader.ReadInt16();
     vertexIndices = new short[vertexCount];
     for (var i = 0; i < vertexIndices.Length; i++)
     {
         vertexIndices[i] = reader.ReadInt16();
     }
 }
Пример #17
0
 public MavLink4Net.Messages.IMessage Deserialize(System.IO.BinaryReader reader)
 {
     MavLink4Net.Messages.Common.MissionRequestPartialListMessage message = new MavLink4Net.Messages.Common.MissionRequestPartialListMessage();
     message.StartIndex      = reader.ReadInt16();
     message.EndIndex        = reader.ReadInt16();
     message.TargetSystem    = reader.ReadByte();
     message.TargetComponent = reader.ReadByte();
     return(message);
 }
Пример #18
0
 public void FromBinary(System.IO.BinaryReader reader)
 {
     timestamp_us = (ulong)IPAddress.NetworkToHostOrder(reader.ReadInt64());
     command      = (Commands)IPAddress.NetworkToHostOrder(reader.ReadInt16());
     param1       = IPAddress.NetworkToHostOrder(reader.ReadInt16());
     param2       = IPAddress.NetworkToHostOrder(reader.ReadInt16());
     param3       = IPAddress.NetworkToHostOrder(reader.ReadInt16());
     param4       = IPAddress.NetworkToHostOrder(reader.ReadInt16());
 }
Пример #19
0
        public List <Frame> Read(System.IO.BinaryReader r)
        {
            List <Frame> ret = new List <Frame>();

            this.identifier = System.Text.Encoding.ASCII.GetString(r.ReadBytes(3));
            if (this.identifier != "ID3")
            {
                return(ret);
            }

            this.majorVersion = r.ReadByte();
            this.minorVersion = r.ReadByte();

            this.flags = r.ReadByte();

            // They're doing some weird 7 bits per byte shenangianfoolery
            byte sz0 = r.ReadByte();
            byte sz1 = r.ReadByte();
            byte sz2 = r.ReadByte();
            byte sz3 = r.ReadByte();

            this.size = (sz0 << 21) | (sz1 << 14) | (sz2 << 7) | (sz3 << 0);


            long startPos = r.BaseStream.Position;
            long endPos   = r.BaseStream.Position + this.size;

            if ((this.flags & (byte)Flags.Experimental) != 0)
            {
                const ushort CRCDataPresentFlag = 0x8000;

                uint  extSz    = r.ReadUInt32();
                short extFlags = r.ReadInt16();
                uint  padding  = r.ReadUInt32();

                if ((extFlags & CRCDataPresentFlag) != 0)
                {
                    // Consume the CRC
                    uint crc = r.ReadUInt32();
                }
            }

            while (r.BaseStream.Position < endPos)
            {
                Frame frame = new Frame();
                frame.id    = r.ReadInt32();
                frame.size  = ReversedEndianInt32(r);
                frame.flags = r.ReadInt16();
                frame.pos   = r.BaseStream.Position;

                ret.Add(frame);
                r.BaseStream.Seek(frame.pos + frame.size, System.IO.SeekOrigin.Begin);
            }

            return(ret);
        }
Пример #20
0
	public void FromBinary(System.IO.BinaryReader reader)
	{
		timestamp_us = (ulong)IPAddress.NetworkToHostOrder(reader.ReadInt64());
		laser_speed = (ushort)IPAddress.NetworkToHostOrder(reader.ReadInt16());
		laser_angle = (ushort)IPAddress.NetworkToHostOrder(reader.ReadInt16());


		for (int i = 0; i < laser_readings.Length; ++i)
			laser_readings[i].FromBinary(reader);	
	}
Пример #21
0
        protected override void InternalDeserialize(ref System.IO.BinaryReader reader)
        {
            base.InternalDeserialize(ref reader);

            m_year   = reader.ReadInt16();
            m_month  = reader.ReadInt16();
            m_day    = reader.ReadInt16();
            m_hour   = reader.ReadInt16();
            m_minute = reader.ReadInt16();
        }
Пример #22
0
 public MavLink4Net.Messages.IMessage Deserialize(System.IO.BinaryReader reader)
 {
     MavLink4Net.Messages.Common.RawPressureMessage message = new MavLink4Net.Messages.Common.RawPressureMessage();
     message.TimeUsec    = reader.ReadUInt64();
     message.PressAbs    = reader.ReadInt16();
     message.PressDiff1  = reader.ReadInt16();
     message.PressDiff2  = reader.ReadInt16();
     message.Temperature = reader.ReadInt16();
     return(message);
 }
Пример #23
0
 public ArmorRecordData(System.IO.BinaryReader reader)
 {
     armorPart     = (ArmorPart)reader.ReadInt32();
     weight        = reader.ReadSingle();
     value         = reader.ReadInt32();
     maxHealth     = reader.ReadInt32();
     enchantPoints = reader.ReadInt16();
     unknown       = reader.ReadInt16();
     armorRating   = reader.ReadInt32();
 }
Пример #24
0
        /// <summary>
        /// Unserializes a BinaryStream into the Attributes of this Instance
        /// </summary>
        /// <param name="reader">The Stream that contains the FileData</param>
        internal void UnserializeData(System.IO.BinaryReader reader)
        {
            datai[0] = reader.ReadUInt32();

            datas[0] = reader.ReadInt16();
            datas[1] = reader.ReadInt16();
            datas[2] = reader.ReadInt16();

            datai[1] = reader.ReadUInt32();
        }
Пример #25
0
        private void LoadFile(string filename)
        {
            int dataOffset = 0;

            if (System.IO.File.Exists(filename) == false)
            {
                return;
            }

            System.IO.BinaryReader fileA;

            try
            {
                System.IO.FileStream fsA = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);

                fileA = new System.IO.BinaryReader(fsA);
            }
            catch (System.ApplicationException)
            {
                return;
            }

            dataOffset = fileA.ReadInt16() + 2;

            List <DaxHeaderEntry> headers = new List <DaxHeaderEntry>();

            const int headerEntrySize = 9;

            for (int i = 0; i < ((dataOffset - 2) / headerEntrySize); i++)
            {
                DaxHeaderEntry dhe = new DaxHeaderEntry();
                dhe.id       = fileA.ReadByte();
                dhe.offset   = fileA.ReadInt32();
                dhe.rawSize  = fileA.ReadInt16();
                dhe.compSize = fileA.ReadUInt16();

                headers.Add(dhe);
            }

            foreach (DaxHeaderEntry dhe in headers)
            {
                byte[] comp = new byte[dhe.compSize];
                byte[] raw  = new byte[dhe.rawSize];

                fileA.BaseStream.Seek(dataOffset + dhe.offset, System.IO.SeekOrigin.Begin);

                comp = fileA.ReadBytes(dhe.compSize);

                Decode(dhe.rawSize, dhe.compSize, raw, comp);

                entries.Add(dhe.id, raw);
            }

            fileA.Close();
        }
Пример #26
0
 public override void Deserialize(System.IO.BinaryReader reader)
 {
     base.Deserialize(reader);
     if (null == _gi)
     {
         _gi = new GameInfo();
     }
     _gi.Name            = this.ReadString(reader);
     _gi.MapId           = reader.ReadInt16();
     _gi.MaxPlayerNumber = reader.ReadInt16();
 }
 public override void Read(System.IO.BinaryReader br, int len, int[] blockSizes = null)
 {
     if (len == 16)
     {
         br.BaseStream.Position += 8;
         this.Parent.Version     = (short)(br.ReadInt16() / 100);
         br.BaseStream.Position += 6;
         return;
     }
     this.Parent.Version = (short)(br.ReadInt16() / 100);
 }
Пример #28
0
        public static ZBoard Deserialize(System.IO.BinaryReader reader)
        {
            ZBoard info = new ZBoard();

            info.BoardSize = reader.ReadInt16();
            info.BoardName = reader.ReadString();
            reader.ReadBytes(50 - info.BoardName.Length);

            List <byte[]> bytes       = new List <byte[]>(10);
            int           tileCounter = 0;

            do
            {
                byte[] byteData;
                byteData = reader.ReadBytes(3);
                if (byteData[0] == 0)
                {
                    tileCounter += 256;
                }
                else
                {
                    tileCounter += byteData[0];
                }
                bytes.Add(byteData);
            } while (tileCounter != 1500);
            info.BoardData = bytes.ToArray();

            info.MaxPlayerShots = reader.ReadByte();
            info.IsDark         = reader.ReadByte();
            info.ExitNorth      = reader.ReadByte();
            info.ExitSouth      = reader.ReadByte();
            info.ExitWest       = reader.ReadByte();
            info.ExitEast       = reader.ReadByte();
            info.RestartOnZap   = reader.ReadByte();
            info.Message        = reader.ReadString();
            reader.ReadBytes(58 - info.Message.Length);
            info.PlayerEnterX = reader.ReadByte();
            info.PlayerEnterY = reader.ReadByte();
            info.Timelimit    = reader.ReadInt16();
            reader.ReadBytes(16);
            info.StatElementCount = reader.ReadInt16();

            info.Player = ZStatusElement.Deserialize(reader);

            List <ZStatusElement> elements = new List <ZStatusElement>(info.StatElementCount);

            for (int i = 0; i < info.StatElementCount; i++)
            {
                elements.Add(ZStatusElement.Deserialize(reader));
            }
            info.Elements = elements.ToArray();

            return(info);
        }
 public MavLink4Net.Messages.IMessage Deserialize(System.IO.BinaryReader reader)
 {
     MavLink4Net.Messages.Common.ManualControlMessage message = new MavLink4Net.Messages.Common.ManualControlMessage();
     message.X       = reader.ReadInt16();
     message.Y       = reader.ReadInt16();
     message.Z       = reader.ReadInt16();
     message.R       = reader.ReadInt16();
     message.Buttons = reader.ReadUInt16();
     message.Target  = reader.ReadByte();
     return(message);
 }
Пример #30
0
        /// <summary>
        /// Unserializes a BinaryStream into the Attributes of this Instance
        /// </summary>
        /// <param name="reader">The Stream that contains the FileData</param>
        internal void Unserialize(System.IO.BinaryReader reader)
        {
            type = (SlotItemType)reader.ReadUInt16();

            unknownf1 = reader.ReadSingle();
            unknownf2 = reader.ReadSingle();
            unknownf3 = reader.ReadSingle();

            unknowni1 = reader.ReadInt32();
            unknowni2 = reader.ReadInt32();
            unknowni3 = reader.ReadInt32();
            unknowni4 = reader.ReadInt32();
            unknowni5 = reader.ReadInt32();

            if (parent.Version >= 5)
            {
                unknownf4 = reader.ReadSingle();
                unknownf5 = reader.ReadSingle();
                unknownf6 = reader.ReadSingle();

                unknowni6 = reader.ReadInt32();
            }

            if (parent.Version >= 6)
            {
                unknowns1 = reader.ReadInt16();
                unknowns2 = reader.ReadInt16();
            }

            if (parent.Version >= 7)
            {
                unknownf7 = reader.ReadSingle();
            }
            if (parent.Version >= 8)
            {
                unknowni7 = reader.ReadInt32();
            }
            if (parent.Version >= 9)
            {
                unknowni8 = reader.ReadInt32();
            }
            if (parent.Version >= 0x10)
            {
                unknownf8 = reader.ReadSingle();
            }

            if (parent.Version >= 0x40)
            {
                unknowni9  = reader.ReadInt32();
                unknowni10 = reader.ReadInt32();
            }
        }
Пример #31
0
        public void Parse(Header header, byte[] data)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
            {
                using (System.IO.BinaryReader br = new System.IO.BinaryReader(ms))
                {
                    _authCode = br.ReadInt32();
                    _accountId = br.ReadUInt32();
                    _userLevel = br.ReadUInt32();
                    _lastLoginIP = br.ReadUInt32();
                    _lastLoginTime = br.ReadBytes(26);
                    _sex = br.ReadByte();

                    _serverList = new Dictionary<string, Server>();
                    for (int i = (int)ms.Position; i < header.Size; i += 32)
                    {
                        Server s = new Server();
                        s.IP = string.Format("{0}.{1}.{2}.{3}", br.ReadByte(), br.ReadByte(), br.ReadByte(), br.ReadByte());
                        s.Port = br.ReadInt16();
                        s.Name = br.ReadBytes(22).NullByteTerminatedString();
                        s.Type = br.ReadInt16();
                        s.UserCount = br.ReadInt16();
                        _serverList.Add(s.Name, s);
                    }
                }
            }
        }
Пример #32
0
        public override bool IsCorrectFormat(System.IO.FileStream fs)
        {
            System.IO.BinaryReader _brdrReader = new System.IO.BinaryReader(fs);

            // Make sure file size > 4100 (data begins after a 4100-byte header).
            if (fs.Length <= 4100)
            {
                return false;
            }

            // Datatype field in header ONLY can be 0~3
            // We can finde the datatype at offset 108 according to the file spec.
            fs.Seek(108, System.IO.SeekOrigin.Begin);

            DataType _dtDataType = (DataType)_brdrReader.ReadInt16();
            if (_dtDataType < DataType.SPE_DATA_FLOAT || _dtDataType > DataType.SPE_DATA_UINT)
            {
                return false;
            }
            return true;
        }
Пример #33
0
 public RGSSTable(byte[] raw)
 {
     System.IO.MemoryStream s = new System.IO.MemoryStream(raw);
     System.IO.BinaryReader r = new System.IO.BinaryReader(s);
     this.dimensions = (byte)r.ReadInt32();
     int x = r.ReadInt32();
     int y = r.ReadInt32();
     int z = r.ReadInt32();
     long check = r.ReadInt32();
     this.value = new short[x, y, z];
     for (int j = 0; j < z; j++)
     {
         for (int k = 0; k < y; k++)
         {
             for (int l = 0; l < x; l++)
             {
                 this[l, k, j] = r.ReadInt16();
             }
         }
     }
 }
Пример #34
0
        public WaveFile(short bitDepth, short channels, int sampleRate, byte[] data)
        {
            this.bitDepth = bitDepth;
            this.channels = channels;
            this.sampleRate = sampleRate;
            path = null;
            name = "[Untitled Recording]";

            System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
            int numSamples = data.Length / (channels * (bitDepth / 8));
            samples = new double[channels][];
            for (int c = 0; c < channels; c++) {
                samples[c] = new double[numSamples];
            }

            if (bitDepth == 16) {
                for (int i = 0; i < numSamples; i++) {
                    for (int c = 0; c < channels; c++) {
                        //assuming signed
                        //normalized to -1.0..+1.0
                        samples[c][i] = (double)br.ReadInt16() / 32768.0;
                    }
                }
            } else if (bitDepth == 8) {
                for (int i = 0; i < numSamples; i++) {
                    for (int c = 0; c < channels; c++) {
                        //assuming unsigned
                        //normalized to -1.0..+1.0
                        samples[c][i] = (double)br.ReadByte() / 128.0 - 1.0;
                    }
                }
            } else {
                throw new FormatException("Bit depth must be one of 8 or 16 bits.");
            }
        }
Пример #35
0
        public void Populate(int iOffset, bool useMemoryStream)
        {
            this.isNulledOutReflexive = false;
            System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS);
            //set offsets
            BR.BaseStream.Position = iOffset + this.chunkOffset;
            this.offsetInMap = iOffset + this.chunkOffset;
            // If we need to read / save tag info directly to file...
            if (!useMemoryStream)
            {
                map.OpenMap(MapTypes.Internal);
                BR = map.BR;
                BR.BaseStream.Position = this.offsetInMap;
            }
            else
                this.offsetInMap += meta.offset;

            switch (this.enumType)
            {
                case 8:
                    {
                        this.value = (int)BR.ReadByte();
                        break;
                    }
                case 16:
                    {
                        this.value = (int)BR.ReadInt16();
                        break;
                    }
                case 32:
                    {
                        this.value = BR.ReadInt32();
                        break;
                    }

            }
            // ...and then close the file once we are done!
            if (!useMemoryStream)
                map.CloseMap();
            UpdateComboBox();
        }
Пример #36
0
        public void readFile()
        {
            System.IO.BinaryReader sr;

            try { //TODO: test, rather than try/fail?
                sr = new System.IO.BinaryReader(System.IO.File.Open(path, System.IO.FileMode.Open));
            } catch (System.IO.IOException) {
                throw;
            }

            //====================
            //RIFF chunk id
            char[] ckID = sr.ReadChars(4);
            String a = new string(ckID);
            if (a.CompareTo("RIFF") != 0) {
                throw new FormatException("RIFF chunkID missing. Found " + ckID[0] + ckID[1] + ckID[2] + ckID[3] + ".");
            }

            UInt32 RIFFSize = sr.ReadUInt32();

            //====================
            //WAVE chunk id
            ckID = sr.ReadChars(4);
            a = new string(ckID);
            if (a.CompareTo("WAVE") != 0) {
                throw new FormatException("WAVE chunkID missing. Found " + ckID[0] + ckID[1] + ckID[2] + ckID[3] + ".");
            }

            //====================
            //fmt_ chunk id
            ckID = sr.ReadChars(4);
            a = new string(ckID);
            UInt32 chunkSize = sr.ReadUInt32();
            while (a.CompareTo("fmt ") != 0) {
                sr.ReadBytes((int)chunkSize);
                ckID = sr.ReadChars(4);
                a = new string(ckID);
                chunkSize = sr.ReadUInt32();
            }
            Int16 wFormatTag = sr.ReadInt16();
            Int16 nChannels = sr.ReadInt16();
            Int32 nSamplesPerSec = sr.ReadInt32();
            Int32 nAvgBytesPerSec = sr.ReadInt32();
            Int16 nBlockAlign = sr.ReadInt16();
            Int16 wBitsPerSample = sr.ReadInt16();
            chunkSize -= 16;
            //there may be more bytes in fmt_ so skip those.
            sr.ReadBytes((int)chunkSize);

            if (wFormatTag != 0x0001) {
                throw new FormatException("Invalid wave format. Only PCM wave files supported.");
            }

            //====================
            //data chunk id
            ckID = sr.ReadChars(4);
            a = new string(ckID);
            chunkSize = sr.ReadUInt32();
            while (a.CompareTo("data") != 0) {
                sr.ReadBytes((int)chunkSize);
                ckID = sr.ReadChars(4);
                a = new string(ckID);
                chunkSize = sr.ReadUInt32();
            }

            channels = (short)nChannels;
            bitDepth = (short)wBitsPerSample;
            sampleRate = nSamplesPerSec;
            long numSamples = chunkSize / (bitDepth / 8) / channels;
            samples = new double[channels][];
            for (int c = 0; c < channels; c++) {
                samples[c] = new double[numSamples];
            }

            //======================
            // read samples
            if (bitDepth == 16) {
                for (int i = 0; i < numSamples; i++) {
                    for (int c = 0; c < channels; c++) {
                        //assuming signed
                        //normalized to -1.0..+1.0
                        samples[c][i] = (double)sr.ReadInt16() / 32768.0;
                    }
                }
            } else if (bitDepth == 8) {
                for (int i = 0; i < numSamples; i++) {
                    for (int c = 0; c < channels; c++) {
                        //assuming unsigned
                        //normalized to -1.0..+1.0
                        samples[c][i] = (double)sr.ReadByte() / 128.0 - 1.0;
                    }
                }
            } else {
                throw new FormatException("Bit depth must be one of 8 or 16 bits.");
            }
            sr.Close();
        }
Пример #37
0
        public static HeightData LoadHeightmapFromImageFile(string path){
            Config config = Main.Get().GetConfig();
            
            HeightData heights;
            
            string ext = path.Substring(path.LastIndexOf('.'), path.Length - path.LastIndexOf('.')).ToLower();

            if (ext == ".shd")
            {
                // byte-by-byte binary reading
                System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.Open(path, System.IO.FileMode.Open, System.IO.FileAccess.Read));

                // read first eight bytes with map dimensions
                int width = reader.ReadInt32();
                int height = reader.ReadInt32();

                heights = new HeightData((UInt16) width,(UInt16) height);

                // read the double bytes containing the height data
                for (int i = 0; i < width * height; i++)
                {
                    heights[i] = reader.ReadInt16();
                }

                reader.Close();

                reader.Dispose();
            }
            else
            {
                // read the bitmap file


                System.Drawing.Bitmap bitmap;

                try
                {
                    bitmap = new System.Drawing.Bitmap(path);
                }
                catch(ArgumentException){
                    return null;
                }

                System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
                System.Drawing.Imaging.BitmapData data = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat);

                heights = new HeightData((UInt16) bitmap.Width, (UInt16)bitmap.Height);

                // prepare memory space for the color data
                byte[] bytes = new byte[data.Stride * bitmap.Height];

                int pixelSize = data.Stride / data.Width;

                // get a pointer to the to first line (=first pixel)
                IntPtr ptr = data.Scan0;

                // create a byte copy of the heightmap data
                System.Runtime.InteropServices.Marshal.Copy(ptr, bytes, 0, data.Stride * bitmap.Height);

                // create the color data
                for (int i = 0; i < bytes.Length; i += pixelSize)
                {
                    heights[i / pixelSize] = (short)((short)bytes[i] * 128);
                }

                bitmap.UnlockBits(data);

                bitmap.Dispose();
            }

            HeightData heights2 = Main.GetResizedHeightData(heights, Math.Min(heights.Width, (int)config.mapDetailLevel), Math.Min(heights.Height, (int)config.mapDetailLevel));

            return heights2;
        }
Пример #38
0
        public void Populate(int iOffset, bool useMemoryStream)
        {
            this.isNulledOutReflexive = false;
            System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS);
            //set offsets
            BR.BaseStream.Position = iOffset + this.chunkOffset;
            this.offsetInMap = iOffset + this.chunkOffset;
            // If we need to read / save tag info directly to file...
            if (!useMemoryStream)
            {
                map.OpenMap(MapTypes.Internal);
                BR = map.BR;
                BR.BaseStream.Position = this.offsetInMap;
            }
            else
                this.offsetInMap += meta.offset;

            this.sidIndexer = BR.ReadInt16();
            byte tempnull = BR.ReadByte();
            byte sidLength = BR.ReadByte();

            // ...and then close the file once we are done!
            if (!useMemoryStream)
                map.CloseMap();

            try
            {
                string s = map.Strings.Name[this.sidIndexer];
                if (map.Strings.Length[this.sidIndexer] == sidLength)
                {
                    if (this.comboBox1.DataSource == null)
                    {
                        this.comboBox1.Items.Clear();
                        this.comboBox1.Items.Add(s);
                        this.comboBox1.SelectedIndex = 0;
                    }
                    else
                        this.comboBox1.SelectedIndex = this.sidIndexer; //.Text = s;
                }
                else
                    this.comboBox1.Text = "";
            }
            catch
            {
                this.comboBox1.Text = "error reading sid";
            }

            /*
            if (AddEvents == true)
            {
                this.comboBox1.TextChanged += new System.EventHandler(this.comboBox1_TextChanged);
                AddEvents = false;
            }
            */
        }
Пример #39
0
		/// <summary>Loads the black-box logs from the previous simulation run</summary>
		internal static void LoadLogs()
		{
			string BlackBoxFile = OpenBveApi.Path.CombineFile(Program.FileSystem.SettingsFolder, "logs.bin");
			try
			{
				using (System.IO.FileStream Stream = new System.IO.FileStream(BlackBoxFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))
				{
					using (System.IO.BinaryReader Reader = new System.IO.BinaryReader(Stream, System.Text.Encoding.UTF8))
					{
						byte[] Identifier = new byte[] { 111, 112, 101, 110, 66, 86, 69, 95, 76, 79, 71, 83 };
						const short Version = 1;
						byte[] Data = Reader.ReadBytes(Identifier.Length);
						for (int i = 0; i < Identifier.Length; i++)
						{
							if (Identifier[i] != Data[i]) throw new System.IO.InvalidDataException();
						}
						short Number = Reader.ReadInt16();
						if (Version != Number) throw new System.IO.InvalidDataException();
						Game.LogRouteName = Reader.ReadString();
						Game.LogTrainName = Reader.ReadString();
						Game.LogDateTime = DateTime.FromBinary(Reader.ReadInt64());
						Interface.CurrentOptions.GameMode = (Interface.GameMode)Reader.ReadInt16();
						Game.BlackBoxEntryCount = Reader.ReadInt32();
						Game.BlackBoxEntries = new Game.BlackBoxEntry[Game.BlackBoxEntryCount];
						for (int i = 0; i < Game.BlackBoxEntryCount; i++)
						{
							Game.BlackBoxEntries[i].Time = Reader.ReadDouble();
							Game.BlackBoxEntries[i].Position = Reader.ReadDouble();
							Game.BlackBoxEntries[i].Speed = Reader.ReadSingle();
							Game.BlackBoxEntries[i].Acceleration = Reader.ReadSingle();
							Game.BlackBoxEntries[i].ReverserDriver = Reader.ReadInt16();
							Game.BlackBoxEntries[i].ReverserSafety = Reader.ReadInt16();
							Game.BlackBoxEntries[i].PowerDriver = (Game.BlackBoxPower)Reader.ReadInt16();
							Game.BlackBoxEntries[i].PowerSafety = (Game.BlackBoxPower)Reader.ReadInt16();
							Game.BlackBoxEntries[i].BrakeDriver = (Game.BlackBoxBrake)Reader.ReadInt16();
							Game.BlackBoxEntries[i].BrakeSafety = (Game.BlackBoxBrake)Reader.ReadInt16();
							Game.BlackBoxEntries[i].EventToken = (Game.BlackBoxEventToken)Reader.ReadInt16();
						}
						Game.ScoreLogCount = Reader.ReadInt32();
						Game.ScoreLogs = new Game.ScoreLog[Game.ScoreLogCount];
						Game.CurrentScore.Value = 0;
						for (int i = 0; i < Game.ScoreLogCount; i++)
						{
							Game.ScoreLogs[i].Time = Reader.ReadDouble();
							Game.ScoreLogs[i].Position = Reader.ReadDouble();
							Game.ScoreLogs[i].Value = Reader.ReadInt32();
							Game.ScoreLogs[i].TextToken = (Game.ScoreTextToken)Reader.ReadInt16();
							Game.CurrentScore.Value += Game.ScoreLogs[i].Value;
						}
						Game.CurrentScore.Maximum = Reader.ReadInt32();
						Identifier = new byte[] { 95, 102, 105, 108, 101, 69, 78, 68 };
						Data = Reader.ReadBytes(Identifier.Length);
						for (int i = 0; i < Identifier.Length; i++)
						{
							if (Identifier[i] != Data[i]) throw new System.IO.InvalidDataException();
						}
						Reader.Close();
					} Stream.Close();
				}
			}
			catch
			{
				Game.LogRouteName = "";
				Game.LogTrainName = "";
				Game.LogDateTime = DateTime.Now;
				Game.BlackBoxEntries = new Game.BlackBoxEntry[256];
				Game.BlackBoxEntryCount = 0;
				Game.ScoreLogs = new Game.ScoreLog[64];
				Game.ScoreLogCount = 0;
			}
		}
Пример #40
0
 public void Populate(int iOffset, bool useMemoryStream)
 {
     this.isNulledOutReflexive = false;
     System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS);
     //set offsets
     BR.BaseStream.Position = iOffset + this.chunkOffset;
     this.offsetInMap = iOffset + this.chunkOffset;
     // If we need to read / save tag info directly to file...
     if (!useMemoryStream)
     {
         map.OpenMap(MapTypes.Internal);
         BR = map.BR;
         BR.BaseStream.Position = this.offsetInMap;
     }
     else
         this.offsetInMap += meta.offset;
     switch (ValueType)
     {
         case IFPIO.ObjectEnum.Short:
             {
                 this.Value = BR.ReadInt16();
                 break;
             }
         case IFPIO.ObjectEnum.Int:
             {
                 this.Value = BR.ReadInt32();
                 break;
             }
         case IFPIO.ObjectEnum.UShort:
             {
                 this.Value = BR.ReadUInt16();
                 break;
             }
         case IFPIO.ObjectEnum.UInt:
             {
                 this.Value = BR.ReadUInt32();
                 break;
             }
         case IFPIO.ObjectEnum.Float:
             {
                 this.Value = BR.ReadSingle();
                 break;
             }
         case IFPIO.ObjectEnum.Unknown:
             {
                 this.Value = BR.ReadSingle();
                 break;
             }
         case IFPIO.ObjectEnum.Byte:
             {
                 this.Value = BR.ReadByte();
                 break;
             }
     }
     // ...and then close the file once we are done!
     if (!useMemoryStream)
         map.CloseMap();
     if (this.ValueType != IFPIO.ObjectEnum.Unused)
         this.Controls[1].Text = this.Value.ToString();
 }
Пример #41
0
        public void Populate(int iOffset, int iIndexedReflexiveOffset)
        {
            this.isNulledOutReflexive = false;
            System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS);

            int mapMetaOffset = meta.offset;

            if (this._EntIndex.reflexiveTagType + this._EntIndex.reflexiveTagName != string.Empty)
            {
                int tagNum = map.Functions.ForMeta.FindByNameAndTagType(this._EntIndex.reflexiveTagType, this._EntIndex.reflexiveTagName);
                if (tagNum != -1)
                {
                    Meta meta2 = new Meta(map);
                    map.OpenMap(MapTypes.Internal);
                    meta2.ReadMetaFromMap(tagNum, true);
                    map.CloseMap();
                    mapMetaOffset = meta2.offset;
                    this._EntIndex.reflexiveLayer = "root";
                }
            }

            if (this._EntIndex.reflexiveLayer.ToLower() == "root")
                this._IndexedReflexiveOffset = mapMetaOffset + this._EntIndex.ReflexiveOffset;
            else if (this._EntIndex.reflexiveLayer.ToLower() == "oneup")
                this._IndexedReflexiveOffset = iIndexedReflexiveOffset + this._EntIndex.ReflexiveOffset;

            /*
            bool openedMap = false;
            if (map.isOpen == false)
            {
                map.OpenMap(MapTypes.Internal);
                openedMap = true;
            }
            map.BA.Position = iOffset + this.chunkOffset;
            */
            BR.BaseStream.Position = iOffset + this.chunkOffset;
            this.offsetInMap = meta.offset + iOffset + this.chunkOffset;

            switch (_ValueType)
            {
                case IFPIO.ObjectEnum.Short:
                    {
                        this.Value = (int)BR.ReadInt16();
                        break;
                    }
                case IFPIO.ObjectEnum.Int:
                    {
                        this.Value = BR.ReadInt32();
                        break;
                    }
                case IFPIO.ObjectEnum.UShort:
                    {
                        this.Value = (int)BR.ReadUInt16();
                        break;
                    }
                case IFPIO.ObjectEnum.UInt:
                    {
                        this.Value = (int)BR.ReadUInt32();
                        break;
                    }
                case IFPIO.ObjectEnum.Byte:
                    {
                        this.Value = (int)BR.ReadByte();
                        break;
                    }
            }
            UpdateSelectionList(false);
            /*
            if (openedMap == true)
                map.CloseMap();
            */
        }
Пример #42
0
        public override void LoadData(System.IO.FileStream __fsFileStream)
        {
            System.IO.BinaryReader _brdrReader = new System.IO.BinaryReader(__fsFileStream);

            // only read necessary params from file header
            __fsFileStream.Seek(42, System.IO.SeekOrigin.Begin);
            int _iXDimension = (int)_brdrReader.ReadInt16();
            __fsFileStream.Seek(108, System.IO.SeekOrigin.Begin);
            DataType _dtDataType = (DataType)_brdrReader.ReadInt16();
            __fsFileStream.Seek(656, System.IO.SeekOrigin.Begin);
            int _iYDimension = (int)_brdrReader.ReadInt16();
            __fsFileStream.Seek(1446, System.IO.SeekOrigin.Begin);
            UInt32 numframes = (UInt32)_brdrReader.ReadInt32();

            // Start reading the XCalibStruct.
            SpeCalib XCalib = new SpeCalib(0, 0);
            __fsFileStream.Seek(3000, System.IO.SeekOrigin.Begin);
            XCalib.Offset = (double)_brdrReader.ReadDouble();
            __fsFileStream.Seek(3008, System.IO.SeekOrigin.Begin);
            XCalib.Factor = (double)_brdrReader.ReadDouble();
            __fsFileStream.Seek(3016, System.IO.SeekOrigin.Begin);
            XCalib.current_unit = (char)_brdrReader.ReadChar();
            __fsFileStream.Seek(3098, System.IO.SeekOrigin.Begin);
            XCalib.CalibValid = (char)_brdrReader.ReadChar();
            __fsFileStream.Seek(3101, System.IO.SeekOrigin.Begin);
            XCalib.PolynomOrder = (char)_brdrReader.ReadChar();
            __fsFileStream.Seek(3263, System.IO.SeekOrigin.Begin);

            XCalib.PolynomCoeff[0] = _brdrReader.ReadDouble();
            XCalib.PolynomCoeff[1] = _brdrReader.ReadDouble();
            XCalib.PolynomCoeff[2] = _brdrReader.ReadDouble();
            XCalib.PolynomCoeff[3] = _brdrReader.ReadDouble();
            XCalib.PolynomCoeff[4] = _brdrReader.ReadDouble();
            XCalib.PolynomCoeff[5] = _brdrReader.ReadDouble();

            __fsFileStream.Seek(3311, System.IO.SeekOrigin.Begin);
            XCalib.LaserPosition = (double)_brdrReader.ReadDouble();

            // Start reading the YCalibStruct.
            SpeCalib YCalib = new SpeCalib(0, 0);
            __fsFileStream.Seek(3489, System.IO.SeekOrigin.Begin);   // move ptr to x_calib start
            YCalib.Offset = (double)_brdrReader.ReadDouble();
            __fsFileStream.Seek(3497, System.IO.SeekOrigin.Begin);
            YCalib.Factor = (double)_brdrReader.ReadDouble();
            __fsFileStream.Seek(3505, System.IO.SeekOrigin.Begin);
            YCalib.current_unit = (char)_brdrReader.ReadChar();
            __fsFileStream.Seek(3587, System.IO.SeekOrigin.Begin);
            YCalib.CalibValid = (char)_brdrReader.ReadChar();
            __fsFileStream.Seek(3590, System.IO.SeekOrigin.Begin);
            YCalib.PolynomOrder = (char)_brdrReader.ReadChar();
            __fsFileStream.Seek(3752, System.IO.SeekOrigin.Begin);

            YCalib.PolynomCoeff[0] = _brdrReader.ReadDouble();
            YCalib.PolynomCoeff[1] = _brdrReader.ReadDouble();
            YCalib.PolynomCoeff[2] = _brdrReader.ReadDouble();
            YCalib.PolynomCoeff[3] = _brdrReader.ReadDouble();
            YCalib.PolynomCoeff[4] = _brdrReader.ReadDouble();
            YCalib.PolynomCoeff[5] = _brdrReader.ReadDouble();

            __fsFileStream.Seek(3800, System.IO.SeekOrigin.Begin);
            YCalib.LaserPosition = (double)_brdrReader.ReadDouble();

            int _iDimension;
            SpeCalib _calCurrCalib;
            if (_iYDimension == 1)
            {
                _iDimension = _iXDimension;
                _calCurrCalib = XCalib;
            }
            else if (_iXDimension == 1)
            {
                _iDimension = _iYDimension;
                _calCurrCalib = YCalib;
            }
            else
            {
                throw new UnexpectedFormatException("xylib does not support 2-D images");
            }

            __fsFileStream.Seek(4100, System.IO.SeekOrigin.Begin);      // move ptr to frames-start
            for (int frm = 0; frm < (int)numframes; frm++)
            {
                Block _blkBlock = new Block();

                Column _colXCol = this.GetCalibColumn(_calCurrCalib, _iDimension);
                _blkBlock.AddColumn(_colXCol, "", true);

                ListColumn _colYCol = new ListColumn();

                for (int i = 0; i < _iDimension; ++i)
                {
                    double _dYVal = 0;
                    switch (_dtDataType)
                    {
                        case DataType.SPE_DATA_FLOAT:
                            _dYVal = (double)_brdrReader.ReadSingle();
                            break;
                        case DataType.SPE_DATA_LONG:
                            _dYVal = (double)_brdrReader.ReadInt32();
                            break;
                        case DataType.SPE_DATA_INT:
                            _dYVal = (double)_brdrReader.ReadInt16();
                            break;
                        case DataType.SPE_DATA_UINT:
                            _dYVal = (double)_brdrReader.ReadUInt16();
                            break;
                        default:
                            break;
                    }
                    _colYCol.AddValue(_dYVal);
                }
                _blkBlock.AddColumn(_colYCol, "", true);
                this.m_blcklstBlocks.Add(_blkBlock);
            }
        }
Пример #43
0
        /// <summary>Loads a wave/riff audio file from a stream. Resource file can be passed as the stream.</summary>
        private static byte[] LoadWave(System.IO.Stream stream, out int channels, out int bits, out int rate)
        {
            if (stream == null) throw new ArgumentNullException("stream");

            // ReSharper disable UnusedVariable
            using (var reader = new System.IO.BinaryReader(stream))
            {
                //RIFF header
                var signature = new string(reader.ReadChars(4));
                if (signature != "RIFF") throw new NotSupportedException("Specified stream is not a wave file.");

                int riffChunckSize = reader.ReadInt32();

                var format = new string(reader.ReadChars(4));
                if (format != "WAVE") throw new NotSupportedException("Specified stream is not a wave file.");

                //WAVE header
                var formatSignature = new string(reader.ReadChars(4));
                if (formatSignature != "fmt ") throw new NotSupportedException("Specified wave file is not supported.");

                int formatChunkSize = reader.ReadInt32();
                int audioFormat = reader.ReadInt16();
                int numChannels = reader.ReadInt16();
                int sampleRate = reader.ReadInt32();
                int byteRate = reader.ReadInt32();
                int blockAlign = reader.ReadInt16();
                int bitsPerSample = reader.ReadInt16();

                var dataSignature = new string(reader.ReadChars(4));
                //check if the data dignature for this chunk is LIST headers, can happen with .wav files from web, or when converting other formats such as .mp3 to .wav using tools such as audacity
                //if this happens, the extra header info can be cleared using audacity, export to wave and select 'clear' when the extra header info window appears
                //see http://www.lightlink.com/tjweber/StripWav/WAVE.html
                if (dataSignature == "LIST") throw new NotSupportedException("Specified wave file contains LIST headers (author, copyright etc).");
                if (dataSignature != "data") throw new NotSupportedException("Specified wave file is not supported.");

                int dataChunkSize = reader.ReadInt32();

                channels = numChannels;
                bits = bitsPerSample;
                rate = sampleRate;

                return reader.ReadBytes((int)reader.BaseStream.Length);
            }
            // ReSharper restore UnusedVariable
        }
    /// <summary>
    /// Imports a Galactic SPC file into a x and an y array. The file must not be a multi spectrum file (an exception is thrown in this case).
    /// </summary>
    /// <param name="xvalues">The x values of the spectrum.</param>
    /// <param name="yvalues">The y values of the spectrum.</param>
    /// <param name="filename">The filename where to import from.</param>
    /// <returns>Null if successful, otherwise an error description.</returns>
    public static string ToArrays(string filename, out double [] xvalues, out double [] yvalues)
    {
      System.IO.Stream stream=null;

      SPCHDR hdr = new SPCHDR();
      SUBHDR subhdr = new SUBHDR();

      try
      {
        stream = new System.IO.FileStream(filename,System.IO.FileMode.Open,System.IO.FileAccess.Read,System.IO.FileShare.Read);
        System.IO.BinaryReader binreader = new System.IO.BinaryReader(stream);


        hdr.ftflgs = binreader.ReadByte(); // ftflgs : not-evenly spaced data
        hdr.fversn = binreader.ReadByte(); // fversn : new version
        hdr.fexper = binreader.ReadByte(); // fexper : general experimental technique
        hdr.fexp   = binreader.ReadByte(); // fexp   : fractional scaling exponent (0x80 for floating point)

        hdr.fnpts  = binreader.ReadInt32(); // fnpts  : number of points

        hdr.ffirst = binreader.ReadDouble(); // ffirst : first x-value
        hdr.flast  = binreader.ReadDouble(); // flast : last x-value
        hdr.fnsub  = binreader.ReadInt32(); // fnsub : 1 (one) subfile only
      
        binreader.ReadByte(); //  Type of X axis units (see definitions below) 
        binreader.ReadByte(); //  Type of Y axis units (see definitions below) 
        binreader.ReadByte(); // Type of Z axis units (see definitions below)
        binreader.ReadByte(); // Posting disposition (see GRAMSDDE.H)

        binreader.Read(new byte[0x1E0],0,0x1E0); // rest of SPC header


        // ---------------------------------------------------------------------
        //   following the x-values array
        // ---------------------------------------------------------------------

        if(hdr.fversn!=0x4B)
        {
          if(hdr.fversn==0x4D)
            throw new System.FormatException(string.Format("This SPC file has the old format version of {0}, the only version supported here is the new version {1}",hdr.fversn,0x4B));
          else
            throw new System.FormatException(string.Format("This SPC file has a version of {0}, the only version recognized here is {1}",hdr.fversn,0x4B));
        }

        if(0!=(hdr.ftflgs & 0x80))
        {
          xvalues = new double[hdr.fnpts];
          for(int i=0;i<hdr.fnpts;i++)
            xvalues[i] = binreader.ReadSingle();
        }
        else if(0==hdr.ftflgs) // evenly spaced data
        {
          xvalues = new double[hdr.fnpts];
          for(int i=0;i<hdr.fnpts;i++)
            xvalues[i] = hdr.ffirst + i*(hdr.flast-hdr.ffirst)/(hdr.fnpts-1);
        }
        else
        {
          throw new System.FormatException("The SPC file must not be a multifile; only single file format is accepted!");
        }



        // ---------------------------------------------------------------------
        //   following the y SUBHEADER
        // ---------------------------------------------------------------------

        subhdr.subflgs = binreader.ReadByte(); // subflgs : always 0
        subhdr.subexp  = binreader.ReadByte(); // subexp : y-values scaling exponent (set to 0x80 means floating point representation)
        subhdr.subindx = binreader.ReadInt16(); // subindx :  Integer index number of trace subfile (0=first)

        subhdr.subtime = binreader.ReadSingle(); // subtime;   Floating time for trace (Z axis corrdinate) 
        subhdr.subnext = binreader.ReadSingle(); // subnext;   Floating time for next trace (May be same as beg) 
        subhdr.subnois = binreader.ReadSingle(); // subnois;   Floating peak pick noise level if high byte nonzero 

        subhdr.subnpts = binreader.ReadInt32(); // subnpts;  Integer number of subfile points for TXYXYS type 
        subhdr.subscan = binreader.ReadInt32(); // subscan; Integer number of co-added scans or 0 (for collect) 
        subhdr.subwlevel = binreader.ReadSingle();        // subwlevel;  Floating W axis value (if fwplanes non-zero) 
        subhdr.subresv   = binreader.ReadInt32(); // subresv[4];   Reserved area (must be set to zero) 


        // ---------------------------------------------------------------------
        //   following the y-values array
        // ---------------------------------------------------------------------
        yvalues = new double[hdr.fnpts];
        
        if(hdr.fexp==0x80) //floating point format
        {
          for(int i=0;i<hdr.fnpts;i++)
            yvalues[i] = binreader.ReadSingle();
        }
        else // fixed exponent format
        {
          for(int i=0;i<hdr.fnpts;i++)
            yvalues[i] = binreader.ReadInt32()*Math.Pow(2,hdr.fexp-32);
        }
      }
      catch(Exception e)
      {
        xvalues = null;
        yvalues = null;
        return e.ToString();
      }
      finally
      {
        if(null!=stream)
          stream.Close();
      }
      
      return null;
    }
Пример #45
0
        static bool setupDaxFiles(out System.IO.BinaryReader fileA, out System.IO.BinaryReader fileB, out short arg_8, string file_name)
        {
            fileA = null;
            fileB = null;
            arg_8 = 0;

            if (System.IO.File.Exists(file_name) == false)
            {
                /*TODO Add message about missing file here.*/
                return false;
            }

            try
            {
                System.IO.FileStream fsA = new System.IO.FileStream(file_name, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
                System.IO.FileStream fsB = new System.IO.FileStream(file_name, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);

                fileA = new System.IO.BinaryReader(fsA);
                fileB = new System.IO.BinaryReader(fsB);
            }
            catch (System.ApplicationException)
            {
                /*TODO Add message about error here.*/
                return false;
            }

            arg_8 = fileA.ReadInt16();
            arg_8 += 2;

            fileB.BaseStream.Seek(arg_8, System.IO.SeekOrigin.Begin);
            return true;
        }
 public Ole10Native(System.IO.Stream inputStream)
 {
     System.IO.BinaryReader reader = new System.IO.BinaryReader(inputStream);
     totalSize = reader.ReadInt32();
     if (totalSize < 4)
     {
         throw new Exception(
                 String.Format("Invalid total data size: {0}.", totalSize));
     }
     flags1 = reader.ReadInt16();
     label = ReadString(reader);
     fileName = ReadString(reader);
     flags2 = reader.ReadInt16();
     byte unknown1Len = reader.ReadByte();
     unknown1 = reader.ReadBytes(unknown1Len);
     unknown2 = reader.ReadBytes(3);
     command = ReadString(reader);
     nativeDataSize = reader.ReadInt32();
     if (nativeDataSize > totalSize || nativeDataSize < 0)
     {
         throw new Exception(
                 String.Format("Invalid native data size: {0}.", nativeDataSize));
     }
     nativeData = reader.ReadBytes(nativeDataSize);
     unknown3 = unknown1.Length > 0 ? reader.ReadInt16() : (short)0;
 }
Пример #47
0
        /// <summary>
        /// Handles HidDataReceived events and processes incoming raw data from the
        /// Device. Fills m_Translation and m_Rotation objects with the filtered and
        /// scaled raw data. At the end fire SensorInput to notify clients.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="p_HidDataReceivedEventArgs"></param>
        private void HidDataReceived(object sender, HidDataReceivedEventArgs p_HidDataReceivedEventArgs)
        {
            short x = 0;
            short y = 0;
            short z = 0;

            ///////////////////////////////
            // set Length of translation //
            // movement to 0 zeroes also //
            // x, y and z components     //
            ///////////////////////////////
            m_Translation.Length = 0;

            ///////////////////////////////
            // set Angle of rotation     //
            // movement to 0 zeroes also //
            // x, y and z components     //
            ///////////////////////////////
            m_Rotation.Angle = 0;

            ///////////////////////////////
            // handling the translation  //
            ///////////////////////////////
            if (p_HidDataReceivedEventArgs[0] == c_Translation)
            {
                try
                {
                    byte[] buffer = {
                        p_HidDataReceivedEventArgs[1],
                        p_HidDataReceivedEventArgs[2],
                        p_HidDataReceivedEventArgs[3],
                        p_HidDataReceivedEventArgs[4],
                        p_HidDataReceivedEventArgs[5],
                        p_HidDataReceivedEventArgs[6],
                    };

                    System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer, 0, buffer.Length);
                    System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);

                    x = reader.ReadInt16();
                    y = reader.ReadInt16();
                    z = reader.ReadInt16();

                    /*
                    Console.Out.WriteLine("transX: {0}", x);
                    Console.Out.WriteLine("transY: {0}", y);
                    Console.Out.WriteLine("transZ: {0}", z);
                    */

                    ////////////////////////////////////////
                    // Filtering and scaling is done here //
                    // X value of Aerion Input data must  //
                    // be multiplied with -1              //
                    ////////////////////////////////////////
                    m_Translation.X = m_TranslationFunction(System.Convert.ToDouble(x), c_MaxValueTranslation) * XScaleFactor;
                    m_Translation.Y = m_TranslationFunction(System.Convert.ToDouble(y), c_MaxValueTranslation) * YScaleFactor;
                    m_Translation.Z = m_TranslationFunction(System.Convert.ToDouble(z), c_MaxValueTranslation) * ZScaleFactor;
                }
                catch (Exception e)
                {
                    Console.Out.WriteLine("Exception: {0}, {1}, {2}", e.GetType(), e.Message, e.StackTrace);
                }
            }

            ///////////////////////////
            // handling the rotation //
            ///////////////////////////
            else if (p_HidDataReceivedEventArgs[0] == c_Rotation)
            {
                try
                {
                    byte[] buffer = {
                        p_HidDataReceivedEventArgs[1],
                        p_HidDataReceivedEventArgs[2],
                        p_HidDataReceivedEventArgs[3],
                        p_HidDataReceivedEventArgs[4],
                        p_HidDataReceivedEventArgs[5],
                        p_HidDataReceivedEventArgs[6],
                    };

                    System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer, 0, buffer.Length);
                    System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);

                    x = reader.ReadInt16();
                    y = reader.ReadInt16();
                    z = reader.ReadInt16();

                    /*
                    Console.Out.WriteLine("rotX: {0}", x);
                    Console.Out.WriteLine("rotY: {0}", y);
                    Console.Out.WriteLine("rotZ: {0}", z);
                    */

                    ////////////////////////////////////////
                    // Filtering and scaling is done here //
                    ////////////////////////////////////////
                    m_Rotation.X =  m_RotationFunction(System.Convert.ToDouble(x), c_MaxValueRotation) * XRotScaleFactor; //Rotation um X-Achse = rot
                    m_Rotation.Y =  m_RotationFunction(System.Convert.ToDouble(y), c_MaxValueRotation) * YRotScaleFactor; //Rotation um Y-Achse = gr�n
                    m_Rotation.Z =  m_RotationFunction(System.Convert.ToDouble(z), c_MaxValueRotation) * ZRotScaleFactor; //Rotation um Z-Achse = blau
                }
                catch (Exception e)
                {
                    Console.Out.WriteLine("Exception: {0}, {1}, {2}", e.GetType(), e.Message, e.StackTrace);
                }
                #region old stuff...
                /*
                _xRot = (ushort)(p_HidDataReceivedEventArgs[1]);
                _xRot += (ushort)(p_HidDataReceivedEventArgs[2] << 8);
                xRot = (short)(_xRot);

                m_Rotation.X = xRot * XRotScaleFactor;
                //Console.Out.WriteLine("rotX: {0}", rotX);

                _yRot = (ushort)(p_HidDataReceivedEventArgs[3]);
                _yRot += (ushort)(p_HidDataReceivedEventArgs[4] << 8);
                yRot = (short)(_yRot);

                m_Rotation.Y = yRot * YRotScaleFactor;
                //Console.Out.WriteLine("rotY: {0}", rotY);

                _zRot = (ushort)(p_HidDataReceivedEventArgs[5]);
                _zRot += (ushort)(p_HidDataReceivedEventArgs[6] << 8);
                zRot = (short)(_zRot);

                m_Rotation.Z = zRot * ZRotScaleFactor;
                //Console.Out.WriteLine("angle_internal: {0}", m_Rotation.Angle);
                */
                #endregion
            }
            ///////////////////////////////////////
            // Fire SensorInput iff              //
            // Angle > RotationThreshold         //
            // and Length > TranslationThreshold //
            ///////////////////////////////////////
            if ((m_Rotation.Angle > m_RotationThreshold) || m_Translation.Length > m_TranslationThreshold)
            {
                // Scale down Ticks
                m_Period = Convert.ToDouble(System.DateTime.Now.Ticks)/1000000000 - m_Period;

                // Fire event thread save
                _ISensorEvents_SensorInputEventHandler SensorEventHandler = null;

                lock (m_lock)
                {
                    SensorEventHandler = m_SensorInput;
                    if (SensorEventHandler != null)
                    {
                        SensorEventHandler();
                    }
                }
                #region old stuff
                /*
                if (SensorInput != null)
                {
                    lock (m_lock)
                    {
                        //SensorInput(this, new EventArgs());
                        SensorInput();

                    }

                }
                */
                #endregion
            }
        }
Пример #48
0
 //Загрузка файла и превращение его в удобочитаемый вид с одновременным анализом
 bool LoadWavFile()
 {
     Log(openFileDialog1.FileName);
     WAV.Data.Clear();
     byte[] wave;
     int Len;
     try
     {
         System.IO.BinaryReader File = new System.IO.BinaryReader(new System.IO.FileStream(FileName, System.IO.FileMode.Open));
         //Прочитаем сперва параметры файла
         File.ReadBytes(22);
         WAV.Channels = File.ReadInt16();
         WAV.Sampling = File.ReadInt32();
         File.ReadBytes(6);
         WAV.Bits = File.ReadInt16();
         File.ReadBytes(4);
         Len = File.ReadInt32();// +44;
         string Channels = "Моно";
         if (WAV.Channels == 2) Channels = "Стерео";
         Log(WAV.Bits.ToString() + " bit; " + Channels + "; " + WAV.Sampling.ToString() + " Hz");
         Log("Загрузка файла");
         //Грузим выборку
         wave = File.ReadBytes(Len);
         File.Close();
     }
     catch
     {
         Log("Сбой загрузки");
         Editor.Error("Произошла ошибка при загрузке WAV-файла.");
         return false;
     }
     //Обрабатываем то что загрузилось
     bool readOK;
     for (int ii = 0; ii < Len; )
     {
         Application.DoEvents();
         int result = 0;
         readOK = true; //Вот, будем проверять всё ли прочиталось, а то попадаются 16-битные записи где не хватает второго байта
         for (int i = 0; i < WAV.Channels; i++) //Грузим каналы по очереди (вдруг больше 2-х будет)
         {
             try
             {
                 if (WAV.Bits == 8) result += wave[ii];
                 if (WAV.Bits == 16) { result += TwoBytesToInt(wave[ii], wave[ii + 1]); ii++; }
             }
             catch
             {
                 readOK = false;
             }
             ii++;
         }
         if (!readOK) break;
         result /= WAV.Channels;
         if (WAV.Bits == 16) { result += 32768; result /= 256; }
         try
         {
             WAV.Data.Add((byte)result);
         }
         catch
         {
             break;
         }
     }
     HightSam = WAV.Sampling.ToString() + " Hz";
     LowSam = (WAV.Sampling / 100).ToString() + " Hz";
         //Ищим ось (находим минимумы и максимумы, ровно между ними и будет ось)
     byte min = WAV.Data[0];
     byte max = WAV.Data[0];
     foreach (byte b in WAV.Data)
     {
         if (b < min) min = b;
         if (b > max) max = b;
     }
     byte OS = (byte)((min + max) / 2);
     //Преобразовываем выборку в "ровную пилу" _-__--_- для последующего удобства использования
     for (int i = 0; i<WAV.Data.Count;i++)
         if (WAV.Data[i] < OS) WAV.Data[i] = 0;
         else WAV.Data[i] = 1;
     return true;
 }
Пример #49
0
        private void LoadFile(string filename)
        {
            int dataOffset = 0;

            if (System.IO.File.Exists(filename) == false)
            {
                return;
            }

            System.IO.BinaryReader fileA;

            try
            {
                System.IO.FileStream fsA = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);

                fileA = new System.IO.BinaryReader(fsA);
            }
            catch (System.ApplicationException)
            {
                return;
            }

            dataOffset = fileA.ReadInt16() + 2;

            List<DaxHeaderEntry> headers = new List<DaxHeaderEntry>();

            const int headerEntrySize = 9;

            for (int i = 0; i < ((dataOffset - 2) / headerEntrySize); i++)
            {
                DaxHeaderEntry dhe = new DaxHeaderEntry();
                dhe.id = fileA.ReadByte();
                dhe.offset = fileA.ReadInt32();
                dhe.rawSize = fileA.ReadInt16();
                dhe.compSize = fileA.ReadUInt16();

                headers.Add(dhe);
            }

            foreach (DaxHeaderEntry dhe in headers)
            {
                byte[] comp = new byte[dhe.compSize];
                byte[] raw = new byte[dhe.rawSize];

                fileA.BaseStream.Seek(dataOffset + dhe.offset, System.IO.SeekOrigin.Begin);

                comp = fileA.ReadBytes(dhe.compSize);

                Decode(dhe.rawSize, dhe.compSize, raw, comp);

                entries.Add(dhe.id, raw);
            }

            fileA.Close();
        }
Пример #50
0
        public IndexList(StreamChunk indexStream)
        {
            this.indices = new short[indexStream.VertexCount];
            this.used = new bool[indexStream.VertexCount / 3];

            // Copy indices
            using (var ms = new System.IO.MemoryStream(indexStream.VertexData, false))
            using (var br = new System.IO.BinaryReader(ms))
            {
                for (var i = 0; i < indexStream.VertexCount; i++)
                {
                    indices[i] = br.ReadInt16();
                }
            }
        }
Пример #51
0
Файл: Row.cs Проект: vebin/BD2
 public static Row Deserialize(byte[] bytes)
 {
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream (bytes, false)) {
         using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
             byte[] columnSet = BR.ReadBytes (32);
             int FieldCount = BR.ReadInt32 ();
             object[] fields = new object[FieldCount];
             ColumnSet cs = css [columnSet];
             if (cs.Columns.Length != fields.Length)
                 throw new Exception ();
             for (int n = 0; n != fields.Length; n++) {
                 bool Null = BR.ReadBoolean ();
                 if (Null) {
                     fields [n] = null;
                     continue;
                 }
                 switch (cs.Columns [n].TFQN) {
                 case "System.Byte[]":
                     fields [n] = BR.ReadBytes (BR.ReadInt32 ());
                     break;
                 case "System.Byte":
                     fields [n] = BR.ReadByte ();
                     break;
                 case "System.SByte":
                     fields [n] = BR.ReadSByte ();
                     break;
                 case "System.Int16":
                     fields [n] = BR.ReadInt16 ();
                     break;
                 case "System.UInt16":
                     fields [n] = BR.ReadUInt16 ();
                     break;
                 case "System.Int32":
                     fields [n] = BR.ReadInt32 ();
                     break;
                 case "System.UInt32":
                     fields [n] = BR.ReadUInt32 ();
                     break;
                 case "System.Int64":
                     fields [n] = BR.ReadInt64 ();
                     break;
                 case "System.UInt64":
                     fields [n] = BR.ReadUInt64 ();
                     break;
                 case "System.Single":
                     fields [n] = BR.ReadSingle ();
                     break;
                 case "System.Double":
                     fields [n] = BR.ReadDouble ();
                     break;
                 case "System.String":
                     fields [n] = BR.ReadString ();
                     break;
                 case "System.Char":
                     fields [n] = BR.ReadChar ();
                     break;
                 case "System.Boolean":
                     fields [n] = BR.ReadBoolean ();
                     break;
                 case "System.DateTime":
                     fields [n] = new DateTime (BR.ReadInt64 ());
                     break;
                 case "System.Guid":
                     fields [n] = new Guid (BR.ReadBytes (16));
                     break;
                 }
             }
             return new Row (cs, fields);
         }
     }
 }