Esempio n. 1
0
		public static void DeserializeVoxelAreaData (byte[] bytes, VoxelArea target) {
			
			Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
			System.IO.MemoryStream stream = new System.IO.MemoryStream();
			stream.Write(bytes,0,bytes.Length);
			stream.Position = 0;
			zip = Ionic.Zip.ZipFile.Read(stream);
			System.IO.MemoryStream stream2 = new System.IO.MemoryStream();
			
			zip["data"].Extract (stream2);
			stream2.Position = 0;
			System.IO.BinaryReader reader = new System.IO.BinaryReader(stream2);
			
			int width = reader.ReadInt32();
			int depth = reader.ReadInt32();
			if (target.width != width) throw new System.ArgumentException ("target VoxelArea has a different width than the data ("+target.width + " != " + width + ")");
			if (target.depth != depth) throw new System.ArgumentException ("target VoxelArea has a different depth than the data ("+target.depth + " != " + depth + ")");
			LinkedVoxelSpan[] spans = new LinkedVoxelSpan[reader.ReadInt32()];
			
			for (int i=0;i<spans.Length;i++) {
				spans[i].area = reader.ReadInt32();
				spans[i].bottom = reader.ReadUInt32();
				spans[i].next = reader.ReadInt32();
				spans[i].top = reader.ReadUInt32();
			}
			target.linkedSpans = spans;
		}
Esempio n. 2
0
        /// <summary>
        /// ファイルからデータをロード
        /// </summary>
        public static void LoadData()
        {
            if(System.IO.File.Exists(@SAVEFILE)){
                using(var fs = System.IO.File.Open(@SAVEFILE,System.IO.FileMode.Open)){
                    // バイナリリーダ作成
                    var br = new System.IO.BinaryReader(fs);

                    // Read data
                    Global.isStageOpened[(int)StageID.Stage1] = br.ReadBoolean();
                    Global.isStageOpened[(int)StageID.Stage2] = br.ReadBoolean();
                    Global.isStageOpened[(int)StageID.Stage3] = br.ReadBoolean();

                    Global.characterLevel = br.ReadInt32();
                    Global.characterExp = br.ReadInt32();

                    br.Close();
                }
            }else{
                Global.isStageOpened[(int)StageID.Stage1] = true;
                Global.isStageOpened[(int)StageID.Stage2] = false;
                Global.isStageOpened[(int)StageID.Stage3] = false;

                Global.characterLevel = 1;
                Global.characterExp = 0;
            }
        }
Esempio n. 3
0
        public static FullAnimation From3DMAXStream(System.IO.Stream stream, SkeletonExtended skeleton, bool reverse)
        {
            Matrix[][] Frames;
            var clip = new FullAnimation();
            var reader = new System.IO.BinaryReader(stream);
            var start = reader.ReadInt32();
            var end = reader.ReadInt32();
            var length = end - start + 1;
            clip.BonesCount = reader.ReadInt32();
            var counter = reader.ReadInt32();
            Frames = new Matrix[length][];
            for (int i = 0; i < length; i++)
                Frames[i] = new Matrix[clip.BonesCount];
            for (int i = 0; i < clip.BonesCount; i++)
                for (int j = 0; j < length; j++)
                    Frames[j][i] = reader.ReadMatrix();
            //теперь надо вычислить дельты
            //(идёт загрузка экспортированного из макса)
            for (int i = 0; i < clip.BonesCount; i++)
                for (int @in = 0; @in < length; @in++)
                    Frames[@in][i] = skeleton.baseskelet.bones[i].BaseMatrix * Frames[@in][i];

            if (reverse)
            {
                //Matrix[][] FramesTmp = new Matrix[length][];
                Frames = Frames.Reverse().ToArray();
            }
            Matrix[][] relatedMatrices = Animation.GetRelatedMatrices(Frames, skeleton.baseskelet);
            DecomposedMatrix[][] decomposedMatrices = GetDecomposedMatrices(skeleton.baseskelet, relatedMatrices);

            clip.matrices = decomposedMatrices;
            return clip;
        }
        private void btnChooseFile_Click(object sender, RoutedEventArgs e)
        {
            // Create OpenFileDialog
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            // Set filter for file extension and default file extension
            dlg.DefaultExt = ".data";
            dlg.Filter = "Frame data (*.data)|*.data";

            // Display OpenFileDialog by calling ShowDialog method
            Nullable<bool> result = dlg.ShowDialog();

            // Get the selected file name and display in a TextBox
            if (result == true)
            {
                frameList.Clear();
                // Open document
                string filename = dlg.FileName;
                using (System.IO.BinaryReader br =
                    new System.IO.BinaryReader(System.IO.File.Open(filename, System.IO.FileMode.Open)))
                {
                    while (br.BaseStream.Position < br.BaseStream.Length)
                    {
                        //deserialises and reads the binary file
                        DateTime date = new DateTime();
                        date = DateTime.FromBinary(br.ReadInt64());
                        // Console.WriteLine(date.ToString());

                        Int32 stimCode = br.ReadInt32();

                        Int32 nextBlock = br.ReadInt32();
                        byte[] frameData = br.ReadBytes(nextBlock);
                        Leap.Frame newFrame = new Leap.Frame();
                        newFrame.Deserialize(frameData);

                        if (stimCode == 5443)
                        {
                            Debug.WriteLine("5443 detected: " + newFrame.Id);
                        }
                        frameList.Add(newFrame);
                        //Console.WriteLine(newFrame.CurrentFramesPerSecond);

                    }
                    br.Close();
                    br.Dispose();
                }
                /* WRITE CODE HERE TO EXTRACT DATA FROM FILE
                foreach (Leap.Frame frame in frameList)
                {
                    //Console.WriteLine(frame.Id);
                }
                */

            }
        }
Esempio n. 5
0
 public static ChunkRangesRequest Deserialize(byte[] bytes)
 {
     Tuple<byte[],byte[]>[] ranges;
     using (System.IO.MemoryStream MS  = new System.IO.MemoryStream (bytes,false)) {
         using (System.IO.BinaryReader BR= new System.IO.BinaryReader(MS)) {
             ranges = new Tuple<byte[], byte[]>[BR.ReadInt32 ()];
             for (int n = 0; n != ranges.Length; n++) {
                 ranges [n] = new Tuple<byte[], byte[]> (BR.ReadBytes (BR.ReadInt32 ()), BR.ReadBytes (BR.ReadInt32 ()));
             }
         }
         return new ChunkRangesRequest (ranges);
     }
 }
		public static ZipFile Read ( System.IO.Stream stream ) {
			ZipFile file = new ZipFile();

			var reader = new System.IO.BinaryReader ( stream );
			int count = reader.ReadInt32 ();
			for ( int i = 0; i < count; i++ ) {
				var name = reader.ReadString();
				var length = reader.ReadInt32 ();
				var bytes = reader.ReadBytes (length);

				file.dict[name] = new ZipEntry(name, bytes);
			}

			return file;
		}
Esempio n. 7
0
 public static MachineType GetDllMachineType(this string dllPath)
 {
     // See http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx
     // Offset to PE header is always at 0x3C.
     // The PE header starts with "PE\0\0" =  0x50 0x45 0x00 0x00,
     // followed by a 2-byte machine type field (see the document above for the enum).
     //
     using (var fs = new System.IO.FileStream(dllPath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
         using (var br = new System.IO.BinaryReader(fs)) {
             MachineType machineType = MachineType.IMAGE_FILE_MACHINE_UNKNOWN;
     //					bool isgood = false;
             try {
                 fs.Seek(0x3c, System.IO.SeekOrigin.Begin);
                 Int32 peOffset = br.ReadInt32();
                 fs.Seek(peOffset, System.IO.SeekOrigin.Begin);
                 UInt32 peHead = br.ReadUInt32();
                 if (peHead != 0x00004550)
                     // "PE\0\0", little-endian
                     throw new Exception("Can't find PE header");
                 machineType = (MachineType)br.ReadUInt16();
     //						isgood = true;
             }
             catch {
     //						isgood = false;
             }
             finally {
                 br.Close();
                 fs.Close();
             }
             return machineType;
         }
 }
Esempio n. 8
0
        public void Parse(Header header, byte[] data)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
            {
                using (System.IO.BinaryReader br = new System.IO.BinaryReader(ms))
                {
                    _authCode = br.ReadInt32();
                    _accountId = br.ReadUInt32();
                    _userLevel = br.ReadUInt32();
                    _lastLoginIP = br.ReadUInt32();
                    _lastLoginTime = br.ReadBytes(26);
                    _sex = br.ReadByte();

                    _serverList = new Dictionary<string, Server>();
                    for (int i = (int)ms.Position; i < header.Size; i += 32)
                    {
                        Server s = new Server();
                        s.IP = string.Format("{0}.{1}.{2}.{3}", br.ReadByte(), br.ReadByte(), br.ReadByte(), br.ReadByte());
                        s.Port = br.ReadInt16();
                        s.Name = br.ReadBytes(22).NullByteTerminatedString();
                        s.Type = br.ReadInt16();
                        s.UserCount = br.ReadInt16();
                        _serverList.Add(s.Name, s);
                    }
                }
            }
        }
Esempio n. 9
0
        public static void Load()
        {
            IO.Log.Write("    Loading CampaingProgresss...");
            levelsCompleted.Clear();

            System.IO.BinaryReader br = new System.IO.BinaryReader(new System.IO.FileStream("Saves/progress.lpg",
                System.IO.FileMode.Open));

            String s = "";
            int l = 0;
            while (br.PeekChar() > -1)
            {
                s = br.ReadString();
                l = br.ReadInt32();
                byte[] d = new byte[l];
                for (int j = 0; j < l; j++)
                {
                    d[j] = br.ReadByte();
                }
                levelsCompleted.Add(s, d);
            }

            br.Close();
            IO.Log.Write("    Loading complete");
        }
Esempio n. 10
0
        public void Load(string filename)
        {
            System.IO.BinaryReader br = new System.IO.BinaryReader(System.IO.File.Open(filename, System.IO.FileMode.Open));

            width = br.ReadInt32();
            height = br.ReadInt32();

            Create(width, height);

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    int attrCnt = 0;

                    groundData[x, y].type = br.ReadInt32();
                    attrCnt = br.ReadInt32();
                    for (int k = 0; k < attrCnt; k++)
                    {
                        int attr;
                        attr = br.ReadInt32();
                        groundData[x, y].attributes.Add(attr);
                    }
                }
            }

            int entityCnt = 0;
            entityCnt = br.ReadInt32();
            for (int e = 0; e < entityCnt; e++)
            {
                Cell entityCell = new Cell();
                int x, y, attrCnt;
                entityCell.type = br.ReadInt32();
                entityCell.empty = false;
                x = br.ReadInt32();
                y = br.ReadInt32();

                attrCnt = br.ReadInt32();
                for (int k = 0; k < attrCnt; k++)
                {
                    entityCell.attributes.Add(br.ReadInt32());
                }

                entityData[x, y] = entityCell;
            }
            br.Close();
        }
Esempio n. 11
0
 public void LoadBody(byte[] buffer)
 {
     System.IO.BinaryReader br = new System.IO.BinaryReader(new System.IO.MemoryStream(buffer));
     int count = br.ReadInt32();
     lodMats = new Lod[count];
     for (int i = 0; i < count; i++)
     {
         lodMats[i] = new Lod();
         int matc = br.ReadInt32();
         lodMats[i].mats = new SubsetMaterial[matc];
         for (int j = 0; j < matc; j++)
         {
             lodMats[i].mats[j] = new SubsetMaterial();
             lodMats[i].mats[j].DiffuseTextureName = br.ReadPackString();
         }
     }
 }
Esempio n. 12
0
 public void UsingTest()
 {
     using (var s = System.IO.File.Open(GetTestDataFilePath("SPATIAL_F_SKARVMUFF.shp"), System.IO.FileMode.Open))
     {
         using (var reader = new System.IO.BinaryReader(s))
         {
             System.Console.WriteLine(reader.ReadInt32());
         }
         NUnit.Framework.Assert.Throws<System.ObjectDisposedException>(() => System.Console.WriteLine(s.Position));
     } 
 }
Esempio n. 13
0
 public object[] DeserializeArray(byte[] buffer)
 {
     System.IO.MemoryStream MS = new System.IO.MemoryStream (buffer);
     System.IO.BinaryReader BR = new System.IO.BinaryReader (MS);
     object[] objects = new object[BR.ReadInt32 ()];
     int n = 0;
     while (MS.Position < MS.Length) {
         objects [n] = Deserialize (BR);
         n++;
     }
     return objects;
 }
Esempio n. 14
0
 public RGSSTable(byte[] raw)
 {
     System.IO.MemoryStream s = new System.IO.MemoryStream(raw);
     System.IO.BinaryReader r = new System.IO.BinaryReader(s);
     this.dimensions = (byte)r.ReadInt32();
     int x = r.ReadInt32();
     int y = r.ReadInt32();
     int z = r.ReadInt32();
     long check = r.ReadInt32();
     this.value = new short[x, y, z];
     for (int j = 0; j < z; j++)
     {
         for (int k = 0; k < y; k++)
         {
             for (int l = 0; l < x; l++)
             {
                 this[l, k, j] = r.ReadInt16();
             }
         }
     }
 }
Esempio n. 15
0
 /// <summary>Checks whether a specified file is a valid Win32 plugin.</summary>
 /// <param name="file">The file to check.</param>
 /// <returns>Whether the file is a valid Win32 plugin.</returns>
 private static bool CheckWin32Header(string file)
 {
     using (System.IO.FileStream stream = new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read)) {
         using (System.IO.BinaryReader reader = new System.IO.BinaryReader(stream)) {
             if (reader.ReadUInt16() != 0x5A4D) {
                 /* Not MZ signature */
                 return false;
             }
             stream.Position = 0x3C;
             stream.Position = reader.ReadInt32();
             if (reader.ReadUInt32() != 0x00004550) {
                 /* Not PE signature */
                 return false;
             }
             if (reader.ReadUInt16() != 0x014C) {
                 /* Not IMAGE_FILE_MACHINE_I386 */
                 return false;
             }
         }
     }
     return true;
 }
Esempio n. 16
0
 public static void Main(string[] args)
 {
     int config = -1;
     if(args.Length == 0)
         return;
     if(args[0].Contains(".cmp"))
         config = 0;
     if(args[0].Contains(".img"))
         config = 1;
     if(config == 0) {
         CVMCompiler compiler = new CVMCompiler();
         string codeMain = System.IO.File.OpenText(args[0]).ReadToEnd();
         string library = System.IO.File.OpenText("Library.cmp").ReadToEnd();
         int position = compiler.ParseCode(5,library);
         compiler.image[4] = compiler.ParseCode(position,codeMain);
         string codeBoot = "(MAIN) DO HLT";
         compiler.ParseCode(0,codeBoot);
         var binWriter = new System.IO.BinaryWriter(
             System.IO.File.OpenWrite(args[0].Replace(".cmp",".img")));
         for(var ndx = 0;ndx < compiler.image[4];ndx++)
             binWriter.Write(compiler.image[ndx]);
     }
     if(config == 1) {
         CVM vm = new CVM();
         var binReader = new System.IO.BinaryReader(
             System.IO.File.OpenRead(args[0]));
         int ndx=0;
         while(true) {
             try {
                 vm.SetMemory(ndx++,binReader.ReadInt32());
             }
             catch { break; }
         }
         vm.SetPC(0);
         while(vm.DO_OP((CVM.OPCODES)vm.RUN()) != (int)CVM.OPCODES.HLT);
     }
     Console.ReadKey(true);
 }
Esempio n. 17
0
        /// <summary>
        /// Processes the PCAP packet header
        /// </summary>
        /// <param name="theBinaryReader">The object that provides for binary reading from the packet capture</param>
        /// <param name="thePacketNumber">The number for the packet read from the packet capture</param>
        /// <param name="thePacketPayloadLength">The payload length of the packet read from the packet capture</param>
        /// <param name="thePacketTimestamp">The timestamp for the packet read from the packet capture</param>
        /// <returns>Boolean flag that indicates whether the PCAP packet header could be processed</returns>
        protected override bool ProcessPacketHeader(System.IO.BinaryReader theBinaryReader, ref ulong thePacketNumber, out long thePacketPayloadLength, out double thePacketTimestamp)
        {
            bool theResult = true;

            if (theBinaryReader == null)
            {
                throw new System.ArgumentNullException("theBinaryReader");
            }

            // Provide a default value to the output parameter for the length of the PCAP packet payload
            thePacketPayloadLength = 0;

            // Provide a default value to the output parameter for the timestamp
            thePacketTimestamp = 0.0;

            // Always increment the number for the packet read from the packet capture for a PCAP packet
            ++thePacketNumber;

            uint theTimestampSeconds      = 0;
            uint theTimestampMicroseconds = 0;
            uint theSavedLength           = 0;

            // Just read off the remainder of the PCAP packet header from the packet capture so we can move on
            // Some of the data will be stored for use below
            if (this.isTheGlobalHeaderLittleEndian)
            {
                theTimestampSeconds      = theBinaryReader.ReadUInt32();
                theTimestampMicroseconds = theBinaryReader.ReadUInt32();
                theSavedLength           = theBinaryReader.ReadUInt32();
                theBinaryReader.ReadUInt32(); // Actual length
            }
            else
            {
                theTimestampSeconds      = (uint)System.Net.IPAddress.NetworkToHostOrder(theBinaryReader.ReadInt32());
                theTimestampMicroseconds = (uint)System.Net.IPAddress.NetworkToHostOrder(theBinaryReader.ReadInt32());
                theSavedLength           = (uint)System.Net.IPAddress.NetworkToHostOrder(theBinaryReader.ReadInt32());
                theBinaryReader.ReadUInt32(); // Actual length
            }

            // No need to validate fields from the PCAP packet header
            if (theResult)
            {
                // Set up the value for the length of the PCAP packet capture packet payload
                switch (this.PacketCaptureNetworkDataLinkType)
                {
                case (uint)PacketCapture.CommonConstants.NetworkDataLinkType.Ethernet:
                {
                    // Subtract the normal Ethernet trailer of twelve bytes as this would typically not be exposed in the packet capture
                    thePacketPayloadLength = theSavedLength - 12;

                    break;
                }

                case (uint)PacketCapture.CommonConstants.NetworkDataLinkType.NullLoopback:
                case (uint)PacketCapture.CommonConstants.NetworkDataLinkType.CiscoHDLC:
                default:
                {
                    thePacketPayloadLength = theSavedLength;
                    break;
                }
                }

                // Set up the output parameter for the timestamp based on the timestamp values in seconds and microseconds
                thePacketTimestamp =
                    (double)theTimestampSeconds +
                    ((double)theTimestampMicroseconds / 1000000.0);
            }

            return(theResult);
        }
Esempio n. 18
0
		public static void DeserializeMeshNodes (NavMeshGraph graph, GraphNode[] nodes, byte[] bytes) {
			
			System.IO.MemoryStream mem = new System.IO.MemoryStream(bytes);
			System.IO.BinaryReader stream = new System.IO.BinaryReader(mem);
			
			for (int i=0;i<nodes.Length;i++) {
				TriangleMeshNode node = nodes[i] as TriangleMeshNode;
				
				if (node == null) {
					Debug.LogError ("Serialization Error : Couldn't cast the node to the appropriate type - NavMeshGenerator");
					return;
				}
				
				node.v0 = stream.ReadInt32 ();
				node.v1 = stream.ReadInt32 ();
				node.v2 = stream.ReadInt32 ();
				
			}
			
			int numVertices = stream.ReadInt32 ();
			
			graph.vertices = new Int3[numVertices];
			
			for (int i=0;i<numVertices;i++) {
				int x = stream.ReadInt32 ();
				int y = stream.ReadInt32 ();
				int z = stream.ReadInt32 ();
				
				graph.vertices[i] = new Int3 (x,y,z);
			}
			
			RebuildBBTree (graph);
		}
Esempio n. 19
0
        public static Entity ReadFrom(System.IO.BinaryReader reader)
        {
            int id       = reader.ReadInt32();
            int?playerId = null;

            if (reader.ReadBoolean())
            {
                playerId = reader.ReadInt32();
            }

            Model.EntityType entityType;
            switch (reader.ReadInt32())
            {
            case 0:
                entityType = Model.EntityType.Wall;
                break;

            case 1:
                entityType = Model.EntityType.House;
                break;

            case 2:
                entityType = Model.EntityType.BuilderBase;
                break;

            case 3:
                entityType = Model.EntityType.BuilderUnit;
                break;

            case 4:
                entityType = Model.EntityType.MeleeBase;
                break;

            case 5:
                entityType = Model.EntityType.MeleeUnit;
                break;

            case 6:
                entityType = Model.EntityType.RangedBase;
                break;

            case 7:
                entityType = Model.EntityType.RangedUnit;
                break;

            case 8:
                entityType = Model.EntityType.Resource;
                break;

            case 9:
                entityType = Model.EntityType.Turret;
                break;

            default:
                throw new System.Exception("Unexpected tag value");
            }

            Vec2Int position = Model.Vec2Int.ReadFrom(reader);
            int     health   = reader.ReadInt32();
            bool    active   = reader.ReadBoolean();
            var     result   = new Entity(id, playerId, entityType, position, health, active);

            return(result);
        }
            /// <summary>
            /// reads a file and populates the map receiver instance.
            /// </summary>
            /// <returns></returns>
            public static bool Read_pachm(out Mapping.PachMapReceiver[] Map)
            {
                System.Windows.Forms.OpenFileDialog of = new System.Windows.Forms.OpenFileDialog();
                of.DefaultExt   = ".pachm";
                of.AddExtension = true;
                of.Filter       = "Pachyderm Mapping Data File (*.pachm)|*.pachm|" + "All Files|";
                if (of.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    Map = null;
                    return(false);
                }
                System.IO.BinaryReader sr = new System.IO.BinaryReader(System.IO.File.Open(of.FileName, System.IO.FileMode.Open));
                //1. Write calculation type. (string)
                string CalcType = sr.ReadString();

                if (CalcType != "Type;Map_Data" && CalcType != "Type;Map_Data_NoDir")
                {
                    throw new Exception("Map Data File Expected");
                }
                bool Directional = (CalcType == "Type;Map_Data");

                //2. Write the number of samples in each histogram. (int)
                int SampleCT = (int)sr.ReadUInt32();
                //3. Write the sample rate. (int)
                int SampleRate = (int)sr.ReadUInt32();
                //4. Write the number of Receivers (int)
                int Rec_CT = (int)sr.ReadUInt32();
                //4.5 Write the version number
                double version = 1.1;
                double rev     = 0;
                //5. Announce that the following data pertains to the form of the analysis mesh. (string)
                int s_ct = 1;

                Rhino.Geometry.Mesh Map_Mesh = new Rhino.Geometry.Mesh();
                Map = new Mapping.PachMapReceiver[1];
                //Map[0] = new Pach_Map_Receiver();
                //double[] Rho_C = null;
                double[] delay;

                do
                {
                    switch (sr.ReadString())
                    {
                    case "Version":
                        //Pach1.7 = Versioning functionality added.
                        string v = sr.ReadString();
                        version = double.Parse(v.Substring(0, 3));
                        rev     = int.Parse(v.Split(new char[1] {
                            '.'
                        })[3]);
                        break;

                    case "Mesh Information":
                        //6. Announce Mesh Vertices (string)
                        //Write the number of vertices & faces (int) (int)
                        if (sr.ReadString() != "Mesh Vertices")
                        {
                            throw new Exception("Mesh Vertices Expected");
                        }

                        int VC = (int)sr.ReadUInt32();
                        int FC = (int)sr.ReadUInt32();
                        for (int i = 0; i < VC; i++)
                        {
                            //Write Vertex: (double) (double) (double)
                            Map_Mesh.Vertices.Add(new Rhino.Geometry.Point3d(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()));
                        }

                        //7. Announce Mesh Faces (string)
                        if (sr.ReadString() != "Mesh Faces")
                        {
                            throw new Exception("Mesh Faces Expected");
                        }

                        for (int i = 0; i < FC; i++)
                        {
                            // Write mesh vertex indices: (int) (int) (int) (int)
                            Map_Mesh.Faces.AddFace((int)sr.ReadUInt32(), (int)sr.ReadUInt32(), (int)sr.ReadUInt32(), (int)sr.ReadUInt32());
                        }
                        break;

                    case "Sources":
                        //7.5: Announce the number of sources.
                        s_ct  = sr.ReadInt32();
                        delay = new double[s_ct];
                        Map   = new Mapping.PachMapReceiver[s_ct];
                        //7.5a Announce the type of source.

                        for (int s = 0; s < s_ct; s++)
                        {
                            Map[s]            = new Mapping.PachMapReceiver();
                            Map[s].CutOffTime = (double)SampleCT / (double)SampleRate;
                            Map[s].SampleCT   = SampleCT;
                            Map[s].SampleRate = SampleRate;
                            Map[s].Map_Mesh   = Map_Mesh;
                            Map[s].Rec_List   = new Mapping.PachMapReceiver.Map_Receiver[Rec_CT];
                            Map[s].SrcType    = sr.ReadString();
                            //4.4 Source delay (ms)
                            if (version > 2.0 || (version == 2.0 && rev >= 1))
                            {
                                delay[s] = sr.ReadDouble();
                            }
                        }
                        break;

                    case "SourceswLoc":
                        //7.5: Announce the number of sources.
                        s_ct  = sr.ReadInt32();
                        delay = new double[s_ct];
                        Map   = new Mapping.PachMapReceiver[s_ct];
                        //7.5a Announce the type of source.

                        for (int s = 0; s < s_ct; s++)
                        {
                            Map[s]            = new Mapping.PachMapReceiver();
                            Map[s].CutOffTime = (double)SampleCT / (double)SampleRate * 1000;
                            Map[s].SampleCT   = SampleCT;
                            Map[s].SampleRate = SampleRate;
                            Map[s].Map_Mesh   = Map_Mesh;
                            Map[s].Rec_List   = new Mapping.PachMapReceiver.Map_Receiver[Rec_CT];
                            Map[s].Src        = new Rhino.Geometry.Point3d(sr.ReadDouble(), sr.ReadDouble(), sr.ReadDouble());
                            Map[s].SrcType    = sr.ReadString();
                            //4.4 Source delay (ms)
                            if (version > 2.0 || (version == 2.0 && rev >= 1))
                            {
                                delay[s] = sr.ReadDouble();
                            }
                        }
                        break;

                    case "Receiver Hit Data":
                        if (Map[0] == null)
                        {
                            Map               = new Mapping.PachMapReceiver[1];
                            Map[0]            = new Mapping.PachMapReceiver();
                            Map[0].CutOffTime = (double)SampleCT / (double)SampleRate;
                            Map[0].SampleRate = SampleRate;
                            Map[0].SampleCT   = SampleCT;
                            Map[0].Map_Mesh   = Map_Mesh;
                            Map[0].Rec_List   = new Mapping.PachMapReceiver.Map_Receiver[Rec_CT];
                            Map[0].SrcType    = "Geodesic";
                        }

                        //8. Announce that the following data pertains to the receiver histograms (string)
                        //8a. Announce whether or not data is linked to vertices rather than faces (bool)
                        bool vert_Receiver = sr.ReadBoolean();
                        for (int s = 0; s < s_ct; s++)
                        {
                            Map[s].Rec_Vertex = vert_Receiver;
                            for (int i = 0; i < Map[s].Rec_List.Length; i++)
                            {
                                //for version 1.7 and up, write direct sound arrival time.
                                //Write Receiver Index (int)
                                int j = (int)sr.ReadUInt32();
                                //Write Direct Sound Arrival Time.
                                double Direct_Time;
                                if (version >= 1.7)
                                {
                                    Direct_Time = sr.ReadDouble();
                                }
                                else
                                {
                                    Direct_Time = (Utilities.PachTools.RPttoHPt(Map[s].Src) - Map[s].Rec_List[i].H_Origin).Length() / 343f;
                                }
                                //Write Impedance of Air
                                double Rho_C = version >= 2.0 ? sr.ReadDouble() : 400;

                                if (vert_Receiver)
                                {
                                    Map[s].Rec_List[i] = new Mapping.PachMapReceiver.Map_Receiver(Map_Mesh.Vertices[i], new Rhino.Geometry.Point3f((float)Map[s].Src.X, (float)Map[s].Src.Y, (float)Map[s].Src.Z), Direct_Time, Rho_C, i, SampleRate, SampleCT, Directional);
                                }
                                else
                                {
                                    Rhino.Geometry.Point3d RecLoc = Map_Mesh.Faces.GetFaceCenter(i);
                                    Map[s].Rec_List[i] = new Mapping.PachMapReceiver.Map_Receiver(new Rhino.Geometry.Point3f((float)RecLoc.X, (float)RecLoc.Y, (float)RecLoc.Z), new Rhino.Geometry.Point3f((float)Map[s].Src.X, (float)Map[s].Src.Y, (float)Map[s].Src.Z), Direct_Time, Rho_C, i, SampleRate, SampleCT, Directional);
                                }

                                for (int Octave = 0; Octave < 8; Octave++)
                                {
                                    //Write Octave (int)
                                    int Oct_out = (int)sr.ReadUInt32();
                                    if (Oct_out != Octave)
                                    {
                                        throw new Exception(string.Format("Octave {0} Expected", Octave));
                                    }
                                    double[] Hist = Map[s].Rec_List[i].GetEnergyHistogram(Octave);
                                    if (Directional)
                                    {
                                        if (version < 1.7)
                                        {
                                            for (int e = 0; e < SampleCT; e++)
                                            {
                                                Map[s].Rec_List[i].Combine_Sample(e, sr.ReadDouble(), new Hare.Geometry.Vector(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()), new Hare.Geometry.Vector(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()), Octave);
                                            }
                                        }
                                        else
                                        {
                                            for (int e = 0; e < SampleCT; e++)
                                            {
                                                Map[s].Rec_List[i].Combine_Sample(e, sr.ReadDouble(), new Hare.Geometry.Vector(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()), new Hare.Geometry.Vector(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()), Octave);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (version < 1.7)
                                        {
                                            for (int e = 0; e < SampleCT; e++)
                                            {
                                                Map[s].Rec_List[i].Combine_Sample(e, sr.ReadDouble(), new Hare.Geometry.Vector(0, 0, 0), new Hare.Geometry.Vector(0, 0, 0), Octave);
                                            }
                                        }
                                        else
                                        {
                                            for (int e = 0; e < SampleCT; e++)
                                            {
                                                Map[s].Rec_List[i].Combine_Sample(e, sr.ReadDouble(), new Hare.Geometry.Vector(0, 0, 0), new Hare.Geometry.Vector(0, 0, 0), Octave);
                                            }
                                        }
                                    }
                                }
                                if (sr.ReadString() != "End_Receiver_Hits")
                                {
                                    throw new Exception("End of Receiver Hits Expected");
                                }
                            }
                        }
                        break;

                    case "End_of_File":
                        sr.Close();
                        return(true);
                    }
                } while (true);
                throw new Exception("Unsuccessful Read");
            }
Esempio n. 21
0
		/// <summary>Loads the black-box logs from the previous simulation run</summary>
		internal static void LoadLogs()
		{
			string BlackBoxFile = OpenBveApi.Path.CombineFile(Program.FileSystem.SettingsFolder, "logs.bin");
			try
			{
				using (System.IO.FileStream Stream = new System.IO.FileStream(BlackBoxFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))
				{
					using (System.IO.BinaryReader Reader = new System.IO.BinaryReader(Stream, System.Text.Encoding.UTF8))
					{
						byte[] Identifier = new byte[] { 111, 112, 101, 110, 66, 86, 69, 95, 76, 79, 71, 83 };
						const short Version = 1;
						byte[] Data = Reader.ReadBytes(Identifier.Length);
						for (int i = 0; i < Identifier.Length; i++)
						{
							if (Identifier[i] != Data[i]) throw new System.IO.InvalidDataException();
						}
						short Number = Reader.ReadInt16();
						if (Version != Number) throw new System.IO.InvalidDataException();
						Game.LogRouteName = Reader.ReadString();
						Game.LogTrainName = Reader.ReadString();
						Game.LogDateTime = DateTime.FromBinary(Reader.ReadInt64());
						Interface.CurrentOptions.GameMode = (Interface.GameMode)Reader.ReadInt16();
						Game.BlackBoxEntryCount = Reader.ReadInt32();
						Game.BlackBoxEntries = new Game.BlackBoxEntry[Game.BlackBoxEntryCount];
						for (int i = 0; i < Game.BlackBoxEntryCount; i++)
						{
							Game.BlackBoxEntries[i].Time = Reader.ReadDouble();
							Game.BlackBoxEntries[i].Position = Reader.ReadDouble();
							Game.BlackBoxEntries[i].Speed = Reader.ReadSingle();
							Game.BlackBoxEntries[i].Acceleration = Reader.ReadSingle();
							Game.BlackBoxEntries[i].ReverserDriver = Reader.ReadInt16();
							Game.BlackBoxEntries[i].ReverserSafety = Reader.ReadInt16();
							Game.BlackBoxEntries[i].PowerDriver = (Game.BlackBoxPower)Reader.ReadInt16();
							Game.BlackBoxEntries[i].PowerSafety = (Game.BlackBoxPower)Reader.ReadInt16();
							Game.BlackBoxEntries[i].BrakeDriver = (Game.BlackBoxBrake)Reader.ReadInt16();
							Game.BlackBoxEntries[i].BrakeSafety = (Game.BlackBoxBrake)Reader.ReadInt16();
							Game.BlackBoxEntries[i].EventToken = (Game.BlackBoxEventToken)Reader.ReadInt16();
						}
						Game.ScoreLogCount = Reader.ReadInt32();
						Game.ScoreLogs = new Game.ScoreLog[Game.ScoreLogCount];
						Game.CurrentScore.Value = 0;
						for (int i = 0; i < Game.ScoreLogCount; i++)
						{
							Game.ScoreLogs[i].Time = Reader.ReadDouble();
							Game.ScoreLogs[i].Position = Reader.ReadDouble();
							Game.ScoreLogs[i].Value = Reader.ReadInt32();
							Game.ScoreLogs[i].TextToken = (Game.ScoreTextToken)Reader.ReadInt16();
							Game.CurrentScore.Value += Game.ScoreLogs[i].Value;
						}
						Game.CurrentScore.Maximum = Reader.ReadInt32();
						Identifier = new byte[] { 95, 102, 105, 108, 101, 69, 78, 68 };
						Data = Reader.ReadBytes(Identifier.Length);
						for (int i = 0; i < Identifier.Length; i++)
						{
							if (Identifier[i] != Data[i]) throw new System.IO.InvalidDataException();
						}
						Reader.Close();
					} Stream.Close();
				}
			}
			catch
			{
				Game.LogRouteName = "";
				Game.LogTrainName = "";
				Game.LogDateTime = DateTime.Now;
				Game.BlackBoxEntries = new Game.BlackBoxEntry[256];
				Game.BlackBoxEntryCount = 0;
				Game.ScoreLogs = new Game.ScoreLog[64];
				Game.ScoreLogCount = 0;
			}
		}
Esempio n. 22
0
        public static JSONNode Deserialize(System.IO.BinaryReader aReader)
        {
            JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();

            switch (type)
            {
            case JSONBinaryTag.Array:
            {
                int       count = aReader.ReadInt32();
                JSONArray tmp   = new JSONArray();
                for (int i = 0; i < count; i++)
                {
                    tmp.Add(Deserialize(aReader));
                }
                return(tmp);
            }

            case JSONBinaryTag.Class:
            {
                int       count = aReader.ReadInt32();
                JSONClass tmp   = new JSONClass();
                for (int i = 0; i < count; i++)
                {
                    string key = aReader.ReadString();
                    var    val = Deserialize(aReader);
                    tmp.Add(key, val);
                }
                return(tmp);
            }

            case JSONBinaryTag.Value:
            {
                return(new JSONData(aReader.ReadString()));
            }

            case JSONBinaryTag.IntValue:
            {
                return(new JSONData(aReader.ReadInt32()));
            }

            case JSONBinaryTag.DoubleValue:
            {
                return(new JSONData(aReader.ReadDouble()));
            }

            case JSONBinaryTag.BoolValue:
            {
                return(new JSONData(aReader.ReadBoolean()));
            }

            case JSONBinaryTag.FloatValue:
            {
                return(new JSONData(aReader.ReadSingle()));
            }

            default:
            {
                throw new Exception("Error deserializing JSON. Unknown tag: " + type);
            }
            }
        }
        private bool FinalizeSpritePackInfo(byte[] bytes)
        {
            var spritePack = new RBRenderer.SpritePack();

            spritePack.sprites = new Dictionary <int, PackedSprite>();

            try
            {
                var reader = new System.IO.BinaryReader(new System.IO.MemoryStream(bytes));

                if (reader.ReadUInt16() != RBRenderer.RetroBlit_SP_MAGIC)
                {
                    Debug.Log("Sprite pack index file " + path + " is invalid!");
                    return(false);
                }

                if (reader.ReadUInt16() != RBRenderer.RetroBlit_SP_VERSION)
                {
                    Debug.Log("Sprite pack file " + path + " version is not supported!");
                    return(false);
                }

                int spriteCount = reader.ReadInt32();
                if (spriteCount < 0 || spriteCount > 200000)
                {
                    Debug.Log("Sprite pack sprite count is invalid! Please try reimporting" + path + ".rb");
                    return(false);
                }

                for (int i = 0; i < spriteCount; i++)
                {
                    int hash = reader.ReadInt32();

                    var size = new Vector2i();
                    size.x = (int)reader.ReadUInt16();
                    size.y = (int)reader.ReadUInt16();

                    var sourceRect = new Rect2i();
                    sourceRect.x      = (int)reader.ReadUInt16();
                    sourceRect.y      = (int)reader.ReadUInt16();
                    sourceRect.width  = (int)reader.ReadUInt16();
                    sourceRect.height = (int)reader.ReadUInt16();

                    var trimOffset = new Vector2i();
                    trimOffset.x = (int)reader.ReadUInt16();
                    trimOffset.y = (int)reader.ReadUInt16();

                    var packedSprite = new PackedSprite(new PackedSpriteID(hash), size, sourceRect, trimOffset);

                    spritePack.sprites.Add(hash, packedSprite);
                }
            }
            catch (System.Exception e)
            {
                Debug.Log("Sprite pack index file " + path + " is invalid! Exception: " + e.ToString());
                return(false);
            }

            spriteSheetAsset.internalState.spritePack = spritePack;

            return(true);
        }
Esempio n. 24
0
        public static bool downloadFile(string pagename, int databaseid, string filepath, DownloadingFileHandler callback)
        {
            HttpWebRequest  req = null;
            HttpWebResponse res = null;

            System.IO.Stream stream = null;
            bool             result = false;

            System.GC.Collect();
            try
            {
                req = HttpWebRequest.Create(Helper.WebSite + "/" + pagename + "?databaseid=" + databaseid + "&filepath=" + System.Web.HttpUtility.UrlEncode(filepath, System.Text.Encoding.UTF8)) as System.Net.HttpWebRequest;
                req.Headers["Cookie"] = $"WayScriptRemoting={Net.RemotingClient.SessionID}";
                req.AllowAutoRedirect = true;
                req.KeepAlive         = false;
                req.Timeout           = 20000;
                req.ServicePoint.ConnectionLeaseTimeout = 2 * 60 * 1000;

                res    = req.GetResponse() as System.Net.HttpWebResponse;
                stream = res.GetResponseStream();

                using (var fs = System.IO.File.Create(filepath))
                {
                    byte[] header;
                    if (pagename == "DownloadDatabaseCode.aspx")
                    {
                        header = System.Text.Encoding.UTF8.GetBytes(@"
using System;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;

");
                    }
                    else
                    {
                        header = System.Text.Encoding.UTF8.GetBytes(@"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

");
                    }
                    fs.Write(header, 0, header.Length);

                    System.IO.BinaryReader br = new System.IO.BinaryReader(stream);
                    string msg = br.ReadString();
                    if (msg != "start")
                    {
                        throw new Exception(msg);
                    }

                    int fileCount = br.ReadInt32();
                    int readed    = 0;
                    while (true)
                    {
                        string filename = br.ReadString();
                        if (filename == ":end")
                        {
                            break;
                        }
                        int    len  = br.ReadInt32();
                        byte[] data = br.ReadBytes(len);

                        readed++;
                        fs.Write(data, 0, data.Length);
                        callback(filename, data, fileCount, readed);
                    }
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close(); stream.Dispose();
                }
                if (req != null)
                {
                    req.Abort();
                    req = null;
                }
                if (res != null)
                {
                    res.Close();
                    res = null;
                }
            }
            return(result);
        }
Esempio n. 25
0
        /// <summary>Loads the black-box logs from the previous simulation run</summary>
        internal static void LoadLogs()
        {
            string BlackBoxFile = OpenBveApi.Path.CombineFile(Program.FileSystem.SettingsFolder, "logs.bin");

            try
            {
                using (System.IO.FileStream Stream = new System.IO.FileStream(BlackBoxFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    using (System.IO.BinaryReader Reader = new System.IO.BinaryReader(Stream, System.Text.Encoding.UTF8))
                    {
                        byte[]      Identifier = new byte[] { 111, 112, 101, 110, 66, 86, 69, 95, 76, 79, 71, 83 };
                        const short Version    = 1;
                        byte[]      Data       = Reader.ReadBytes(Identifier.Length);
                        for (int i = 0; i < Identifier.Length; i++)
                        {
                            if (Identifier[i] != Data[i])
                            {
                                throw new System.IO.InvalidDataException();
                            }
                        }
                        short Number = Reader.ReadInt16();
                        if (Version != Number)
                        {
                            throw new System.IO.InvalidDataException();
                        }
                        Game.LogRouteName = Reader.ReadString();
                        Game.LogTrainName = Reader.ReadString();
                        Game.LogDateTime  = DateTime.FromBinary(Reader.ReadInt64());
                        Interface.CurrentOptions.PreviousGameMode = (GameMode)Reader.ReadInt16();
                        Game.BlackBoxEntryCount = Reader.ReadInt32();
                        Game.BlackBoxEntries    = new Game.BlackBoxEntry[Game.BlackBoxEntryCount];
                        for (int i = 0; i < Game.BlackBoxEntryCount; i++)
                        {
                            Game.BlackBoxEntries[i].Time           = Reader.ReadDouble();
                            Game.BlackBoxEntries[i].Position       = Reader.ReadDouble();
                            Game.BlackBoxEntries[i].Speed          = Reader.ReadSingle();
                            Game.BlackBoxEntries[i].Acceleration   = Reader.ReadSingle();
                            Game.BlackBoxEntries[i].ReverserDriver = Reader.ReadInt16();
                            Game.BlackBoxEntries[i].ReverserSafety = Reader.ReadInt16();
                            Game.BlackBoxEntries[i].PowerDriver    = (Game.BlackBoxPower)Reader.ReadInt16();
                            Game.BlackBoxEntries[i].PowerSafety    = (Game.BlackBoxPower)Reader.ReadInt16();
                            Game.BlackBoxEntries[i].BrakeDriver    = (Game.BlackBoxBrake)Reader.ReadInt16();
                            Game.BlackBoxEntries[i].BrakeSafety    = (Game.BlackBoxBrake)Reader.ReadInt16();
                            Game.BlackBoxEntries[i].EventToken     = (Game.BlackBoxEventToken)Reader.ReadInt16();
                        }
                        Game.ScoreLogCount             = Reader.ReadInt32();
                        Game.ScoreLogs                 = new Game.ScoreLog[Game.ScoreLogCount];
                        Game.CurrentScore.CurrentValue = 0;
                        for (int i = 0; i < Game.ScoreLogCount; i++)
                        {
                            Game.ScoreLogs[i].Time          = Reader.ReadDouble();
                            Game.ScoreLogs[i].Position      = Reader.ReadDouble();
                            Game.ScoreLogs[i].Value         = Reader.ReadInt32();
                            Game.ScoreLogs[i].TextToken     = (Game.ScoreTextToken)Reader.ReadInt16();
                            Game.CurrentScore.CurrentValue += Game.ScoreLogs[i].Value;
                        }
                        Game.CurrentScore.Maximum = Reader.ReadInt32();
                        Identifier = new byte[] { 95, 102, 105, 108, 101, 69, 78, 68 };
                        Data       = Reader.ReadBytes(Identifier.Length);
                        for (int i = 0; i < Identifier.Length; i++)
                        {
                            if (Identifier[i] != Data[i])
                            {
                                throw new System.IO.InvalidDataException();
                            }
                        }
                        Reader.Close();
                    } Stream.Close();
                }
            }
            catch
            {
                Game.LogRouteName       = "";
                Game.LogTrainName       = "";
                Game.LogDateTime        = DateTime.Now;
                Game.BlackBoxEntries    = new Game.BlackBoxEntry[256];
                Game.BlackBoxEntryCount = 0;
                Game.ScoreLogs          = new Game.ScoreLog[64];
                Game.ScoreLogCount      = 0;
            }
        }
Esempio n. 26
0
        static void Main(string[] args)
        {
            if (args.Length < 3)
            {
                return;
            }

            string bin         = args[0];
            string txt         = args[1];
            string jis2ucs_new = args[2];

            System.IO.FileStream   fs = System.IO.File.OpenRead(bin);
            System.IO.BinaryReader br = new System.IO.BinaryReader(fs);

            System.IO.FileStream   fs_new = System.IO.File.Create(jis2ucs_new);
            System.IO.BinaryWriter bw     = new System.IO.BinaryWriter(fs_new);

            System.IO.StreamWriter sw = new System.IO.StreamWriter(txt);

            for (int i = 0x20; i < 0x7F; i++)
            {
                sw.WriteLine("{0:X4}", i);
            }

            for (int i = 0xFF01; i < 0xFF5F; i++)
            {
                sw.WriteLine("{0:X4}", i);
            }

            for (int i = 0; i < sp.Length; i += 2)
            {
                sw.WriteLine("{0:X4}={1:X4}", (UInt16)sp[i], (UInt16)sp[i + 1]);
            }

            fs_new.Write(Resources.jis2ucs, 0, Resources.jis2ucs.Length);

            int num = br.ReadInt32();

            for (int i = 0; i < num; i++)
            {
                int    jis = br.ReadUInt16();
                UInt16 ucs = br.ReadUInt16();

                int off = jis2ucs_bin.JIS2Offset(jis);
                fs_new.Seek(off, 0);
                bw.Write(ucs);

                if (ucs >= 0x4000 && ucs < 0xF000)
                {
                    sw.WriteLine("{0:X4}", ucs);
                }
            }

            bw.Close();
            fs_new.Close();

            br.Close();
            fs.Close();

            sw.Close();
        }
Esempio n. 27
0
        private void OpenFile(string filename)
        {
#if !DEBUG
            try
            {
#endif
            _filename = filename;
            fileIn    = new System.IO.BinaryReader(System.IO.File.Open(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read));

            string startFileSig = "";
            for (int i = 0; i < 4; i++)     // 4 bytes
            {
                startFileSig += fileIn.ReadChar();
            }
            if (startFileSig != "#PES")
            {
                // This is not a file that we can read
                readyStatus = statusEnum.ParseError;
                lastError   = "Missing #PES at beginning of file";
                fileIn.Close();
                return;
            }

            // PES version
            string versionString = "";
            for (int i = 0; i < 4; i++)     // 4 bytes
            {
                versionString += fileIn.ReadChar();
            }
            pesVersion = Convert.ToUInt16(versionString);

            int pecstart = fileIn.ReadInt32();

            // Read number of colors in this design
            fileIn.BaseStream.Position = pecstart + 48;
            int numColors         = fileIn.ReadByte() + 1;
            List <byte> colorList = new List <byte>();
            for (int x = 0; x < numColors; x++)
            {
                colorList.Add(fileIn.ReadByte());
            }

            // Read stitch data
            fileIn.BaseStream.Position = pecstart + 532;
            bool thisPartIsDone = false;
            StitchBlock curBlock;
            int prevX                  = 0;
            int prevY                  = 0;
            int maxX                   = 0;
            int minX                   = 0;
            int maxY                   = 0;
            int minY                   = 0;
            int colorNum               = -1;
            int colorIndex             = 0;
            List <Stitch> tempStitches = new List <Stitch>();
            while (!thisPartIsDone)
            {
                byte val1;
                byte val2;
                val1 = fileIn.ReadByte();
                val2 = fileIn.ReadByte();
                if (val1 == 0xff && val2 == 0x00)
                {
                    //end of stitches
                    thisPartIsDone = true;

                    //add the last block
                    curBlock          = new StitchBlock();
                    curBlock.stitches = new Stitch[tempStitches.Count];
                    tempStitches.CopyTo(curBlock.stitches);
                    curBlock.stitchesTotal = tempStitches.Count;
                    colorNum++;
                    colorIndex          = colorList[colorNum];
                    curBlock.colorIndex = colorIndex;
                    curBlock.color      = getColorFromIndex(colorIndex);
                    blocks.Add(curBlock);
                }
                else if (val1 == 0xfe && val2 == 0xb0)
                {
                    //color switch, start a new block

                    curBlock          = new StitchBlock();
                    curBlock.stitches = new Stitch[tempStitches.Count];
                    tempStitches.CopyTo(curBlock.stitches);
                    curBlock.stitchesTotal = tempStitches.Count;
                    colorNum++;
                    colorIndex          = colorList[colorNum];
                    curBlock.colorIndex = colorIndex;
                    curBlock.color      = getColorFromIndex(colorIndex);
                    //read useless(?) byte
                    // The value of this 'useless' byte seems to alternate
                    // between 2 and 1 for every other block. The only
                    // exception I've noted is the last block which appears
                    // to always be 0.
                    curBlock.unknownStartByte = fileIn.ReadByte();
                    blocks.Add(curBlock);

                    tempStitches = new List <Stitch>();
                }
                else
                {
                    int deltaX = 0;
                    int deltaY = 0;
                    if ((val1 & 0x80) == 0x80)
                    {
                        // This is a 12-bit int. Allows for needle movement
                        // of up to +2047 or -2048.
                        deltaX = get12Bit2sComplement(val1, val2);

                        // The X value used both bytes, so read next byte
                        // for Y value.
                        val1 = fileIn.ReadByte();
                    }
                    else
                    {
                        // This is a 7-bit int. Allows for needle movement
                        // of up to +63 or -64.
                        deltaX = get7Bit2sComplement(val1);

                        // The X value only used 1 byte, so copy the second
                        // to to the first for Y value.
                        val1 = val2;
                    }

                    if ((val1 & 0x80) == 0x80)
                    {
                        // This is a 12-bit int. Allows for needle movement
                        // of up to +2047 or -2048.
                        // Read in the next byte to get the full value
                        val2   = fileIn.ReadByte();
                        deltaY = get12Bit2sComplement(val1, val2);
                    }
                    else
                    {
                        // This is a 7-bit int. Allows for needle movement
                        // of up to +63 or -64.
                        deltaY = get7Bit2sComplement(val1);
                        // Finished reading data for this stitch, no more
                        // bytes needed.
                    }
                    tempStitches.Add(
                        new Stitch(
                            new Point(prevX, prevY),
                            new Point(prevX + deltaX, prevY + deltaY)
                            )
                        );
                    prevX = prevX + deltaX;
                    prevY = prevY + deltaY;
                    if (prevX > maxX)
                    {
                        maxX = prevX;
                    }
                    else if (prevX < minX)
                    {
                        minX = prevX;
                    }

                    if (prevY > maxY)
                    {
                        maxY = prevY;
                    }
                    else if (prevY < minY)
                    {
                        minY = prevY;
                    }
                }
            }
            imageWidth       = maxX - minX;
            imageHeight      = maxY - minY;
            translateStart.X = -minX;
            translateStart.Y = -minY;
            readyStatus      = statusEnum.Ready;

            // Close the file
            fileIn.Close();

#if !DEBUG
        }

        catch (System.IO.IOException ioex)
        {
            readyStatus = statusEnum.IOError;
            lastError   = ioex.Message;
            if (fileIn != null)
            {
                fileIn.Close();
            }
        }
        catch (Exception ex)
        {
            readyStatus = statusEnum.ParseError;
            lastError   = ex.Message;
            if (fileIn != null)
            {
                fileIn.Close();
            }
        }
#endif
        }
Esempio n. 28
0
        public static Instruction ParseInstruction(System.IO.BinaryReader br, Assembly asm, Function func)
        {
            Instructions op   = (Instructions)br.ReadInt16();
            Instruction  insn = new Instruction();

            insn.Assembly = asm;
            insn.Function = func;
            insn.Inst     = op;
            switch (op)
            {
            case Instructions.BneLocal:
            case Instructions.BgeLocal:
            case Instructions.BltLocal:
            case Instructions.BgtLocal:
            case Instructions.BneField:
            case Instructions.BeqField:
            case Instructions.BneFieldLocal:
            case Instructions.BgtField:
                insn.Operand1 = br.ReadInt32();
                insn.Operand2 = br.ReadInt32();
                insn.Operand3 = br.ReadInt32();
                insn.BranchTarget.Add(insn.Operand3);
                insn.StartNewBlock = true;
                break;

            case Instructions.Jmp:
                insn.Operand1 = br.ReadInt32();
                insn.BranchTarget.Add(insn.Operand1);
                insn.EndBlock = true;
                break;

            case Instructions.BrFalse:
            case Instructions.BrTrue:
                insn.Operand1 = br.ReadInt32();
                insn.BranchTarget.Add(insn.Operand1);
                insn.StartNewBlock = true;
                break;

            case Instructions.Switch:
            case Instructions.SwitchS:
                insn.Operand1 = br.ReadInt32();
                Switch swi = asm.SwitchTables[insn.Operand1];
                foreach (int i in swi.SwitchTable.Values)
                {
                    insn.BranchTarget.Add(i);
                }
                if (swi.DefaultCase != -1)
                {
                    insn.BranchTarget.Add(swi.DefaultCase);
                }
                break;

            case Instructions.Push:
            case Instructions.CallMethod:
            case Instructions.Call:
            case Instructions.RefGlobal:
            case Instructions.RefLocal:
            case Instructions.PushS:
            case Instructions.AssertFunc:
            case Instructions.AssertFile:
            case Instructions.CallSys:
            case Instructions.EndOfFunc:
            case Instructions.StructDelLocal:
            case Instructions.PushField:
            case Instructions.IncLocal:
            case Instructions.DecLocal:
            case Instructions.ArraySizeField:
            case Instructions.ArraySizeGlobal:
            case Instructions.PushLocal2:
            case Instructions.PushSLocal:
            case Instructions.AssignSConst:
            case Instructions.PushSField:
            case Instructions.ArrayStructRef:
            case Instructions.PushSGlobal:
            case Instructions.AssignSLocal:
            case Instructions.StringEmptyLocal:
            case Instructions.StringEmptyField:
            case Instructions.StructRef:
            case Instructions.AssignSField:
            case Instructions.Msg:
                insn.Operand1 = br.ReadInt32();
                break;

            case Instructions.PushF:
                insn.Operand1F = br.ReadSingle();
                break;

            case Instructions.BrFalseField:
            case Instructions.BNotEmptyField:
            case Instructions.BneS:
                insn.Operand1 = br.ReadInt32();
                insn.Operand2 = br.ReadInt32();
                insn.BranchTarget.Add(insn.Operand2);
                insn.StartNewBlock = true;
                break;

            case Instructions.StructCreateLocal:
            case Instructions.AssignLocal:
            case Instructions.AssignField:
            case Instructions.CallHLL:
            case Instructions.AssignFieldLocal:
            case Instructions.AssignGlobalLocal:
            case Instructions.AssignLocalField:
            case Instructions.ArrayPushBackLocal:
            case Instructions.AssignGlobal:
            case Instructions.GeField:
            case Instructions.EqlSLocal:
            case Instructions.NeqSLocal:
            case Instructions.EqlSFieldLocal:
            case Instructions.AssignSFieldLocal:
            case Instructions.PushStructRefField:
            case Instructions.ArrayPushBackFieldLocal:
            case Instructions.AssignArrayLocalField:
            case Instructions.ArrayPushBackLocalString:
            case Instructions.ArrayPushBackGlobalLocalRef:
            case Instructions.ArrayPushBackFieldLocalRef:
            case Instructions.AssignFieldLocalITOB:
            case Instructions.ArrayPushBackGlobalLocal:
            case Instructions.MinLocal:
            case Instructions.NeqFieldS:
            case Instructions.NeqSFieldLocal:
            case Instructions.AssignSLocalLocal:
                insn.Operand1 = br.ReadInt32();
                insn.Operand2 = br.ReadInt32();
                break;

            case Instructions.LtOrGeLocal:
                insn.Operand1 = br.ReadInt32();
                insn.Operand2 = br.ReadInt32();
                insn.Operand3 = br.ReadInt32();
                break;

            case Instructions.Ret:
                insn.EndBlock = true;
                break;

            case Instructions.PushSP:
            case Instructions.Le:
            default:
                break;
            }
            return(insn);
        }
Esempio n. 29
0
        private void readUIC4tagData(System.IO.BinaryReader reader)
        {
            System.IO.Stream stream = reader.BaseStream;

            UIC4data = new SortedList <ushort, TiffData[]>();
            ushort id = reader.ReadUInt16();

            while (id > 0)
            {
                // UIC4 2*(# OF PLANES) RATIONALS
                if (id == StkInfoCollection.StagePosition || id == StkInfoCollection.CameraChipOffset)
                {
                    TiffData[] data = new TiffData[numPlane];
                    for (int i = 0; i < numPlane; i++)
                    {
                        data[i] = new TiffData(TiffData.TIFFdataType.Rational, 2);
                        data[i].read(reader);
                    }
                    UIC4data.Add(id, data);
                }
                // UIC4 (# OF PLANES) STRINGS
                else if (id == StkInfoCollection.StageLabel)
                {
                    TiffData[] data = new TiffData[numPlane];
                    for (int i = 0; i < numPlane; i++)
                    {
                        data[i] = new TiffData(TiffData.TIFFdataType.Ascii, reader.ReadInt32());
                        data[i].read(reader);
                    }
                    UIC4data.Add(id, data);
                }
                // UIC4 (# OF PLANES) RATIONALS
                else if (id == StkInfoCollection.AbsoluteZ || id == StkInfoCollection.CameraBin)
                {
                    TiffData[] data = new TiffData[numPlane];
                    for (int i = 0; i < numPlane; i++)
                    {
                        data[i] = new TiffData(TiffData.TIFFdataType.Rational, 1);
                        data[i].read(reader);
                    }
                    UIC4data.Add(id, data);
                }
                // UIC4 (# OF PLANES) LONGS
                else if (id == StkInfoCollection.AbsoluteZValid)
                {
                    TiffData[] data = new TiffData[numPlane];
                    for (int i = 0; i < numPlane; i++)
                    {
                        data[i] = new TiffData(TiffData.TIFFdataType.Long, 1);
                        data[i].read(reader);
                    }
                    UIC4data.Add(id, data);
                }
                // ignore any other tags
                else
                {
                    return;
                }
                id = reader.ReadUInt16();
            }
        }
Esempio n. 30
0
        private void readUIC1tagData(System.IO.BinaryReader reader, int count)
        {
            System.IO.Stream stream = reader.BaseStream;

            UIC1data = new SortedList <uint, TiffData[]>();
            for (int i = 0; i < count; i++)
            {
                uint id = reader.ReadUInt32();

                // ONE LONG
                //New Lut??
                if (id == StkInfoCollection.AutoScale || id == StkInfoCollection.MinScale || id == StkInfoCollection.MaxScale || id == StkInfoCollection.SpatialCalibration ||
                    id == StkInfoCollection.ThreshState || id == StkInfoCollection.ThreshStateRed || id == StkInfoCollection.ThreshStateBlue || id == StkInfoCollection.ThreshStateGreen ||
                    id == StkInfoCollection.ThreshStateLo || id == StkInfoCollection.ThreshStateHi || id == StkInfoCollection.Zoom || id == StkInfoCollection.CurrentBuffer ||
                    id == StkInfoCollection.GrayFit || id == StkInfoCollection.GrayPointCount || id == StkInfoCollection.WavelengthTag ||
                    id == StkInfoCollection.RedAutoScaleInfo || id == StkInfoCollection.RedMinScaleInfo || id == StkInfoCollection.RedMaxScaleInfo ||
                    id == StkInfoCollection.GreenAutoScaleInfo || id == StkInfoCollection.GreenMinScaleInfo || id == StkInfoCollection.GreenMaxScaleInfo ||
                    id == StkInfoCollection.BlueAutoScaleInfo || id == StkInfoCollection.BlueMinScaleInfo || id == StkInfoCollection.BlueMaxScaleInfo ||
                    id == StkInfoCollection.GrayUnitName || id == StkInfoCollection.StandardLUT || id == StkInfoCollection.NewLUT ||
                    id == 10)
                {
                    TiffData data = new TiffData(TiffData.TIFFdataType.Long, 1);
                    data.read(reader);
                    UIC1data.Add(id, new TiffData[1] {
                        data
                    });
                }
                // ONE RATIONAL
                else if (id == StkInfoCollection.XCalibration || id == StkInfoCollection.YCalibration || id == StkInfoCollection.CreateTime || id == StkInfoCollection.LastSavedTime ||
                         id == StkInfoCollection.GrayX || id == StkInfoCollection.GrayY || id == StkInfoCollection.GrayMin || id == StkInfoCollection.GrayMax ||
                         id == StkInfoCollection.AutoScaleLoInfo || id == StkInfoCollection.AutoScaleHiInfo ||
                         id == StkInfoCollection.RedAutoScaleLoInfo || id == StkInfoCollection.RedAutoScaleHiInfo ||
                         id == StkInfoCollection.GreenAutoScaleLoInfo || id == StkInfoCollection.GreenAutoScaleHiInfo ||
                         id == StkInfoCollection.BlueAutoScaleHiInfo || id == StkInfoCollection.BlueAutoScaleLoInfo)
                {
                    long offset  = reader.ReadUInt32();
                    long currPos = stream.Position;
                    stream.Seek(offset, System.IO.SeekOrigin.Begin);
                    TiffData data = new TiffData(TiffData.TIFFdataType.Rational, 1);
                    data.read(reader);
                    UIC1data.Add(id, new TiffData[1] {
                        data
                    });
                    stream.Seek(currPos, System.IO.SeekOrigin.Begin);
                }
                // 2*N LONG (N RATIONALs)
                else if (id == StkInfoCollection.AbsoluteZ)
                {
                    long offset  = reader.ReadUInt32();
                    long currPos = stream.Position;
                    stream.Seek(offset, System.IO.SeekOrigin.Begin);
                    TiffData data = new TiffData(TiffData.TIFFdataType.Rational, numPlane);
                    data.read(reader);
                    UIC1data.Add(id, new TiffData[1] {
                        data
                    });
                    stream.Seek(currPos, System.IO.SeekOrigin.Begin);
                }
                // N LONGs
                else if (id == StkInfoCollection.AbsoluteZValid)
                {
                    long offset  = reader.ReadUInt32();
                    long currPos = stream.Position;
                    stream.Seek(offset, System.IO.SeekOrigin.Begin);
                    TiffData data = new TiffData(TiffData.TIFFdataType.Long, numPlane);
                    data.read(reader);
                    UIC1data.Add(id, new TiffData[1] {
                        data
                    });
                    stream.Seek(currPos, System.IO.SeekOrigin.Begin);
                }
                // STRING
                else if (id == StkInfoCollection.CalibrationUnits || id == StkInfoCollection.Name)
                {
                    long offset  = reader.ReadUInt32();
                    long currPos = stream.Position;
                    stream.Seek(offset, System.IO.SeekOrigin.Begin);
                    TiffData data = new TiffData(TiffData.TIFFdataType.Ascii, reader.ReadInt32());
                    data.read(reader);
                    UIC1data.Add(id, new TiffData[1] {
                        data
                    });
                    stream.Seek(currPos, System.IO.SeekOrigin.Begin);
                }
                // OFFSET OF A LONG
                else if (id == StkInfoCollection.Gamma || id == StkInfoCollection.GammaRed || id == StkInfoCollection.GammaGreen || id == StkInfoCollection.GammaBlue)
                {
                    long offset  = reader.ReadUInt32();
                    long currPos = stream.Position;
                    stream.Seek(offset, System.IO.SeekOrigin.Begin);
                    TiffData data = new TiffData(TiffData.TIFFdataType.Long, 1);
                    data.read(reader);
                    UIC1data.Add(id, new TiffData[1] {
                        data
                    });
                    stream.Seek(currPos, System.IO.SeekOrigin.Begin);
                }
                // RGB TABLE
                else if (id == StkInfoCollection.UserLutTable)
                {
                    long offset  = reader.ReadUInt32();
                    long currPos = stream.Position;
                    stream.Seek(offset, System.IO.SeekOrigin.Begin);
                    TiffData data = new TiffData(TiffData.TIFFdataType.Byte, 768);
                    data.read(reader);
                    UIC1data.Add(id, new TiffData[1] {
                        data
                    });
                    stream.Seek(currPos, System.IO.SeekOrigin.Begin);
                }
                // 4*N long (2*N RATIONALS)
                else if (id == StkInfoCollection.StagePosition || id == StkInfoCollection.CameraChipOffset)
                {
                    long offset  = reader.ReadUInt32();
                    long currPos = stream.Position;
                    stream.Seek(offset, System.IO.SeekOrigin.Begin);
                    TiffData data = new TiffData(TiffData.TIFFdataType.Rational, 2 * numPlane);
                    data.read(reader);
                    UIC1data.Add(id, new TiffData[1] {
                        data
                    });
                    stream.Seek(currPos, System.IO.SeekOrigin.Begin);
                }
                // IGNORED FOR NOW
                else if (id == StkInfoCollection.CameraBin || id == StkInfoCollection.ImagePropertyEx || id == StkInfoCollection.OverlayPlaneColor)
                {
                    reader.ReadUInt32();
                }
                // N STRINGs
                else if (id == StkInfoCollection.StageLabel)
                {
                    long offset  = reader.ReadUInt32();
                    long currPos = stream.Position;
                    if (offset >= 0)
                    {
                        try {
                            stream.Seek(offset, System.IO.SeekOrigin.Begin);
                            uint[]     pos  = new uint[numPlane];
                            TiffData[] data = new TiffData[numPlane];
                            stream.Seek(reader.ReadUInt32(), System.IO.SeekOrigin.Begin);
                            for (int x = 0; x < numPlane; x++)
                            {
                                data[x] = new TiffData(TiffData.TIFFdataType.Ascii, reader.ReadInt32());
                            }
                            UIC1data.Add(id, data);
                        } catch {
                        } finally {
                            stream.Seek(currPos, System.IO.SeekOrigin.Begin);
                        }
                    }
                }
                // ignore undefined tags
                else
                {
                    return;
                }
            }
        }
Esempio n. 31
0
 public IBRW BRead(System.IO.BinaryReader br)
 {
     ientity = br.ReadInt32();
     return(new RecInt(ientity));
 }
Esempio n. 32
0
 public override void LoadState(System.IO.BinaryReader stream)
 {
     base.LoadState(stream);
     latch = stream.ReadInt32();
     menu  = stream.ReadByte();
 }
Esempio n. 33
0
            public static bool Read_Pac1(string filename, ref Direct_Sound[] Direct_Data, ref ImageSourceData[] IS_Data, ref Environment.Receiver_Bank[] Receiver)
            {
                System.IO.BinaryReader sr = new System.IO.BinaryReader(System.IO.File.Open(filename, System.IO.FileMode.Open));
                try
                {
                    //1. Date & Time
                    string Savedate = sr.ReadString();
                    //2. Plugin Version
                    string Pach_version = sr.ReadString();
                    //3. Cut off Time and SampleRate
                    double CO_TIME    = sr.ReadDouble();
                    int    SampleRate = sr.ReadInt32();
                    //4. Source Count
                    int SrcCt = 1;
                    if (double.Parse(Pach_version.Substring(0, 3)) >= 1.1)
                    {
                        SrcCt = sr.ReadInt32();
                    }
                    //4.1 Source Location x
                    //4.2 Source Location y
                    //4.3 Source Location z
                    Hare.Geometry.Point[] SrcPt = new Hare.Geometry.Point[SrcCt];
                    for (int s = 0; s < SrcCt; s++)
                    {
                        SrcPt[s] = new Hare.Geometry.Point(sr.ReadDouble(), sr.ReadDouble(), sr.ReadDouble());
                    }
                    //5. No of Receivers
                    int Rec_Ct = sr.ReadInt32();
                    //6. Write the coordinates of each receiver point
                    //6b. Write the environmental characteristics at each receiver point (Rho * C); V2.0 only...
                    Hare.Geometry.Point[] Recs = new Hare.Geometry.Point[Rec_Ct];
                    double[] Rho_C             = new double[Rec_Ct];
                    for (int q = 0; q < Rec_Ct; q++)
                    {
                        Recs[q] = new Hare.Geometry.Point(sr.ReadDouble(), sr.ReadDouble(), sr.ReadDouble());
                        if (double.Parse(Pach_version.Substring(0, 3)) >= 2.0)
                        {
                            Rho_C[q] = sr.ReadDouble();
                        }
                        else
                        {
                            Rho_C[q] = 400;
                        }
                    }

                    Direct_Data = new Direct_Sound[SrcCt];
                    IS_Data     = new ImageSourceData[SrcCt];
                    Receiver    = new Environment.Receiver_Bank[SrcCt];

                    int DDCT = 0;
                    int ISCT = 0;
                    int RTCT = 0;
                    do
                    {
                        string readin = sr.ReadString();
                        switch (readin)
                        {
                        case "Direct_Sound":
                        case "Direct_Sound w sourcedata":
                            //9. Read Direct Sound Data
                            Direct_Data[DDCT]            = Direct_Sound.Read_Data(ref sr, Recs, SrcPt[DDCT], Rho_C, Pach_version);
                            Direct_Data[DDCT].CO_Time    = CO_TIME;
                            Direct_Data[DDCT].SampleFreq = (int)SampleRate;
                            DDCT++;
                            break;

                        case "Image-Source_Data":
                            //10. Read Image Source Sound Data
                            IS_Data[ISCT] = ImageSourceData.Read_Data(ref sr, Recs.Length, Direct_Data[DDCT - 1], false, ISCT, Pach_version);
                            ISCT++;
                            break;

                        case "Ray-Traced_Data":
                            //11. Read Ray Traced Sound Data
                            Receiver[RTCT] = Environment.Receiver_Bank.Read_Data(ref sr, Rec_Ct, Recs, Rho_C, Direct_Data[RTCT].Delay_ms, ref SampleRate, Pach_version);
                            RTCT++;
                            break;

                        case "End":
                            sr.Close();
                            return(true);
                        }
                    } while (true);
                }
                catch (System.Exception X)
                {
                    sr.Close();
                    System.Windows.Forms.MessageBox.Show("File Read Failed...", String.Format("Results file was corrupt or incomplete. We apologize for this inconvenience. Please report this to the software author. It will be much appreciated. \r\n Exception Message: {0}. \r\n Method: {1}", X.Message, X.TargetSite));
                    return(false);
                }
            }
Esempio n. 34
0
 public override void LoadState(System.IO.BinaryReader stream)
 {
     base.LoadState(stream);
     stream.Read(RAM, 0, RAM.Length);
     bank = stream.ReadInt32();
 }
Esempio n. 35
0
 /// <summary>
 ///Deserializes DOFDesc
 ///</summary>
 ///<param name="reader">the reader from which to deserialize</param>
 ///<returns>deserialized DOFDesc</returns>
 public virtual object Deserialize(System.IO.BinaryReader reader)
 {
     if ((reader.ReadByte() != 0))
     {
         this._Name = reader.ReadString();
     }
     if ((reader.ReadByte() != 0))
     {
         this._Description = ((global::ProMRDS.Simulation.JointMover.Proxy.JointDesc)(((Microsoft.Dss.Core.IDssSerializable)(new global::ProMRDS.Simulation.JointMover.Proxy.JointDesc())).Deserialize(reader)));
     }
     this._Type              = ((global::ProMRDS.Simulation.JointMover.Proxy.DOFType)(reader.ReadInt32()));
     this._Minimum           = reader.ReadSingle();
     this._Maximum           = reader.ReadSingle();
     this._Scale             = reader.ReadSingle();
     this._IsVelocityDrive   = reader.ReadBoolean();
     this._DefaultDriveValue = reader.ReadSingle();
     return(this);
 }
Esempio n. 36
0
        public static void readSeparateIndex(System.IO.Stream index, System.IO.Stream XMLBytes, int XMLSize, VTDGen vg)
        {
            if (index == null || vg == null || XMLBytes == null)
            {
                throw new System.ArgumentException("Invalid argument(s) for readIndex()");
            }
            //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' 
            //which has a different behavior. 
            //"ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'"
            System.IO.BinaryReader dis = new System.IO.BinaryReader(index);
            byte b = dis.ReadByte(); // first byte
            // no check on version number for now
            // second byte
            vg.encoding = dis.ReadByte();
            int intLongSwitch;
            int endian;
            // third byte
            b = dis.ReadByte();
            if ((b & 0x80) != 0)
                intLongSwitch = 1;
            //use ints
            else
                intLongSwitch = 0;
            if ((b & 0x40) != 0)
                vg.ns = true;
            else
                vg.ns = false;
            if ((b & 0x20) != 0)
                endian = 1;
            else
                endian = 0;
            if ((b & 0x1f) != 0)
                throw new IndexReadException("Last 5 bits of the third byte should be zero");

            // fourth byte
            vg.VTDDepth = dis.ReadByte();

            // 5th and 6th byte
            int LCLevel = (((int)dis.ReadByte()) << 8) | dis.ReadByte();
            if (LCLevel != 4 && LCLevel != 6)
            {
                throw new IndexReadException("LC levels must be at least 3");
            }
            // 7th and 8th byte
            vg.rootIndex = (((int)dis.ReadByte()) << 8) | dis.ReadByte();

            // skip a long
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            long l = dis.ReadInt64();

            int size;
            // read XML size
            if (BitConverter.IsLittleEndian && endian == 0
                || BitConverter.IsLittleEndian == false && endian == 1)
                size = (int)l;
            else
                size = (int)reverseLong(l);


            // read XML bytes
            byte[] XMLDoc = new byte[size];
            XMLBytes.Read(XMLDoc, 0, size);

            //dis.Read(XMLDoc, 0, size);
            /*if ((size & 0x7) != 0)
            {
                int t = (((size >> 3) + 1) << 3) - size;
                while (t > 0)
                {
                    dis.ReadByte();
                    t--;
                }
            }*/

            vg.setDoc(XMLDoc);
            // skip a long
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            if (BitConverter.IsLittleEndian && endian == 0
                || BitConverter.IsLittleEndian == false && endian == 1)
            {
                // read vtd records
                int vtdSize = (int)dis.ReadInt64();
                while (vtdSize > 0)
                {
                    vg.VTDBuffer.append(dis.ReadInt64());
                    vtdSize--;
                }
                // read L1 LC records
                int l1Size = (int)dis.ReadInt64();
                while (l1Size > 0)
                {
                    vg.l1Buffer.append(dis.ReadInt64());
                    l1Size--;
                }
                // read L2 LC records
                int l2Size = (int)dis.ReadInt64();
                while (l2Size > 0)
                {
                    vg.l2Buffer.append(dis.ReadInt64());
                    l2Size--;
                }
                // read L3 LC records
                int l3Size = (int)dis.ReadInt64();
                if (vg.shallowDepth)
                {
                    if (intLongSwitch == 1)
                    {
                        //l3 uses ints
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append(dis.ReadInt32());
                            l3Size--;
                        }
                    }
                    else
                    {
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append((int)(dis.ReadInt64() >> 32));
                            l3Size--;
                        }
                    }
                }
                else
                {
                    while (l3Size > 0)
                    {
                        vg._l3Buffer.append(dis.ReadInt64());
                        l3Size--;
                    }

                    int l4Size = (int)dis.ReadInt64();
                    while (l4Size > 0)
                    {
                        vg._l4Buffer.append(dis.ReadInt64());
                        l4Size--;
                    }

                    int l5Size = (int)dis.ReadInt64();
                    if (intLongSwitch == 1)
                    {
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append(dis.ReadInt32());
                            l5Size--;
                        }
                    }
                    else
                    {
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append((int)(dis.ReadInt64() >> 32));
                            l5Size--;
                        }
                    }
                }
            }
            else
            {
                // read vtd records
                int vtdSize = (int)reverseLong(dis.ReadInt64());
                while (vtdSize > 0)
                {
                    vg.VTDBuffer.append(reverseLong(dis.ReadInt64()));
                    vtdSize--;
                }
                // read L1 LC records
                int l1Size = (int)reverseLong(dis.ReadInt64());
                while (l1Size > 0)
                {
                    vg.l1Buffer.append(reverseLong(dis.ReadInt64()));
                    l1Size--;
                }
                // read L2 LC records
                int l2Size = (int)reverseLong(dis.ReadInt64());
                while (l2Size > 0)
                {
                    vg.l2Buffer.append(reverseLong(dis.ReadInt64()));
                    l2Size--;
                }
                // read L3 LC records
                int l3Size = (int)reverseLong(dis.ReadInt64());
                if (vg.shallowDepth)
                {
                    if (intLongSwitch == 1)
                    {
                        //l3 uses ints
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append(reverseInt(dis.ReadInt32()));
                            l3Size--;
                        }
                    }
                    else
                    {
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append(reverseInt((int)(dis.ReadInt64() >> 32)));
                            l3Size--;
                        }
                    }
                }
                else
                {
                    while (l3Size > 0)
                    {
                        vg._l3Buffer.append(reverseLong(dis.ReadInt64()));
                        l3Size--;
                    }

                    int l4Size = (int)reverseLong(dis.ReadInt64());
                    {
                        vg._l4Buffer.append(reverseLong(dis.ReadInt64()));
                        l4Size--;
                    }

                    int l5Size = (int)reverseLong(dis.ReadInt64());
                    if (intLongSwitch == 1)
                    {
                        //l3 uses ints
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append(reverseInt(dis.ReadInt32()));
                            l5Size--;
                        }
                    }
                    else
                    {
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append(reverseInt((int)(dis.ReadInt64() >> 32)));
                            l5Size--;
                        }
                    }
                }
            }
        }
Esempio n. 37
0
        public static PlayerView ReadFrom(System.IO.BinaryReader reader)
        {
            int  myId                 = reader.ReadInt32();
            int  mapSize              = reader.ReadInt32();
            bool fogOfWar             = reader.ReadBoolean();
            int  entityPropertiesSize = reader.ReadInt32();
            var  entityProperties     = new System.Collections.Generic.Dictionary <Model.EntityType, Model.EntityProperties>(entityPropertiesSize);

            for (int i = 0; i < entityPropertiesSize; i++)
            {
                Model.EntityType entityPropertiesKey;
                switch (reader.ReadInt32())
                {
                case 0:
                    entityPropertiesKey = Model.EntityType.Wall;
                    break;

                case 1:
                    entityPropertiesKey = Model.EntityType.House;
                    break;

                case 2:
                    entityPropertiesKey = Model.EntityType.BuilderBase;
                    break;

                case 3:
                    entityPropertiesKey = Model.EntityType.BuilderUnit;
                    break;

                case 4:
                    entityPropertiesKey = Model.EntityType.MeleeBase;
                    break;

                case 5:
                    entityPropertiesKey = Model.EntityType.MeleeUnit;
                    break;

                case 6:
                    entityPropertiesKey = Model.EntityType.RangedBase;
                    break;

                case 7:
                    entityPropertiesKey = Model.EntityType.RangedUnit;
                    break;

                case 8:
                    entityPropertiesKey = Model.EntityType.Resource;
                    break;

                case 9:
                    entityPropertiesKey = Model.EntityType.Turret;
                    break;

                default:
                    throw new System.Exception("Unexpected tag value");
                }

                Model.EntityProperties entityPropertiesValue;
                entityPropertiesValue = Model.EntityProperties.ReadFrom(reader);
                entityProperties.Add(entityPropertiesKey, entityPropertiesValue);
            }

            int maxTickCount     = reader.ReadInt32();
            int maxPathfindNodes = reader.ReadInt32();
            int currentTick      = reader.ReadInt32();

            Player[] players = new Model.Player[reader.ReadInt32()];
            for (int i = 0; i < players.Length; i++)
            {
                players[i] = Model.Player.ReadFrom(reader);
            }

            Entity[] entities = new Model.Entity[reader.ReadInt32()];
            for (int i = 0; i < entities.Length; i++)
            {
                entities[i] = Model.Entity.ReadFrom(reader);
            }

            var result = new PlayerView(
                myId,
                mapSize,
                fogOfWar,
                entityProperties,
                maxTickCount,
                maxPathfindNodes,
                currentTick,
                players,
                entities);

            return(result);
        }
Esempio n. 38
0
        /// <summary>
        /// Processes the PCAP packet capture global header
        /// </summary>
        /// <param name="theBinaryReader">The object that provides for binary reading from the packet capture</param>
        /// <returns>Boolean flag that indicates whether the PCAP packet capture global header could be processed</returns>
        protected override bool ProcessPacketCaptureGlobalHeader(System.IO.BinaryReader theBinaryReader)
        {
            bool theResult = true;

            if (theBinaryReader == null)
            {
                throw new System.ArgumentNullException("theBinaryReader");
            }

            // Read the magic number of the PCAP packet capture global header from the packet capture
            uint theMagicNumber = theBinaryReader.ReadUInt32();

            // The endianism of the remainder of the values in the PCAP packet capture global header will be corrected to little endian if the magic number indicates big endian representation
            if (theMagicNumber == Constants.LittleEndianMagicNumber)
            {
                this.TheDebugInformation.WriteInformationEvent(
                    "The PCAP packet capture contains the little endian magic number");

                this.isTheGlobalHeaderLittleEndian = true;
            }
            else if (theMagicNumber == Constants.BigEndianMagicNumber)
            {
                this.TheDebugInformation.WriteInformationEvent(
                    "The PCAP packet capture contains the big endian magic number");

                this.isTheGlobalHeaderLittleEndian = false;
            }
            else
            {
                this.TheDebugInformation.WriteErrorEvent(
                    "The PCAP packet capture contains an unknown endian magic number");

                // Assume little endian
                this.isTheGlobalHeaderLittleEndian = true;
            }

            ushort theVersionMajor        = 0;
            ushort theVersionMinor        = 0;
            uint   theNetworkDataLinkType = 0;

            // Just read off the remainder of the PCAP packet capture global header from the packet capture so we can move on
            // Some of the data will be stored for use below
            if (this.isTheGlobalHeaderLittleEndian)
            {
                theVersionMajor = theBinaryReader.ReadUInt16();
                theVersionMinor = theBinaryReader.ReadUInt16();
                theBinaryReader.ReadInt32();  // This time zone
                theBinaryReader.ReadUInt32(); // Significant figures
                theBinaryReader.ReadUInt32(); // Snapshot length
                theNetworkDataLinkType = theBinaryReader.ReadUInt32();
            }
            else
            {
                theVersionMajor = (ushort)System.Net.IPAddress.NetworkToHostOrder(theBinaryReader.ReadInt16());
                theVersionMinor = (ushort)System.Net.IPAddress.NetworkToHostOrder(theBinaryReader.ReadInt16());
                theBinaryReader.ReadInt32();  // This time zone
                theBinaryReader.ReadUInt32(); // Significant figures
                theBinaryReader.ReadUInt32(); // Snapshot length
                theNetworkDataLinkType = (uint)System.Net.IPAddress.NetworkToHostOrder(theBinaryReader.ReadInt32());
            }

            // Validate fields from the PCAP packet capture global header
            theResult = this.ValidateGlobalHeader(
                theMagicNumber,
                theVersionMajor,
                theVersionMinor,
                theNetworkDataLinkType);

            if (theResult)
            {
                // Set up the value for the network data link type
                this.PacketCaptureNetworkDataLinkType =
                    theNetworkDataLinkType;
            }

            return(theResult);
        }
Esempio n. 39
0
 public void Unpack(System.IO.BinaryReader reader)
 {
     Key.Unpack(reader);
     AddressID = reader.ReadInt32();
 }
Esempio n. 40
0
        public override object Deserialize(System.IO.BinaryReader binaryReader)
        {
            bool hasValue = binaryReader.ReadBoolean();

            if (!hasValue)
            {
                return(null);
            }
            int typeID = binaryReader.ReadByte();

            switch (typeID)
            {
            case 1:
                return(binaryReader.ReadBoolean());

            case 2:
                return(binaryReader.ReadByte());

            case 128:
                return(binaryReader.ReadSByte());

            case 3:
                return(binaryReader.ReadInt16());

            case 129:
                return(binaryReader.ReadUInt16());

            case 4:
                return(binaryReader.ReadInt32());

            case 130:
                return(binaryReader.ReadUInt32());

            case 5:
                return(binaryReader.ReadInt64());

            case 131:
                return(binaryReader.ReadUInt64());

            case 9:
                return(binaryReader.ReadDouble());

            case 16:
                return(binaryReader.ReadString());

            case 144:
                return(binaryReader.ReadChar());

            case 24:
                return(new DateTime(binaryReader.ReadInt64()));

            case 32:
                return(new Guid(binaryReader.ReadBytes(16)));

            case 36:
                return(binaryReader.ReadBytes(binaryReader.ReadInt32()));

            default:
                throw new Exception(string.Format("Serialization for type <{0}> is not supported", typeID));
            }
        }
            /// <summary>
            /// reads a file and populates the map receiver instance.
            /// </summary>
            /// <returns></returns>
            public static bool Read_pachm(out Mapping.PachMapReceiver[] Map)
            {
                System.Windows.Forms.OpenFileDialog of = new System.Windows.Forms.OpenFileDialog();
                of.DefaultExt = ".pachm";
                of.AddExtension = true;
                of.Filter = "Pachyderm Mapping Data File (*.pachm)|*.pachm|" + "All Files|";
                if (of.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    Map = null;
                    return false;
                }
                System.IO.BinaryReader sr = new System.IO.BinaryReader(System.IO.File.Open(of.FileName, System.IO.FileMode.Open));
                //1. Write calculation type. (string)
                string CalcType = sr.ReadString();
                if (CalcType != "Type;Map_Data" && CalcType != "Type;Map_Data_NoDir") throw new Exception("Map Data File Expected");
                bool Directional = (CalcType == "Type;Map_Data");

                //2. Write the number of samples in each histogram. (int)
                int SampleCT = (int)sr.ReadUInt32();
                //3. Write the sample rate. (int)
                int SampleRate = (int)sr.ReadUInt32();
                //4. Write the number of Receivers (int)
                int Rec_CT = (int)sr.ReadUInt32();
                //4.5 Write the version number
                double version = 1.1;
                double rev = 0;
                //5. Announce that the following data pertains to the form of the analysis mesh. (string)
                int s_ct=1;
                Rhino.Geometry.Mesh Map_Mesh = new Rhino.Geometry.Mesh();
                Map = new Mapping.PachMapReceiver[1];
                //Map[0] = new Pach_Map_Receiver();
                //double[] Rho_C = null;
                double[] delay;

                do
                {
                    switch (sr.ReadString())
                    {
                        case "Version":
                            //Pach1.7 = Versioning functionality added.
                            string v = sr.ReadString();
                            version = double.Parse(v.Substring(0, 3));
                            rev = int.Parse(v.Split(new char[1] { '.' })[3]);
                            break;
                        case "Mesh Information":
                            //6. Announce Mesh Vertices (string)
                            //Write the number of vertices & faces (int) (int)
                            if (sr.ReadString() != "Mesh Vertices") throw new Exception("Mesh Vertices Expected");

                            int VC = (int)sr.ReadUInt32();
                            int FC = (int)sr.ReadUInt32();
                            for (int i = 0; i < VC; i++)
                            {
                                //Write Vertex: (double) (double) (double)
                                Map_Mesh.Vertices.Add(new Rhino.Geometry.Point3d(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()));
                            }

                            //7. Announce Mesh Faces (string)
                            if (sr.ReadString() != "Mesh Faces") throw new Exception("Mesh Faces Expected");

                            for (int i = 0; i < FC; i++)
                            {
                                // Write mesh vertex indices: (int) (int) (int) (int)
                                Map_Mesh.Faces.AddFace((int)sr.ReadUInt32(), (int)sr.ReadUInt32(), (int)sr.ReadUInt32(), (int)sr.ReadUInt32());
                            }
                            break;
                        case "Sources":
                            //7.5: Announce the number of sources.
                            s_ct = sr.ReadInt32();
                            delay = new double[s_ct];
                            Map = new Mapping.PachMapReceiver[s_ct];
                            //7.5a Announce the type of source.

                            for (int s = 0; s < s_ct; s++)
                            {
                                Map[s] = new Mapping.PachMapReceiver();
                                Map[s].CutOffTime = (double)SampleCT / (double)SampleRate;
                                Map[s].SampleCT = SampleCT;
                                Map[s].SampleRate = SampleRate;
                                Map[s].Map_Mesh = Map_Mesh;
                                Map[s].Rec_List = new Mapping.PachMapReceiver.Map_Receiver[Rec_CT];
                                Map[s].SrcType = sr.ReadString();
                                //4.4 Source delay (ms)
                                if (version > 2.0 || (version == 2.0 && rev >= 1))
                                {
                                    delay[s] = sr.ReadDouble();
                                }
                            }
                            break;
                        case "SourceswLoc":
                            //7.5: Announce the number of sources.
                            s_ct = sr.ReadInt32();
                            delay = new double[s_ct];
                            Map = new Mapping.PachMapReceiver[s_ct];
                            //7.5a Announce the type of source.

                            for (int s = 0; s < s_ct; s++)
                            {
                                Map[s] = new Mapping.PachMapReceiver();
                                Map[s].CutOffTime = (double)SampleCT / (double)SampleRate * 1000;
                                Map[s].SampleCT = SampleCT;
                                Map[s].SampleRate = SampleRate;
                                Map[s].Map_Mesh = Map_Mesh;
                                Map[s].Rec_List = new Mapping.PachMapReceiver.Map_Receiver[Rec_CT];
                                Map[s].Src = new Rhino.Geometry.Point3d(sr.ReadDouble(), sr.ReadDouble(), sr.ReadDouble());
                                Map[s].SrcType = sr.ReadString();
                                //4.4 Source delay (ms)
                                if (version > 2.0 || (version == 2.0 && rev >= 1))
                                {
                                    delay[s] = sr.ReadDouble();
                                }
                            }
                            break;
                        case "Receiver Hit Data":
                            if (Map[0] == null)
                            {
                                Map = new Mapping.PachMapReceiver[1];
                                Map[0] = new Mapping.PachMapReceiver();
                                Map[0].CutOffTime = (double)SampleCT / (double)SampleRate;
                                Map[0].SampleRate = SampleRate;
                                Map[0].SampleCT = SampleCT;
                                Map[0].Map_Mesh = Map_Mesh;
                                Map[0].Rec_List = new Mapping.PachMapReceiver.Map_Receiver[Rec_CT];
                                Map[0].SrcType = "Geodesic";
                            }

                            //8. Announce that the following data pertains to the receiver histograms (string)
                            //8a. Announce whether or not data is linked to vertices rather than faces (bool)
                            bool vert_Receiver = sr.ReadBoolean();
                            for (int s = 0; s < s_ct; s++)
                            {
                                Map[s].Rec_Vertex = vert_Receiver;
                                for (int i = 0; i < Map[s].Rec_List.Length; i++)
                                {
                                    //for version 1.7 and up, write direct sound arrival time.
                                    //Write Receiver Index (int)
                                    int j = (int)sr.ReadUInt32();
                                    //Write Direct Sound Arrival Time.
                                    double Direct_Time;
                                    if (version >= 1.7) Direct_Time = sr.ReadDouble(); else Direct_Time = (Utilities.PachTools.RPttoHPt(Map[s].Src) - Map[s].Rec_List[i].H_Origin).Length() / 343f;
                                    //Write Impedance of Air
                                    double Rho_C = version >= 2.0 ? sr.ReadDouble() : 400;

                                    if (vert_Receiver)
                                    {
                                        Map[s].Rec_List[i] = new Mapping.PachMapReceiver.Map_Receiver(Map_Mesh.Vertices[i], new Rhino.Geometry.Point3f((float)Map[s].Src.X, (float)Map[s].Src.Y, (float)Map[s].Src.Z), Direct_Time, Rho_C, i, SampleRate, SampleCT, Directional);
                                    }
                                    else
                                    {
                                        Rhino.Geometry.Point3d RecLoc = Map_Mesh.Faces.GetFaceCenter(i);
                                        Map[s].Rec_List[i] = new Mapping.PachMapReceiver.Map_Receiver(new Rhino.Geometry.Point3f((float)RecLoc.X, (float)RecLoc.Y, (float)RecLoc.Z), new Rhino.Geometry.Point3f((float)Map[s].Src.X, (float)Map[s].Src.Y, (float)Map[s].Src.Z), Direct_Time, Rho_C, i, SampleRate, SampleCT, Directional);
                                    }

                                    for (int Octave = 0; Octave < 8; Octave++)
                                    {
                                        //Write Octave (int)
                                        int Oct_out = (int)sr.ReadUInt32();
                                        if (Oct_out != Octave) throw new Exception(string.Format("Octave {0} Expected", Octave));
                                        double[] Hist = Map[s].Rec_List[i].GetEnergyHistogram(Octave);
                                        if (Directional)
                                        {
                                            if (version < 1.7)
                                            {
                                                for (int e = 0; e < SampleCT; e++)
                                                    Map[s].Rec_List[i].Combine_Sample(e, sr.ReadDouble(), new Hare.Geometry.Vector(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()), new Hare.Geometry.Vector(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()), Octave);
                                            }
                                            else
                                            {
                                                for (int e = 0; e < SampleCT; e++)
                                                    Map[s].Rec_List[i].Combine_Sample(e, sr.ReadDouble(), new Hare.Geometry.Vector(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()), new Hare.Geometry.Vector(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()), Octave);
                                            }
                                        }
                                        else
                                        {
                                            if (version < 1.7)
                                            {
                                                for (int e = 0; e < SampleCT; e++)
                                                    Map[s].Rec_List[i].Combine_Sample(e, sr.ReadDouble(), new Hare.Geometry.Vector(0, 0, 0), new Hare.Geometry.Vector(0, 0, 0), Octave);
                                            }
                                            else
                                            {
                                                for (int e = 0; e < SampleCT; e++)
                                                    Map[s].Rec_List[i].Combine_Sample(e, sr.ReadDouble(), new Hare.Geometry.Vector(0, 0, 0), new Hare.Geometry.Vector(0,0,0), Octave);
                                            }
                                        }
                                    }
                                    if (sr.ReadString() != "End_Receiver_Hits") throw new Exception("End of Receiver Hits Expected");
                                }
                            }
                            break;
                        case "End_of_File":
                            sr.Close();
                            return true;
                    }
                } while (true);
                throw new Exception("Unsuccessful Read");
            }
Esempio n. 42
0
        public void Load(System.IO.BinaryReader br)
        {
            //Read tile definition mapper (oldId -> newId)
            byte[] mapTileDefinitionMapper = new byte[byte.MaxValue];

            int definitions = br.ReadInt32();

            for (int i = 0; i < definitions; i++)
            {
                byte   oldType = br.ReadByte();
                string id      = br.ReadString();
                byte   newType = 0;

                foreach (TileDefinition td in tileDefinitions)
                {
                    if (td.id == id)
                    {
                        newType = td.tileType;
                        break;
                    }
                }

                mapTileDefinitionMapper[oldType] = newType;
            }

            //Read map size
            //This is read in CubeWorld.Load()
            //int sizeXbits = br.ReadInt32();
            //int sizeYbits = br.ReadInt32();
            //int sizeZbits = br.ReadInt32();

            //Create empty world
            //The world is already created in CubeLoad.Load()
            //Create(tileDefinitions, sizeXbits, sizeYbits, sizeZbits);

            //Read tiles
            byte[] tileBytes = br.ReadBytes(sizeX * sizeY * sizeZ * 4);
            Tile   tile      = new Tile();

            for (int n = tiles.Length - 1; n >= 0; n--)
            {
                tile.tileType  = mapTileDefinitionMapper[tileBytes[(n << 2) | 0]];
                tile.luminance = tileBytes[(n << 2) | 1];
                tile.extra     = tileBytes[(n << 2) | 2];
                tile.extra2    = tileBytes[(n << 2) | 3];

                tiles[n] = tile;
            }

            //Read dynamic tiles
            int nDyanamicTiles = br.ReadInt32();

            for (int n = 0; n < nDyanamicTiles; n++)
            {
                int          objectId = br.ReadInt32();
                TilePosition pos      = SerializationUtils.ReadTilePosition(br);
                int          timeout  = br.ReadInt32();

                DynamicTile dynamicTile = new DynamicTile(world, pos, true, objectId);

                //TODO: Get gravity attribute from somewhere
                if (true)
                {
                    dynamicTile.AddComponent(new TileComponentGravity());
                }

                dynamicTiles[pos] = dynamicTile;

                if (timeout > 0)
                {
                    dynamicTile.timeout      = timeout;
                    dynamicTilesTimeout[pos] = dynamicTile;
                }

                world.cwListener.CreateObject(dynamicTile);
            }

            //Read top positions
            topPositions = br.ReadBytes(sizeX * sizeZ);

            if (world.gameplay.useEnqueueTileUpdates)
            {
                EnqueueTilesWithRules();
            }

            enqueueTileUpdates    = world.gameplay.useEnqueueTileUpdates;
            updateLighting        = true;
            reportTileInvalidated = true;

            if (world.gameplay.useEnqueueTileUpdates)
            {
                UpdateTiles();
            }

            //The read tiles already have the light information updated
            //LightModelAmbient.InitLuminance(this);
            //LightModelLightSource.InitLuminance(this);
        }
Esempio n. 43
0
        public static HeightData LoadHeightmapFromImageFile(string path){
            Config config = Main.Get().GetConfig();
            
            HeightData heights;
            
            string ext = path.Substring(path.LastIndexOf('.'), path.Length - path.LastIndexOf('.')).ToLower();

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

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

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

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

                reader.Close();

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


                System.Drawing.Bitmap bitmap;

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

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

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

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

                int pixelSize = data.Stride / data.Width;

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

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

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

                bitmap.UnlockBits(data);

                bitmap.Dispose();
            }

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

            return heights2;
        }
Esempio n. 44
0
        private void OnPaste( object sender, RoutedEventArgs e )
        {
            var files = Clipboard.GetData( "FileDrop" ) as string[];
            var dropEffectStream = Clipboard.GetData( "Preferred DropEffect" ) as System.IO.MemoryStream;

            if( files == null || dropEffectStream == null ||
                files.Length == 0 || dropEffectStream.Length != 4 ) return;

            var dropEffectReader = new System.IO.BinaryReader( dropEffectStream );
            var dropEffect =  (DragDropEffects)dropEffectReader.ReadInt32();

            ProcessFileDrop( files, dropEffect.HasFlag( DragDropEffects.Move ) );
        }
Esempio n. 45
0
        internal static string ReadString(System.IO.BinaryReader reader)
        {
            int ct = reader.ReadInt32();

            return(Helper.ToString(reader.ReadBytes(ct)));
        }
 public static TransparentStreamReadResponseMessage Deserialize(byte[] buffer)
 {
     if (buffer == null)
         throw new ArgumentNullException ("buffer");
     Guid streamID;
     Guid requestID;
     byte[] data;
     Exception exception;
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream (buffer)) {
         using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
             streamID = new Guid (BR.ReadBytes (16));
             requestID = new Guid (BR.ReadBytes (16));
             data = BR.ReadBytes (BR.ReadInt32 ());
             if (MS.ReadByte () == 1) {
                 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter ();
                 object deserializedObject = BF.Deserialize (MS);
                 if (deserializedObject is Exception) {
                     exception = (Exception)deserializedObject;
                 } else {
                     throw new Exception ("buffer contains an object of invalid type, expected System.Exception.");
                 }
             } else
                 exception = null;
         }
     }
     return new TransparentStreamReadResponseMessage (streamID, requestID, data, exception);
 }
Esempio n. 47
0
        public void readFile()
        {
            System.IO.BinaryReader sr;

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

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

            UInt32 RIFFSize = sr.ReadUInt32();

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

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

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

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

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

            //======================
            // read samples
            if (bitDepth == 16) {
                for (int i = 0; i < numSamples; i++) {
                    for (int c = 0; c < channels; c++) {
                        //assuming signed
                        //normalized to -1.0..+1.0
                        samples[c][i] = (double)sr.ReadInt16() / 32768.0;
                    }
                }
            } else if (bitDepth == 8) {
                for (int i = 0; i < numSamples; i++) {
                    for (int c = 0; c < channels; c++) {
                        //assuming unsigned
                        //normalized to -1.0..+1.0
                        samples[c][i] = (double)sr.ReadByte() / 128.0 - 1.0;
                    }
                }
            } else {
                throw new FormatException("Bit depth must be one of 8 or 16 bits.");
            }
            sr.Close();
        }
Esempio n. 48
0
        void OnReceive(DebugMessageType type, byte[] buffer)
        {
            if (clientSocket == null || clientSocket.Disconnected)
            {
                return;
            }
            System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);
            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);

            switch (type)
            {
            case DebugMessageType.CSAttach:
            {
                SendAttachResult();
            }
            break;

            case DebugMessageType.CSBindBreakpoint:
            {
                CSBindBreakpoint msg = new Protocol.CSBindBreakpoint();
                msg.BreakpointHashCode = br.ReadInt32();
                msg.IsLambda           = br.ReadBoolean();
                msg.TypeName           = br.ReadString();
                msg.MethodName         = br.ReadString();
                msg.StartLine          = br.ReadInt32();
                msg.EndLine            = br.ReadInt32();
                TryBindBreakpoint(msg);
            }
            break;

            case DebugMessageType.CSDeleteBreakpoint:
            {
                CSDeleteBreakpoint msg = new Protocol.CSDeleteBreakpoint();
                msg.BreakpointHashCode = br.ReadInt32();
                ds.DeleteBreakpoint(msg.BreakpointHashCode);
            }
            break;

            case DebugMessageType.CSExecute:
            {
                CSExecute msg = new Protocol.CSExecute();
                msg.ThreadHashCode = br.ReadInt32();
                ds.ExecuteThread(msg.ThreadHashCode);
            }
            break;

            case DebugMessageType.CSStep:
            {
                CSStep msg = new CSStep();
                msg.ThreadHashCode = br.ReadInt32();
                msg.StepType       = (StepTypes)br.ReadByte();
                ds.StepThread(msg.ThreadHashCode, msg.StepType);
            }
            break;

            case DebugMessageType.CSResolveVariable:
            {
                CSResolveVariable msg = new CSResolveVariable();
                msg.ThreadHashCode = br.ReadInt32();
                msg.Variable       = ReadVariableReference(br);
                VariableInfo info;
                try
                {
                    object res;
                    info = ds.ResolveVariable(msg.ThreadHashCode, msg.Variable, out res);
                }
                catch (Exception ex)
                {
                    info = VariableInfo.GetException(ex);
                }
                if (info.Type != VariableTypes.Pending)
                {
                    SendSCResolveVariableResult(info);
                }
            }
            break;

            case DebugMessageType.CSResolveIndexAccess:
            {
                CSResolveIndexer msg = new CSResolveIndexer();
                msg.ThreadHashCode = br.ReadInt32();
                msg.Body           = ReadVariableReference(br);
                msg.Index          = ReadVariableReference(br);

                VariableInfo info;
                try
                {
                    object res;
                    info = ds.ResolveIndexAccess(msg.ThreadHashCode, msg.Body, msg.Index, out res);
                }
                catch (Exception ex)
                {
                    info = VariableInfo.GetException(ex);
                }
                if (info.Type != VariableTypes.Pending)
                {
                    SendSCResolveVariableResult(info);
                }
            }
            break;

            case DebugMessageType.CSEnumChildren:
            {
                int thId   = br.ReadInt32();
                var parent = ReadVariableReference(br);

                VariableInfo[] info = null;
                try
                {
                    info = ds.EnumChildren(thId, parent);
                }
                catch (Exception ex)
                {
                    info = new VariableInfo[] { VariableInfo.GetException(ex) };
                }
                if (info != null)
                {
                    SendSCEnumChildrenResult(info);
                }
            }
            break;
            }
        }
Esempio n. 49
0
        public void Populate(int iOffset, bool useMemoryStream)
        {
            this.isNulledOutReflexive = false;
            System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS);
            //set offsets
            BR.BaseStream.Position = iOffset + this.chunkOffset;
            this.offsetInMap = iOffset + this.chunkOffset;
            // If we need to read / save tag info directly to file...
            if (!useMemoryStream)
            {
                map.OpenMap(MapTypes.Internal);
                BR = map.BR;
                BR.BaseStream.Position = this.offsetInMap;
            }
            else
                this.offsetInMap += meta.offset;

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

            }
            // ...and then close the file once we are done!
            if (!useMemoryStream)
                map.CloseMap();
            UpdateComboBox();
        }
Esempio n. 50
0
        /////////PARENTS FUNCTION//////////
        protected override void DataUpdate()
        {
            System.IO.BinaryReader BSReader = new System.IO.BinaryReader(ByteStream);
            ByteStream.Position = 0;
            Chunks = BSReader.ReadInt32();
            Array.Resize(ref Chunk, Chunks);
            for (int i = 0; i <= Chunks - 1; i++)
            {
                ChunkType CH = new ChunkType {
                    Unknown = new uint[] { }
                };
                CH.Type = BSReader.ReadUInt32();
                switch (CH.Type)
                {
                case 0:
                {
                    CH.Path  = BSReader.ReadChars(BSReader.ReadInt32()).ToString();
                    CH.Flags = BSReader.ReadUInt32();
                    CH.PlayerTeleportScaleX = BSReader.ReadSingle();
                    CH.SomeInt1             = BSReader.ReadUInt32();
                    CH.SomeInt2             = BSReader.ReadUInt32();
                    CH.Null1                   = BSReader.ReadUInt32();
                    CH.SomeInt3                = BSReader.ReadUInt32();
                    CH.PlayerTeleportScaleY    = BSReader.ReadSingle();
                    CH.SomeInt4                = BSReader.ReadUInt32();
                    CH.Null2                   = BSReader.ReadUInt32();
                    CH.SomeInt5                = BSReader.ReadUInt32();
                    CH.SomeInt6                = BSReader.ReadUInt32();
                    CH.PlayerTeleportScaleZ    = BSReader.ReadSingle();
                    CH.Null3                   = BSReader.ReadUInt32();
                    CH.UnkV4.X                 = BSReader.ReadSingle();
                    CH.UnkV4.Y                 = BSReader.ReadSingle();
                    CH.UnkV4.Z                 = BSReader.ReadSingle();
                    CH.UnkV4.W                 = BSReader.ReadSingle();
                    CH.PlayerTeleport.X        = BSReader.ReadSingle();
                    CH.PlayerTeleport.Y        = BSReader.ReadSingle();
                    CH.PlayerTeleport.Z        = BSReader.ReadSingle();
                    CH.PlayerTeleport.W        = BSReader.ReadSingle();
                    CH.VisualSubchunkScaleX    = BSReader.ReadSingle();
                    CH.SomeInt7                = BSReader.ReadUInt32();
                    CH.SomeInt8                = BSReader.ReadUInt32();
                    CH.Null4                   = BSReader.ReadUInt32();
                    CH.SomeInt9                = BSReader.ReadUInt32();
                    CH.VisualSubchunkScaleY    = BSReader.ReadSingle();
                    CH.SomeInt10               = BSReader.ReadUInt32();
                    CH.Null5                   = BSReader.ReadUInt32();
                    CH.SomeInt11               = BSReader.ReadUInt32();
                    CH.SomeInt12               = BSReader.ReadUInt32();
                    CH.VisualSubchunkScaleZ    = BSReader.ReadSingle();
                    CH.Null6                   = BSReader.ReadUInt32();
                    CH.VisualSubchunkLocationX = BSReader.ReadSingle();
                    CH.VisualSubchunkLocationY = BSReader.ReadSingle();
                    CH.VisualSubchunkLocationZ = BSReader.ReadSingle();
                    CH.LoadWallPoint1.X        = BSReader.ReadSingle();
                    CH.LoadWallPoint1.Y        = BSReader.ReadSingle();
                    CH.LoadWallPoint1.Z        = BSReader.ReadSingle();
                    CH.LoadWallPoint1.W        = BSReader.ReadSingle();

                    CH.LoadWallPoint2.X = BSReader.ReadSingle();
                    CH.LoadWallPoint2.Y = BSReader.ReadSingle();
                    CH.LoadWallPoint2.Z = BSReader.ReadSingle();
                    CH.LoadWallPoint2.W = BSReader.ReadSingle();

                    CH.LoadWallPoint3.X = BSReader.ReadSingle();
                    CH.LoadWallPoint3.Y = BSReader.ReadSingle();
                    CH.LoadWallPoint3.Z = BSReader.ReadSingle();
                    CH.LoadWallPoint3.W = BSReader.ReadSingle();

                    CH.LoadWallPoint4.X = BSReader.ReadSingle();
                    CH.LoadWallPoint4.Y = BSReader.ReadSingle();
                    CH.LoadWallPoint4.Z = BSReader.ReadSingle();
                    CH.LoadWallPoint4.W = BSReader.ReadSingle();
                    break;
                }

                case 1:
                {
                    CH.Path  = BSReader.ReadChars(BSReader.ReadInt32()).ToString();
                    CH.Flags = BSReader.ReadUInt32();
                    CH.PlayerTeleportScaleX = BSReader.ReadSingle();
                    CH.SomeInt1             = BSReader.ReadUInt32();
                    CH.SomeInt2             = BSReader.ReadUInt32();
                    CH.Null1                   = BSReader.ReadUInt32();
                    CH.SomeInt3                = BSReader.ReadUInt32();
                    CH.PlayerTeleportScaleY    = BSReader.ReadSingle();
                    CH.SomeInt4                = BSReader.ReadUInt32();
                    CH.Null2                   = BSReader.ReadUInt32();
                    CH.SomeInt5                = BSReader.ReadUInt32();
                    CH.SomeInt6                = BSReader.ReadUInt32();
                    CH.PlayerTeleportScaleZ    = BSReader.ReadSingle();
                    CH.Null3                   = BSReader.ReadUInt32();
                    CH.UnkV4.X                 = BSReader.ReadSingle();
                    CH.UnkV4.Y                 = BSReader.ReadSingle();
                    CH.UnkV4.Z                 = BSReader.ReadSingle();
                    CH.UnkV4.W                 = BSReader.ReadSingle();
                    CH.PlayerTeleport.X        = BSReader.ReadSingle();
                    CH.PlayerTeleport.Y        = BSReader.ReadSingle();
                    CH.PlayerTeleport.Z        = BSReader.ReadSingle();
                    CH.PlayerTeleport.W        = BSReader.ReadSingle();
                    CH.VisualSubchunkScaleX    = BSReader.ReadSingle();
                    CH.SomeInt7                = BSReader.ReadUInt32();
                    CH.SomeInt8                = BSReader.ReadUInt32();
                    CH.Null4                   = BSReader.ReadUInt32();
                    CH.SomeInt9                = BSReader.ReadUInt32();
                    CH.VisualSubchunkScaleY    = BSReader.ReadSingle();
                    CH.SomeInt10               = BSReader.ReadUInt32();
                    CH.Null5                   = BSReader.ReadUInt32();
                    CH.SomeInt11               = BSReader.ReadUInt32();
                    CH.SomeInt12               = BSReader.ReadUInt32();
                    CH.VisualSubchunkScaleZ    = BSReader.ReadSingle();
                    CH.Null6                   = BSReader.ReadUInt32();
                    CH.VisualSubchunkLocationX = BSReader.ReadSingle();
                    CH.VisualSubchunkLocationY = BSReader.ReadSingle();
                    CH.VisualSubchunkLocationZ = BSReader.ReadSingle();
                    CH.LoadWallPoint1.X        = BSReader.ReadSingle();
                    CH.LoadWallPoint1.Y        = BSReader.ReadSingle();
                    CH.LoadWallPoint1.Z        = BSReader.ReadSingle();
                    CH.LoadWallPoint1.W        = BSReader.ReadSingle();

                    CH.LoadWallPoint2.X = BSReader.ReadSingle();
                    CH.LoadWallPoint2.Y = BSReader.ReadSingle();
                    CH.LoadWallPoint2.Z = BSReader.ReadSingle();
                    CH.LoadWallPoint2.W = BSReader.ReadSingle();

                    CH.LoadWallPoint3.X = BSReader.ReadSingle();
                    CH.LoadWallPoint3.Y = BSReader.ReadSingle();
                    CH.LoadWallPoint3.Z = BSReader.ReadSingle();
                    CH.LoadWallPoint3.W = BSReader.ReadSingle();

                    CH.LoadWallPoint4.X = BSReader.ReadSingle();
                    CH.LoadWallPoint4.Y = BSReader.ReadSingle();
                    CH.LoadWallPoint4.Z = BSReader.ReadSingle();
                    CH.LoadWallPoint4.W = BSReader.ReadSingle();
                    Array.Resize(ref CH.Unknown, 17);
                    CH.Null7 = BSReader.ReadUInt32();
                    for (int j = 0; j <= 16; j++)
                    {
                        CH.Unknown[j] = BSReader.ReadUInt32();
                    }
                    CH.V1.X = BSReader.ReadSingle();
                    CH.V1.Y = BSReader.ReadSingle();
                    CH.V1.Z = BSReader.ReadSingle();
                    CH.Z1   = BSReader.ReadSingle();

                    CH.V2.X = BSReader.ReadSingle();
                    CH.V2.Y = BSReader.ReadSingle();
                    CH.V2.Z = BSReader.ReadSingle();
                    CH.Y2   = BSReader.ReadSingle();

                    CH.V3.X = BSReader.ReadSingle();
                    CH.V3.Y = BSReader.ReadSingle();
                    CH.V3.Z = BSReader.ReadSingle();
                    CH.Z2   = BSReader.ReadSingle();

                    CH.V4.X = BSReader.ReadSingle();
                    CH.V4.Y = BSReader.ReadSingle();
                    CH.V4.Z = BSReader.ReadSingle();
                    CH.Y1   = BSReader.ReadSingle();

                    CH.V5.X = BSReader.ReadSingle();
                    CH.V5.Y = BSReader.ReadSingle();
                    CH.V5.Z = BSReader.ReadSingle();
                    CH.X2   = BSReader.ReadSingle();

                    CH.V6.X = BSReader.ReadSingle();
                    CH.V6.Y = BSReader.ReadSingle();
                    CH.V6.Z = BSReader.ReadSingle();
                    CH.X1   = BSReader.ReadSingle();

                    Array.Resize(ref CH.V4Arr, 6);
                    for (int j = 0; j <= 5; j++)
                    {
                        CH.V4Arr[j].X = BSReader.ReadSingle();
                        CH.V4Arr[j].Y = BSReader.ReadSingle();
                        CH.V4Arr[j].Z = BSReader.ReadSingle();
                        CH.V4Arr[j].W = BSReader.ReadSingle();
                    }
                    CH.Bytes = BSReader.ReadBytes(60);
                    break;
                }
                }
                Chunk[i] = CH;
            }
        }
Esempio n. 51
0
        public override Packet GetNextPacket()
        {
            Packet packet = null;
            try
            {
                if (reader.Read())
                {
                    var id = reader.GetInt32(0);
                    var datetime = reader.GetDateTime(1);
                    var direction = (Direction)reader.GetInt32(2);
                    var opcode = (uint)reader.GetInt32(3);
                    var blob = reader.GetValue(4);

                    var data = new byte[0];

                    if (!DBNull.Value.Equals(blob))
                    {
                        data = (byte[])blob;

                        //decompress
                        if (opcode == 502 || opcode == 763 || (ClientBuildAmount < 9183 && opcode == 751))
                        {
                            using (var ms = new System.IO.MemoryStream(data))
                            using (var br = new System.IO.BinaryReader(ms))
                            {
                                var zsstream = new ComponentAce.Compression.Libs.zlib.ZStream();
                                var compdata = new byte[data.Length - 4];
                                System.Array.Copy(data, 4, compdata, 0, data.Length - 4);
                                int decompsize = br.ReadInt32();
                                var decompdata = new byte[decompsize];
                                zsstream.inflateInit();
                                zsstream.avail_in = compdata.Length;
                                zsstream.next_in = compdata;
                                zsstream.avail_out = decompsize;
                                zsstream.next_out = decompdata;
                                var ret = zsstream.inflate(ComponentAce.Compression.Libs.zlib.zlibConst.Z_NO_FLUSH);
                                var ret2 = zsstream.inflateEnd();

                                data = decompdata;
                            }
                        }
                    }

                    packet = new Packet(id, datetime, direction, opcode, data, data.Length, ClientBuild);

                    currentIndex = id;
                }

            }
            catch (Exception exc)
            {
                delegatemanager.AddException(exc);
            }

            return packet;
        }
            public void Unpack(System.IO.BinaryReader reader)
            {
                var c = reader.ReadInt32();

                Blob = reader.ReadBytes(c);
            }
Esempio n. 53
0
 public static ObjectBusMessage Deserialize(byte[] bytes)
 {
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream (bytes, false)) {
         using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
             return new ServiceRequestMessage (new Guid (BR.ReadBytes (16)), new Guid (BR.ReadBytes (16)), BR.ReadBytes (BR.ReadInt32 ()));
         }
     }
 }
Esempio n. 54
0
 public override void LoadState(System.IO.BinaryReader stream)
 {
     base.LoadState(stream);
     address_8001 = stream.ReadInt32();
 }
Esempio n. 55
0
		public static void DeserializeVoxelAreaCompactData (byte[] bytes, VoxelArea target) {
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
			System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes);
			System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);
			int width = reader.ReadInt32();
			int depth = reader.ReadInt32();
			if (target.width != width) throw new System.ArgumentException ("target VoxelArea has a different width than the data ("+target.width + " != " + width + ")");
			if (target.depth != depth) throw new System.ArgumentException ("target VoxelArea has a different depth than the data ("+target.depth + " != " + depth + ")");
			CompactVoxelCell[] cells = new CompactVoxelCell[reader.ReadInt32()];
			CompactVoxelSpan[] spans = new CompactVoxelSpan[reader.ReadInt32()];
			int[] areas = new int[reader.ReadInt32()];
			
			for (int i=0;i<cells.Length;i++) {
				cells[i].index = reader.ReadUInt32();
				cells[i].count = reader.ReadUInt32();
			}
			for (int i=0;i<spans.Length;i++) {
				spans[i].con = reader.ReadUInt32();
				spans[i].h = reader.ReadUInt32();
				spans[i].reg = reader.ReadInt32();
				spans[i].y = reader.ReadUInt16();
			}
			for (int i=0;i<areas.Length;i++) {
				areas[i] = reader.ReadInt32();
			}
			
			target.compactCells = cells;
			target.compactSpans = spans;
			target.areaTypes = areas;
#else
			throw new System.NotImplementedException ("This method only works with !ASTAR_RECAST_CLASS_BASED_LINKED_LIST");
#endif
		}
Esempio n. 56
0
 public override void LoadState(System.IO.BinaryReader stream)
 {
     base.LoadState(stream);
     prg_reg = stream.ReadInt32();
     chr_reg = stream.ReadInt32();
 }
 public static TransparentStreamReadRequestMessage Deserialize(byte[] buffer)
 {
     if (buffer == null)
         throw new ArgumentNullException ("buffer");
     Guid id;
     Guid streamID;
     int count;
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream (buffer)) {
         using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
             id = new Guid (BR.ReadBytes (16));
             streamID = new Guid (BR.ReadBytes (16));
             count = BR.ReadInt32 ();
         }
     }
     return new TransparentStreamReadRequestMessage (id, streamID, count);
 }
Esempio n. 58
0
        private static void LoadLibrary()
        {
            // Already loaded?
            if (library != null)
            {
                return;
            }

            if (!IsSupported)
            {
                return;
            }

            int version = 1;

            rwLock.EnterWriteLock();

            library = new Dictionary <Uri, HTTPCacheFileInfo>(new UriComparer());
            try
            {
                using (var fs = HTTPManager.IOService.CreateFileStream(LibraryPath, FileStreamModes.OpenRead))
                    using (var br = new System.IO.BinaryReader(fs))
                    {
                        version = br.ReadInt32();

                        if (version > 1)
                        {
                            NextNameIDX = br.ReadUInt64();
                        }

                        int statCount = br.ReadInt32();

                        for (int i = 0; i < statCount; ++i)
                        {
                            Uri uri = new Uri(br.ReadString());

                            var entity = new HTTPCacheFileInfo(uri, br, version);
                            if (entity.IsExists())
                            {
                                library.Add(uri, entity);

                                if (version > 1)
                                {
                                    UsedIndexes.Add(entity.MappedNameIDX, entity);
                                }
                            }
                        }
                    }
            }
            catch (Exception ex)
            {
                if (HTTPManager.Logger.Level == Logger.Loglevels.All)
                {
                    HTTPManager.Logger.Exception("HTTPCacheService", "LoadLibrary", ex);
                }
            }

            finally
            {
                rwLock.ExitWriteLock();
            }

            if (version == 1)
            {
                BeginClear();
            }
            else
            {
                DeleteUnusedFiles();
            }
        }
Esempio n. 59
0
 public static ObjectBusMessage Deserialize(byte[] bytes)
 {
     Guid requestID;
     Table[] tables;
     Exception exception;
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream (bytes, false)) {
         using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
             requestID = new Guid (BR.ReadBytes (16));
             tables = new Table[BR.ReadInt32 ()];
             for (int n = 0; n != tables.Length; n++) {
                 tables [n] = Table.Deserialize (BR.ReadBytes (BR.ReadInt32 ()));
             }
             if (MS.ReadByte () == 1) {
                 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter ();
                 object deserializedObject = BF.Deserialize (MS);
                 if (deserializedObject is Exception) {
                     exception = (Exception)deserializedObject;
                 } else if (deserializedObject is string) {
                     exception = new Exception ((string)deserializedObject);
                 } else {
                     throw new Exception ("buffer contains an object of invalid type, expected System.Exception.");
                 }
             } else
                 exception = null;
             return new GetTablesResponseMessage (requestID, tables, exception);
         }
     }
 }
Esempio n. 60
0
        static void Main(string[] args)
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 7001));
            socket.Listen(10);
            for (;;)
            {
                var client = socket.Accept();
                Console.WriteLine("connected..");
                var thread = new System.Threading.Thread(() =>
                {
                    try
                    {
                        var clientReader = new System.IO.BinaryReader(new NetworkStream(client));
                        for (;;)
                        {
                            if (client.Poll(1, SelectMode.SelectRead) && client.Available == 0)
                            {
                                Console.WriteLine("disconnected..");
                                break;
                            }
                            if (client.Available > 0)
                            {
                                var msgSize       = clientReader.ReadInt32();
                                var message       = clientReader.ReadBytes(msgSize);
                                var messageReader = new System.IO.BinaryReader(new System.IO.MemoryStream(message));
                                var msgKind       = messageReader.ReadInt32();
                                Console.WriteLine("message: kind:{0}, len:{1}", msgKind, message.Length);
                                switch (msgKind)
                                {
                                case 0:
                                    {
                                        var activeProcessId = GetWindowProcessId(GetForegroundWindow());
                                        if (activeProcessId == null)
                                        {
                                            break;
                                        }
                                        if (Process.GetProcessById(activeProcessId.Value)?.ProcessName != "ZumasRevenge")
                                        {
                                            break;
                                        }

                                        var flags = messageReader.ReadUInt32();
                                        var x     = messageReader.ReadInt32();
                                        var y     = messageReader.ReadInt32();
                                        var data  = messageReader.ReadUInt32();
                                        mouse_event(flags, x, y, data, UIntPtr.Zero);
                                    }
                                    break;

                                case 1:      //reset
                                    {
                                        Process.GetProcessesByName("ZumasRevenge").FirstOrDefault()?.Kill();
                                        System.Threading.Thread.Sleep(TimeSpan.FromSeconds(4));
                                        var info = new ProcessStartInfo
                                        {
                                            FileName         = @"C:\Program Files\Games\Zuma's Revenge! v1.0.4\ZumasRevenge.exe",
                                            WorkingDirectory = @"C:\Program Files\Games\Zuma's Revenge! v1.0.4",
                                            UseShellExecute  = false,
                                        };
                                        Process.Start(info);
                                        System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
                                    }
                                    break;
                                }
                            }
                            else
                            {
                                System.Threading.Thread.Sleep(10);
                            }
                        }
                    }
                    catch (Exception exc)
                    {
                        Console.WriteLine(exc);
                    }
                })
                {
                    IsBackground = true
                };
                thread.Start();
            }
        }