public static int Compress(Stream input, Stream output, int uncompressedSize, Action<long> compressed = null) { Exceptions.CheckArgumentNull(input, "input"); Exceptions.CheckArgumentNull(output, "output"); Exceptions.CheckArgumentOutOfRangeException(uncompressedSize, "uncompressedSize", 0, int.MaxValue); byte[] buff = new byte[Math.Min(32 * 1024, uncompressedSize)]; ZOutputStream writer = new ZOutputStream(output, 6); long position = output.Position; int readed; while (uncompressedSize > 0 && (readed = input.Read(buff, 0, Math.Min(buff.Length, uncompressedSize))) > 0) { uncompressedSize -= readed; writer.Write(buff, 0, readed); compressed.NullSafeInvoke(readed); } writer.finish(); if (uncompressedSize != 0) throw new Exception("Неожиданный конец потока."); return (int)(output.Position - position); }
public void Compress() { //压缩 byte[] byteData = System.Text.Encoding.UTF8.GetBytes("ul{\"state\":1,\"nick\":\"小龙\",\"sex\":true,\"email\":\"[email protected]\",\"exp\":109040,\"isguest\":false,\"hotpoint\":26,\"money\":7099,\"styletype\":\"stand\",\"style\":\"2/2/2/1\",\"id\":\"2ef38760-9000-4f10-b96b-af4da8c656ae\",\"vertify\":1,\"level\":12,\"sign\":\"小龙\",\"score\":6323}"); MemoryStream ms = new MemoryStream(); Stream s = new ZOutputStream(ms, 9); s.Write(byteData, 0, byteData.Length); s.Close(); byte[] compressData = (byte[])ms.ToArray(); ms.Flush(); ms.Close(); Console.WriteLine(compressData.Length); //解压 MemoryStream md = new MemoryStream(); Stream d = new ZOutputStream(md); d.Write(compressData, 0, compressData.Length); d.Close(); byte[] dompressData = (byte[])md.ToArray(); md.Flush(); md.Close(); Console.WriteLine(dompressData.Length); }
/// <summary> /// Zip compress data with offset and length. /// </summary> /// <param name="src"></param> /// <returns></returns> public static byte[] Compress(byte[] src, int offset, int length) { MemoryStream ms = new MemoryStream(); Stream s = new ZOutputStream(ms, 9); s.Write(src, offset, length); s.Close(); return (byte[])ms.ToArray(); }
/// <summary> /// Zip uncompress data. /// </summary> /// <param name="src"></param> /// <returns></returns> public static byte[] Uncompress(byte[] src) { MemoryStream md = new MemoryStream(); Stream d = new ZOutputStream(md); d.Write(src, 0, src.Length); d.Close(); return (byte[])md.ToArray(); }
public void Compress() { byte[] buffer = m_Stream.GetBuffer(); ZOutputStream zs = new ZOutputStream(m_Stream); zs.Write(buffer, 0, buffer.Length); zs.Close(); Init(); }
/// <summary> /// Deflate a string using zlib.net library since IronRuby's Deflate module is buggy, f**k /// </summary> /// <param name="data">The string to compress</param> /// <returns>The decompressed string as a Ruby string</returns> public static MutableString ZlibDeflate(string data) { using (MemoryStream outMemoryStream = new MemoryStream()) using (ZOutputStream outZStream = new ZOutputStream(outMemoryStream, zlibConst.Z_BEST_COMPRESSION)) { byte[] bytes = Encoding.UTF8.GetBytes(data); outZStream.Write(bytes, 0, bytes.Length); outZStream.finish(); return MutableString.CreateBinary(outMemoryStream.ToArray()); } }
public static void Decompress(Stream compressed, Stream target) { var zip = new ZOutputStream(target); int readBytes; var buffer = new byte[512]; do { readBytes = compressed.Read(buffer, 0, buffer.Length); zip.Write(buffer, 0, readBytes); } while (readBytes > 0); zip.Flush(); target.Seek(0, SeekOrigin.Begin); }
public static void Compress(Stream uncompressed, Stream target) { var buffer = new byte[4096]; int readBytes; var zip = new ZOutputStream(target, zlibConst.Z_BEST_COMPRESSION); do { readBytes = uncompressed.Read(buffer, 0, buffer.Length); zip.Write(buffer, 0, readBytes); } while (readBytes > 0); zip.finish(); zip.Flush(); }
public void SendChunk(Chunk chunk) { Transmit(PacketType.PreChunk, chunk.ChunkX, chunk.ChunkZ, (sbyte) 1); byte[] uncompressed = chunk.GetBytes(); MemoryStream mem = new MemoryStream(); ZOutputStream stream = new ZOutputStream(mem, zlibConst.Z_BEST_COMPRESSION); stream.Write(uncompressed, 0, uncompressed.Length); stream.Close(); byte[] data = mem.ToArray(); Transmit(PacketType.MapChunk, 16 * chunk.ChunkX, (short) 0, 16 * chunk.ChunkZ, (sbyte) 15, (sbyte) 127, (sbyte) 15, data.Length, data); }
public void Receive2(string Message) { MessageEventArgs args = new MessageEventArgs(); try { byte[] messagebytes = Helpers.DecodeBase64Byte(Message); using (MemoryStream ms = new MemoryStream(messagebytes)) { using (var output = new MemoryStream()) using (var zipStream = new zlib.ZOutputStream(output)) { using (ms) { var buffer = new byte[2000]; int len; while ((len = ms.Read(buffer, 0, 2000)) > 0) { zipStream.Write(buffer, 0, len); } } // reset output stream to start so we can read it to a string output.Position = 0; byte[] content = new byte[output.Length]; output.Read(content, 0, (int)output.Length); args.Message = Encoding.Default.GetString(content); } } receivedCount++; if (receivedCount >= 10) { receivedEvent.Set(); } } catch (Exception ex) { throw ex; } EventHandler <MessageEventArgs> handler = MessageReceived; if (handler != null) { handler(this, args); } }
//导出 private void exportBtn_Click(object sender, EventArgs e) { int index = swfListBox.SelectedIndex; SwfClass swf = ProcessHandle.getInstence().getSwfClassByIndex(index); if (saveFileDialog.ShowDialog() == DialogResult.OK){ string localFilePath = saveFileDialog.FileName; if(checkBox.Checked == false){ byte[] fileByte = swf.fileByte; FileStream file = new FileStream(localFilePath, FileMode.Create); file.Write(fileByte, 0, swf.size); file.Flush(); file.Close(); } else { MemoryStream mStream = new MemoryStream(swf.fileByte.Length); mStream.WriteByte(0x43); mStream.Write(swf.fileByte, 1, 7); MemoryStream getStream = new MemoryStream(swf.fileByte.Length); //ZipOutputStream outPut = new ZipOutputStream(getStream); //ZipEntry entry = new ZipEntry(""); //entry.CompressionMethod = CompressionMethod.WinZipAES //outPut.PutNextEntry(entry); //outPut.Write(swf.fileByte, 8, swf.fileByte.Length - 8); //outPut.Finish(); ZOutputStream outPut = new ZOutputStream(getStream,zlib.zlibConst.Z_DEFAULT_COMPRESSION); outPut.Write(swf.fileByte, 8, swf.fileByte.Length - 8); outPut.finish(); getStream.WriteTo(mStream); outPut.Close(); FileStream file = new FileStream(localFilePath, FileMode.Create); file.Write(mStream.ToArray(), 0,(int)mStream.Length); file.Flush(); file.Close(); MessageBox.Show("导出swf成功,路径:" + localFilePath,"成功"); } } }
public static byte[] CompressData(byte[] inData) { byte[] byteArray = inData; byte[] tmpArray; using (MemoryStream ms = new MemoryStream()) { using (zlib.ZOutputStream outZStream = new zlib.ZOutputStream(ms, zlib.zlibConst.Z_DEFAULT_COMPRESSION)) { outZStream.Write(byteArray, 0, byteArray.Length); outZStream.Flush(); } tmpArray = ms.ToArray(); } return(tmpArray); }
public static MemoryStream Decompress(BinaryReader input, long destLength) { int bufferLength = 4; MemoryStream output = new MemoryStream(); ZOutputStream zipStream = new ZOutputStream(output); byte[] buffer = new byte[bufferLength]; while (output.Length < destLength) { input.Read(buffer, 0, bufferLength); zipStream.Write(buffer, 0, bufferLength); } return output; }
public static string Compress(string param) { byte[] data = System.Text.Encoding.UTF8.GetBytes(param); //byte[] data = Convert.FromBase64String(param); MemoryStream ms = new MemoryStream(); Stream stream = new zlib.ZOutputStream(ms); try { stream.Write(data, 0, data.Length); } finally { stream.Close(); ms.Close(); } return(Convert.ToBase64String(ms.ToArray())); }
public static byte[] Decompress(byte[] input) { using (MemoryStream output = new MemoryStream()) { using (ZOutputStream zipStream = new ZOutputStream(output)) { using (MemoryStream inputStream = new MemoryStream(input)) { var buffer = new byte[2000]; int len; while ((len = inputStream.Read(buffer, 0, 2000)) > 0) { zipStream.Write(buffer, 0, len); } } } return output.ToArray(); } }
public static MemoryStream Decompress(Stream input) { var output = new MemoryStream(); var zipStream = new zlib.ZOutputStream(output); using (input) { var buffer = new byte[2000]; int len; while ((len = input.Read(buffer, 0, 2000)) > 0) { zipStream.Write(buffer, 0, len); } } output.Position = 0; byte[] content = new byte[output.Length]; output.Read(content, 0, (int)output.Length); return(output); }
public static MemoryStream Decompress(Stream input) { var output = new MemoryStream(); var zipStream = new zlib.ZOutputStream(output); using (input) { var buffer = new byte[2000]; int len; while ((len = input.Read(buffer, 0, 2000)) > 0) { zipStream.Write(buffer, 0, len); } } output.Position = 0; byte[] content = new byte[output.Length]; output.Read(content, 0, (int)output.Length); return output; }
public Stream OpenStream() { var output = new MemoryStream(); if (entry.Length != 0) { reader.BaseStream.Position = (long)entry.Offset; uint num = entry.zIndex; do { if (zLengths[num] == 0) { byte[] array = reader.ReadBytes((int)blockSize); output.Write(array, 0, (int)blockSize); } else { ushort num2 = reader.ReadUInt16(); reader.BaseStream.Position -= 2; byte[] array = reader.ReadBytes((int)zLengths[num]); if (num2 == 30938) { ZOutputStream zOutputStream = new ZOutputStream(output); zOutputStream.Write(array, 0, array.Length); zOutputStream.Flush(); } else { output.Write(array, 0, array.Length); } } num += 1; } while (output.Length < (long)entry.Length); } output.Flush(); output.Seek(0, SeekOrigin.Begin); return output; }
public static long Zip(Stream str, Stream outStream, long plainLen, bool rewind = true) { /*zlib works great, can't say that about SharpZipLib*/ var buffer = new byte[65536]; var zOutputStream = new ZOutputStream(outStream, 9); while (str.Position < plainLen) { var size = (int)Math.Min(plainLen - str.Position, buffer.Length); str.Read(buffer, 0, size); zOutputStream.Write(buffer, 0, size); } zOutputStream.finish(); buffer = null; if (rewind) { outStream.Position = 0; outStream.Flush(); } return zOutputStream.TotalOut; }
/// <summary> /// 压缩Deflate数据至 /// </summary> /// <param name="A">要被压缩的流</param> /// <param name="B">要输出的流</param> /// <param name="Length">要压缩的数据长度</param> public static void DeflateEncodeTo(Stream A, Stream B, int Length) { ZOutputStream tOutput = new ZOutputStream(B, 9); byte[] tBuffer = new byte[8192]; // 8kb缓冲区 int tLen = 0; int tTotal = 0; while ((tLen = A.Read(tBuffer, 0, (Length - tTotal) > 8192 ? 8192 : Length - tTotal)) > 0) { tTotal += tLen; tOutput.Write(tBuffer, 0, tLen); } tOutput.finish(); if (tTotal != Length) throw new EndOfStreamException(); }
private static IDictionary<string, string> GetFromQch(string docsPath, string module) { string dataSource = Path.Combine(docsPath, string.Format("qt{0}.qch", module.ToLowerInvariant())); if (!File.Exists(dataSource)) { return new Dictionary<string, string>(); } SqliteConnectionStringBuilder sqliteConnectionStringBuilder = new SqliteConnectionStringBuilder(); sqliteConnectionStringBuilder.DataSource = dataSource; using (SqliteConnection sqliteConnection = new SqliteConnection(sqliteConnectionStringBuilder.ConnectionString)) { sqliteConnection.Open(); using (SqliteCommand sqliteCommand = new SqliteCommand( "SELECT Name, Data FROM FileNameTable INNER JOIN FileDataTable ON FileNameTable.FileId = FileDataTable.Id " + "WHERE Name LIKE '%.html' " + "ORDER BY Name", sqliteConnection)) { using (SqliteDataReader sqliteDataReader = sqliteCommand.ExecuteReader()) { Dictionary<string, string> documentation = new Dictionary<string, string>(); while (sqliteDataReader.Read()) { byte[] blob = new byte[ushort.MaxValue]; int length = (int) sqliteDataReader.GetBytes(1, 0, blob, 0, blob.Length); using (MemoryStream output = new MemoryStream(length - 4)) { using (ZOutputStream zOutputStream = new ZOutputStream(output)) { zOutputStream.Write(blob, 4, length - 4); zOutputStream.Flush(); documentation.Add(sqliteDataReader.GetString(0), StripTags(Encoding.UTF8.GetString(output.ToArray()))); } } } return documentation; } } } }
public override void Decode(Frame output) { int width = 0, height = 0; byte depth = 0; PNGColorType colorType = PNGColorType.TruecolorWithAlpha; Frame result = output; // TODO: Verify signature // Pull the PNG into a data buffer. if (this.Bitstream == null || this.Bitstream.Length < 1) return; var bytes = new byte[this.Bitstream.Length]; this.Bitstream.Read(bytes, 0, bytes.Length); var buf = new DataBuffer(bytes, ByteOrder.BigEndian); var signature = buf.ReadInt64(); if (signature != PNGCodec.BitstreamSignature) { } bool ihdrDone = false; //bool iendDone = false; using (var pixelStream = new MemoryStream()) { var zout = new ZOutputStream(pixelStream); // Start reading chunks. while (buf.Available > 0) { int length = buf.ReadInt32(); string chunk = string.Concat((char)buf.ReadByte(), (char)buf.ReadByte(), (char)buf.ReadByte(), (char)buf.ReadByte()); switch (chunk) { case "IHDR": if (ihdrDone) throw new NotImplementedException(); else ihdrDone = true; if (length != 13) throw new NotImplementedException(); width = buf.ReadInt32(); height = buf.ReadInt32(); depth = buf.ReadByte(); colorType = (PNGColorType)buf.ReadByte(); byte xmethod = buf.ReadByte(); PNGFilterMethod filterMethod = (PNGFilterMethod)buf.ReadByte(); byte interlaceMethod = buf.ReadByte(); break; case "IDAT": var data = buf.ReadBytes(length); zout.Write(data, 0, data.Length); break; default: Console.WriteLine("Skipping unknown chunk \"{0}\" in PNG bitstream at offset {1}", chunk, (buf.Position - 8).ToString("X")); buf.Position += (length > buf.Available) ? buf.Available : length; break; } int crc32 = buf.ReadInt32(); } if (depth == 8) { if (colorType == PNGColorType.TruecolorWithAlpha) { //var pd = new byte[width * height * 4]; var pd = new byte[pixelStream.Length]; pixelStream.Position = 0; pixelStream.Read(pd, 0, pd.Length); ColorRGB32[] pix = new ColorRGB32[width * height]; ColorRGB32 p = new ColorRGB32(); //File.WriteAllBytes("dump.bin", pd); for (int i = 0, n = 0; i < pix.Length; i++) { if (i % width == 0) n++; p.Red = pd[n++]; p.Green = pd[n++]; p.Blue = pd[n++]; p.Alpha = pd[n++]; pix[i] = p; } result.Video[0] = new BitmapRGB32(width, height, pix); } else if (colorType == PNGColorType.Truecolor) { //var pd = new byte[width * height * 3]; var pd = new byte[pixelStream.Length]; pixelStream.Position = 0; pixelStream.Read(pd, 0, pd.Length); ColorRGB24[] pix = new ColorRGB24[width * height]; ColorRGB24 p = new ColorRGB24(); //File.WriteAllBytes("dump.bin", pd); for (int i = 0, n = 0; i < pix.Length; i++) { if (i % width == 0) n++; p.Red = pd[n++]; p.Green = pd[n++]; p.Blue = pd[n++]; pix[i] = p; } result.Video[0] = new BitmapRGB24(width, height, pix); } else { throw new NotImplementedException(); } } else { throw new NotImplementedException(); } } }
public void Write(Stream stream) { BinaryWriter output = new BinaryWriter(stream, Encoding.UTF8); MemoryStream buffer = new MemoryStream(); BinaryWriter bufferOut; Console.WriteLine("BAD! SETTING COMPRESSION TO FALSE ALWAYS FOR OUTPUT CURRENTLY!"); _header.IsCompressed = false; // Part 1: Write header basics) output.Write(_header.Signature); output.Write(_header.Version); bufferOut = new BinaryWriter(buffer, Encoding.UTF8); // Part 2: Write tags into buffer _frameSize.WriteExternal(bufferOut); // 8.8 fixed ?? // TODO verify float d = _frameRate - ((byte)(_frameRate)); d *= 100; bufferOut.Write((byte)d); bufferOut.Write((byte)_frameRate); bufferOut.Write(_frameCount); foreach (Tag tag in _tags) { tag.WriteExternal(bufferOut); } // Part 3: Update header size output.Write((uint)((uint)buffer.Length + 8U)); // Part 4: Write buffer (compressed) to the main stream buffer.Seek(0, SeekOrigin.Begin); byte[] bb = new byte[1024]; int len; if (_header.IsCompressed) { /* TODO can we do something about this zlib crap? */ // Careful! zlib.net can not read when itself compresses using Z_BEST_COMPRESSION // So since zlib.Inflate was getting stuck in and endless lopp I decided to use // Z_DEFAULT_COMPRESSION which has been working fine for me now ... ZOutputStream zOut = new ZOutputStream(stream, zlibConst.Z_DEFAULT_COMPRESSION ); while ((len = buffer.Read(bb, 0, 1024)) > 0) { zOut.Write(bb, 0, len); } zOut.Flush(); zOut.finish(); } else { while ((len = buffer.Read(bb, 0, 1024)) > 0) { output.Write(bb, 0, len); } } // Part 4: Finalize bufferOut.Close(); buffer.Dispose(); output.Close(); }
public void Read(Stream stream) { BinaryReader input = new BinaryReader(stream, Encoding.UTF8); MemoryStream buffer = null; // Part 1 _header = new Header(); _header.ReadExternal(input); if (_header.IsCompressed) { int len; byte[] bb = new byte[1024]; buffer = new MemoryStream(); /* TODO can we do something about this zlib crap? */ ZOutputStream zo = new ZOutputStream(buffer); #if DEBUG Console.WriteLine("[i] Decompressing ..."); #endif while ((len = input.Read(bb, 0, 1024)) > 0) { // Careful ... This is getting stuck in an endless loop if Z_BEST_COMPRESSION was used when // compressing the output. zo.Write(bb, 0, len); } #if DEBUG Console.WriteLine("[+] Decompressed"); #endif zo.Flush(); input.Close(); buffer.Seek(0, SeekOrigin.Begin); input = new BinaryReader(buffer, Encoding.UTF8); } // Part 2 _frameSize = new RECT(); _frameSize.ReadExternal(input); // 8.8 fixed value ?? // TODO verify byte lo = input.ReadByte(); byte hi = input.ReadByte(); _frameRate = hi + (lo * 0.01f); _frameCount = input.ReadUInt16(); _tags = new ArrayList(); while (true) { Tag tag = new Tag(this); tag.ReadExternal(input); _tags.Add(tag); if (0x00 == tag.Header.Type) { break; } } input.Close(); if (null != buffer) { buffer.Close(); buffer.Dispose(); } }
/// <summary> /// Decodes mesh asset. See <see cref="OpenMetaverse.Rendering.FacetedMesh.TryDecodeFromAsset"/> /// to furter decode it for rendering</summary> /// <returns>true</returns> public override bool Decode() { try { MeshData = new OSDMap(); using (MemoryStream data = new MemoryStream(AssetData)) { OSDMap header = (OSDMap)OSDParser.DeserializeLLSDBinary(data); long start = data.Position; foreach(string partName in header.Keys) { if (header[partName].Type != OSDType.Map) { MeshData[partName] = header[partName]; continue; } OSDMap partInfo = (OSDMap)header[partName]; if (partInfo["offset"] < 0 || partInfo["size"] == 0) { MeshData[partName] = partInfo; continue; } byte[] part = new byte[partInfo["size"]]; Buffer.BlockCopy(AssetData, partInfo["offset"] + (int)start, part, 0, part.Length); using (MemoryStream input = new MemoryStream(part)) { using (MemoryStream output = new MemoryStream()) { using (ZOutputStream zout = new ZOutputStream(output)) { byte[] buffer = new byte[2048]; int len; while ((len = input.Read(buffer, 0, buffer.Length)) > 0) { zout.Write(buffer, 0, len); } zout.Flush(); output.Seek(0, SeekOrigin.Begin); MeshData[partName] = OSDParser.DeserializeLLSDBinary(output); } } } } } return true; } catch (Exception ex) { Logger.Log("Failed to decode mesh asset", Helpers.LogLevel.Error, ex); return false; } }
public void SendChunk(Chunk c) { PreChunk(c.ChunkX, c.ChunkZ, 1); // TODO: maybe we can cache some uncompressed chunk byte[] uncompressed = c.GetBytes(); byte[] data; using(MemoryStream mem = new MemoryStream()) { using(ZOutputStream stream = new ZOutputStream(mem, zlibConst.Z_BEST_COMPRESSION)) { stream.Write(uncompressed, 0, uncompressed.Length); } data = mem.ToArray(); } CXMineServer.SendLogFile("Sending: MapChunk dimension: " + (data.Length + 18).ToString() + "\r\n"); Send(new MapChunk(16 * c.ChunkX, (short)0, 16 * c.ChunkZ, 15, 127, 15, data.Length, data)); //KeepAlive(); }
/// <summary> /// Returns a compressed copy of the chunk's block data. /// </summary> public byte[] GetCompressedData() { byte[] compressed; using (MemoryStream ms = new MemoryStream()) { using (ZOutputStream zout = new ZOutputStream(ms, zlibConst.Z_BEST_COMPRESSION)) { // Write block types zout.Write(blocks, 0, blocks.Length); // Write metadata zout.Write(meta, 0, meta.Length); // Write block light zout.Write(Light, 0, Light.Length); // Write sky light zout.Write(SkyL, 0, SkyL.Length); } compressed = ms.ToArray(); } return compressed; }
public override void Read(NetworkReader reader) { ChunkX = reader.ReadInt32(); ChunkY = reader.ReadInt16(); ChunkZ = reader.ReadInt32(); Width = reader.ReadByte() + 1; Height = reader.ReadByte() + 1; Depth = reader.ReadByte() + 1; byte[] data = new byte[reader.ReadInt32()]; reader.Read(data, 0, data.Length); var uncompressed = new MemoryStream(data.Length); // TODO: use better guess here var zlib = new ZOutputStream(uncompressed); zlib.Write(data, 0, data.Length); zlib.Flush(); zlib.finish(); Data = new byte[zlib.TotalOut]; uncompressed.Read(Data, 0, Data.Length); zlib.Close(); uncompressed.Close(); }
public override void Write(NetworkWriter writer) { writer.WriteInt32(ChunkX); writer.WriteInt16(ChunkY); writer.WriteInt32(ChunkZ); writer.WriteByte((byte)(Width - 1)); writer.WriteByte((byte)(Height - 1)); writer.WriteByte((byte)(Depth - 1)); var compressed = new MemoryStream(Data.Length); // TODO: use better guess here var zlib = new ZOutputStream(compressed, zlibConst.Z_DEFAULT_COMPRESSION); zlib.Write(Data, 0, Data.Length); zlib.Flush(); zlib.finish(); writer.WriteInt32((int)zlib.TotalOut); writer.Write(compressed.GetBuffer(), 0, (int)zlib.TotalOut); zlib.Close(); compressed.Close(); }
/// <summary> /// Decompresses the block. /// </summary> /// <param name="compressed">The compressed data.</param> /// <param name="type">The type data type contained in the block.</param> /// <returns>The decompressed block.</returns> private static byte[] DecompressBlock(byte[] compressed, ref DataType type) { byte[] data; using (var decompressed = new MemoryStream()) { using (var decompressor = new ZOutputStream(decompressed)) { decompressor.Write(compressed, 0, compressed.Length); decompressed.Position = 0; var buf = new byte[4]; decompressed.Read(buf, 0, 4); type = (DataType)BitConverter.ToInt32(buf, 0); decompressed.Read(buf, 0, 4); var size = BitConverter.ToInt32(buf, 0); data = new byte[size]; decompressed.Read(data, 0, size); } } return data; }
private MemoryStream CompressCache() { // small arrays almost never yeild a benefit from compressing if (cache.Length < 50) return null; byte[] cacheBytes = cache.GetBuffer(); MemoryStream compressedBuffer = new MemoryStream(); ZOutputStream zos = new ZOutputStream(compressedBuffer, zlibConst.Z_DEFAULT_COMPRESSION); zos.Write(cacheBytes, 0, (int) cache.Length); zos.finish(); // if the compression hasn't helped, then just return null if (compressedBuffer.Length >= cache.Length) return null; return compressedBuffer; }
public static MemoryStream Decompress(MemoryStream input) { var output = new MemoryStream(); using (var outZStream = new ZOutputStream(output)) { input.Seek(0, SeekOrigin.Begin); byte[] buffer = new byte[2000]; int len; while ((len = input.Read(buffer, 0, 2000)) > 0) { outZStream.Write(buffer, 0, len); } outZStream.Flush(); } return output; }
private Mesh CreateMeshFromPrimMesher(string primName, PrimitiveBaseShape primShape, Vector3 size, float lod, ulong key) { PrimMesh primMesh; SculptMesh sculptMesh; List<Coord> coords = new List<Coord>(); List<Face> faces = new List<Face>(); Image idata = null; string decodedSculptFileName = ""; if (primShape.SculptEntry) { if (((SculptType) primShape.SculptType & SculptType.Mesh) == SculptType.Mesh) { if (!UseMeshesPhysicsMesh) return null; MainConsole.Instance.Debug("[MESH]: experimental mesh proxy generation"); OSD meshOsd = null; if (primShape.SculptData == null || primShape.SculptData.Length <= 0) { //MainConsole.Instance.Error("[MESH]: asset data is zero length"); return null; } long start = 0; using (MemoryStream data = new MemoryStream(primShape.SculptData)) { try { meshOsd = OSDParser.DeserializeLLSDBinary(data); } catch (Exception e) { MainConsole.Instance.Error("[MESH]: Exception deserializing mesh asset header:" + e); } start = data.Position; } if (meshOsd is OSDMap) { OSDMap map = (OSDMap) meshOsd; OSDMap physicsParms = new OSDMap(); if (map.ContainsKey("physics_cached")) { OSD cachedMeshMap = map["physics_cached"]; // cached data from Aurora Mesh cachedMesh = new Mesh(key); cachedMesh.Deserialize(cachedMeshMap); cachedMesh.WasCached = true; return cachedMesh; //Return here, we found all of the info right here } if (map.ContainsKey("physics_shape")) physicsParms = (OSDMap) map["physics_shape"]; // old asset format if (physicsParms.Count == 0 && map.ContainsKey("physics_mesh")) physicsParms = (OSDMap) map["physics_mesh"]; // new asset format if (physicsParms.Count == 0 && map.ContainsKey("physics_convex")) // convex hull format, which we can't read, so instead // read the highest lod that exists, and use it instead physicsParms = (OSDMap) map["high_lod"]; int physOffset = physicsParms["offset"].AsInteger() + (int) start; int physSize = physicsParms["size"].AsInteger(); if (physOffset < 0 || physSize == 0) return null; // no mesh data in asset OSD decodedMeshOsd = new OSD(); byte[] meshBytes = new byte[physSize]; Buffer.BlockCopy(primShape.SculptData, physOffset, meshBytes, 0, physSize); try { using (MemoryStream inMs = new MemoryStream(meshBytes)) { using (MemoryStream outMs = new MemoryStream()) { using (ZOutputStream zOut = new ZOutputStream(outMs)) { byte[] readBuffer = new byte[2048]; int readLen = 0; while ((readLen = inMs.Read(readBuffer, 0, readBuffer.Length)) > 0) { zOut.Write(readBuffer, 0, readLen); } zOut.Flush(); outMs.Seek(0, SeekOrigin.Begin); byte[] decompressedBuf = outMs.GetBuffer(); decodedMeshOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf); } } } } catch (Exception e) { MainConsole.Instance.Error("[MESH]: exception decoding physical mesh: " + e); return null; } OSDArray decodedMeshOsdArray = null; // physics_shape is an array of OSDMaps, one for each submesh if (decodedMeshOsd is OSDArray) { decodedMeshOsdArray = (OSDArray) decodedMeshOsd; foreach (OSD subMeshOsd in decodedMeshOsdArray) { if (subMeshOsd is OSDMap) { OSDMap subMeshMap = (OSDMap) subMeshOsd; // As per http://wiki.secondlife.com/wiki/Mesh/Mesh_Asset_Format, some Mesh Level // of Detail Blocks (maps) contain just a NoGeometry key to signal there is no // geometry for this submesh. if (subMeshMap.ContainsKey("NoGeometry") && (subMeshMap["NoGeometry"])) continue; Vector3 posMax = new Vector3(0.5f, 0.5f, 0.5f); Vector3 posMin = new Vector3(-0.5f, -0.5f, -0.5f); if (subMeshMap.ContainsKey("PositionDomain")) //Optional, so leave the max and min values otherwise { posMax = ((OSDMap) subMeshMap["PositionDomain"])["Max"].AsVector3(); posMin = ((OSDMap) subMeshMap["PositionDomain"])["Min"].AsVector3(); } ushort faceIndexOffset = (ushort) coords.Count; byte[] posBytes = subMeshMap["Position"].AsBinary(); for (int i = 0; i < posBytes.Length; i += 6) { ushort uX = Utils.BytesToUInt16(posBytes, i); ushort uY = Utils.BytesToUInt16(posBytes, i + 2); ushort uZ = Utils.BytesToUInt16(posBytes, i + 4); Coord c = new Coord( Utils.UInt16ToFloat(uX, posMin.X, posMax.X)*size.X, Utils.UInt16ToFloat(uY, posMin.Y, posMax.Y)*size.Y, Utils.UInt16ToFloat(uZ, posMin.Z, posMax.Z)*size.Z); coords.Add(c); } byte[] triangleBytes = subMeshMap["TriangleList"].AsBinary(); for (int i = 0; i < triangleBytes.Length; i += 6) { ushort v1 = (ushort) (Utils.BytesToUInt16(triangleBytes, i) + faceIndexOffset); ushort v2 = (ushort) (Utils.BytesToUInt16(triangleBytes, i + 2) + faceIndexOffset); ushort v3 = (ushort) (Utils.BytesToUInt16(triangleBytes, i + 4) + faceIndexOffset); Face f = new Face(v1, v2, v3); faces.Add(f); } } } } } } else { if (cacheSculptMaps && primShape.SculptTexture != UUID.Zero) { decodedSculptFileName = System.IO.Path.Combine(decodedSculptMapPath, "smap_" + primShape.SculptTexture.ToString()); try { if (File.Exists(decodedSculptFileName)) { idata = Image.FromFile(decodedSculptFileName); } } catch (Exception e) { MainConsole.Instance.Error("[SCULPT]: unable to load cached sculpt map " + decodedSculptFileName + " " + e); } //if (idata != null) // MainConsole.Instance.Debug("[SCULPT]: loaded cached map asset for map ID: " + primShape.SculptTexture.ToString()); } if (idata == null) { if (primShape.SculptData == null || primShape.SculptData.Length == 0) return null; try { idata = m_j2kDecoder.DecodeToImage(primShape.SculptData); if (idata != null && cacheSculptMaps && (cacheSculptAlphaMaps || (((ImageFlags) (idata.Flags) & ImageFlags.HasAlpha) == 0))) { try { idata.Save(decodedSculptFileName, ImageFormat.MemoryBmp); } catch (Exception e) { MainConsole.Instance.Error("[SCULPT]: unable to cache sculpt map " + decodedSculptFileName + " " + e); } } } catch (DllNotFoundException) { MainConsole.Instance.Error( "[PHYSICS]: OpenJpeg is not installed correctly on this system. Physics Proxy generation failed. Often times this is because of an old version of GLIBC. You must have version 2.4 or above!"); return null; } catch (IndexOutOfRangeException) { MainConsole.Instance.Error( "[PHYSICS]: OpenJpeg was unable to decode this. Physics Proxy generation failed"); return null; } catch (Exception ex) { MainConsole.Instance.Error( "[PHYSICS]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed: " + ex); return null; } } SculptMesh.SculptType sculptType; switch ((SculptType) primShape.SculptType) { case SculptType.Cylinder: sculptType = SculptMesh.SculptType.cylinder; break; case SculptType.Plane: sculptType = SculptMesh.SculptType.plane; break; case SculptType.Torus: sculptType = SculptMesh.SculptType.torus; break; case SculptType.Sphere: sculptType = SculptMesh.SculptType.sphere; break; default: sculptType = SculptMesh.SculptType.plane; break; } bool mirror = ((primShape.SculptType & 128) != 0); bool invert = ((primShape.SculptType & 64) != 0); if (idata == null) return null; sculptMesh = new SculptMesh((Bitmap) idata, sculptType, (int) lod, false, mirror, invert); idata.Dispose(); idata = null; sculptMesh.DumpRaw(baseDir, primName, "primMesh"); sculptMesh.Scale(size.X, size.Y, size.Z); coords = sculptMesh.coords; faces = sculptMesh.faces; } } else { float pathShearX = primShape.PathShearX < 128 ? primShape.PathShearX*0.01f : (primShape.PathShearX - 256)*0.01f; float pathShearY = primShape.PathShearY < 128 ? primShape.PathShearY*0.01f : (primShape.PathShearY - 256)*0.01f; float pathBegin = primShape.PathBegin*2.0e-5f; float pathEnd = 1.0f - primShape.PathEnd*2.0e-5f; float pathScaleX = (primShape.PathScaleX - 100)*0.01f; float pathScaleY = (primShape.PathScaleY - 100)*0.01f; float profileBegin = primShape.ProfileBegin*2.0e-5f; float profileEnd = 1.0f - primShape.ProfileEnd*2.0e-5f; float profileHollow = primShape.ProfileHollow*2.0e-5f; if (profileHollow > 0.95f) { if (profileHollow > 0.99f) profileHollow = 0.99f; float sizeX = primShape.Scale.X - (primShape.Scale.X*profileHollow); if (sizeX < 0.1f) //If its > 0.1, its fine to mesh at the small hollow profileHollow = 0.95f + (sizeX/2); //Scale the rest by how large the size of the prim is } int sides = 4; switch ((primShape.ProfileCurve & 0x07)) { case (byte) ProfileShape.EquilateralTriangle: sides = 3; break; case (byte) ProfileShape.Circle: sides = 24; break; case (byte) ProfileShape.HalfCircle: sides = 24; profileBegin = 0.5f*profileBegin + 0.5f; profileEnd = 0.5f*profileEnd + 0.5f; break; } int hollowSides = sides; switch (primShape.HollowShape) { case HollowShape.Circle: hollowSides = 24; break; case HollowShape.Square: hollowSides = 4; break; case HollowShape.Triangle: hollowSides = 3; break; } primMesh = new PrimMesh(sides, profileBegin, profileEnd, profileHollow, hollowSides); if (primMesh.errorMessage != null) if (primMesh.errorMessage.Length > 0) MainConsole.Instance.Error("[ERROR] " + primMesh.errorMessage); primMesh.topShearX = pathShearX; primMesh.topShearY = pathShearY; primMesh.pathCutBegin = pathBegin; primMesh.pathCutEnd = pathEnd; if (primShape.PathCurve == (byte) Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible) { primMesh.twistBegin = primShape.PathTwistBegin*18/10; primMesh.twistEnd = primShape.PathTwist*18/10; primMesh.taperX = pathScaleX; primMesh.taperY = pathScaleY; if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f) { ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh); if (profileBegin < 0.0f) profileBegin = 0.0f; if (profileEnd > 1.0f) profileEnd = 1.0f; } #if SPAM MainConsole.Instance.Debug("****** PrimMesh Parameters (Linear) ******\n" + primMesh.ParamsToDisplayString()); #endif try { primMesh.Extrude(primShape.PathCurve == (byte) Extrusion.Straight ? PathType.Linear : PathType.Flexible); } catch (Exception ex) { ReportPrimError("Extrusion failure: exception: " + ex, primName, primMesh); return null; } } else { primMesh.holeSizeX = (200 - primShape.PathScaleX)*0.01f; primMesh.holeSizeY = (200 - primShape.PathScaleY)*0.01f; primMesh.radius = 0.01f*primShape.PathRadiusOffset; primMesh.revolutions = 1.0f + 0.015f*primShape.PathRevolutions; primMesh.skew = 0.01f*primShape.PathSkew; primMesh.twistBegin = primShape.PathTwistBegin*36/10; primMesh.twistEnd = primShape.PathTwist*36/10; primMesh.taperX = primShape.PathTaperX*0.01f; primMesh.taperY = primShape.PathTaperY*0.01f; if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f) { ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh); if (profileBegin < 0.0f) profileBegin = 0.0f; if (profileEnd > 1.0f) profileEnd = 1.0f; } #if SPAM MainConsole.Instance.Debug("****** PrimMesh Parameters (Circular) ******\n" + primMesh.ParamsToDisplayString()); #endif try { primMesh.Extrude(PathType.Circular); } catch (Exception ex) { ReportPrimError("Extrusion failure: exception: " + ex, primName, primMesh); return null; } } primMesh.DumpRaw(baseDir, primName, "primMesh"); primMesh.Scale(size.X, size.Y, size.Z); coords = primMesh.coords; faces = primMesh.faces; primMesh = null; } Mesh mesh = new Mesh(key); //mesh.m_triangles = faces; //mesh.m_vertices = coords; // Add the corresponding triangles to the mesh mesh.Set(coords, faces); coords.Clear(); faces.Clear(); coords = null; faces = null; return mesh; }
public static void Deflate(Stream input, Stream output) { var zoutput = new ZOutputStream(output); var inputReader = new BinaryReader(input); zoutput.Write(inputReader.ReadBytes((int)input.Length), 0, (int)input.Length); zoutput.Flush(); }