Beispiel #1
0
        public void DumpToOBJ(string file_name)
        {
            using (FileStream strm = new FileStream(file_name, FileMode.Create))
            {
                EndianBinaryWriter writer = new EndianBinaryWriter(strm, Endian.Big);

                List <Vector3> master_list = new List <Vector3>();

                for (int i = 0; i < m_Meshes.Count; i++)
                {
                    Mesh cur_mesh = m_Meshes[i];

                    for (int j = 0; j < cur_mesh.VertexData.Position.Count; j++)
                    {
                        if (!master_list.Contains(cur_mesh.VertexData.Position[j]))
                        {
                            master_list.Add(cur_mesh.VertexData.Position[j]);
                        }
                    }
                }

                for (int i = 0; i < master_list.Count; i++)
                {
                    writer.Write($"v { master_list[i].X } { master_list[i].Y } { master_list[i].Z }\n".ToCharArray());
                    writer.Flush();
                }

                for (int i = 0; i < m_Meshes.Count; i++)
                {
                    writer.Write($"o { m_Meshes[i].Name }\n".ToCharArray());

                    for (int j = 0; j < m_Meshes[i].Vertices.Count; j += 3)
                    {
                        MeshVertexIndex index_1 = m_Meshes[i].Vertices[j];
                        MeshVertexIndex index_2 = m_Meshes[i].Vertices[j + 1];
                        MeshVertexIndex index_3 = m_Meshes[i].Vertices[j + 2];

                        if (index_1.Position >= m_Meshes[i].VertexData.Position.Count)
                        {
                            continue;
                        }
                        if (index_2.Position >= m_Meshes[i].VertexData.Position.Count)
                        {
                            continue;
                        }
                        if (index_3.Position >= m_Meshes[i].VertexData.Position.Count)
                        {
                            continue;
                        }

                        Vector3 vec_1 = m_Meshes[i].VertexData.Position[index_1.Position];
                        Vector3 vec_2 = m_Meshes[i].VertexData.Position[index_2.Position];
                        Vector3 vec_3 = m_Meshes[i].VertexData.Position[index_3.Position];

                        writer.Write($"f { master_list.IndexOf(vec_1) + 1 } { master_list.IndexOf(vec_2) + 1 } { master_list.IndexOf(vec_3) + 1 }\n".ToCharArray());
                        writer.Flush();
                    }
                }
            }
        }
        public static string GenerateSoundBank(string soundbankName, Stream audioStream, Stream outStream, float volume, Platform platform, bool preview = false, bool sameID = false)
        {
            bitConverter = platform.GetBitConverter;
            int soundbankID = RandomGenerator.NextInt();
            int fileID      = sameID ? oldFileID : RandomGenerator.NextInt();
            int soundID     = sameID ? oldSoundID : RandomGenerator.NextInt();

            oldSoundID = soundID; oldFileID = fileID;

            var audioReader = new EndianBinaryReader(bitConverter, audioStream);

            byte[] dataChunk      = audioReader.ReadBytes(51200); // wwise is based on audio length, we'll just make it up(prefetch lookup is 100ms)
            byte[] dataIndexChunk = DataIndex(fileID, dataChunk.Length);
            byte[] headerChunk    = Header(soundbankID, dataIndexChunk.Length, platform.IsConsole);
            byte[] stringIdChunk  = StringID(soundbankID, soundbankName);
            byte[] hierarchyChunk = Hierarchy(soundbankID, soundID, fileID, soundbankName, volume, preview, platform.IsConsole);

            var bankWriter = new EndianBinaryWriter(bitConverter, outStream);

            WriteChunk(bankWriter, "BKHD", headerChunk);
            WriteChunk(bankWriter, "DIDX", dataIndexChunk);
            WriteChunk(bankWriter, "DATA", dataChunk);
            WriteChunk(bankWriter, "HIRC", hierarchyChunk);
            WriteChunk(bankWriter, "STID", stringIdChunk);
            //Flush
            bankWriter.Flush();
            audioStream.Flush();
            outStream.Flush();
            audioStream.Position = 0;
            outStream.Position   = 0;

            return(fileID.ToString());
        }
Beispiel #3
0
        private byte[] fHe(byte[] dataArray, int cmd, bool isLoginReq = false)
        {
            var buffer = new MemoryStream(F + dataArray.Length);
            EndianBinaryWriter dataView = new EndianBinaryWriter(EndianBitConverter.Little, buffer);

            dataView.Write(F + dataArray.Length); //size; +4
            dataView.Write(s++);                  //seq +4
            dataView.Write((short)cmd);           //cmd; +2
            if (isLoginReq)
            {
                dataView.Write((short)3);//version +2
            }
            else
            {
                dataView.Write((short)V);//version +2
            }

            dataView.Write(u);//userID +4

            dataView.Write(dataArray);
            dataView.Flush();
            buffer.Flush();

            //to byte
            byte[] bytes = new byte[buffer.Length];
            buffer.Seek(0, SeekOrigin.Begin);
            buffer.Read(bytes, 0, bytes.Length);

            buffer.Close();
            dataView.Close();

            return(bytes);
        }
Beispiel #4
0
        public PrecompiledPacket(List <PacketFromServer> packets)
        {
            if (packets.Count == 0)
            {
                throw new ArgumentException("Empty list");
            }

            using (var ms = new MemoryStream())
                using (var w = new EndianBinaryWriter(EndianBitConverter.Big, ms))
                {
                    foreach (var m in packets)
                    {
                        //Buffer to memory stream
                        if (m.PacketBuffer == null)
                        {
                            m.Prepare();
                        }
                        Packet.WriteVarInt(w, m.PacketBuffer.Length);
                        w.Write(m.PacketBuffer);
                    }
                    w.Flush();
                    SetPacketBuffer(ms.ToArray());
                }
            if (PacketBuffer.Length == 0)
            {
                throw new ArgumentException("Empty compiled packet");
            }
        }
Beispiel #5
0
 private static void Encode(byte[] data, EndianBinaryWriter w)
 {
     w.Write(Preamble);
     w.Write(data.Length);
     w.Write(data);
     w.Write(CRC.Default.CalcCrc16(data));
     w.Flush();
 }
Beispiel #6
0
        public static void PackSng(Stream input, Stream output, Platform platform)
        {
            EndianBitConverter conv = platform.GetBitConverter;
            Int32 platformHeader    = 3;

            if (conv == EndianBitConverter.Big)
            {
                platformHeader = 1;
            }

            using (var w = new EndianBinaryWriter(conv, output))
                using (var zData = new MemoryStream())
                    using (var plain = new MemoryStream())
                        using (var encrypted = new MemoryStream())
                            using (var encw = new EndianBinaryWriter(conv, plain))
                            {
                                w.Write((Int32)0x4A);
                                w.Write(platformHeader);

                                // pack with zlib
                                RijndaelEncryptor.Zip(input, zData, input.Length);

                                if (platformHeader == 3)
                                {
                                    // write size of uncompressed data and packed data itself | already there
                                    encw.Write((Int32)input.Length);
                                    encw.Write(zData.ToArray());
                                    encw.Flush();

                                    // choose key
                                    byte[] key;
                                    switch (platform.platform)
                                    {
                                    case GamePlatform.Mac:
                                        key = RijndaelEncryptor.SngKeyMac;
                                        break;

                                    default: //PC
                                        key = RijndaelEncryptor.SngKeyPC;
                                        break;
                                    }
                                    // encrypt (writes 16B IV and encrypted data)
                                    plain.Position = 0;
                                    RijndaelEncryptor.EncryptSngData(plain, encrypted, key);
                                    w.Write(encrypted.ToArray());
                                    // append zero signature
                                    w.Write(new Byte[56]);
                                }
                                else
                                {
                                    // unencrypted and unsigned
                                    w.Write((Int32)input.Length);
                                    w.Write(zData.ToArray());
                                }

                                output.Flush();
                            }
        }
 /// <summary>
 /// Return null if no data
 /// </summary>
 public PrecompiledPacket Compile()
 {
     w.Flush();
     byte[] data = ms.ToArray();
     if (data.Length == 0)
     {
         return(null);
     }
     return(new PrecompiledPacket(data));
 }
Beispiel #8
0
        public void MakeAco(string file)
        {
            MemoryStream       memory        = new MemoryStream();
            EndianBinaryWriter bwriterWriter = new EndianBinaryWriter(EndianBitConverter.Big, memory);

            const UInt16 separator      = 0;
            UInt16       sectionCounter = 0;

            var colorlist = CollectionColorArea.List.Select(c => c.Color).ToList();

            UInt16 numberOfColors = UInt16.Parse(colorlist.Count.ToString());

            sectionCounter++;

            using (memory)
            {
                using (bwriterWriter)
                {
                    bwriterWriter.Write(sectionCounter);

                    bwriterWriter.Write(numberOfColors); // write the number of colors

                    foreach (var color in colorlist)
                    {
                        ColorStructureWriter(bwriterWriter, color);
                    }
                    sectionCounter++;

                    bwriterWriter.Write(sectionCounter);

                    bwriterWriter.Write(numberOfColors);

                    var encoding = new UnicodeEncoding(true, true, true);

                    foreach (var color in colorlist)
                    {
                        ColorStructureWriter(bwriterWriter, color);

                        var tmpcol = CollectionColorArea.List.FirstOrDefault(c => c.Color == color);
                        var bytes  = (encoding.GetBytes(tmpcol.Name));
                        bwriterWriter.Write((ushort)tmpcol.Name.Length + 1);
                        bwriterWriter.Write(bytes);
                        bwriterWriter.Write((ushort)0);
                    }
                    bwriterWriter.Flush();

                    using (FileStream output = new FileStream(file, FileMode.Create))
                    {
                        memory.WriteTo(output);
                    }
                }
            }
        }
Beispiel #9
0
        public override byte[] ToArray()
        {
            base.ToArray();

            //Write the length of the packet before returning the stream.
            m_Writer = new EndianBinaryWriter(new BigEndianBitConverter(), m_PacketStream);
            m_Writer.Seek(14, SeekOrigin.Begin);
            WriteUInt32((uint)(m_PacketStream.Length - 12));
            m_Writer.Flush();
            m_Writer.Seek(0, SeekOrigin.End);

            return(m_PacketStream.ToArray());
        }
Beispiel #10
0
        public static void Encode(UdpPacket packet, Stream stream)
        {
            if (packet == null)
            {
                throw new ArgumentNullException(nameof(packet));
            }
            EndianBinaryWriter endianBinaryWriter = stream != null?stream.CreateSuitableBinaryWriter() : throw new ArgumentNullException(nameof(stream));

            switch (packet.Type)
            {
            case UdpPacketType.DataReqAck:
            case UdpPacketType.DataNotReqAck:
                UdpData payload1 = packet.Payload as UdpData;
                if (payload1 != null)
                {
                    int num = 6 + ImeiEncoding.Encoding.GetByteCount(payload1.Imei) + payload1.Data.Length;
                    endianBinaryWriter.Write((short)num);
                    endianBinaryWriter.Write(packet.Id);
                    endianBinaryWriter.Write((byte)packet.Type);
                    endianBinaryWriter.Write(payload1.AvlPacketId);
                    endianBinaryWriter.Write(ImeiEncoding.Encode(payload1.Imei));
                    endianBinaryWriter.Write(payload1.Data);
                    break;
                }
                UdpResponse payload2 = packet.Payload as UdpResponse;
                if (payload2 == null)
                {
                    throw new InvalidOperationException("Payload");
                }
                endianBinaryWriter.Write((short)5);
                endianBinaryWriter.Write(packet.Id);
                endianBinaryWriter.Write((byte)packet.Type);
                endianBinaryWriter.Write(payload2.AvlPacketId);
                endianBinaryWriter.Write(payload2.AcceptedNum);
                break;

            case UdpPacketType.Ack:
                if (packet.Payload as UdpResponse == null)
                {
                    throw new InvalidOperationException("UdpAck");
                }
                endianBinaryWriter.Write((short)3);
                endianBinaryWriter.Write(packet.Id);
                endianBinaryWriter.Write((byte)packet.Type);
                break;

            default:
                throw new ApplicationException("Not supported packet type");
            }
            endianBinaryWriter.Flush();
        }
Beispiel #11
0
        public MemoryStream CopyStruct(object obj)
        {
            EndianBitConverter conv = EndianBitConverter.Little;
            MemoryStream       data = new MemoryStream();
            var  w    = new EndianBinaryWriter(conv, data);
            bool mode = this.consoleMode;

            this.consoleMode = false;
            writeStruct(w, obj);
            this.consoleMode = mode;
            w.Flush();
            data.Position = 0;
            return(data);
        }
Beispiel #12
0
        /// <summary>
        /// Reconstructs a (full) Voltron packet in memory.
        /// </summary>
        /// <param name="AriesHeader">The header of an aries packet.</param>
        /// <param name="VoltronPacket">The body (and header) of a Voltron packet.</param>
        /// <returns>A Voltron packet with its corresponding Aries header.</returns>
        private byte[] ReconstructVoltronPacket(byte[] AriesHeader, byte[] VoltronPacket)
        {
            MemoryStream       OutputStream = new MemoryStream();
            EndianBinaryWriter Writer       = new EndianBinaryWriter(new LittleEndianBitConverter(),
                                                                     OutputStream);

            Writer.Write(AriesHeader);
            Writer.Flush();

            Writer = new EndianBinaryWriter(new BigEndianBitConverter(), OutputStream);

            Writer.Write(VoltronPacket);
            Writer.Flush();

            return(OutputStream.ToArray());
        }
Beispiel #13
0
        /// <summary>
        /// Encodes the image to the specified stream from the <see cref="ImageBase{T,TP}"/>.
        /// </summary>
        /// <typeparam name="T">The pixel format.</typeparam>
        /// <typeparam name="TP">The packed format. <example>long, float.</example></typeparam>
        /// <param name="image">The <see cref="ImageBase{T,TP}"/> to encode from.</param>
        /// <param name="stream">The <see cref="Stream"/> to encode the image data to.</param>
        /// <param name="bitsPerPixel">The <see cref="BmpBitsPerPixel"/></param>
        public void Encode <T, TP>(ImageBase <T, TP> image, Stream stream, BmpBitsPerPixel bitsPerPixel)
            where T : IPackedVector <TP>
            where TP : struct
        {
            Guard.NotNull(image, nameof(image));
            Guard.NotNull(stream, nameof(stream));

            this.bmpBitsPerPixel = bitsPerPixel;

            // Cast to int will get the bytes per pixel
            short bpp          = (short)(8 * (int)bitsPerPixel);
            int   bytesPerLine = 4 * (((image.Width * bpp) + 31) / 32);

            this.padding = bytesPerLine - (image.Width * (int)bitsPerPixel);

            // Do not use IDisposable pattern here as we want to preserve the stream.
            EndianBinaryWriter writer = new EndianBinaryWriter(EndianBitConverter.Little, stream);

            BmpInfoHeader infoHeader = new BmpInfoHeader
            {
                HeaderSize   = BmpInfoHeader.Size,
                Height       = image.Height,
                Width        = image.Width,
                BitsPerPixel = bpp,
                Planes       = 1,
                ImageSize    = image.Height * bytesPerLine,
                ClrUsed      = 0,
                ClrImportant = 0
            };

            BmpFileHeader fileHeader = new BmpFileHeader
            {
                Type     = 19778, // BM
                Offset   = 54,
                FileSize = 54 + infoHeader.ImageSize
            };

            WriteHeader(writer, fileHeader);
            this.WriteInfo(writer, infoHeader);
            this.WriteImage(writer, image);

            writer.Flush();
        }
Beispiel #14
0
        /// <summary>
        /// Encodes the image to the specified stream from the <see cref="ImageFrame{TPixel}"/>.
        /// </summary>
        /// <typeparam name="TPixel">The pixel format.</typeparam>
        /// <param name="image">The <see cref="ImageFrame{TPixel}"/> to encode from.</param>
        /// <param name="stream">The <see cref="Stream"/> to encode the image data to.</param>
        public void Encode <TPixel>(Image <TPixel> image, Stream stream)
            where TPixel : struct, IPixel <TPixel>
        {
            Guard.NotNull(image, nameof(image));
            Guard.NotNull(stream, nameof(stream));

            // Cast to int will get the bytes per pixel
            short bpp          = (short)(8 * (int)this.bitsPerPixel);
            int   bytesPerLine = 4 * (((image.Width * bpp) + 31) / 32);

            this.padding = bytesPerLine - (image.Width * (int)this.bitsPerPixel);

            // Do not use IDisposable pattern here as we want to preserve the stream.
            var writer = new EndianBinaryWriter(Endianness.LittleEndian, stream);

            var infoHeader = new BmpInfoHeader
            {
                HeaderSize   = sizeof(uint),
                Height       = image.Height,
                Width        = image.Width,
                BitsPerPixel = (ushort)bpp,
                Planes       = 1,
                ImageSize    = (uint)(image.Height * bytesPerLine),
                ClrUsed      = 0,
                ClrImportant = 0
            };

            uint offset     = (uint)(BmpFileHeader.Size + infoHeader.HeaderSize);
            var  fileHeader = new BmpFileHeader
            {
                Type      = 0x4D42, // BM
                FileSize  = offset + (uint)infoHeader.ImageSize,
                Reserved1 = 0,
                Reserved2 = 0,
                Offset    = offset
            };

            WriteHeader(writer, fileHeader);
            this.WriteInfo(writer, infoHeader);
            this.WriteImage(writer, image.Frames.RootFrame);

            writer.Flush();
        }
Beispiel #15
0
        public void InitStageOne(bool authenticated)
        {
            // Generate code
            Generator generator = new Generator();

            if (authenticated)
            {
                generator.Build(Code);
            }
            else
            {
                generator.Build(new byte[1]);
            }

            // Return response
            writer.Write((short)(generator.Output.Length + 2));
            writer.Write((short)102);
            writer.Write(generator.Output);
            writer.Flush();
        }
Beispiel #16
0
        public void Encode(ImageBase image, Stream stream, BmpBitsPerPixel bitsPerPixel)
        {
            if (image == null || stream == null)
            {
                throw new ArgumentNullException();
            }
            bmpBitsPerPixel = bitsPerPixel;
            int rowWidth = image.Width;

            // TODO: Check this for varying file formats.
            int amount = (image.Width * (int)bmpBitsPerPixel) % 4;

            if (amount != 0)
            {
                rowWidth += 4 - amount;
            }

            // Do not use IDisposable pattern here as we want to preserve the stream.
            EndianBinaryWriter writer = new EndianBinaryWriter(EndianBitConverter.Little, stream);
            int           bpp         = (int)bmpBitsPerPixel;
            BmpFileHeader fileHeader  = new BmpFileHeader {
                Type     = 19778,             // BM
                Offset   = 54,
                FileSize = 54 + image.Height * rowWidth * bpp
            };
            BmpInfoHeader infoHeader = new BmpInfoHeader {
                HeaderSize   = 40,
                Height       = image.Height,
                Width        = image.Width,
                BitsPerPixel = (short)(8 * bpp),
                Planes       = 1,
                ImageSize    = image.Height * rowWidth * bpp,
                ClrUsed      = 0,
                ClrImportant = 0
            };

            WriteHeader(writer, fileHeader);
            WriteInfo(writer, infoHeader);
            WriteImage(writer, image);
            writer.Flush();
        }
Beispiel #17
0
        private void CompileVoltronPackets(Client C)
        {
            MemoryStream       OutputStream = new MemoryStream();
            EndianBinaryReader Reader;
            EndianBinaryWriter Writer;

            AriesHeader AHeader = new AriesHeader();

            AHeader.PacketSize = m_PacketSize;
            AHeader.PacketType = m_PacketType;

            //Reassemble all the Voltron packets.
            for (int i = 0; i < C.ReceivedSplitBuffers.Count; i++)
            {
                SplitBufferPDU SplitBuffer;
                C.ReceivedSplitBuffers.TryDequeue(out SplitBuffer);

                Reader = new EndianBinaryReader(new BigEndianBitConverter(), OutputStream);
                Writer = new EndianBinaryWriter(new BigEndianBitConverter(), OutputStream);

                Writer.Write(Reader.ReadBytes((int)SplitBuffer.FragmentSize));
                Writer.Flush();
            }

            MemoryStream VoltronPackets = new MemoryStream(OutputStream.ToArray());
            uint         BufSize        = (uint)VoltronPackets.Length;

            for (int i = 0; i < BufSize; i++)
            {
                Reader = new EndianBinaryReader(new BigEndianBitConverter(), VoltronPackets);
                VoltronHeader Header = ReadVoltronHeader(Reader.ReadBytes(12));
                Reader.BaseStream.Position = 0; //Backtrack to beginning of stream.

                VoltronPacket VPacket = new VoltronPacket(
                    ReconstructVoltronPacket(AHeader, Reader.ReadBytes((int)Header.PacketSize)), true);
                C.ReceivedPackets.Enqueue(VPacket);
                BufSize -= Header.PacketSize;

                ReceivedData?.Invoke(this, C);
            }
        }
 private byte[] GetMessageHash(
     uint messageId,
     uint replyToMessageId,
     byte messageKind,
     byte[] data
     )
 {
     using (
         var msBuffer = new MemoryStream(
             +sizeof(uint)
             + sizeof(uint)
             + sizeof(byte)
             + 32
             )
         )
     {
         using (
             var writer
                 = new EndianBinaryWriter(
                       _littleEndianConverter,
                       msBuffer
                       )
                 )
         {
             writer.Write(messageId);
             writer.Write(replyToMessageId);
             writer.Write(messageKind);
             using (var hashAlg = new SHA256Managed())
             {
                 writer.Write(hashAlg.ComputeHash(data));
             }
             writer.Flush();
             using (var hashAlg = new SHA256Managed())
             {
                 return(hashAlg.ComputeHash(msBuffer.ToArray()));
             }
         }
     }
 }
    /**
         * Send the XML request string
         */
    public String sendCommand(string command)
    {
        try {
                bw = new EndianBinaryWriter(new BigEndianBitConverter(), tcS);
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                byte[] bytes = encoding.GetBytes(command);
                bw.Write(bytes.Length);
                bw.Write(bytes);

                bw.Flush();
                br = new EndianBinaryReader(new BigEndianBitConverter(), tcS);
                int i = br.ReadInt32();

                byte[] bytess = new byte[i];
                br.Read(bytess, 0, i);
                String response = encoding.GetString(bytess, 0, i);
                Console.WriteLine(response);
                return response;
            } catch (Exception) {
                return "";
            }
    }
Beispiel #20
0
        static void Process(string filename)
        {
            int         floatsSent = 0;
            int         lineCount  = 0;
            IFeatureSet fs         = FeatureSet.Open(filename);
            var         shapes     = fs.ShapeIndices.ToList();

            foreach (var shape in shapes)
            {
                foreach (var part in shape.Parts)
                {
                    lineCount += part.Segments.Count();
                }
            }
            var fileStream = File.Create(filename + ".wrlineoverlay");
            EndianBinaryWriter endianBinaryWriter = new EndianBinaryWriter(fileStream, Encoding.ASCII, true);

            endianBinaryWriter.Write(lineCount);
            endianBinaryWriter.Flush();
            BinaryWriter binaryWriter = new BinaryWriter(fileStream);

            foreach (var shape in shapes)
            {
                foreach (var part in shape.Parts)
                {
                    foreach (var s in part.Segments)
                    {
                        binaryWriter.Write(ConvertLongitude(s.P1.X)); //long1
                        binaryWriter.Write(ConvertLatitude(s.P1.Y));  //lat1
                        binaryWriter.Write(ConvertLongitude(s.P2.X)); //long2
                        binaryWriter.Write(ConvertLatitude(s.P2.Y));  //lat2
                        floatsSent += 4;
                    }
                }
            }
            binaryWriter.Flush();
            fileStream.Close();
        }
Beispiel #21
0
        public override VirtualFilesystemDirectory ExportToVFS()
        {
            VirtualFilesystemDirectory new_dir = SourceDirectory;

            new_dir.Name = Name;

            VirtualFilesystemFile dzr_file = SourceDirectory.GetFileAtPath("dzr/room.dzr");

            using (MemoryStream mem = new MemoryStream())
            {
                using (EndianBinaryWriter writer = new EndianBinaryWriter(mem, Endian.Big))
                {
                    SceneDataExporter exporter = new SceneDataExporter();
                    exporter.ExportToStream(writer, this);

                    writer.Flush();

                    dzr_file.Data = mem.ToArray();
                }
            }

            return(new_dir);
        }
Beispiel #22
0
        public byte[] GetBytes()
        {
            MemoryStream       stream = new MemoryStream();
            EndianBinaryWriter writer = new EndianBinaryWriter(EndianBitConverter.Big, stream);

#if REIGN_MSG_PROTOCOL_CLUSTER
            writer.Write(packageType);
            writer.Write(serverType);
            writer.Write(serverId);
#endif

            byte[] commandBytes = Encoding.UTF8.GetBytes(command);
            byte[] bytes        = new byte[32];
            Array.Copy(commandBytes, bytes, commandBytes.Length);
            writer.Write(bytes);

            writer.Write(requestId);

            bytes = Encoding.UTF8.GetBytes(content);
            writer.Write(bytes);

            writer.Flush();
            bytes = stream.ToArray();
            writer.Dispose();

            // 先写入长度,再写入内容
            stream = new MemoryStream();
            writer = new EndianBinaryWriter(EndianBitConverter.Big, stream);
            writer.Write(bytes.Length);
            writer.Write(bytes);
            writer.Flush();
            bytes = stream.ToArray();
            writer.Dispose();

            return(bytes);
        }
Beispiel #23
0
        public override VirtualFilesystemDirectory ExportToVFS()
        {
            VirtualFilesystemDirectory new_dir = SourceDirectory;

            new_dir.Name = Name;

            VirtualFilesystemFile dzs_file = SourceDirectory.GetFileAtPath("dzs/stage.dzs");

            using (MemoryStream mem = new MemoryStream())
            {
                using (EndianBinaryWriter writer = new EndianBinaryWriter(mem, Endian.Big))
                {
                    SceneDataExporter exporter = new SceneDataExporter();
                    exporter.ExportToStream(writer, this);

                    writer.Flush();

                    dzs_file.Data = mem.ToArray();
                }
            }

            List <J3DNode> meshes = GetChildrenOfType <J3DNode>();

            for (int i = 0; i < meshes.Count; i++)
            {
                string modelExt = meshes[i].Model.StudioType == "bdl4" ? "bdl" : "bmd";

                VirtualFilesystemFile modelFile = SourceDirectory.GetFileAtPath($"{ modelExt }/{ meshes[i].Name }.{ modelExt }");
                byte[] data = File.ReadAllBytes(meshes[i].Filename);

                if (modelFile != null)
                {
                    modelFile.Data = data;
                }
                else
                {
                    VirtualFilesystemDirectory modelDir = null;

                    foreach (VirtualFilesystemNode n in new_dir.Children)
                    {
                        if (n.Name == modelExt)
                        {
                            modelDir = n as VirtualFilesystemDirectory;
                            break;
                        }
                    }

                    if (modelDir == null)
                    {
                        modelDir = new VirtualFilesystemDirectory(modelExt);
                        new_dir.Children.Add(modelDir);
                    }

                    modelDir.Children.Add(new VirtualFilesystemFile(meshes[i].Name, $".{ modelExt }", data));
                }
            }

            VirtualFilesystemFile dat_file  = SourceDirectory.GetFileAtPath("dat/event_list.dat");
            WEventList            eventlist = GetChildrenOfType <WEventList>()[0];

            using (MemoryStream ev_strm = new MemoryStream())
            {
                using (EndianBinaryWriter writer = new EndianBinaryWriter(ev_strm, Endian.Big))
                {
                    eventlist.ExportToStream(writer);
                    writer.Flush();

                    dat_file.Data = ev_strm.ToArray();
                }
            }

            return(new_dir);
        }
        public void LoadFromArc(string fileName)
        {
            string tempFileName = "";

            using (FileStream yaz0TestStream = new FileStream(fileName, FileMode.Open))
            {

                EndianBinaryReader yaz0TestReader = new EndianBinaryReader(yaz0TestStream, Endian.Big);

                string yaz0Test = yaz0TestReader.ReadString(4);

                if (yaz0Test == "Yaz0")
                {
                    byte[] uncompressedArc = DecodeYaz0(yaz0TestReader);

                    yaz0TestReader.Close();

                    fileName = Path.GetTempFileName();

                    tempFileName = fileName;

                    FileInfo info = new FileInfo(fileName);

                    info.Attributes = FileAttributes.Temporary;

                    using (FileStream tempStream = new FileStream(fileName, FileMode.Open))
                    {
                        EndianBinaryWriter tempWriter = new EndianBinaryWriter(tempStream, Endian.Big);

                        tempWriter.Write(uncompressedArc);

                        tempWriter.Flush();

                        tempWriter.Close();
                    }
                }
            }

            RARC loadedArc = new RARC(fileName);

            if (File.Exists(tempFileName))
            {
                File.Delete(tempFileName);
            }

            FilesFromArc = new List<FileData>();

            for (int i = 0; i < loadedArc.Nodes.Count(); i++)
            {
                for (int j = 0; j < loadedArc.Nodes[i].Entries.Count(); j++)
                {
                    if (loadedArc.Nodes[i].Entries[j].Data != null)
                    {
                        FileData file = new FileData();

                        file.Name = loadedArc.Nodes[i].Entries[j].Name;

                        file.Data = loadedArc.Nodes[i].Entries[j].Data;

                        FilesFromArc.Add(file);
                    }
                }
            }

            foreach (FileData file in FilesFromArc)
            {
                if (file.Name.Contains(".dzb"))
                {
                    using (EndianBinaryReader reader = new EndianBinaryReader(file.Data, Endian.Big))
                    {

                        Collision = new CollisionMesh();

                        Collision.Load(reader);
                    }
                }

                if (file.Name.Contains(".dzs") || file.Name.Contains(".dzr"))
                {
                    using (EndianBinaryReader reader = new EndianBinaryReader(file.Data, Endian.Big))
                    {
                        Read(reader);
                    }
                }

                if (file.Name.Contains(".bdl") || file.Name.Contains(".bmd"))
                {
                    //Not implemented
                }
            }
        }
Beispiel #25
0
 public void WriteByte(byte Value)
 {
     m_Writer.Write(Value);
     m_Writer.Flush();
 }
        public static string GenerateSoundBank(string soundbankName, Stream audioStream, Stream outStream, float volume, Platform platform)
        {
            string eventName   = PLAY + soundbankName;
            string previewName = PLAY30SEC + soundbankName;
            string bankName    = SONG + soundbankName;
            var    id          = RandomGenerator.NextInt();

            byte[] soundbank = null;

            switch (platform.version)
            {
            case GameVersion.RS2012:
                switch (platform.platform)
                {
                case GamePlatform.Pc:
                    soundbank = Resources.PC_soundbank;
                    break;

                case GamePlatform.XBox360:
                case GamePlatform.PS3:
                    soundbank = Resources.Console_soundbank;
                    break;

                default:
                    throw new InvalidOperationException("Unexpected game platform value");
                }
                break;

            default:
                throw new InvalidOperationException("Unexpected game version value");
            }

            var bitConverter = platform.GetBitConverter;

            using (var bankStream = new MemoryStream(soundbank))
                using (var bankReader = new EndianBinaryReader(bitConverter, bankStream))
                {
                    var audioReader = new EndianBinaryReader(bitConverter, audioStream);
                    var bankWriter  = new EndianBinaryWriter(bitConverter, outStream);
                    bankWriter.Write(bankReader.ReadBytes(platform.GetOffsets()[0]));
                    bankReader.ReadInt32();
                    bankWriter.Write(id);
                    bankWriter.Write(bankReader.ReadInt32());
                    int dataSize = bankReader.ReadInt32();
                    bankWriter.Write(dataSize);
                    bankWriter.Write(bankReader.ReadInt32());
                    bankWriter.Write(bankReader.ReadInt32());
                    bankWriter.Write(audioReader.ReadBytes(dataSize));
                    bankReader.BaseStream.Seek(dataSize, SeekOrigin.Current);
                    bankWriter.Write(bankReader.ReadBytes(platform.GetOffsets()[1]));
                    bankWriter.Write(id);
                    bankWriter.Write(id);
                    bankReader.BaseStream.Seek(8, SeekOrigin.Current);
                    bankWriter.Write(bankReader.ReadBytes(platform.GetOffsets()[2]));
                    bankWriter.Write((float)volume);
                    bankReader.ReadInt32();
                    bankWriter.Write(bankReader.ReadBytes(platform.GetOffsets()[3]));
                    bankReader.ReadInt32();
                    bankWriter.Write(HashString(eventName));
                    bankWriter.Write(bankReader.ReadBytes(platform.GetOffsets()[4]));
                    bankReader.ReadInt32();
                    bankWriter.Write(HashString(previewName));
                    bankWriter.Write(bankReader.ReadBytes(platform.GetOffsets()[5]));
                    bankWriter.Write(12 + bankName.Length + 1);
                    bankReader.ReadInt32();
                    bankWriter.Write(bankReader.ReadBytes(platform.GetOffsets()[6]));
                    bankWriter.Write((byte)bankName.Length);
                    bankWriter.Write(Encoding.ASCII.GetBytes(bankName));
                    bankWriter.Flush();
                }

            return(id.ToString());
        }
        private void SaveFiles()
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string savePath = saveFileDialog1.FileName;

                FileStream originalArc = new FileStream(ArcFilePath, FileMode.Open);

                EndianBinaryReader reader = new EndianBinaryReader(originalArc, GameFormatReader.Common.Endian.Big);

                List<byte> testList = reader.ReadBytes((int)reader.BaseStream.Length).ToList();

                reader.Close();

                List<Message> exportList = new List<Message>();

                foreach (Message mes in MessageList)
                {
                    mes.ProofReadTagstoCodes();

                    Message temp = mes.Copy();

                    exportList.Add(temp);
                }

                byte[] newBMGFile = TextBankClass.ExportBMGFromPath(exportList);

                testList.RemoveRange(1344, testList.Count - 1344);

                testList.AddRange(newBMGFile);

                byte[] newBMCFile = ColorClass.BMCExporter(ColorList);

                testList.RemoveRange(256, newBMCFile.Length);

                testList.InsertRange(256, newBMCFile);

                FileStream testStream = new FileStream(savePath, FileMode.Create);

                EndianBinaryWriter writer = new EndianBinaryWriter(testStream, Endian.Big);

                writer.Write(testList.ToArray());

                writer.BaseStream.Position = 128;

                writer.Write((int)newBMGFile.Length);

                writer.BaseStream.Position = 4;

                writer.Write((int)testList.Count);

                writer.Flush();

                writer.Close();
            }
        }
Beispiel #28
0
        public static void PackSng(Stream input, Stream output, Platform platform)
        {
            EndianBitConverter conv;
            Int32 platformHeader;

            switch (platform.platform)
            {
            case GamePlatform.Pc:
            case GamePlatform.Mac:
                // Desktop
                conv           = EndianBitConverter.Little;
                platformHeader = 3;
                break;

            case GamePlatform.XBox360:
            case GamePlatform.PS3:
                // Console
                conv           = EndianBitConverter.Big;
                platformHeader = 1;
                break;

            default:
                conv           = EndianBitConverter.Little;
                platformHeader = 3;
                break;
            }

            using (EndianBinaryWriter w = new EndianBinaryWriter(conv, output)) {
                w.Write((Int32)0x4A);
                w.Write(platformHeader);

                byte[] inputChartData = null;
                using (var mStream = new MemoryStream())
                {
                    input.CopyTo(mStream);
                    inputChartData = mStream.ToArray();
                }

                // pack with zlib
                MemoryStream  zData = new MemoryStream();
                ZOutputStream zOut  = new ZOutputStream(zData, zlib.zlibConst.Z_BEST_COMPRESSION);
                zOut.Write(inputChartData, 0, inputChartData.Length);
                zOut.finish();
                byte[] packed = zData.ToArray();

                if (platformHeader == 3)
                {
                    MemoryStream encrypted = new MemoryStream();
                    MemoryStream plain     = new MemoryStream();
                    var          encw      = new EndianBinaryWriter(conv, plain);
                    // write size of uncompressed data and packed data itself
                    encw.Write((Int32)inputChartData.Length);
                    encw.Write(packed);
                    encw.Flush();
                    MemoryStream inputPlainStream = new MemoryStream(plain.ToArray());

                    // choose key
                    byte[] key;
                    switch (platform.platform)
                    {
                    case GamePlatform.Mac:
                        key = RijndaelEncryptor.SngKeyMac;
                        break;

                    default:     //PC
                        key = RijndaelEncryptor.SngKeyPC;
                        break;
                    }

                    // encrypt (writes 16B IV and encrypted data)
                    RijndaelEncryptor.EncryptSngData(inputPlainStream, encrypted, key);
                    w.Write(encrypted.ToArray());
                    // append zero signature
                    w.Write(new Byte[56]);
                }
                else
                {
                    // unencrypted and unsigned
                    w.Write((Int32)inputChartData.Length);
                    w.Write(packed);
                }

                output.Flush();
            }
        }
        public async Task <uint> SendRawDatagram(
            string destination,
            byte[] data,
            uint messageId        = 0,
            uint replyToMessageId = 0,
            byte messageKind      = 0
            )
        {
            using (_stateHelper.GetFuncWrapper())
            {
                if (messageId == 0)
                {
                    messageId = await GetNextOutMessageId().ConfigureAwait(false);
                }
                using (
                    var msBuffer = new MemoryStream(
                        sizeof(byte)
                        + sizeof(uint)
                        + sizeof(uint)
                        + sizeof(byte)
                        + data.Length
                        + 32
                        )
                    )
                {
                    using (
                        var writer
                            = new EndianBinaryWriter(
                                  _littleEndianConverter,
                                  msBuffer
                                  )
                            )
                    {
                        writer.Write((byte)ReliableDatagramCodes.RawDatagram);
                        writer.Write(messageId);
                        writer.Write(replyToMessageId);
                        writer.Write(messageKind);
                        writer.Write(GetMessageHash(messageId, replyToMessageId, messageKind, data));
                        writer.Write(data);
                        writer.Flush();
                        await _samHelper.SendDatagram(
                            destination,
                            msBuffer.ToArray()
                            ).ThrowIfCancelled(_cts.Token).ConfigureAwait(false);

                        _log.Trace(
                            string.Format(
                                "{5}, send raw datagram of {0} bytes " +
                                "to {1} id={2},rid={3},kind={6},ansiS='{4}'",
                                data.Length,
                                destination.Substring(0, 20),
                                messageId,
                                replyToMessageId,
                                Encoding.ASCII.GetString(data),
                                _reliableSamHelperGuid.ToString().Substring(0, 5),
                                messageKind
                                )
                            );
                        return(messageId);
                    }
                }
            }
        }
 private async Task SendHandshakeStart(
     string destination,
     uint messageId,
     uint replyToMessageId,
     uint totalSize,
     uint blockSize,
     byte[] messageHash,
     byte[] firstBlockData,
     byte messageKind = 0
     )
 {
     if (messageHash == null)
     {
         throw new ArgumentNullException(
                   MyNameof.GetLocalVarName(() => messageHash));
     }
     if (messageHash.Length != 32)
     {
         throw new ArgumentOutOfRangeException(
                   MyNameof.GetLocalVarName(() => messageHash));
     }
     using (
         var ms = new MemoryStream(
             sizeof(byte)
             + sizeof(uint)
             + sizeof(uint)
             + sizeof(byte)
             + sizeof(uint)
             + sizeof(uint)
             + 32
             + sizeof(uint)
             + firstBlockData.Length
             )
         )
     {
         using (
             var binaryWriter
                 = new EndianBinaryWriter(
                       _littleEndianConverter,
                       ms
                       )
                 )
         {
             binaryWriter.Write(
                 (byte)ReliableDatagramCodes.HandshakeStart
                 );
             binaryWriter.Write(messageId);
             binaryWriter.Write(replyToMessageId);
             binaryWriter.Write(messageKind);
             binaryWriter.Write(totalSize);
             binaryWriter.Write(blockSize);
             binaryWriter.Write(messageHash);
             binaryWriter.Write((uint)firstBlockData.Length);
             binaryWriter.Write(firstBlockData);
             binaryWriter.Flush();
             await _samHelper.SendDatagram(
                 destination,
                 ms.ToArray()
                 ).ThrowIfCancelled(_cts.Token).ConfigureAwait(false);
         }
     }
 }