Ejemplo n.º 1
0
        public static int ReadBinary(byte[] buf, int ofs, out OsmWay way)
        {
            int   p = 0;
            ulong tmp;

            p += ProtoBuf.ReadVarInt(buf, ofs + p, out tmp);
            long id = (long)tmp;

            p += ProtoBuf.ReadVarInt(buf, ofs + p, out tmp);
            var values = new KeyValuePair <string, string> [tmp];

            for (int i = 0; i < values.Length; i++)
            {
                string key, val;
                p        += ProtoBuf.ReadString(buf, ofs + p, out key);
                p        += ProtoBuf.ReadString(buf, ofs + p, out val);
                values[i] = new KeyValuePair <string, string>(key, val);
            }
            p  += ProtoBuf.ReadVarInt(buf, ofs + p, out tmp);
            way = new OsmWay(id, values, new long[tmp]);
            for (int i = 0; i < way.nodeIds.Length; i++)
            {
                p += ProtoBuf.ReadVarInt(buf, ofs + p, out tmp);
                way.nodeIds[i] = (long)tmp;
            }
            return(p);
        }
Ejemplo n.º 2
0
        void WriteIndex(MemberType type, long id, long index)
        {
            switch (type)
            {
            case MemberType.Relation: relationsIndex.Add(id, index); break;

            case MemberType.Way: waysIndex.Add(id, index); break;

            case MemberType.Node: nodesIndex.Add(id, index); break;

            default: throw new Exception("unknown type?");
            }

            byte[] miniBuf = new byte[64];
            int    p       = 0;

            miniBuf[p] = (byte)type; p++;
            p         += ProtoBuf.WriteVarInt(miniBuf, p, (ulong)id);
            p         += ProtoBuf.WriteVarInt(miniBuf, p, (ulong)index);
            using (var indexFile = File.OpenWrite(CacheIndexFile))
            {
                indexFile.Position = indexFile.Length;
                indexFile.Write(miniBuf, 0, p);
            }
        }
Ejemplo n.º 3
0
        protected override void EmitRead(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
        {
            /* This looks more complex than it is. Look at the non-compiled Read to
             * see what it is trying to do, but note that it needs to cope with a
             * few more scenarios. Note that it picks the **most specific** Add,
             * unlike the runtime version that uses IList when possible. The core
             * is just a "do {list.Add(readValue())} while {thereIsMore}"
             * 
             * The complexity is due to:
             *  - value types vs reference types (boxing etc)
             *  - initialization if we need to pass in a value to the tail
             *  - handling whether or not the tail *returns* the value vs updates the input
             */ 
            using (Compiler.Local list = ctx.GetLocalWithValue(ExpectedType, valueFrom))            
            {
                if (concreteType != null)
                {
                    ctx.LoadValue(list);
                    Compiler.CodeLabel notNull = ctx.DefineLabel();
                    ctx.BranchIfTrue(notNull, true);
                    ctx.EmitCtor(concreteType);
                    ctx.StoreValue(list);
                    ctx.MarkLabel(notNull);
                }

                EmitReadList(ctx, list, Tail, add, packedWireType);
                ctx.LoadValue(list);
            }
        }
Ejemplo n.º 4
0
        public ReflectedUriDecorator(Type type, ProtoBuf.Meta.TypeModel model, IProtoSerializer tail) : base(tail)
        {
            expectedType = type;

            absoluteUriProperty = expectedType.GetProperty("AbsoluteUri");
            typeConstructor = expectedType.GetConstructor(new Type[] { typeof(string) });
        }
Ejemplo n.º 5
0
        public static int ReadBinary(byte[] buf, int ofs, out OsmRelation relation)
        {
            int   p = 0;
            ulong tmp;

            p += ProtoBuf.ReadVarInt(buf, ofs + p, out tmp);
            long id = (long)tmp;

            p += ProtoBuf.ReadVarInt(buf, ofs + p, out tmp);
            var values = new KeyValuePair <string, string> [tmp];

            for (int i = 0; i < values.Length; i++)
            {
                string key, val;
                p        += ProtoBuf.ReadString(buf, ofs + p, out key);
                p        += ProtoBuf.ReadString(buf, ofs + p, out val);
                values[i] = new KeyValuePair <string, string>(key, val);
            }
            p += ProtoBuf.ReadVarInt(buf, ofs + p, out tmp);
            var members = new OsmRelationMember[tmp];

            for (int i = 0; i < members.Length; i++)
            {
                p += OsmRelationMember.ReadBinary(buf, ofs + p, out members[i]);
            }
            relation = new OsmRelation(id, values, members);
            return(p);
        }
Ejemplo n.º 6
0
        public static int ReadBinary(byte[] buf, int ofs, out OsmNode node)
        {
            int   p = 0;
            ulong tmp;

            p += ProtoBuf.ReadVarInt(buf, ofs + p, out tmp);
            long id = (long)tmp;

            p += ProtoBuf.ReadVarInt(buf, ofs + p, out tmp);
            int latCode = ProtoBuf.SignedInt32((uint)tmp);

            p += ProtoBuf.ReadVarInt(buf, ofs + p, out tmp);
            int lonCode = ProtoBuf.SignedInt32((uint)tmp);

            p += ProtoBuf.ReadVarInt(buf, ofs + p, out tmp);
            var values = tmp == 0 ? emptyValues : new KeyValuePair <string, string> [tmp];

            for (int i = 0; i < values.Length; i++)
            {
                string key, val;
                p        += ProtoBuf.ReadString(buf, ofs + p, out key);
                p        += ProtoBuf.ReadString(buf, ofs + p, out val);
                values[i] = new KeyValuePair <string, string>(key, val);
            }
            node = new OsmNode(id, latCode, lonCode, values);
            return(p);
        }
Ejemplo n.º 7
0
        long WriteRelationCache(OsmRelation osmRelation, OsmWay[] osmWays, OsmNode[] osmNodes)
        {
            long relationIndex = cacheData.Length;

            int p   = sizeof(int); // cacheblock-size
            var buf = cacheBuffer;

            p += osmRelation.WriteBinary(buf, p);
            p += ProtoBuf.WriteVarInt(buf, p, (ulong)osmWays.Length);
            var tmpWays = osmWays.ToArray();

            EncodeDelta(tmpWays);
            foreach (var way in tmpWays)
            {
                p += way.WriteBinary(buf, p);
            }
            p += ProtoBuf.WriteVarInt(buf, p, (ulong)osmNodes.Length);
            var tmpNodes = osmNodes.ToArray();

            EncodeDelta(tmpNodes);
            foreach (var node in tmpNodes)
            {
                p += node.WriteBinary(buf, p);
            }
            buf[0] = (byte)p;
            buf[1] = (byte)(p >> 8);
            buf[2] = (byte)(p >> 16);
            buf[3] = (byte)(p >> 24);

            cacheData.Position = relationIndex;
            cacheData.Write(buf, 0, p);
            return(relationIndex);
        }
Ejemplo n.º 8
0
 protected static T Deserialize <T>(byte[] bytes)
 {
     using (var memstream = new MemoryStream(bytes))
     {
         return(ProtoBuf.Deserialize <T>(memstream));
     }
 }
Ejemplo n.º 9
0
 public CraftEvent(ItemCrafter self, ItemBlueprint bp, BasePlayer owner, ProtoBuf.Item.InstanceData instanceData, int amount)
 {
     Crafter = Server.GetPlayer(owner);
     Target = bp.targetItem;
     itemCrafter = self;
     Amount = amount;
     bluePrint = bp;
 }
Ejemplo n.º 10
0
        public int WriteBinary(byte[] buf, int ofs)
        {
            int p = 0;

            p           += ProtoBuf.WriteVarInt(buf, ofs + p, (ulong)id);
            buf[ofs + p] = (byte)type; p++;
            p           += ProtoBuf.WriteString(buf, ofs + p, role);
            return(p);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Dekodiert die Werte aus einem PBF-Stream
        /// </summary>
        /// <param name="buf">Buffer, worraus die Werte gelesen werden sollen</param>
        /// <param name="ofs">Startposition innerhalb des Buffers</param>
        /// <param name="box">BBox-Struktur mit den ausgelesenen Werten</param>
        /// <returns>Anzahl der gelesenen Bytes aus dem Buffer</returns>
        public static int Decode(byte[] buf, int ofs, out HeaderBBox box)
        {
            /*****
            * message HeaderBBox
            * {
            *   required sint64 left = 1;
            *   required sint64 right = 2;
            *   required sint64 top = 3;
            *   required sint64 bottom = 4;
            * }
            *****/

            box = new HeaderBBox();

            ulong tmp;
            int   len    = ProtoBuf.ReadVarInt(buf, ofs, out tmp);
            int   endLen = len + (int)tmp;

            // --- required sint64 left = 1; ---
            if (buf[ofs + len++] != (1 << 3 | 0))
            {
                throw new PbfParseException();
            }
            len     += ProtoBuf.ReadVarInt(buf, ofs + len, out tmp);
            box.left = ProtoBuf.SignedInt64(tmp);

            // --- required sint64 right = 2; ---
            if (buf[ofs + len++] != (2 << 3 | 0))
            {
                throw new PbfParseException();
            }
            len      += ProtoBuf.ReadVarInt(buf, ofs + len, out tmp);
            box.right = ProtoBuf.SignedInt64(tmp);

            // --- required sint64 top = 3; ---
            if (buf[ofs + len++] != (3 << 3 | 0))
            {
                throw new PbfParseException();
            }
            len    += ProtoBuf.ReadVarInt(buf, ofs + len, out tmp);
            box.top = ProtoBuf.SignedInt64(tmp);

            // --- required sint64 bottom = 4; ---
            if (buf[ofs + len++] != (4 << 3 | 0))
            {
                throw new PbfParseException();
            }
            len       += ProtoBuf.ReadVarInt(buf, ofs + len, out tmp);
            box.bottom = ProtoBuf.SignedInt64(tmp);

            if (len != endLen)
            {
                throw new PbfParseException();
            }

            return(len);
        }
Ejemplo n.º 12
0
        static int WriteNodesPath(byte[] buf, int ofs, OsmNode[] nodes)
        {
            int p = ProtoBuf.WriteVarInt(buf, ofs, (uint)nodes.Length);

            foreach (var node in nodes)
            {
                p += node.WriteBinary(buf, ofs + p);
            }
            return(p);
        }
Ejemplo n.º 13
0
 protected override void EmitRead(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
 {
     if (strict || NeedsHint)
     {
         ctx.LoadReaderWriter();
         ctx.LoadValue((int)wireType);
         ctx.EmitCall(typeof(ProtoReader).GetMethod(strict ? "Assert" : "Hint"));
     }
     Tail.EmitRead(ctx, valueFrom);
 }
Ejemplo n.º 14
0
        internal static void EmitReadList(ProtoBuf.Compiler.CompilerContext ctx, Compiler.Local list, IProtoSerializer tail, MethodInfo add, WireType packedWireType)
        {
            using (Compiler.Local fieldNumber = new Compiler.Local(ctx, typeof(int)))
            {
                Compiler.CodeLabel readPacked = packedWireType == WireType.None ? new Compiler.CodeLabel() : ctx.DefineLabel();                                   
                if (packedWireType != WireType.None)
                {
                    ctx.LoadReaderWriter();
                    ctx.LoadValue(typeof(ProtoReader).GetProperty("WireType"));
                    ctx.LoadValue((int)WireType.String);
                    ctx.BranchIfEqual(readPacked, false);
                }
                ctx.LoadReaderWriter();
                ctx.LoadValue(typeof(ProtoReader).GetProperty("FieldNumber"));
                ctx.StoreValue(fieldNumber);

                Compiler.CodeLabel @continue = ctx.DefineLabel();
                ctx.MarkLabel(@continue);

                EmitReadAndAddItem(ctx, list, tail, add);

                ctx.LoadReaderWriter();
                ctx.LoadValue(fieldNumber);
                ctx.EmitCall(typeof(ProtoReader).GetMethod("TryReadFieldHeader"));
                ctx.BranchIfTrue(@continue, false);

                if (packedWireType != WireType.None)
                {
                    Compiler.CodeLabel allDone = ctx.DefineLabel();
                    ctx.Branch(allDone, false);
                    ctx.MarkLabel(readPacked);

                    ctx.LoadReaderWriter();
                    ctx.EmitCall(typeof(ProtoReader).GetMethod("StartSubItem"));

                    Compiler.CodeLabel testForData = ctx.DefineLabel(), noMoreData = ctx.DefineLabel();
                    ctx.MarkLabel(testForData);
                    ctx.LoadValue((int)packedWireType);
                    ctx.LoadReaderWriter();
                    ctx.EmitCall(typeof(ProtoReader).GetMethod("HasSubValue"));
                    ctx.BranchIfFalse(noMoreData, false);

                    EmitReadAndAddItem(ctx, list, tail, add);
                    ctx.Branch(testForData, false);

                    ctx.MarkLabel(noMoreData);
                    ctx.LoadReaderWriter();
                    ctx.EmitCall(typeof(ProtoReader).GetMethod("EndSubItem"));
                    ctx.MarkLabel(allDone);
                }


                
            }
        }
Ejemplo n.º 15
0
		public bool TryApplyMessage(ProtoBuf.IExtensible message, DemoParser parser)
		{
			CSVCMsg_UserMessage userMessage = message as CSVCMsg_UserMessage;
			if (userMessage == null)
				return false;

			var messageType = (Messages.ECstrike15UserMessages)userMessage.msg_type;
			// TODO: maybe, like, implement something here one day?
			//Problem: There is no real useful info here if I see it correcly. Sorry.
			return true;
		}
        static void DecodeNodeBlock(byte[] buf, int bufLen)
        {
            long id  = 0;
            long pos = 0;

            var keyDict = new Dictionary <string, int>();
            var valDict = new Dictionary <string, int>();

            var outputNodes  = new List <DecodeNodeBlockValue>();
            var outputValues = new List <int>();

            for (int p = 0; p < bufLen;)
            {
                DecodeNodeBlockValue nodeValue;
                ulong tmp;
                p            += ProtoBuf.ReadVarInt(buf, p, out tmp);
                id           += ProtoBuf.SignedInt64(tmp);
                nodeValue.id  = id;
                p            += ProtoBuf.ReadVarInt(buf, p, out tmp);
                pos          += ProtoBuf.SignedInt64(tmp);
                nodeValue.pos = pos;
                p            += ProtoBuf.ReadVarInt(buf, p, out tmp);
                int valueCount = (int)(uint)tmp;
                nodeValue.valueCount = valueCount;
                nodeValue.valuePos   = outputValues.Count / 2;
                for (int i = 0; i < valueCount; i++)
                {
                    string key, val;
                    p += ProtoBuf.ReadString(buf, p, out key);
                    if (!keyDict.ContainsKey(key))
                    {
                        keyDict.Add(key, keyDict.Count);
                    }
                    outputValues.Add(keyDict[key]);
                    p += ProtoBuf.ReadString(buf, p, out val);
                    if (!valDict.ContainsKey(val))
                    {
                        valDict.Add(val, valDict.Count);
                    }
                    outputValues.Add(valDict[val]);
                }
                outputNodes.Add(nodeValue);
            }

            // --- sort ---
            long lastId = outputNodes[outputNodes.Count - 1].id;

            Console.WriteLine(" sort: " + outputNodes.Count + " nodes");
            outputNodes.Sort((x, y) => x.pos.CompareTo(y.pos));

            // --- write ---
            Console.WriteLine("write: " + outputNodes.Count + " nodes");
            WriteNodeBlock(keyDict, valDict, outputValues, outputNodes, lastId);
        }
Ejemplo n.º 17
0
		static void Serialize(ProtoBuf.IExtensible message)
		{
			PlayerPrefs.SetInt("Version", 1);
			byte[] buf = null;
			using(var mem = new MemoryStream())
			{
				ProtoBuf.Serializer.Serialize(mem, message);
				buf = mem.ToArray();
			}
			PlayerPrefs.SetString("UserData", Convert.ToBase64String(Crypto.Encode(buf)));
			Debug.Log("Serialize: " + message.Dump());
		}
Ejemplo n.º 18
0
 static void EncodeDelta(OsmWay[] ways)
 {
     for (int i = ways.Length - 1; i > 0; i--)
     {
         var ids = ways[i].nodeIds.ToArray();
         for (int n = ids.Length - 1; n > 0; n--)
         {
             ids[n] = (long)ProtoBuf.UnsignedInt64(ids[n] - ids[n - 1]);
         }
         ways[i] = new OsmWay(ways[i].id - ways[i - 1].id, ways[i].values, ids);
     }
 }
Ejemplo n.º 19
0
 static void DecodeDelta(OsmWay[] ways)
 {
     for (int i = 1; i < ways.Length; i++)
     {
         var ids = ways[i].nodeIds;
         for (int n = 1; n < ids.Length; n++)
         {
             ids[n] = ProtoBuf.SignedInt64((ulong)ids[n]) + ids[n - 1];
         }
         ways[i] = new OsmWay(ways[i].id + ways[i - 1].id, ways[i].values, ids);
     }
 }
Ejemplo n.º 20
0
        static int ReadNodesPath(byte[] buf, int ofs, out OsmNode[] nodes)
        {
            ulong tmp;
            int   p = ProtoBuf.ReadVarInt(buf, ofs, out tmp);

            nodes = new OsmNode[tmp];
            for (int i = 0; i < nodes.Length; i++)
            {
                p += OsmNode.ReadBinary(buf, ofs + p, out nodes[i]);
            }
            return(p);
        }
Ejemplo n.º 21
0
        public static int ReadBinary(byte[] buf, int ofs, out OsmRelationMember member)
        {
            int   p = 0;
            ulong tmp;

            p += ProtoBuf.ReadVarInt(buf, ofs + p, out tmp);
            long   id   = (long)tmp;
            var    type = (MemberType)buf[ofs + p]; p++;
            string str;

            p     += ProtoBuf.ReadString(buf, ofs + p, out str);
            member = new OsmRelationMember(id, type, str);
            return(p);
        }
Ejemplo n.º 22
0
 public CraftEvent(ItemCrafter itemCrafter,
                   ItemBlueprint itemBlueprint,
                   BasePlayer owner,
                   ProtoBuf.Item.InstanceData instanceData,
                   int amount,
                   int skinid)
 {
     this.itemCrafter = itemCrafter;
     bluePrint = itemBlueprint;
     Crafter = Server.GetPlayer(owner);
     Target = itemBlueprint.targetItem;
     Amount = amount;
     SkinID = skinid;
 }
Ejemplo n.º 23
0
        public int WriteBinary(byte[] buf, int ofs)
        {
            int p = 0;

            p += ProtoBuf.WriteVarInt(buf, ofs + p, (ulong)id);
            p += ProtoBuf.WriteVarInt(buf, ofs + p, ProtoBuf.UnsignedInt32(latCode));
            p += ProtoBuf.WriteVarInt(buf, ofs + p, ProtoBuf.UnsignedInt32(lonCode));
            p += ProtoBuf.WriteVarInt(buf, ofs + p, (uint)values.Length);
            foreach (var val in values)
            {
                p += ProtoBuf.WriteString(buf, ofs + p, val.Key);
                p += ProtoBuf.WriteString(buf, ofs + p, val.Value);
            }
            return(p);
        }
Ejemplo n.º 24
0
        public byte[] Serialize()
        {
            byte[] bytes;

            using (var memstream = new MemoryStream())
            {
                ProtoBuf.Serialize(this, memstream);

                memstream.Seek(0, SeekOrigin.Begin);
                bytes = new byte[memstream.Length];
                memstream.Read(bytes, 0, bytes.Length);
            }

            return(bytes);
        }
Ejemplo n.º 25
0
        IEnumerable <T[]> BlobSmtDecoder <T>(IList <OsmBlob> blobs, Func <OsmBlob, byte[], T[]> decode)
        {
            //return blobs.SelectParallelEnumerable(blob =>
            return(blobs.Select(blob =>
            {
                // --- Thread-Buffer abfragen ---
                int threadId = Thread.CurrentThread.ManagedThreadId;
                byte[] buf;
                lock (SmtCache)
                {
                    if (!SmtCache.TryGetValue(threadId, out buf))
                    {
                        buf = new byte[16777216 * 2];
                        SmtCache.Add(threadId, buf);
                    }
                    lock (runningThreads)
                    {
                        runningThreads.Add(Thread.CurrentThread);
                    }
                }

                // --- lesen ---
                var tim = Stopwatch.StartNew();
                lock (pbfReader)
                {
                    int pbfOfs = pbfReader.PrepareBuffer(blob.pbfOfs + blob.zlibOfs, blob.zlibLen);
                    Array.Copy(pbfReader.buffer, pbfOfs, buf, 16777216, blob.zlibLen);
                }
                tim.Stop();
                lock (times)
                {
                    times.Add(tim.ElapsedMilliseconds);
                }

                // --- entpacken ---
                int bytes = ProtoBuf.FastInflate(buf, 16777216, blob.zlibLen, buf, 0);
                if (bytes != blob.rawSize)
                {
                    throw new PbfParseException();
                }
                buf[bytes] = 0;

                // --- decoden ---
                return decode(blob, buf);
                //}, priority: ThreadPriority.Lowest);
            }));
        }
Ejemplo n.º 26
0
        public int WriteBinary(byte[] buf, int ofs)
        {
            int p = 0;

            p += ProtoBuf.WriteVarInt(buf, ofs + p, (ulong)id);
            p += ProtoBuf.WriteVarInt(buf, ofs + p, (uint)values.Length);
            foreach (var val in values)
            {
                p += ProtoBuf.WriteString(buf, ofs + p, val.Key);
                p += ProtoBuf.WriteString(buf, ofs + p, val.Value);
            }
            p += ProtoBuf.WriteVarInt(buf, ofs + p, (uint)members.Length);
            foreach (var member in members)
            {
                p += member.WriteBinary(buf, ofs + p);
            }
            return(p);
        }
        protected override void EmitWrite(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
        {
            // int i and T[] arr
            using (Compiler.Local arr = ctx.GetLocalWithValue(arrayType, valueFrom))
            using (Compiler.Local i = new ProtoBuf.Compiler.Local(ctx, typeof(int)))
            {
                if (packedFieldNumber > 0)
                {
                    Compiler.CodeLabel allDone = ctx.DefineLabel();
                    ctx.LoadLength(arr, false);
                    ctx.BranchIfFalse(allDone, false);

                    ctx.LoadValue(packedFieldNumber);
                    ctx.LoadValue((int)WireType.String);
                    ctx.LoadReaderWriter();
                    ctx.EmitCall(typeof(ProtoWriter).GetMethod("WriteFieldHeader"));

                    ctx.LoadValue(arr);
                    ctx.LoadReaderWriter();
                    ctx.EmitCall(typeof(ProtoWriter).GetMethod("StartSubItem"));
                    using (Compiler.Local token = new Compiler.Local(ctx, typeof(SubItemToken))) { 
                        ctx.StoreValue(token);

                        ctx.LoadValue(packedFieldNumber);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(typeof(ProtoWriter).GetMethod("SetPackedField"));

                        EmitWriteArrayLoop(ctx, i, arr);

                        ctx.LoadValue(token);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(typeof(ProtoWriter).GetMethod("EndSubItem"));
                    }
                    ctx.MarkLabel(allDone);
                }
                else
                {
                    EmitWriteArrayLoop(ctx, i, arr);    
                }
            }
        }
Ejemplo n.º 28
0
        OsmRelation GetRelationData(long relationIndex, out OsmWay[] osmWays, out OsmNode[] osmNodes)
        {
            var buf = cacheBuffer;

            cacheData.Position = relationIndex;
            cacheData.Read(buf, 0, sizeof(int));

            int size = BitConverter.ToInt32(buf, 0) - sizeof(int);

            if (cacheData.Read(buf, sizeof(int), size) != size)
            {
                throw new IOException("EOF?");
            }

            int         p = sizeof(int);
            OsmRelation osmRelation;

            p += OsmRelation.ReadBinary(buf, p, out osmRelation);
            ulong tmp;

            p      += ProtoBuf.ReadVarInt(buf, p, out tmp);
            osmWays = new OsmWay[tmp];
            for (int i = 0; i < osmWays.Length; i++)
            {
                p += OsmWay.ReadBinary(buf, p, out osmWays[i]);
            }
            DecodeDelta(osmWays);
            p       += ProtoBuf.ReadVarInt(buf, p, out tmp);
            osmNodes = new OsmNode[tmp];
            for (int i = 0; i < osmNodes.Length; i++)
            {
                p += OsmNode.ReadBinary(buf, p, out osmNodes[i]);
            }
            DecodeDelta(osmNodes);
            if (p != size + sizeof(int))
            {
                throw new PbfParseException();
            }

            return(osmRelation);
        }
Ejemplo n.º 29
0
        public OsmCache(OsmPbfReader pbf)
        {
            if (!File.Exists(CacheIndexFile))
            {
                File.WriteAllBytes(CacheIndexFile, new byte[0]);
            }
            if (!File.Exists(CacheDataFile))
            {
                File.WriteAllBytes(CacheDataFile, new byte[1]);
            }

            // --- Read Index ---
            relationsIndex = new Dictionary <long, long>();
            waysIndex      = new Dictionary <long, long>();
            nodesIndex     = new Dictionary <long, long>();
            var buf = File.ReadAllBytes(CacheIndexFile);

            for (int p = 0; p < buf.Length;)
            {
                var   type = (MemberType)buf[p++];
                ulong id, index;
                p += ProtoBuf.ReadVarInt(buf, p, out id);
                p += ProtoBuf.ReadVarInt(buf, p, out index);
                switch (type)
                {
                case MemberType.Relation: relationsIndex.Add((long)id, (long)index); break;

                case MemberType.Way: waysIndex.Add((long)id, (long)index); break;

                case MemberType.Node: nodesIndex.Add((long)id, (long)index); break;

                default: throw new Exception("unknown type?");
                }
            }

            cacheData = new FileStream(CacheDataFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            pbfReader = pbf;
        }
Ejemplo n.º 30
0
        protected override void EmitWrite(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
        {
            // int i and T[] arr
            using (Compiler.Local arr = ctx.GetLocalWithValue(arrayType, valueFrom))
            using (Compiler.Local i = new ProtoBuf.Compiler.Local(ctx, ctx.MapType(typeof(int))))
            {
                bool writePacked = (options & OPTIONS_WritePacked) != 0;
                using (Compiler.Local token = writePacked ? new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken))) : null)
                {
                    Type mappedWriter = ctx.MapType(typeof (ProtoWriter));
                    if (writePacked)
                    {
                        ctx.LoadValue(fieldNumber);
                        ctx.LoadValue((int)WireType.String);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(mappedWriter.GetMethod("WriteFieldHeader"));

                        ctx.LoadValue(arr);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(mappedWriter.GetMethod("StartSubItem"));
                        ctx.StoreValue(token);

                        ctx.LoadValue(fieldNumber);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(mappedWriter.GetMethod("SetPackedField"));
                    }
                    EmitWriteArrayLoop(ctx, i, arr);

                    if (writePacked)
                    {
                        ctx.LoadValue(token);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(mappedWriter.GetMethod("EndSubItem"));
                    }
                }
            }
        }
Ejemplo n.º 31
0
	/// <summary>
	/// 连接到LoginServer,并发送指定的消息
	/// </summary>
	/// <returns></returns>
	IEnumerator ConnectLoginServer(ProtoBuf.IExtensible cmd)
	{
		var remotes = new string[]
		{
			"ws://14.17.104.56:7000/shen/user", // 广东佛山
			"ws://112.65.197.72:7000/shen/user", // 松江机房
			"ws://192.168.85.71:7000/shen/user", // 公司本地
		};

		foreach (var url in remotes)
		{
			foreach (var c in WebSocketClient.Instance.Open(url).AsEnumerable())
				yield return c;
			if (WebSocketClient.Instance.State == WebSocket.State.Open)
			{
				WebSocketClient.Instance.Send(cmd);
				yield break;
			}
			Debug.LogWarning("登陆服务器连接错误: " + url);
		}

		Debug.LogError("无法连接到登陆服务器");
		MessageBox.Show("无法连接到登陆服务器");
	}
Ejemplo n.º 32
0
        public static IEnumerator CoroutinePostRequest(ProtoBuf.IExtensible serializableRequest, ResponseHandlerDelegate responseHandler, string url, bool isGet)
        {
            //UnityEngine.Debug.Log ("set up recv result");
            WWW recvResult = SetUpRecvResult(serializableRequest, url, isGet);

            yield return GetSingletonInstance().StartCoroutine(
                CoroutinePostRequest (recvResult, serializableRequest, responseHandler, url));
        }
Ejemplo n.º 33
0
 public static IEnumerator CoroutinePostRequest(WWW recvResult, ProtoBuf.IExtensible serializableRequest, ResponseHandlerDelegate responseHandler, string url)
 {
     if (!SenseixSession.GetSessionState())
     {
         yield break;
     }
     //UnityEngine.Debug.Log ("wait for request");
     yield return GetSingletonInstance().StartCoroutine(WaitForRequest (recvResult));
     //UnityEngine.Debug.Log ("handle result");
     HandleResult (recvResult, responseHandler);
 }
Ejemplo n.º 34
0
        public static WWW SetUpRecvResult(ProtoBuf.IExtensible serializableRequest, string url, bool isGet)
        {
            byte[] bytes;
            Dictionary<string, string> mods = new Dictionary<string, string>();
            mods.Add ("X-Auth-Token", SenseixSession.GetAuthToken ());
            mods.Add ("X-Access-Token", SenseixSession.GetAccessToken());
            mods.Add("Content-Type", "application/protobuf");

            MemoryStream requestMessageStream = new MemoryStream ();
            ThinksyProtosSerializer serializer = new ThinksyProtosSerializer ();
            //UnityEngine.Debug.Log ("Serializing request");
            serializer.Serialize(requestMessageStream, serializableRequest);
            bytes = requestMessageStream.ToArray();
            requestMessageStream.Close();

            WWW recvResult;
            if (!isGet)
            {
                //UnityEngine.Debug.Log("POST");
                recvResult = new WWW (url, bytes, mods);
            }
            else
            {
                //UnityEngine.Debug.Log("GET");
                recvResult = new WWW (url, null, mods);
            }

            return recvResult;
        }
 void IProtoTypeSerializer.Callback(object value, ProtoBuf.Meta.TypeModel.CallbackType callbackType) { }
Ejemplo n.º 36
0
        /// <summary>
        /// Called from <c>ItemCrafter.CraftItem(ItemBlueprint, BasePlayer, ProtoBuf.Item.InstanceData, int, int, Item)</c> .
        /// </summary>
        public static bool On_PlayerStartCrafting(ItemCrafter self,
                                                  ItemBlueprint bp,
                                                  BasePlayer owner,
                                                  ProtoBuf.Item.InstanceData instanceData = null,
                                                  int amount = 1,
                                                  int skinID = 0,
                                                  Item fromTempBlueprint = null)
        {
            var ce = new CraftEvent(self, bp, owner, instanceData, amount, skinID);

            OnNext("On_PlayerStartCrafting", ce);

            if (!self.CanCraft(bp, ce.Amount))
                return false;

            if (ce.Cancel) {
                if (ce.cancelReason != String.Empty)
                    ce.Crafter.Message(ce.cancelReason);
                return false;
            }

            self.taskUID++;

            ItemCraftTask itemCraftTask = Facepunch.Pool.Get<ItemCraftTask>();
            itemCraftTask.blueprint = bp;
            self.CallMethod("CollectIngredients", bp, itemCraftTask, ce.Amount, owner);
            itemCraftTask.endTime = 0;
            itemCraftTask.taskUID = self.taskUID;
            itemCraftTask.owner = owner;
            itemCraftTask.instanceData = instanceData;

            if (itemCraftTask.instanceData != null) {
                itemCraftTask.instanceData.ShouldPool = false;
            }

            itemCraftTask.amount = ce.Amount;
            itemCraftTask.skinID = ce.SkinID;

            if (fromTempBlueprint != null) {
                fromTempBlueprint.RemoveFromContainer();
                itemCraftTask.takenItems.Add(fromTempBlueprint);
                itemCraftTask.conditionScale = 0.5f;
            }

            self.queue.Enqueue(itemCraftTask);

            if (itemCraftTask.owner != null) {
                itemCraftTask.owner.Command("note.craft_add", new object[] {
                    itemCraftTask.taskUID,
                    itemCraftTask.blueprint.targetItem.itemid,
                    amount
                });
            }

            return true;
        }
        static void WriteNodeBlock(Dictionary <string, int> keyDict, Dictionary <string, int> valDict, List <int> outputValues, List <DecodeNodeBlockValue> outputNodes, long lastId)
        {
            Func <Stream, byte[], int, int> write = (writeStream, buffer, len) =>
            {
                if (len > 0)
                {
                    writeStream.Write(buffer, 0, len);
                }
                return(-len);
            };

            using (var wdat = File.Create("../tmp/node_sorted_" + lastId + ".dat"))
            {
                var buf = new byte[1048576];
                int p   = 8;

                p += ProtoBuf.WriteVarInt(buf, p, (uint)keyDict.Count);
                foreach (var k in keyDict.OrderBy(x => x.Value).Select(x => x.Key))
                {
                    p += ProtoBuf.WriteString(buf, p, k);
                    if (p > 1000000)
                    {
                        p += write(wdat, buf, p);
                    }
                }
                p += ProtoBuf.WriteVarInt(buf, p, (uint)valDict.Count);
                foreach (var k in valDict.OrderBy(x => x.Value).Select(x => x.Key))
                {
                    p += ProtoBuf.WriteString(buf, p, k);
                    if (p > 1000000)
                    {
                        p += write(wdat, buf, p);
                    }
                }
                p            += write(wdat, buf, p);
                wdat.Position = 0;
                wdat.Write(BitConverter.GetBytes((int)wdat.Length), 0, sizeof(int));
                wdat.Position = wdat.Length;

                p += ProtoBuf.WriteVarInt(buf, p, (uint)(outputValues.Count / 2));
                foreach (var v in outputValues)
                {
                    p += ProtoBuf.WriteVarInt(buf, p, (uint)v);
                    if (p > 1000000)
                    {
                        p += write(wdat, buf, p);
                    }
                }
                p            += write(wdat, buf, p);
                wdat.Position = 4;
                wdat.Write(BitConverter.GetBytes((int)wdat.Length), 0, sizeof(int));
                wdat.Position = wdat.Length;

                p += ProtoBuf.WriteVarInt(buf, p, (uint)outputNodes.Count);
                long pos      = 0;
                long id       = 0;
                int  valuePos = 0;
                foreach (var n in outputNodes)
                {
                    p       += ProtoBuf.WriteVarInt(buf, p, ProtoBuf.UnsignedInt64(n.pos - pos));
                    pos      = n.pos;
                    p       += ProtoBuf.WriteVarInt(buf, p, ProtoBuf.UnsignedInt64(n.id - id));
                    id       = n.id;
                    p       += ProtoBuf.WriteVarInt(buf, p, ProtoBuf.UnsignedInt64(n.valuePos - valuePos));
                    valuePos = n.valuePos;
                    p       += ProtoBuf.WriteVarInt(buf, p, (uint)n.valueCount);
                    if (p > 1000000)
                    {
                        p += write(wdat, buf, p);
                    }
                }
                write(wdat, buf, p);
            }
        }
		protected override void EmitRead(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
		{
			if (arrayType.GetArrayRank() > 1)
			{
				return;
			}

			Type listType;
#if NO_GENERICS
            listType = typeof(BasicList);
#else
			listType = typeof (System.Collections.Generic.List<>).MakeGenericType(itemType);
#endif
            if (nested)
            {
                ctx.LoadReaderWriter();
                ctx.EmitCall(typeof (ProtoReader).GetMethod("ReadFieldHeader"));
                ctx.DiscardValue();
            }

			using (Compiler.Local oldArr = AppendToCollection ? ctx.GetLocalWithValue(ExpectedType, valueFrom) : null)
			using (Compiler.Local newArr = new Compiler.Local(ctx, ExpectedType))
			using (Compiler.Local list = new Compiler.Local(ctx, listType))
			{
				ctx.EmitCtor(listType);
				ctx.StoreValue(list);

				EmitReadArray(ctx, list, oldArr, newArr, Tail, listType.GetMethod("Add"), listType);
			}
		}
Ejemplo n.º 39
0
        static void ConverterTest_1_ExtractNodes()
        {
            Directory.CreateDirectory("../tmp");
            using (var wdatRaw = File.Create("../tmp/node_rawfull.dat"))
                using (var wdatRawIndex = File.Create("../tmp/node_rawfull_index.dat"))
                    using (var pbf = new OsmPbfReader(PbfPath))
                    {
                        long cc = 0;

                        var  rawBuf = new byte[4096];
                        int  rawLen = 0;
                        long rawId  = 0;
                        long rawPos = 0;

                        var  buf     = new byte[2000 * 1048576];
                        int  len     = 0;
                        long lastId  = 0;
                        long lastPos = 0;
                        int  block   = 0;

                        long totalPos = 0;
                        long totalSum = pbf.nodeIndex.Sum(x => x.nodeCount);

                        wdatRawIndex.Write(BitConverter.GetBytes(0L), 0, sizeof(long));
                        wdatRawIndex.Write(BitConverter.GetBytes(0L), 0, sizeof(long));
                        foreach (var node in pbf.ReadAllNodes())
                        {
                            totalPos++;
                            var gpsPos = new GpsPos(node);

                            rawLen += ProtoBuf.WriteVarInt(rawBuf, rawLen, ProtoBuf.UnsignedInt64(node.id - rawId));
                            rawId   = node.id;
                            long nextFullPos = gpsPos.Int64Pos;
                            rawLen += ProtoBuf.WriteVarInt(rawBuf, rawLen, ProtoBuf.UnsignedInt64(nextFullPos - rawPos));
                            rawPos  = nextFullPos;

                            if (rawLen > rawBuf.Length - 18)
                            {
                                while (rawLen < rawBuf.Length)
                                {
                                    rawBuf[rawLen++] = 0;
                                }
                                wdatRaw.Write(rawBuf, 0, rawBuf.Length);
                                wdatRawIndex.Write(BitConverter.GetBytes(rawId + 1), 0, sizeof(long));
                                wdatRawIndex.Write(BitConverter.GetBytes(wdatRaw.Length), 0, sizeof(long));
                                rawLen = 0;
                                rawId  = 0;
                                rawPos = 0;
                            }

                            //todo
                            //if (node.values.Length > 0)
                            //{
                            //  cc++;
                            //  if ((ushort)cc == 0) Console.WriteLine(cc.ToString("N0") + " (" + (100.0 / totalSum * totalPos).ToString("N2") + " %) - " + (len / 1048576.0).ToString("N1") + " MByte / " + (wdatRaw.Length / 1048576.0).ToString("N1") + " MByte");
                            //  len += ProtoBuf.WriteVarInt(buf, len, ProtoBuf.UnsignedInt64(node.id - lastId));
                            //  lastId = node.id;
                            //  long nextPos = gpsPos.Int64Pos;
                            //  len += ProtoBuf.WriteVarInt(buf, len, ProtoBuf.UnsignedInt64(nextPos - lastPos));
                            //  lastPos = nextPos;
                            //  len += ProtoBuf.WriteVarInt(buf, len, (uint)node.values.Length);
                            //  foreach (var v in node.values)
                            //  {
                            //    len += ProtoBuf.WriteString(buf, len, v.Key);
                            //    len += ProtoBuf.WriteString(buf, len, v.Value);
                            //  }
                            //  if (len > buf.Length - 65536)
                            //  {
                            //    block++;
                            //    using (var wdat = File.Create("../tmp/node_block_" + block + "_" + lastId + ".dat"))
                            //    {
                            //      wdat.Write(buf, 0, len);
                            //      len = 0;
                            //      lastId = 0;
                            //      lastPos = 0;
                            //    }
                            //  }
                            //}
                        }
                        if (rawLen > 0)
                        {
                            while (rawLen < rawBuf.Length)
                            {
                                rawBuf[rawLen++] = 0;
                            }
                            wdatRaw.Write(rawBuf, 0, rawBuf.Length);
                        }
                        if (len > 0)
                        {
                            block++;
                            using (var wdat = File.Create("../tmp/node_block_" + block + "_" + lastId + ".dat"))
                            {
                                wdat.Write(buf, 0, len);
                            }
                        }

                        //foreach (var way in pbf.ReadAllWays())
                        //{
                        //  Console.WriteLine(way);
                        //}
                        //foreach (var relation in pbf.ReadAllRelations())
                        //{
                        //  cc++;
                        //  if ((byte)cc == 0)
                        //  {
                        //    Console.WriteLine(cc.ToString("N0") + " - " + relation);
                        //  }
                        //}
                    }
        }
Ejemplo n.º 40
0
 void IProtoTypeSerializer.Callback(object value, ProtoBuf.Meta.TypeModel.CallbackType callbackType,
     SerializationContext context)
 {
 }
Ejemplo n.º 41
0
        protected override void EmitWrite(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
        {
            using (Compiler.Local list = ctx.GetLocalWithValue(ExpectedType, valueFrom))
            {
                MethodInfo moveNext, current, getEnumerator = GetEnumeratorInfo(out moveNext, out current);
                Helpers.DebugAssert(moveNext != null);
                Helpers.DebugAssert(current != null);
                Helpers.DebugAssert(getEnumerator != null);
                Type enumeratorType = getEnumerator.ReturnType;
                bool writePacked = WritePacked;
                using (Compiler.Local iter = new Compiler.Local(ctx, enumeratorType))
                using (Compiler.Local token = writePacked ? new Compiler.Local(ctx, typeof(SubItemToken)) : null)
                {
                    if (writePacked)
                    {
                        ctx.LoadValue(fieldNumber);
                        ctx.LoadValue((int)WireType.String);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(typeof(ProtoWriter).GetMethod("WriteFieldHeader"));

                        ctx.LoadValue(list);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(typeof(ProtoWriter).GetMethod("StartSubItem"));
                        ctx.StoreValue(token);

                        ctx.LoadValue(fieldNumber);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(typeof(ProtoWriter).GetMethod("SetPackedField"));
                    }

                    ctx.LoadAddress(list, ExpectedType);
                    ctx.EmitCall(getEnumerator);
                    ctx.StoreValue(iter);
                    using (ctx.Using(iter))
                    {
                        Compiler.CodeLabel body = ctx.DefineLabel(),
                                           @next = ctx.DefineLabel();
                        
                        
                        ctx.Branch(@next, false);
                        
                        ctx.MarkLabel(body);

                        ctx.LoadAddress(iter, enumeratorType);
                        ctx.EmitCall(current);
                        Type itemType = Tail.ExpectedType;
                        if (itemType != typeof(object) && current.ReturnType == typeof(object))
                        {
                            ctx.CastFromObject(itemType);
                        }
                        Tail.EmitWrite(ctx, null);

                        ctx.MarkLabel(@next);
                        ctx.LoadAddress(iter, enumeratorType);
                        ctx.EmitCall(moveNext);
                        ctx.BranchIfTrue(body, false);
                    }

                    if (writePacked)
                    {
                        ctx.LoadValue(token);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(typeof(ProtoWriter).GetMethod("EndSubItem"));
                    }                    
                }
            }
        }
Ejemplo n.º 42
0
        protected override void EmitRead(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
        {
            /* This looks more complex than it is. Look at the non-compiled Read to
             * see what it is trying to do, but note that it needs to cope with a
             * few more scenarios. Note that it picks the **most specific** Add,
             * unlike the runtime version that uses IList when possible. The core
             * is just a "do {list.Add(readValue())} while {thereIsMore}"
             * 
             * The complexity is due to:
             *  - value types vs reference types (boxing etc)
             *  - initialization if we need to pass in a value to the tail
             *  - handling whether or not the tail *returns* the value vs updates the input
             */
            bool returnList = ReturnList;
            using (Compiler.Local list = AppendToCollection ? ctx.GetLocalWithValue(ExpectedType, valueFrom) : new Compiler.Local(ctx, declaredType))
            using (Compiler.Local origlist = (returnList && AppendToCollection) ? new Compiler.Local(ctx, ExpectedType) : null)
            {
                if (!AppendToCollection)
                { // always new
                    ctx.LoadNullRef();
                    ctx.StoreValue(list);
                }
                else if (returnList)
                { // need a copy
                    ctx.LoadValue(list);
                    ctx.StoreValue(origlist);
                }
                if (concreteType != null)
                {
                    ctx.LoadValue(list);
                    Compiler.CodeLabel notNull = ctx.DefineLabel();
                    ctx.BranchIfTrue(notNull, true);
                    ctx.EmitCtor(concreteType);
                    ctx.StoreValue(list);
                    ctx.MarkLabel(notNull);
                }

                EmitReadList(ctx, list, Tail, add, packedWireType);

                if (returnList)
                {
                    if (AppendToCollection)
                    {
                        // remember ^^^^ we had a spare copy of the list on the stack; now we'll compare
                        ctx.LoadValue(origlist);
                        ctx.LoadValue(list); // [orig] [new-value]
                        Compiler.CodeLabel sameList = ctx.DefineLabel(), allDone = ctx.DefineLabel();
                        ctx.BranchIfEqual(sameList, true);
                        ctx.LoadValue(list);
                        ctx.Branch(allDone, true);
                        ctx.MarkLabel(sameList);
                        ctx.LoadNullRef();
                        ctx.MarkLabel(allDone);
                    }
                    else
                    {
                        ctx.LoadValue(list);
                    }
                }
            }
        }
Ejemplo n.º 43
0
 /// <summary>
 /// Indicates whether the reader still has data remaining in the current sub-item,
 /// additionally setting the wire-type for the next field if there is more data.
 /// This is used when decoding packed data.
 /// </summary>
 public static bool HasSubValue(ProtoBuf.WireType wireType, ProtoReader source)
 {
     // check for virtual end of stream
     if (source.blockEnd <= source.position || wireType == WireType.EndGroup) { return false; } 
     source.wireType = wireType;
     return true;
 }
Ejemplo n.º 44
0
		public bool TryApplyMessage(ProtoBuf.IExtensible message, DemoParser parser)
		{
			CSVCMsg_UserMessage userMessage = message as CSVCMsg_UserMessage;

			if (userMessage == null || !Enum.IsDefined(typeof(ECstrike15UserMessages), userMessage.msg_type))
				return false;

			ECstrike15UserMessages msg = (ECstrike15UserMessages)userMessage.msg_type;
			Type toParse = Assembly.GetExecutingAssembly().GetType("DemoInfo.Messages.CCSUsrMsg_" + msg.ToString().Substring(6));

			using (var memstream = new MemoryStream(userMessage.msg_data))
			{
				ProtoBuf.IExtensible data = memstream.ReadProtobufMessage(toParse);
				if (data != null)
				{
					switch (data.GetType().Name)
					{
						case "CCSUsrMsg_SayText":
							{
								SayTextEventArgs e = new SayTextEventArgs();
								CCSUsrMsg_SayText sayMsg = (CCSUsrMsg_SayText)data;
								e.Text = sayMsg.text;
								e.TextAllChat = sayMsg.textallchat;
								e.Chat = sayMsg.chat;
								parser.RaiseSayText(e);
								break;
							}
						case "CCSUsrMsg_SayText2":
							{
								SayText2EventArgs e = new SayText2EventArgs();
								CCSUsrMsg_SayText2 sayMsg = (CCSUsrMsg_SayText2)data;
								e.TextAllChat = sayMsg.textallchat;
								e.Chat = sayMsg.chat;

								// get the player who wrote the message
								foreach (KeyValuePair<int, Player> keyValuePair in parser.Players)
								{
									if (keyValuePair.Value.Name == sayMsg.@params[0])
									{
										e.Sender = parser.Players[keyValuePair.Key];
										break;
									}
								}

								// @params is a 4 length array but only 2 are used [0] = nickname [1] = message text
								e.Text = sayMsg.@params[0] + " : " + sayMsg.@params[1];
								parser.RaiseSayText2(e);
								break;
							}
						case "CCSUsrMsg_ServerRankUpdate":
							{
								ServerRankUpdateEventArgs e = new ServerRankUpdateEventArgs
								{
									RankStructList = new List<ServerRankUpdateEventArgs.RankStruct>()
								};

								CCSUsrMsg_ServerRankUpdate rankMsg = (CCSUsrMsg_ServerRankUpdate)data;

								foreach (CCSUsrMsg_ServerRankUpdate.RankUpdate rankUpdate in (rankMsg.rank_update))
								{
									ServerRankUpdateEventArgs.RankStruct rankStruct = new ServerRankUpdateEventArgs.RankStruct
									{
										New = rankUpdate.rank_new,
										Old = rankUpdate.rank_old,
										NumWins = rankUpdate.num_wins,
										RankChange = rankUpdate.rank_change,
										SteamId = rankUpdate.account_id + VALVE_MAGIC_NUMBER
									};
									e.RankStructList.Add(rankStruct);
								}

								parser.RaiseServerRankUpdate(e);

								break;
							}
						default:
							// TODO: maybe, like, implement something here one day?
							//Problem: There is no real useful info here if I see it correcly. Sorry.
							//var messageType = (Messages.ECstrike15UserMessages)userMessage.msg_type;
							return true;
					}
				}
				return false;
			}
		}
        protected override void EmitWrite(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
        {
			if (arrayType.GetArrayRank() > 1)
			{
				return;
			}

            // int i and T[] arr
            using (Compiler.Local arr = ctx.GetLocalWithValue(arrayType, valueFrom))
			using (Compiler.Local len = new Compiler.Local(ctx, typeof(int)))
            using (Compiler.Local i = new ProtoBuf.Compiler.Local(ctx, typeof(int)))
			using (Compiler.Local writeObject = new Compiler.Local(ctx, typeof(bool)))
            {
				// int len = arr.Count;
				ctx.LoadValue(arr);
				ctx.LoadValue(arrayType.GetProperty("Length"));
				ctx.StoreValue(len);

				// writeObject = true;
				ctx.LoadValue(true);
				ctx.StoreValue(writeObject);

                bool writePacked = (options & OPTIONS_WritePacked) != 0;
                using (Compiler.Local token = writePacked ? new Compiler.Local(ctx, typeof(SubItemToken)) : null)
                {
                    if (writePacked)
                    {
                        ctx.LoadValue(fieldNumber);
                        ctx.LoadValue((int)WireType.String);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(typeof(ProtoWriter).GetMethod("WriteFieldHeader"));

                        ctx.LoadValue(arr);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(typeof(ProtoWriter).GetMethod("StartSubItem"));
                        ctx.StoreValue(token);

                        ctx.LoadValue(fieldNumber);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(typeof(ProtoWriter).GetMethod("SetPackedField"));
                    }
                    else
                    {
                    	ctx.LoadValue(fieldNumber);
						ctx.LoadValue((int)WireType.Variant);
						ctx.LoadReaderWriter();
						ctx.EmitCall(typeof(ProtoWriter).GetMethod("WriteFieldHeader"));

						if (AsReference)
						{
							using (Compiler.Local existing = new Compiler.Local(ctx, typeof(bool)))
							using (Compiler.Local objectKey = new Compiler.Local(ctx, typeof(int)))
							{
								//int objectKey = dest.NetCache.AddObjectKey(value, out existing);
								ctx.LoadReaderWriter();
								ctx.LoadValue(typeof(ProtoWriter).GetProperty("NetCache")); //dest.NetCache
								ctx.LoadValue(arr);
								ctx.LoadAddress(existing, typeof(bool));
								ctx.EmitCall(typeof(NetObjectCache).GetMethod("AddObjectKey", new Type[] { typeof(object), typeof(bool).MakeByRefType() }));
								ctx.StoreValue(objectKey);

								//writeObject = !existing;
								ctx.LoadValue(existing);

								Compiler.CodeLabel @writeBoolean = ctx.DefineLabel();
								Compiler.CodeLabel @trueCase = ctx.DefineLabel();

								ctx.BranchIfTrue(@trueCase, true);
								ctx.LoadValue(true);
								ctx.Branch(@writeBoolean, true);
								ctx.MarkLabel(@trueCase);
								ctx.LoadValue(false);
								ctx.MarkLabel(@writeBoolean);
								
								ctx.StoreValue(writeObject);

								//ProtoWriter.WriteUInt32(existing ? (uint)objectKey : 0, dest);
								using (Compiler.Local valueToWrite = new Compiler.Local(ctx, typeof(uint)))
								{
                                    ctx.LoadValue(0);
                                    ctx.StoreValue(valueToWrite);

									Compiler.CodeLabel @endValueWrite = ctx.DefineLabel();

									ctx.LoadValue(existing);
									ctx.BranchIfFalse(@endValueWrite, true);

									ctx.LoadValue(objectKey);
									ctx.CastToObject(typeof(uint));
									ctx.StoreValue(valueToWrite);

									ctx.MarkLabel(@endValueWrite);

									ctx.LoadValue(valueToWrite);
									ctx.LoadReaderWriter();
									ctx.EmitCall(typeof(ProtoWriter).GetMethod("WriteUInt32"));
								}
							}
						}
						else
						{
							// bool isEmpty = len == 0;
							// ProtoWriter.WriteBoolean(isEmpty, dest);
							ctx.LoadValue(len);
							ctx.LoadValue(0);
							ctx.TestEqual();
							ctx.LoadReaderWriter();
							ctx.EmitCall(typeof(ProtoWriter).GetMethod("WriteBoolean"));
						}
                    }

                	Compiler.CodeLabel @endWrite = ctx.DefineLabel();
                	ctx.LoadValue(writeObject);
                	ctx.BranchIfFalse(@endWrite, false);

                    EmitWriteArrayLoop(ctx, i, arr);

					ctx.MarkLabel(@endWrite);
						
                    if (writePacked)
                    {
                        ctx.LoadValue(token);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(typeof(ProtoWriter).GetMethod("EndSubItem"));
                    }
                }
            }
        }
Ejemplo n.º 46
0
        protected override void EmitRead(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
        {
            Type listType;
#if NO_GENERICS
            listType = typeof(BasicList);
#else
            listType = ctx.MapType(typeof(System.Collections.Generic.List<>)).MakeGenericType(itemType);
#endif
            Type expected = ExpectedType;
            using (Compiler.Local oldArr = AppendToCollection ? ctx.GetLocalWithValue(expected, valueFrom) : null)
            using (Compiler.Local newArr = new Compiler.Local(ctx, expected))
            using (Compiler.Local list = new Compiler.Local(ctx, listType))
            {
                ctx.EmitCtor(listType);
                ctx.StoreValue(list);
                ListDecorator.EmitReadList(ctx, list, Tail, listType.GetMethod("Add"), packedWireType, false);

                // leave this "using" here, as it can share the "FieldNumber" local with EmitReadList
                using(Compiler.Local oldLen = AppendToCollection ? new ProtoBuf.Compiler.Local(ctx, ctx.MapType(typeof(int))) : null) {
                    Type[] copyToArrayInt32Args = new Type[] { ctx.MapType(typeof(Array)), ctx.MapType(typeof(int)) };

                    if (AppendToCollection)
                    {
                        ctx.LoadLength(oldArr, true);
                        ctx.CopyValue();
                        ctx.StoreValue(oldLen);

                        ctx.LoadAddress(list, listType);
                        ctx.LoadValue(listType.GetProperty("Count"));
                        ctx.Add();
                        ctx.CreateArray(itemType, null); // length is on the stack
                        ctx.StoreValue(newArr);

                        ctx.LoadValue(oldLen);
                        Compiler.CodeLabel nothingToCopy = ctx.DefineLabel();
                        ctx.BranchIfFalse(nothingToCopy, true);
                        ctx.LoadValue(oldArr);
                        ctx.LoadValue(newArr);
                        ctx.LoadValue(0); // index in target

                        ctx.EmitCall(expected.GetMethod("CopyTo", copyToArrayInt32Args));
                        ctx.MarkLabel(nothingToCopy);

                        ctx.LoadValue(list);
                        ctx.LoadValue(newArr);
                        ctx.LoadValue(oldLen);
                        
                    }
                    else
                    {
                        ctx.LoadAddress(list, listType);
                        ctx.LoadValue(listType.GetProperty("Count"));
                        ctx.CreateArray(itemType, null);
                        ctx.StoreValue(newArr);

                        ctx.LoadAddress(list, listType);
                        ctx.LoadValue(newArr);
                        ctx.LoadValue(0);
                    }

                    copyToArrayInt32Args[0] = expected; // // prefer: CopyTo(T[], int)
                    MethodInfo copyTo = listType.GetMethod("CopyTo", copyToArrayInt32Args);
                    if (copyTo == null)
                    { // fallback: CopyTo(Array, int)
                        copyToArrayInt32Args[1] = ctx.MapType(typeof(Array));
                        copyTo = listType.GetMethod("CopyTo", copyToArrayInt32Args);
                    }
                    ctx.EmitCall(copyTo);
                }
                ctx.LoadValue(newArr);
            }


        }
Ejemplo n.º 47
0
 bool IProtoTypeSerializer.HasCallbacks(ProtoBuf.Meta.TypeModel.CallbackType callbackType)
 {
     return false;
 }
Ejemplo n.º 48
0
        /// <summary>
        /// dekodiert nur den Header eines Blockes (benötigt mindestens 32 Bytes)
        /// </summary>
        /// <param name="buf">Buffer, welcher ausgelesen werden soll</param>
        /// <param name="ofs">Startposition innerhalb des Buffers</param>
        /// <param name="result">fertig gelesenes Ergebnis</param>
        /// <returns>Größe des gesamten Blockes in Bytes</returns>
        public static int DecodeQuick(byte[] buf, int ofs, out OsmBlob result)
        {
            /*****
            * message BlobHeader
            * {
            *   required string type = 1;
            *   optional bytes indexdata = 2;
            *   required int32 datasize = 3;
            * }
            *****/

            int len = 0;
            int blobHeaderLen;

            len   += ProtoBuf.ReadInt32Fix(buf, ofs + len, out blobHeaderLen);
            result = new OsmBlob();

            // --- required string type = 1; ---
            string type;

            if (buf[ofs + len++] != (1 << 3 | 2))
            {
                throw new PbfParseException();
            }
            len += ProtoBuf.ReadString(buf, ofs + len, out type);

            // --- optional bytes indexdata = 2; ---
            if (buf[ofs + len] == (2 << 3 | 2))
            {
                throw new NotImplementedException();
            }

            // --- required int32 datasize = 3; ---
            if (buf[ofs + len++] != (3 << 3 | 0))
            {
                throw new PbfParseException();
            }
            ulong tmp;

            len           += ProtoBuf.ReadVarInt(buf, ofs + len, out tmp);
            result.blobLen = len + (int)tmp;
            if (len - sizeof(int) != blobHeaderLen)
            {
                throw new PbfParseException();
            }

            /*****
            * message Blob
            * {
            *   optional bytes raw = 1; // keine Kompression
            *   optional int32 raw_size = 2; // Nur gesetzt, wenn komprimiert, auf die unkomprimierte Größe
            *   optional bytes zlib_data = 3;
            *   // optional bytes lzma_data = 4; // GEPLANT.
            *   // optional bytes OBSOLETE_bzip2_data = 5; // Veraltet.
            * }
            *****/

            // --- optional bytes raw = 1; ---
            if (buf[ofs + len] == (1 << 3 | 2))
            {
                throw new NotSupportedException();
            }

            // --- optional int32 raw_size = 2; ---
            if (buf[ofs + len] == (2 << 3 | 0))
            {
                len++;
                len           += ProtoBuf.ReadVarInt(buf, ofs + len, out tmp);
                result.rawSize = (int)tmp;
            }

            // --- optional bytes zlib_data = 3; ---
            if (buf[ofs + len] == (3 << 3 | 2))
            {
                len++;
                len           += ProtoBuf.ReadVarInt(buf, ofs + len, out tmp);
                result.zlibOfs = len;
                result.zlibLen = (int)tmp;
                len           += (int)tmp;
            }
            else
            {
                // --- optional bytes lzma_data = 4; ---
                if (buf[ofs + len] == (4 << 3 | 2))
                {
                    throw new NotSupportedException();
                }

                // --- optional bytes OBSOLETE_bzip2_data = 5; ---
                if (buf[ofs + len] == (5 << 3 | 2))
                {
                    throw new NotSupportedException();
                }
            }

            if (len != result.blobLen)
            {
                throw new PbfParseException();
            }

            switch (type)
            {
            case "OSMHeader": break;

            case "OSMData": break;

            default: throw new Exception("unknown Type: " + type);
            }

            return(len);
        }
Ejemplo n.º 49
0
        // ItemCrafter.CraftItem()
        public static bool PlayerStartCrafting(ItemCrafter self, ItemBlueprint bp, BasePlayer owner, ProtoBuf.Item.InstanceData instanceData = null, int amount = 1)
        {
            /*ItemBlueprint bpcopy = new ItemBlueprint();
            bpcopy.amountToCreate = bp.amountToCreate;
            bpcopy.defaultBlueprint = bp.defaultBlueprint;
            bpcopy.ingredients = bp.ingredients;
            bpcopy.rarity = bp.rarity;
            bpcopy.targetItem = bp.targetItem;
            bpcopy.time = bp.time / Server.GetInstance().CraftingTimeScale;
            bpcopy.userCraftable = bp.userCraftable;*/
            CraftEvent ce = new CraftEvent(self, bp, owner, instanceData, amount);
            OnPlayerStartCrafting.OnNext(ce);
            if (!self.CanCraft(bp, 1)) {
                return false;
            }
            if (ce.Cancel) {
                if (ce.cancelReason != "")
                    owner.SendConsoleCommand("chat.add", 0, String.Format("{0}: {1}", Server.server_message_name.ColorText("fa5"), ce.cancelReason));
                return false;
            }

            self.taskUID++;
            ItemCraftTask itemCraftTask = new ItemCraftTask();
            itemCraftTask.blueprint = bp;
            if (!ce.FreeCraft) {
                List<Item> list = new List<Item>();
                foreach (ItemAmount current in bp.ingredients) {
                    int amount2 = (int)current.amount * amount;
                    foreach (ItemContainer current2 in self.containers) {
                        amount2 -= current2.Take(list, current.itemid, amount2);
                    }
                }
                foreach (Item current2 in list) {
                    current2.Remove(0f);
                }
            }
            itemCraftTask.endTime = 0;
            itemCraftTask.taskUID = self.taskUID;
            itemCraftTask.owner = owner;
            itemCraftTask.instanceData = instanceData;
            itemCraftTask.amount = amount;
            self.queue.Enqueue(itemCraftTask);
            if (itemCraftTask.owner != null) {
                itemCraftTask.owner.Command("note.craft_add", new object[] {
                    itemCraftTask.taskUID,
                    itemCraftTask.blueprint.targetItem.itemid,
                    amount
                });
            }
            return true;
        }
Ejemplo n.º 50
0
 void IProtoTypeSerializer.EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, ProtoBuf.Meta.TypeModel.CallbackType callbackType)
 {
 }
Ejemplo n.º 51
0
        /// <summary>
        /// Dekodiert die Werte aus einem PBF-Stream
        /// </summary>
        /// <param name="buf">Buffer, worraus die Werte gelesen werden sollen</param>
        /// <param name="ofs">Startposition innerhalb des Buffers</param>
        /// <param name="headerBlock">HeaderBlock-Struktur mit den ausgelesenen Werten</param>
        /// <returns>Anzahl der gelesenen Bytes aus dem Buffer</returns>
        public static int Decode(byte[] buf, int ofs, out HeaderBlock headerBlock)
        {
            /*****
            * message HeaderBlock
            * {
            *   optional HeaderBBox bbox = 1;
            *
            *   // Additional tags to aid in parsing this dataset
            *   repeated string required_features = 4;
            *   repeated string optional_features = 5;
            *
            *   optional string writingprogram = 16;
            *
            *   optional string source = 17; // From the bbox field.
            *
            *   // Tags that allow continuing an Osmosis replication
            *   // replication timestamp, expressed in seconds since the epoch,
            *   // otherwise the same value as in the "timestamp=..." field
            *   // in the state.txt file used by Osmosis
            *   optional int64 osmosis_replication_timestamp = 32;
            *
            *   // replication sequence number (sequenceNumber in state.txt)
            *   optional int64 osmosis_replication_sequence_number = 33;
            *
            *   // replication base URL (from Osmosis' configuration.txt file)
            *   optional string osmosis_replication_base_url = 34;
            * }
            *****/

            int   len = 0;
            ulong tmp;
            var   tmps = new List <string>();

            headerBlock = new HeaderBlock();

            // --- optional HeaderBBox bbox = 1; ---
            if (buf[ofs + len] == (1 << 3 | 2))
            {
                len++;
                len += HeaderBBox.Decode(buf, ofs + len, out headerBlock.bbox);
            }

            // --- repeated string required_features = 4; ---
            tmps.Clear();
            while (buf[ofs + len] == (4 << 3 | 2))
            {
                len++;
                string feature;
                len += ProtoBuf.ReadString(buf, ofs + len, out feature);
                tmps.Add(feature);
                switch (feature)
                {
                case "OsmSchema-V0.6": break;

                case "DenseNodes": break;

                default: throw new PbfParseException("required feature not supported: \"" + feature + "\"");
                }
            }
            headerBlock.requiredFeatures = tmps.ToArray();

            // --- repeated string optional_features = 5; ---
            tmps.Clear();
            while (buf[ofs + len] == (5 << 3 | 2))
            {
                len++;
                string feature;
                len += ProtoBuf.ReadString(buf, ofs + len, out feature);
                tmps.Add(feature);
                switch (feature)
                {
                case "Has_Metadata": break;

                case "Sort.Type_then_ID": break;

                default: throw new PbfParseException("optional feature not supported: \"" + feature + "\"");
                }
            }
            headerBlock.optionalFeatures = tmps.ToArray();

            // --- optional string writingprogram = 16; ---
            if (ProtoBuf.PeekVarInt(buf, ofs + len) == (16 << 3 | 2))
            {
                len += 2;
                len += ProtoBuf.ReadString(buf, ofs + len, out headerBlock.writingprogram);
            }
            else
            {
                headerBlock.writingprogram = "";
            }

            // --- optional string source = 17; ---
            if (ProtoBuf.PeekVarInt(buf, ofs + len) == (17 << 3 | 2))
            {
                len += 2;
                len += ProtoBuf.ReadString(buf, ofs + len, out headerBlock.source);
            }
            else
            {
                headerBlock.source = "";
            }

            // --- optional int64 osmosis_replication_timestamp = 32; ---
            if (ProtoBuf.PeekVarInt(buf, ofs + len) == (32 << 3 | 0))
            {
                len += 2;
                len += ProtoBuf.ReadVarInt(buf, ofs + len, out tmp);
                headerBlock.replicationTimestamp = (long)tmp;
            }

            // --- optional int64 osmosis_replication_sequence_number = 33; ---
            if (ProtoBuf.PeekVarInt(buf, ofs + len) == (33 << 3 | 0))
            {
                len += 2;
                len += ProtoBuf.ReadVarInt(buf, ofs + len, out tmp);
                headerBlock.replicationSequenceNumber = (long)tmp;
            }

            // --- optional string osmosis_replication_base_url = 34; ---
            if (ProtoBuf.PeekVarInt(buf, ofs + len) == (34 << 3 | 2))
            {
                len += 2;
                len += ProtoBuf.ReadString(buf, ofs + len, out headerBlock.replicationBaseUrl);
            }
            else
            {
                headerBlock.replicationBaseUrl = "";
            }

            return(len);
        }