System.Collections.Generic.Dictionary.ContainsKey(int)

Here are the examples of the csharp api System.Collections.Generic.Dictionary.ContainsKey(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3459 Examples 7

19 Source : MemcachedProcess.cs
with MIT License
from 0ffffffffh

public static MemcachedProcess Attach(int pid)
        {
            MemcachedProcess mcproc;
            Process nativeProcess;

            nativeProcess = Process.GetProcessById(pid);

            if (nativeProcess==null)
            {
                Log.Critical("Pid {0} could not be found", pid);
                return null;
            }

            nativeProcess.Exited += Process_Exited;
            nativeProcess.EnableRaisingEvents = true;

            mcproc = new MemcachedProcess();
            mcproc.process = nativeProcess;

            if (!_Processes.ContainsKey(mcproc.process.Id))
                _Processes.Add(mcproc.process.Id, mcproc);

            Log.Info("Pid {0} attached successfuly as memcachedprocess", pid);

            return mcproc;
        }

19 Source : MemcachedProcess.cs
with MIT License
from 0ffffffffh

public static MemcachedProcess FireUp(ulong memSize, ushort port)
        {
            MemcachedProcess mcproc = null;

            string arg;
            ProcessStartInfo psi = null;

            arg = string.Format("-p {0} -m {1}", port,memSize);
            psi = new ProcessStartInfo(Config.Get().MemcachedPath,arg);
            psi.CreateNoWindow = true;
            psi.UseShellExecute = false;

            
            mcproc = new MemcachedProcess();

            try
            {
                mcproc.process = new Process();
                mcproc.process.EnableRaisingEvents = true;
                mcproc.process.Exited += Process_Exited;
                mcproc.process.StartInfo = psi;

                if (!mcproc.process.Start())
                {
                    mcproc.process = null;
                    mcproc = null;

                    Log.Error("Process could not be started");

                    return null;

                }

            }
            catch (Exception e)
            {
                mcproc = null;
                Log.Error("memcached process start error: %s", e.Message);
                return null;
            }

            if (!_Processes.ContainsKey(mcproc.process.Id))
                _Processes.Add(mcproc.process.Id, mcproc);

            return mcproc;
        }

19 Source : MemcachedProcess.cs
with MIT License
from 0ffffffffh

public bool Kill()
        {
            this.process.Kill();
            this.process.WaitForExit(5000);

            if (this.process.HasExited)
            {
                if (_Processes.ContainsKey(this.process.Id))
                    _Processes.Remove(this.process.Id);

                return true;
            }

            return false;
        }

19 Source : StringDedupeContext.cs
with MIT License
from 0x0ade

public void Count(int value) {
            if (Map.ContainsKey(value))
                return;

            if (!Counting.TryGetValue(value, out int count))
                count = 0;
            if (++count >= PromotionCount) {
                Counting.Remove(value);
                Map[value] = new();
            } else {
                Counting[value] = count;
            }

            if (Counting.Count >= MaxCounting)
                Cleanup();
        }

19 Source : AvifWriter.AvifWriterState.cs
with MIT License
from 0xC0000054

private void DeduplicateAlphaTiles(
                IReadOnlyList<CompressedAV1Image> alphaImages,
                replacedgeneousTileInfo replacedgeneousTiles,
                IArrayPoolService arrayPool)
            {
                if (alphaImages.Count == 1)
                {
                    return;
                }

                foreach (KeyValuePair<int, int> item in replacedgeneousTiles.DuplicateAlphaTileMap)
                {
                    this.duplicateAlphaTiles.Add(item.Key, item.Value);
                }

                if (alphaImages.Count == replacedgeneousTiles.replacedgeneousAlphaTiles.Count)
                {
                    return;
                }

                using (IArrayPoolBuffer<int> duplicateTileSearchSpace = GetDuplicateTileSearchSpace(alphaImages,
                                                                                                    replacedgeneousTiles.replacedgeneousAlphaTiles,
                                                                                                    arrayPool))
                {
                    for (int i = 0; i < duplicateTileSearchSpace.Count; i++)
                    {
                        int firstTileIndex = duplicateTileSearchSpace[i];

                        if (this.duplicateAlphaTiles.ContainsKey(firstTileIndex))
                        {
                            continue;
                        }

                        CompressedAV1Data firstImageData = alphaImages[firstTileIndex].Data;
                        IPinnableBuffer firstPinnable = firstImageData;

                        IntPtr firstBuffer = IntPtr.Zero;
                        try
                        {
                            for (int j = i + 1; j < duplicateTileSearchSpace.Count; j++)
                            {
                                int secondTileIndex = duplicateTileSearchSpace[j];

                                if (this.duplicateAlphaTiles.ContainsKey(secondTileIndex))
                                {
                                    continue;
                                }

                                CompressedAV1Data secondImageData = alphaImages[secondTileIndex].Data;

                                if (firstImageData.ByteLength == secondImageData.ByteLength)
                                {
                                    IPinnableBuffer secondPinnable = secondImageData;

                                    if (firstBuffer == IntPtr.Zero)
                                    {
                                        firstBuffer = firstPinnable.Pin();
                                    }
                                    IntPtr secondBuffer = secondPinnable.Pin();
                                    try
                                    {
                                        if (AvifNative.MemoryBlocksAreEqual(firstBuffer, secondBuffer, firstImageData.ByteLength))
                                        {
                                            this.duplicateAlphaTiles.Add(secondTileIndex, firstTileIndex);
                                        }
                                    }
                                    finally
                                    {
                                        secondPinnable.Unpin();
                                    }
                                }
                            }
                        }
                        finally
                        {
                            if (firstBuffer != IntPtr.Zero)
                            {
                                firstPinnable.Unpin();
                            }
                        }
                    }
                }
            }

19 Source : AvifWriter.AvifWriterState.cs
with MIT License
from 0xC0000054

private void DeduplicateColorTiles(
                IReadOnlyList<CompressedAV1Image> colorImages,
                replacedgeneousTileInfo replacedgeneousTiles,
                IArrayPoolService arrayPool)
            {
                if (colorImages.Count == 1)
                {
                    return;
                }

                foreach (KeyValuePair<int, int> item in replacedgeneousTiles.DuplicateColorTileMap)
                {
                    this.duplicateColorTiles.Add(item.Key, item.Value);
                }

                if (colorImages.Count == replacedgeneousTiles.replacedgeneousColorTiles.Count)
                {
                    return;
                }

                using (IArrayPoolBuffer<int> duplicateTileSearchSpace = GetDuplicateTileSearchSpace(colorImages,
                                                                                                    replacedgeneousTiles.replacedgeneousColorTiles,
                                                                                                    arrayPool))
                {
                    for (int i = 0; i < duplicateTileSearchSpace.Count; i++)
                    {
                        int firstTileIndex = duplicateTileSearchSpace[i];

                        if (this.duplicateColorTiles.ContainsKey(firstTileIndex))
                        {
                            continue;
                        }

                        CompressedAV1Data firstImageData = colorImages[firstTileIndex].Data;
                        IPinnableBuffer firstPinnable = firstImageData;

                        IntPtr firstBuffer = IntPtr.Zero;
                        try
                        {
                            for (int j = i + 1; j < duplicateTileSearchSpace.Count; j++)
                            {
                                int secondTileIndex = duplicateTileSearchSpace[j];

                                if (this.duplicateColorTiles.ContainsKey(secondTileIndex))
                                {
                                    continue;
                                }

                                CompressedAV1Data secondImageData = colorImages[secondTileIndex].Data;

                                if (firstImageData.ByteLength == secondImageData.ByteLength)
                                {
                                    IPinnableBuffer secondPinnable = secondImageData;

                                    if (firstBuffer == IntPtr.Zero)
                                    {
                                        firstBuffer = firstPinnable.Pin();
                                    }
                                    IntPtr secondBuffer = secondPinnable.Pin();
                                    try
                                    {
                                        if (AvifNative.MemoryBlocksAreEqual(firstBuffer, secondBuffer, firstImageData.ByteLength))
                                        {
                                            this.duplicateColorTiles.Add(secondTileIndex, firstTileIndex);
                                        }
                                    }
                                    finally
                                    {
                                        secondPinnable.Unpin();
                                    }
                                }
                            }
                        }
                        finally
                        {
                            if (firstBuffer != IntPtr.Zero)
                            {
                                firstPinnable.Unpin();
                            }
                        }
                    }
                }
            }

19 Source : MetroWaterfallFlow.cs
with MIT License
from 1217950746

public void Refresh()
        {
            // 初始化参数
            var maxHeight = 0.0;
            var list = new Dictionary<int, Point>();
            var nlist = new Dictionary<int, Dictionary<int, Point>>();
            for (int i = 0; i < Children.Count; i++)
            {
                (Children[i] as FrameworkElement).UpdateLayout();
                list.Add(i, new Point(i, (Children[i] as FrameworkElement).ActualHeight, 0.0));
            }
            for (int i = 0; i < column; i++)
            {
                nlist.Add(i, new Dictionary<int, Point>());
            }

            // 智能排序到 nlist
            for (int i = 0; i < list.Count; i++)
            {
                if (i < column)
                {
                    list[i].Buttom = list[i].Height;
                    nlist[i].Add(nlist[i].Count, list[i]);
                }
                else
                {
                    var b = 0.0;
                    var l = 0;
                    for (int j = 0; j < column; j++)
                    {
                        var jh = nlist[j][nlist[j].Count - 1].Buttom + list[i].Height;
                        if (b == 0.0 || jh < b)
                        {
                            b = jh;
                            l = j;
                        }
                    }
                    list[i].Buttom = b;
                    nlist[l].Add(nlist[l].Count, list[i]);
                }
            }

            // 开始布局
            for (int i = 0; i < nlist.Count; i++)
            {
                for (int j = 0; j < nlist[i].Count; j++)
                {
                    Children[nlist[i][j].Index].SetValue(LeftProperty, i * ActualWidth / column);
                    Children[nlist[i][j].Index].SetValue(TopProperty, nlist[i][j].Buttom - nlist[i][j].Height);
                    Children[nlist[i][j].Index].SetValue(WidthProperty, ActualWidth / column);

                    if (Children[nlist[i][j].Index] is Grid)
                    {
                        ((Children[nlist[i][j].Index] as Grid).Children[0] as FrameworkElement).Margin = Margin;
                    }
                }

                // 不知道为什么如果不写这么一句会出错
                if (nlist.ContainsKey(i))
                {
                    if (nlist[i].ContainsKey(nlist[i].Count - 1))
                    {
                        var mh = nlist[i][nlist[i].Count - 1].Buttom;
                        maxHeight = mh > maxHeight ? mh : maxHeight;
                    }
                }
            }
            Height = maxHeight;
            list.Clear();
            nlist.Clear();
        }

19 Source : Client.cs
with MIT License
from 1ZouLTReX1

private void RenderServerTick(List<PlayerState> playerStates, List<RayState> rayStates)
    {
        // Every time we encounter an ID when we set the state we remove it from this hashset and then 
        // disconnect all the players that left in the hashset.
        HashSet<int> DisconnectedPlayersIds = new HashSet<int>(PlayerFromId.Keys);

        foreach (PlayerState ps in playerStates)
        {
            // Since we got the id in the players state this ps.Id client is still connected thus we remove it from the hashset.
            DisconnectedPlayersIds.Remove(ps.playerId);

            if (PlayerFromId.ContainsKey(ps.playerId))
            {
                // Update Scene from the new given State
                PlayerFromId[ps.playerId].FromState(ps);
            }
            else
            {
                var obj = Instantiate(playerPrefab, Vector3.zero, Quaternion.idenreplacedy);
                var tmpPlayer = obj.GetComponent<Player>();
                tmpPlayer.SetPlayerID(ps.playerId);
                // The replicated gameobjects shouldn't be simulated
                tmpPlayer.rb.simulated = false;

                tmpPlayer.FromState(ps);
                PlayerFromId.Add(ps.playerId, tmpPlayer);
            }
        }

        foreach (RayState rs in rayStates)
        {
            PlayerFromId[rs.owner].FromState(rs);
        }

        // Only the clients that were in the hashset beforehand but got removed is here 
        // (since they are disconnected they are no longer in the snapshots).
        foreach (int playerId in DisconnectedPlayersIds)
        {
            if (playerId == myID)
            {
                Application.Quit();
            }

            Destroy(PlayerFromId[playerId].playerContainer);
            PlayerFromId.Remove(playerId);
        }
    }

19 Source : LandLord.cs
with Apache License 2.0
from 2881099

public static List<int> OrderPaiLordWithColor(List<int> paiarr)
        {
            List<int> _tempList = new List<int>(paiarr);
            for (int i = 0; i < _tempList.Count; i++)
            {
                if (_tempList[i] > 100) _tempList[i] %= 100;
            }
            int[] temparr = _tempList.ToArray<int>();
            Array.Sort<int>(temparr);
            List<int> _ASCList = temparr.ToList<int>();
            _ASCList.Reverse();//默认是升序反转一下就降序了

            //带上花色,有点小复杂 
            Dictionary<int, int> _dicPoker2Count = GetPoker_Count(_ASCList);
            Dictionary<int, int> _dicPoker2CountUsed = new Dictionary<int, int>();
            for (int j = 0; j < _ASCList.Count; j++)
            {
                if (!_dicPoker2CountUsed.ContainsKey(_ASCList[j])) _dicPoker2CountUsed.Add(_ASCList[j], 1);

                for (int c = _dicPoker2CountUsed[_ASCList[j]]; c <= 4; c++)
                {
                    _dicPoker2CountUsed[_ASCList[j]]++;
                    if (paiarr.Contains(_ASCList[j] + 100 * c))
                    {
                        _ASCList[j] = _ASCList[j] + 100 * c;
                        break;
                    }
                }
            }
            return _ASCList;
        }

19 Source : LandLord.cs
with Apache License 2.0
from 2881099

public static List<int> GetPaiColor(List<int> _shoupai, List<int> pokervalue)
        {
            List<int> _ASCList = new List<int>(pokervalue);
            //带上花色,有点小复杂 
            Dictionary<int, int> _dicPoker2Count = GetPoker_Count(_ASCList);
            Dictionary<int, int> _dicPoker2CountUsed = new Dictionary<int, int>();
            for (int j = 0; j < _ASCList.Count; j++)
            {
                if (!_dicPoker2CountUsed.ContainsKey(_ASCList[j])) _dicPoker2CountUsed.Add(_ASCList[j], 1);

                for (int c = _dicPoker2CountUsed[_ASCList[j]]; c <= 4; c++)
                {
                    _dicPoker2CountUsed[_ASCList[j]]++;
                    if (_shoupai.Contains(_ASCList[j] + 100 * c))
                    {
                        _ASCList[j] = _ASCList[j] + 100 * c;
                        break;
                    }
                }
            }
            return _ASCList;
        }

19 Source : LandLord.cs
with Apache License 2.0
from 2881099

public static Dictionary<int, int> GetPoker_Count(List<int> paiList)
        {
            Dictionary<int, int> _dicPoker2Count = new Dictionary<int, int>();
            foreach (int poke in paiList)
            {
                if (_dicPoker2Count.ContainsKey(poke)) _dicPoker2Count[poke]++;
                else _dicPoker2Count.Add(poke, 1);
            }
            return _dicPoker2Count;
        }

19 Source : GrblCodeTranslator.cs
with MIT License
from 3RD-Dimension

public static string GetErrorMessage(int errorCode, bool alarm = false)
		{
			if (!alarm)
			{
				if (Errors.ContainsKey(errorCode))
					return Errors[errorCode];
				else
					return $"Unknown Error: {errorCode}";
			}
			else
			{
				if (Alarms.ContainsKey(errorCode))
					return Alarms[errorCode];
				else
					return $"Unknown Alarm: {errorCode}";
			}
		}

19 Source : GrblSettingsWindow.xaml.cs
with MIT License
from 3RD-Dimension

public void LineReceived(string line)
        {
            // Recieve GRBL Controller Version number and display - $i
            // Recieved in format [VER: ... and [OPT:

            if (!line.StartsWith("$") && !line.StartsWith("[VER:") && !line.StartsWith("[OPT:"))
                return;

            if (line.StartsWith("$"))
            {
                try
                {
                    Match m = settingParser.Match(line);
                    int number = int.Parse(m.Groups[1].Value);
                    double value = double.Parse(m.Groups[2].Value, Util.Constants.DecimalParseFormat);

                    // Value = Setting Value, Number = Setting Code

                    if (!CurrentSettings.ContainsKey(number))
                    {
                        RowDefinition rowDef = new RowDefinition();
                        rowDef.Height = new GridLength(25);
                        gridMain.RowDefinitions.Add(rowDef);

                        TextBox valBox = new TextBox // Value of Setting Textbox
                        {
                            Text = value.ToString(Util.Constants.DecimalOutputFormat),
                            VerticalAlignment = VerticalAlignment.Center
                        };

                        // Define Mouseclick for textbox to open GRBLStepsCalcWindow for setting $100, $101, $102
                        if (number == 100) { valBox.Name = "Set100"; valBox.MouseDoubleClick += openStepsCalc; }
                        else if (number == 101) { valBox.Name = "Set101"; valBox.MouseDoubleClick += openStepsCalc; }
                        else if (number == 102) { valBox.Name = "Set102"; valBox.MouseDoubleClick += openStepsCalc; }
                        Grid.SetRow(valBox, gridMain.RowDefinitions.Count - 1);
                        Grid.SetColumn(valBox, 1);
                        gridMain.Children.Add(valBox);

                        TextBlock num = new TextBlock
                        {
                            Text = $"${number}=",
                            HorizontalAlignment = HorizontalAlignment.Right,
                            VerticalAlignment = VerticalAlignment.Center
                        };
                        Grid.SetRow(num, gridMain.RowDefinitions.Count - 1);
                        Grid.SetColumn(num, 0);
                        gridMain.Children.Add(num);

                        if (Util.GrblCodeTranslator.Settings.ContainsKey(number))
                        {
                            Tuple<string, string, string> labels = Util.GrblCodeTranslator.Settings[number];

                            TextBlock name = new TextBlock
                            {
                                Text = labels.Item1,
                                VerticalAlignment = VerticalAlignment.Center
                            };
                            Grid.SetRow(name, gridMain.RowDefinitions.Count - 1);
                            Grid.SetColumn(name, 0);
                            gridMain.Children.Add(name);

                            TextBlock unit = new TextBlock
                            {
                                Text = labels.Item2,
                                VerticalAlignment = VerticalAlignment.Center
                            };
                            Grid.SetRow(unit, gridMain.RowDefinitions.Count - 1);
                            Grid.SetColumn(unit, 2);
                            gridMain.Children.Add(unit);

                            valBox.ToolTip = $"{labels.Item1} ({labels.Item2}):\n{labels.Item3}";
                        }

                        CurrentSettings.Add(number, value);
                        SettingsBoxes.Add(number, valBox);
                    }
                    else
                    {
                        SettingsBoxes[number].Text = value.ToString(Util.Constants.DecimalOutputFormat);
                        CurrentSettings[number] = value;
                    }
                }
                catch { }
            }
            // If the line starts with [VER: then we know we are getting the version and options
            else if (line.StartsWith("[VER:") || line.StartsWith("[OPT:"))
            {
                // Frist need to remove front [ and rear ]
                string VerOptInput; // Input string
                string[] VerOptTrimmed;
                VerOptInput = line.Remove(0, 1); // Remove [ from the start
                VerOptInput = VerOptInput.Remove(VerOptInput.Length - 1);

                // Next, split the values in half at the : - we only want VER/OPT and then the values
                VerOptTrimmed = VerOptInput.Split(':');

                // Now we fill in the boxes depending on which one
                switch (VerOptTrimmed[0])
                {
                    case "VER":
                        controllerInfo += "Version: " + VerOptTrimmed[1];
                        break;

                    case "OPT":
                        // First we have to split commas
                        string[] optSplit;
                        optSplit = VerOptTrimmed[1].Split(','); // Splits Options into 3.  0=Options, 1=blockBufferSize, 2=rxBufferSize
                        var individualChar = optSplit[0].ToCharArray();// Now split optSplit[0] into each option character

                        controllerInfo += " | Options: " + VerOptTrimmed[1]; // Full Options Non-Decoded String

                        foreach (char c in individualChar)
                        {
                            // Lookup what each code is and display....  buildCodes Dictionary
                            if (Util.GrblCodeTranslator.BuildCodes.ContainsKey(c.ToString()))
                            {
                                // Now lets try and create and append to a string and then bind it to a ToolTip? or some other way
                                controllerInfo += Environment.NewLine + Util.GrblCodeTranslator.BuildCodes[c.ToString()];
                            }
                        }
                        controllerInfo += Environment.NewLine + "Block Buffer Size: " + optSplit[1];
                        controllerInfo += Environment.NewLine + "RX Buffer Size: " + optSplit[2];
                        GRBL_Controller_Info.Text = controllerInfo.ToString();
                        break;
                }
            }
        }

19 Source : CutMesh.cs
with GNU Affero General Public License v3.0
from 3drepo

private Mesh GetMesh(RepoForUnity.MeshLocation[] meshLocations)
    {
        List<Vector3> vertices = new List<Vector3>();
        List<Vector3> normal = new List<Vector3>();
        List<int> triangles = new List<int>();

        foreach (var entry in meshLocations)
        {
            var go = GameObject.Find(entry.superMeshID);
            var meshFilter = go.GetComponent<MeshFilter>();
            var superMesh = meshFilter.mesh;
            Dictionary<int, int> vIndexChange = new Dictionary<int, int>();
            for (int i = 0; i < superMesh.uv2.Length; ++i)
            {
                if (superMesh.uv2[i].y == entry.index)
                {
                    vIndexChange[i] = vertices.Count;
                    vertices.Add(superMesh.vertices[i]);
                    normal.Add(superMesh.normals[i]);
                }
            }

            for (int i = 0; i < superMesh.triangles.Length; ++i)
            {
                var index = superMesh.triangles[i];
                if (vIndexChange.ContainsKey(index))
                {
                    triangles.Add(vIndexChange[index]);
                }
            }
        }

        var mesh = new Mesh();
        mesh.vertices = vertices.ToArray();
        mesh.normals = normal.ToArray();
        mesh.triangles = triangles.ToArray();
        return mesh;
    }

19 Source : PacketLogger.cs
with BSD 3-Clause "New" or "Revised" License
from 3gstudent

public void AddBlob(PacketType type, byte[] data, string socket)
        {
            if (!this.m_Blobs.ContainsKey(this.BuildBlobId(type, socket)))
            {
                this.m_Blobs.Add(this.BuildBlobId(type, socket), new PacketBlob(data, type));
            }
        }

19 Source : ReceivePacket.cs
with MIT License
from 499116344

internal void TlvExecutionProcessing(ICollection<Tlv> tlvs)
        {
            if (_tlvTypes == null)
            {
                var types = replacedembly.GetExecutingreplacedembly().GetTypes();
                _tlvTypes = new Dictionary<int, Type>();
                foreach (var type in types)
                {
                    var attributes = type.GetCustomAttributes();
                    if (!attributes.Any(attr => attr is TlvTagAttribute))
                    {
                        continue;
                    }

                    var attribute = attributes.First(attr => attr is TlvTagAttribute) as TlvTagAttribute;
                    _tlvTypes.Add((int) attribute.Tag, type);
                }
            }
            foreach (var tlv in tlvs)
            {
                if (_tlvTypes.ContainsKey(tlv.Tag))
                {
                    var tlvClreplaced = replacedembly.GetExecutingreplacedembly().CreateInstance(_tlvTypes[tlv.Tag].FullName, true);
                    var methodinfo = _tlvTypes[tlv.Tag].GetMethod("Parser_Tlv");
                    methodinfo.Invoke(tlvClreplaced, new object[] { User, Reader });
                }
            }
        }

19 Source : Redirection.Reactive.cs
with MIT License
from 71

private static MethodRedirection CreateDynamicRedirection(MethodBase method, out int id)
        {
            // Make id
            do
            {
                id = ObservingRedirectionsIdGenerator.Next();
            }
            while (ObservingRedirections.ContainsKey(id));

            // Creates an array containing all parameter types
            int diff = method.IsStatic ? 0 : 1;

            ParameterInfo[] originalParameters = method.GetParameters();
            Type[] originalParameterTypes = new Type[originalParameters.Length + diff];

            if (diff == 1 /* !method.IsStatic */)
                originalParameterTypes[0] = method.DeclaringType;

            for (int i = 0; i < originalParameters.Length; i++)
            {
                originalParameterTypes[i + diff] = originalParameters[i].ParameterType;
            }

            // Create an identical method
            bool isCtor = method is ConstructorInfo;
            Type returnType = isCtor ? typeof(void) : ((MethodInfo)method).ReturnType;

            DynamicMethod dyn = new DynamicMethod(
                name:              method.Name,
                attributes:        MethodAttributes.Public | MethodAttributes.Static,
                callingConvention: CallingConventions.Standard,
                returnType:        returnType,
                parameterTypes:    originalParameterTypes,
                owner:             method.DeclaringType,
                skipVisibility:    true);

            // Make the method call the observable
            ILGenerator il = dyn.GetILGenerator();
            {
                // This is in a block to make every more readable,
                // the following comments describe what's happening in the generated method.

                // Emit "this", or "null"
                if (method.IsStatic)
                {
                    il.Emit(OpCodes.Ldnull);
                }
                else
                {
                    il.Emit(OpCodes.Ldarg_0);

                    if (method.DeclaringType.GetTypeInfo().IsValueType)
                    {
                        il.Emit(OpCodes.Ldobj, method.DeclaringType);
                        il.Emit(OpCodes.Box, method.DeclaringType);
                    }
                }

                // Create an array containing all parameters
                il.Emit(OpCodes.Ldc_I4, originalParameters.Length);
                il.Emit(OpCodes.Newarr, typeof(object));

                for (int i = 0; i < originalParameters.Length; i++)
                {
                    il.Emit(OpCodes.Dup);
                    il.Emit(OpCodes.Ldc_I4, i);
                    il.Emit(OpCodes.Ldarg, i + diff);

                    Type parameterType = originalParameterTypes[i + diff];

                    if (parameterType.GetTypeInfo().IsValueType)
                        il.Emit(OpCodes.Box, parameterType);

                    il.Emit(OpCodes.Stelem_Ref);
                }

                // Array is still on stack (thanks to dup)
                // Emit id
                il.Emit(OpCodes.Ldc_I4, id);

                // Call "hook" method
                il.Emit(OpCodes.Call, typeof(Redirection).GetMethod(nameof(OnInvoked), BindingFlags.Static | BindingFlags.NonPublic));

                // Return returned result
                // (But first, cast it if needed)
                if (returnType == typeof(void))
                    il.Emit(OpCodes.Pop);
                else if (returnType.GetTypeInfo().IsValueType)
                    il.Emit(OpCodes.Unbox_Any, returnType);
                else if (returnType != typeof(object))
                    il.Emit(OpCodes.Castclreplaced, returnType);

                il.Emit(OpCodes.Ret);
            }

            // Return the redirection
            return new MethodRedirection(method, dyn, false);
        }

19 Source : DialogueSystem.cs
with MIT License
from 7ark

void BuildWindows()
    {
        if (CheckDialogue() && !CheckDialogueExists()) return;

        for (int j = 0; j < CurrentDialogue.Set[CurrentDialogue.CurrentSet].Windows.Count; j++)
        {
            Dialogues.Window WindowList = CurrentDialogue.Set[CurrentDialogue.CurrentSet].Windows[j];

            List<Dialogues.Window> PrevWindow = FindPreviousWindows(WindowList);
            if (PrevWindow != null)
            {
                for (int i = 0; i < PrevWindow.Count; i++)
                {
                    if (PrevWindow[i].Type == Dialogues.WindowTypes.Choice)
                    {
                        WindowList.Type = Dialogues.WindowTypes.ChoiceAnswer;
                        break;
                    }
                    if (PrevWindow[i].Type == Dialogues.WindowTypes.ChoiceAnswer && WindowList.Type == Dialogues.WindowTypes.ChoiceAnswer)
                        WindowList.Type = Dialogues.WindowTypes.Text;
                    if (PrevWindow[i].Type == Dialogues.WindowTypes.Text && WindowList.Type == Dialogues.WindowTypes.ChoiceAnswer)
                        WindowList.Type = Dialogues.WindowTypes.Text;
                }
            }

            //Default naming
            string BoxName = "";
            switch (WindowList.Type)
            {
                case Dialogues.WindowTypes.Text:
                    BoxName = "Dialogue";
                    break;
                case Dialogues.WindowTypes.Choice:
                    BoxName = "Decision";
                    break;
                case Dialogues.WindowTypes.ChoiceAnswer:
                    BoxName = "Option";
                    break;
            }
            //Determines what type of node it is
            if (WindowList.Connections.Count == 0 && WindowList != CurrentDialogue.Set[CurrentDialogue.CurrentSet].FirstWindow && WindowList.Type != Dialogues.WindowTypes.Choice)
                WindowList.NodeType = Dialogues.NodeType.End;
            else if (WindowList.ID == CurrentDialogue.Set[CurrentDialogue.CurrentSet].FirstWindow.ID)
                WindowList.NodeType = Dialogues.NodeType.Start;
            else
                WindowList.NodeType = Dialogues.NodeType.Default;

            //Changes the name accordingly
            if (WindowList.Type != Dialogues.WindowTypes.Choice)
            {
                switch (WindowList.NodeType)
                {
                    case Dialogues.NodeType.Start:
                        BoxName = "Start";
                        break;
                    case Dialogues.NodeType.End:
                        BoxName = "End";
                        if (WindowList.Type == Dialogues.WindowTypes.ChoiceAnswer)
                            BoxName = "End (Option)";
                        break;
                    default: break;
                }
            }

            //Sets up the ID for the window
            object[] Vals = { WindowList };
            if (!Ids.ContainsKey(WindowList.ID))
                Ids.Add(WindowList.ID, Vals);

            //Creates the actual window
            string Style = "flow node 0";
            if (WindowList.Type == Dialogues.WindowTypes.Choice) Style = "flow node 3";
            if (WindowList.NodeType == Dialogues.NodeType.Start) Style = "flow node 1";
            if (WindowList.Type == Dialogues.WindowTypes.ChoiceAnswer) Style = "flow node 2";
            if (WindowList.NodeType == Dialogues.NodeType.End) Style = "flow node 6";
            if (WindowList.Type == Dialogues.WindowTypes.Choice && WindowList.Connections.Count == 0) Style = "flow node 4";

            GUIStyle FinalStyle = new GUIStyle(Style);
            FinalStyle.fontSize = 14;
            FinalStyle.contentOffset = new Vector2(0, -30);
            CheckPosition(WindowList);
            WindowList.Size = GUI.Window(WindowList.ID, WindowList.Size, WindowFunction, BoxName, FinalStyle);

        }

    }

19 Source : DialogueSystem.cs
with MIT License
from 7ark

void WindowFunction(int windowID)
    {
        if (!Ids.ContainsKey(windowID)) return;
        Dialogues.Window Win = (Dialogues.Window)Ids[windowID][0];

        int xSize = 150;
        int ySize = 84;

        if(Win.Type != Dialogues.WindowTypes.Choice)
        {
            if(GUI.Button(new Rect(0, 0, 15, 15), "-")) AddWindowBefore(Win);
            if(GUI.Button(new Rect(135, 0, 15, 15), "+")) AddWindowAfter(Win) ;
        }

        Win.Trigger = GUI.Toggle(new Rect(10, 100, 60, 30), Win.Trigger, "Trigger");
        if (Win.Trigger)
        {
            Win.TriggerText = GUI.TextField(new Rect(70, 100, 70, 20), Win.TriggerText);
        }
        else
            Win.TriggerText = "";

        Win.Text = GUI.TextArea(new Rect(0, 15, xSize, ySize), Win.Text);

        GUI.DragWindow();
    }

19 Source : AssetsFile.cs
with MIT License
from 91Act

private void readBase5()
        {
            int clreplacedID = a_Stream.ReadInt32();
            if (fileGen > 15)//5.5.0 and up
            {
                a_Stream.ReadByte();
                int type1;
                if ((type1 = a_Stream.ReadInt16()) >= 0)
                {
                    type1 = -1 - type1;
                }
                else
                {
                    type1 = clreplacedID;
                }
                clreplacedIDs.Add(new[] { type1, clreplacedID });
                clreplacedID = type1;
                /*TODO 用来替换下方的代码
                if(clreplacedID == 114)
                {
                    a_Stream.Position += 16;
                }*/
                var temp = a_Stream.ReadInt32();
                if (temp == 0)
                {
                    a_Stream.Position += 16;
                }
                a_Stream.Position -= 4;
                if (type1 < 0)
                {
                    a_Stream.Position += 16;
                }
            }
            else if (clreplacedID < 0)
            {
                a_Stream.Position += 16;
            }
            a_Stream.Position += 16;

            if (baseDefinitions)
            {
                int varCount = a_Stream.ReadInt32();
                int stringSize = a_Stream.ReadInt32();

                a_Stream.Position += varCount * 24;
                string varStrings = Encoding.UTF8.GetString(a_Stream.ReadBytes(stringSize));
                string clreplacedName = "";
                var clreplacedVar = new List<ClreplacedMember>();
                //build Clreplaced Structures
                a_Stream.Position -= varCount * 24 + stringSize;
                for (int i = 0; i < varCount; i++)
                {
                    ushort num0 = a_Stream.ReadUInt16();
                    byte level = a_Stream.ReadByte();
                    bool isArray = a_Stream.ReadBoolean();

                    ushort varTypeIndex = a_Stream.ReadUInt16();
                    ushort test = a_Stream.ReadUInt16();
                    string varTypeStr;
                    if (test == 0) //varType is an offset in the string block
                    { varTypeStr = varStrings.Substring(varTypeIndex, varStrings.IndexOf('\0', varTypeIndex) - varTypeIndex); }//substringToNull
                    else //varType is an index in an internal strig array
                    { varTypeStr = baseStrings.ContainsKey(varTypeIndex) ? baseStrings[varTypeIndex] : varTypeIndex.ToString(); }

                    ushort varNameIndex = a_Stream.ReadUInt16();
                    test = a_Stream.ReadUInt16();
                    string varNameStr;
                    if (test == 0) { varNameStr = varStrings.Substring(varNameIndex, varStrings.IndexOf('\0', varNameIndex) - varNameIndex); }
                    else { varNameStr = baseStrings.ContainsKey(varNameIndex) ? baseStrings[varNameIndex] : varNameIndex.ToString(); }

                    int size = a_Stream.ReadInt32();
                    int index = a_Stream.ReadInt32();
                    int flag = a_Stream.ReadInt32();

                    if (index == 0) { clreplacedName = varTypeStr + " " + varNameStr; }
                    else
                    {
                        clreplacedVar.Add(new ClreplacedMember()
                        {
                            Level = level - 1,
                            Type = varTypeStr,
                            Name = varNameStr,
                            Size = size,
                            Flag = flag
                        });
                    }
                }
                a_Stream.Position += stringSize;

                var aClreplaced = new ClreplacedStruct() { ID = clreplacedID, Text = clreplacedName, members = clreplacedVar };
                aClreplaced.SubItems.Add(clreplacedID.ToString());
                ClreplacedStructures[clreplacedID] = aClreplaced;
            }
        }

19 Source : RoadPointer.cs
with MIT License
from a3geek

public static void AddRoadID(int id, int roadID)
        {
            if(Points.ContainsKey(id) == false)
            {
                return;
            }

            Points[id].Value.Add(roadID);
        }

19 Source : Manager.cs
with GNU General Public License v3.0
from a2659802

public int SwitchGroup(int span = 1)
        {
            var next_group = CurrentGroup + span;
            if (!group.ContainsKey(next_group))
                next_group = 1;
            CurrentGroup = next_group;
            SetupFlag.GetComponent<TextMeshPro>().text = $"Editing [{CurrentGroup}]";

            GroupSwitchEventHandler?.Invoke(group[CurrentGroup]);

            return CurrentGroup;
        }

19 Source : OverlayLibrary.cs
with Apache License 2.0
from A7ocin

override public void UpdateDictionary()
		{
			ValidateDictionary();
			overlayDictionary.Clear();
			for (int i = 0; i < overlayElementList.Length; i++)
			{
				if (overlayElementList[i])
				{
					var hash = UMAUtils.StringToHash(overlayElementList[i].overlayName);
					if (!overlayDictionary.ContainsKey(hash))
					{
						overlayDictionary.Add(hash, overlayElementList[i]);
					}
				}
			}
		}

19 Source : OverlayLibrary.cs
with Apache License 2.0
from A7ocin

public override bool HasOverlay(string Name)
		{
			ValidateDictionary();
			var hash = UMAUtils.StringToHash(Name);
			return overlayDictionary.ContainsKey(hash);
		}

19 Source : OverlayLibrary.cs
with Apache License 2.0
from A7ocin

public override bool HasOverlay(int NameHash)
		{
			ValidateDictionary();
			return overlayDictionary.ContainsKey(NameHash);
		}

19 Source : OverlayLibrary.cs
with Apache License 2.0
from A7ocin

public override void AddOverlayreplacedet(OverlayDatareplacedet overlay)
		{
			ValidateDictionary();
			var hash = UMAUtils.StringToHash(overlay.overlayName);
			if (overlayDictionary.ContainsKey(hash))
			{
				for (int i = 0; i < overlayElementList.Length; i++)
				{
					if (overlayElementList[i].overlayName == overlay.overlayName)
					{
						overlayElementList[i] = overlay;
						break;
					}
				}
			}
			else
			{
				var list = new OverlayDatareplacedet[overlayElementList.Length + 1];
				for (int i = 0; i < overlayElementList.Length; i++)
				{
					list[i] = overlayElementList[i];
				}
				list[list.Length - 1] = overlay;
				overlayElementList = list;
			}
			overlayDictionary[hash] = overlay;
		}

19 Source : SlotLibrary.cs
with Apache License 2.0
from A7ocin

override public void UpdateDictionary()
		{
			ValidateDictionary();
			slotDictionary.Clear();
			for (int i = 0; i < slotElementList.Length; i++)
			{
				if (slotElementList[i])
				{
					var hash = slotElementList[i].nameHash;
					if (!slotDictionary.ContainsKey(hash))
					{
						slotDictionary.Add(hash, slotElementList[i]);
					}
				}
			}
		}

19 Source : SlotLibrary.cs
with Apache License 2.0
from A7ocin

public override void AddSlotreplacedet(SlotDatareplacedet slot)
		{
			ValidateDictionary();
			if (slotDictionary.ContainsKey(slot.nameHash))
			{
				for (int i = 0; i < slotElementList.Length; i++)
				{
					if (slotElementList[i].slotName == slot.slotName)
					{
						slotElementList[i] = slot;
						break;
					}
				}
			}
			else
			{
				var list = new SlotDatareplacedet[slotElementList.Length + 1];
				for (int i = 0; i < slotElementList.Length; i++)
				{
					list[i] = slotElementList[i];
				}
				list[list.Length - 1] = slot;
				slotElementList = list;
			}
			slotDictionary[slot.nameHash] = slot;
		}

19 Source : SlotLibrary.cs
with Apache License 2.0
from A7ocin

public override bool Hreplacedlot(string name)
		{
			ValidateDictionary();
			return slotDictionary.ContainsKey(UMAUtils.StringToHash(name));
		}

19 Source : SlotLibrary.cs
with Apache License 2.0
from A7ocin

public override bool Hreplacedlot(int nameHash)
		{
			ValidateDictionary();
			return slotDictionary.ContainsKey(nameHash);
		}

19 Source : RoadPointer.cs
with MIT License
from a3geek

public static List<int> GetRoadsID(int id)
        {
            if(Points.ContainsKey(id) == false)
            {
                return new List<int>();
            }

            return Points[id].Value;
        }

19 Source : RoadPointer.cs
with MIT License
from a3geek

public static Vector2 GetPoint(int id)
        {
            return Points.ContainsKey(id) == true ? Points[id].Key : Vector2.zero;
        }

19 Source : UMAData.cs
with Apache License 2.0
from A7ocin

public void RegisterAnimatedBone(int hash)
		{
			if (!animatedBonesTable.ContainsKey(hash))
			{
				animatedBonesTable.Add(hash, animatedBonesTable.Count);
			}
		}

19 Source : UMAData.cs
with Apache License 2.0
from A7ocin

public void RegisterAnimatedBoneHierarchy(int hash)
		{
			if (!animatedBonesTable.ContainsKey(hash))
			{
				animatedBonesTable.Add(hash, animatedBonesTable.Count);
			}
		}

19 Source : UMAData.cs
with Apache License 2.0
from A7ocin

public void EnsureAllDNAPresent()
			{
				List<int> requiredDnas = new List<int>();
				if (raceData != null)
				{
					foreach (var converter in raceData.dnaConverterList)
					{
						var dnaTypeHash = converter.DNATypeHash;
						//'old' dna converters return a typehash based on the type name. 
						//Dynamic DNA Converters return the typehash of their dna replacedet or 0 if none is replacedigned- we dont want to include those
						if (dnaTypeHash == 0)
						continue;
						requiredDnas.Add(dnaTypeHash);
                        if (!umaDna.ContainsKey(dnaTypeHash))
						{
							var dna = converter.DNAType.GetConstructor(System.Type.EmptyTypes).Invoke(null) as UMADnaBase;
							dna.DNATypeHash = dnaTypeHash;
							//DynamireplacedADna:: needs the DNAreplacedet from the converter - moved because this might change
							if (converter is DynamicDNAConverterBehaviourBase)
							{
								((DynamireplacedADnaBase)dna).dnareplacedet = ((DynamicDNAConverterBehaviourBase)converter).dnareplacedet;
							}
							umaDna.Add(dnaTypeHash, dna);
							dnaValues.Add(dna);
						}
						else if (converter is DynamicDNAConverterBehaviourBase)
						{
							var dna = umaDna[dnaTypeHash];
							((DynamireplacedADnaBase)dna).dnareplacedet = ((DynamicDNAConverterBehaviourBase)converter).dnareplacedet;
						}
					}
				}
				foreach (var slotData in slotDataList)
				{
					if (slotData != null && slotData.replacedet.slotDNA != null)
					{
						var dnaTypeHash = slotData.replacedet.slotDNA.DNATypeHash;
						//'old' dna converters return a typehash based on the type name. 
						//Dynamic DNA Converters return the typehash of their dna replacedet or 0 if none is replacedigned- we dont want to include those
						if (dnaTypeHash == 0)
							continue;
						requiredDnas.Add(dnaTypeHash);
						if (!umaDna.ContainsKey(dnaTypeHash))
						{
							var dna = slotData.replacedet.slotDNA.DNAType.GetConstructor(System.Type.EmptyTypes).Invoke(null) as UMADnaBase;
							dna.DNATypeHash = dnaTypeHash;
							//DynamireplacedADna:: needs the DNAreplacedet from the converter TODO are there other places where I heed to sort out this slotDNA?
							if (slotData.replacedet.slotDNA is DynamicDNAConverterBehaviourBase)
							{
								((DynamireplacedADnaBase)dna).dnareplacedet = ((DynamicDNAConverterBehaviourBase)slotData.replacedet.slotDNA).dnareplacedet;
							}
							umaDna.Add(dnaTypeHash, dna);
							dnaValues.Add(dna);
						}
						else if (slotData.replacedet.slotDNA is DynamicDNAConverterBehaviourBase)
						{
							var dna = umaDna[dnaTypeHash];
							((DynamireplacedADnaBase)dna).dnareplacedet = ((DynamicDNAConverterBehaviourBase)slotData.replacedet.slotDNA).dnareplacedet;
						}
                    }
				}
				foreach (int addedDNAHash in umaDnaConverter.Keys)
				{
					requiredDnas.Add(addedDNAHash);
				}

				//now remove any we no longer need
				var keysToRemove = new List<int>();
				foreach(var kvp in umaDna)
				{
					if (!requiredDnas.Contains(kvp.Key))
						keysToRemove.Add(kvp.Key);
				}
				for(int i = 0; i < keysToRemove.Count; i++)
				{
					RemoveDna(keysToRemove[i]);
				}
				
			}

19 Source : UMAData.cs
with Apache License 2.0
from A7ocin

public void ClearDNAConverters()
			{
				umaDnaConverter.Clear();
				if (raceData != null)
				{
					foreach (var converter in raceData.dnaConverterList)
					{
						if(converter == null)
						{
							Debug.LogWarning("RaceData " + raceData.raceName + " has a missing DNAConverter");
							continue;
						}
						//'old' dna converters return a typehash based on the type name. 
						//Dynamic DNA Converters return the typehash of their dna replacedet or 0 if none is replacedigned- we dont want to include those
						if (converter.DNATypeHash == 0)
							continue;
						if (!umaDnaConverter.ContainsKey(converter.DNATypeHash))
						{
							umaDnaConverter.Add(converter.DNATypeHash, converter.ApplyDnaAction);
						}
						else
						{
							//We MUST NOT give DynamicDNA the same hash a UMADnaHumanoid or else we loose the values
							Debug.Log(raceData.raceName + " has multiple dna converters that are trying to use the same dna (" + converter.DNATypeHash + "). This is not allowed.");
						}
					}
				}
			}

19 Source : UMAData.cs
with Apache License 2.0
from A7ocin

public void AddDNAUpdater(DnaConverterBehaviour dnaConverter)
			{
				if (dnaConverter == null) return;
				//DynamicDNAConverter:: We need to SET these values using the TypeHash since 
				//just getting the hash of the DNAType will set the same value for all instance of a DynamicDNAConverter
				if (!umaDnaConverter.ContainsKey(dnaConverter.DNATypeHash))
				{
					umaDnaConverter.Add(dnaConverter.DNATypeHash, dnaConverter.ApplyDnaAction);
				}
				else
				{
					Debug.Log(raceData.raceName + " has multiple dna converters that are trying to use the same dna ("+ dnaConverter.DNATypeHash+"). This is not allowed.");
				}
			}

19 Source : UMASkeleton.cs
with Apache License 2.0
from A7ocin

private void AddBonesRecursive(Transform transform)
		{
			var hash = UMAUtils.StringToHash(transform.name);
			var parentHash = transform.parent != null ? UMAUtils.StringToHash(transform.parent.name) : 0;
			BoneData data = new BoneData()
			{
				parentBoneNameHash = parentHash,
				boneNameHash = hash,
				accessedFrame = frame,
				boneTransform = transform,
				umaTransform = new UMATransform(transform, hash, parentHash)
			};

			if (!boneHashData.ContainsKey(hash))
			{
				boneHashData.Add(hash, data);
#if UNITY_EDITOR
				boneHashDataBackup.Add(data);
#endif
			}
			else
				Debug.LogError("AddBonesRecursive: " + transform.name + " already exists in the dictionary!");

			for (int i = 0; i < transform.childCount; i++)
			{
				var child = transform.GetChild(i);
				AddBonesRecursive(child);
			}
		}

19 Source : UMASkeleton.cs
with Apache License 2.0
from A7ocin

public virtual void EnsureBoneHierarchy()
		{
			foreach (var entry in boneHashData.Values)
			{
				if (entry.accessedFrame == -1)
				{
					if (boneHashData.ContainsKey(entry.umaTransform.parent))
					{
						entry.boneTransform.parent = boneHashData[entry.umaTransform.parent].boneTransform;
						entry.boneTransform.localPosition = entry.umaTransform.position;
						entry.boneTransform.localRotation = entry.umaTransform.rotation;
						entry.boneTransform.localScale = entry.umaTransform.scale;
						entry.accessedFrame = frame;
					}
					else
						Debug.LogError("EnsureBoneHierarchy: " + entry.umaTransform.name + " parent not found in dictionary!");
				}
			}
		}

19 Source : UMASkeleton.cs
with Apache License 2.0
from A7ocin

public virtual bool HasBone(int nameHash)
		{
			return boneHashData.ContainsKey(nameHash);
		}

19 Source : UMASkeleton.cs
with Apache License 2.0
from A7ocin

public virtual void AddBone(int parentHash, int hash, Transform transform)
		{
			BoneData newBone = new BoneData()
			{
				accessedFrame = frame,
				parentBoneNameHash = parentHash,
				boneNameHash = hash,
				boneTransform = transform,
				umaTransform = new UMATransform(transform, hash, parentHash),
			};

			if (!boneHashData.ContainsKey(hash))
			{
				boneHashData.Add(hash, newBone);
#if UNITY_EDITOR
				boneHashDataBackup.Add(newBone);
#endif
			}
			else
				Debug.LogError("AddBone: " + transform.name + " already exists in the dictionary!");
		}

19 Source : UMASkeleton.cs
with Apache License 2.0
from A7ocin

public virtual void AddBone(UMATransform transform)
		{
			var go = new GameObject(transform.name);
			BoneData newBone = new BoneData()
			{
				accessedFrame = -1,
				parentBoneNameHash = transform.parent,
				boneNameHash = transform.hash,
				boneTransform = go.transform,
				umaTransform = transform.Duplicate(),
			};

			if (!boneHashData.ContainsKey(transform.hash))
			{
				boneHashData.Add(transform.hash, newBone);
#if UNITY_EDITOR
				boneHashDataBackup.Add(newBone);
#endif
			}
			else
				Debug.LogError("AddBone: " + transform.name + " already exists in the dictionary!");
		}

19 Source : Loger.cs
with Apache License 2.0
from AantCoder

private static void LogWrite(string msg, bool withCatch, int threadId = 0)
        {
            var thn = threadId != 0 ? threadId : Thread.CurrentThread.ManagedThreadId;
            var dn = DateTime.Now;
            var dd = !LastMsg.ContainsKey(thn) ? 0 : (long)(dn - LastMsg[thn]).TotalMilliseconds;
            LastMsg[thn] = dn;
            if (dd >= 1000000) dd = 0;
            var logMsg = dn.ToString(Culture) + " |" + dd.ToString().PadLeft(6) + " |" + thn.ToString().PadLeft(4) + " | " + msg;
            var fileName = $"Log_{DateTime.Now.ToString("yyyy-MM-dd")}_{MainHelper.RandomSeed}.txt";

            if (withCatch) Console.WriteLine(logMsg);
            lock (ObjLock)
            {
                try
                {
                    //if (LogMessage != null) LogMessage(logMsg);
                    File.AppendAllText(PathLog + fileName, logMsg + Environment.NewLine, Encoding.UTF8);
                }
                catch (Exception exp)
                {
                    if (withCatch)
                    {
                        LogErr = "Log exception: " + exp.Message + Environment.NewLine + logMsg;
                        LogErrThr = thn;
                    }
                }
            }
        }

19 Source : UpdateWorldController.cs
with Apache License 2.0
from AantCoder

public static void ApplyWorldObject(WorldObjectEntry worldObjectEntry)
        {
            var err = "";
            try
            {
                List<WorldObject> allWorldObjects = Find.WorldObjects.AllWorldObjects;
                err += "1 ";
                if (worldObjectEntry.LoginOwner == SessionClientController.My.Login)
                {
                    //для своих нужно только занести в MyWorldObjectEntry (чтобы запомнить ServerId)
                    if (!WorldObjectEntrys.Any(wo => wo.Value.ServerId == worldObjectEntry.ServerId))
                    {
                        err += "2 ";

                        for (int i = 0; i < allWorldObjects.Count; i++)
                        {
                            err += "3 ";
                            if (!WorldObjectEntrys.ContainsKey(allWorldObjects[i].ID)
                                && allWorldObjects[i].Tile == worldObjectEntry.Tile
                                && (allWorldObjects[i] is Caravan && worldObjectEntry.Type == WorldObjectEntryType.Caravan
                                    || allWorldObjects[i] is MapParent && worldObjectEntry.Type == WorldObjectEntryType.Base))
                            {
                                err += "4 ";
                                var id = allWorldObjects[i].ID;
                                Loger.Log("SetMyID " + id + " ServerId " + worldObjectEntry.ServerId + " " + worldObjectEntry.Name);
                                WorldObjectEntrys.Add(id, worldObjectEntry);

                                ConverterServerId[worldObjectEntry.ServerId] = id;
                                err += "5 ";
                                return;
                            }
                        }

                        err += "6 ";
                        Loger.Log("ToDel " + worldObjectEntry.ServerId + " " + worldObjectEntry.Name);

                        //объект нужно удалить на сервере - его нету у самого игрока (не заполняется при самом первом обновлении после загрузки)
                        if (ToDelete != null) ToDelete.Add(worldObjectEntry);
                        err += "7 ";
                    }
                    else
                    {
                        //если такой есть, то обновляем информацию
                        var pair = WorldObjectEntrys.First(wo => wo.Value.ServerId == worldObjectEntry.ServerId);
                        WorldObjectEntrys[pair.Key] = worldObjectEntry;
                    }
                    return;
                }

                //поиск уже существующих
                CaravanOnline worldObject = null;
                /*
                int existId;
                if (ConverterServerId.TryGetValue(worldObjectEntry.ServerId, out existId))
                {
                    for (int i = 0; i < allWorldObjects.Count; i++)
                    {
                        if (allWorldObjects[i].ID == existId && allWorldObjects[i] is CaravanOnline)
                        {
                            worldObject = allWorldObjects[i] as CaravanOnline;
                            break;
                        }
                    }
                }
                */
                err += "8 ";
                worldObject = GetOtherByServerId(worldObjectEntry.ServerId, allWorldObjects);

                err += "9 ";
                //если тут база другого игрока, то удаление всех кто занимает этот тайл, кроме караванов (удаление новых НПЦ и событий с занятых тайлов)
                if (worldObjectEntry.Type == WorldObjectEntryType.Base)
                {
                    err += "10 ";
                    for (int i = 0; i < allWorldObjects.Count; i++)
                    {
                        err += "11 ";
                        if (allWorldObjects[i].Tile == worldObjectEntry.Tile && allWorldObjects[i] != worldObject
                            && !(allWorldObjects[i] is Caravan) && !(allWorldObjects[i] is CaravanOnline)
                            && (allWorldObjects[i].Faction == null || !allWorldObjects[i].Faction.IsPlayer))
                        {
                            err += "12 ";
                            Loger.Log("Remove " + worldObjectEntry.ServerId + " " + worldObjectEntry.Name);
                            Find.WorldObjects.Remove(allWorldObjects[i]);
                        }
                    }
                }

                err += "13 ";
                //создание
                if (worldObject == null)
                {
                    err += "14 ";
                    worldObject = worldObjectEntry.Type == WorldObjectEntryType.Base
                        ? (CaravanOnline)WorldObjectMaker.MakeWorldObject(ModDefOf.BaseOnline)
                        : (CaravanOnline)WorldObjectMaker.MakeWorldObject(ModDefOf.CaravanOnline);
                    err += "15 ";
                    worldObject.SetFaction(Faction.OfPlayer);
                    worldObject.Tile = worldObjectEntry.Tile;
                    Find.WorldObjects.Add(worldObject);
                    err += "16 ";
                    ConverterServerId.Add(worldObjectEntry.ServerId, worldObject.ID);
                    Loger.Log("Add " + worldObjectEntry.ServerId + " " + worldObjectEntry.Name + " " + worldObjectEntry.LoginOwner);
                    err += "17 ";
                }
                else
                {
                    err += "18 ";
                    ConverterServerId[worldObjectEntry.ServerId] = worldObject.ID; //на всякий случай
                    err += "19 ";
                    //Loger.Log("SetID " + worldObjectEntry.ServerId + " " + worldObjectEntry.Name);
                }
                err += "20 ";
                //обновление
                worldObject.Tile = worldObjectEntry.Tile;
                err += "21 ";
                worldObject.OnlineWObject = worldObjectEntry;
            }
            catch
            {
                Loger.Log("ApplyWorldObject ErrorLog: " + err);
                throw;
            }
        }

19 Source : MixedRealityInputModule.cs
with Apache License 2.0
from abist-co-ltd

void IMixedRealityPointerHandler.OnPointerUp(MixedRealityPointerEventData eventData)
        {
            int pointerId = (int)eventData.Pointer.PointerId;
            Debug.replacedert(pointerDataToUpdate.ContainsKey(pointerId));
            pointerDataToUpdate[pointerId].nextPressState = PointerEventData.FramePressState.Released;
        }

19 Source : MixedRealityInputModule.cs
with Apache License 2.0
from abist-co-ltd

void IMixedRealityPointerHandler.OnPointerDown(MixedRealityPointerEventData eventData)
        {
            int pointerId = (int)eventData.Pointer.PointerId;
            Debug.replacedert(pointerDataToUpdate.ContainsKey(pointerId));
            pointerDataToUpdate[pointerId].nextPressState = PointerEventData.FramePressState.Pressed;
        }

19 Source : MixedRealityInputModule.cs
with Apache License 2.0
from abist-co-ltd

void OnSourceDetected(IMixedRealityInputSource inputSource)
        {
            using (OnSourceDetectedPerfMarker.Auto())
            {
                for (int i = 0; i < inputSource.Pointers.Length; i++)
                {
                    var pointer = inputSource.Pointers[i];
                    if (pointer.InputSourceParent == inputSource)
                    {
                        // This !ContainsKey is only necessary due to inconsistent initialization of
                        // various input providers and this clreplaced's ActivateModule() call.
                        int pointerId = (int)pointer.PointerId;
                        if (!pointerDataToUpdate.ContainsKey(pointerId))
                        {
                            pointerDataToUpdate.Add(pointerId, new PointerData(pointer, eventSystem));
                        }
                    }
                }
            }
        }

19 Source : MixedRealityInputModule.cs
with Apache License 2.0
from abist-co-ltd

void IMixedRealitySourceStateHandler.OnSourceLost(SourceStateEventData eventData)
        {
            using (OnSourceLostPerfMarker.Auto())
            {
                var inputSource = eventData.InputSource;

                for (int i = 0; i < inputSource.Pointers.Length; i++)
                {
                    var pointer = inputSource.Pointers[i];
                    if (pointer.InputSourceParent == inputSource)
                    {
                        int pointerId = (int)pointer.PointerId;
                        Debug.replacedert(pointerDataToUpdate.ContainsKey(pointerId));

                        PointerData pointerData = null;
                        if (pointerDataToUpdate.TryGetValue(pointerId, out pointerData))
                        {
                            Debug.replacedert(!pointerDataToRemove.Contains(pointerData));
                            pointerDataToRemove.Add(pointerData);

                            pointerDataToUpdate.Remove(pointerId);
                        }
                    }
                }
            }
        }

19 Source : OvrAvatarTextureCopyManager.cs
with MIT License
from absurd-joy

public void AddTextureIDToTextureSet(int gameobjectID, ulong textureID, bool isSingleMesh)
    {
        if (!textureSets.ContainsKey(gameobjectID))
        {
            TextureSet newTextureSet = new TextureSet(new Dictionary<ulong, bool>(), false);
            newTextureSet.TextureIDSingleMeshPair.Add(textureID, isSingleMesh);
            textureSets.Add(gameobjectID, newTextureSet);
        }
        else
        {
            bool TexIDSingleMesh;
            if (textureSets[gameobjectID].TextureIDSingleMeshPair.TryGetValue(textureID, out TexIDSingleMesh))
            {
                if (!TexIDSingleMesh && isSingleMesh)
                {
                    textureSets[gameobjectID].TextureIDSingleMeshPair[textureID] = true;
                }
            }
            else
            {
                textureSets[gameobjectID].TextureIDSingleMeshPair.Add(textureID, isSingleMesh);
            }
        }
    }

19 Source : P2PManager.cs
with MIT License
from absurd-joy

void ReceiveBallTransforms(ulong remoteID, byte[] msg, ulong msgLength)
		{
			int offset = 1;
			float remoteTime = UnpackTime(remoteID, msg, ref offset);

			// because we're using unreliable networking the packets could come out of order
			// and the best thing to do is just ignore old packets because the data isn't
			// very useful anyway
			if (remoteTime < m_remotePlayers[remoteID].lastReceivedBallsTime)
				return;

			m_remotePlayers[remoteID].lastReceivedBallsTime = remoteTime;

			// loop over all ball updates in the message
			while (offset != (int)msgLength)
			{
				bool isHeld = UnpackBool(msg, ref offset);
				int instanceID = UnpackInt32(msg, ref offset);
				Vector3 pos = UnpackVector3(msg, ref offset);
				Vector3 vel = UnpackVector3(msg, ref offset);

				if (!m_remotePlayers[remoteID].activeBalls.ContainsKey(instanceID))
				{
					var newball = m_remotePlayers[remoteID].player.CreateBall().AddComponent<P2PNetworkBall>();
					newball.transform.SetParent(m_remotePlayers[remoteID].player.transform.parent);
					m_remotePlayers[remoteID].activeBalls[instanceID] = newball;
				}
				var ball = m_remotePlayers[remoteID].activeBalls[instanceID];
				if (ball)
				{
					ball.ProcessRemoteUpdate(remoteTime, isHeld, pos, vel);
				}
			}
		}

See More Examples