public static byte[] Decode(byte[] data, int from, int to, int bitsInterval) { var copiedData = new byte[to - from + 1]; Array.Copy(data, from, copiedData, 0, copiedData.Length); byte[] reverseBytes = Convert.ReverseBitsInBytes(copiedData); using (var s = new MemoryStream(reverseBytes)) using (var reader = new BitReader(s)) { using (var decoded = new MemoryStream()) using (var writer = new BitWriter(decoded)) { int counter = 0; while (reader.CanRead) { byte bit = reader.ReadBits(1); writer.WriteBit(bit); counter = (bit == 1) ? counter + 1 : 0; if (counter == bitsInterval) { reader.ReadBits(1); // skip next 0 bit counter = 0; } } // !! do not flush last bits return Convert.ReverseBitsInBytes(decoded.ToArray()); } } }
public override void Serialize( Stream stream ) { base.Serialize( stream ); var bw = new BitWriter(); bw.WriteInt32( Protocol ); bw.WriteInt32(AuthProtocol); bw.WriteInt32(ServerChallenge); bw.WriteInt32(ClientChallenge); bw.WriteString( Name ); bw.WriteString( Password ); bw.WriteByte( ( byte )Players.Count ); foreach ( var player in Players ) { bw.WriteByte( ( byte )CLC_Messages.clc_SplitPlayerConnect ); using ( var ms = new MemoryStream() ) { Serializer.SerializeWithLengthPrefix( ms, player, PrefixStyle.Base128 ); bw.WriteBytes( ms.ToArray() ); } } // bLowViolence bw.WriteBits( 0, 1 ); bw.WriteUInt16( ( ushort )Ticket.Length ); bw.WriteBytes( Ticket ); stream.Write( bw.Data, 0, bw.Data.Length - 1 ); }
public static byte[] Encode(byte[] data, int bitsInterval) { byte[] reverseBytes = Convert.ReverseBitsInBytes(data); using (var s = new MemoryStream(reverseBytes)) using (var reader = new BitReader(s)) { using (var encoded = new MemoryStream()) using (var writer = new BitWriter(encoded)) { int counter = 0; while (reader.CanRead) { byte bit = reader.ReadBits(1); writer.WriteBit(bit); counter = (bit == 1) ? counter + 1 : 0; if (counter == bitsInterval) { writer.WriteBit(0); counter = 0; } } writer.FlushBits(); return Convert.ReverseBitsInBytes(encoded.ToArray()); } } }
/* * 0 通道ID BYTE >0 1 拍摄命令 WORD 0 表示停止拍摄;0xFFFF 表示录像;其它表示拍 照张数 3 拍照间隔/录像时间 WORD 秒,0 表示按最小间隔拍照或一直录像 5 保存标志 BYTE 1:保存; 0:实时上传 6 分辨率a BYTE 0x01:320*240; 0x02:640*480; 0x03:800*600; 0x04:1024*768; 0x05:176*144;[Qcif]; 0x06:352*288;[Cif]; 0x07:704*288;[HALF D1]; 0x08:704*576;[D1]; 7 图像/视频质量 BYTE 1-10,1 代表质量损失最小,10 表示压缩比最大 8 亮度 BYTE 0-255 9 对比度 BYTE 0-127 10 饱和度 BYTE 0-127 11 色度 BYTE 0-255 * * */ /// <summary> /// 中心抓拍图片 /// </summary> /// <param name="ordinal"></param> /// <param name="size"></param> /// <param name="quality"></param> /// <param name="count"></param> /// <returns></returns> public override byte[] Capture(uint ordinal, SizeType size, QualityType quality, byte count) { var mes = Message.Create(0x8801, this.terminalid + "", 0, null); var ms = new MemoryStream(); BitWriter bw = new BitWriter(ms); bw.Write((byte)1);//通道一 bw.Write((UInt16)count);//拍一张 bw.Write((UInt16)0);//拍照间隔 bw.Write((byte)0);//0实时上传 1保存 byte pixel = 0x01; switch (size) //分辨率 图片大小 { case SizeType.Big: pixel = 0x04; break; // case SizeType.Normal: pixel = 0x08; break; // case SizeType.Small: pixel = 0x01; break; // } bw.Write(pixel);//分辨率 byte level = 1; switch (quality) //图片质量 { case QualityType.Height: level = 1; break; case QualityType.Normal: level = 5; break; case QualityType.Low: level = 10; break; } bw.Write(level);//图片质量 bw.Write((byte)127);//亮度 bw.Write((byte)64);//对比度 bw.Write((byte)64);//饱和度 bw.Write((byte)127);//色度 mes.BodyBytes = ms.ToArray(); return mes.ToBytes(); }
public static void GammaCode(ulong number, BitWriter writer) { // to allow zero number += 1; int size = 0; ulong tmp = number; while (tmp >= 1) { size++; tmp /= 2; } int zeroes = size - 1; for (int i = 0; i < zeroes; i++) writer.Write(false); for (int i = size - 1; i >= 0; i--) { bool bit = (number & (1UL << i)) != 0; writer.Write(bit); } }
public void Serialize(BitWriter bw) { bw.Write(Active); bw.Write(ActorId); Offset.Serialize(bw); bw.Write(Mass); Rotation.Serialize(bw); }
public void Serialize(BitWriter bw) { bw.Write(TeamNumber); bw.Write(TeamColorId); bw.Write(CustomColorId); bw.Write(TeamFinishId); bw.Write(CustomFinishId); }
public void Encode(Stream reader, BitWriter writer) { if (!reader.CanRead || !reader.CanSeek) throw new InvalidOperationException(); m_writer = writer; Encode(reader); }
public void Serialize(BitWriter bw) { string.Join(",", Mutators).Serialize(bw); bw.Write(Unknown1); bw.Write(Unknown2); GameName.Serialize(); Password.Serialize(); bw.Write(Unknown3); }
public void Serialize(BitWriter bw) { bw.Write(FieldOfView); bw.Write(Height); bw.Write(Pitch); bw.Write(Distance); bw.Write(Stiffness); bw.Write(SwivelSpeed); }
public void Serialize(BitWriter bw) { bw.Write(Unknown1); bw.Write(AttackerActorId); bw.Write(Unknown2); bw.Write(VictimActorId); AttackerVelocity.Serialize(bw); VictimVelocity.Serialize(bw); }
public static void Compress(string inputFile, string outputFile) { var coder = new Coder(); using (var reader = File.OpenRead(inputFile)) using (var writer = new BitWriter(outputFile)) { coder.Encode(reader, writer); } }
public void Serialize(BitWriter bw) { bw.Write(Sleeping); Position.Serialize(bw); Rotation.SerializeFixed(bw); if (!Sleeping) { LinearVelocity.Serialize(bw); AngularVelocity.Serialize(bw); } }
public void Serialize(BitWriter bw) { bw.Write((byte)ThingLists.Count); foreach (var thingList in ThingLists) { bw.Write((byte)thingList.Count); foreach(var thing in thingList) { thing.Serialize(bw); // "i >= 21" logic from Deserialize is handled automatically here. No special serialize logic needed. } } }
public void BitWriterEmptyTest() { using (MemoryStream ms = new MemoryStream()) { BitWriter bw = new BitWriter() { Output = ms, CodeLength = 4, }; bw.FlushBits(); bw.FlushBytes(); byte[] bytes = ms.ToArray(); Assert.AreEqual(0, bytes.Length); } }
public void Serialize(BitWriter bw) { bw.Write(Version); bw.Write(BodyProductId); bw.Write(SkinProductId); bw.Write(WheelProductId); bw.Write(BoostProductId); bw.Write(AntennaProductId); bw.Write(HatProductId); bw.Write(Unknown2); if (Version > 10) { bw.Write(Unknown3); } }
public void BitWriterOneUnitTest() { using (MemoryStream ms = new MemoryStream()) { BitWriter bw = new BitWriter() { Output = ms, CodeLength = 4, }; bw.WriteBits(5); bw.FlushBits(); bw.FlushBytes(); byte[] bytes = ms.ToArray(); Assert.AreEqual(2, bytes.Length); Assert.AreEqual(0x01, bytes[0]); Assert.AreEqual(0x05, bytes[1]); } }
public void Serialize(UInt32 versionMajor, UInt32 versionMinor, BitWriter bw) { bw.WriteFixedBitCount(Unknown1, 3); PlayerId.Serialize(bw); if ( PlayerId.Type != UniqueId.UniqueIdType.Unknown) { PlayerName.Serialize(bw); } if (versionMajor < 868 || versionMinor < 12) { bw.WriteFixedBitCount(Unknown2, 2); } else { bw.Write(Unknown2); } }
/// <summary> /// Finalizes the hash computation after the last data is processed by the cryptographic stream object. /// </summary> /// <returns>The computed hash code.</returns> protected override byte[] HashFinal() { try { this.ProcessMessage(this.Padding()); BitWriter writer = new BitWriter(16); writer.AppendUInit32(this.state[0], 32); writer.AppendUInit32(this.state[1], 32); writer.AppendUInit32(this.state[2], 32); writer.AppendUInit32(this.state[3], 32); return writer.Bytes; } finally { this.Initialize(); } }
public void Write(BitWriter writer) { var alm = InfoManager.AssetLibraryManager; alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.WeaponTypes, this.Type); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.BalanceDefs, this.Balance); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.Manufacturers, this.Manufacturer); writer.WriteInt32(this.ManufacturerGradeIndex, 7); writer.WriteInt32(this.GameStage, 7); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.WeaponParts, this.BodyPart); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.WeaponParts, this.GripPart); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.WeaponParts, this.BarrelPart); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.WeaponParts, this.SightPart); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.WeaponParts, this.StockPart); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.WeaponParts, this.ElementalPart); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.WeaponParts, this.Accessory1Part); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.WeaponParts, this.Accessory2Part); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.WeaponParts, this.MaterialPart); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.WeaponParts, this.PrefixPart); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.WeaponParts, this.TitlePart); }
public void Write(BitWriter writer) { var alm = InfoManager.AssetLibraryManager; alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.ItemTypes, this.Type); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.BalanceDefs, this.Balance); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.Manufacturers, this.Manufacturer); writer.WriteInt32(this.ManufacturerGradeIndex, 7); writer.WriteInt32(this.GameStage, 7); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.ItemParts, this.AlphaPart); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.ItemParts, this.BetaPart); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.ItemParts, this.GammaPart); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.ItemParts, this.DeltaPart); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.ItemParts, this.EpsilonPart); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.ItemParts, this.ZetaPart); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.ItemParts, this.EtaPart); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.ItemParts, this.ThetaPart); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.ItemParts, this.MaterialPart); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.ItemParts, this.PrefixPart); alm.Encode(writer, this.AssetLibrarySetId, AssetGroup.ItemParts, this.TitlePart); }
private void WriteImage() { Logger.Trace("写入图像..."); var paletteHash = new Dictionary <Color, byte>(); byte i = 0; foreach (var color in _palette) { paletteHash[color] = i; i++; } using (var context = _image.CreateUnsafeContext()) { for (var y = 0; y < _height; y++) { var rowData = new byte[_rowLengthInBytes]; var memoryStream = new MemoryStream(rowData); var bitWriter = new BitWriter(memoryStream); for (var x = 0; x < _width; x++) { var color = context.GetPixel(x, y); if (color.A < 0x80 && _transparency == 1) { bitWriter.WriteBits(0, _bitsPerPixel); } else { var paletteIndex = paletteHash[color]; bitWriter.WriteBits(paletteIndex, _bitsPerPixel); } } bitWriter.Flush(); _writer.Write(rowData); } } }
public void Send(BitWriter bs, PacketReliability reliablity, Connection connection, int sequenceChannel) { bs.FlushBits(); LocalClientInterface targetClient = null; foreach (var client in clients) { if (client.connection == connection) { targetClient = client; break; } } if (targetClient == null) { throw new Exception("Client not found."); } targetClient.EnqueueMessage(bs); }
public void TestFlushAndContinue() { var stream = new MemoryStream(); var writer = new BitWriter(stream); writer.WriteBits(2, 3); // 01010[1101]10 Assert.That(writer.Position, Is.EqualTo(2)); writer.Flush(); Assert.That(writer.Position, Is.EqualTo(2)); var bytes = stream.ToArray(); Assert.That(bytes, Is.EqualTo(new byte[] { 0xC0 })); writer.WriteBits(4, 6); writer.Flush(); Assert.That(writer.Position, Is.EqualTo(6)); bytes = stream.ToArray(); Assert.That(bytes, Is.EqualTo(new byte[] { 0xD8 })); // 11 0110 00 }
private int WriteDictString(BitWriter bw, int length, Tuple <int, int>[] dict, int start) { _stack.Clear(); var stack = _stack; var idx = start; while (idx < LzwMaxCode + 1) { stack.Push(dict[idx].Item2); idx = dict[idx].Item1; } var last = stack.Peek(); while (stack.Count > 0) { bw.WriteBits(stack.Pop(), length); } return(last); }
public override void Encode(Stream input, BitWriter bw, Match[] matches) { CreateDisplacementTable(matches.Select(x => x.Displacement).ToArray(), 2); WriteDisplacementTable(bw); foreach (var match in matches) { var rawLength = match.Position - input.Position; if (rawLength > 0) { WriteRawData(input, bw, rawLength); } WriteMatchData(input, bw, match); input.Position += match.Length; } if (input.Length - input.Position > 0) { WriteRawData(input, bw, input.Length - input.Position); } }
public override void Construct(BitWriter writer) { var hasJetpackEffect = JetpackEffectId != 0; writer.WriteBit(hasJetpackEffect); if (hasJetpackEffect) { writer.Write(JetpackEffectId); writer.WriteBit(false); // Is flying? writer.WriteBit(false); // Bypass Checks? } writer.WriteBit(true); for (var i = 0; i < 7; i++) { writer.Write <uint>(0); } WritePhysics(writer); }
public void BitWriterUnalignedTest() { using (MemoryStream ms = new MemoryStream()) { BitWriter bw = new BitWriter() { Output = ms, CodeLength = 5, }; bw.WriteBits(5); bw.WriteBits(7); bw.WriteBits(3); bw.WriteBits(7); bw.FlushBits(); bw.FlushBytes(); byte[] bytes = ms.ToArray(); Assert.AreEqual(4, bytes.Length); Assert.AreEqual(0x03, bytes[0]); Assert.AreEqual(0xE5, bytes[1]); Assert.AreEqual(0x8C, bytes[2]); Assert.AreEqual(0x03, bytes[3]); } }
public void WriteBit() { var random = new Random(); var ms = new MemoryStream(); var writer = new BitWriter(ms); int n = 8 * 8; var bits = new bool[n]; for (int i = 0; i < n; ++i) { bits[i] = random.Next(-10, 10) > 0; writer.WriteBit(bits[i]); } Assert.AreEqual(n / 8, ms.Length); ms.Position = 0; var reader = new BitReader(ms); for (int i = 0; i < n; ++i) { Assert.AreEqual(bits[i], reader.ReadBit()); } }
/// <summary> /// Writes the property to the writer. /// </summary> /// <param name="objectToWrite">Object with the property to write.</param> /// <param name="writer">Bit writer to write to.</param> /// <param name="writtenProperties">Properties that were previously written.</param> public void Write(object objectToWrite, BitWriter writer, Dictionary <string, object> writtenProperties) { // Convert the object if it is a property. if (this.StructProperty != null) { objectToWrite = this.StructProperty.GetValue(objectToWrite); } // Write the properties. var subWrittenProperties = new Dictionary <string, object>(); foreach (var property in this.Properties) { property.Write(objectToWrite, writer, subWrittenProperties); } // Store the written string. if (writtenProperties != null && this.StructProperty != null) { writtenProperties[this.StructProperty.Name] = objectToWrite; } }
internal override void WriteSpecific(BitWriter writer, DwgObjectMap objectMap, int pointerOffset, DwgVersionId version) { writer.Write_T(Name); writer.Write_B(_64flag); writer.Write_BS(_xrefIndex); writer.Write_B(_isDependentOnXRef); writer.Write_T(Description); writer.Write_BD(PatternLength); writer.Write_RC((byte)_alignment); writer.Write_RC((byte)DashInfos.Count); foreach (var dashInfo in DashInfos) { dashInfo.Write(writer); } writer.Write_H(LineTypeControlHandle); foreach (var reactorHandle in _reactorHandles) { writer.Write_H(reactorHandle); } writer.Write_H(_xDictionaryObjectHandle); writer.Write_H(_nullHandle); }
public void Write1ByteOf0_WriteBit() { var fileName = $"{_basePath}Value0x00_bitWriter.txt"; DeleteFile(fileName); using (var bitWriter = new BitWriter(fileName)) { for (var i = 0; i < 8; i++) { bitWriter.WriteBit(0x00); } } using (var reader = new FileStream(fileName, FileMode.OpenOrCreate)) { Assert.AreEqual(1, reader.Length); var solution = (byte)reader.ReadByte(); Assert.AreEqual(0x00, solution); } }
public override void SerializePacket(BitWriter writer) { writer.Write((byte)LoginCode); foreach (string item in GatingStrings) { writer.WriteString(item); } writer.WriteString("", 33 * (8 - GatingStrings.Length)); writer.Write(Version); writer.WriteString(UserKey, wide: true); writer.WriteString(CharacterInstanceAddress); writer.WriteString(ChatInstanceAddress); writer.Write(CharacterInstancePort); writer.Write(ChatInstancePort); writer.WriteString(UnknownIp); writer.WriteString(LegoUUID, 37); writer.Write <uint>(0); writer.WriteString(Locale, 3); writer.Write((byte)(FirstLoginWithSubscription ? 1 : 0)); writer.Write((byte)(FreeToPlay ? 1 : 0)); writer.Write <ulong>(0); writer.Write(Error); writer.Write(StampCount); }
internal override void WriteSpecific(BitWriter writer, DwgObjectMap objectMap, int pointerOffset, DwgVersionId version) { writer.Write_T(Name); writer.Write_T(Description); writer.Write_BS(Flags); writer.Write_BS(FillColor.RawValue); writer.Write_BD(StartAngle); writer.Write_BD(EndAngle); writer.Write_RC(_lineStyleCount); for (int i = 0; i < _lineStyleCount; i++) { writer.Write_BD(_lineStyleOffsets[i]); writer.Write_BS(_lineStyleColors[i]); writer.Write_BS(_lineStyleLineTypeIndicies[i]); } writer.Write_H(_parentHandle); for (int i = 0; i < _reactorCount; i++) { writer.Write_H(_reactorHandles[i]); } writer.Write_H(_xDictionaryObjectHandle); }
public static byte[] Write(Attributes attributes) { using (BitWriter writer = new BitWriter()) { ItemStatCostTXT itemStatCost = Core.TXT.ItemStatCostTXT; writer.WriteUInt16(attributes.Header ?? (UInt16)0x6667); foreach (var entry in attributes.Stats) { var property = itemStatCost[entry.Key]; writer.WriteUInt16(property["ID"].ToUInt16(), 9); Int32 attribute = entry.Value; if (property["ValShift"].ToInt32() > 0) { attribute <<= property["ValShift"].ToInt32(); } writer.WriteInt32(attribute, property["CSvBits"].ToInt32()); } writer.WriteUInt16(0x1ff, 9); writer.Align(); return(writer.ToArray()); } }
public void GetBytes_Works_When_MoreThan64Bits() { /* There are 12 entries, * and we will Write them together in groups of 4. * In total, 96 bits, forcing the Writer to make 2 BinaryNumber * The bytes from GetBytes should match perfectly with these */ byte[] input = new byte[] { 12, 0, 157, 212, 255, 2, 42, 128, 188, 200, 10, 32 }; BitWriter writer = new BitWriter(); for (int i = 0; i < input.Length; i += 4) { writer.Write(BitConverter.ToUInt32(input, i)); } Assert.AreEqual(input, writer.GetBytes()); }
private void SaveDecBttn_Click(object sender, EventArgs e) { string outputName = _filePath.Name + ".bmp"; _bitwriter = new BitWriter(Path.Combine(_filePath.DirectoryName, outputName)); foreach (var item in _bmpHeader) { _bitwriter.WriteNBits(8, item); } for (int i = _imgLength - 1; i >= 0; i--) { for (int j = 0; j < _imgLength; j++) { _bitwriter.WriteNBits(8, _decodedImg[j, i]); } } //bwrite.WriteNBits(7, 1); _bitwriter.Dispose(); }
public static void WriteArrayAndDict(BitWriter writer, Array array = null, IDictionary <string, object> dict = null) { var arrayLength = (uint)(array?.Length ?? 0); WriteNumber(writer, (arrayLength << 1) | 0x01); if (dict != null) { foreach (var(key, value) in dict) { WriteText(writer, key); Write(writer, value); } } WriteText(writer, ""); if (array != null) { foreach (var value in array) { Write(writer, value); } } }
private static void WriteScaleFactors(BitWriter writer, CriHcaChannel channel) { int deltaBits = channel.ScaleFactorDeltaBits; var scales = channel.ScaleFactors; writer.Write(deltaBits, 3); if (deltaBits == 0) { return; } if (deltaBits == 6) { for (int i = 0; i < channel.CodedScaleFactorCount; i++) { writer.Write(scales[i], 6); } return; } writer.Write(scales[0], 6); int maxDelta = (1 << (deltaBits - 1)) - 1; int escapeValue = (1 << deltaBits) - 1; for (int i = 1; i < channel.CodedScaleFactorCount; i++) { int delta = scales[i] - scales[i - 1]; if (Math.Abs(delta) > maxDelta) { writer.Write(escapeValue, deltaBits); writer.Write(scales[i], 6); } else { writer.Write(maxDelta + delta, deltaBits); } } }
public void writebitsTest() { byte[] buf = new byte[0x10000]; for (int seed = 0; seed < 10; seed++) { BitWriter target = new BitWriter(buf, 0, buf.Length); var rnd = new Random(seed); int count = 0; do { int bits = rnd.Next(0, 64) + 1; ulong val = (1U << (bits - 1)); target.writebits(bits, val); count++; }while (target.Length < buf.Length - 32); target.flush(); ushort c1 = target.get_crc16(), c2; rnd = new Random(seed); unsafe { fixed(byte *ptr = buf) { BitReader reader = new BitReader(ptr, 0, buf.Length); for (int i = 0; i < count; i++) { int bits = rnd.Next(0, 64) + 1; ulong val = (1U << (bits - 1)); ulong val1 = reader.readbits64(bits); Assert.AreEqual(val, val1, string.Format("i = {0}, bits = {1}, seed = {2}, pos = {3}", i, bits, seed, reader.Position)); } reader.flush(); c2 = reader.get_crc16(); } } Assert.AreEqual(c1, c2, string.Format("seed = {0}", seed)); } }
public static void Write(BitWriter writer, object value) { switch (value) { case string str: writer.Write((byte)Amf3Type.String); WriteText(writer, str); break; case int integer: writer.Write((byte)Amf3Type.Integer); WriteNumber(writer, (uint)integer); break; case uint unsigned: writer.Write((byte)Amf3Type.Integer); WriteNumber(writer, unsigned); break; case bool boolean: writer.Write((byte)(boolean ? Amf3Type.True : Amf3Type.False)); break; case IDictionary <string, object> dict: writer.Write((byte)Amf3Type.Array); WriteDict(writer, dict); break; case Array array: writer.Write((byte)Amf3Type.Array); WriteArray(writer, array); break; case null: writer.Write((byte)Amf3Type.Undefined); break; } }
public async Task CalculateImpactAsync(GameObject target) { target ??= Target; await target.NetFavorAsync(); var distance = Vector3.Distance(Destination, target.Transform.Position); if (distance > RadiusCheck) { return; } var tree = await BehaviorTree.FromLotAsync(Lot); await using var stream = new MemoryStream(); var writer = new BitWriter(stream); tree.Serialize( Owner, writer, tree.SkillRoots.First().Key, Owner.GetComponent <SkillComponent>().ClaimSyncId(), target.Transform.Position, target ); Zone.BroadcastMessage(new DoClientProjectileImpact { Associate = Owner, Data = stream.ToArray(), Owner = Owner, ProjectileId = ClientObjectId, Target = target }); await tree.ExecuteAsync(); }
public async Task SaveAsync(string path) { var scene = LuzScene; var file = new LvlFile { LvlVersion = 0x26 }; if (Objects?.Count > 0) { file.LevelObjects = new LevelObjects(file.LvlVersion) { Templates = Objects.Select(o => o.Template).ToArray() }; } if (!string.IsNullOrWhiteSpace(SkyBox)) { var skyConfig = new LevelSkyConfig { Skybox = { [0] = SkyBox } }; file.LevelSkyConfig = skyConfig; } file.LevelInfo = new LevelInfo { RevisionNumber = Revision }; await using var stream = File.Create(Path.Combine(path, scene.FileName)); using var writer = new BitWriter(stream); file.Serialize(writer); }
public void Serialize(BitWriter writer) { for (var i = 0; i < 4; i++) { writer.Write(Header[i]); } writer.Write((uint)Mesh.Vertices.Length); writer.Write((uint)Mesh.Triangles.Length); writer.Write((uint)Flags); foreach (var vertex in Mesh.Vertices) { writer.Write(vertex); } if ((Flags & GeometryFlags.Normals) == GeometryFlags.Normals) { foreach (var normal in Mesh.Normals) { writer.Write(normal); } } if ((Flags & GeometryFlags.Uv) == GeometryFlags.Uv) { foreach (var vector2 in Mesh.Uv) { writer.Write(vector2); } } foreach (var triangle in Mesh.Triangles) { writer.Write((uint)triangle); } }
public override void Serialize(BitWriter writer) { writer.WriteBit(true); writer.Write <uint>(0x4000002); writer.Write <uint>(0x00); var hasPetInteraction = PetInteractionObject != null; writer.WriteBit(hasPetInteraction); if (hasPetInteraction) { writer.Write(PetInteractionObject); } var hasOwner = Owner != null; writer.WriteBit(hasOwner); if (hasOwner) { writer.Write(Owner); } writer.WriteBit(true); writer.Write(ModerationStatus); writer.Write((byte)GameObject.Name.Length); writer.WriteString(GameObject.Name, GameObject.Name.Length, true); if (hasOwner) { writer.Write((byte)Owner.Name.Length); writer.WriteString(Owner.Name, Owner.Name.Length, true); } else { writer.Write <byte>(0); } }
public override void Serialize(BitWriter writer) { writer.Write((uint)(8 + UnknownFloatArray0.Length * 4)); var skySectionPointer = new PointerToken(writer); var otherSectionPointer = new PointerToken(writer); foreach (var f in UnknownFloatArray0) { writer.Write(f); } writer.Write((uint)Identifiers.Length); foreach (var identifier in Identifiers) { identifier.Serialize(writer); } for (var i = 0; i < 3; i++) { writer.Write(UnknownFloatArray1[i]); } for (var i = 0; i < 3; i++) { writer.Write(UnknownFloatArray2[i]); } skySectionPointer.Dispose(); writer.Write(WriteSkySection()); otherSectionPointer.Dispose(); writer.Write(WriteOtherSection()); }
public void write(BitWriter outb) { outb.writeNBit(f_code[0][0], 4); outb.writeNBit(f_code[0][1], 4); outb.writeNBit(f_code[1][0], 4); outb.writeNBit(f_code[1][1], 4); outb.writeNBit(intra_dc_precision, 2); outb.writeNBit(picture_structure, 2); outb.write1Bit(top_field_first); outb.write1Bit(frame_pred_frame_dct); outb.write1Bit(concealment_motion_vectors); outb.write1Bit(q_scale_type); outb.write1Bit(intra_vlc_format); outb.write1Bit(alternate_scan); outb.write1Bit(repeat_first_field); outb.write1Bit(chroma_420_type); outb.write1Bit(progressive_frame); outb.write1Bit(compositeDisplay != null ? 1 : 0); if (compositeDisplay != null) { compositeDisplay.write(outb); } }
public void Serialize(BitWriter bw) { byte b = AxisToByte(Pitch); bw.Write(b != 0); if (b != 0) { bw.Write(b); } b = AxisToByte(Yaw); bw.Write(b != 0); if (b != 0) { bw.Write(b); } b = AxisToByte(Roll); bw.Write(b != 0); if (b != 0) { bw.Write(b); } }
private static void WriteGenericMessageHeader(this BitWriter writer, ushort messageType, bool isTargeted, uint targetNetworkId, ushort behaviourIndex, bool isPassthrough, uint?passthroughTarget, uint?passthroughOrigin) { writer.WriteUShort(messageType); writer.WriteBool(isTargeted); if (isTargeted) { writer.WriteUInt(targetNetworkId); writer.WriteUShort(behaviourIndex); } writer.WriteBool(isPassthrough); if (isPassthrough) { if (passthroughTarget != null) { writer.WriteUInt(passthroughTarget.Value); } if (passthroughOrigin != null) { writer.WriteUInt(passthroughOrigin.Value); } } writer.WriteAlignBits(); }
public static void WriteNiString(this BitWriter @this, string str, bool wide = false, bool small = false) { if (small) { @this.Write((byte)str.Length); } else { @this.Write((uint)str.Length); } foreach (var c in str) { if (wide) { @this.Write((ushort)c); } else { @this.Write((byte)c); } } }
void SendRoomNameResponse(NodeIndex clientIndex) { using (BitWriter writer = _network.GetPooledWriter()) { writer.Normal <byte>((byte)CustomMessageType.RoomNameResponse); _sb.Clear(); _sb.Append(_world.GetRoomName()); int length = _sb.Length; _sb.CopyTo(0, _charBuffer, 0, length); writer.ArrayPacked <char>(_charBuffer, length); string error; if (!_network.SendCustomClient(clientIndex, writer, false, out error)) { Log.Error($"Failed to send RoomNameResponse to client {clientIndex.GetClientIndex()}, error:\n{error}\n"); } else { Log.Info($"Sent room name: {_world.GetRoomName()} to client: {clientIndex.GetClientIndex()}"); } } }
/// <summary> /// Compresses and writes booleans to writer /// </summary> /// <param name="w"></param> /// <param name="values"></param> private void CompressBooleanTrack(BinaryWriter w, IList <object> values) { // Compressed Header w.Write((short)0x04); w.Write((short)0); w.Write((short)0x20); // default values offset w.Write((short)1); // bits per entry w.Write(0x21); // compressed data start w.Write(values.Count); // frame count w.Write(0); // all 0s for booleans w.Write(0); w.Write(0); w.Write(0); BitWriter bitWriter = new BitWriter(); foreach (bool b in values) { bitWriter.WriteBits(b ? 1 : 0, 1); } w.Write(bitWriter.GetBytes()); }
public void WriteRIFFHeader(Stream outputStream) { uint dataSize = (uint)Math.Ceiling(((double)TotalSamples * ((double)BitsPerSample / 8d) * (double)(NumberOfChannels))); var streamSize = dataSize + WAV_HEADER_SIZE; uint fileSize = dataSize + 36; BitWriter wr = new BitWriter(outputStream); wr.WriteBits(WAV_HDR_RIFF, 32); wr.WriteLE(fileSize); wr.WriteBits(WAV_HDR_WAVE, 32); wr.WriteBits(WAV_HDR_FMT, 32); wr.WriteLE(WAV_FORMATEX_SIZE); wr.WriteLE((ushort)AudioFormat); wr.WriteLE(NumberOfChannels); wr.WriteLE(SampleRate); wr.WriteLE((uint)(SampleRate * BitsPerSample * NumberOfChannels / 8)); //avg bytes wr.WriteLE((ushort)(BitsPerSample * NumberOfChannels / 8)); wr.WriteLE(BitsPerSample); wr.WriteBits(WAV_HDR_DATA, 32); wr.WriteLE(dataSize); }
/// <summary> /// Close the stream. /// </summary> /// <remarks> /// <para> /// This may or may not close the underlying stream. Check the /// constructors that accept a bool value. /// </para> /// </remarks> public void Close() { if (this.pendingException != null) { this.handlingException = true; var pe = this.pendingException; this.pendingException = null; throw pe; } if (this.handlingException) return; if (output == null) return; Stream o = this.output; try { FlushOutput(true); } finally { this.output = null; this.bw = null; } if (!leaveOpen) o.Dispose(); }
/// <summary> /// Constructs a new <c>ParallelBZip2OutputStream</c> with specified blocksize, /// and explicitly specifies whether to leave the wrapped stream open. /// </summary> /// /// <param name = "output">the destination stream.</param> /// <param name = "blockSize"> /// The blockSize in units of 100000 bytes. /// The valid range is 1..9. /// </param> /// <param name = "leaveOpen"> /// whether to leave the captive stream open upon closing this stream. /// </param> public ParallelBZip2OutputStream(Stream output, int blockSize, bool leaveOpen) { if (blockSize < BZip2.MinBlockSize || blockSize > BZip2.MaxBlockSize) { var msg = String.Format("blockSize={0} is out of range; must be between {1} and {2}", blockSize, BZip2.MinBlockSize, BZip2.MaxBlockSize); throw new ArgumentException(msg, "blockSize"); } this.output = output; if (!this.output.CanWrite) throw new ArgumentException("The stream is not writable.", "output"); this.bw = new BitWriter(this.output); this.blockSize100k = blockSize; this.leaveOpen = leaveOpen; this.combinedCRC = 0; this.MaxWorkers = 16; // default EmitHeader(); }
public WorkItem(int ix, int blockSize) { // compressed data gets written to a MemoryStream this.ms = new MemoryStream(); this.bw = new BitWriter(ms); this.Compressor = new BZip2Compressor(bw, blockSize); this.index = ix; }
public byte[] BuildPacket() { using (MemoryStream ms = new MemoryStream()) { using (BitWriter writer = new BitWriter(ms)) { //Id writer.WriteByte(this.Id[0]); writer.WriteByte(this.Id[1]); // flags writer.WriteByte(0x80); writer.WriteByte(0x00); // questions writer.WriteInt16(IPAddress.HostToNetworkOrder(QDCOUNT)); // answers RRs writer.WriteInt16(IPAddress.HostToNetworkOrder((short)AnswerList.Count)); // autority RRs writer.WriteInt16(IPAddress.HostToNetworkOrder(NSCOUNT)); // additional RRs writer.WriteInt16(IPAddress.HostToNetworkOrder(ARCOUNT)); //QUERY if (this.Query != null) { // query name writer.WriteString(Query.Name); // type writer.WriteInt16(IPAddress.HostToNetworkOrder((Query.Type.HasValue ? (short)Query.Type.Value : (short)0))); //class writer.WriteInt16(IPAddress.HostToNetworkOrder((Query.Class.HasValue ? (short)Query.Class.Value : (short)0))); } foreach (var item in AnswerList) { // answer name writer.WriteString(item.Name); // type answer writer.WriteInt16(IPAddress.HostToNetworkOrder((item.Type.HasValue ? (short)item.Type.Value : (short)0))); // class answer writer.WriteInt16(IPAddress.HostToNetworkOrder((item.Class.HasValue ? (short)item.Class.Value : (short)0))); // time to live writer.WriteByte(0x00); writer.WriteByte(0x00); writer.WriteByte(0x00); writer.WriteByte(0x1e); // longitud RData writer.WriteInt16(IPAddress.HostToNetworkOrder((short)item.RData.Length)); //RDATA for (int index = 0; index < item.RData.Length; index++) writer.WriteByte(item.RData[index]); } } return ms.ToArray(); } }
public BZip2Compressor(BitWriter writer, int blockSize) { this.blockSize100k = blockSize; this.bw = writer; // 20 provides a margin of slop (not to say "Safety"). The maximum // size of an encoded run in the output block is 5 bytes, so really, 5 // bytes ought to do, but this is a margin of slop found in the // original bzip code. Not sure if important for decoding // (decompressing). So we'll leave the slop. this.outBlockFillThreshold = (blockSize * BZip2.BlockSizeMultiple) - 20; this.cstate = new CompressionState(blockSize); Reset(); }
/// <summary> /// BZip2Compressor writes its compressed data out via a BitWriter. This /// is necessary because BZip2 does byte shredding. /// </summary> public BZip2Compressor(BitWriter writer) : this(writer, BZip2.MaxBlockSize) { }
internal void Write(BitWriter writer) { writer.WriteBits((ulong)nodetype, 2); Helpers.WriteNumber(writer, stackid); if(nodetype == NodeType.AssemblyLoad) { Helpers.WriteNumber(writer, nameId); } Helpers.WriteNumber(writer, 1 + kidOffset); Helpers.WriteNumber(writer, 1 + prevOffset); Helpers.WriteNumber(writer, nodeOffset); data.Write(writer); }