Ejemplo n.º 1
0
 /// <summary>
 /// Wraps the given stream in a compression stream.
 /// </summary>
 /// <param name="output">Stream to wrap.</param>
 /// <returns>Compression stream to which data can be written.</returns>
 public static Stream CompressStream(Stream output)
 {
     Stream result = new GZipStream(output, CompressionMode.Compress);
     result.WriteByte(0xff & (MagicNumber >> 24));
     result.WriteByte(0xff & (MagicNumber >> 16));
     result.WriteByte(0xff & (MagicNumber >> 8));
     result.WriteByte(0xff & (MagicNumber));
     return result;
 }
Ejemplo n.º 2
0
        public static void Save(Level level, string file) {
            using (Stream fs = File.Create(file),
                   gs = new GZipStream(fs, CompressionMode.Compress, true))
            {
                byte[] header = new byte[16];
                BitConverter.GetBytes(1874).CopyTo(header, 0);
                gs.Write(header, 0, 2);

                BitConverter.GetBytes(level.Width).CopyTo(header, 0);
                BitConverter.GetBytes(level.Length).CopyTo(header, 2);
                BitConverter.GetBytes(level.Height).CopyTo(header, 4);
                BitConverter.GetBytes(level.spawnx).CopyTo(header, 6);
                BitConverter.GetBytes(level.spawnz).CopyTo(header, 8);
                BitConverter.GetBytes(level.spawny).CopyTo(header, 10);
                header[12] = level.rotx;
                header[13] = level.roty;
                header[14] = (byte)level.permissionvisit;
                header[15] = (byte)level.permissionbuild;
                gs.Write(header, 0, header.Length);
                byte[] blocks = level.blocks;
                byte[] convBlocks = new byte[blocks.Length];

                for (int i = 0; i < blocks.Length; ++i) {
                    byte block = blocks[i];
                    if (block < Block.CpeCount) {
                        convBlocks[i] = block; //CHANGED THIS TO INCOPARATE SOME MORE SPACE THAT I NEEDED FOR THE door_orange_air ETC.
                    } else {
                        convBlocks[i] = Block.SaveConvert(block);
                    }
                }
                gs.Write(convBlocks, 0, convBlocks.Length);
                
                // write out new blockdefinitions data
                gs.WriteByte(0xBD);
                int index = 0;
                for (int y = 0; y < level.ChunksY; y++)
                	for (int z = 0; z < level.ChunksZ; z++)
                		for (int x = 0; x < level.ChunksX; x++)
                {
                    byte[] chunk = level.CustomBlocks[index];
                    if (chunk == null) {
                        gs.WriteByte(0);
                    } else {
                        gs.WriteByte(1);
                        gs.Write(chunk, 0, chunk.Length);
                    }
                    index++;
                }
            }
        }
        public async Task ConcatenatedEmptyGzipStreams()
        {
            const int copyToBufferSizeRequested = 0x8000;

            // we'll request a specific size buffer, but we cannot guarantee that's the size
            // that will be used since CopyTo will rent from the array pool
            // take advantage of this knowledge to find out what size it will actually use
            var rentedBuffer = ArrayPool <byte> .Shared.Rent(copyToBufferSizeRequested);

            int actualBufferSize = rentedBuffer.Length;

            ArrayPool <byte> .Shared.Return(rentedBuffer);

            // use 3 buffers-full so that we can prime the stream with the first buffer-full,
            // test that CopyTo successfully flushes this at the beginning of the operation,
            // then populates the second buffer-full and reads its entirety despite every
            // payload being 0 length before it reads the final buffer-full.
            int minCompressedSize = 3 * actualBufferSize;

            using (Stream compressedStream = new DerivedMemoryStream())
            {
                using (var gz = new GZipStream(compressedStream, CompressionLevel.NoCompression, leaveOpen: true))
                {
                    // write one byte in order to allow us to prime the inflater buffer
                    gz.WriteByte(3);
                }

                while (compressedStream.Length < minCompressedSize)
                {
                    using (var gz = new GZipStream(compressedStream, CompressionLevel.NoCompression, leaveOpen: true))
                    {
                        gz.Write(Array.Empty <byte>());
                    }
                }

                compressedStream.Seek(0, SeekOrigin.Begin);
                using (Stream gz = new GZipStream(compressedStream, CompressionMode.Decompress, leaveOpen: true))
                    using (Stream decompressedData = new DerivedMemoryStream())
                    {
                        // read one byte in order to fill the inflater bufffer before copy
                        Assert.Equal(3, gz.ReadByte());

                        gz.CopyTo(decompressedData, copyToBufferSizeRequested);
                        Assert.Equal(0, decompressedData.Length);
                    }

                compressedStream.Seek(0, SeekOrigin.Begin);
                using (Stream gz = new GZipStream(compressedStream, CompressionMode.Decompress, leaveOpen: true))
                    using (Stream decompressedData = new DerivedMemoryStream())
                    {
                        // read one byte in order to fill the inflater bufffer before copy
                        Assert.Equal(3, gz.ReadByte());

                        await gz.CopyToAsync(decompressedData, copyToBufferSizeRequested);

                        Assert.Equal(0, decompressedData.Length);
                    }
            }
        }
Ejemplo n.º 4
0
 static void CompressFile(string inFilename, string outFilename)
 {
     FileStream sourceFile = File.OpenRead(inFilename);
     FileStream destFile = File.Create(outFilename);
     GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress);
     int theByte = sourceFile.ReadByte();
     while (theByte != -1)
     {
         compStream.WriteByte((byte)theByte);
         theByte = sourceFile.ReadByte();
     }
     sourceFile.Close();
     destFile.Close();
     compStream.Close();
 }
Ejemplo n.º 5
0
        public byte[] Compress(byte[] fileBytes)
        {
            byte[] bytes;

            using (MemoryStream fileStream = new MemoryStream(fileBytes)) {
                using (MemoryStream compressedStream = new MemoryStream()) {
                    using (GZipStream zipStream = new GZipStream(compressedStream, CompressionMode.Compress)) {
                        int value;
                        while ((value = fileStream.ReadByte()) != -1) {
                            zipStream.WriteByte((byte) value);
                        }
                        zipStream.Close();
                        bytes = compressedStream.ToArray();
                    }
                }
            }

            return bytes;
        }
Ejemplo n.º 6
0
        static void Main()
        {
            // Создание файла и архива.
            FileStream source = File.OpenRead(@"D:\test.txt");
            FileStream destination = File.Create(@"D:\archive.zip");

            // Создание компрессора.
            GZipStream compressor = new GZipStream(destination, CompressionMode.Compress);

            // Заполнение архива информацией из файла.
            int theByte = source.ReadByte();
            while (theByte != -1)
            {
                compressor.WriteByte((byte)theByte);
                theByte = source.ReadByte();
            }

            // Удаление компрессора.
            compressor.Close();
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            FileStream sourceFile = File.OpenRead(@"d.txt");
            FileStream destFile = File.Create(@"sample.zip");

            GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress);

            try
            {
                int theByte = sourceFile.ReadByte();
                while (theByte != -1)
                {
                    compStream.WriteByte((byte)theByte);
                    theByte = sourceFile.ReadByte();
                }
            }
            finally
            {
                compStream.Dispose();
            } 
        }
Ejemplo n.º 8
0
		// Compresses the given file, and optionally deletes the source file when finished
		private void CompressFile(string fileName, bool deleteFile = true)
		{
			// zip up the file, taking the compression level from the configuration
			var zipFileName = String.Format(ZipPattern, fileName);

			using (var fileStream = File.OpenRead(fileName))
			using (var destFile = File.Create(zipFileName))
			using (var compStream = new GZipStream(destFile, CompressionLevel.Optimal))
			{
				int theByte = fileStream.ReadByte();
				while (theByte != -1)
				{
					compStream.WriteByte((byte)theByte);
					theByte = fileStream.ReadByte();
				}
			}

			if (deleteFile)
				File.Delete(fileName);
		}
Ejemplo n.º 9
0
 public void ToStream(Stream writestream)
 {
     GZipStream gZipStream = null;
         try
         {
             System.Windows.MessageBox.Show(Convert.ToString(this.Filedata.Length));
             gZipStream = new GZipStream(writestream, CompressionMode.Compress, true);
             gZipStream.Write(this.Filedata, 0, (int)this.Filedata.Length);
             gZipStream.WriteByte(255);
             //gZipStream.Write(this.Screenshot, 0, (int)this.Screenshot.Length);
         }
         finally
         {
             if (gZipStream != null)
             {
                 gZipStream.Close();
             }
         }
         return;
 }
Ejemplo n.º 10
0
        private async Task TestConcatenatedGzipStreams(int streamCount, bool useAsync, bool useReadByte, int bufferSize, int bytesPerStream = 1)
        {
            using (var correctDecompressedOutput = new MemoryStream())
                using (var compressedStream = new MemoryStream())
                    using (var decompressorOutput = new MemoryStream())
                    {
                        for (int i = 0; i < streamCount; i++)
                        {
                            using (var gz = new GZipStream(compressedStream, CompressionLevel.NoCompression, true))
                            {
                                for (int j = 0; j < bytesPerStream; j++)
                                {
                                    byte b = (byte)((i * j) % 256);
                                    gz.WriteByte(b);
                                    correctDecompressedOutput.WriteByte(b);
                                }
                            }
                        }
                        compressedStream.Seek(0, SeekOrigin.Begin);

                        var decompressor = CreateStream(compressedStream, CompressionMode.Decompress);
                        //Thread.Sleep(10000);

                        var  bytes = new byte[bufferSize];
                        bool finished = false;
                        int  retCount = 0, totalRead = 0;
                        while (!finished)
                        {
                            if (useAsync)
                            {
                                try
                                {
                                    retCount = await decompressor.ReadAsync(bytes, 0, bufferSize);

                                    totalRead += retCount;
                                    if (retCount != 0)
                                    {
                                        await decompressorOutput.WriteAsync(bytes, 0, retCount);
                                    }
                                    else
                                    {
                                        finished = true;
                                    }
                                }
                                catch (Exception)
                                {
                                    throw new Exception(retCount + " " + totalRead);
                                }
                            }
                            else if (useReadByte)
                            {
                                int b = decompressor.ReadByte();

                                if (b != -1)
                                {
                                    decompressorOutput.WriteByte((byte)b);
                                }
                                else
                                {
                                    finished = true;
                                }
                            }
                            else
                            {
                                retCount = decompressor.Read(bytes, 0, bufferSize);

                                if (retCount != 0)
                                {
                                    decompressorOutput.Write(bytes, 0, retCount);
                                }
                                else
                                {
                                    finished = true;
                                }
                            }
                        }
                        decompressor.Dispose();
                        decompressorOutput.Position = 0;

                        byte[] decompressorOutputBytes = decompressorOutput.ToArray();
                        byte[] correctOutputBytes      = correctDecompressedOutput.ToArray();

                        Assert.Equal(correctOutputBytes.Length, decompressorOutputBytes.Length);
                        for (int i = 0; i < correctOutputBytes.Length; i++)
                        {
                            Assert.Equal(correctOutputBytes[i], decompressorOutputBytes[i]);
                        }
                    }
        }
Ejemplo n.º 11
0
        internal void FullSave()
        {
            /*
             * All we need to do here is dump our level blocks to the file
             *
             * we dont need to close the filehandle for the uncompressed version
             */

            Server.Log("Full Save Directory check...", LogTypesEnum.debug);
            DirectoryCheck();

            Server.Log("Backup old file...", LogTypesEnum.debug);
            if (File.Exists(fileName + compressedExtension))
            {
                if (File.Exists(fileName + compressedExtension + backupExtension)) File.Delete(fileName + compressedExtension + backupExtension);
                File.Copy(fileName + compressedExtension, fileName + compressedExtension + backupExtension);
            }

            Server.Log("Saving new File...", LogTypesEnum.debug);
            FileStream fileStream = new FileStream(compressedPath, FileMode.Create);
            GZipStream gzipStream = new GZipStream(fileStream, CompressionMode.Compress);

            gzipStream.Write(encode.GetBytes(name.PadRight(64)), 0, 64);
            gzipStream.Write(BitConverter.GetBytes(sizeX), 0, 2);
            gzipStream.Write(BitConverter.GetBytes(sizeY), 0, 2);
            gzipStream.Write(BitConverter.GetBytes(sizeZ), 0, 2);
            gzipStream.Write(BitConverter.GetBytes(spawnPos.x), 0, 2);
            gzipStream.Write(BitConverter.GetBytes(spawnPos.y), 0, 2);
            gzipStream.Write(BitConverter.GetBytes(spawnPos.z), 0, 2);
            gzipStream.WriteByte(spawnPos.pitch);
            gzipStream.WriteByte(spawnPos.yaw);
            gzipStream.Write(BitConverter.GetBytes(physics.isEnabled), 0, 1);
            gzipStream.Write(BitConverter.GetBytes(physics.realistic), 0, 1);

            gzipStream.Write(blocks, 0, blocks.Length);

            gzipStream.Flush();
            gzipStream.Close();
            //fileStream.Flush();
            fileStream.Close();

            Console.WriteLine("Done?");
        }
        private async Task TestConcatenatedGzipStreams(int streamCount, TestScenario scenario, int bufferSize, int bytesPerStream = 1)
        {
            bool isCopy = scenario == TestScenario.Copy || scenario == TestScenario.CopyAsync;

            using (MemoryStream correctDecompressedOutput = new MemoryStream())
                // For copy scenarios use a derived MemoryStream to avoid MemoryStream's Copy optimization
                // that turns the Copy into a single Write passing the backing buffer
                using (MemoryStream compressedStream = isCopy ? new DerivedMemoryStream() : new MemoryStream())
                    using (MemoryStream decompressorOutput = new MemoryStream())
                    {
                        for (int i = 0; i < streamCount; i++)
                        {
                            using (var gz = new GZipStream(compressedStream, CompressionLevel.NoCompression, true))
                            {
                                for (int j = 0; j < bytesPerStream; j++)
                                {
                                    byte b = (byte)((i * j) % 256);
                                    gz.WriteByte(b);
                                    correctDecompressedOutput.WriteByte(b);
                                }
                            }
                        }
                        compressedStream.Seek(0, SeekOrigin.Begin);

                        var decompressor = CreateStream(compressedStream, CompressionMode.Decompress);

                        var  bytes = new byte[bufferSize];
                        bool finished = false;
                        int  retCount = 0, totalRead = 0;
                        while (!finished)
                        {
                            switch (scenario)
                            {
                            case TestScenario.ReadAsync:
                                try
                                {
                                    retCount = await decompressor.ReadAsync(bytes, 0, bufferSize);

                                    totalRead += retCount;
                                    if (retCount != 0)
                                    {
                                        await decompressorOutput.WriteAsync(bytes, 0, retCount);
                                    }
                                    else
                                    {
                                        finished = true;
                                    }
                                }
                                catch (Exception)
                                {
                                    throw new Exception(retCount + " " + totalRead);
                                }
                                break;

                            case TestScenario.ReadByte:
                                int b = decompressor.ReadByte();

                                if (b != -1)
                                {
                                    decompressorOutput.WriteByte((byte)b);
                                }
                                else
                                {
                                    finished = true;
                                }

                                break;

                            case TestScenario.Read:
                                retCount = decompressor.Read(bytes, 0, bufferSize);

                                if (retCount != 0)
                                {
                                    decompressorOutput.Write(bytes, 0, retCount);
                                }
                                else
                                {
                                    finished = true;
                                }

                                break;

                            case TestScenario.Copy:
                                decompressor.CopyTo(decompressorOutput, bufferSize);
                                finished = true;
                                break;

                            case TestScenario.CopyAsync:
                                await decompressor.CopyToAsync(decompressorOutput, bufferSize);

                                finished = true;
                                break;
                            }
                        }
                        decompressor.Dispose();
                        decompressorOutput.Position = 0;

                        byte[] decompressorOutputBytes = decompressorOutput.ToArray();
                        byte[] correctOutputBytes      = correctDecompressedOutput.ToArray();

                        Assert.Equal(correctOutputBytes.Length, decompressorOutputBytes.Length);
                        for (int i = 0; i < correctOutputBytes.Length; i++)
                        {
                            Assert.Equal(correctOutputBytes[i], decompressorOutputBytes[i]);
                        }
                    }
        }
        static void Slice(string sourceFile, string destinationDirectory, int parts)
        {
            int partsCounter = 0;
            int dotPosition = sourceFile.LastIndexOf('.');
            int slashPosition = sourceFile.LastIndexOf('\\');
            string sourceFileName = sourceFile.Substring(slashPosition + 1, dotPosition - slashPosition - 1);
            string sourceFileExtension = sourceFile.Substring(dotPosition);
            if (destinationDirectory.LastIndexOf('\\') != destinationDirectory.Length - 1)
            {
                destinationDirectory += "\\";
            }

            using (FileStream source = new FileStream(sourceFile, FileMode.Open, FileAccess.ReadWrite))
            {
                long partSize = source.Length / parts;
                while (partsCounter < parts)
                {
                    source.Position = partsCounter * partSize;
                    using (FileStream destination = new FileStream(destinationDirectory + sourceFileName + "-part" + partsCounter + sourceFileExtension + ".gz", FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        using (GZipStream compressionStream = new GZipStream(destination,CompressionLevel.Optimal))
                        {
                            long byteCounter = 0;
                            while (byteCounter <= partSize)
                            {
                                compressionStream.WriteByte((byte)source.ReadByte());
                                byteCounter++;
                            }
                        }
                    }
                    partsCounter++;
                }
            }
            Console.WriteLine("The file was sliced successfully.");
        }
Ejemplo n.º 14
0
 public void Save(string outpath)
 {
     #if WIN32
     {
         string file = System.IO.Path.Combine(outpath, "seeds.bin.bytes");
         if (System.IO.Directory.Exists(outpath) == false)
         {
             System.IO.Directory.CreateDirectory(outpath);
         }
         using (System.IO.Stream os = System.IO.File.Create(file))
         {
     #if USECompression
             using (GZipStream s = new GZipStream(os, CompressionMode.Compress))
     #else
             var s = os;
     #endif
             {
                 UInt16 len=(UInt16) seeds.Count;
                 s.Write(BitConverter.GetBytes(len), 0, 2);
                 foreach (var i in seeds)
                 {
                     byte[] sb = System.Text.Encoding.UTF8.GetBytes(i.Key);
                     s.WriteByte((byte)sb.Length);
                     s.Write(sb, 0, sb.Length);
                     i.Value.Write(s);
                 }
             }
         }
     }
     string flist = "";
     foreach (var i in anims)
     {
         string file = System.IO.Path.Combine(outpath, i.Key + ".anim.bin");
         using (System.IO.Stream s = System.IO.File.Create(file+".bytes"))
         {
             i.Value.Write(s);
         }
         flist += file + "\r\n";
     }
     System.IO.File.WriteAllText(System.IO.Path.Combine(outpath, "anims.txt"), flist);
     #endif
 }
Ejemplo n.º 15
0
        public static byte[] GZip(byte[] mapSize, byte[] levelData)
        {
            var ms = new MemoryStream();
            var gs = new GZipStream(ms, CompressionMode.Compress, true);
            gs.Write(mapSize, 0, mapSize.Length);
            //gs.Write(levelData, 0, levelData.Length);

            int currentstart = 0;

            for (int i = 0; i < levelData.Length; i++ )
            {
                byte block = levelData[i];
                if(block>49)
                {
                    if(i>0) gs.Write(levelData, currentstart, (i-currentstart));
                    currentstart = i + 1;

                    gs.WriteByte((Block.Blocks.ContainsKey(block) ? Block.Blocks[block].BaseType : (byte)0));
                }

            }

            if (currentstart != levelData.Length)
            {
                gs.Write(levelData, currentstart, (levelData.Length - currentstart));
            }

            gs.Flush();
            gs.Dispose();

            ms.Position = 0;
            var bytes = new byte[ms.Length];
            ms.Read(bytes, 0, (int) ms.Length);
            ms.Close();
            ms.Dispose();
            return bytes;
        }
Ejemplo n.º 16
0
        public void FullSave()
        {
            /*
             * All we need to do here is dump our level blocks to the file
             *
             * we dont need to close the filehandle for the uncompressed version
             */

            Server.Log("Full Save Directory check...", LogTypesEnum.Debug);
            DirectoryCheck();

            Server.Log("Backup old file...", LogTypesEnum.Debug);
            if (File.Exists(FileName + CompressedExtension))
            {
                if (File.Exists(FileName + CompressedExtension + BackupExtension))
                    File.Delete(FileName + CompressedExtension + BackupExtension);
                File.Copy(FileName + CompressedExtension, FileName + CompressedExtension + BackupExtension);
            }

            Server.Log("Saving new File...", LogTypesEnum.Debug);
            var fileStream = new FileStream(CompressedPath, FileMode.Create);
            var gzipStream = new GZipStream(fileStream, CompressionMode.Compress);

            gzipStream.Write(_encode.GetBytes(Name.PadRight(64)), 0, 64);
            gzipStream.Write(BitConverter.GetBytes(SizeX), 0, 2);
            gzipStream.Write(BitConverter.GetBytes(SizeY), 0, 2);
            gzipStream.Write(BitConverter.GetBytes(SizeZ), 0, 2);
            gzipStream.Write(BitConverter.GetBytes(SpawnPos.X), 0, 2);
            gzipStream.Write(BitConverter.GetBytes(SpawnPos.Y), 0, 2);
            gzipStream.Write(BitConverter.GetBytes(SpawnPos.Z), 0, 2);
            gzipStream.WriteByte(SpawnPos.Pitch);
            gzipStream.WriteByte(SpawnPos.Yaw);
            gzipStream.Write(BitConverter.GetBytes(Physics.IsEnabled), 0, 1);
            gzipStream.Write(BitConverter.GetBytes(Physics.Realistic), 0, 1);
            gzipStream.WriteByte(BuildPermissions);
            gzipStream.WriteByte(VisitPermissions);

            gzipStream.Write(BlockData, 0, BlockData.Length);

            gzipStream.Flush();
            gzipStream.Close();
            //fileStream.Flush();
            fileStream.Close();

            Console.WriteLine("Done?");
        }
Ejemplo n.º 17
0
        public void Backup()
        {
            if (((TimeSpan)(DateTime.Now - lastSaveTime)).TotalSeconds > 600) return; //Don't back up if the map hasn't changed in 10 minutes
            try
            {
                string name = "backups/" + this.name + "/" + DateTime.Now.ToFileTime().ToString();
                string filename = name + ".umw";
                byte[] saveblocks = new byte[blocks.Length];
                blocks.CopyTo(saveblocks, 0);
                for (int i = 0; i < saveblocks.Length; i++)
                {
                    switch (saveblocks[i])
                    {
                        case Blocks.unflood:
                            saveblocks[i] = Blocks.ConvertType(saveblocks[i]);
                            break;
                        default:
                            break;
                    }
                }

                if (!Directory.Exists("backups/" + this.name)) Directory.CreateDirectory("backups/" + this.name);

                GZipStream gzout = new GZipStream(new FileStream("maps/" + filename, FileMode.OpenOrCreate), CompressionMode.Compress);
                gzout.Write(BitConverter.GetBytes(0xebabefac), 0, 4);
                gzout.Write(BitConverter.GetBytes(width), 0, 2);
                gzout.Write(BitConverter.GetBytes(height), 0, 2);
                gzout.Write(BitConverter.GetBytes(depth), 0, 2);
                gzout.Write(BitConverter.GetBytes(spawnx), 0, 2);
                gzout.Write(BitConverter.GetBytes(spawny), 0, 2);
                gzout.Write(BitConverter.GetBytes(spawnz), 0, 2);
                gzout.WriteByte(this.srotx);
                gzout.WriteByte(this.sroty);
                gzout.Write(saveblocks, 0, saveblocks.Length);

                //gzout.BaseStream.Close();
                gzout.Close();

                StreamWriter mBlocksOut = new StreamWriter(File.Open("maps/" + name + ".mb", FileMode.Create));
                foreach (KeyValuePair<int, string> mb in this.messageBlocks)
                {
                    mBlocksOut.WriteLine(mb.Key + " " + mb.Value);
                }
                mBlocksOut.Close();

                StreamWriter tBlocksOut = new StreamWriter(File.Open("maps/" + name + ".tb", FileMode.Create));
                foreach (KeyValuePair<int, int> tb in this.teleportBlocks)
                {
                    tBlocksOut.WriteLine(tb.Key + " " + tb.Value);
                }
                tBlocksOut.Close();

                Program.server.logger.log("Level \"" + this.name + "\" backed up");
            }
            catch (Exception e)
            {
                Program.server.logger.log("Error occurred while backing up map", Logger.LogType.Error);
                Program.server.logger.log(e);
            }
        }
Ejemplo n.º 18
0
        public void Save()
        {
            if (!blockChanged) return; //Don't save if nothing happened
            try
            {
                byte[] saveblocks = new byte[blocks.Length];
                blocks.CopyTo(saveblocks, 0);
                for (int i = 0; i < saveblocks.Length; i++)
                {
                    switch (saveblocks[i])
                    {
                        case Blocks.unflood:
                            saveblocks[i] = Blocks.ConvertType(saveblocks[i]);
                            break;
                        case Blocks.doorOpen:
                            saveblocks[i] = Blocks.door;
                            break;
                        default:
                            break;
                    }
                }

                GZipStream gzout = new GZipStream(new FileStream("maps/" + filename, FileMode.OpenOrCreate), CompressionMode.Compress);
                gzout.Write(BitConverter.GetBytes(0xebabefac), 0, 4);
                gzout.Write(BitConverter.GetBytes(width), 0, 2);
                gzout.Write(BitConverter.GetBytes(height), 0, 2);
                gzout.Write(BitConverter.GetBytes(depth), 0, 2);
                gzout.Write(BitConverter.GetBytes(spawnx), 0, 2);
                gzout.Write(BitConverter.GetBytes(spawny), 0, 2);
                gzout.Write(BitConverter.GetBytes(spawnz), 0, 2);
                gzout.WriteByte(this.srotx);
                gzout.WriteByte(this.sroty);
                gzout.Write(saveblocks, 0, saveblocks.Length);

                //gzout.BaseStream.Close();
                gzout.Close();

                StreamWriter mBlocksOut = new StreamWriter(File.Open("maps/" + name + ".mb", FileMode.Create));
                foreach (KeyValuePair<int, string> mb in this.messageBlocks)
                {
                    mBlocksOut.WriteLine(mb.Key + " " + mb.Value);
                }
                mBlocksOut.Close();

                StreamWriter tBlocksOut = new StreamWriter(File.Open("maps/" + name + ".tb", FileMode.Create));
                foreach (KeyValuePair<int, int> tb in this.teleportBlocks)
                {
                    tBlocksOut.WriteLine(tb.Key + " " + tb.Value);
                }
                tBlocksOut.Close();

                Program.server.logger.log("Level \"" + this.name + "\" saved");
                lastSaveTime = DateTime.Now;
                blockChanged = false;
            }
            catch (Exception e)
            {
                Program.server.logger.log("Error occurred while saving map", Logger.LogType.Error);
                Program.server.logger.log(e);
            }
        }
Ejemplo n.º 19
0
        public static void Save(VoxelSprite sprite, ref Color[] swatches)
        {
            //StringBuilder sb = new StringBuilder();

            //using (StringWriter str = new StringWriter(sb))
            //{

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.AddExtension = true;
            sfd.DefaultExt = ".vxl";
            sfd.Filter = "Voxel Sprite|*.vxs";
            DialogResult dr = sfd.ShowDialog();

            if (string.IsNullOrEmpty(sfd.FileName) || dr != DialogResult.OK) return;

            using (FileStream str = new FileStream(sfd.FileName, FileMode.Create))
            {
                //str.Write(gameWorld.X_CHUNKS + "," + gameWorld.Y_CHUNKS + "," + gameWorld.Z_CHUNKS + "\n");
                using (GZipStream gzstr = new GZipStream(str, CompressionMode.Compress))
                {

                    gzstr.WriteByte(Convert.ToByte(sprite.X_SIZE));
                    gzstr.WriteByte(Convert.ToByte(sprite.Y_SIZE));
                    gzstr.WriteByte(Convert.ToByte(sprite.Z_SIZE));
                    gzstr.WriteByte(Convert.ToByte(sprite.AnimChunks.Count));

                    for (int i = 0; i < 10; i++)
                    {
                        gzstr.WriteByte(swatches[i].R);
                        gzstr.WriteByte(swatches[i].G);
                        gzstr.WriteByte(swatches[i].B);
                    }

                    foreach (AnimChunk c in sprite.AnimChunks)
                    {
                        //str.Write("C\n");

                        //Chunk c = gameWorld.Chunks[x, y, z];
                        for (int vx = 0; vx < sprite.X_SIZE; vx++)
                            for (int vy = 0; vy < sprite.Y_SIZE; vy++)
                                for (int vz = 0; vz < sprite.Z_SIZE; vz++)
                                {
                                    if (!c.Voxels[vx, vy, vz].Active) continue;

                                    //string vox = vx + "," + vy + "," + vz + ",";
                                    //vox += ((int)c.Voxels[vx, vy, vz].Type);
                                    //str.Write(vox + "\n");

                                    gzstr.WriteByte(Convert.ToByte(vx));
                                    gzstr.WriteByte(Convert.ToByte(vy));
                                    gzstr.WriteByte(Convert.ToByte(vz));
                                    gzstr.WriteByte(c.Voxels[vx, vy, vz].Color.R);
                                    gzstr.WriteByte(c.Voxels[vx, vy, vz].Color.G);
                                    gzstr.WriteByte(c.Voxels[vx, vy, vz].Color.B);
                                }
                        gzstr.WriteByte(Convert.ToByte('c'));

                    }
                    //str.Flush();

                }
            }
            //}

            //using (StreamWriter fs = new StreamWriter(fn))
            //{
            //    fs.Write(Compress(sb.ToString()));
            //    fs.Flush();
            //}

            //sb.Clear();
            //sb = null;

            GC.Collect();
        }
Ejemplo n.º 20
0
        public static void Main(string[] args)
        {
            List<FerriesRoute> _items = new List<FerriesRoute>();
            List<CacheFlushDate> _cacheFlushDate = new List<CacheFlushDate>();
            var serializer = new JsonSerializer();
            string cachedDateTime = "";

            // The Traveler Information Application Programming Interface is designed to provide third parties
            // with a single gateway to all of WSDOT's traveler information data. To use the WSDL services you
            // must be assigned an Access Code. You can obtain an Access Code by simply providing your email
            // address at the Traveler Information API site, http://www.wsdot.wa.gov/traffic/api/

            string API_ACCESS_CODE = "INSERT_YOUR_API_ACCESS_CODE_HERE";

            b2b.wsdot.wa.gov.WSFSchedule obj = new b2b.wsdot.wa.gov.WSFSchedule();

            try
            {
                using (var re = File.OpenText(@"WSFCacheFlushDateSchedules.js"))
                using (var reader = new JsonTextReader(re))
                {
                    var entries = serializer.Deserialize<CacheFlushDate[]>(reader);
                    cachedDateTime = entries[0].CacheDate.ToString();
                }
            }
            catch
            {
                Console.WriteLine("Error opening WSFCacheFlushDateSchedules.js file");
            }

            // Most web methods in this service are cached. Implementing caching in your program is recommended
            // in order to not query the web service when not necessary. GetCacheFlushDate() will tell you the
            // date and time that the cache was last flushed.
            System.DateTime dateTime = (System.DateTime) obj.GetCacheFlushDate();
            _cacheFlushDate.Add(new CacheFlushDate() {
                CacheDate = dateTime
            });

            // Write the most recent cache flush date and time to a JSON file.
            string jsonCacheDate = JsonConvert.SerializeObject(_cacheFlushDate);
            File.WriteAllText(@"WSFCacheFlushDateSchedules.js", jsonCacheDate);

            // Compare the cache dates. If dates are equal then we already have the most current data.
            if (!cachedDateTime.Equals(dateTime.ToString()))
            {
                // All method calls require the APIAccessHeader to pass a valid APIAccessCode.
                b2b.wsdot.wa.gov.APIAccessHeader apiAccessHeader = new b2b.wsdot.wa.gov.APIAccessHeader();
                apiAccessHeader.APIAccessCode = API_ACCESS_CODE;
                obj.APIAccessHeaderValue = apiAccessHeader;
                b2b.wsdot.wa.gov.TripDateMsg tripDateMsg = new b2b.wsdot.wa.gov.TripDateMsg();
                b2b.wsdot.wa.gov.RouteMsg routeMsg = new b2b.wsdot.wa.gov.RouteMsg();

                tripDateMsg.TripDate = DateTime.Today;

                // Provide all available routes for a particular date.
                b2b.wsdot.wa.gov.RouteBriefResponse[] routes = obj.GetAllRoutes(tripDateMsg);

                for (int i=0; i<routes.Length; i++)
                {
                    _items.Add(new FerriesRoute() {
                        RouteID = routes[i].RouteID,
                        Description = routes[i].Description
                    });

                    DateTime today = DateTime.Today;

                    for (int j=0; j<7; j++)
                    {
                        _items[i].Date.Add(new Dates() {
                            Date = today
                        });

                        routeMsg.RouteID = routes[i].RouteID;
                        routeMsg.TripDate = today;

                        // Retrieve sailing times associated with a specific route for a particular date.
                        b2b.wsdot.wa.gov.SchedResponse scheduleByRouteResults = obj.GetScheduleByRoute(routeMsg);

                        for (int k=0; k<scheduleByRouteResults.TerminalCombos.Length; k++)
                        {
                            _items[i].Date[j].Sailings.Add(new FerriesTerminal() {
                                DepartingTerminalID = scheduleByRouteResults.TerminalCombos[k].DepartingTerminalID,
                                DepartingTerminalName = scheduleByRouteResults.TerminalCombos[k].DepartingTerminalName,
                                ArrivingTerminalID = scheduleByRouteResults.TerminalCombos[k].ArrivingTerminalID,
                                ArrivingTerminalName = scheduleByRouteResults.TerminalCombos[k].ArrivingTerminalName
                            });

                            b2b.wsdot.wa.gov.TerminalComboMsg terminalComboMsg = new b2b.wsdot.wa.gov.TerminalComboMsg();
                            terminalComboMsg.TripDate = today;
                            terminalComboMsg.DepartingTerminalID = scheduleByRouteResults.TerminalCombos[k].DepartingTerminalID;
                            terminalComboMsg.ArrivingTerminalID = scheduleByRouteResults.TerminalCombos[k].ArrivingTerminalID;

                            // Retrieve sailing times associated with a specific departing / arriving terminal combination for a particular date.
                            b2b.wsdot.wa.gov.SchedResponse scheduleByTerminalComboResults = obj.GetScheduleByTerminalCombo(terminalComboMsg);

                            for (int l=0; l<scheduleByTerminalComboResults.TerminalCombos.Length; l++)
                            {
                                for (int m=0; m<scheduleByTerminalComboResults.TerminalCombos[l].Annotations.Length; m++)
                                {
                                    _items[i].Date[j].Sailings[k].Annotations.Add(scheduleByTerminalComboResults.TerminalCombos[l].Annotations[m]);
                                }

                                for (int n=0; n<scheduleByTerminalComboResults.TerminalCombos[l].Times.Length; n++)
                                {
                                    _items[i].Date[j].Sailings[k].Times.Add(new FerriesScheduleTimes() {
                                        DepartingTime = scheduleByTerminalComboResults.TerminalCombos[l].Times[n].DepartingTime
                                    });

                                    for (int o=0; o<scheduleByTerminalComboResults.TerminalCombos[l].Times[n].AnnotationIndexes.Length; o++)
                                    {
                                        _items[i].Date[j].Sailings[k].Times[n].AnnotationIndexes.Add(scheduleByTerminalComboResults.TerminalCombos[l].Times[n].AnnotationIndexes[o]);
                                    }
                                }
                            }
                        }

                        today = today.AddDays(1);
                    }

                }

                // Serialize the data object to a JSON file.
                string json = JsonConvert.SerializeObject(_items);
                File.WriteAllText(@"WSFRouteSchedules.js", json);

                FileStream sourceFile = File.OpenRead(@"WSFRouteSchedules.js");
                FileStream destFile = File.Create(@"WSFRouteSchedules.js.gz");

                // Now compress the JSON file so it is smaller to download.
                // Uncompressed the file is about 459 KB, compressed it drops to 25 KB. Nice.
                GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress);

                try
                {
                    int theByte = sourceFile.ReadByte();
                    while (theByte != -1)
                    {
                        compStream.WriteByte((byte)theByte);
                        theByte = sourceFile.ReadByte();
                    }
                }
                finally
                {
                    compStream.Dispose();
                }
            }
        }