/// <summary> /// Encodes the specified image data to png. /// </summary> /// <param name="pixels">The pixel data indexed as [x,y] (bottom line first).</param> /// <returns>The png image data.</returns> public byte[] Encode(OxyColor[,] pixels) { int width = pixels.GetLength(0); int height = pixels.GetLength(1); var bytes = new byte[(width * height * 4) + height]; int k = 0; for (int y = 0; y < height; y++) { bytes[k++] = 0; // Filter for (int x = 0; x < width; x++) { bytes[k++] = pixels[x, y].R; bytes[k++] = pixels[x, y].G; bytes[k++] = pixels[x, y].B; bytes[k++] = pixels[x, y].A; } } var w = new MemoryWriter(); w.Write((byte)0x89); w.Write("PNG\r\n\x1a\n".ToCharArray()); WriteChunk(w, "IHDR", CreateHeaderData(width, height)); WriteChunk(w, "pHYs", CreatePhysicalDimensionsData(this.options.DpiX, this.options.DpiY)); WriteChunk(w, "IDAT", CreateUncompressedBlocks(bytes)); WriteChunk(w, "IEND", new byte[0]); return(w.ToArray()); }
/// <summary> /// Encodes the specified image data to png. /// </summary> /// <param name="pixels"> /// The pixel data (bottom line first). /// </param> /// <param name="dpi"> /// The image resolution in dots per inch. /// </param> /// <returns> /// The png image data. /// </returns> public static byte[] Encode(OxyColor[,] pixels, int dpi = 96) { int height = pixels.GetLength(0); int width = pixels.GetLength(1); var bytes = new byte[(width * height * 4) + height]; int k = 0; for (int i = height - 1; i >= 0; i--) { bytes[k++] = 0; // Filter for (int j = 0; j < width; j++) { bytes[k++] = pixels[i, j].R; bytes[k++] = pixels[i, j].G; bytes[k++] = pixels[i, j].B; bytes[k++] = pixels[i, j].A; } } var w = new MemoryWriter(); w.Write((byte)0x89); w.Write("PNG\r\n\x1a\n".ToCharArray()); WriteChunk(w, "IHDR", CreateHeaderData(width, height)); WriteChunk(w, "pHYs", CreatePhysicalDimensionsData(dpi, dpi)); WriteChunk(w, "IDAT", CreateUncompressedBlocks(bytes)); WriteChunk(w, "IEND", new byte[0]); return(w.ToArray()); }
public virtual SmartBuffer EncryptUdp(ReadOnlyMemory <byte> plain) { if (plain.IsEmpty) { _logger?.LogInformation($"ShadowosocksAeadCipher EncryptUdp plain.IsEmpty."); return(null); } var cipherPacket = SmartBuffer.Rent(1500 + LEN_TAG + _keySize_SaltSize.Item2); var cipherPacketStream = new MemoryWriter(cipherPacket.Memory); byte[] salt = new byte[_keySize_SaltSize.Item2], key = new byte[_keySize_SaltSize.Item1]; RandomNumberGenerator.Fill(salt); DeriveSubKey(_masterKeyBytes, salt, SubkeyInfoBytes, key, key.Length); //[encrypted payload][tag] using (var payload = this.EncryptChunk(plain, key.AsSpan(), _nonceZero.AsSpan())) { cipherPacketStream.Write(salt.AsMemory()); cipherPacketStream.Write(payload.SignificantMemory); cipherPacket.SignificantLength = cipherPacketStream.Position; //[salt][encrypted payload][tag] } return(cipherPacket); }
public virtual SmartBuffer EncryptTcp(ReadOnlyMemory <byte> plain) { if (plain.IsEmpty) { _logger?.LogInformation($"ShadowosocksAeadCipher EncryptTcp plain.IsEmpty."); return(null); } int cipherLen = CalcTcpCipherStreamLength(plain.Length); SmartBuffer cihperBuffer = SmartBuffer.Rent(cipherLen); var cipherStream = new MemoryWriter(cihperBuffer.Memory); if (!_tcpCtx加密.HaveSalt()) { _tcpCtx加密.NewSalt(); cipherStream.Write(_tcpCtx加密.Salt.AsMemory()); _logger?.LogInformation($"ShadowosocksAeadCipher EncryptTcp new salt wrote. { _tcpCtx加密.Salt.ToHexString()}"); DeriveSubKey(_masterKeyBytes, _tcpCtx加密.Salt, SubkeyInfoBytes, _tcpCtx加密.Key, _tcpCtx加密.Key.Length); _logger?.LogInformation($"ShadowosocksAeadCipher EncryptTcp new subkey {_tcpCtx加密.Key.ToHexString()}."); } int remain = plain.Length; int chunkLen = 0, encrypted = 0; do { chunkLen = Math.Min(remain, LEN_TCP_MAX_CHUNK); //payload length. { byte[] payloadLenBytes = BitConverter.GetBytes((ushort)(System.Net.IPAddress.HostToNetworkOrder((short)chunkLen))); _logger?.LogInformation($"ShadowosocksAeadCipher EncryptTcp chunklen={chunkLen}, payloadLenBytes={payloadLenBytes.ToHexString()}."); using (var payloadLenC = this.EncryptChunk(payloadLenBytes, _tcpCtx加密.Key, _tcpCtx加密.Nonce)) { //[encrypted payload length][length tag] cipherStream.Write(payloadLenC.Memory.Slice(0, payloadLenC.SignificantLength)); _tcpCtx加密.IncreaseNonce(); } } //payload. { var payload = plain.Slice(plain.Length - remain, chunkLen); using (var payloadC = this.EncryptChunk(payload, _tcpCtx加密.Key, _tcpCtx加密.Nonce)) { //[encrypted payload][payload tag] cipherStream.Write(payloadC.Memory.Slice(0, payloadC.SignificantLength)); _tcpCtx加密.IncreaseNonce(); } } //------------------------------- encrypted += chunkLen; _logger?.LogInformation($"ShadowosocksAeadCipher EncryptTcp encrypted {encrypted} bytes."); remain -= chunkLen; } while (remain > 0); cihperBuffer.SignificantLength = cipherStream.Position; return(cihperBuffer); }
/// <summary> /// Creates the header data. /// </summary> /// <param name="width"> /// The width. /// </param> /// <param name="height"> /// The height. /// </param> /// <returns> /// The header. /// </returns> private static byte[] CreateHeaderData(int width, int height) { // http://www.w3.org/TR/PNG-Chunks.html var w = new MemoryWriter(); WriteBigEndian(w, width); WriteBigEndian(w, height); w.Write((byte)8); // bit depth w.Write((byte)6); // color type RGBA w.Write((byte)0); // compression method w.Write((byte)0); // filter method w.Write((byte)0); // interlace method return(w.ToArray()); }
/// <summary> /// Creates the uncompressed blocks. /// </summary> /// <param name="bytes"> /// The data. /// </param> /// <returns> /// The output data. /// </returns> private static byte[] CreateUncompressedBlocks(byte[] bytes) { // http://www.w3.org/TR/PNG-Compression.html const int MaxDeflate = 0xFFFF; var w = new MemoryWriter(); const uint CompressionMethod = 8; const uint Check = (31 - ((CompressionMethod << 8) % 31)) % 31; w.Write((byte)CompressionMethod); w.Write((byte)Check); for (int i = 0; i < bytes.Length; i += MaxDeflate) { var n = (ushort)Math.Min(bytes.Length - i, MaxDeflate); var last = (byte)(i + n < bytes.Length ? 0 : 1); w.Write(last); w.Write((byte)(n & 0xFF)); w.Write((byte)((n >> 8) & 0xFF)); var n2 = ~n; w.Write((byte)(n2 & 0xFF)); w.Write((byte)((n2 >> 8) & 0xFF)); w.Write(bytes, i, n); } WriteBigEndian(w, Adler32(bytes)); return(w.ToArray()); }
private void Form1_Load(object sender, EventArgs e) { double[] values = Clin(cl, 256, 4096); List <ChartPoint> chartPoints = new List <ChartPoint>(); for (int k = 0; k < values.Length; k++) { ChartPoint point = new ChartPoint(k, values[k]); chartPoints.Add(point); } Chart chart = new Chart() { SeriesCollection = new List <ChartSeries>() { new ChartSeries() { Name = "Graphic", ColorDescriptor = new ColorDescriptor(255, 0, 0), Type = HoloCommon.Enumeration.Charting.ChartSeriesType.Linear, Points = chartPoints } } }; MemoryWriter.Write <Chart>(chart, new ChartSerialization()); ProcessManager.RunProcess(@"d:\Projects\HoloApplication\Modules\ChartApp\ChartApp\bin\Release\ChartApp.exe", null, false); }
static void Main(string[] args) { WriteableBitmap image = MemoryReader.Read <WriteableBitmap>(new WriteableBitmapSerialization()); image = image.Rotate(90); MemoryWriter.Write <WriteableBitmap>(image, new WriteableBitmapSerialization()); }
static void Main(string[] args) { if (args.Length != 1) { return; } double phaseShift = double.Parse(args[0], CultureInfo.InvariantCulture); int width = 4096; int height = 1024; double percentNoise = 0; int fringeCount = 10; double minIntensity = 35; InterferogramInfo interferogramInfo = new InterferogramInfo(width, height, percentNoise, minIntensity); LinearFringeInterferogramCreator interferogramCreator = new LinearFringeInterferogramCreator(interferogramInfo, fringeCount); RealMatrix interferogramMatrix = interferogramCreator.CreateInterferogram(phaseShift); WriteableBitmap writeableBitmap = WriteableBitmapCreator.CreateGrayScaleWriteableBitmapFromMatrix(interferogramMatrix, OS.IntegerSystemDpiX, OS.IntegerSystemDpiY); MemoryWriter.Write <WriteableBitmap>(writeableBitmap, new WriteableBitmapSerialization()); SynchronizationManager.SetSignal(HoloCommon.Synchronization.Events.Image.IMAGE_CREATED); }
public static int Cast(Processor proc, ProgramReader reader) { TypeFlag returnType = (TypeFlag)reader.NextInt(); uint addr = reader.NextPtr(); object v1 = BytesToNative(proc.Registers.TypeRegisters[0], proc.Registers.OperationRegisters[0]); byte[] b = null; switch (returnType) { case TypeFlag.Char: v1 = Conversions.ToChar(v1); break; case TypeFlag.Int: v1 = Conversions.ToInteger(v1); break; case TypeFlag.Float: v1 = Conversions.ToSingle(v1); break; } b = Convert(v1, returnType); MemoryWriter w = MemoryWriter.GetWriter(2, proc, addr); w.Write(b); return(reader.Elapsed()); }
private void btnBuildTable_Click(object sender, EventArgs e) { List <Point2D> points = ModularArithmeticHelper.BuildTable(M1, M2, MAX_RANGE_VALUE); List <ChartPoint> chartPoints = new List <ChartPoint>(); for (int k = 0; k < points.Count; k++) { Point2D p = points[k]; ChartPoint p1 = new ChartPoint(p.X, p.Y); chartPoints.Add(p1); } Chart chart1 = new Chart() { SeriesCollection = new List <ChartSeries>() { new ChartSeries() { Name = "Graph diagonals", Type = HoloCommon.Enumeration.Charting.ChartSeriesType.Linear, ColorDescriptor = new ColorDescriptor(255, 0, 0), Points = chartPoints } } }; MemoryWriter.Write <Chart>(chart1, new ChartSerialization()); ProcessManager.RunProcess(@"D:\Projects\HoloApplication\Modules\ChartApp\ChartApp\bin\Release\ChartApp.exe", null, false, false); Thread.Sleep(2000); }
public void WriteToFileTest() { var filePath = $@"{_logFolderPath}\LogTest{DateTime.Now.AddMinutes(1):yyyyMMdd HHmmss fff}.log"; var config = new Mock <IConfiguration>(); config.Setup(c => c.GetLogFileName()).Returns(filePath); config.Setup(c => c.GetLogFolderPath()).Returns(_logFolderPath); var fileWriter = new FileWriter(config.Object); var memoryWriter = new MemoryWriter(); var logLine = new LogLine { Timestamp = DateTime.Now, Text = "Test" }; fileWriter.Write(logLine); fileWriter.Close(); _filesCreatedPaths.Add(filePath); memoryWriter.Write(logLine); //try to find the file var fileExist = File.Exists(filePath); Assert.IsTrue(fileExist); //try to read from the file var file = new StreamReader(filePath); var text = file.ReadToEnd(); file.Close(); Assert.AreEqual(memoryWriter.MemoryLog, text); }
public void WritingLogsFromDifferentDaysEndUpInDifferentFilesTest() { var filePathToday = $@"{_logFolderPath}\LogTest{DateTime.Now:yyyyMMdd HHmmss fff}.log"; var filePathTomorrow = $@"{_logFolderPath}\LogTest{DateTime.Now.AddDays(1):yyyyMMdd HHmmss fff}.log"; var configMock = new Mock <IConfiguration>(); //setup configuration to return a different file name on the second call configMock.SetupSequence(x => x.GetLogFileName()) .Returns(filePathToday) .Returns(filePathTomorrow); var fileWriter = new FileWriter(configMock.Object); var memoryWriter1 = new MemoryWriter(); var memoryWriter2 = new MemoryWriter(); //setup two different logLines, one with a timestamp from today and the other with a timestamp from tomorrow var logLine1 = new LogLine { Timestamp = DateTime.Now, Text = "Test" }; var logLine2 = new LogLine { Timestamp = DateTime.Now.AddDays(1), Text = "Test2" }; fileWriter.Write(logLine1); memoryWriter1.Write(logLine1); fileWriter.Write(logLine2); memoryWriter2.Write(logLine2); fileWriter.Close(); _filesCreatedPaths.Add(filePathToday); _filesCreatedPaths.Add(filePathTomorrow); //try to find the first file var fileExist = File.Exists(filePathToday); Assert.IsTrue(fileExist); //try to find the second file fileExist = File.Exists(filePathTomorrow); Assert.IsTrue(fileExist); //try to read from the first file var file1 = new StreamReader(filePathToday); var textFile1 = file1.ReadToEnd(); file1.Close(); Assert.AreEqual(memoryWriter1.MemoryLog, textFile1); //try to read from the second file var file2 = new StreamReader(filePathTomorrow); var textFile2 = file2.ReadToEnd(); file2.Close(); Assert.AreEqual(memoryWriter2.MemoryLog, textFile2); }
// Thanks to nlgzrgn for helping with this part!))) private static byte[] CPI_Part3(Database.Underground2 db) { int part3size = db.SlotTypes.Part3.Data.Length; var carlist = new List <string>(); // Precalculate size of part3 foreach (var car in db.CarTypeInfos.Collections) { if (car.Deletable && car.UsageType == eUsageType.Racer) { carlist.Add(car.CollectionName); } } part3size += carlist.Count * 0x158; int padding = 0x10 - ((part3size + 8) % 0x10); if (padding != 0x10) { part3size += padding; } // Use MemoryWriter instead of BinaryWriter so we can return an array for later processes var mw = new MemoryWriter(part3size); mw.Write(db.SlotTypes.Part3.Data); const uint key1 = 0x10C98090; // ??? const uint key2 = 0x0D4B85C7; // HOODUNDER // Write all info foreach (var name in carlist) { for (int a1 = 0; a1 < 0x2B; ++a1) { mw.Write((a1 > 34 && a1 < 40) ? key2 : key1); mw.Write(Bin.Hash(name + UsageType.SpecPartNames[a1])); } } // Fix length in the header mw.Position = 4; mw.Write(mw.Length - 8); db.SlotTypes.Part0.SetRecordNumber((mw.Length - 8) / 8); return(mw.Data); }
static void WriteChart() { Chart chart = new Chart(); ChartSeries chartSeries1 = new ChartSeries() { Name = "Sin", Type = ChartSeriesType.Linear, ColorDescriptor = new ColorDescriptor(255, 0, 0), Points = new List <ChartPoint>() }; ChartSeries chartSeries2 = new ChartSeries() { Name = "Cos", Type = ChartSeriesType.Linear, ColorDescriptor = new ColorDescriptor(0, 255, 0), Points = new List <ChartPoint>() }; ChartSeries chartSeries3 = new ChartSeries() { Name = "scatter", Type = ChartSeriesType.Bubble, ColorDescriptor = new ColorDescriptor(0, 0, 255), Points = new List <ChartPoint>() }; Random rnd = new Random(); int count = 100000; for (double x = 0; x < count; x += 0.1) { ChartPoint point1 = new ChartPoint(x, Math.Sin(x)); chartSeries1.Points.Add(point1); ChartPoint point2 = new ChartPoint(x, Math.Cos(x)); chartSeries2.Points.Add(point2); ChartPoint point3 = new ChartPoint(x, x * rnd.NextDouble()); chartSeries3.Points.Add(point3); } chart.SeriesCollection = new List <ChartSeries>() { //chartSeries1, //chartSeries2, chartSeries3 }; ChartSerialization cs = new ChartSerialization(); MemoryWriter.Write <Chart>(chart, cs); }
/// <summary> /// Creates the physical dimensions data. /// </summary> /// <param name="dpix"> /// The horizontal resolution. /// </param> /// <param name="dpiy"> /// The vertical resolution. /// </param> /// <returns> /// The data. /// </returns> private static byte[] CreatePhysicalDimensionsData(int dpix, int dpiy) { var ppux = (int)(dpix / 0.0254); var ppuy = (int)(dpiy / 0.0254); var w = new MemoryWriter(); WriteBigEndian(w, ppux); WriteBigEndian(w, ppuy); w.Write((byte)1); // Unit: metre return(w.ToArray()); }
public void TestReadWrite() { int len = 16; byte[] buff = new byte[len]; MemoryWriter ms = new MemoryWriter(buff); Assert.IsTrue(ms.Length == len); Assert.IsTrue(0 == ms.Position); byte[] a2 = { 0x12, 0x34, 0x56, 0xab }; ms.Write(a2.AsMemory()); Assert.IsTrue(a2.Length == ms.Position); Assert.IsTrue(ms.Memory.Slice(0, a2.Length).Span.SequenceEqual(a2)); byte[] a3 = { 0xcd, 0xef }; ms.Write(a3.AsSpan()); byte[] a = { 0x12, 0x34, 0x56, 0xab, 0xcd, 0xef }; Assert.IsTrue(ms.Memory.Slice(0, ms.Position).Span.SequenceEqual(a)); Assert.IsTrue(a2.Length + a3.Length == ms.Position); }
public static int Set(Processor proc, ProgramReader reader) { int sourceSize = reader.NextInt(); byte[] source = reader.NextArray(sourceSize); uint dest = reader.NextPtr(); MemoryReader r = MemoryReader.GetReader(0, proc, source, sourceSize); MemoryWriter w = MemoryWriter.GetWriter(1, proc, dest); w.Write(r.Data); return(reader.Elapsed()); }
static void Main(string[] args) { Console.WriteLine("Enter number 1:"); string str1 = Console.ReadLine(); Console.WriteLine("Enter number 2:"); string str2 = Console.ReadLine(); double num1 = double.Parse(str1); double num2 = double.Parse(str2); double res = num1 + num2; MemoryWriter.Write(res); }
public void GeneralSerialization() { var writer = new MemoryWriter(); writer.Write(true); writer.Write(123); writer.Write(-0.25f); writer.Write('c'); var guid = Guid.NewGuid(); writer.Write(guid); writer.Write("Hello"); writer.Write(new Vector2(0.25f, -0.3f)); writer.Write(new Vector3(0.5f, -0.6f, 0.25f)); writer.Write(new Vector4(0.75f, -0.9f, -0.4f, 0.333f)); writer.Write(new Quaternion(0.75f, -0.9f, -0.4f, 0.333f)); var reader = new MemoryReader(writer.GetBuffer(), writer.Length); Assert.True(reader.ReadBoolean()); Assert.AreEqual(123, reader.ReadInt32()); Assert.AreEqual(-0.25f, reader.ReadSingle()); Assert.AreEqual('c', reader.ReadChar()); Assert.AreEqual(guid, reader.ReadGuid()); Assert.AreEqual("Hello", reader.ReadString()); Assert.AreEqual(new Vector2(0.25f, -0.3f), reader.ReadVector2()); Assert.AreEqual(new Vector3(0.5f, -0.6f, 0.25f), reader.ReadVector3()); Assert.AreEqual(new Vector4(0.75f, -0.9f, -0.4f, 0.333f), reader.ReadVector4()); Assert.AreEqual(new Quaternion(0.75f, -0.9f, -0.4f, 0.333f), reader.ReadQuaternion()); }
private void SDK_ImageDownloaded(Bitmap bitmap, ImageType imageType) { Bitmap newBitmap = new Bitmap(bitmap); MemoryWriter.Write(newBitmap, new ImageSerialization()); SynchronizationManager.SetSignal(HoloCommon.Synchronization.Events.Camera.PICTURE_TAKEN); if (PictureTaken != null) { short number = 0; if (seriesType == TakePhotoSeriesTypeEnum.ImageSeries) { number = currentImageNumber; } if (seriesType == TakePhotoSeriesTypeEnum.PhaseShifts) { number = currentPhaseShiftNumber; } if (!is256Frames) { PictureTakenEventArgs eventArgs = new PictureTakenEventArgs() { Image = bitmap, StartImageNumber = startImageNumber, Number = number, GroupNumber = groupNumber, PhaseShiftValue = Convert.ToInt16(currentPhaseShiftValue), ColorMode = colorMode }; PictureTaken(eventArgs); } else { //Save bitmap string fileName = string.Format("{0}.jpg", currentImageNumber.ToString()); string filePath = Path.Combine(frames256Directory, fileName); Bitmap image = new Bitmap(bitmap); image.Save(filePath); } } TryTakeNextPhoto(); }
public void FillFirstBuffer() { // Write 4 blocks to the stream and then verify they can all be read for (int i = 0; i < 4; i++) { Initialise(buffer, (byte)(i + 1)); level1.Write(singleFile, Piece.BlockSize * i, buffer, 0, buffer.Length); } // Read them all back out and verify them for (int i = 0; i < 4; i++) { level1.Read(singleFile, Piece.BlockSize * i, buffer, 0, Piece.BlockSize); Verify(buffer, (byte)(i + 1)); } }
private void Form1_Shown(object sender, EventArgs e) { int width = 4096; int height = 2048; double percentNoise = 0; int fringeCount = 20; double minIntensity = 35; InterferogramInfo interferogramInfo = new InterferogramInfo(width, height, percentNoise, minIntensity); LinearFringeInterferogramCreator interferogramCreator = new LinearFringeInterferogramCreator(interferogramInfo, fringeCount); double phaseShift = 0; RealMatrix interferogramMatrix = interferogramCreator.CreateInterferogram(phaseShift); WriteableBitmap writeableBitmap = WriteableBitmapCreator.CreateGrayScaleWriteableBitmapFromMatrix(interferogramMatrix, OS.IntegerSystemDpiX, OS.IntegerSystemDpiY); MemoryWriter.Write <WriteableBitmap>(writeableBitmap, new WriteableBitmapSerialization()); //ProcessManager.RunProcess(@"D:\Projects\HoloApplication\Modules\ImageViewer\ImageViewer\bin\Release\ImageViewer.exe", null, false); SynchronizationManager.SetSignal(HoloCommon.Synchronization.Events.Image.IMAGE_CREATED); }
private void mainImage_MouseDown(object sender, MouseButtonEventArgs e) { if (e.ClickCount == 2) { Image imageControl = sender as Image; Point point = e.GetPosition(imageControl); int row = (int)point.Y; WriteableBitmap mainBitmap = this.mainViewModel.MainImageSource as WriteableBitmap; double[] yValues = GetRowGrayScaleValues(mainBitmap, row); Chart chart = new Chart() { SeriesCollection = new List <ChartSeries>() }; ChartSeries series = new ChartSeries() { Name = "Row " + row.ToString(), Type = ChartSeriesType.Linear, ColorDescriptor = new ColorDescriptor(255, 0, 0), Points = new List <ChartPoint>() }; for (int x = 0; x < yValues.Length; x++) { ChartPoint chartPoint = new ChartPoint(x, yValues[x]); series.Points.Add(chartPoint); } chart.SeriesCollection.Add(series); MemoryWriter.Write <Chart>(chart, new ChartSerialization()); ProcessManager.RunProcess(CHART_APP_PATH, null, false); } }
/// <summary> /// Creates the header data. /// </summary> /// <param name="width"> /// The width. /// </param> /// <param name="height"> /// The height. /// </param> /// <returns> /// The header. /// </returns> private static byte[] CreateHeaderData(int width, int height) { // http://www.w3.org/TR/PNG-Chunks.html var w = new MemoryWriter(); WriteBigEndian(w, width); WriteBigEndian(w, height); w.Write((byte)8); // bit depth w.Write((byte)6); // color type RGBA w.Write((byte)0); // compression method w.Write((byte)0); // filter method w.Write((byte)0); // interlace method return w.ToArray(); }
/// <summary> /// Creates the physical dimensions data. /// </summary> /// <param name="dpix"> /// The horizontal resolution. /// </param> /// <param name="dpiy"> /// The vertical resolution. /// </param> /// <returns> /// The data. /// </returns> private static byte[] CreatePhysicalDimensionsData(int dpix, int dpiy) { var ppux = (int)(dpix / 0.0254); var ppuy = (int)(dpiy / 0.0254); var w = new MemoryWriter(); WriteBigEndian(w, ppux); WriteBigEndian(w, ppuy); w.Write((byte)1); // Unit: metre return w.ToArray(); }
/// <summary> /// Creates the uncompressed blocks. /// </summary> /// <param name="bytes"> /// The data. /// </param> /// <returns> /// The output data. /// </returns> private static byte[] CreateUncompressedBlocks(byte[] bytes) { // http://www.w3.org/TR/PNG-Compression.html const int MaxDeflate = 0xFFFF; var w = new MemoryWriter(); const uint CompressionMethod = 8; const uint Check = (31 - ((CompressionMethod << 8) % 31)) % 31; w.Write((byte)CompressionMethod); w.Write((byte)Check); for (int i = 0; i < bytes.Length; i += MaxDeflate) { var n = (ushort)Math.Min(bytes.Length - i, MaxDeflate); var last = (byte)(i + n < bytes.Length ? 0 : 1); w.Write(last); w.Write((byte)(n & 0xFF)); w.Write((byte)((n >> 8) & 0xFF)); var n2 = ~n; w.Write((byte)(n2 & 0xFF)); w.Write((byte)((n2 >> 8) & 0xFF)); w.Write(bytes, i, n); } WriteBigEndian(w, Adler32(bytes)); return w.ToArray(); }
public static unsafe void Assemble(BinaryWriter bw, Database.Underground2 db) { // Initialize MemoryWriter for string block to its maximum size var mw = new MemoryWriter(0xFFFF); mw.Write((byte)0); // write null-termination mw.WriteNullTerminated(Process.Watermark); // Get arrays of all blocks var GCareerRacesBlock = WriteGCareerRaces(mw, db); var WorldShopBlock = WriteWorldShops(mw, db); var GCareerBrandsBlock = WriteGCareerBrands(mw, db); var PartPerformancesBlock = WritePartPerformances(db); var GShowcasesBlock = WriteGShowcases(mw, db); var SMSMessagesBlock = WriteSMSMessages(mw, db); var SponsorsBlock = WriteSponsors(mw, db); var GCareerStagesBlock = WriteGCareerStages(db); var PerfSliderTuningsBlock = WritePerfSliderTunings(db); var WorldChallengesBlock = WriteWorldChallenges(mw, db); var PartUnlockablesBlock = WritePartUnlockables(db); var BankTriggersBlock = WriteBankTriggers(db); var GCarUnlocksBlock = WriteGCarUnlocks(db); // Compress to the position mw.Position += 4 - (mw.Position % 4); mw.CompressToPosition(); // Pre-calculate size var size = 8 + mw.Length; size += GCareerRacesBlock.Length; size += WorldShopBlock.Length; size += GCareerBrandsBlock.Length; size += PartPerformancesBlock.Length; size += GShowcasesBlock.Length; size += SMSMessagesBlock.Length; size += SponsorsBlock.Length; size += GCareerStagesBlock.Length; size += PerfSliderTuningsBlock.Length; size += WorldChallengesBlock.Length; size += PartUnlockablesBlock.Length; size += BankTriggersBlock.Length; size += GCarUnlocksBlock.Length; // Pre-calculate padding var padding = Resolve.GetPaddingArray(size + 0x50, 0x80); size += padding.Length; // Finally, write entire Career Block bw.Write(CareerInfo.MAINID); bw.Write(size); bw.Write(CareerInfo.STRING_BLOCK); bw.Write(mw.Length); bw.Write(mw.Data); bw.Write(GCareerRacesBlock); bw.Write(WorldShopBlock); bw.Write(GCareerBrandsBlock); bw.Write(PartPerformancesBlock); bw.Write(GShowcasesBlock); bw.Write(SMSMessagesBlock); bw.Write(SponsorsBlock); bw.Write(GCareerStagesBlock); bw.Write(PerfSliderTuningsBlock); bw.Write(WorldChallengesBlock); bw.Write(PartUnlockablesBlock); bw.Write(BankTriggersBlock); bw.Write(GCarUnlocksBlock); bw.Write(padding); }
// Thanks to nlgzrgn for helping with this part!))) private static byte[] CPI_Part2(Database.Underground2 db) { int part2size = db.SlotTypes.Part2.Data.Length; int part3entries = (db.SlotTypes.Part3.Data.Length - 8) / 8; int numaddons = 0; // Precalculate size of part2 foreach (var car in db.CarTypeInfos.Collections) { if (car.Deletable && car.UsageType == eUsageType.Racer) { part2size += 0x11E; ++numaddons; } } int padding = 0x10 - ((part2size + 4) % 0x10); if (padding != 0x10) { part2size += padding; } // Use MemoryWriter instead of BinaryWriter so we can return an array for later processes var mw = new MemoryWriter(part2size); mw.Write(db.SlotTypes.Part2.Data); // Write all info for (int a1 = 0; a1 < numaddons; ++a1) { // CARNAME_CV - KIT00_BODY mw.Write((short)2); mw.Write((short)part3entries++); mw.Write((short)0x0CCB); // CARNAME_W01_CV mw.Write((short)2); mw.Write((short)part3entries++); mw.Write((short)0x0CCE); // CARNAME_W02_CV mw.Write((short)2); mw.Write((short)part3entries++); mw.Write((short)0x0CCE); // CARNAME_W03_CV mw.Write((short)2); mw.Write((short)part3entries++); mw.Write((short)0x0CCE); // CARNAME_W04_CV mw.Write((short)2); mw.Write((short)part3entries++); mw.Write((short)0x0CCE); // CARNAME_KIT00_HEADLIGHT mw.Write((short)2); mw.Write((short)part3entries++); mw.Write((short)0x0CDC); // CARNAME_STYLE01_HEADLIGHT mw.Write((short)3); mw.Write((short)part3entries++); mw.Write((short)0x0CCE); mw.Write((short)0x0CDE); // CARNAME_STYLE04_HEADLIGHT mw.Write((short)3); mw.Write((short)part3entries++); mw.Write((short)0x0CCE); mw.Write((short)0x0CDE); // CARNAME_STYLE10_HEADLIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE11_HEADLIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE02_HEADLIGHT mw.Write((short)3); mw.Write((short)part3entries++); mw.Write((short)0x0CCE); mw.Write((short)0x0CDE); // CARNAME_STYLE03_HEADLIGHT mw.Write((short)3); mw.Write((short)part3entries++); mw.Write((short)0x0CCE); mw.Write((short)0x0CDE); // CARNAME_STYLE05_HEADLIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE08_HEADLIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE13_HEADLIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE06_HEADLIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE07_HEADLIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE09_HEADLIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE12_HEADLIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE14_HEADLIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_KIT00_BRAKELIGHT mw.Write((short)2); mw.Write((short)part3entries++); mw.Write((short)0x0CED); // CARNAME_STYLE01_BRAKELIGHT mw.Write((short)3); mw.Write((short)part3entries++); mw.Write((short)0x0CCE); mw.Write((short)0x0CDE); // CARNAME_STYLE04_BRAKELIGHT mw.Write((short)3); mw.Write((short)part3entries++); mw.Write((short)0x0CCE); mw.Write((short)0x0CDE); // CARNAME_STYLE10_BRAKELIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE11_BRAKELIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE02_BRAKELIGHT mw.Write((short)3); mw.Write((short)part3entries++); mw.Write((short)0x0CCE); mw.Write((short)0x0CDE); // CARNAME_STYLE03_BRAKELIGHT mw.Write((short)3); mw.Write((short)part3entries++); mw.Write((short)0x0CCE); mw.Write((short)0x0CDE); // CARNAME_STYLE05_BRAKELIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE08_BRAKELIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE13_BRAKELIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE06_BRAKELIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE07_BRAKELIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE09_BRAKELIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE12_BRAKELIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE14_BRAKELIGHT mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_KIT22_HOOD_UNDER mw.Write((short)2); mw.Write((short)part3entries); mw.Write((short)0x0D03); // CARNAME_KIT24_HOOD_UNDER mw.Write((short)2); mw.Write((short)(part3entries + 1)); mw.Write((short)0x0D03); // CARNAME_KIT23_HOOD_UNDER mw.Write((short)3); mw.Write((short)(part3entries + 2)); mw.Write((short)0x0D07); mw.Write((short)0x0D03); // CARNAME_KIT25_HOOD_UNDER mw.Write((short)3); mw.Write((short)(part3entries + 3)); mw.Write((short)0x0D07); mw.Write((short)0x0D03); // CARNAME_KIT21_HOOD_UNDER mw.Write((short)2); mw.Write((short)(part3entries + 4)); mw.Write((short)0x0D03); // CARNAME_KIT22_HOOD_UNDER CF mw.Write((short)4); mw.Write((short)part3entries++); mw.Write((short)0x0D0A); mw.Write((short)2); mw.Write((short)0x0D03); // CARNAME_KIT24_HOOD_UNDER CF mw.Write((short)4); mw.Write((short)part3entries++); mw.Write((short)0x0D0B); mw.Write((short)2); mw.Write((short)0x0D03); // CARNAME_KIT23_HOOD_UNDER CF mw.Write((short)5); mw.Write((short)part3entries++); mw.Write((short)0x0D07); mw.Write((short)0x0D0C); mw.Write((short)2); mw.Write((short)0x0D03); // CARNAME_KIT25_HOOD_UNDER CF mw.Write((short)5); mw.Write((short)part3entries++); mw.Write((short)0x0D07); mw.Write((short)0x0D0D); mw.Write((short)2); mw.Write((short)0x0D03); // CARNAME_KIT21_HOOD_UNDER CF mw.Write((short)4); mw.Write((short)part3entries++); mw.Write((short)0x0D0E); mw.Write((short)2); mw.Write((short)0x0D03); // CARNAME_ENGINE mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE01_ENGINE mw.Write((short)1); mw.Write((short)part3entries++); // CARNAME_STYLE02_ENGINE mw.Write((short)1); mw.Write((short)part3entries++); } // Fix length in the header mw.Position = 4; mw.Write(mw.Length - 8); return(mw.Data); }
// Thanks to nlgzrgn for helping with this part!))) private static byte[] CPI_Part4(Database.Underground2 db) { int part4size = db.SlotTypes.Part4.Data.Length; var carlist = new List <string>(); // Precalculate size of part4 foreach (var car in db.CarTypeInfos.Collections) { if (car.Deletable && car.UsageType == eUsageType.Racer) { carlist.Add(car.CollectionName); part4size += 0xD8; } else if (car.Deletable && car.UsageType == eUsageType.Traffic) { carlist.Add(car.CollectionName); part4size += 0x48; } } int padding = 0x10 - ((part4size + 8) % 0x10); if (padding != 0x10) { part4size += padding; } // Use MemoryWriter instead of BinaryWriter so we can return an array for later processes var mw = new MemoryWriter(part4size); mw.Write(db.SlotTypes.Part4.Data); const uint negative = 0xFFFFFFFF; const uint definer = 0xFFFF0000; foreach (var name in carlist) { var car = db.CarTypeInfos.FindCollection(name); switch (car.UsageType) { case eUsageType.Racer: for (int a1 = 0; a1 < 5; ++a1) { mw.Write(definer); mw.Write(Bin.Hash(name + UsageType.MiscPartsRacer[a1])); for (int a2 = 0; a2 < 7; ++a2) { mw.Write(negative); } } mw.Write(definer); mw.Write(Bin.Hash(name + UsageType.MiscPartsRacer[5])); mw.Write(Bin.Hash(name + UsageType.MiscPartsRacer[6])); mw.Write(Bin.Hash(name + UsageType.MiscPartsRacer[7])); mw.Write(negative); mw.Write(Bin.Hash(name + UsageType.MiscPartsRacer[8])); mw.Write(Bin.Hash(name + UsageType.MiscPartsRacer[9])); mw.Write(Bin.Hash(name + UsageType.MiscPartsRacer[10])); mw.Write(negative); break; case eUsageType.Traffic: mw.Write(definer); mw.Write(Bin.Hash(name + UsageType.MiscPartsTraffic[0])); for (int a1 = 0; a1 < 7; ++a1) { mw.Write(negative); } mw.Write(definer); for (int a1 = 1; a1 < 5; ++a1) { mw.Write(Bin.Hash(name + UsageType.MiscPartsTraffic[a1])); } for (int a1 = 0; a1 < 4; ++a1) { mw.Write(negative); } break; default: // should never happen break; } } // Fix length in the header mw.Position = 4; mw.Write(mw.Length - 8); db.SlotTypes.Part0.SetMiscNumber((mw.Length - 8) / 0x24); return(mw.Data); }
private void btnGraphFromImages_Click(object sender, EventArgs e) { string directoryPath = @"D:\Images\!"; int x = 2690; int y = 1990; if (Directory.Exists(directoryPath)) { string[] files = Directory.GetFiles(directoryPath); IEnumerable <string> sortedFiles = files.OrderBy(f => int.Parse(Path.GetFileNameWithoutExtension(f))); int n = 0; int minIntensity = 255; int maxIntensity = 0; List <ChartPoint> points = new List <ChartPoint>(); foreach (string file in sortedFiles) { using (Bitmap bitmap = new Bitmap(file)) { System.Drawing.Color color = bitmap.GetPixel(x, y); int intensity = ColorWrapper.GetGrayIntensity(color); if (intensity < minIntensity) { minIntensity = intensity; } if (intensity > maxIntensity) { maxIntensity = intensity; } ChartPoint chartPoint = new ChartPoint(n, intensity); points.Add(chartPoint); n++; } } Chart chart1 = new Chart() { SeriesCollection = new List <ChartSeries>() { new ChartSeries() { Name = "Grpah", Type = HoloCommon.Enumeration.Charting.ChartSeriesType.Linear, ColorDescriptor = new ColorDescriptor(255, 0, 0), Points = points } } }; MemoryWriter.Write <Chart>(chart1, new ChartSerialization()); ProcessManager.RunProcess(@"D:\Projects\HoloApplication\Modules\ChartApp\ChartApp\bin\Release\ChartApp.exe", null, false, false); Thread.Sleep(2000); Interval <double> startInterval = new Interval <double>(minIntensity, maxIntensity); Interval <double> finishInterval = new Interval <double>(-1, 1); RealIntervalTransform transform = new RealIntervalTransform(startInterval, finishInterval); List <ChartPoint> points2 = new List <ChartPoint>(); foreach (ChartPoint p in points) { double newValue = transform.TransformToFinishIntervalValue(p.Y); ChartPoint point = new ChartPoint(p.X, newValue); points2.Add(point); } Chart chart2 = new Chart() { SeriesCollection = new List <ChartSeries>() { new ChartSeries() { Name = "Grpah2", Type = HoloCommon.Enumeration.Charting.ChartSeriesType.Linear, ColorDescriptor = new ColorDescriptor(0, 255, 0), Points = points2 } } }; MemoryWriter.Write <Chart>(chart2, new ChartSerialization()); ProcessManager.RunProcess(@"D:\Projects\HoloApplication\Modules\ChartApp\ChartApp\bin\Release\ChartApp.exe", null, false, false); Thread.Sleep(2000); List <ChartPoint> points3 = new List <ChartPoint>(); foreach (ChartPoint p in points2) { double newValue = Math.Acos(p.Y); ChartPoint point = new ChartPoint(p.X, newValue); points3.Add(point); } Chart chart3 = new Chart() { SeriesCollection = new List <ChartSeries>() { new ChartSeries() { Name = "Grpah3", Type = HoloCommon.Enumeration.Charting.ChartSeriesType.Linear, ColorDescriptor = new ColorDescriptor(0, 0, 0), Points = points3 } } }; MemoryWriter.Write <Chart>(chart3, new ChartSerialization()); ProcessManager.RunProcess(@"D:\Projects\HoloApplication\Modules\ChartApp\ChartApp\bin\Release\ChartApp.exe", null, false, false); Thread.Sleep(2000); } }
/// <summary> /// Encodes the specified image data to png. /// </summary> /// <param name="pixels">The pixel data indexed as [x,y] (bottom line first).</param> /// <returns>The png image data.</returns> public byte[] Encode(OxyColor[,] pixels) { int width = pixels.GetLength(0); int height = pixels.GetLength(1); var bytes = new byte[(width * height * 4) + height]; int k = 0; for (int y = 0; y < height; y++) { bytes[k++] = 0; // Filter for (int x = 0; x < width; x++) { bytes[k++] = pixels[x, y].R; bytes[k++] = pixels[x, y].G; bytes[k++] = pixels[x, y].B; bytes[k++] = pixels[x, y].A; } } var w = new MemoryWriter(); w.Write((byte)0x89); w.Write("PNG\r\n\x1a\n".ToCharArray()); WriteChunk(w, "IHDR", CreateHeaderData(width, height)); WriteChunk(w, "pHYs", CreatePhysicalDimensionsData(this.options.DpiX, this.options.DpiY)); WriteChunk(w, "IDAT", CreateUncompressedBlocks(bytes)); WriteChunk(w, "IEND", new byte[0]); return w.ToArray(); }
/// <summary> /// Encodes the specified image data to png. /// </summary> /// <param name="pixels"> /// The pixel data (bottom line first). /// </param> /// <param name="dpi"> /// The image resolution in dots per inch. /// </param> /// <returns> /// The png image data. /// </returns> public static byte[] Encode(OxyColor[,] pixels, int dpi = 96) { int height = pixels.GetLength(0); int width = pixels.GetLength(1); var bytes = new byte[(width * height * 4) + height]; int k = 0; for (int i = height - 1; i >= 0; i--) { bytes[k++] = 0; // Filter for (int j = 0; j < width; j++) { bytes[k++] = pixels[i, j].R; bytes[k++] = pixels[i, j].G; bytes[k++] = pixels[i, j].B; bytes[k++] = pixels[i, j].A; } } var w = new MemoryWriter(); w.Write((byte)0x89); w.Write("PNG\r\n\x1a\n".ToCharArray()); WriteChunk(w, "IHDR", CreateHeaderData(width, height)); WriteChunk(w, "pHYs", CreatePhysicalDimensionsData(dpi, dpi)); WriteChunk(w, "IDAT", CreateUncompressedBlocks(bytes)); WriteChunk(w, "IEND", new byte[0]); return w.ToArray(); }
/// <summary> /// /// </summary> /// <param name="cipher"></param> /// <returns>plain. null if decrypt failed.</returns> public virtual SmartBuffer DecryptTcp(ReadOnlyMemory <byte> cipher) { if (cipher.IsEmpty) { _logger?.LogInformation($"ShadowosocksAeadCipher DecryptTcp plain.IsEmpty."); return(null); } bool decrypteFailed = false; #region crumb if (null != _tcp_decrypt_crumb && _tcp_decrypt_crumb.SignificantLength > 0)//have crumb left lasttime. { _logger?.LogInformation($"ShadowosocksAeadCipher DecryptTcp crumb {_tcp_decrypt_crumb.SignificantLength} bytes found."); using (var combCipher = SmartBuffer.Rent(cipher.Length + _tcp_decrypt_crumb.SignificantLength)) { //combine crumb var combCipherStream = new MemoryWriter(combCipher.Memory); combCipherStream.Write(_tcp_decrypt_crumb.SignificantMemory); combCipherStream.Write(cipher); combCipher.SignificantLength = cipher.Length + _tcp_decrypt_crumb.SignificantLength; _tcp_decrypt_crumb.SignificantLength = 0; _logger?.LogInformation($"ShadowosocksAeadCipher DecryptTcp combined crumb + new cipher = {combCipher.SignificantLength} bytes."); return(DecryptTcp(combCipher.SignificantMemory)); } } if (cipher.Length <= LEN_TCP_OVERHEAD_PER_CHUNK)//still an incomplete chunk. { Initialize_TcpDecrypt_Crumb(); cipher.CopyTo(_tcp_decrypt_crumb.Memory); _tcp_decrypt_crumb.SignificantLength = cipher.Length; _logger?.LogInformation($"ShadowosocksAeadCipher DecryptTcp save crumb {_tcp_decrypt_crumb.SignificantLength} bytes."); return(null); } #endregion var cipherStreamReader = new ReadOnlyMemoryReader(cipher); if (!_tcpCtx解密.HaveSalt()) { _tcpCtx解密.SetSalt(cipherStreamReader.Read(_tcpCtx解密.Salt.Length)); _logger?.LogInformation($"ShadowosocksAeadCipher DecryptTcp salt read. {_tcpCtx解密.Salt.ToHexString()}"); DeriveSubKey(_masterKeyBytes, _tcpCtx解密.Salt, SubkeyInfoBytes, _tcpCtx解密.Key, _tcpCtx解密.Key.Length); _logger?.LogInformation($"ShadowosocksAeadCipher DecryptTcp new subkey. {_tcpCtx解密.Key.ToHexString()}"); } var plainBuffer = SmartBuffer.Rent(cipher.Length);//enough var plainStream = new MemoryWriter(plainBuffer.Memory); int remain = cipher.Length; do { const int LEN_AND_LENTAG = LEN_TCP_PAYLOADLEN_LENGTH + LEN_TAG; ushort payloadLen = 0; //payloadlen { var arrPayloadLen = cipherStreamReader.Read(LEN_AND_LENTAG); using (var len = this.DecryptChunk(arrPayloadLen, _tcpCtx解密.Key, _tcpCtx解密.Nonce)) { _tcpCtx解密.IncreaseNonce(); if (null == len || 0 >= len.SignificantLength) { decrypteFailed = true;//TODO close client or not break; } var payloadLenBytes = len.SignificantMemory; _logger?.LogInformation($"ShadowosocksAeadCipher DecryptTcp payloadLenBytes ={payloadLenBytes.ToArray().ToHexString()}."); // payloadLen = (ushort)System.Net.IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(payloadLenBytes.Span)); BinaryPrimitives.TryReadUInt16BigEndian(payloadLenBytes.Span, out payloadLen); _logger?.LogInformation($"ShadowosocksAeadCipher DecryptTcp decrypted payloadLen={payloadLen}."); } if (payloadLen <= 0) { decrypteFailed = true; _logger?.LogInformation($"ShadowosocksAeadCipher DecryptTcp something weird happened."); break; } if (!decrypteFailed && payloadLen + LEN_TAG > (cipherStreamReader.Length - cipherStreamReader.Position)) { Initialize_TcpDecrypt_Crumb(); cipher.Slice(cipherStreamReader.Position - LEN_AND_LENTAG).CopyTo(_tcp_decrypt_crumb.Memory); _tcp_decrypt_crumb.SignificantLength = (cipherStreamReader.Length - cipherStreamReader.Position + LEN_AND_LENTAG); remain = 0; _tcpCtx解密.DecreaseNonce(); _logger?.LogInformation($"ShadowosocksAeadCipher DecryptTcp save incomplete chunk {_tcp_decrypt_crumb.SignificantLength} bytes."); break; } } //payload { var arrPayload = cipherStreamReader.Read(payloadLen + LEN_TAG); using (var payload = this.DecryptChunk(arrPayload, _tcpCtx解密.Key, _tcpCtx解密.Nonce)) { _tcpCtx解密.IncreaseNonce(); if (0 >= payload.SignificantLength) { decrypteFailed = true; break; } plainStream.Write(payload.SignificantMemory); _logger?.LogInformation($"ShadowosocksAeadCipher DecryptTcp decrypted payload {payload.SignificantLength} bytes."); _logger?.LogInformation($"ShadowosocksAeadCipher DecryptTcp decrypted plain= " + $"{payload.SignificantMemory.ToArray().ToHexString()}"); _logger?.LogInformation($"ShadowosocksAeadCipher DecryptTcp decrypted plain.UTF8= " + $"{Encoding.UTF8.GetString(payload.SignificantMemory.ToArray())}\r\n"); } } //----- _logger?.LogInformation($"ShadowosocksAeadCipher DecryptTcp one chunk decrypted."); remain = cipherStreamReader.Length - cipherStreamReader.Position; } while (remain > LEN_TCP_OVERHEAD_PER_CHUNK); if (!decrypteFailed && 0 < remain && remain <= LEN_TCP_OVERHEAD_PER_CHUNK)//crumb { Initialize_TcpDecrypt_Crumb(); _logger?.LogInformation($"ShadowosocksAeadCipher DecryptTcp save incomplete chunk {_tcp_decrypt_crumb.SignificantLength} bytes."); cipher.Slice(cipher.Length - remain, remain).CopyTo(_tcp_decrypt_crumb.Memory); _tcp_decrypt_crumb.SignificantLength += remain;//_decrypt_crumb must be empty. //TODO not thread-safe. } if (decrypteFailed && null != _tcp_decrypt_crumb) { _tcp_decrypt_crumb.Erase(); } plainBuffer.SignificantLength = decrypteFailed ? 0 : plainStream.Position; _logger?.LogInformation($"ShadowosocksAeadCipher DecryptTcp {plainBuffer.SignificantLength} bytes got, will return."); return(plainBuffer); }
private void btnIntensityIncrease_Click(object sender, EventArgs e) { int count = 1000; double step = GetStep(); List <double> valuesList = new List <double>(); double x = 0; for (int k = 0; k < count; k++) { double value = Math.Cos(x); valuesList.Add(value); x += step; } List <ChartPoint> points = new List <ChartPoint>(); for (int k = 0; k < count; k++) { ChartPoint p = new ChartPoint(k, valuesList[k]); points.Add(p); } Chart chart1 = new Chart() { SeriesCollection = new List <ChartSeries>() { new ChartSeries() { Name = "Graph", Type = HoloCommon.Enumeration.Charting.ChartSeriesType.Linear, ColorDescriptor = new ColorDescriptor(255, 0, 0), Points = points } } }; MemoryWriter.Write <Chart>(chart1, new ChartSerialization()); ProcessManager.RunProcess(@"D:\Projects\HoloApplication\Modules\ChartApp\ChartApp\bin\Release\ChartApp.exe", null, false, false); Thread.Sleep(2000); Interval <double> startInterval = new Interval <double>(-1, 1); Interval <double> finishInterval = new Interval <double>(0, MAX_RANGE_VALUE); RealIntervalTransform transform = new RealIntervalTransform(startInterval, finishInterval); List <ChartPoint> points2 = new List <ChartPoint>(); for (int k = 0; k < count; k++) { double newValue = transform.TransformToFinishIntervalValue(valuesList[k]); ChartPoint p = new ChartPoint(k, newValue); points2.Add(p); } List <ChartPoint> points3 = new List <ChartPoint>(); for (int k = 0; k < points2.Count; k++) { ChartPoint p = points2[k]; double v = p.Y % M1; ChartPoint newPoint = new ChartPoint(p.X, v); points3.Add(newPoint); } List <ChartPoint> points4 = new List <ChartPoint>(); for (int k = 0; k < points2.Count; k++) { ChartPoint p = points2[k]; double v = p.Y % M2; ChartPoint newPoint = new ChartPoint(p.X, v); points4.Add(newPoint); } Chart chart2 = new Chart() { SeriesCollection = new List <ChartSeries>() { new ChartSeries() { Name = "Graph", Type = HoloCommon.Enumeration.Charting.ChartSeriesType.Linear, ColorDescriptor = new ColorDescriptor(0, 0, 0), Points = points2 }, new ChartSeries() { Name = "M1", Type = HoloCommon.Enumeration.Charting.ChartSeriesType.Linear, ColorDescriptor = new ColorDescriptor(0, 255, 0), Points = points3 }, new ChartSeries() { Name = "M2", Type = HoloCommon.Enumeration.Charting.ChartSeriesType.Linear, ColorDescriptor = new ColorDescriptor(255, 0, 0), Points = points4 } } }; MemoryWriter.Write <Chart>(chart2, new ChartSerialization()); ProcessManager.RunProcess(@"D:\Projects\HoloApplication\Modules\ChartApp\ChartApp\bin\Release\ChartApp.exe", null, false, false); Thread.Sleep(2000); List <ChartPoint> points5 = new List <ChartPoint>(); for (int k = 0; k < points3.Count; k++) { ChartPoint m1Point = points3[k]; ChartPoint m2Point = points4[k]; ChartPoint point = new ChartPoint(m1Point.Y, m2Point.Y); //ChartPoint point = new ChartPoint(m1Point.Y - M1, M2 - m2Point.Y); points5.Add(point); } List <Point2D> pointsDiagonal = ModularArithmeticHelper.BuildTable(M1, M2, MAX_RANGE_VALUE); List <ChartPoint> points6 = new List <ChartPoint>(); for (int k = 0; k < pointsDiagonal.Count; k++) { Point2D p = pointsDiagonal[k]; ChartPoint p1 = new ChartPoint(p.X, p.Y); //ChartPoint p1 = new ChartPoint(p.X - M1, M2 - p.Y); points6.Add(p1); } Chart chart5 = new Chart() { //InvertAxisX = true, //InvertAxisY = true, SeriesCollection = new List <ChartSeries>() { new ChartSeries() { Name = "Diagonal", Type = HoloCommon.Enumeration.Charting.ChartSeriesType.Linear, ColorDescriptor = new ColorDescriptor(0, 255, 0), Points = points6 }, new ChartSeries() { Name = "Points", Type = HoloCommon.Enumeration.Charting.ChartSeriesType.Bubble, ColorDescriptor = new ColorDescriptor(0, 0, 0), Points = points5 } } }; MemoryWriter.Write <Chart>(chart5, new ChartSerialization()); ProcessManager.RunProcess(@"D:\Projects\HoloApplication\Modules\ChartApp\ChartApp\bin\Release\ChartApp.exe", null, false, false); Thread.Sleep(2000); }