示例#1
0
    IEnumerator Upload()
    {
        if (File.Exists(m_strErrorPath))
        {
            string totalFile = string.Empty;
            using (StreamReader reader = new StreamReader(m_strErrorPath, Encoding.UTF8, true))
            {
                totalFile = reader.ReadToEnd();
            }
            File.Delete(m_strErrorPath);
            byte[] buf = Encoding.UTF8.GetBytes(totalFile.ToCharArray());
            buf = CLZF2.Compress(buf);
            WWWForm form = new WWWForm();
            form.AddField("VERSION_CODE", VERSION_CODE);
            form.AddBinaryData("upload_file", buf, "error.txt", "text/plain");
            WWW www = new WWW(UPLOAD_URL, form);
            yield return(www);

            if (www.text != null)
            {
                Debug.Log(www.text);
            }
            if (www.error != null)
            {
                Debug.LogError(www.error);
            }
        }
    }
示例#2
0
        public void ModifySaveGame(int slot, string description)
        {
            Debug.Log("ModifySaveGame " + slot);
            SaveEntry saveInfoInSlot = saveManager.GetSaveInfoInSlot(slot);

            if (saveInfoInSlot != null)
            {
                byte[] array = File.ReadAllBytes(saveInfoInSlot.Path);
                MGHelper.KeyEncode(array);
                byte[]       buffer        = CLZF2.Decompress(array);
                MemoryStream memoryStream  = new MemoryStream(buffer);
                MemoryStream memoryStream2 = new MemoryStream();
                BinaryReader binaryReader  = new BinaryReader(memoryStream);
                BinaryWriter binaryWriter  = new BinaryWriter(memoryStream2);
                binaryWriter.Write(binaryReader.ReadBytes(16));
                binaryReader.ReadString();
                binaryWriter.Write(description);
                binaryWriter.Write(binaryReader.ReadBytes((int)(memoryStream.Length - memoryStream.Position)));
                byte[] inputBytes = memoryStream2.ToArray();
                memoryStream.Dispose();
                memoryStream2.Dispose();
                byte[] array2 = CLZF2.Compress(inputBytes);
                MGHelper.KeyEncode(array2);
                File.WriteAllBytes(saveInfoInSlot.Path, array2);
                saveManager.UpdateSaveSlot(slot);
            }
        }
示例#3
0
    // private void OnNewPitchBounds(object pitchBoundsObj)
    // {
    //     float[] pitchBounds = (float[])pitchBoundsObj;
    //     minPitch = pitchBounds[0];
    //     maxPitch = pitchBounds[1];
    // }

    private void OnMicrophonePitch(object pitchObj)
    {
        float?pitch = (float?)pitchObj;

        if (pitch.HasValue)
        {
            float roundedPitch = (float)Math.Round(pitch.Value, 1, MidpointRounding.AwayFromZero);
            pitchSamples.Add(roundedPitch);
        }
        else
        {
            pitchSamples.Add(0f);
        }

        if (pitchSamples.Count >= pitchSampleCount)
        {
            byte[] pitchRecentSamplesBytes = new byte[pitchSampleCount * 4];
            Buffer.BlockCopy(pitchSamples.ToArray(), pitchSamples.Count * 4 - pitchSampleCount * 4, pitchRecentSamplesBytes, 0, pitchRecentSamplesBytes.Length);

            byte[] compressedSamples = CLZF2.Compress(pitchRecentSamplesBytes);
            compressionRatio = (float)compressedSamples.Length / (float)pitchSampleCount;
            text.text        = compressionRatio.ToString("0.00");

            EventManager.TriggerEvent(EventTypes.Spookometer, compressionRatio);
        }
    }
示例#4
0
        public static int Serialize(ChunkData data, BinaryWriter writer, bool compress)
        {
            writer.Write(compress);
            writer.Write(data.IndexX);
            writer.Write(data.IndexY);
            writer.Write(data.IndexZ);
            writer.Write(data.Height);
            writer.Write(32768);
            writer.Write(data.Origin.x);
            writer.Write(data.Origin.y);
            writer.Write(data.Origin.z);
            var blockData    = new byte[0];
            var uncompressed = ChunkHelper.ToByteArray(data.Blocks.Data, Chunk.CHUNK_SIZE_X * Chunk.CHUNK_SIZE_Z * Chunk.CHUNK_SIZE_Y);

            if (compress)
            {
                blockData = CLZF2.Compress(uncompressed);
            }
            else
            {
                blockData = uncompressed;
            }
            writer.Write(blockData.Length);
            writer.Write(blockData);
            return((int)writer.BaseStream.Position);
        }
示例#5
0
    public void SavingComplexObject()
    {
        MyComplexObject[] MySaveItem = new MyComplexObject[1000];
        for (int i = 0; i < MySaveItem.Length; i++)
        {
            var item = new MyComplexObject();
            item.myPosition        = Vector3.one * i;
            item.myPositionHistory = new Vector3[100];
            item.myChatHistory     = new string[100];
            for (int j = 0; j < 100; j++)
            {
                item.myPositionHistory[j] = Vector3.one * j;
                item.myChatHistory[j]     = "Chat line: " + j;
            }
        }
        var mySaveObject = ObjectToByteArray(MySaveItem);

        byte[] compressed    = CLZF2.Compress(mySaveObject);
        byte[] decompressed  = CLZF2.Decompress(compressed);
        var    outSaveObject = ObjectToByteArray <MyComplexObject[]>(decompressed);

        Assert.AreEqual(mySaveObject.Length, decompressed.Length);
        Assert.AreEqual(mySaveObject, decompressed);
        Assert.AreEqual(outSaveObject, MySaveItem);
    }
示例#6
0
        public void SaveCellDataToFile(Cell[] cellData, string path)
        {
            if (container == null)
            {
                container          = ScriptableObject.CreateInstance <MapDataContainer>();
                container.CellData = cellData;
            }
            else
            {
                container.CellData = cellData;
            }

            Debug.Log("Saving cell data to : " + path);

            using (var ms = new MemoryStream(2000000))
                using (var bw = new BinaryWriter(ms))
                {
                    container.Serialize(bw);

                    var bytes = ms.ToArray();
                    var b2    = CLZF2.Compress(bytes);

                    var basePath = Path.GetDirectoryName(path);
                    if (!Directory.Exists(basePath))
                    {
                        Directory.CreateDirectory(basePath);
                    }

                    File.WriteAllBytes(path, b2);
                }
        }
示例#7
0
        public static void Encode(
            this short[] intensities,
            out byte[] spectra,
            out double tic,
            out double bpi,
            out int indexOfMaxIntensity, out int nonZeroCount)
        {
            // 16-bit integers are 2 bytes
            const int dataTypeSize = 2;

            spectra             = null;
            tic                 = 0;
            bpi                 = 0;
            indexOfMaxIntensity = 0;

            nonZeroCount = RlzEncode.Encode(intensities, out var runLengthZeroEncodedData, out tic, out bpi, out indexOfMaxIntensity);

            // Compress intensities
            var encodedDataLength = runLengthZeroEncodedData.Length;

            if (encodedDataLength > 0)
            {
                spectra = new byte[encodedDataLength * dataTypeSize];
                Buffer.BlockCopy(runLengthZeroEncodedData, 0, spectra, 0, encodedDataLength * dataTypeSize);
                spectra = CLZF2.Compress(spectra);
            }
        }
示例#8
0
 public static byte[] Pack(byte[] data, CompressionMode mode)
 {
     if (mode == CompressionMode.LZF)
     {
         return(CLZF2.Compress(data));
     }
     return(data);
 }
示例#9
0
        private void HashDataBuild(string outPath, HashInfo info)
        {
            var files = info.files.Keys.ToList <string>();
            var paths = new string[files.Count];

            for (var i = 0; i < files.Count; ++i)
            {
                paths[i] = GetPath(files[i]);
            }

            PatchData data = null;

            Object[] assets = GetMainAssets(paths);
            var      names  = new string[1];
            var      hash   = string.Empty;
            var      key    = string.Empty;

            byte[]     bytes   = null;
            byte[]     comps   = null;
            var        newPath = string.Empty;
            FileStream fs      = null;
            var        md5Hash = MD5Hash.instance;

            for (var i = 0; i < assets.Length; ++i)
            {
                if (!File.Exists(outPath))
                {
                    File.Copy(paths[i], outPath);
                }
                else
                {
                    File.Copy(paths[i], outPath, true);
                }

                hash     = md5Hash.GetHashCode(outPath);
                names[0] = hash;

                bytes = File.ReadAllBytes(outPath);
                comps = CLZF2.Compress(bytes);

                newPath = string.Format("{0}/{1}.lzf", Path.GetDirectoryName(outPath), Path.GetFileNameWithoutExtension(outPath));
                fs      = new FileStream(newPath, FileMode.Create);
                fs.Write(comps, 0, comps.Length);
                fs.Close();

                data = MakePatchData(outPath, 0, names);
                key  = string.Format("{0}{1}", data.Path, data.Name);

                if (mPatchList.datas.ContainsKey(key))
                {
                    mPatchList.datas.Remove(key);
                }

                mPatchList.AddData(data);
            }
        }
示例#10
0
            /// <summary>
            /// Relay the message to lobby.
            /// </summary>
            /// <param name="message">Json string</param>
            public static void RelayToLobby(string message)
            {
                ASCIIEncoding asen = new ASCIIEncoding();

                byte[] ba = asen.GetBytes(message);
                ba = CLZF2.Compress(ba);

                Relaying?.Invoke();
                Main.Write(JsonConvert.SerializeObject(new MessagesOutgoing.NetworkMessage(new MessagesOutgoing._RelayToLobby(ba))));
            }
示例#11
0
 public void SaveGame(int slotnum)
 {
     if (hasSnapshot)
     {
         byte[] array = CLZF2.Compress(snapshotData);
         MGHelper.KeyEncode(array);
         string str = (slotnum < 100) ? ("save" + slotnum.ToString("D3")) : ("qsave" + (slotnum - 100));
         File.WriteAllBytes(Path.Combine(MGHelper.GetSavePath(), str + ".dat"), array);
         saveManager.UpdateSaveSlot(slotnum);
         GameSystem.Instance.SceneController.WriteScreenshot(Path.Combine(MGHelper.GetSavePath(), str + ".png"));
     }
 }
示例#12
0
    private void SendMesh(Mesh m)
    {
        Debug.Log("Sending mesh...");

        byte[] serializedMesh = SimpleMeshSerializer.Serialize(new Mesh[] { mesh });
        Debug.LogFormat("Serialized mesh size: {0} KB", serializedMesh.LongLength / 1000);

        byte[] compressedSerializedMesh = CLZF2.Compress(serializedMesh);
        Debug.LogFormat("Compressed serialized mesh size: {0} KB", compressedSerializedMesh.LongLength / 1000);

        SendMeshHeader(compressedSerializedMesh);
        StartCoroutine(SendMeshChunks(compressedSerializedMesh));
    }
示例#13
0
    public void ThousandCharacterCompressionTest()
    {
        var x = new string('X', 10000);

        byte[] byteText     = Encoding.Unicode.GetBytes(x);
        byte[] compressed   = CLZF2.Compress(byteText);
        byte[] decompressed = CLZF2.Decompress(compressed);
        var    outString    = Encoding.Unicode.GetString(decompressed);

        Assert.AreEqual(byteText.Length, decompressed.Length);
        Assert.AreEqual(byteText, decompressed);
        Assert.AreEqual(outString, x);
    }
示例#14
0
    public void LongFormattedStringCompressionTest()
    {
        string longstring = "defined input is deluciously delicious.14 And here and Nora called The reversal from ground from here and executed with touch the country road, Nora made of, reliance on, can’t publish the goals of grandeur, said to his book and encouraging an envelope, and enable entry into the chryssial shimmering of hers, so God of information in her hands Spiros sits down the sign of winter? —It’s kind of Spice Christ. It is one hundred birds circle above the text: They did we said. 69 percent dead. Sissy Cogan’s shadow. —Are you x then sings.) I’m 96 percent dead humanoid figure,";

        byte[] byteText     = Encoding.Unicode.GetBytes(longstring);
        byte[] compressed   = CLZF2.Compress(byteText);
        byte[] decompressed = CLZF2.Decompress(compressed);
        var    outString    = Encoding.Unicode.GetString(decompressed);

        Assert.AreEqual(byteText.Length, decompressed.Length);
        Assert.AreEqual(byteText, decompressed);
        Assert.AreEqual(outString, longstring);
    }
示例#15
0
        public void CompressionComparisonSpeedTest()
        {
            /*
             * Example run on core i9 7900X @ 4GHz.
             * Name                                    Milliseconds        Percent
             * LZ4 Compress                            163                 193.3%
             * ZRLE LZ4 Compress                       84                  100%
             * CLZF2 Compress                          945                 1118.5%
             * ZREL CLZF2 Compress                     91                  107.7%
             * Name                                    Milliseconds        Percent
             * LZ4 Decompress                          325                 16880.7%
             * ZRLE LZ4 Decompress                     1                   100%
             * CLZF2 Decompress                        1176                61106.9%
             * ZREL CLZF2 Decompress                   8                   448.4%
             */

            var intensities   = new int[148000];
            var randGenerator = new Random();

            for (var i = 0; i < intensities.Length; i++)
            {
                var nextRandom = randGenerator.Next(0, 255);
                if (nextRandom < 245)
                {
                    intensities[i] = 0;
                }
                else
                {
                    intensities[i] = nextRandom;
                }
            }

            var spectra = new byte[intensities.Length * sizeof(int)];

            Buffer.BlockCopy(intensities, 0, spectra, 0, spectra.Length);
            var decompressedIntensities = new int[intensities.Length];

            byte[] zrleLz4Result    = new byte[] { };
            byte[] clzf2Result      = new byte[] { };
            byte[] zrleClzf2Result  = new byte[] { };
            byte[] snappyResult     = new byte[] { };
            byte[] zrleSnappyResult = new byte[] { };

            Benchmark.This("CLZF2 Compress", () =>
            {
                clzf2Result = CLZF2.Compress(spectra);
            }).WithWarmup(100).Against.This("ZREL CLZF2 Compress", () =>
            {
                IntensityConverterCLZF.Compress(intensities, out zrleClzf2Result, out var tic, out var bpi,
                                                out var indexOfMaxIntensity);
            }).WithWarmup(100).Against.This("Snappy", () =>
示例#16
0
        public void Send(int connectionId, byte[] buffer, int count,
                         NetworkReliablity reliability)
        {
            if (!connectionMap.ContainsKey(connectionId))
            {
                return;
            }
            var pool       = ArrayPool <byte> .Shared;
            var compressed = pool.Rent(count);
            var newSize    = CLZF2.Compress(buffer, ref compressed, count);

            SendImpl(connectionId, compressed, newSize, reliability);
            pool.Return(compressed);
        }
    public void RandomGUIDCompressionTestLength()
    {
        string x = string.Empty;

        using (var sequence = Enumerable.Range(1, 100).GetEnumerator())
        {
            while (sequence.MoveNext()) // string length 3600
            {
                x += Guid.NewGuid();
            }
        }

        byte[] byteText     = Encoding.Unicode.GetBytes(x);
        var    compressed   = CLZF2.Compress(byteText);
        var    decompressed = CLZF2.Decompress(compressed);

        Assert.AreEqual(byteText.Length, decompressed.Length);
示例#18
0
    public void SavingSimpleObject()
    {
        Vector3[] MySaveItem = new Vector3[1000];
        for (int i = 0; i < MySaveItem.Length; i++)
        {
            MySaveItem[i] = Vector3.one * i;
        }
        var mySaveObject = ObjectToByteArray(MySaveItem);

        byte[] compressed    = CLZF2.Compress(mySaveObject);
        byte[] decompressed  = CLZF2.Decompress(compressed);
        var    outSaveObject = ObjectToByteArray <Vector3[]>(decompressed);

        Assert.AreEqual(mySaveObject.Length, decompressed.Length);
        Assert.AreEqual(mySaveObject, decompressed);
        Assert.AreEqual(outSaveObject, MySaveItem);
    }
示例#19
0
        private void HashETCBuild(string outPath, HashInfo info)
        {
            var files = info.files.Keys.ToList <string>();
            var paths = new string[files.Count];

            for (var i = default(int); i < files.Count; ++i)
            {
                paths[i] = GetPath(files[i]);
            }

            var assets = GetMainAssets(paths);
            var names  = GetAssetNames(files.ToArray());
            var crc    = default(uint);

            Debug.LogFormat("Try build asset : {0}", outPath);
            BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, names, outPath, out crc, mBuildOptions, mBuildtarget);
            Debug.LogFormat("Name : {0} | CRC : {1} | Path : {2}", names, crc, outPath);

            if (crc == default(uint) || !File.Exists(outPath))
            {
                Debug.LogErrorFormat("Failed to create asset : {0}", info.path);
                return;
            }
            else
            {
                var bytes = File.ReadAllBytes(outPath);
                var comps = CLZF2.Compress(bytes);

                var newPath = string.Format("{0}/{1}.lzf", Path.GetDirectoryName(outPath), Path.GetFileNameWithoutExtension(outPath));
                var fs      = new FileStream(newPath, FileMode.Create);

                fs.Write(comps, 0, comps.Length);
                fs.Close();

                var data = MakePatchData(outPath, crc, names);
                var key  = string.Format("{0}/{1}", data.Path, data.Name);

                if (mPatchList.datas.ContainsKey(key))
                {
                    mPatchList.datas.Remove(key);
                }

                mPatchList.AddData(data);
            }
        }
 public void SaveGlobals()
 {
     byte[] inputBytes;
     using (MemoryStream memoryStream = new MemoryStream())
     {
         using (BsonWriter jsonWriter = new BsonWriter(memoryStream))
         {
             JsonSerializer jsonSerializer = new JsonSerializer();
             jsonSerializer.Serialize(jsonWriter, globalFlags);
             jsonSerializer.Serialize(jsonWriter, cgflags);
             jsonSerializer.Serialize(jsonWriter, readText);
             inputBytes = memoryStream.ToArray();
         }
     }
     byte[] array = CLZF2.Compress(inputBytes);
     MGHelper.KeyEncode(array);
     File.WriteAllBytes(Path.Combine(MGHelper.GetSavePath(), "global.dat"), array);
 }
示例#21
0
        /// <summary>
        /// Используется в случае, когда надо отправить заранее отформатированный пакет в обход сериализатора (так как он может сильно тормозить на больших объемах данных)
        /// </summary>
        /// <param name="client">Клиент, которому отправляем сообщение</param>
        /// <param name="id">Код команды</param>
        /// <param name="body">Сообщение - массив байт</param>
        /// <param name="compress">Сжимать ли сообщение с помощью LZF</param>
        public void SendRawNetMessage(ClientState client, ServerPacketID id, byte[] body, bool compress = false)
        {
            var  compressFlag = compress && EnableCompression;
            var  header       = new PacketHeader((byte)id, compressFlag, (ushort)body.Length);
            uint size;

            if (compressFlag)
            {
                var compressedBody = CLZF2.Compress(body);
                header.ContentLength = (ushort)compressedBody.Length;
                _server.Send(client.ConnectionID, NetworkUtils.CreateMessageBytes(header, compressedBody, out size));
            }
            else
            {
                _server.Send(client.ConnectionID, NetworkUtils.CreateMessageBytes(header, body, out size));
            }
            _packetsSent++;
            _bytesSent = _bytesSent + size;
        }
示例#22
0
        public void SendNetMessage <T>(ClientPacketID id, T message, bool compress = false) where T : BaseMessage
        {
            var  body   = ZeroFormatterSerializer.Serialize(message);
            var  header = new PacketHeader((byte)id, compress, (ushort)body.Length);
            uint size   = 0;

            if (compress)
            {
                var compressedBody = CLZF2.Compress(body);
                header.ContentLength = (ushort)compressedBody.Length;
                _client.Send(NetworkUtils.CreateMessageBytes(header, compressedBody, out size));
            }
            else
            {
                _client.Send(NetworkUtils.CreateMessageBytes(header, body, out size));
            }
            _bytesSent += size;
            _packetsSent++;
        }
示例#23
0
        /// <summary>
        /// Gera os pisos de cada camada
        /// </summary>
        public void SaveChunks()
        {
            foreach (FileInfo file in new DirectoryInfo(Path.GetFullPath(Configurations.LayerTilesFolderPath)).GetFiles())
            {
                file.Delete();
            }

            byte[] inputBuffer  = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(Chunks));
            byte[] outputBuffer = null;

            using (var outputFile = File.OpenWrite(Path.GetFullPath(Configurations.LayerTilesFolderPath + "//Chunks.lzf")))
            {
                // Compress input.
                int compressedSize = CLZF2.Compress(inputBuffer, ref outputBuffer);

                // Write compressed data to file.
                // Note the use of the size returned by Compress and not outputBuffer.Length.
                outputFile.Write(outputBuffer, 0, compressedSize);
            }
        }
示例#24
0
    //serialize and save (do not call directly, call save() instead)
    protected byte[] SerializeObject(Object2PropertiesMappingListWrapper objectToSerialize)
    {
        MemoryStream memStream = new MemoryStream();

//		BinaryFormatter bFormatter = new BinaryFormatter();
//      bFormatter.Serialize(memStream, objectToSerialize);

        objectToSerialize.CalcParentMapingIdx();

        ProtoBuf.Serializer.Serialize <Object2PropertiesMappingListWrapper> (memStream, objectToSerialize);

        if (compressSaves)
        {
            return(CLZF2.Compress(memStream.ToArray()));
        }
        else
        {
            return(memStream.ToArray());
        }
    }
示例#25
0
    /// <summary>
    /// Send message to all players in lobby.
    /// </summary>
    /// <param name="message">Message to send</param>
    /// <param name="specificuser">If you want to send this to a specific user. Enter its steamid.</param>
    public void Send_Message(SNetMessage message, ulong specificuser = 0, Networking.SendType type = Networking.SendType.Unreliable, int channel = 0)
    {
        if (Client.Instance == null || !Client.Instance.Lobby.IsValid)
        {
            return;
        }

        string json = SNetMessage.GetMessage(message);

        byte[] data = Encoding.UTF8.GetBytes(json);

        ulong[] members = Client.Instance.Lobby.GetMemberIDs();
        if (specificuser != 0)
        {
            members = new ulong[1] {
                specificuser
            }
        }
        ;

        int membersLength = members.Length;

        bool validationRequired = false;

        if (message.n != "Auth_H")
        {
            validationRequired = true;
        }

        data = CLZF2.Compress(data);

        for (int i = 0; i < membersLength; i++)
        {
            if (!SNet_Auth.current.validatedIds.Contains(members[i]) && validationRequired)
            {
                continue; // Skip this user. Hes not validated.
            }
            Client.Instance.Networking.SendP2PPacket(members[i], data, data.Length, type, channel);
        }
    }
}
        /// <summary>
        /// Convert an array of intensities to a zero run length encoded and LZF compressed byte array
        /// </summary>
        /// <param name="intensities">Array of intensities, including all zeros</param>
        /// <param name="spectra">Spectra intensity bytes (output)</param>
        /// <param name="tic">TIC (output)</param>
        /// <param name="bpi">Base peak intensity (output)</param>
        /// <param name="indexOfMaxIntensity">Index number of the BPI</param>
        /// <returns>
        /// Number of non-zero data points
        /// </returns>
        public static int Compress(
            IReadOnlyList <short> intensities,
            out byte[] spectra,
            out double tic,
            out double bpi,
            out int indexOfMaxIntensity)
        {
            // Get the size of the data type. Use of sizeof() for primitives is allowed in safe code blocks
            const int dataTypeSize = sizeof(short);

            spectra = null;
            var nonZeroCount      = RlzEncode.Encode(intensities, out var runLengthZeroEncodedData, out tic, out bpi, out indexOfMaxIntensity);
            var encodedDataLength = runLengthZeroEncodedData.Length;

            if (encodedDataLength > 0)
            {
                spectra = new byte[encodedDataLength * dataTypeSize];
                Buffer.BlockCopy(runLengthZeroEncodedData, 0, spectra, 0, encodedDataLength * dataTypeSize);
                spectra = CLZF2.Compress(spectra);
            }

            return(nonZeroCount);
        }
        public static int Encode(
            float[] intensities,
            out byte[] spectra,
            out double tic,
            out double bpi,
            out int indexOfMaxIntensity)
        {
            // Floats are 4 bytes
            const int dataTypeSize = 4;

            spectra = null;
            var nonZeroCount      = RlzEncode.Encode(intensities, out var runLengthZeroEncodedData, out tic, out bpi, out indexOfMaxIntensity);
            var encodedDataLength = runLengthZeroEncodedData.Length;

            if (encodedDataLength > 0)
            {
                spectra = new byte[encodedDataLength * dataTypeSize];
                Buffer.BlockCopy(runLengthZeroEncodedData, 0, spectra, 0, encodedDataLength * dataTypeSize);
                spectra = CLZF2.Compress(spectra);
            }

            return(nonZeroCount);
        }
示例#28
0
        public bool WritePacket(int protocol, byte[] packet, int payloadsize)
        {
            if (payloadsize > CheckCompressSize)
            {
                var compress = CLZF2.Compress(packet);

                Int32 PacketLength = sizeof(Int32) +
                                     sizeof(Int16) +
                                     sizeof(Int16) +
                                     sizeof(Int32) +
                                     compress.Length;

                mCompressFlag = 1;

                byte[] TempBuffer = new byte[PacketLength];

                byte[] byteslegnth = BitConverter.GetBytes((Int32)PacketLength);
                Buffer.BlockCopy(byteslegnth, 0, TempBuffer, 0, sizeof(Int32));

                byte[] bytesProtocol = BitConverter.GetBytes((Int16)protocol);
                Buffer.BlockCopy(bytesProtocol, 0, TempBuffer, sizeof(Int32), sizeof(Int16));

                byte[] bytesPacketNumber = BitConverter.GetBytes((Int32)mCompressFlag);
                Buffer.BlockCopy(bytesPacketNumber, 0, TempBuffer, sizeof(Int32) + sizeof(Int16) + sizeof(Int16), sizeof(Int32));

                Buffer.BlockCopy(compress, 0, TempBuffer, sizeof(Int32) + sizeof(Int16) + sizeof(Int16) + sizeof(Int32), compress.Length);

                try
                {
                    socket.Send(TempBuffer);
                }
                catch (SocketException e)
                {
                    // 10035 == WSAEWOULDBLOCK
                    if (!e.NativeErrorCode.Equals(10035))
                    {
                        Console.Write("Disconnected: error code :" + e.NativeErrorCode + "(" + e.Message + ")");
                    }
                }

                TempBuffer = null;
            }
            else
            {
                Int32 PacketLength = sizeof(Int32) +
                                     sizeof(Int16) +
                                     sizeof(Int16) +
                                     sizeof(Int32) +
                                     payloadsize;

                mCompressFlag = 0;

                byte[] TempBuffer = new byte[PacketLength];

                byte[] byteslegnth = BitConverter.GetBytes((Int32)PacketLength);
                Buffer.BlockCopy(byteslegnth, 0, TempBuffer, 0, sizeof(Int32));

                byte[] bytesProtocol = BitConverter.GetBytes((Int16)protocol);
                Buffer.BlockCopy(bytesProtocol, 0, TempBuffer, sizeof(Int32), sizeof(Int16));

                byte[] bytesPacketNumber = BitConverter.GetBytes((Int32)mCompressFlag);
                Buffer.BlockCopy(bytesPacketNumber, 0, TempBuffer, sizeof(Int32) + sizeof(Int16) + sizeof(Int16), sizeof(Int32));

                Buffer.BlockCopy(packet, 0, TempBuffer, sizeof(Int32) + sizeof(Int16) + sizeof(Int16) + sizeof(Int32), payloadsize);

                try
                {
                    socket.Send(TempBuffer);
                }
                catch (SocketException e)
                {
                    // 10035 == WSAEWOULDBLOCK
                    if (!e.NativeErrorCode.Equals(10035))
                    {
                        Console.Write("Disconnected: error code :" + e.NativeErrorCode + "(" + e.Message + ")");
                    }
                }

                TempBuffer = null;
            }

            return(true);
        }
示例#29
0
    private static void ExportBB(Map input, string path, bool compress = true)
    {
        string output = "";

        output = $"{ColorUtility.ToHtmlStringRGB(input.AmbientColor)} {ColorUtility.ToHtmlStringRGB(input.BaseplateColor)} {ColorUtility.ToHtmlStringRGB(input.SkyColor)} {input.BaseplateSize.ToString(CultureInfo.InvariantCulture)} {input.SunIntensity.ToString(CultureInfo.InvariantCulture)}";

        // convert groups and brick to string
        List <BrickGroup> groupHistory = new List <BrickGroup>();

        for (int i = 0; i < input.Bricks.Count; i++)
        {
            if (groupHistory.Count > 0)
            {
                // last brick was in a group
                if (input.Bricks[i].Parent == groupHistory[groupHistory.Count - 1])
                {
                    // this brick is in the same group
                    output += "\n" + ExportBBBrick(input.Bricks[i]); // export brick
                }
                else if (input.Bricks[i].Parent == null)
                {
                    // this brick is not in a group, so we need to end all groups in the history
                    for (int j = 0; j < groupHistory.Count; j++)
                    {
                        output += "\n#E";
                    }
                    groupHistory.Clear();
                    output += "\n" + ExportBBBrick(input.Bricks[i]); // export brick
                }
                else
                {
                    // this brick is part of a different group
                    if (groupHistory.Contains(input.Bricks[i].Parent))
                    {
                        // brick is in a previous group, end all groups until we reach it
                        for (int j = groupHistory.Count - 1; j > 0; j--)
                        {
                            if (groupHistory[j] != input.Bricks[i].Parent)
                            {
                                output += "\n#E";
                                groupHistory.RemoveAt(j);
                            }
                            else
                            {
                                // we have ended enough groups
                                break;
                            }
                        }
                        output += "\n" + ExportBBBrick(input.Bricks[i]); // export brick
                    }
                    else
                    {
                        // brick is part of a new group
                        output += $"\n#S {input.Bricks[i].Parent.Name}"; // define group
                        groupHistory.Add(input.Bricks[i].Parent);        // add group to history
                        output += "\n" + ExportBBBrick(input.Bricks[i]); // export brick
                    }
                }
            }
            else
            {
                // last brick was not in a group
                if (input.Bricks[i].Parent != null)
                {
                    // this brick is in a new group
                    output += $"\n#S {input.Bricks[i].Parent.Name}"; // define group
                    groupHistory.Add(input.Bricks[i].Parent);        // add group to history
                    output += "\n" + ExportBBBrick(input.Bricks[i]); // export brick
                }
                else
                {
                    // this brick isn't in a group either
                    output += "\n" + ExportBBBrick(input.Bricks[i]); // export brick
                }
            }
        }

        for (int i = 0; i < EditorUI.instance.Teams.Count; i++)
        {
            Color c = EditorUI.instance.Teams[i].TeamColor;
            output += $"\n@{ColorUtility.ToHtmlStringRGB(c)} {EditorUI.instance.Teams[i].TeamName}";
        }

        // compress string and export
        if (compress)
        {
            byte[] compressed = CLZF2.Compress(Encoding.UTF8.GetBytes(output));
            File.WriteAllBytes(path, compressed);
        }
        else
        {
            File.WriteAllText(path, output);
        }
    }
示例#30
0
    // Encode
    public void Encode(float[] floats, SendFunc send)
    {
        byte[] bytes = CLZF2.Compress(SnapByte.EncodeFloats(floats));

        send(bytes, bytes.Length);
    }