ReadChars() public method

public ReadChars ( int count ) : char[]
count int
return char[]
Beispiel #1
0
        /// <summary>
        /// Creates a new entity that was embedded next in the stream
        /// </summary>
        /// <param name="stream">The System.IO.BinaryReader to use.</param>
        public Entity(BinaryReader stream)
        {
            X = stream.ReadInt16();
            Y = stream.ReadInt16();
            Layer = stream.ReadInt16();
            Scripts = new List<string>();
            Type = (EntityType)stream.ReadInt16();
            stream.ReadBytes(8);

            short len;
            if (Type == EntityType.Person)
            {
                len = stream.ReadInt16();
                Name = new string(stream.ReadChars(len));
                len = stream.ReadInt16();
                Spriteset = new string(stream.ReadChars(len));
                int scripts = stream.ReadInt16();

                // read the person script data
                for (int i = 0; i < scripts; ++i)
                {
                    len = stream.ReadInt16();
                    Scripts.Add(new string(stream.ReadChars(len)));
                }

                stream.ReadBytes(16); // reserved
            }
            else
            {
                len = stream.ReadInt16();
                Function = new string(stream.ReadChars(len));
                Trigger = new CompiledMethod(Program._engine, Function);
            }
        }
        //-------------------------------------------------------------------------------
        private static void ReadPrintDataRec(short i, BinaryReader f, StreamWriter log)
        {
            short id;
            char[] code = new char[3];
            char[] name = new char[17];
            char[] continent = new char[11];
            char[] region = new char[10];
            int surfaceArea;
            short yearOfIndep;
            long population;
            float lifeExp;
            int gnp;

            id = f.ReadInt16();
            code = f.ReadChars(3);
            name = f.ReadChars(17);
            continent = f.ReadChars(11);
            region = f.ReadChars(10);
            surfaceArea = f.ReadInt32();
            yearOfIndep = f.ReadInt16();
            population = f.ReadInt64();
            lifeExp = f.ReadSingle();
            gnp = f.ReadInt32();
            if (id == 0)
                log.WriteLine("[{0:000}] EMPTY SPOT", i);
            else
                log.WriteLine("[{0:000}] {1:000}|{2}|{3}|{4}|{5}|" +
                    "{6,10:N0}|{7,5}|{8,13:N0}|{9,4:N1}|{10,9:N0}|",
                    i, id, new string(code), new string(name),
                    new string(continent), new string(region),
                    surfaceArea, yearOfIndep, population, lifeExp, gnp);
        }
Beispiel #3
0
        public static TileSet ReadFromFile(string fileName)
        {
            var data = ZFile.ReadFile(fileName);
            if (data == null)
                return null;

            var reader = new BinaryReader(new MemoryStream(data));
            var tileSet = new TileSet(null);

            tileSet.Signature		= new string(reader.ReadChars(4));
            tileSet.Version			= new string(reader.ReadChars(4));
            tileSet.ColorDepth		= (BitsPerColor)reader.ReadByte();
            tileSet.ExtendedOptions = ZMath.GetBool(reader.ReadByte());
            var tileDataSize		= reader.ReadByte();		// maybe can be check for some conditions?
            var nameLength			= reader.ReadByte();
            var tilesCount			= reader.ReadInt32();
            tileSet.Name			= new string(reader.ReadChars(64), 0, nameLength);

            for (int i = 0; i < tilesCount; i++)
            {
                try		{	tileSet.Add(new Tile(reader.ReadUInt64()));	}
                catch	{	return null;	}
            }

            return tileSet;
        }
Beispiel #4
0
        public override void Read(string fileIn)
        {
            BinaryReader br = new BinaryReader(File.OpenRead(fileIn));
            nscr = new sNSCR();

            // Generic header
            nscr.header.id = br.ReadChars(4);
            nscr.header.endianess = br.ReadUInt16();
            if (nscr.header.endianess == 0xFFFE)
                nscr.header.id.Reverse<char>();
            nscr.header.constant = br.ReadUInt16();
            nscr.header.file_size = br.ReadUInt32();
            nscr.header.header_size = br.ReadUInt16();
            nscr.header.nSection = br.ReadUInt16();

            // Read section
            nscr.nrcs.id = br.ReadChars(4);
            nscr.nrcs.section_size = br.ReadUInt32();
            nscr.nrcs.width = br.ReadUInt16();
            nscr.nrcs.height = br.ReadUInt16();
            nscr.nrcs.padding = br.ReadUInt32();
            nscr.nrcs.data_size = br.ReadUInt32();
            nscr.nrcs.mapData = new NTFS[nscr.nrcs.data_size / 2];

            for (int i = 0; i < nscr.nrcs.mapData.Length; i++)
                nscr.nrcs.mapData[i] = Actions.MapInfo(br.ReadUInt16());

            br.Close();

            Set_Map(nscr.nrcs.mapData, true, nscr.nrcs.width, nscr.nrcs.height);
        }
Beispiel #5
0
        private UserHeaderLabel ReadUHL(BinaryReader br)
        {
            char[] header = br.ReadChars(4);
            if (new string(header) != "UHL1")
                throw new Exception("Wrong UHL header");

            UserHeaderLabel uhl = new UserHeaderLabel();

            uhl.Longitude = ReadGeoAngle(br, 3, 2);
            uhl.Latitude = ReadGeoAngle(br, 3, 2);
            uhl.LonInterval = ReadInterval(br);
            uhl.LatInterval = ReadInterval(br);

            char[] accuracy = br.ReadChars(4);
            char[] classification = br.ReadChars(3);
            char[] uniqueRef = br.ReadChars(12);

            uhl.Accuracy = new string(accuracy);
            uhl.Classification = new string(classification);
            uhl.UniqueRef = new string(uniqueRef);

            uhl.LongitudeLines = ReadInt(br, 4);
            uhl.LatitudePoints = ReadInt(br, 4);
            uhl.MultipleAccuracy = br.ReadChar() == '1';
            char[] reserved = br.ReadChars(24);

            return uhl;
        }
Beispiel #6
0
        public FruaGameData GetGameData()
        {
            var data = new FruaGameData();

            using (var stream = new FileStream(_fullPath, FileMode.Open, FileAccess.Read))
            {
                using (var reader = new BinaryReader(stream))
                {
                    data.Name = new string(reader.ReadChars(32)).RemoveNulls();
                    data.StartingXp = reader.ReadInt32();
                    data.StartingPp = reader.ReadInt32();
                    data.StartingGems = reader.ReadInt32();
                    data.StartingJewelry = reader.ReadInt32();
                    data.StartingModule = reader.ReadByte();
                    data.StartingTown = reader.ReadByte();
                    data.StartingEquipment = reader.ReadByte();

                    reader.ReadByte(); // unused or unknown byte

                    for (int i = 0; i < 8; i++)
                    {
                        data.Keys.Add(new string(reader.ReadChars(16)).RemoveNulls());
                    }

                    for (int i = 0; i < 12; i++)
                    {
                        data.Items.Add(new string(reader.ReadChars(16)).RemoveNulls());
                    }

                    data.Password = new string(reader.ReadChars(15)).RemoveNulls();
                }
            }

            return data;
        }
Beispiel #7
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="file">Path to the DBM module to open.</param>
        public DbmReader(string file)
        {
            using (var dbm = new BinaryReader(File.OpenRead(file)))
            {
                // Header
                HeaderID = new string(dbm.ReadChars(4));

                // Skip to module name. Also cut off any padded bytes.
                dbm.BaseStream.Position = 0x10;
                string modName = new string(dbm.ReadChars(44));
                ModuleName = modName.Substring(0, modName.LastIndexOf('\0'));

                // Number of instruments.
                dbm.BaseStream.Position = NameChunkOffset + NameChunkSize + 8; // + 8 is to skip over the chunk name and length indicators.
                NumInstruments = BitConverter.IsLittleEndian ? dbm.ReadInt16()>>8 : dbm.ReadInt16();

                // Number of samples
                dbm.BaseStream.Position = NameChunkOffset + NameChunkSize + 10;
                NumSamples = BitConverter.IsLittleEndian ? dbm.ReadInt16()>>8 : dbm.ReadInt16();

                // Number of songs.
                dbm.BaseStream.Position = NameChunkOffset + NameChunkSize + 12;
                NumSongs = BitConverter.IsLittleEndian ? dbm.ReadInt16()>>8 : dbm.ReadInt16();

                // Number of patterns
                dbm.BaseStream.Position = NameChunkOffset + NameChunkSize + 14;
                NumPatterns = BitConverter.IsLittleEndian ? dbm.ReadInt16()>>8 : dbm.ReadInt16();

                // Number of channels
                dbm.BaseStream.Position = NameChunkOffset + NameChunkSize + 16;
                NumChannels = BitConverter.IsLittleEndian ? dbm.ReadInt16()>>8 : dbm.ReadInt16();
            }
        }
Beispiel #8
0
 public FsaNajka(Stream stream, bool leaveOpen = false)
 {
     using (var file = new BinaryReader(stream, Encoding.UTF8, leaveOpen))
     {
         if (new string(file.ReadChars(4)) != "@naj")
             throw new Exception("Invalid header");
         if (file.ReadByte() != 1)
             throw new Exception("Invalid version");
         _type = file.ReadByte();
         _id2Char = file.ReadChars(file.ReadByte());
         _tree = file.ReadBytes((int)(file.BaseStream.Length - file.BaseStream.Position));
     }
     _id2ConvertedChar = new char[4][];
     _id2ConvertedChar[0] = _id2Char;
     _id2ConvertedChar[1] = new char[_id2Char.Length];
     _id2ConvertedChar[2] = new char[_id2Char.Length];
     _id2ConvertedChar[3] = new char[_id2Char.Length];
     for (var i = 0; i < _id2Char.Length; i++)
     {
         _id2ConvertedChar[1][i] = char.ToLowerInvariant(_id2Char[i]);
         _id2ConvertedChar[2][i] = _id2Char[i].RemoveDiacritics();
         _id2ConvertedChar[3][i] = char.ToLowerInvariant(_id2ConvertedChar[2][i]);
     }
     _nodePrefix = SinkTo(0, '!');
     _nodePostfix = SinkTo(0, '^');
 }
        public TextureArchive[] ReadTextures(BinaryReader pacStream)
        {
            int nfiles = pacStream.ReadInt32();
            pacStream.ReadBytes(12); //The rest of the header. Not important...

            var textures = new TextureArchive[nfiles];
            for (var i = 0; i < nfiles; i++)
            {
                var texture = new TextureArchive();
                texture.alignedstring = new string(pacStream.ReadChars(16));

                texture.extension = new string(pacStream.ReadChars(4));
                texture.size = pacStream.ReadInt32();
                texture.offset = pacStream.ReadInt32();
                pacStream.ReadBytes(4);

                var pos = pacStream.BaseStream.Position;
                pacStream.BaseStream.Position = texture.offset;
                texture.stream = pacStream.ReadBytes(texture.size);
                pacStream.BaseStream.Position = pos;
                textures[i] = texture;
            }

            return textures;
        }
Beispiel #10
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;
            }
        }
Beispiel #11
0
    public void Read(System.IO.BinaryReader r)
    {
        int maxStringSize = 30;

        char[] chars;
        int    stringEnd;
        string stringValue;

        m_Price      = r.ReadDouble();
        m_PagesCount = r.ReadInt32();

        // read type of notebook
        chars     = r.ReadChars(maxStringSize);
        stringEnd = Array.IndexOf(chars, '\0');
        if (stringEnd == 0)
        {
            stringValue = null;
            return;
        }
        stringValue = new String(chars, 0, stringEnd);
        m_Type      = stringValue;

        // read page size, ex: B5, A4 etc.
        chars     = r.ReadChars(maxStringSize);
        stringEnd = Array.IndexOf(chars, '\0');
        if (stringEnd == 0)
        {
            stringValue = null;
            return;
        }
        stringValue = new String(chars, 0, stringEnd);
        m_PageSize  = stringValue;
        m_HardCover = r.ReadBoolean();
    }
Beispiel #12
0
        public BIF_KEY(String filename)
        {
            BinaryReader br = new BinaryReader(new FileStream(filename, FileMode.Open));

            signature = br.ReadChars(4);
            version = br.ReadChars(4);

            FILETABLE_ENTRIES = br.ReadUInt32();
            KEYTABLE_ENTRIES = br.ReadUInt32();
            br.ReadBytes(4);

            FILETABLE_OFFSET = br.ReadUInt32();
            KEYTABLE_OFFSET = br.ReadUInt32();
            BUILD_YEAR += br.ReadUInt32();
            BUILD_DAY = br.ReadUInt32();

               // MessageBox.Show(this+"");

            br.BaseStream.Seek(FILETABLE_OFFSET, SeekOrigin.Begin);

            for (int i = 0; i < FILETABLE_ENTRIES; i++)
            {
                FILETABLE.Add(new BIF_FILETABLE_ENTRY(br));
            }

            br.BaseStream.Seek(KEYTABLE_OFFSET, SeekOrigin.Begin);

            for (int i = 0; i < KEYTABLE_ENTRIES; i++)
            {
                BIF_KEYTABLE_ENTRY key = new BIF_KEYTABLE_ENTRY(br);
                FILETABLE[(int)key.ResourceIdx].ownedResources.Add(key);
            }

            br.Close();
        }
Beispiel #13
0
        public wavefile(FileStream file)
        {
            BinaryReader binRead = new BinaryReader(file);

            //head data
            ChunkID =  binRead.ReadChars(4);
            ChunkSize = binRead.ReadInt32();
            Format = binRead.ReadChars(4);
            Subchunk1ID = binRead.ReadChars(4);
            Subchunk1Size = binRead.ReadInt32();//in bytes
            AudioFormat = binRead.ReadInt16();
            NumChannels = binRead.ReadInt16();
            SampleRate = binRead.ReadInt32();//samples per second?
            ByteRate = binRead.ReadInt32();
            BlockAlign = binRead.ReadInt16();
            BitsPerSample = binRead.ReadInt16();
            Subchunk2ID = binRead.ReadChars(4);
            Subchunk2Size = binRead.ReadInt32();//in bytes

            int numSamples = Subchunk2Size / (BitsPerSample / 8);
            data = new byte[numSamples];
            wave = new float[numSamples];

            data = binRead.ReadBytes(numSamples);

            for (int i = 0; i < numSamples; i++)
            {
                wave[i] = ((float)data[i] - 128) / 128;
            }
        }
Beispiel #14
0
    public void Read(System.IO.BinaryReader r)
    {
        int maxStringSize = 30;

        char[] chars;
        int    stringEnd;
        string stringValue;

        m_Price = r.ReadDouble();

        // read color
        chars     = r.ReadChars(maxStringSize);
        stringEnd = Array.IndexOf(chars, '\0');
        if (stringEnd == 0)
        {
            stringValue = null;
            return;
        }
        stringValue = new String(chars, 0, stringEnd);
        m_Color     = stringValue;

        // read quality
        chars     = r.ReadChars(maxStringSize);
        stringEnd = Array.IndexOf(chars, '\0');
        if (stringEnd == 0)
        {
            stringValue = null;
            return;
        }
        stringValue = new String(chars, 0, stringEnd);
        m_Quality   = stringValue;
    }
Beispiel #15
0
        /// <summary>
        /// Creates a new entity that was embedded next in the stream
        /// </summary>
        /// <param name="stream">The System.IO.BinaryReader to use.</param>
        public Entity(BinaryReader stream)
        {
            X = stream.ReadInt16();
            Y = stream.ReadInt16();
            Layer = stream.ReadInt16();
            Scripts = new List<string>();
            Type = (EntityType)stream.ReadInt16();
            stream.ReadBytes(8);

            short len;
            if (Type == EntityType.Person)
            {
                len = stream.ReadInt16();
                Name = new string(stream.ReadChars(len));
                len = stream.ReadInt16();
                Spriteset = new string(stream.ReadChars(len));
                int scripts = stream.ReadInt16();

                // read the person script data
                for (int i = 0; i < scripts; ++i)
                {
                    len = stream.ReadInt16();
                    Scripts.Add(new string(stream.ReadChars(len)));
                }

                stream.ReadBytes(16); // reserved
                _graphic = new Bitmap(Properties.Resources.person);
            }
            else
            {
                len = stream.ReadInt16();
                Function = new string(stream.ReadChars(len));
                _graphic = new Bitmap(Properties.Resources.trigger);
            }
        }
Beispiel #16
0
        protected void LoadDirectoriesFromStream( BinaryReader reader )
        {
            Directories = new List<DirectoryEntry>();

            while( reader.PeekChar() != INT_RecordSeparator )
            {
                var entry = CreateDirectoryObject();
                char[] buffer = reader.ReadChars( Leader.SizeFieldTag );
                string tag = new string( buffer );
                if( tag == "0000" )
                    entry.Tag = DirectoryDataType.Filename;
                else if( tag == "0001" )
                    entry.Tag = DirectoryDataType.DDFRecordIdentifier;
                else
                    entry.Tag = (DirectoryDataType)Enum.Parse( typeof( DirectoryDataType ), tag );
                if( entry.Tag == DirectoryDataType.Unknown )
                    throw new InvalidDataException( String.Format("Unknown tag {0}", tag) );
                buffer = reader.ReadChars( Leader.SizeFieldLength );
                entry.Length = int.Parse( new string( buffer ) );
                buffer = reader.ReadChars( Leader.SizeFieldPos );
                entry.Position = int.Parse( new string( buffer ) );
                Directories.Add( entry );
            }
            reader.Read();
        }
Beispiel #17
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="path">Path to an IT module</param>
        public ITReader(string path)
        {
            using (var br = new BinaryReader(File.OpenRead(path)))
            {
                HeaderID = new string(br.ReadChars(4));
                SongName = new string(br.ReadChars(26));
                PatternHighlightInfo = br.ReadInt16();

                // Totals
                TotalOrders      = br.ReadInt16();
                TotalInstruments = br.ReadInt16();
                TotalSamples     = br.ReadInt16();
                TotalPatterns    = br.ReadInt16();

                // Tracker related
                CreatedWithTracker    = br.ReadInt16();
                CompatibleWithTracker = br.ReadInt16();

                // Flags
                short flag = br.ReadInt16();
                IsStereo                = ((flag &  1) != 0);
                HasVol0MixOptimizations = ((flag &  2) != 0);
                UsesInstruments         = ((flag &  4) != 0);
                SlideType               = ((flag &  8) != 0) ? SlideTypes.Linear : SlideTypes.Amiga;
                UsesOldEffects          = ((flag & 16) != 0);
                LinkEffectMemory        = ((flag & 32) != 0);
                UsesMidiPitchController = ((flag & 64) != 0);

                // Special flags
                short special = br.ReadInt16();
                HasSongMessage = ((special & 1) != 0);

                // Volume and Tempo related stuff
                GlobalVolume      = br.ReadByte();
                MixVolume         = br.ReadByte();
                InitialSpeed      = br.ReadByte();
                InitialTempo      = br.ReadByte();
                PanningSeparation = br.ReadByte();
                PitchWheelDepth   = br.ReadByte();

                // Song message
                short messageLen = br.ReadInt16();
                int messageOffset = br.ReadInt32();
                br.BaseStream.Position = messageOffset;
                if (HasSongMessage)
                    SongMessage = new string(br.ReadChars(messageLen)).Replace((char) 0xD, '\n');
                else
                    SongMessage = "N/A";

                // Channel related
                TotalUsedChannels = GetTotalUsedChannels(br);
                ChannelPanning    = GetChannelPanning(br);
                ChannelVolumes    = GetChannelVolumes(br);

                // Parsing
                ParseInstruments(br);
                ParseSamples(br);
            }
        }
Beispiel #18
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="path">Path to the PSF file</param>
        public PsfReader(string path)
        {
            using (var fs = new BinaryReader(File.OpenRead(path)))
            {
                // Header ID
                HeaderID = new string(fs.ReadChars(3));

                // Skip version byte (don't care)
                fs.BaseStream.Position += 1;

                // Reserved area length and compressed data length
                int resLen  = fs.ReadInt32();
                int dataLen = fs.ReadInt32();

                // CRC32 of the data
                CRC32 = fs.ReadUInt32();

                // Skip those lengths, we don't read any of this.
                fs.BaseStream.Position += (resLen + dataLen);

                // Check if we have any metadata, and read it if we do.
                bool endOfStream = (fs.BaseStream.Position == fs.BaseStream.Length);
                if (!endOfStream && new string(fs.ReadChars(5)) == "[TAG]")
                {
                    // Now read in the metadata
                    this.tag = new string(fs.ReadChars((int)(fs.BaseStream.Length - fs.BaseStream.Position)));

                    // Check for "_lib[n]" tags
                    ReferencedLibs = ParseIncludedLibs();

                    // Actual tag metadata
                    Artist     = GetInfo("artist=");
                    Game       = GetInfo("game=");
                    SongTitle  = GetInfo("title=");
                    Genre      = GetInfo("genre=");
                    Copyright  = GetInfo("copyright=");
                    Year       = GetInfo("year=");
                    Comment    = GetInfo("comment=");
                    XSFRipper  = GetXSFRipper(path);
                    Volume     = GetInfo("volume=");
                    Length     = GetInfo("length=");
                    FadeLength = GetInfo("fade=");
                }
                else
                {
                    Artist     = "N/A";
                    Game       = "N/A";
                    SongTitle  = "N/A";
                    Genre      = "N/A";
                    Copyright  = "N/A";
                    Year       = "N/A";
                    Comment    = "N/A";
                    XSFRipper  = "N/A";
                    Volume     = "N/A";
                    Length     = "N/A";
                    FadeLength = "N/A";
                }
            }
        }
Beispiel #19
0
        public override void Read(string fileIn)
        {
            nclr = new sNCLR();

            BinaryReader br = new BinaryReader(File.OpenRead(fileIn));

            // Generic header
            nclr.header.id = br.ReadChars(4);
            nclr.header.endianess = br.ReadUInt16();
            if (nclr.header.endianess == 0xFFFE)
                nclr.header.id.Reverse<char>();
            nclr.header.constant = br.ReadUInt16();
            nclr.header.file_size = br.ReadUInt32();
            nclr.header.header_size = br.ReadUInt16();
            nclr.header.nSection = br.ReadUInt16();

            // PLTT section
            TTLP pltt = new TTLP();

            pltt.ID = br.ReadChars(4);
            pltt.length = br.ReadUInt32();
            pltt.depth = (ColorFormat)br.ReadUInt16();
            pltt.unknown1 = br.ReadUInt16();
            pltt.unknown2 = br.ReadUInt32();

            pltt.pal_length = br.ReadUInt32();
            if (pltt.pal_length == 0 || pltt.pal_length > pltt.length)
                pltt.pal_length = pltt.length - 0x18;

            uint colors_startOffset = br.ReadUInt32();
            pltt.num_colors = (uint)((pltt.depth == ColorFormat.colors16) ? 0x10 : 0x100);
            if (pltt.pal_length / 2 < pltt.num_colors)
                pltt.num_colors = pltt.pal_length / 2;
            pltt.palettes = new Color[pltt.pal_length / (pltt.num_colors * 2)][];

            br.BaseStream.Position = 0x18 + colors_startOffset;
            for (int i = 0; i < pltt.palettes.Length; i++)
                pltt.palettes[i] = Actions.BGR555ToColor(br.ReadBytes((int)pltt.num_colors * 2));

            nclr.pltt = pltt;

            // PMCP section
            if (nclr.header.nSection == 1 || br.BaseStream.Position >= br.BaseStream.Length)
                goto End;

            PMCP pmcp = new PMCP();
            pmcp.ID = br.ReadChars(4);
            pmcp.blockSize = br.ReadUInt32();
            pmcp.unknown1 = br.ReadUInt16();
            pmcp.unknown2 = br.ReadUInt16();
            pmcp.unknown3 = br.ReadUInt32();
            pmcp.first_palette_num = br.ReadUInt16();

            nclr.pmcp = pmcp;

            End:
            br.Close();
            Set_Palette(pltt.palettes, pltt.depth, true);
        }
Beispiel #20
0
			protected void Read(Stream stream)
			{
				BinaryReader rdr = new BinaryReader(stream);
				Next = (IntPtr) rdr.ReadInt32();
				IpAddress = new string(rdr.ReadChars(0x10)).TrimEnd('\0');
				IpMask = new string(rdr.ReadChars(0x10)).TrimEnd('\0');
				Context = rdr.ReadUInt32();
			}
 public GFFHeader(BinaryReader file)
 {
     _magicNumber = new String(file.ReadChars(4));
     _versionNumber = new String(file.ReadChars(4));
     _targetPlatform = new String(file.ReadChars(4));
     _fileType = new String(file.ReadChars(4));
     _fileVersion = new String(file.ReadChars(4));
     _structCount = file.ReadUInt32();
     _dataOffset = file.ReadUInt32();
 }
        public virtual void Read(BinaryReader stream)
        {
            //	Read the data.
            id = new string(stream.ReadChars(9));
            version = new string(stream.ReadChars(6));
            dataMode = stream.ReadChar();
            bitFormat = new string(stream.ReadChars(2));

            //	Skip past the pad and newline, 14 chars.
            stream.ReadChars(14);
        }
Beispiel #23
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("usage: wavextract <filename>");
                return;
            }
            BinaryReader reader;
            try
            {
                reader = new BinaryReader(new FileStream(args[0], FileMode.Open), Encoding.ASCII);
            } catch (FileNotFoundException e)
            {
                Console.WriteLine("file not found.");
                return;
            }
            Directory.CreateDirectory("wav_output");

            int num_files = 0;

            while (true)
            {
                try
                {
                    long position = reader.BaseStream.Position;
                    if (reader.ReadByte() != 0x52 || new string(reader.ReadChars(3)) != "IFF")
                        continue;
                    int chunk_size = reader.ReadInt32();
                    if (new string(reader.ReadChars(4)) == "WAVE")
                    {
                        reader.BaseStream.Position = position;
                        byte[] wav = reader.ReadBytes(chunk_size + 8);

                        Console.WriteLine("output/{0}.wav", position.ToString("X"));
                        BinaryWriter writer =
                            new BinaryWriter(new FileStream(@"wav_output\" + position.ToString("X") + ".wav", FileMode.Create),
                                             Encoding.ASCII);
                        num_files++;
                        writer.Write(wav);
                        writer.Flush();
                        writer.Close();
                    }
                }
                catch (EndOfStreamException)
                {
                    if (num_files == 0)
                    {
                        Directory.Delete("wav_output");
                    }
                    Console.WriteLine("Done! extracted {0} files", num_files);
                    return;
                }
            }
        }
Beispiel #24
0
        public WavAudioSource(Stream file, bool streaming = true)
        {
            Streaming = streaming;

            _fileStream = file;
            _reader = new BinaryReader(file);

            if (new string(_reader.ReadChars(4)) != "RIFF")
                throw new InvalidDataException("Specified stream is not a wave file.");

            int chunkSize = _reader.ReadInt32();

            if (new string(_reader.ReadChars(4)) != "WAVE")
                throw new InvalidDataException("Specified stream is not a wave file");
            if (new string(_reader.ReadChars(4)) != "fmt ")
                throw new NotSupportedException("Specified wave format is not supported.");

            _formatChunkSize = _reader.ReadInt32();
            _audioFormat = _reader.ReadInt16();
            if (_audioFormat != 1)
                throw new NotSupportedException("Compressed WAV files are not supported.");

            _numChannels = _reader.ReadInt16();
            _sampleRate = _reader.ReadInt32();
            _byteRate = _reader.ReadInt32();
            _blockAlign = _reader.ReadInt16();
            _bitsPerSample = _reader.ReadInt16();

            if (new string(_reader.ReadChars(4)) != "data")
                throw new InvalidDataException("Specified wave format is not supported.");

            _dataChunkSize = _reader.ReadInt32();

            if(_numChannels == 2)
            {
                if (_bitsPerSample == 8)
                    _alFormat = ALFormat.Stereo8;
                else
                    _alFormat = ALFormat.Stereo16;
            }
            else
            {
                if (_bitsPerSample == 8)
                    _alFormat = ALFormat.Mono8;
                else
                    _alFormat = ALFormat.Mono16;
            }

            _dataStart = (int)_reader.BaseStream.Position;

            if (!Streaming)
                _data = _reader.ReadBytes((int)_reader.BaseStream.Length);
        }
Beispiel #25
0
 public bool Read(BinaryReader BR)
 {
     try
     {
         this.Flag_ = BR.ReadByte();
         if (this.Flag_ != 0x91 && this.Flag_ != 0xA1 && this.Flag_ != 0xB1)
         {
             // Accuracy unknown
             this.Clear();
             return false;
         }
         // Assumes that BR is set to ASCII encoding
         this.Category_ = new string(BR.ReadChars(8)).TrimEnd(' ');
         this.ID_ = new string(BR.ReadChars(8)).TrimEnd(' ');
         // Read BITMAPINFO structure length
         if (BR.ReadUInt32() != 40)
         {
             this.Clear();
             return false;
         }
         // Read BITMAPINFO structure
         this.Width_ = BR.ReadInt32();
         this.Height_ = BR.ReadInt32();
         this.Planes_ = BR.ReadUInt16();
         this.BitCount_ = BR.ReadUInt16();
         this.Compression_ = BR.ReadUInt32();
         this.ImageSize_ = BR.ReadUInt32();
         this.HorizontalResolution_ = BR.ReadUInt32();
         this.VerticalResolution_ = BR.ReadUInt32();
         this.UsedColors_ = BR.ReadUInt32();
         this.ImportantColors_ = BR.ReadUInt32();
         // Sanity check on the values in the structure
         if (this.Width_ < 0 || this.Width_ > 16 * 1024 || this.Height_ < 0 || this.Height_ > 16 * 1024 || this.Planes_ != 1)
         {
             this.Clear();
             return false;
         }
         if (this.Flag_ == 0xA1) // Assume DirectX texture
         {
             this.ReadDXT(BR);
         }
         else if (this.Flag_ == 0x91 || this.Flag_ == 0xB1) // Bitmap
         {
             this.ReadBitmap(BR);
         }
     }
     catch
     {
         this.Clear();
     }
     return (this.Image_ != null);
 }
Beispiel #26
0
        public WaveFile(Stream stream)
        {
            if (stream == null)
                throw new ArgumentNullException ("s");

                var reader = new BinaryReader (stream);
                //RIFF check
                if (new String (reader.ReadChars (4)) != "RIFF")
                    new InvalidDataException ("Not a RIFF format file.");

                int riff_chunk_size = reader.ReadInt32 ();

                //WAVE check
                if (new String (reader.ReadChars (4)) != "WAVE")
                    new InvalidDataException ("Not a WAVE format file.");

                //FMT  check
                if (new String (reader.ReadChars (4)) != "fmt ")
                    new InvalidDataException ("Doesn't have fmt chunk.");

                int format_chunk_size = reader.ReadInt32 ();
                int audio_format = reader.ReadInt16 ();
                int num_channels = reader.ReadInt16 ();
                int sample_rate = reader.ReadInt32 ();
                int byte_rate = reader.ReadInt32 ();
                int block_align = reader.ReadInt16 ();
                int bits_per_sample = reader.ReadInt16 ();

                //data check
                if (new String (reader.ReadChars (4)) != "data")
                    new InvalidDataException ("Doesn't have data chunk");

                int data_chunk_size = reader.ReadInt32();

                this.channels = num_channels;
                this.bps = bits_per_sample;
                this.SampleRate = sample_rate;
                this.HeaderSize = reader.BaseStream.Position;
                this.DataBinary = reader;

                switch (channels) {
                case 1:
                    this.SoundFormat =
                        this.bps == 8 ? ALFormat.Mono8 : ALFormat.Mono16;
                    break;
                case 2:
                    this.SoundFormat = this.bps == 8 ? ALFormat.Stereo8 : ALFormat.Stereo16;
                    break;
                default:
                    throw new NotSupportedException ("The specified sound format is not supported.");
                }
        }
Beispiel #27
0
        /* Lifted from example code in OpenTK
         * See: https://github.com/opentk/opentk/blob/develop/Source/Examples/OpenAL/1.1/Playback.cs */
        private static byte[] LoadWave(Stream stream, out int channels, out int bits, out int rate)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

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

                /*int riff_chunck_size = */
                reader.ReadInt32();

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

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

                /* int format_chunk_size = */
                reader.ReadInt32();
                /* int audio_format = */
                reader.ReadInt16();
                int num_channels = reader.ReadInt16();
                int sample_rate = reader.ReadInt32();
                /* int byte_rate = */
                reader.ReadInt32();
                /* int block_align = */
                reader.ReadInt16();
                int bits_per_sample = reader.ReadInt16();

                string data_signature = new string(reader.ReadChars(4));
                if (data_signature != "data")
                    throw new NotSupportedException("Specified wave file is not supported.");

                /* int data_chunk_size = */
                reader.ReadInt32();

                channels = num_channels;
                bits = bits_per_sample;
                rate = sample_rate;

                return reader.ReadBytes((int)reader.BaseStream.Length);
            }
        }
Beispiel #28
0
        public string ReadBuffer()
        {
            using (BinaryReader reader = new BinaryReader(StreamWAV))
            {
                Header.FileTypeID = reader.ReadChars(4);
                if (!Header.FileTypeID.SequenceEqual("RIFF"))
                {
                    Passed = false;
                    return "Format non conforme du fichier";
                }

                Header.FileLenght = reader.ReadInt32();

                Header.MediaTypedID = reader.ReadChars(8);
                if (!Header.MediaTypedID.SequenceEqual("WAVEfmt "))
                {
                    Passed = false;
                    return "Format non conforme du fichier";
                }

                Header.ChunkSizeFormat = reader.ReadInt32();
                Header.FormatTag = Math.Abs(reader.ReadInt16());
                Header.Channels = reader.ReadInt16();
                Header.Frequency = reader.ReadInt32();
                Header.AverageBytesPerSec = reader.ReadInt32();
                Header.BlockAlign = reader.ReadInt16();
                Header.BitsPerSample = reader.ReadInt16();

                if (Header.ChunkSizeFormat > 16)
                {
                    int ExtraSize = reader.ReadInt16();
                    var ExtraData = reader.ReadBytes(ExtraSize);
                }

                Header.ChunkIDData = reader.ReadChars(4);
                if (!Header.ChunkIDData.SequenceEqual("data"))
                {
                    Passed = false;
                    return "Format non conforme du fichier";
                }

                Header.ChunkSizeData = reader.ReadInt32();

                Buffer = reader.ReadBytes(Header.ChunkSizeData);

                reader.Close();

                Passed = true;
                StreamWAV.Close();
                return "Analyse du fichier réussi";
            }
        }
Beispiel #29
0
			protected void Read(Stream stream)
			{
				BinaryReader rdr = new BinaryReader(stream);
				HostName = new string(rdr.ReadChars(MAX_HOSTNAME_LEN + 4)).TrimEnd('\0');
				DomainName = new string(rdr.ReadChars(MAX_DOMAIN_NAME_LEN + 4)).TrimEnd('\0');
				CurrentDnsServer = (IntPtr) rdr.ReadInt32();
				DnsServerList.Add(new IpAddrString(stream));//TODO: get the rest of the servers in the list too
				NodeType = rdr.ReadUInt32();
				ScopeId = new string(rdr.ReadChars(MAX_SCOPE_ID_LEN + 4)).TrimEnd('\0');
				EnableRouting = rdr.ReadUInt32();
				EnableProxy = rdr.ReadUInt32();
				EnableDns = rdr.ReadUInt32();
			}
        public static WavFile ReadFile(string fileName)
        {
            //
            // Using .WAV file format from https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
            //

            WavFile wf = new WavFile();

            using (BinaryReader br = new BinaryReader(File.Open(fileName, FileMode.Open, FileAccess.Read)))
            {
                char[] id = br.ReadChars(4);

                if (!id.SequenceEqual(new char[] { 'R', 'I', 'F', 'F' }))
                    throw new FormatException("Missing RIFF header");

                br.ReadUInt32(); // chunk size

                id = br.ReadChars(4);

                if (!id.SequenceEqual(new char[] { 'W', 'A', 'V', 'E' }))
                    throw new FormatException("Only WAVE format currently supported");

                id = br.ReadChars(4);

                if (!id.SequenceEqual(new char[] { 'f', 'm', 't', ' ' }))
                    throw new FormatException("Missing 'fmt ' sub-chunk");

                int size = (int)br.ReadUInt32(); // sub-chunk size

                if (size != 16)
                    throw new FormatException("Unexpected format size");

                wf.AudioFormat = br.ReadUInt16();
                wf.NumChannels = br.ReadUInt16();
                wf.SampleRate = br.ReadUInt32();
                wf.ByteRate = br.ReadUInt32();
                wf.BlockAlign = br.ReadUInt16();
                wf.BitsPerSample = br.ReadUInt16();

                id = br.ReadChars(4);

                if (!id.SequenceEqual(new char[] { 'd', 'a', 't', 'a' }))
                    throw new FormatException("Missing 'data' sub-chunk");

                size = (int)br.ReadUInt32(); // sub-chunk size

                wf.Data = br.ReadBytes(size);
            }

            return wf;
        }
Beispiel #31
0
        public static SoundBuffer Load(Stream s)
        {
            BinaryReader br = new BinaryReader(s);
            var magic = new String(br.ReadChars(4));
            if (magic != "RIFF")
                throw new FormatException("Invalid WAV file");

            UInt32 size = br.ReadUInt32();
            var id = new String(br.ReadChars(4));
            if (id != "WAVE")
                throw new FormatException("Invalid WAV file");

            var fmtSig = new String(br.ReadChars(4));
            if (fmtSig != "fmt ")
                throw new FormatException("Format Chunk in WAV file not found");

            var fmtChunckSize = br.ReadInt32();
            var audioFormat = br.ReadInt16();
            var channels = br.ReadInt16();
            var sampleRate = br.ReadInt32();
            var byteRate = br.ReadInt32();
            var blockAlign = br.ReadInt16();
            var bitsPerSample = br.ReadInt16(); ;

            var dataSig = new String(br.ReadChars(4));
            if (dataSig != "data")
            {
                throw new FormatException("Data chunk in WAV file not found");
            }

            var dataChunckSize = br.ReadInt32();

            var data = br.ReadBytes(dataChunckSize);
            OpenTK.Audio.OpenAL.ALFormat format;

            if (channels == 1 && bitsPerSample == 8)
                format = OpenTK.Audio.OpenAL.ALFormat.Mono8;
            else if (channels == 1 && bitsPerSample == 16)
                format = OpenTK.Audio.OpenAL.ALFormat.Mono16;
            else if (channels == 2 && bitsPerSample == 8)
                format = OpenTK.Audio.OpenAL.ALFormat.Stereo8;
            else if (channels == 2 && bitsPerSample == 16)
                format = OpenTK.Audio.OpenAL.ALFormat.Stereo16;
            else
                throw new Exception("Unsupported audio format");

            SoundBuffer sb = new SoundBuffer();
            sb.BufferData(data, format, sampleRate);
            return sb;
        }
Beispiel #32
0
 public int getWafeFormat(BinaryReader br)
 {
     UInt32 sz = findChunk(true, "hdrl", br.BaseStream.Length, br);
     if (sz ==0)
         throw new Exception("AVI header not found");
     int res = -1;
     int cstream = 0;
     long epos=br.BaseStream.Position+sz;
     while(br.BaseStream.Position<epos && res==-1)
     {
         string s = new String(br.ReadChars(4));
         sz = br.ReadUInt32();
         long x=br.BaseStream.Position+sz;
         if (s == "LIST")
         {
             s = new String(br.ReadChars(4));
             if (s == "strl")
             {
                 long xx = br.BaseStream.Position;
                 UInt32 xsz = findChunk(false, "strh", br.BaseStream.Position + sz, br);
                 if (xsz >0)
                 {
                     s = new string(br.ReadChars(4));
                     if (s == "auds")
                     {
                         br.BaseStream.Position = xx;
                         xsz = findChunk(false, "strf", br.BaseStream.Position + sz, br);
                         if (xsz==16)
                         {
                             UInt16 fmt=br.ReadUInt16();
                             if (fmt != 1)
                                 throw new Exception("Unknown wave format");
                             wf.FormatTag = WaveFormatTag.Pcm;
                             wf.Channels = br.ReadInt16();
                             wf.SamplesPerSecond = br.ReadInt32();
                             wf.AverageBytesPerSecond = br.ReadInt32();
                             wf.BlockAlign = br.ReadInt16();
                             wf.BitsPerSample = br.ReadInt16();
                             res = cstream;
                         }
                     }
                 }
                 cstream++;
             }
         }
         br.BaseStream.Position = x;
     }
     return res;
 }
Beispiel #33
0
 public void readPlayerOldFormat(System.IO.BinaryReader dataReader)
 {
     this.players = new PlayerInfo[dataReader.ReadInt32()];
     for (int i = 0; i < this.players.Length; i++)
     {
         this.players[i] = new PlayerInfo();
         int    count = dataReader.ReadInt32();
         char[] value = dataReader.ReadChars(count);
         this.players[i].playerName = new string(value);
         count = dataReader.ReadInt32();
         char[] value2 = dataReader.ReadChars(count);
         this.players[i].championName = new string(value2);
         this.players[i].team         = dataReader.ReadUInt32();
         this.players[i].clientID     = dataReader.ReadInt32();
     }
 }
        //<Snippet1>
        // The binary layout is as follows:
        //    Bytes 0 - 19: string text, padded to the right with null characters
        //    Bytes 20+: Double value

        // using Microsoft.SqlServer.Server;
        public void Read(System.IO.BinaryReader r)
        {
            int maxStringSize = 20;

            char[] chars;
            int    stringEnd;
            string stringValue;
            double doubleValue;

            // Read the characters from the binary stream.
            chars = r.ReadChars(maxStringSize);

            // Find the start of the null character padding.
            stringEnd = Array.IndexOf(chars, '\0');

            if (stringEnd == 0)
            {
                stringValue = null;
                return;
            }

            // Build the string from the array of characters.
            stringValue = new String(chars, 0, stringEnd);

            // Read the double value from the binary stream.
            doubleValue = r.ReadDouble();

            // Set the object's properties equal to the values.
            this.StringValue = stringValue;
            this.DoubleValue = doubleValue;
        }
Beispiel #35
0
 public void Read(System.IO.BinaryReader r)
 {
     _null = r.ReadBoolean();
     if (!_null)
     {
         _text = new String(r.ReadChars(r.ReadInt32()));
     }
 }
 /// <summary>
 /// Reads an object of type <see cref="char[]"/> from the current stream
 /// and advances the stream position.
 /// This method reads directly from the underlying stream.
 /// </summary>
 /// <returns>object read from the stream</returns>
 public char[] ReadChars(int count)
 {
     if (reader == null)
     {
         reader = new BinaryReader(stream);
     }
     return(reader.ReadChars(count));
 }
    static int ReadChars(IntPtr L)
    {
        LuaScriptMgr.CheckArgsCount(L, 2);
        System.IO.BinaryReader obj = (System.IO.BinaryReader)LuaScriptMgr.GetNetObjectSelf(L, 1, "System.IO.BinaryReader");
        int arg0 = (int)LuaScriptMgr.GetNumber(L, 2);

        char[] o = obj.ReadChars(arg0);
        LuaScriptMgr.PushArray(L, o);
        return(1);
    }
Beispiel #38
0
        private static void ReadHeader(System.IO.BinaryReader reader)
        {
            var signature = reader.ReadChars(4);
            var length    = reader.ReadBigEndianUInt32();

            var format = reader.ReadBigEndianUInt16();
            var tracks = reader.ReadBigEndianUInt16();
            var ticks  = reader.ReadBigEndianUInt16();

            Song.Tracks       = new Song.Track[tracks];
            Song.TicksPerBeat = (int)ticks;
        }
Beispiel #39
0
        private static void ReadTrack(System.IO.BinaryReader reader, int track)
        {
            var signature = reader.ReadChars(4);
            var length    = reader.ReadBigEndianUInt32();

            var start = reader.BaseStream.Position;

            var events     = new List <Song.Event>();
            var lastStatus = (byte)0;

            while (true)
            {
                var delay  = reader.ReadQuantity();
                var status = reader.ReadByte();

                if ((status & 0x80) == 0)
                {
                    status = lastStatus;
                    reader.BaseStream.Seek(-1, System.IO.SeekOrigin.Current);
                }

                switch (status)
                {
                case 0xFF:
                    ReadMetaEvent(reader, track, (int)delay, events);
                    break;

                case 0xF0:
                    ReadSystemExclusiveEvent(reader, track);
                    break;

                default:
                    var e = ReadTrackEvent(reader, track, status);
                    e.Delay = (int)delay;

                    events.Add(e);
                    break;
                }

                lastStatus = status;

                if (reader.BaseStream.Position == start + length)
                {
                    break;
                }
            }

            Song.Tracks[track].Events = events.ToArray();
        }
Beispiel #40
0
 static public int ReadChars(IntPtr l)
 {
     try {
         System.IO.BinaryReader self = (System.IO.BinaryReader)checkSelf(l);
         System.Int32           a1;
         checkType(l, 2, out a1);
         var ret = self.ReadChars(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Beispiel #41
0
        public static object LoadKey(this DbColumnType keyType, io.BinaryReader reader)
        {
            switch (keyType)
            {
            case DbColumnType.Char:
                //
                return(reader.ReadChar());

            case DbColumnType.Byte:
                //
                return(reader.ReadByte());

            case DbColumnType.Int16:
                //
                return(reader.ReadInt16());

            case DbColumnType.Int32:
                //
                return(reader.ReadInt32());

            case DbColumnType.Int64:
                //
                return(reader.ReadInt64());

            case DbColumnType.Single:
                //
                return(reader.ReadSingle());

            case DbColumnType.Double:
                //
                return(reader.ReadDouble());

            case DbColumnType.Decimal:
                //
                return(reader.ReadDecimal());

            case DbColumnType.String:
                //
                var length = reader.ReadByte();
                var chars  = reader.ReadChars(length);
                return(new string(chars));

            default:
                return(null);
            }
        }
Beispiel #42
0
    public void Read(System.IO.BinaryReader r)
    {
        int maxStringSize = 10;

        char[] chars;
        string stringValue;

        // Read the characters from the binary stream.
        this.Id = r.ReadInt32();
        chars   = r.ReadChars(maxStringSize);


        // Build the string from the array of characters.
        stringValue = new String(chars, 0, chars.Length);

        // Set the object's properties equal to the values.
        this.Title = stringValue;
    }
Beispiel #43
0
        private void Mod_LoadEntityString(SDHeader header, ref CModel.SModel _SModel, ref System.IO.BinaryReader br)
        {
            if (header.lumps[LUMP_ENTITIES].filelen > MAX_MAP_ENTSTRING)
            {
                // entity string exceeds maximum
                _SModel.map_entitystring = null;
                return;
            }

            br.BaseStream.Seek(header.lumps[LUMP_ENTITIES].fileofs, System.IO.SeekOrigin.Begin);
            if (br.BaseStream.Position < (header.lumps[LUMP_ENTITIES].fileofs + header.lumps[LUMP_ENTITIES].filelen))
            {
                _SModel.map_entitystring = CShared.Com_ToString(br.ReadChars(header.lumps[LUMP_ENTITIES].filelen));
                _SModel.map_entitystring = _SModel.map_entitystring.Replace("\r", "").Replace("\n", "\r\n");
            }
            else
            {
                _SModel.map_entitystring = null;
            }
        }
Beispiel #44
0
    public void Read(System.IO.BinaryReader r)
    {
        int maxStringSize = 50;

        char[] chars;
        int    stringEnd;
        string stringValue;

        chars     = r.ReadChars(maxStringSize);
        stringEnd = Array.IndexOf(chars, '\0');
        if (stringEnd == 0)
        {
            stringValue = null;
            return;
        }
        stringValue = new String(chars, 0, stringEnd);
        string[] dane = stringValue.Split(",".ToCharArray());

        this._accountNr = dane[1];
        this._bankType  = dane[0];
    }
Beispiel #45
0
    public void Read(System.IO.BinaryReader r)
    {
        int maxStringSize = 20;

        char[] chars;
        int    stringEnd;
        string stringValue;

        m_Price   = r.ReadDouble();
        chars     = r.ReadChars(maxStringSize);
        stringEnd = Array.IndexOf(chars, '\0');
        if (stringEnd == 0)
        {
            stringValue = null;
            return;
        }
        stringValue = new String(chars, 0, stringEnd);
        m_Color     = stringValue;
        m_Length    = r.ReadInt32();
        m_Clickable = r.ReadBoolean();
    }
Beispiel #46
0
    public void Read(System.IO.BinaryReader r)
    {
        int maxStringSize = 50;

        char[] chars;
        int    stringEnd;
        string stringValue;

        chars     = r.ReadChars(maxStringSize);
        stringEnd = Array.IndexOf(chars, '\0');
        if (stringEnd == 0)
        {
            stringValue = null;
            return;
        }
        stringValue = new String(chars, 0, stringEnd);
        string[] data = stringValue.Split(",".ToCharArray());

        this._firm         = data[0];
        this._model        = data[1];
        this._serialNumber = data[2];
    }
Beispiel #47
0
    public void Read(System.IO.BinaryReader r)
    {
        int maxStringSize = 20;

        char[] chars;
        int    stringEnd;
        string stringValue;

        m_Price   = r.ReadDouble();
        chars     = r.ReadChars(maxStringSize);
        stringEnd = Array.IndexOf(chars, '\0');
        if (stringEnd == 0)
        {
            stringValue = null;
            return;
        }
        stringValue       = new String(chars, 0, stringEnd);
        m_Brand           = stringValue;
        m_Width           = r.ReadInt32();
        m_Height          = r.ReadInt32();
        m_DigitsDisplayed = r.ReadInt32();
    }
Beispiel #48
0
    public void Read(System.IO.BinaryReader r)
    {
        int maxStringSize = 50;

        char[] chars;
        int    stringEnd;
        string stringValue;

        chars     = r.ReadChars(maxStringSize);
        stringEnd = Array.IndexOf(chars, '\0');
        if (stringEnd == 0)
        {
            stringValue = null;
            return;
        }
        stringValue = new String(chars, 0, stringEnd);
        string[] dane = stringValue.Split(",".ToCharArray());

        this._city     = dane[2];
        this._street   = dane[0];
        this._nr       = Int32.Parse(dane[1]);
        this._postCode = Int32.Parse(dane[3]);
    }
Beispiel #49
0
    public void Read(System.IO.BinaryReader r)
    {
        int maxStringSize = 50;

        char[] chars;
        int    stringEnd;
        string stringValue;

        chars     = r.ReadChars(maxStringSize);
        stringEnd = Array.IndexOf(chars, '\0');
        if (stringEnd == 0)
        {
            stringValue = null;
            return;
        }
        stringValue = new String(chars, 0, stringEnd);
        string[] data = stringValue.Split(",".ToCharArray());

        this._surname = data[0];
        this._name    = data[1];
        this._sex     = data[2];
        this._pesel   = Int64.Parse(data[3]);
    }
Beispiel #50
0
        public static VoxelStruct ReadFromMagicaVoxel(System.IO.BinaryReader br)
        {
            VoxelStruct vs = new VoxelStruct();

            VectorInt4[] palette = null;
            Point[]      points  = null;

            string vox = new string(br.ReadChars(4));

            if (vox != "VOX ")
            {
                return(vs);
            }

            int version = br.ReadInt32();

            vs.version = version;
            VectorInt3 box       = new VectorInt3();
            bool       subsample = false;


            while (br.BaseStream.Position < br.BaseStream.Length)
            {
                // each chunk has an ID, size and child chunks
                string name   = new string(br.ReadChars(4));
                int    size   = br.ReadInt32();
                int    chunks = br.ReadInt32();
                // Debug.LogError (chunkName);
                // there are only 2 chunks we only care about, and they are SIZE and XYZI
                if (name == "MAIN")
                {
                    vs.main        = new VoxelStruct.Main();
                    vs.main.size   = size;
                    vs.main.name   = name;
                    vs.main.chunks = chunks;
                }
                if (name == "SIZE")
                {
                    box.x = br.ReadInt32();
                    box.y = br.ReadInt32();
                    box.z = br.ReadInt32();


                    vs.size        = new VoxelStruct.Size();
                    vs.size.size   = 12;
                    vs.size.name   = name;
                    vs.size.chunks = chunks;
                    vs.size.box    = box;

                    if (box.x > 32 || box.y > 32)
                    {
                        subsample = true;
                    }

                    br.ReadBytes(size - 4 * 3);
                }
                else if (name == "XYZI")
                {
                    int count = br.ReadInt32();
                    points = new Point[count];
                    for (int i = 0; i < points.Length; i++)
                    {
                        points [i] = VoxelFormater.CreatePoint(br, subsample);                         //new Data (stream, subsample);
                    }
                }
                else if (name == "RGBA")
                {
                    int n = size / 4;
                    palette = new VectorInt4[n];
                    for (int i = 0; i < n; i++)
                    {
                        byte r = br.ReadByte();
                        byte g = br.ReadByte();
                        byte b = br.ReadByte();
                        byte a = br.ReadByte();
                        palette[i].x = r;
                        palette[i].y = g;
                        palette[i].z = b;
                        palette[i].w = a;
                    }

                    vs.rgba         = new VoxelStruct.Rgba();
                    vs.rgba.size    = size;
                    vs.rgba.name    = name;
                    vs.rgba.chunks  = chunks;
                    vs.rgba.palette = palette;
                }
                else
                {
                    br.ReadBytes(size);                       // read any excess bytes
                }
            }
            vs.datas = CreateVoxelDatas(points, palette);
            return(vs);
        }
Beispiel #51
0
        /// <summary>
        /// ReadHeader
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private static WaveFileHeader ReadHeader(string fileName)
        {
            //Ergebnis
            WaveFileHeader header = new WaveFileHeader();

            //Wenn die Datei existiert
            if (File.Exists(fileName))
            {
                //Datei öffnen
                FileStream             fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                System.IO.BinaryReader rd = new System.IO.BinaryReader(fs, Encoding.UTF8);

                //Lesen
                if (fs.CanRead)
                {
                    //Chunk 1
                    header.RIFF       = rd.ReadChars(4);
                    header.RiffSize   = (uint)rd.ReadInt32();
                    header.RiffFormat = rd.ReadChars(4);

                    //Chunk 2
                    header.FMT              = rd.ReadChars(4);
                    header.FMTSize          = (uint)rd.ReadInt32();
                    header.FMTPos           = fs.Position;
                    header.AudioFormat      = (short)rd.ReadInt16();
                    header.Channels         = (short)rd.ReadInt16();
                    header.SamplesPerSecond = (uint)rd.ReadInt32();
                    header.BytesPerSecond   = (uint)rd.ReadInt32();
                    header.BlockAlign       = (short)rd.ReadInt16();
                    header.BitsPerSample    = (short)rd.ReadInt16();

                    //Zu Beginn von Chunk3 gehen
                    fs.Seek(header.FMTPos + header.FMTSize, SeekOrigin.Begin);

                    //Chunk 3
                    header.DATA     = rd.ReadChars(4);
                    header.DATASize = (uint)rd.ReadInt32();
                    header.DATAPos  = (int)fs.Position;

                    //Wenn nicht DATA
                    if (new String(header.DATA).ToUpper() != "DATA")
                    {
                        uint DataChunkSize = header.DATASize + 8;
                        fs.Seek(DataChunkSize, SeekOrigin.Current);
                        header.DATASize = (uint)(fs.Length - header.DATAPos - DataChunkSize);
                    }

                    //Payload einlesen
                    if (header.DATASize <= fs.Length - header.DATAPos)
                    {
                        header.Payload = rd.ReadBytes((int)header.DATASize);
                    }
                }

                //Schliessen
                rd.Close();
                fs.Close();
            }

            //Fertig
            return(header);
        }
Beispiel #52
0
        public void readFromFile(string path, bool withOutChunks)
        {
            this.relatedFileName = path;
            try
            {
                System.IO.FileStream   fileStream   = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fileStream);
                this.ThisLPRVersion = binaryReader.ReadInt32();
                if (this.ThisLPRVersion >= 0)
                {
                    int count = binaryReader.ReadInt32();
                    this.spectatorClientVersion = binaryReader.ReadChars(count);
                    if (this.ThisLPRVersion < 2)
                    {
                        this.gameId = (ulong)((long)binaryReader.ReadInt32());
                    }
                    else
                    {
                        this.gameId = binaryReader.ReadUInt64();
                    }
                    this.gameEndStartupChunkId    = binaryReader.ReadInt32();
                    this.gameStartChunkId         = binaryReader.ReadInt32();
                    this.gameEndChunkId           = binaryReader.ReadInt32();
                    this.gameEndKeyFrameId        = binaryReader.ReadInt32();
                    this.gameLength               = binaryReader.ReadInt32();
                    this.gameDelayTime            = binaryReader.ReadInt32();
                    this.gameClientAddLag         = binaryReader.ReadInt32();
                    this.gameChunkTimeInterval    = binaryReader.ReadInt32();
                    this.gameKeyFrameTimeInterval = binaryReader.ReadInt32();
                    //this.gameELOLevel = binaryReader.ReadInt32();
                    this.gameLastChunkTime     = binaryReader.ReadInt32();
                    this.gameLastChunkDuration = binaryReader.ReadInt32();
                    count                      = binaryReader.ReadInt32();
                    this.gamePlatform          = binaryReader.ReadChars(count);
                    count                      = binaryReader.ReadInt32();
                    this.observerEncryptionKey = binaryReader.ReadChars(count);
                    //count = binaryReader.ReadInt32();
                    //this.gameCreateTime = binaryReader.ReadChars(count);
                    //count = binaryReader.ReadInt32();
                    //this.gameStartTime = binaryReader.ReadChars(count);
                    //count = binaryReader.ReadInt32();
                    //this.gameEndTime = binaryReader.ReadChars(count);
                    if (this.ThisLPRVersion >= 3)
                    {
                        count           = binaryReader.ReadInt32();
                        this.lolVersion = binaryReader.ReadChars(count);
                    }
                    else
                    {
                        this.lolVersion = string.Empty.ToCharArray();
                    }
                    if (this.ThisLPRVersion >= 2)
                    {
                        this.hasResult = binaryReader.ReadBoolean();
                        if (this.ThisLPRVersion >= 4)
                        {
                            if (this.hasResult)
                            {
                                count = binaryReader.ReadInt32();
                                this.endOfGameStatsBytes = binaryReader.ReadBytes(count);
                                this.gameStats           = new EndOfGameStats(this.endOfGameStatsBytes);
                            }
                            if (binaryReader.ReadBoolean())
                            {
                                this.readPlayerOldFormat(binaryReader);
                            }
                        }
                        else
                        {
                            if (this.hasResult)
                            {
                                count = binaryReader.ReadInt32();
                                this.endOfGameStatsBytes = binaryReader.ReadBytes(count);
                                this.gameStats           = new EndOfGameStats(this.endOfGameStatsBytes);
                            }
                            else
                            {
                                this.readPlayerOldFormat(binaryReader);
                            }
                        }
                    }
                    else
                    {
                        this.readPlayerOldFormat(binaryReader);
                    }
                    if (!withOutChunks)
                    {
                        this.readChunks(binaryReader);
                    }

                    binaryReader.Close();
                    fileStream.Close();
                }
            }
            catch
            {
                this.IsBroken = true;
            }
        }
Beispiel #53
0
        private bool loadFileToDB(string filename)
        {
            log.writeLogWarning("====开始处理文件,预计处理时间1小时:" + filename);

            System.IO.FileStream   fs = null;
            System.IO.BinaryReader reader;
            //===============================
            //0:xDR_ID 一个会话生成一个xDR ID。>> 无用 >> ok
            //1:IMSI 用户IMSI(TBCD编码) >> 15位 >> ok
            //2:MSISDN 用户号码(TBCD编码)>> 手机号,13-??位 >> ok
            //3:Cell_ID UE所在小区的ECI >> 整数?>> 需要增加一个跳变次数
            //4:APN APN >> 需要入库至手机号表 >> ok
            //5:App_Type_Code 业务类型编码,参见附录D XDR类型编码定义 >> 要个编码表 >> 还没想好怎么弄???
            //6:Procedure_Start_Time TCP/ UDP流开始时间,UTC时间 - 毫秒 >> 需要解码时间
            //7:Procedure_End_Time TCP/ UDP流结束时间,UTC时间 - 毫秒 >> 需要解码时间
            //8:App_Type 应用大类—集团18种应用大类,参见《数据流量业务大类分类》 >> 要个编码表 >> 还没想好怎么弄???
            //9:App_Sub_type 应用小类 >> 要个编码规则 >> 还没想好怎么弄???
            //
            //10:USER_IPv4 终端用户的IPv4地址 >> 7-15长度
            //11:User_Port 用户的四层端口号 >> 谁是服务器,反向连接怎么表示?
            //12:L4_protocal L4协议类型:0:TCP;1:UDP >> 1位长度
            //13:App_Server_IP_IPv4  访问服务器的IPv4地址 >> 7-15位长度
            //14:App_Server_Port 访问的服务器的端口 >> 谁是服务器,反向连接怎么表示?
            //15:UL_Data 上行流量;单位:字节 >> 整数
            //16:DL_Data 下行流量;单位:字节 >> 整数
            //17:UL_IP_Packet    上行IP包数 >> 整数
            //18:DL_IP_Packet    下行IP包数 >> 整数
            //19:TCP_Try_Cnt TCP建链尝试次数,一次TCP流多次SYN的数值; 非TCP传输时,此字段填0 >> 整数
            //20:TCP_Link_flag   TCP连接状态指示;0:成功;1:失败 >> 255代表什么?
            //21:Talk_if_end 会话是否结束标志;1:结束 (用户中断)2:未结束   3:超时  4: 拆分会话的第一话单   5:结束 (服务端中断) >> 整数
            //===============================
            //                   0              1               2       3       4                             5       6           7           8  9   10             11    12 13              14   15   16 17 18 19 20  21
            //00008c10045a0e95c498,460041238803470,861064723883470,141986486,cmiotfz.sh.mnc004.mcc460.gprs,  100,1524588437627,1524588437683,21,8921,10.4.38.181,   0,    1, 114.114.114.114,0,   84,  84,1, 1, 0, 255,3
            //00008810545a3772ea0e,460027172840010,8613484491206,  242843531,temp.sn.mnc002.mcc460.gprs,     100,1524598898676,1524598913716,21,143, 100.6.132.46,  47680,0, 223.202.195.96, 443, 300, 0, 5, 0, 5, 1,  2
            //00008810545a3772ea00,460040096750197,861064851419087,7527307,  cmiotbyda.sn.mnc004.mcc460.gprs,100,1524598898656,1524598898695,8, 7549,10.246.119.29, 53661,0, 192.168.0.250,  5000,52,  52,1, 1, 0, 1,  2
            //00008810745a37722dd5,460008072539994,8613758069490,  28010507, OTA.ZJ.mnc000.mcc460.gprs,      100,1524598898731,1524598906076,13,40,  104.13.201.144,49839,0, 106.11.248.1,   80,  120, 0, 2, 0, 2, 1,  2
            //00008210545a67994584,460002605393612,8613927041963,  141269025,BOSSTJFT.GD.mnc000.mcc460.gprs, 100,1524611225191,1524611225191,12,1,   10.144.76.65,  52318,0, 123.151.10.164, 443, 1215,0, 1, 0, 0, 1,  2

            //char[] buff = reader.ReadChars(10000);
            //log.writeLogCommon(new string(buff));

            //大方向:读取入库至apnDay180

            //5. 获取文件名包含的主要日期
            string currentDayString;

            currentDayString = TamPub1.FileOperation.extractFileName(filename).Substring(0, 8);
            log.writeLogCommon("====5.根据文件名获取主要日期子串为:" + currentDayString);

            //10. 初始化内存手机表
            log.writeLogCommon("====10.初始化内存手机表====");
            PhoneNumber phoneNumberList = new PhoneNumber();

            phoneNumberList.init();

            //20. 扫描文件获取手机号列表
            log.writeLogCommon("====20.扫描文件获取手机号列表====");
            if (!System.IO.File.Exists(filename))
            {
                log.writeLogWarning("文件不存在, filename=" + filename);
                return(false);
            }
            try {
                fs = new System.IO.FileStream(filename, System.IO.FileMode.Open);
            } catch (Exception ex) {
                log.writeLogWarning("无法读取文件,reason=" + ex.Message + ", filename=" + filename);
                return(false);
            }
            reader = new System.IO.BinaryReader(fs, System.Text.Encoding.GetEncoding("GBK"));
            string buff = "";
            string oneLine;
            int    lineStartPos, sp;
            int    buffSize = 10000;
            int    batchCount = 0, linesCount = 0;
            Int64  bytesRead = 0;

            while (true)
            {
                if (skip)
                {
                    break;
                }
                Application.DoEvents();
                if (forceExit)
                {
                    break;
                }
                if (batchCount % 1000 == 0)
                {
                    log.logDisplay.sameLine();
                    log.writeLogCommon("批次:" + batchCount.ToString("N0") +
                                       " / 处理字符:" + bytesRead / 1000000 + "M" +
                                       " / 读取记录:" + linesCount.ToString("N0") +
                                       " / 手机号:" + phoneNumberList.items.Count.ToString("N0")
                                       );
                }

                //read one batch
                string fBuff = new string(reader.ReadChars(buffSize));
                bytesRead += fBuff.Length;
                if (fBuff.Length <= 0)
                {
                    break;                    //eof
                }
                buff        += fBuff.Replace("\r\n", "\n").Replace('\r', '\n');
                lineStartPos = 0;
                batchCount++;
                //if (batchCount > 50) break;
                while (true)
                {
                    //read line
                    sp = buff.IndexOf('\n', lineStartPos);
                    if (sp < 0)
                    {
                        break;
                    }
                    oneLine      = buff.Substring(lineStartPos, sp - lineStartPos);
                    lineStartPos = sp + 1;
                    linesCount++;
                    //decode line
                    string[] fields = oneLine.Split(',');
                    if (fields.Length != 22)
                    {
                        log.writeLogWarning("非法记录行:" + oneLine);
                        continue;
                    }
                    PhoneNumber.Item phoneNumberItem = phoneNumberList.newItem();
                    phoneNumberItem.imsi        = fields[1];
                    phoneNumberItem.phoneNumber = fields[2];
                    phoneNumberList.push(phoneNumberItem);
                }
                buff = buff.Substring(lineStartPos);
            }
            fs.Close();

            //30. 根据手机号列表创建apnDay180框架
            log.writeLogCommon("====30.根据手机号列表创建apnDay180框架====");
            StringBuilder sql = new StringBuilder();

            for (int i = 0; i < phoneNumberList.items.Count; i++)
            {
                if (skip)
                {
                    break;
                }
                sql.Append(
                    "exec [dbo].[createImsi] " +
                    "'" + phoneNumberList.items[i].imsi + "'" +
                    ", '" + phoneNumberList.items[i].phoneNumber + "';\r\n"
                    );
                if ((i % 10 != 0) && (i < phoneNumberList.items.Count - 1))
                {
                    continue;
                }
                Application.DoEvents();
                if (forceExit)
                {
                    break;
                }
                log.logDisplay.sameLine();
                log.writeLogCommon(
                    "初始化手机号:" + (i + 1).ToString("N0") + "/" + phoneNumberList.items.Count.ToString("N0")
                    );
                if (!execSqlN(sql.ToString()))
                {
                    return(false);
                }
                sql.Clear();
            }

            //35. 获取当前日期序列号
            int dateSn = 0;

            log.writeLogCommon("====35.获取当前日期序列号==== 由于未上线,此步骤跳过,人工指定日期序列号为:" + dateSn);

            //37. 读取并更新日期维度表,由于目前没有上线,直接产生此表
            log.writeLogCommon("====37.读取并更新日期维度表,由于目前没有上线,直接产生此表====");
            TamPub1.SpeedSearch <string> dimTime = new TamPub1.SpeedSearch <string>();
            DateTime dimTimePos = new DateTime(2018, 4, 23);

            for (int i = 0; i < 30 * 3; i++)
            {
                dimTime.buff.Add(dimTimePos.ToString("yyyyMMdd"));
                dimTimePos = dimTimePos.AddDays(1);
            }
            dimTime.onCompare = dimTimeOnCompare;

            //40. 扫描每行产生update

            /*
             * if (!System.IO.File.Exists(filename)) {
             *  log.writeLogWarning("文件不存在, filename=" + filename);
             *  return false;
             * }
             * try {
             *  fs = new System.IO.FileStream(filename, System.IO.FileMode.Open);
             * } catch (Exception ex) {
             *  log.writeLogWarning("无法读取文件,reason=" + ex.Message + ", filename=" + filename);
             *  return false;
             * }
             * reader = new System.IO.BinaryReader(fs, System.Text.Encoding.GetEncoding("GBK"));
             * batchCount = 0;
             * bytesRead = 0;
             * linesCount = 0;
             * sql.Clear();
             * int updateCount = 0;
             * while (true) {
             *  Application.DoEvents();
             *  if (forceExit) break;
             *  log.logDisplay.sameLine();
             *  log.writeLogCommon("批次:" + batchCount.ToString("N0") +
             *      " / 处理字符:" + bytesRead / 1000000 + "M" +
             *      " / 读取记录:" + linesCount.ToString("N0")
             *      );
             *
             *  //read one batch
             *  string fBuff = new string(reader.ReadChars(buffSize));
             *  bytesRead += fBuff.Length;
             *  if (fBuff.Length <= 0) break; //eof
             *  buff += fBuff.Replace("\r\n", "\n").Replace('\r', '\n');
             *  lineStartPos = 0;
             *  batchCount++;
             *  //if (batchCount > 50) break;
             *  while (true) {
             *      //read line
             *      sp = buff.IndexOf('\n', lineStartPos);
             *      if (sp < 0) break;
             *      oneLine = buff.Substring(lineStartPos, sp - lineStartPos);
             *      lineStartPos = sp + 1;
             *      linesCount++;
             *      //decode line
             *      string[] fields = oneLine.Split(',');
             *      if (fields.Length != 22) {
             *          log.writeLogWarning("非法记录行:" + oneLine);
             *          continue;
             *      }
             *      //解码开始时间(忽略结束时间)
             *      DateTime startTime = decodeDatetime(fields[6]);
             *
             *      //根据时间计算出时间维度坐标
             *      if (!dimTime.search(startTime.ToString("yyyyMMdd"))) {
             *          log.writeLogWarning("检测到超出维度范围的时间标记:" + oneLine);
             *          continue;
             *      }
             *      int dimTimeValue = dimTime.pos;
             *
             *      //根据时间计算出时段维度坐标
             *      int dimDayHourValue = Convert.ToInt32(startTime.Hour) / 3; //目前分割为3小时一个时段
             *
             *      //产生更新apn字段语句
             *      sql.Append(
             *          "update imsiInfo set apn = '" + fields[4] +
             *          "' where imsi = '" + fields[1] + "';\r\n"
             *          );
             *
             *      //产生更新day180表语句
             *      //======================
             *      //12:L4_protocal L4协议类型:0:TCP;1:UDP >> 1位长度
             *      //15:UL_Data 上行流量;单位:字节 >> 整数
             *      //16:DL_Data 下行流量;单位:字节 >> 整数
             *      //17:UL_IP_Packet    上行IP包数 >> 整数
             *      //18:DL_IP_Packet    下行IP包数 >> 整数
             *      //19:TCP_Try_Cnt TCP建链尝试次数,一次TCP流多次SYN的数值; 非TCP传输时,此字段填0 >> 整数
             *      //20:TCP_Link_flag   TCP连接状态指示;0:成功;1:失败 >> 255代表什么?
             *      if (fields[12].Equals("0")) { //tcp
             *          sql.Append(
             *              "update apnDay180 set " +
             *              " tcpUploadBytes = tcpUploadBytes + " + fields[15] +
             *              ",tcpDownloadBytes = tcpDownloadBytes + " + fields[16] +
             *              ",tcpUploadPackets = tcpUploadPackets + " + fields[17] +
             *              ",tcpDownloadPackets = tcpDownloadPackets + " + fields[18] +
             *              ",tcpRetryCount = tcpRetryCount + " + fields[19] +
             *              " where" +
             *              " imsi = '" + fields[1] + "' " +
             *              " and dayIndex = " + dimTimeValue +
             *              " and dayHour = " + dimDayHourValue +
             *              ";\r\n"
             *              );
             *      } else if (fields[12].Equals("1")) { //udp
             *          sql.Append(
             *              "update apnDay180 set " +
             *              " udpUploadBytes = udpUploadBytes + " + fields[15] +
             *              ",udpDownloadBytes = udpDownloadBytes + " + fields[16] +
             *              ",udpUploadPackets = udpUploadPackets + " + fields[17] +
             *              ",udpDownloadPackets = udpDownloadPackets + " + fields[18] +
             *              " where" +
             *              " imsi = '" + fields[1] + "' " +
             *              " and dayIndex = " + dimTimeValue +
             *              " and dayHour = " + dimDayHourValue +
             *              ";\r\n"
             *              );
             *      } else {
             *          log.writeLogWarning("检测到未知类型的包结构:" + oneLine);
             *          continue;
             *      }
             *      updateCount++;
             *      //ip地址问题, 数据方向问题,数据类型问题
             *
             *      //择机执行sql
             *      if (updateCount >= 500) {
             *          execSqlN(sql.ToString());
             *          updateCount = 0;
             *          sql.Clear();
             *      }
             *
             *  }
             *  buff = buff.Substring(lineStartPos);
             * }
             * //执行尾部的sql
             * if (updateCount > 0) {
             *  execSqlN(sql.ToString());
             *  updateCount = 0;
             *  sql.Clear();
             * }
             * fs.Close();
             */

            log.writeLogCommon("====40.扫描文件数据进入高速缓存====");
            if (!System.IO.File.Exists(filename))
            {
                log.writeLogWarning("文件不存在, filename=" + filename);
                return(false);
            }
            try {
                fs = new System.IO.FileStream(filename, System.IO.FileMode.Open);
            } catch (Exception ex) {
                log.writeLogWarning("无法读取文件,reason=" + ex.Message + ", filename=" + filename);
                return(false);
            }
            reader     = new System.IO.BinaryReader(fs, System.Text.Encoding.GetEncoding("GBK"));
            batchCount = 0;
            bytesRead  = 0;
            linesCount = 0;
            sql.Clear();
            int updateCount = 0;
            int outbound1   = 0;
            int outbound2   = 0;

            while (true)
            {
                Application.DoEvents();
                if (forceExit)
                {
                    break;
                }
                //if (phoneNumberList.items.Count > 3000) break;
                if (batchCount % 1000 == 0)
                {
                    log.logDisplay.sameLine();
                    log.writeLogCommon("批次:" + batchCount.ToString("N0") +
                                       " / 处理字符:" + bytesRead / 1000000 + "M" +
                                       " / 读取记录:" + linesCount.ToString("N0") +
                                       " / 手机号:" + phoneNumberList.items.Count.ToString("N0") +
                                       " / 时间维度越界次数:" + outbound1 + "/" + outbound2
                                       );
                }

                //read one batch
                string fBuff = new string(reader.ReadChars(buffSize));
                bytesRead += fBuff.Length;
                if (fBuff.Length <= 0)
                {
                    break;                    //eof
                }
                buff        += fBuff.Replace("\r\n", "\n").Replace('\r', '\n');
                lineStartPos = 0;
                batchCount++;
                //if (batchCount > 50) break;
                while (true)
                {
                    //read line
                    sp = buff.IndexOf('\n', lineStartPos);
                    if (sp < 0)
                    {
                        break;
                    }
                    oneLine      = buff.Substring(lineStartPos, sp - lineStartPos);
                    lineStartPos = sp + 1;
                    linesCount++;
                    //decode line
                    string[] fields = oneLine.Split(',');
                    if (fields.Length != 22)
                    {
                        log.writeLogWarning("非法记录行:" + oneLine);
                        continue;
                    }
                    //解码开始时间(忽略结束时间)
                    DateTime startTime = decodeDatetime(fields[6]);
                    startTime = startTime.AddMinutes(2); //增加x分钟的偏移校正
                    if (startTime.ToString("yyyyMMdd").CompareTo(currentDayString) < 0)
                    {
                        startTime = DateTime.ParseExact(currentDayString, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
                        outbound1++;
                    }
                    else if (startTime.ToString("yyyyMMdd").CompareTo(currentDayString) > 0)
                    {
                        startTime = DateTime.ParseExact(currentDayString + "235959", "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
                        outbound2++;
                    }

                    //根据时间计算出时段维度坐标
                    int dimDayHourValue = Convert.ToInt32(startTime.Hour) / 3; //目前分割为3小时一个时段

                    //抓取数据
                    //======================
                    //12:L4_protocal L4协议类型:0:TCP;1:UDP >> 1位长度
                    //15:UL_Data 上行流量;单位:字节 >> 整数
                    //16:DL_Data 下行流量;单位:字节 >> 整数
                    //17:UL_IP_Packet    上行IP包数 >> 整数
                    //18:DL_IP_Packet    下行IP包数 >> 整数
                    //19:TCP_Try_Cnt TCP建链尝试次数,一次TCP流多次SYN的数值; 非TCP传输时,此字段填0 >> 整数
                    //20:TCP_Link_flag   TCP连接状态指示;0:成功;1:失败 >> 255代表什么?
                    PhoneNumber.Item item = phoneNumberList.newItem();
                    item.imsi        = fields[1];
                    item.phoneNumber = fields[2];
                    item.apn         = fields[4];
                    if (fields[12].Equals("0"))   //tcp
                    {
                        item.dayHour[dimDayHourValue].tcpUploadBytes     = Convert.ToInt32(fields[15]);
                        item.dayHour[dimDayHourValue].tcpDownloadBytes   = Convert.ToInt32(fields[16]);
                        item.dayHour[dimDayHourValue].tcpUploadPackets   = Convert.ToInt32(fields[17]);
                        item.dayHour[dimDayHourValue].tcpDownloadPackets = Convert.ToInt32(fields[18]);
                        item.dayHour[dimDayHourValue].tcpRetryCount      = Convert.ToInt32(fields[19]);
                    }
                    else if (fields[12].Equals("1"))     //udp
                    {
                        item.dayHour[dimDayHourValue].udpUploadBytes     = Convert.ToInt32(fields[15]);
                        item.dayHour[dimDayHourValue].udpDownloadBytes   = Convert.ToInt32(fields[16]);
                        item.dayHour[dimDayHourValue].udpUploadPackets   = Convert.ToInt32(fields[17]);
                        item.dayHour[dimDayHourValue].udpDownloadPackets = Convert.ToInt32(fields[18]);
                    }
                    else
                    {
                        log.writeLogWarning("检测到未知类型的包结构:" + oneLine);
                        continue;
                    }

                    //增加或者查找手机号码
                    phoneNumberList.update(item);
                    updateCount++;

                    //ip地址问题, 数据方向问题,数据类型问题
                }
                buff = buff.Substring(lineStartPos);
            }
            fs.Close();

            //45.计算数据库时间维度偏移量
            if (!dimTime.search(currentDayString))
            {
                log.writeLogWarning("文件提取时间超出范围:" + currentDayString);
                return(false);
            }
            int dimTimeOffset = dimTime.pos;

            //dimTimeOffset--;
            //if (dimTimeOffset < 0) dimTimeOffset = daySize - 1;
            log.writeLogCommon("====45.计算数据库时间维度偏移量:" + dimTimeOffset + "====");

            //50. 高速缓存数据入库
            log.writeLogCommon("====50.高速缓存数据入库====");
            sql.Clear();
            for (int i = 0; i < phoneNumberList.items.Count; i++)
            {
                Application.DoEvents();
                if (forceExit)
                {
                    break;
                }
                if ((i % 500 == 0) || (i == phoneNumberList.items.Count - 1))
                {
                    log.logDisplay.sameLine();
                    log.writeLogCommon(
                        "正在入库高速缓存:" + (i + 1).ToString("N0") +
                        " / " + phoneNumberList.items.Count.ToString("N0")
                        );
                    if (sql.Length > 0)
                    {
                        execSqlN(sql.ToString());
                        sql.Clear();
                    }
                }
                //产生更新手机表的语句
                sql.Append(
                    "update imsiInfo set " +
                    " phoneNumber='" + phoneNumberList.items[i].phoneNumber + "'" +
                    ",apn='" + phoneNumberList.items[i].apn + "'" +
                    " where imsi='" + phoneNumberList.items[i].imsi + "';\r\n"
                    );

                //产生更新day180表的语句
                for (int hourIndex = 0; hourIndex < 24 / 3; hourIndex++)
                {
                    sql.Append(
                        "update apnDay180 set " +
                        " tcpUploadBytes=" + phoneNumberList.items[i].dayHour[hourIndex].tcpUploadBytes +
                        ",tcpDownloadBytes=" + phoneNumberList.items[i].dayHour[hourIndex].tcpDownloadBytes +
                        ",udpUploadBytes=" + phoneNumberList.items[i].dayHour[hourIndex].udpUploadBytes +
                        ",udpDownloadBytes=" + phoneNumberList.items[i].dayHour[hourIndex].udpDownloadBytes +
                        ",tcpUploadPackets=" + phoneNumberList.items[i].dayHour[hourIndex].tcpUploadPackets +
                        ",tcpDownloadPackets=" + phoneNumberList.items[i].dayHour[hourIndex].tcpDownloadPackets +
                        ",udpUploadPackets=" + phoneNumberList.items[i].dayHour[hourIndex].udpUploadPackets +
                        ",udpDownloadPackets=" + phoneNumberList.items[i].dayHour[hourIndex].udpDownloadPackets +
                        ",tcpRetryCount=" + phoneNumberList.items[i].dayHour[hourIndex].tcpRetryCount +
                        " where imsi='" + phoneNumberList.items[i].imsi + "'" +
                        " and dayIndex=" + dimTimeOffset +
                        " and dayHour=" + hourIndex +
                        ";\r\n"
                        );
                }
            }



            //60. 更新当前日期序列号

            //100. 完成

            log.writeLogWarning("第一步处理(day180)完成");
            return(true);
        }
Beispiel #54
0
        public static VoxelStruct ReadFromMagicaVoxel(System.IO.BinaryReader br)
        {
            VoxelStruct vs = new VoxelStruct();


            // check out http://voxel.codeplex.com/wikipage?title=VOX%20Format&referringTitle=Home for the file format used below
            // we're going to return a voxel chunk worth of data
            //ushort[] data = new ushort[32 * 128 * 32];
            VectorInt4[] palette = null;
            Point[]      points  = null;


            string vox = new string(br.ReadChars(4));

            if (vox != "VOX ")
            {
                Debug.Log(vox);
                return(vs);
            }

            int version = br.ReadInt32();

            vs.version = version;
            VectorInt3 box       = new VectorInt3();
            bool       subsample = false;


            while (br.BaseStream.Position < br.BaseStream.Length)
            {
                // each chunk has an ID, size and child chunks
                string name   = new string(br.ReadChars(4));
                int    size   = br.ReadInt32();
                int    chunks = br.ReadInt32();
                // Debug.LogError (chunkName);
                // there are only 2 chunks we only care about, and they are SIZE and XYZI
                if (name == "MAIN")
                {
                    vs.main        = new VoxelStruct.Main();
                    vs.main.size   = size;
                    vs.main.name   = name;
                    vs.main.chunks = chunks;
                }
                if (name == "SIZE")
                {
                    box.x = br.ReadInt32();
                    box.y = br.ReadInt32();
                    box.z = br.ReadInt32();


                    vs.size        = new VoxelStruct.Size();
                    vs.size.size   = 12;
                    vs.size.name   = name;
                    vs.size.chunks = chunks;
                    vs.size.box    = box;

                    if (box.x > 32 || box.y > 32)
                    {
                        subsample = true;
                    }

                    br.ReadBytes(size - 4 * 3);
                }
                else if (name == "XYZI")
                {
                    // XYZI contains n voxels
                    int count = br.ReadInt32();
                    //int div = (subsample ? 2 : 1);
                    // each voxel has x, y, z and color index values
                    points = new Point[count];
                    for (int i = 0; i < points.Length; i++)
                    {
                        points [i] = VoxelFormater.CreatePoint(br, subsample);                         //new Data (stream, subsample);
                    }
                }
                else if (name == "RGBA")
                {
                    int n = size / 4;
                    palette = new VectorInt4[n];
                    for (int i = 0; i < n; i++)
                    {
                        byte r = br.ReadByte();
                        byte g = br.ReadByte();
                        byte b = br.ReadByte();
                        byte a = br.ReadByte();
                        palette[i].x = r;
                        palette[i].y = g;
                        palette[i].z = b;
                        palette[i].w = a;
                    }

                    vs.rgba         = new VoxelStruct.Rgba();
                    vs.rgba.size    = size;
                    vs.rgba.name    = name;
                    vs.rgba.chunks  = chunks;
                    vs.rgba.palette = palette;
                }
                else
                {
                    br.ReadBytes(size);                       // read any excess bytes
                }
            }
            vs.datas = CreateVoxelDatas(points, palette);
            return(vs);
        }
Beispiel #55
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();
                }
            }
        }
Beispiel #56
0
        private void Mod_LoadTexinfo(SDHeader header, ref CModel.SModel _SModel, ref System.IO.BinaryReader br)
        {
            List <CModel.SMTexInfo> MTexInfo = new List <CModel.SMTexInfo>();

            br.BaseStream.Seek(header.lumps[LUMP_TEXINFO].fileofs, System.IO.SeekOrigin.Begin);
            while (br.BaseStream.Position < (header.lumps[LUMP_TEXINFO].fileofs + header.lumps[LUMP_TEXINFO].filelen))
            {
                CModel.SMTexInfo _MTexInfo;
                string           texture;
                int next;

                _MTexInfo.vecs = new Microsoft.Xna.Framework.Vector4[2];
                for (int i = 0; i < 2; i++)
                {
                    _MTexInfo.vecs[i].X = br.ReadSingle();
                    _MTexInfo.vecs[i].Y = br.ReadSingle();
                    _MTexInfo.vecs[i].Z = br.ReadSingle();
                    _MTexInfo.vecs[i].W = br.ReadSingle();
                }

                _MTexInfo.flags = (ESurface)br.ReadInt32();
                br.ReadInt32(); // value
                texture = CShared.Com_ToString(br.ReadChars(32));
                texture = "textures/" + texture;

                next = br.ReadInt32();
                if (next > 0)
                {
                    _MTexInfo.next = next;
                }
                else
                {
                    _MTexInfo.next = 0;
                }

                _MTexInfo.image = CProgram.gQ2Game.gCMain.gCImage.FindImage(texture, out _MTexInfo.Width, out _MTexInfo.Height, CImage.EImageType.IT_WALL);

                // TODO
                //out->image = GL_FindImage (name, it_wall);
                //if (!out->image)
                //{
                //    ri.Con_Printf (PRINT_ALL, "Couldn't load %s\n", name);
                //    out->image = r_notexture;
                //}

                _MTexInfo.numframes = 0;

                MTexInfo.Add(_MTexInfo);
            }

            // count animation frames
            for (int i = 0; i < MTexInfo.Count; i++)
            {
                CModel.SMTexInfo _MTexInfo = MTexInfo[i];
                _MTexInfo.numframes = 1;

                for (int step = _MTexInfo.next; step != 0 && step != i; step = MTexInfo[step].next)
                {
                    _MTexInfo.numframes++;
                }

                MTexInfo[i] = _MTexInfo;
            }

            _SModel.numtexinfo = MTexInfo.Count;
            _SModel.texinfo    = MTexInfo.ToArray();
        }
Beispiel #57
0
 protected override void DoRead(System.IO.BinaryReader reader)
 {
     char[] fourCC = reader.ReadChars(4);
     Value = new String(fourCC);
 }
Beispiel #58
0
        /*public static MagicaVoxel ReadFromFile(TextAsset file){
         *      Stream sw = new MemoryStream(file.bytes);
         *      System.IO.BinaryReader br = new System.IO.BinaryReader (sw);
         *      return ReadFromBinary(br);
         *
         * }
         * public static MagicaVoxel ReadFromUrl(string url){
         *      return null;
         * }*/
        public static MagicaVoxel ReadFromBinary(System.IO.BinaryReader br)
        {
            MagicaVoxel magic = new MagicaVoxel(new VoxelStruct());

            VectorInt4[] palette = null;
            Point[]      points  = null;
            string       vox     = new string(br.ReadChars(4));

            if (vox != "VOX ")
            {
                return(magic);
            }

            int version = br.ReadInt32();

            magic.version = version;
            VectorInt3 box       = new VectorInt3();
            bool       subsample = false;


            while (br.BaseStream.Position + 12 < br.BaseStream.Length)
            {
                string name   = new string(br.ReadChars(4));
                int    size   = br.ReadInt32();
                int    chunks = br.ReadInt32();


                if (name == "MAIN")
                {
                    magic.main        = new MagicaVoxel.Main();
                    magic.main.size   = size;
                    magic.main.name   = name;
                    magic.main.chunks = chunks;
                }
                else if (name == "SIZE")
                {
                    box.x = br.ReadInt32();
                    box.y = br.ReadInt32();
                    box.z = br.ReadInt32();


                    magic.size        = new MagicaVoxel.Size();
                    magic.size.size   = 12;
                    magic.size.name   = name;
                    magic.size.chunks = chunks;
                    magic.size.box    = box;

                    if (box.x > 32 || box.y > 32)
                    {
                        subsample = true;
                    }

                    br.ReadBytes(size - 4 * 3);
                }
                else if (name == "XYZI")
                {
                    int count = br.ReadInt32();
                    points = new Point[count];
                    for (int i = 0; i < points.Length; i++)
                    {
                        points [i] = MagicaVoxelFormater.ReadPoint(br, subsample);                         //new Data (stream, subsample);
                    }
                }
                else if (name == "RGBA")
                {
                    int n = size / 4;
                    palette = new VectorInt4[n];
                    for (int i = 0; i < n; i++)
                    {
                        byte r = br.ReadByte();
                        byte g = br.ReadByte();
                        byte b = br.ReadByte();
                        byte a = br.ReadByte();
                        palette [i].x = r;
                        palette [i].y = g;
                        palette [i].z = b;
                        palette [i].w = a;
                    }

                    magic.rgba         = new MagicaVoxel.Rgba();
                    magic.rgba.size    = size;
                    magic.rgba.name    = name;
                    magic.rgba.chunks  = chunks;
                    magic.rgba.palette = palette;
                }
                else
                {
                    if (br.BaseStream.Position + size >= br.BaseStream.Length)
                    {
                        break;
                    }
                    else
                    {
                        br.ReadBytes(size);
                    }
                }
            }
            magic.vs.datas = CreateVoxelDatas(points, palette);
            return(magic);
        }