System.Collections.Generic.HashSet.Clear()

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

1644 Examples 7

19 View Source File : UIIconManager.cs
License : GNU Affero General Public License v3.0
Project Creator : 0ceal0t

public void Dispose() {
            IconOverride.Clear();
            Reset();
        }

19 View Source File : Watchdog.cs
License : MIT License
Project Creator : 0ffffffffh

public void Dispose()
        {
            if (workTimer == null)
                return;

            Log.Info("Watchdog stopping..");

            ManualResetEvent mre = new ManualResetEvent(false);
            
            workTimer.Dispose(mre);

            mre.WaitOne();

            if (this.wts.Ws != null)
                this.wts.Ws.Release();

            watchList.Clear();
            watchList = null;

            watchdogWorkerCb = null;

            mre.Dispose();

            Log.Info("Watchdog stopped");
            

        }

19 View Source File : CacheManager.cs
License : MIT License
Project Creator : 0ffffffffh

internal static bool Invalidate(KeysetId setId)
        {
            HashSet<string> sets;
            
            CacheKeySetContext cksc = GetKeysetContext(setId, false);

            if (cksc == null)
                return false;
            
            lock (cksc.lck)
            {
                if (!CacheManager.TryGetCachedResult<HashSet<string>>(cksc.CacheSetKey, out sets))
                {
                    Log.Warning("Not expected situation. cache key set does not exists for setId:{0}", setId);
                    RemoveKeysetContext(setId);
                    return false;
                }

                foreach (var key in sets)
                {
                    CacheManager.Remove(key);
                }

                Log.Info("{0} key records invalidated from the keyset ({1})", sets.Count, setId);

                sets.Clear();

                CacheManager.CacheObject(cksc.CacheSetKey, sets);
            }


            return true;
        }

19 View Source File : EdisFace.cs
License : MIT License
Project Creator : 0ffffffffh

private void CacheDeniedClient(string clientIp)
        {
            string key = Edi.MakeUniqueCacheKey("EDI_DENYLIST");

            HashSet<string> denyHashlist = null;

            lock (lck)
            {
                if (!CacheManager.TryGetCachedResult<HashSet<string>>(
                    key,
                    out denyHashlist)
                    )
                {
                    denyHashlist = new HashSet<string>();
                }


                if (!denyHashlist.Contains(clientIp))
                {
                    denyHashlist.Add(clientIp);
                    CacheManager.CacheObject(key, denyHashlist,TimeSpan.FromHours(3));
                }
            }

            denyHashlist.Clear();
            denyHashlist = null;
        }

19 View Source File : EdisFace.cs
License : MIT License
Project Creator : 0ffffffffh

private bool IsClientDeniedAtThisSessionBefore(string clientIp)
        {
            bool denied = false;
            string key = Edi.MakeUniqueCacheKey("EDI_DENYLIST");

            HashSet<string> denyHashlist = null;

            lock (lck)
            {
                if (!CacheManager.TryGetCachedResult<HashSet<string>>(
                    key,
                    out denyHashlist)
                    )
                {
                    return false;
                }
            }

            denied = denyHashlist.Contains(clientIp);

            denyHashlist.Clear();
            denyHashlist = null;

            return denied;
        }

19 View Source File : StringMap.cs
License : MIT License
Project Creator : 0x0ade

public List<Tuple<string, int>> PromoteRead() {
            lock (Pending) {
                if (Pending.Count == 0)
                    return Dummy<Tuple<string, int>>.EmptyList;

                List<Tuple<string, int>> added = new();
                foreach (string value in Pending) {
                    int id = NextID++;
                    MapRead[id] = value;
                    MappedRead.Add(value);
                    added.Add(Tuple.Create(value, id));
                }
                Pending.Clear();
                return added;
            }
        }

19 View Source File : KeyboardEvents.cs
License : zlib License
Project Creator : 0x0ade

public static void Update() {
            Keys[] keys = Keyboard.GetState().GetPressedKeys();
            Down.Clear();
            for (int i = 0; i < keys.Length; i++) {
                Keys key = keys[i];
                if (!LastDown.Contains(key))
                    KeyDown(key);
                Down.Add(key);
            }
            foreach (Keys key in LastDown) {
                if (!Down.Contains(key))
                    KeyUp(key);
            }
            LastDown.Clear();
            LastDown.UnionWith(Down);
        }

19 View Source File : AINavMeshGenerator.cs
License : MIT License
Project Creator : 7ark

private Node[] GetAStar(Vector2 currentPosition, Vector2 destination, GameObject obj = null)
    {
        Node start = generator.FindClosestNode(currentPosition, false, obj);
        Node end = generator.FindClosestNode(destination, true, obj);
        if (start == null || end == null)
        {
            return null;
        }

        openSet.Clear();
        closedSet.Clear();
        openSet.Add(start);
        while (openSet.Count > 0)
        {
            Node current = openSet[0];

            //Evaluate costs
            for (int i = 1; i < openSet.Count; i++)
            {
                if (openSet[i].fCost < current.fCost || openSet[i].fCost == current.fCost)
                {
                    if (openSet[i].hCost < current.hCost)
                    {
                        current = openSet[i];
                    }
                }
            }

            openSet.Remove(current);
            closedSet.Add(current);

            if (current.Equals(end))
            {
                break;
            }

            //Go through neighbors
            foreach (Node neighbor in current.connections.Where(x => x != null))
            {
                //The replacedociated object check is so the enemy ignores pathing through it's own bad sector
                if ((!neighbor.valid && neighbor.replacedociatedObject != obj) || closedSet.Contains(neighbor))
                {
                    continue;
                }

                float newCost = current.gCost + Heuristic(current, neighbor);
                if (newCost < neighbor.gCost || !openSet.Contains(neighbor))
                {
                    neighbor.gCost = newCost;
                    neighbor.hCost = Heuristic(neighbor, end);
                    neighbor.parent = current;

                    if (!openSet.Contains(neighbor))
                    {
                        openSet.Add(neighbor);
                    }
                }
            }
        }

        if(end.parent == null)
        {
            return null;
        }

        //Calculate path
        path.Clear();
        Node currentCheck = end;
        while (!path.Contains(currentCheck) && currentCheck != null)
        {
            path.Add(currentCheck);
            currentCheck = currentCheck.parent;
        }
        path.Reverse();
        if(path[0] != start)
        {
            return null;
        }
        return path.ToArray();
    }

19 View Source File : UdpClient.cs
License : MIT License
Project Creator : a11s

public void Connect(IPEndPoint ipep, bool CreateBackgroundThread)
        {
            IOThreads.Clear();
            lastHandshakeTime = DateTime.MinValue;
            Incoming = new ConcurrentQueue<byte[]>();
            Outgoing = new ConcurrentQueue<byte[]>();
            udp = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                bool bNewBehavior = false;
                byte[] dwBytesReturned = new byte[4];
                udp.IOControl((int)SIO_UDP_CONNRESET, BitConverter.GetBytes(bNewBehavior), dwBytesReturned);
            }
            defpb = new ServerPackBuilderEx(defpb.GetSysIdBuf(), SessionId);
            remote_ipep = ipep;
            udp.Connect(remote_ipep);
            if (CreateBackgroundThread)
            {
                ioThread = new Thread(ioLoop);
                ioThread.IsBackground = true;
                ioThread.Name = $"{nameof(ioThread)}";
                IOThreads.Add(ioThread.ManagedThreadId);
                ioThread.Start();
            }
            debug?.Invoke($"start connect");
        }

19 View Source File : UdpClient.cs
License : MIT License
Project Creator : a11s

public virtual void Close()
        {
            IOThreads.Clear();
            Incoming = null;
            Outgoing = null;
            defpb = null;
            udp.Close();
        }

19 View Source File : SplineDataProviderInspector.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();
            serializedObject.Update();

            // We always draw line points for splines.
            DrawLinePoints = true;

            EditorGUILayout.LabelField("Spline Settings");

            EditorGUI.indentLevel++;

            EditorGUILayout.PropertyField(alignAllControlPoints);
            GUILayout.BeginHorizontal();

            if (GUILayout.Button("Add New Point", GUILayout.Width(48f), GUILayout.ExpandWidth(true)))
            {
                AddControlPoint();
            }

            GUI.enabled = controlPoints.arraySize > 4;

            if (GUILayout.Button("Remove Last Point", GUILayout.Width(48f), GUILayout.ExpandWidth(true)))
            {
                RemoveControlPoint();
            }

            GUI.enabled = true;
            GUILayout.EndHorizontal();

            controlPointFoldout = EditorGUILayout.Foldout(controlPointFoldout, ControlPointHeaderContent, true);

            if (controlPointFoldout)
            {
                // If we found overlapping points, provide an option to auto-separate them
                if (OverlappingPointIndexes.Count > 0)
                {
                    EditorGUILayout.HelpBox("We noticed some of your control points have the same position.", MessageType.Warning);

                    if (GUILayout.Button("Fix overlapping points"))
                    {
                        // Move them slightly out of the way
                        foreach (int pointIndex in OverlappingPointIndexes)
                        {
                            var controlPointProperty = controlPoints.GetArrayElementAtIndex(pointIndex);
                            var position = controlPointProperty.FindPropertyRelative("position");
                            position.vector3Value += Random.onUnitSphere * OverlappingPointThreshold * 2;
                        }
                        OverlappingPointIndexes.Clear();
                    }
                }

                controlPointList.DoLayoutList();
            }

            EditorGUI.indentLevel--;

            serializedObject.ApplyModifiedProperties();
        }

19 View Source File : Dockable.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private void OnDisable()
        {
            if (objectManipulator != null)
            {
                objectManipulator.OnManipulationStarted.RemoveListener(OnManipulationStarted);
                objectManipulator.OnManipulationEnded.RemoveListener(OnManipulationEnded);

                objectManipulator = null;
            }

            if (manipulationHandler != null)
            {
                manipulationHandler.OnManipulationStarted.RemoveListener(OnManipulationStarted);
                manipulationHandler.OnManipulationEnded.RemoveListener(OnManipulationEnded);

                manipulationHandler = null;
            }

            if (dockedPosition != null)
            {
                dockedPosition.DockedObject = null;
                dockedPosition = null;
            }

            overlappingPositions.Clear();
        }

19 View Source File : SplineDataProviderInspector.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

protected override void OnSceneGUI()
        {
            base.OnSceneGUI();

            // We skip the first point as it should always remain at the GameObject's local origin (Pose.ZeroIdenreplacedy)
            for (int i = 1; i < controlPoints?.arraySize; i++)
            {
                bool isTangentHandle = i % 3 != 0;

                serializedObject.Update();

                bool isLastPoint = i == controlPoints.arraySize - 1;

                var controlPointPosition = LineData.GetPoint(i);
                var controlPointProperty = controlPoints.GetArrayElementAtIndex(i);
                var controlPointRotation = controlPointProperty.FindPropertyRelative("rotation");

                // Draw our tangent lines
                Handles.color = Color.gray;
                if (i == 1)
                {
                    Handles.DrawLine(LineData.GetPoint(0), LineData.GetPoint(1));
                }
                else if (!isTangentHandle)
                {
                    Handles.DrawLine(LineData.GetPoint(i), LineData.GetPoint(i - 1));

                    if (!isLastPoint)
                    {
                        Handles.DrawLine(LineData.GetPoint(i), LineData.GetPoint(i + 1));
                    }
                }

                Handles.color = isTangentHandle ? Color.white : Color.green;
                float handleSize = HandleUtility.GetHandleSize(controlPointPosition);

                if (Handles.Button(controlPointPosition, controlPointRotation.quaternionValue, handleSize * HandleSizeModifier, handleSize * PickSizeModifier, Handles.DotHandleCap))
                {
                    selectedHandleIndex = i;
                }

                // Draw our handles
                if (Tools.current == Tool.Move && selectedHandleIndex == i)
                {
                    EditorGUI.BeginChangeCheck();

                    var newTargetPosition = Handles.PositionHandle(controlPointPosition, controlPointRotation.quaternionValue);

                    if (EditorGUI.EndChangeCheck())
                    {
                        Undo.RecordObject(LineData, "Change Spline Point Position");
                        LineData.SetPoint(i, newTargetPosition);
                    }

                    if (isLastPoint)
                    {
                        DrawSceneControlOptionButtons(controlPointPosition);
                    }
                }
                else if (Tools.current == Tool.Rotate && selectedHandleIndex == i)
                {
                    EditorGUI.BeginChangeCheck();
                    Quaternion newTargetRotation = Handles.RotationHandle(controlPointRotation.quaternionValue, controlPointPosition);

                    if (EditorGUI.EndChangeCheck())
                    {
                        Undo.RecordObject(LineData, "Change Spline Point Rotation");
                        controlPointRotation.quaternionValue = newTargetRotation;
                    }
                }

                serializedObject.ApplyModifiedProperties();
            }

            // Check for overlapping points
            OverlappingPointIndexes.Clear();

            for (int i = 0; i < splineData.ControlPoints.Length; i++)
            {
                for (int j = 0; j < splineData.ControlPoints.Length; j++)
                {
                    if (i == j)
                    {
                        continue;
                    }

                    if (Vector3.Distance(splineData.ControlPoints[i].Position, splineData.ControlPoints[j].Position) < OverlappingPointThreshold)
                    {
                        if (i != 0)
                        {
                            OverlappingPointIndexes.Add(i);
                        }

                        if (j != 0)
                        {
                            OverlappingPointIndexes.Add(j);
                        }

                        break;
                    }
                }
            }
        }

19 View Source File : ProximityEffect.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public void UpdateScaling(Vector3 boundsCenter, Vector3 boundsExtents)
        {
            // early out if effect is disabled
            if (config.ProximityEffectActive == false || !IsAnyRegisteredObjectVisible())
            {
                return;
            }

            proximityPointers.Clear();
            proximityPoints.Clear();

            // Find all valid pointers
            foreach (var inputSource in CoreServices.InputSystem.DetectedInputSources)
            {
                foreach (var pointer in inputSource.Pointers)
                {
                    // don't use IsInteractionEnabled for near pointers as the pointers might have a different radius when deciding
                    // if they can interact with a near-by object - we might still want to show proximity scaling even if
                    // eg. grab pointer decides it's too far away to actually perform the interaction
                    if (pointer.IsActive && !proximityPointers.Contains(pointer))
                    {
                        proximityPointers.Add(pointer);
                    }
                }
            }

            // Get the max radius possible of our current bounds and extent the range to include proximity scaled objects. This is done by adjusting the original bounds to include the ObjectMediumProximity range in x, y and z axis
            float squareMaxLength = boundsExtents.sqrMagnitude + (3 * config.ObjectMediumProximity * config.ObjectMediumProximity);

            // Grab points within sphere of influence from valid pointers
            foreach (var pointer in proximityPointers)
            {
                if (IsPointWithinBounds(boundsCenter, pointer.Position, squareMaxLength))
                {
                    proximityPoints.Add(pointer.Position);
                }
                
                if (pointer.Result?.CurrentPointerTarget != null)
                { 
                    Vector3? point = pointer.Result?.Details.Point;
                    if (point.HasValue && IsPointWithinBounds(boundsCenter, pointer.Result.Details.Point, squareMaxLength))
                    {
                        proximityPoints.Add(pointer.Result.Details.Point);
                    }
                }
            }

            // Loop through all objects and find closest one
            Transform closestObject = null;
            float closestDistanceSqr = float.MaxValue;
            foreach (var point in proximityPoints)
            {

                foreach (var keyValuePair in registeredObjects)
                {

                    foreach (var item in keyValuePair.Value)
                    {
                        // If object can't be visible, skip calculations
                        if (!keyValuePair.Key.IsActive)
                        {
                            continue;
                        }

                        // Perform comparison on sqr distance since sqrt() operation is expensive in Vector3.Distance()
                        float sqrDistance = (item.ScaledObject.transform.position - point).sqrMagnitude;
                        if (sqrDistance < closestDistanceSqr)
                        {
                            closestObject = item.ScaledObject;
                            closestDistanceSqr = sqrDistance;
                        }
                    }
                }
            }

            // Loop through all objects and update visual state based on closest point
            foreach (var keyValuePair in registeredObjects)
            {
                foreach (var item in keyValuePair.Value)
                {
                    ProximityState newState = (closestObject == item.ScaledObject) ? GetProximityState(closestDistanceSqr) : ProximityState.FullsizeNoProximity;
                    IProximityEffectObjectProvider provider = keyValuePair.Key;

                    // Only apply updates if object is in a new state or closest object needs to lerp scaling
                    if (item.ProximityState != newState)
                    {
                        // Update and save new state
                        item.ProximityState = newState;

                        if (item.ObjectVisualRenderer)
                        {
                            item.ObjectVisualRenderer.material = newState == ProximityState.CloseProximity ? provider.GetHighlightedMaterial() : provider.GetBaseMaterial();
                        }
                    }

                    ScaleObject(newState, item.ScaledObject, provider.GetObjectSize(), true);
                }
            }
        }

19 View Source File : DefaultPointerMediator.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public virtual void UpdatePointers()
        {
            using (UpdatePointersPerfMarker.Auto())
            {
                // If there's any teleportation going on, disable all pointers except the teleporter
                foreach (IMixedRealityTeleportPointer pointer in teleportPointers)
                {
                    if (pointer.TeleportRequestRaised)
                    {
                        pointer.IsActive = true;

                        foreach (IMixedRealityPointer otherPointer in allPointers)
                        {
                            if (otherPointer.PointerId == pointer.PointerId)
                            {
                                continue;
                            }

                            otherPointer.IsActive = false;
                        }
                        // Don't do any further checks
                        return;
                    }
                }

                // pointers whose active state has not yet been set this frame
                unreplacedignedPointers.Clear();
                foreach (IMixedRealityPointer unreplacedignedPointer in allPointers)
                {
                    unreplacedignedPointers.Add(unreplacedignedPointer);
                }

                ApplyCustomPointerBehaviors();

                // If any pointers are locked, they have priority. 
                // Deactivate all other pointers that are on that input source
                foreach (IMixedRealityPointer pointer in allPointers)
                {
                    if (pointer.IsFocusLocked)
                    {
                        pointer.IsActive = true;
                        unreplacedignedPointers.Remove(pointer);

                        if (pointer.InputSourceParent != null)
                        {
                            foreach (IMixedRealityPointer otherPointer in pointerByInputSourceParent[pointer.InputSourceParent])
                            {
                                if (!unreplacedignedPointers.Contains(otherPointer))
                                {
                                    continue;
                                }

                                otherPointer.IsActive = false;
                                unreplacedignedPointers.Remove(otherPointer);
                            }
                        }
                    }
                }

                // Check for near and far interactions
                // Any far interact pointers become disabled when a near pointer is near an object
                foreach (IMixedRealityNearPointer pointer in nearInteractPointers)
                {
                    if (!unreplacedignedPointers.Contains(pointer))
                    {
                        continue;
                    }

                    if (pointer.IsNearObject)
                    {
                        pointer.IsActive = true;
                        unreplacedignedPointers.Remove(pointer);

                        if (pointer.InputSourceParent != null)
                        {
                            foreach (IMixedRealityPointer otherPointer in pointerByInputSourceParent[pointer.InputSourceParent])
                            {
                                if (!unreplacedignedPointers.Contains(otherPointer))
                                {
                                    continue;
                                }

                                if (otherPointer is IMixedRealityNearPointer)
                                {
                                    // Only disable far interaction pointers
                                    // It is okay for example to have two near pointers active on a single controller
                                    // like a poke pointer and a grab pointer
                                    continue;
                                }

                                otherPointer.IsActive = false;
                                unreplacedignedPointers.Remove(otherPointer);
                            }
                        }
                    }
                }

                // All other pointers that have not been replacedigned this frame
                // have no reason to be disabled, so make sure they are active
                foreach (IMixedRealityPointer unreplacedignedPointer in unreplacedignedPointers)
                {
                    unreplacedignedPointer.IsActive = true;
                }
            }
        }

19 View Source File : BoneCapsuleTriggerLogic.cs
License : MIT License
Project Creator : absurd-joy

private void OnDisable()
		{
			CollidersTouchingUs.Clear();
		}

19 View Source File : CryptoSystem.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public new void ReleaseResources()
        {
            xors?.Clear();
            xors = null;
            base.ReleaseResources();
        }

19 View Source File : LandblockGroup.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public List<LandblockGroup> TrySplit()
        {
            if (IsDungeon)
                return null;

            var results = new List<LandblockGroup>();

            var newLandblockGroup = DoTrySplit();

            while (newLandblockGroup != null)
            {
                results.Add(newLandblockGroup);

                newLandblockGroup = DoTrySplit();
            }

            NextTrySplitTime = DateTime.UtcNow.Add(TrySplitInterval);
            uniqueLandblockIdsRemoved.Clear();

            return results;
        }

19 View Source File : BSPCache.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static void Clear()
        {
            BSPTrees.Clear();
        }

19 View Source File : PolygonCache.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static void Clear()
        {
            Polygons.Clear();
        }

19 View Source File : VertexCache.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static void Clear()
        {
            Vertices.Clear();
        }

19 View Source File : Player_Trade.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void HandleActionResetTrade(ObjectGuid replacedset)
        {
            if (TradeTransferInProgress)
                return;

            ItemsInTradeWindow.Clear();
            TradeAccepted = false;

            Session.Network.EnqueueSend(new GameEventResetTrade(Session, replacedset));
        }

19 View Source File : Player_Trade.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void HandleActionOpenTradeNegotiations(uint tradePartnerGuid, bool initiator = false)
        {
            if (IsOlthoiPlayer)
            {
                Session.Network.EnqueueSend(new GameMessageSystemChat($"As a mindless engine of destruction an Olthoi cannot participate in trade negotiations!", ChatMessageType.Magic));
                return;
            }

            var tradePartner = PlayerManager.GetOnlinePlayer(tradePartnerGuid);
            if (tradePartner == null) return;

            //Check to see if potential trading partner is an Olthoi player
            if (initiator && tradePartner.IsOlthoiPlayer)
            {
                Session.Network.EnqueueSend(new GameMessageSystemChat($"The Olthoi's hunger for destruction is too great to understand a request for trade negotiations!", ChatMessageType.Broadcast));
                return;
            }

            //Check to see if partner is not allowing trades
            if (initiator && tradePartner.GetCharacterOption(CharacterOption.IgnoreAllTradeRequests))
            {
                Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.TradeIgnoringRequests));
                return;
            }

            //Check to see if either party is already part of an in process trade session
            if (IsTrading || tradePartner.IsTrading)
            {
                Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.TradeAlreadyTrading));
                return;
            }

            //Check to see if either party is in combat mode
            if (CombatMode != CombatMode.NonCombat || tradePartner.CombatMode != CombatMode.NonCombat)
            {
                Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.TradeNonCombatMode));
                return;
            }

            //Check to see if trade partner is in range, if so, rotate and move to
            if (initiator)
            {
                CreateMoveToChain(tradePartner, (success) =>
                {
                    if (!success)
                    {
                        Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.TradeMaxDistanceExceeded));
                        return;
                    }

                    Session.Network.EnqueueSend(new GameEventRegisterTrade(Session, Guid, tradePartner.Guid));

                    tradePartner.HandleActionOpenTradeNegotiations(Guid.Full, false);
                });
            }
            else
            {
                IsTrading = true;
                tradePartner.IsTrading = true;
                TradeTransferInProgress = false;
                tradePartner.TradeTransferInProgress = false;

                TradePartner = tradePartner.Guid;
                tradePartner.TradePartner = Guid;

                ItemsInTradeWindow.Clear();
                tradePartner.ItemsInTradeWindow.Clear();

                Session.Network.EnqueueSend(new GameEventRegisterTrade(Session, tradePartner.Guid, tradePartner.Guid));
            }
        }

19 View Source File : Player_Trade.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void HandleActionCloseTradeNegotiations(EndTradeReason endTradeReason = EndTradeReason.Normal)
        {
            if (TradeTransferInProgress) return;

            IsTrading = false;
            TradeAccepted = false;
            TradeTransferInProgress = false;
            ItemsInTradeWindow.Clear();
            TradePartner = ObjectGuid.Invalid;

            Session.Network.EnqueueSend(new GameEventCloseTrade(Session, endTradeReason));
            Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.TradeClosed));
        }

19 View Source File : Player_Trade.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void ClearTradeAcceptance()
        {
            ItemsInTradeWindow.Clear();
            TradeAccepted = false;

            Session.Network.EnqueueSend(new GameEventClearTradeAcceptance(Session));
        }

19 View Source File : LocationCacheManager.cs
License : MIT License
Project Creator : actions

public void ClearIfCacheNotFresh(Int32 serverLastChangeId)
        {
            if (serverLastChangeId != m_lastChangeId)
            {
                m_accessLock.EnterWriteLock();

                try
                {
                    if (serverLastChangeId != m_lastChangeId)
                    {
                        m_accessMappings.Clear();
                        m_services.Clear();
                        m_cachedMisses.Clear();
                        m_lastChangeId = -1;
                        m_cacheExpirationDate = DateTime.MinValue;
                    }
                }
                finally
                {
                    m_accessLock.ExitWriteLock();
                }
            }
        }

19 View Source File : ControlDataRepository.cs
License : MIT License
Project Creator : Actipro

public void ClearFavorites() {
			favorites.Clear();
			FavoritesChanged?.Invoke(this, new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null));
		}

19 View Source File : NodeSet.cs
License : MIT License
Project Creator : active-logic

public void Clear(){ states.Clear(); list.Clear(); }

19 View Source File : AssemblyComparer.cs
License : MIT License
Project Creator : adrianoc

public bool IgnoreNonRequiredLocalVariablereplacedignments(Instruction inst)
        {
            if (toBeIgnored.Remove(inst))
            {
                return false;
            }

            if ((inst.OpCode != OpCodes.Stloc && inst.OpCode != OpCodes.Stloc_0)|| inst.Next == null)
            {
                return true;
            }

            var current = inst.Next;
            while (current != null && current.OpCode == OpCodes.Nop)
                current = current.Next;
                
            if ((current?.OpCode == OpCodes.Ldloc || current?.OpCode == OpCodes.Ldloc_0) && current.Operand == inst.Operand)
            {
                toBeIgnored.Add(current);
                return false;
            }
            
            toBeIgnored.Clear();

            return true;
        }

19 View Source File : CameraOcclusionCuller.cs
License : MIT License
Project Creator : adrenak

void Scan() {
            doScan = false;

            OverFrames.Get().For(0, rayRows, frameLength, i => {
                for(int j = 0; j < rayCols; j++) {
                    var screenPoint = new Vector3(j * (float)Screen.width / rayCols, i  * (float)Screen.height / rayRows);
                    var ray = camera.ScreenPointToRay(screenPoint);
                    rays.Add(ray);

                    if (Physics.Raycast(ray, out hit, camera.farClipPlane)) {
                        var collider = hit.collider;
                        if (collider == null)
                            break;
                        var ocr = collider.GetComponent<OcclusionCulledRenderer>();
                        if (ocr != null) {
                            if (!scannedRenderers.Contains(ocr))
                                scannedRenderers.Add(ocr);
                        }

                    }
                }
            },
            () => {
                for (int i = 0; i < occCullRenderers.Count; i++) {
                    if (scannedRenderers.Contains(occCullRenderers[i]))
                        occCullRenderers[i].MakeVisible();
                    else
                        occCullRenderers[i].MakeInvisible();
                }
                scannedRenderers.Clear();
                doScan = true;
            });
        }

19 View Source File : RenderTextureFactory.cs
License : MIT License
Project Creator : AdultLink

public void ReleaseAll()
        {
            var enumerator = m_TemporaryRTs.GetEnumerator();
            while (enumerator.MoveNext())
                RenderTexture.ReleaseTemporary(enumerator.Current);

            m_TemporaryRTs.Clear();
        }

19 View Source File : AduRipple.cs
License : GNU General Public License v3.0
Project Creator : aduskin

private static void MouseButtonEventHandler(object sender, MouseButtonEventArgs e)
        {
            foreach (var AduRipple in PressedInstances)
            {
                // adjust the transition scale time according to the current animated scale
                var scaleTrans = AduRipple.Template.FindName("ScaleTransform", AduRipple) as ScaleTransform;
                if (scaleTrans != null)
                {
                    double currentScale = scaleTrans.ScaleX;
                    var newTime = TimeSpan.FromMilliseconds(300 * (1.0 - currentScale));

                    // change the scale animation according to the current scale
                    var scaleXKeyFrame = AduRipple.Template.FindName("MousePressedToNormalScaleXKeyFrame", AduRipple) as EasingDoubleKeyFrame;
                    if (scaleXKeyFrame != null)
                    {
                        scaleXKeyFrame.KeyTime = KeyTime.FromTimeSpan(newTime);
                    }
                    var scaleYKeyFrame = AduRipple.Template.FindName("MousePressedToNormalScaleYKeyFrame", AduRipple) as EasingDoubleKeyFrame;
                    if (scaleYKeyFrame != null)
                    {
                        scaleYKeyFrame.KeyTime = KeyTime.FromTimeSpan(newTime);
                    }
                }

                VisualStateManager.GoToState(AduRipple, TemplateStateNormal, true);
            }
            PressedInstances.Clear();
        }

19 View Source File : TriangleMeshConvexContactManifold.cs
License : The Unlicense
Project Creator : aeroson

public override void Update(float dt)
        {
            //First, refresh all existing contacts.  This is an incremental manifold.
            var transform = MeshTransform;
            ContactRefresher.ContactRefresh(contacts, supplementData, ref convex.worldTransform, ref transform, contactIndicesToRemove);

            RemoveQueuedContacts();


            CleanUpOverlappingTriangles();
            //Get all the overlapped triangle indices.
            int triangleCount = FindOverlappingTriangles(dt);

            Matrix3x3 orientation;
            Matrix3x3.CreateFromQuaternion(ref convex.worldTransform.Orientation, out orientation);
            var guaranteedContacts = 0;
            for (int i = 0; i < triangleCount; i++)
            {
                //Initialize the local triangle.
                TriangleIndices indices;
                if (ConfigureTriangle(i, out indices))
                {

                    //Find a pairtester for the triangle.
                    TrianglePairTester pairTester;
                    if (!activePairTesters.TryGetValue(indices, out pairTester))
                    {
                        pairTester = GetTester();
                        pairTester.Initialize(convex.Shape, localTriangleShape);
                        activePairTesters.Add(indices, pairTester);
                    }
                    pairTester.Updated = true;


                    //Put the triangle into the local space of the convex.
                    Vector3.Subtract(ref localTriangleShape.vA, ref convex.worldTransform.Position, out localTriangleShape.vA);
                    Vector3.Subtract(ref localTriangleShape.vB, ref convex.worldTransform.Position, out localTriangleShape.vB);
                    Vector3.Subtract(ref localTriangleShape.vC, ref convex.worldTransform.Position, out localTriangleShape.vC);
                    Matrix3x3.TransformTranspose(ref localTriangleShape.vA, ref orientation, out localTriangleShape.vA);
                    Matrix3x3.TransformTranspose(ref localTriangleShape.vB, ref orientation, out localTriangleShape.vB);
                    Matrix3x3.TransformTranspose(ref localTriangleShape.vC, ref orientation, out localTriangleShape.vC);

                    //Now, generate a contact between the two shapes.
                    ContactData contact;
                    TinyStructList<ContactData> contactList;
                    if (pairTester.GenerateContactCandidate(out contactList))
                    {
                        for (int j = 0; j < contactList.Count; j++)
                        {
                            contactList.Get(j, out contact);


                            if (UseImprovedBoundaryHandling)
                            {
                                if (replacedyzeCandidate(ref indices, pairTester, ref contact))
                                {
                                    //This is let through if there's a face contact. Face contacts cannot be blocked.
                                    guaranteedContacts++;
                                    AddLocalContact(ref contact, ref orientation);
                                }
                            }
                            else
                            {
                                AddLocalContact(ref contact, ref orientation);
                            }

                        }
                    }

                    //Get the voronoi region from the contact candidate generation.  Possibly just recalculate, since most of the systems don't calculate it.
                    //Depending on which voronoi region it is in (Switch on enumeration), identify the indices composing that region.  For face contacts, don't bother- just add it if unique.
                    //For AB, AC, or BC, add an Edge to the blockedEdgeRegions set with the corresponding indices.
                    //For A, B, or C, add the index of the vertex to the blockedVertexRegions set.
                    //If the edge/vertex is already present in the set, then DO NOT add the contact.
                    //When adding a contact, add ALL other voronoi regions to the blocked sets. 
                }

            }



            if (UseImprovedBoundaryHandling)
            {

                //If there were no face contacts that absolutely must be included, we may get into a very rare situation
                //where absolutely no contacts get created.  For example, a sphere falling directly on top of a vertex in a flat terrain.
                //It will generally get locked out of usage by belonging only to restricted regions (numerical issues make it visible by both edges and vertices).
                //In some cases, the contacts will be ignored instead of corrected (e.g. spheres).
                //To prevent objects from just falling through the ground in such a situation, force-correct the contacts regardless of the pair tester's desires.
                //Sure, it might not be necessary under normal cirreplacedstances, but it's a better option than having no contacts.
                //TODO: There is another option: Changing restricted regions so that a vertex only restricts the other two vertices and the far edge,
                //and an edge only restricts the far vertex and other two edges.  This introduces an occasional bump though...

                //It's possible, in very specific instances, for an object to wedge itself between two adjacent triangles.
                //For this state to continue beyond a brief instant generally requires the object be orientation locked and slender.
                //However, some characters fit this description, so it can't be ignored!

                //Conceptually, this issue can occur at either a vertex junction or a shared edge (usually on extremely flat surfaces only).
                //However, an object stuck between multiple triangles is not in a stable state.  In the edge case, the object gets shoved to one side
                //as one contact 'wins' the solver war.  That's not enough to escape, unfortunately.
                //The vertex case, on the other hand, is degenerate and decays into an edge case rapidly thanks to this lack of stability.
                //So, we don't have to explicitly handle the somewhat more annoying and computationally expensive vertex unstucking case, because the edge case handles both! :)

                //This isn't a completely free operation, but it's guarded behind pretty rare conditions.
                //Essentially, we will check to see if there's just edge contacts fighting against each other.
                //If they are, then we will correct any stuck-contributing normals to the triangle normal.
                if (vertexContacts.Count == 0 && guaranteedContacts == 0 && edgeContacts.Count > 1)
                {
                    //There are only edge contacts, check to see if:
                    //all normals are coplanar, and
                    //at least one normal faces against the other normals (meaning it's probably stuck, as opposed to just colliding on a corner).

                    bool allNormalsInSamePlane = true;
                    bool atLeastOneNormalAgainst = false;

                    var firstNormal = edgeContacts.Elements[0].ContactData.Normal;
                    edgeContacts.Elements[0].CorrectedNormal.Normalize();
                    float dot;
                    Vector3.Dot(ref firstNormal, ref edgeContacts.Elements[0].CorrectedNormal, out dot);
                    if (Math.Abs(dot) > .01f)
                    {
                        //Go ahead and test the first contact separately, since we're using its contact normal to determine coplanarity.
                        allNormalsInSamePlane = false;
                    }
                    else
                    {
                        //TODO: Note that we're only checking the new edge contacts, not the existing contacts.
                        //It's possible that some existing contacts could interfere and cause issues, but for the sake of simplicity and due to rarity
                        //we'll ignore that possibility for now.
                        for (int i = 1; i < edgeContacts.Count; i++)
                        {
                            Vector3.Dot(ref edgeContacts.Elements[i].ContactData.Normal, ref firstNormal, out dot);
                            if (dot < 0)
                            {
                                atLeastOneNormalAgainst = true;
                            }
                            //Check to see if the normal is outside the plane.
                            Vector3.Dot(ref edgeContacts.Elements[i].ContactData.Normal, ref edgeContacts.Elements[0].CorrectedNormal, out dot);

                            if (Math.Abs(dot) > .01f)
                            {

                                //We are not stuck!
                                allNormalsInSamePlane = false;
                                break;
                            }
                        }
                    }

                    if (allNormalsInSamePlane && atLeastOneNormalAgainst)
                    {
                        //Uh oh! all the normals are parallel... The object is probably in a weird situation.
                        //Let's correct the normals!

                        //Already normalized the first contact above.
                        //We don't need to perform the perpendicularity test here- we did that before! We know it's perpendicular already.
                        edgeContacts.Elements[0].ContactData.Normal = edgeContacts.Elements[0].CorrectedNormal;
                        edgeContacts.Elements[0].ShouldCorrect = true;

                        for (int i = 1; i < edgeContacts.Count; i++)
                        {
                            //Must normalize the corrected normal before using it.
                            edgeContacts.Elements[i].CorrectedNormal.Normalize();
                            Vector3.Dot(ref edgeContacts.Elements[i].CorrectedNormal, ref edgeContacts.Elements[i].ContactData.Normal, out dot);
                            if (dot < .01)
                            {
                                //Only bother doing the correction if the normal appears to be pointing nearly horizontally- implying that it's a contributor to the stuckness!
                                //If it's blocked, the next section will use the corrected normal- if it's not blocked, the next section will use the direct normal.
                                //Make them the same thing :)
                                edgeContacts.Elements[i].ContactData.Normal = edgeContacts.Elements[i].CorrectedNormal;
                                edgeContacts.Elements[i].ShouldCorrect = true;
                                //Note that the penetration depth is NOT corrected.  The contact's depth no longer represents the true depth.
                                //However, we only need to have some penetration depth to get the object to escape the rut.
                                //Furthermore, the depth computed from the horizontal opposing contacts is known to be less than the depth in the perpendicular direction.
                                //If the current depth was NOT less than the true depth along the corrected normal, then the collision detection system 
                                //would have picked a different depth, as it finds a reasonable approximation of the minimum penetration!
                                //As a consequence, this contact will not be active beyond the object's destuckification, because its contact depth will be negative (or very close to it).

                            }
                        }
                    }
                }


              


                for (int i = 0; i < edgeContacts.Count; i++)
                {
                    //Only correct if it's allowed AND it's blocked.
                    //If it's not blocked, the contact being created is necessary!
                    //The normal generated by the triangle-convex tester is already known not to
                    //violate the triangle sidedness.
                    if (!blockedEdgeRegions.Contains(edgeContacts.Elements[i].Edge))
                    {
                        //If it's not blocked, use the contact as-is without correcting it.
                        AddLocalContact(ref edgeContacts.Elements[i].ContactData, ref orientation);

                    }
                    else if (edgeContacts.Elements[i].ShouldCorrect || guaranteedContacts == 0)
                    {
                        //If it is blocked, we can still make use of the contact.  But first, we need to change the contact normal to ensure that
                        //it will not interfere (and cause a bump or something).
                        float dot;
                        edgeContacts.Elements[i].CorrectedNormal.Normalize();
                        Vector3.Dot(ref edgeContacts.Elements[i].CorrectedNormal, ref edgeContacts.Elements[i].ContactData.Normal, out dot);
                        edgeContacts.Elements[i].ContactData.Normal = edgeContacts.Elements[i].CorrectedNormal;
                        edgeContacts.Elements[i].ContactData.PenetrationDepth *= MathHelper.Max(0, dot); //Never cause a negative penetration depth.
                        AddLocalContact(ref edgeContacts.Elements[i].ContactData, ref orientation);
                    }
                    //If it's blocked AND it doesn't allow correction, ignore its existence.



                }




                for (int i = 0; i < vertexContacts.Count; i++)
                {

                    if (!blockedVertexRegions.Contains(vertexContacts.Elements[i].Vertex))
                    {
                        //If it's not blocked, use the contact as-is without correcting it.
                        AddLocalContact(ref vertexContacts.Elements[i].ContactData, ref orientation);
                    }
                    else if (vertexContacts.Elements[i].ShouldCorrect || guaranteedContacts == 0)
                    {
                        //If it is blocked, we can still make use of the contact.  But first, we need to change the contact normal to ensure that
                        //it will not interfere (and cause a bump or something).
                        float dot;
                        vertexContacts.Elements[i].CorrectedNormal.Normalize();
                        Vector3.Dot(ref vertexContacts.Elements[i].CorrectedNormal, ref vertexContacts.Elements[i].ContactData.Normal, out dot);
                        vertexContacts.Elements[i].ContactData.Normal = vertexContacts.Elements[i].CorrectedNormal;
                        vertexContacts.Elements[i].ContactData.PenetrationDepth *= MathHelper.Max(0, dot); //Never cause a negative penetration depth.
                        AddLocalContact(ref vertexContacts.Elements[i].ContactData, ref orientation);
                    }
                    //If it's blocked AND it doesn't allow correction, ignore its existence.


                }



                blockedEdgeRegions.Clear();
                blockedVertexRegions.Clear();
                vertexContacts.Clear();
                edgeContacts.Clear();


            }



            //Remove stale pair testers.
            //This will only remove 8 stale ones per frame, but it doesn't really matter.
            //VERY rarely will there be more than 8 in a single frame, and they will be immediately taken care of in the subsequent frame.
            var toRemove = new TinyList<TriangleIndices>();
            foreach (KeyValuePair<TriangleIndices, TrianglePairTester> pair in activePairTesters)
            {
                if (!pair.Value.Updated)
                {
                    if (!toRemove.Add(pair.Key))
                        break;
                }
                else
                    pair.Value.Updated = false;
            }



            for (int i = toRemove.Count - 1; i >= 0; i--)
            {
                var pairTester = activePairTesters[toRemove[i]];
                pairTester.CleanUp();
                GiveBackTester(pairTester);
                activePairTesters.Remove(toRemove[i]);
            }


            //Some child types will want to do some extra post processing on the manifold.        
            ProcessCandidates(candidatesToAdd);


            //Check if adding the new contacts would overflow the manifold.
            if (contacts.Count + candidatesToAdd.Count > 4)
            {
                //Adding all the contacts would overflow the manifold.  Reduce to the best subset.
                ContactReducer.ReduceContacts(contacts, candidatesToAdd, contactIndicesToRemove, reducedCandidates);
                RemoveQueuedContacts();
                for (int i = reducedCandidates.Count - 1; i >= 0; i--)
                {
                    Add(ref reducedCandidates.Elements[i]);
                    reducedCandidates.RemoveAt(i);
                }
            }
            else if (candidatesToAdd.Count > 0)
            {
                //Won't overflow the manifold, so just toss it in PROVIDED that it isn't too close to something else.
                for (int i = 0; i < candidatesToAdd.Count; i++)
                {
                    Add(ref candidatesToAdd.Elements[i]);
                }
            }



            candidatesToAdd.Clear();

        }

19 View Source File : ParentObject.cs
License : MIT License
Project Creator : Aeroluna

private void OnDestroy()
        {
            ParentObjects.Clear();
        }

19 View Source File : DetectorVolumeGroupPairHandler.cs
License : The Unlicense
Project Creator : aeroson

public override void UpdateCollision(float dt)
        {
            WasContaining = Containing;
            WasTouching = Touching;

            //Gather current pairs.      
            UpdateContainedPairs();

            //Eliminate old pairs.
            foreach (var other in subPairs.Keys)
            {
                if (!containedPairs.Contains(other))
                    pairsToRemove.Add(other);
            }
            for (int i = 0; i < pairsToRemove.Count; i++)
            {
                var toReturn = subPairs[pairsToRemove.Elements[i]];
                subPairs.Remove(pairsToRemove.Elements[i]);
                toReturn.CleanUp();
                toReturn.Factory.GiveBack(toReturn);

            }
            containedPairs.Clear();
            pairsToRemove.Clear();


            //Scan the pairs in sequence, updating the state as we go.
            //Touching can be set to true by a single touching subpair.
            Touching = false;
            //Containing can be set to false by a single noncontaining or nontouching subpair.
            Containing = subPairs.Count > 0;
            foreach (var pair in subPairs.Values)
            {
                //For child convex pairs, we don't need to always perform containment checks.
                //Only check if the containment state has not yet been invalidated or a touching state has not been identified.
                var convexPair = pair as DetectorVolumeConvexPairHandler;
                if (convexPair != null)
                    convexPair.CheckContainment = Containing || !Touching;

                pair.UpdateCollision(dt);

                if (pair.Touching)
                    Touching = true; //If one child is touching, then we are touching too.
                else
                    Containing = false; //If one child isn't touching, then we aren't containing.

                if (!pair.Containing) //If one child isn't containing, then we aren't containing.
                    Containing = false;


                if (!Containing && Touching)
                {
                    //If it's touching but not containing, no further pairs will change the state.
                    //Containment has been invalidated by something that either didn't touch or wasn't contained.
                    //Touching has been ensured by at least one object touching.
                    break;
                }
            }

            NotifyDetectorVolumeOfChanges();
        }

19 View Source File : GroupPairHandler.cs
License : The Unlicense
Project Creator : aeroson

protected virtual void UpdateContacts(float dt)
        {

            UpdateContainedPairs();
            //Eliminate old pairs.
            foreach (CollidablePair pair in subPairs.Keys)
            {
                if (!containedPairs.Contains(pair))
                    pairsToRemove.Add(pair);
            }
            for (int i = 0; i < pairsToRemove.Count; i++)
            {
                CollidablePairHandler toReturn = subPairs[pairsToRemove.Elements[i]];
                subPairs.Remove(pairsToRemove.Elements[i]);
                toReturn.CleanUp();
                toReturn.Factory.GiveBack(toReturn);

            }
            containedPairs.Clear();
            pairsToRemove.Clear();

            foreach (CollidablePairHandler pair in subPairs.Values)
            {
                if (pair.BroadPhaseOverlap.collisionRule < CollisionRule.NoNarrowPhaseUpdate) //Don't test if the collision rules say don't.
                    pair.UpdateCollision(dt);
            }


        }

19 View Source File : MeshGroupPairHandler.cs
License : The Unlicense
Project Creator : aeroson

protected virtual void UpdateContacts(float dt)
        {

            UpdateContainedPairs(dt);
            //Eliminate old pairs.
            foreach (var pair in subPairs.Keys)
            {
                if (!containedPairs.Contains(pair))
                    pairsToRemove.Add(pair);
            }
            for (int i = 0; i < pairsToRemove.Count; i++)
            {
                var toReturn = subPairs[pairsToRemove.Elements[i]];
                subPairs.Remove(pairsToRemove.Elements[i]);
                toReturn.CleanUp();
                toReturn.Factory.GiveBack(toReturn);

            }
            containedPairs.Clear();
            pairsToRemove.Clear();

            foreach (var pair in subPairs)
            {
                if (pair.Value.BroadPhaseOverlap.collisionRule < CollisionRule.NoNarrowPhaseUpdate) //Don't test if the collision rules say don't.
                {
                    ConfigureCollidable(pair.Key, dt);
                    //Update the contact count using our (the parent) contact count so that the child can avoid costly solidity testing.
                    pair.Value.MeshManifold.parentContactCount = contactCount;
                    pair.Value.UpdateCollision(dt);
                }
            }


        }

19 View Source File : CommonResources.cs
License : The Unlicense
Project Creator : aeroson

public static void GiveBack(HashSet<int> set)
        {
            set.Clear();
            SubPoolIntSet.GiveBack(set);
        }

19 View Source File : Planet.cs
License : The Unlicense
Project Creator : aeroson

private void UpdateChunkRenderers(Stopwatch frameStart, TimeSpan timeBudget)
	{
		MyProfiler.BeginSample("Procedural Planet / Update ChunkRenderers");

		if (subdivisonCalculationLast == null) return;

		MyProfiler.BeginSample("Procedural Planet / Update ChunkRenderers / UnionWith");
		toRenderChunks.Clear();
		toRenderChunks.UnionWith(subdivisonCalculationLast.GetChunksToRender());
		MyProfiler.EndSample();

		MyProfiler.BeginSample("Procedural Planet / Update ChunkRenderers / calculate toStartRendering");
		toStartRendering.Clear();
		foreach (var chunk in toRenderChunks)
		{
			if (!chunk.HasFullyGeneratedData) continue;
			if (!chunksCurrentlyRendered.ContainsKey(chunk)) toStartRendering.Add(chunk);
			//if (toStartRendering.Count > 10) break;
		}
		MyProfiler.EndSample();

		// if chunks are regenerated, refresh their rendering
		foreach (var chunk in chunkGenerationJustFinished)
		{
			if (chunksCurrentlyRendered.ContainsKey(chunk))
			{
				chunksCurrentlyRendered[chunk].RenderChunk(chunk);
				considerChunkForCleanup.Remove(chunk);
			}
		}

		MyProfiler.BeginSample("Procedural Planet / Update ChunkRenderers / toStopRendering / calculate");
		toStopRendering.Clear();
		foreach (var kvp in chunksCurrentlyRendered)
		{
			if (!toRenderChunks.Contains(kvp.Key)) toStopRendering.Add(kvp.Key);
		}
		MyProfiler.EndSample();

		MyProfiler.BeginSample("Procedural Planet / Update ChunkRenderers / toStopRendering / execute");
		foreach (var chunk in toStopRendering)
		{
			bool bIsAnyParentRendered = false;
			{
				ChunkData parent = chunk.parent;
				while (parent != null)
				{
					if (!toStopRendering.Contains(parent) && chunksCurrentlyRendered.ContainsKey(parent))
					{
						bIsAnyParentRendered = true;
						break;
					}

					parent = parent.parent;
				}
			}

			bool bAllChildrenRendered = chunk.AreAllChildrenRendered;

			if (bIsAnyParentRendered || bAllChildrenRendered) // make sure we hide chunk only if there is some other chunk rendering mesh in its place
			{
				freeRenderers.Push(chunksCurrentlyRendered[chunk]);
				chunksCurrentlyRendered.Remove(chunk);
				considerChunkForCleanup.Add(chunk);
			}
		}
		MyProfiler.EndSample();

		MyProfiler.BeginSample("Procedural Planet / Update ChunkRenderers / toStartRendering / get free renderers");
		while (freeRenderers.Count < toStartRendering.Count)
		{
			var renderer = ProceduralPlanets.main.GetFreeChunkRendererFromPool();
			freeRenderers.Push(renderer);
		}
		MyProfiler.EndSample();

		MyProfiler.BeginSample("Procedural Planet / Update ChunkRenderers / toStartRendering / execute");
		foreach (var chunk in toStartRendering)
		{
			var renderer = freeRenderers.Pop();
			renderer.RenderChunk(chunk);
			chunksCurrentlyRendered.Add(chunk, renderer);
			considerChunkForCleanup.Remove(chunk);
		}
		MyProfiler.EndSample();

		MyProfiler.BeginSample("Procedural Planet / Update ChunkRenderers / Return to pool");
		while (freeRenderers.Count > 0)
		{
			ProceduralPlanets.main.ReturnChunkRendererToPool(freeRenderers.Pop());
		}
		MyProfiler.EndSample();


		MyProfiler.AddNumberSample("Procedural Planet / Update ChunkRenderers / to start rendering", toStartRendering.Count);
		MyProfiler.AddNumberSample("Procedural Planet / Update ChunkRenderers / to stop rendering", toStopRendering.Count);
		MyProfiler.AddNumberSample("Procedural Planet / Update ChunkRenderers / to render", toRenderChunks.Count);
		MyProfiler.AddNumberSample("Procedural Planet / chunksCurrentlyRendered", chunksCurrentlyRendered.Count);

		MyProfiler.EndSample();
	}

19 View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb

private void OnButtonSaveClick(object sender, RoutedEventArgs e)
        {
            ButtonSave.IsEnabled = false;
            if (changed.Count > 0)
            {
                RunBackground(() => {
                    var i = 1;
                    var text = "Saving {0} / " + (changed.Count + 1).ToString() + " bundles . . .";
                    foreach (var br in changed)
                    {
                        Dispatcher.Invoke(() => { CurrentBackground.Message.Text = string.Format(text, i); });
                    S:
                        if (!File.Exists(br.Name))
                        {
                            if (MessageBox.Show("File Not Found:" + Environment.NewLine + Path.GetFullPath(br.Name) + "Please put the bundle to the path and click OK", "Error", MessageBoxButton.OKCancel, MessageBoxImage.Error) == MessageBoxResult.OK)
                                goto S;
                            else
                            {
                                MessageBox.Show(" Bundles Changed" + "Please restore the backup", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                                Close();
                                return;
                            }
                        }
                        br.Save(br.Name);
                        i++;
                    }
                    Dispatcher.Invoke(() => { CurrentBackground.Message.Text = string.Format(text, i); });
                    ic.Save("_.index.bin");
                });
            }
            MessageBox.Show("Success saved!" + Environment.NewLine + changed.Count.ToString() + " bundle files changed" + Environment.NewLine + "Remember to replace all bundles and _index.bin into the ggpk.", "Done");
            changed.Clear();
        }

19 View Source File : IOExecutorService.cs
License : Apache License 2.0
Project Creator : akarnokd

public void Shutdown()
        {
            while (Volatile.Read(ref state) == STATE_STARTING) ;
            if (Interlocked.CompareExchange(ref state, STATE_SHUTDOWN, STATE_RUNNING) == STATE_RUNNING)
            {
                cleanupTask.Dispose();
                lock (guard)
                {
                    queue = ShutdownQueue;
                    foreach (var ex in executors)
                    {
                        ex.Shutdown();
                    }
                    executors.Clear();
                }
                Interlocked.Exchange(ref state, STATE_FRESH);
            }
        }

19 View Source File : TechLogFolderWatcher.cs
License : MIT License
Project Creator : akpaevj

protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    ExceceptionPaths.Clear();
                }

                StopWatching();
                disposedValue = true;
            }
        }

19 View Source File : SettingsViewModel.cs
License : MIT License
Project Creator : Aleksbgbg

public void Apply()
        {
            _settingsService.Save();
            _changedValues.Clear();
            NotifyOfPropertyChange(() => CanApply);
        }

19 View Source File : BaseNode.cs
License : MIT License
Project Creator : alelievr

public bool UpdatePortsForField(string fieldName, bool sendPortUpdatedEvent = true)
		{
			bool changed  = false;

			fieldsToUpdate.Clear();
			updatedFields.Clear();

			fieldsToUpdate.Push(new PortUpdate{fieldNames = new List<string>(){fieldName}, node = this});

			// Iterate through all the ports that needs to be updated, following graph connection when the 
			// port is updated. This is required ton have type propagation multiple nodes that changes port types
			// are connected to each other (i.e. the relay node)
			while (fieldsToUpdate.Count != 0)
			{
				var (fields, node) = fieldsToUpdate.Pop();

				// Avoid updating twice a port
				if (updatedFields.Any((t) => t.node == node && fields.SequenceEqual(t.fieldNames)))
					continue;
				updatedFields.Add(new PortUpdate{fieldNames = fields, node = node});

				foreach (var field in fields)
				{
					if (node.UpdatePortsForFieldLocal(field, sendPortUpdatedEvent))
					{
						foreach (var port in node.IsFieldInput(field) ? (NodePortContainer)node.inputPorts : node.outputPorts)
						{
							if (port.fieldName != field)
								continue;

							foreach(var edge in port.GetEdges())
							{
								var edgeNode = (node.IsFieldInput(field)) ? edge.outputNode : edge.inputNode;
								var fieldsWithBehavior = edgeNode.nodeFields.Values.Where(f => HasCustomBehavior(f)).Select(f => f.fieldName).ToList();
								fieldsToUpdate.Push(new PortUpdate{fieldNames = fieldsWithBehavior, node = edgeNode});
							}
						}
						changed = true;
					}
				}
			}

			return changed;
		}

19 View Source File : BaseGraph.cs
License : MIT License
Project Creator : alelievr

public void UpdateComputeOrder(ComputeOrderType type = ComputeOrderType.DepthFirst)
		{
			if (nodes.Count == 0)
				return ;

			// Find graph outputs (end nodes) and reset compute order
			graphOutputs.Clear();
			foreach (var node in nodes)
			{
				if (node.GetOutputNodes().Count() == 0)
					graphOutputs.Add(node);
				node.computeOrder = 0;
			}

			computeOrderDictionary.Clear();
			infiniteLoopTracker.Clear();

			switch (type)
			{
				default:
				case ComputeOrderType.DepthFirst:
					UpdateComputeOrderDepthFirst();
					break;
				case ComputeOrderType.BreadthFirst:
					foreach (var node in nodes)
						UpdateComputeOrderBreadthFirst(0, node);
					break;
			}
		}

19 View Source File : BiomeData.cs
License : MIT License
Project Creator : alelievr

public void Reset()
		{
			ids.Clear();
			biomeSamplerNameMap.Clear();

			for (int i = 0; i < length; i++)
				biomeSamplers[i] = null;

			length = 0;
		}

19 View Source File : MixtureGraphProcessor.cs
License : MIT License
Project Creator : alelievr

void ProcessNodeList(CommandBuffer cmd, HashSet<BaseNode> nodes)
		{
			HashSet<ILoopStart> starts = new HashSet<ILoopStart>();
			HashSet<ILoopEnd> ends = new HashSet<ILoopEnd>();
			HashSet<INeedLoopReset> iNeedLoopReset = new HashSet<INeedLoopReset>();

			// Note that this jump pattern doesn't handle correctly the multiple dependencies a for loop
			// can have and it may cause some nodes to be processed multiple times unnecessarily, depending on the compute order.
			Stack<(ILoopStart node, int index)> jumps = new Stack<(ILoopStart, int)>();

			// TODO: cache?
			var sortedNodes = nodes.Where(n => n.computeOrder >= 0).OrderBy(n => n.computeOrder).ToList();

			int maxLoopCount = 0;
			jumps.Clear();
			starts.Clear();
			ends.Clear();
			iNeedLoopReset.Clear();

			for (int executionIndex = 0; executionIndex < sortedNodes.Count; executionIndex++)
			{
				maxLoopCount++;
				if (maxLoopCount > 10000)
					return;

				var node = sortedNodes[executionIndex];

				if (node is ILoopStart loopStart)
				{
					if (!starts.Contains(loopStart))
					{
						loopStart.PrepareLoopStart();
						jumps.Push((loopStart, executionIndex));
						starts.Add(loopStart);
					}
				}

				bool finalIteration = false;
				if (node is ILoopEnd loopEnd)
				{
					if (jumps.Count == 0)
					{
						Debug.Log("Aborted execution, for end without start");
						return ;
					}

					var startLoop = jumps.Peek();
					if (!ends.Contains(loopEnd))
					{
						loopEnd.PrepareLoopEnd(startLoop.node);
						ends.Add(loopEnd);
					}

					// Jump back to the foreach start
					if (!startLoop.node.IsLasreplacederation())
					{
						executionIndex = startLoop.index - 1;
					}
					else
					{
						var fs2 = jumps.Pop();
						starts.Remove(fs2.node);
						ends.Remove(loopEnd);
						finalIteration = true;
					}
				}

				if (node is INeedLoopReset i)
				{
					if (!iNeedLoopReset.Contains(i))
					{
						i.PrepareNewIteration();
						iNeedLoopReset.Add(i);
					}

					// TODO: remove this node form iNeedLoopReset when we go over a foreach start again
				}
			
				if (finalIteration && node is ILoopEnd le)
				{
					le.FinalIteration();
				}

				ProcessNode(cmd, node);
			}
		}

19 View Source File : OutputNode.cs
License : MIT License
Project Creator : alelievr

void UpdateMessages()
		{
			if (inputPorts.All(p => p?.GetEdges()?.Count == 0))
			{
				if (uniqueMessages.Add("OutputNotConnected"))
					AddMessage("Output node input is not connected", NodeMessageType.Warning);
			}
			else
			{
				uniqueMessages.Clear();
				ClearMessages();
			}
		}

19 View Source File : QuadTreeTileProvider.cs
License : MIT License
Project Creator : alen-smajic

public HashSet<UnwrappedTileId> GetWithWebMerc(Vector2dBounds bounds, int zoom)
		{
			_tiles.Clear();
			_canonicalTiles.Clear();

			if (bounds.IsEmpty()) { return _tiles; }

			//stay within WebMerc bounds
			Vector2d swWebMerc = new Vector2d(Math.Max(bounds.SouthWest.x, -Utils.Constants.WebMercMax), Math.Max(bounds.SouthWest.y, -Utils.Constants.WebMercMax));
			Vector2d neWebMerc = new Vector2d(Math.Min(bounds.NorthEast.x, Utils.Constants.WebMercMax), Math.Min(bounds.NorthEast.y, Utils.Constants.WebMercMax));

			UnwrappedTileId swTile = WebMercatorToTileId(swWebMerc, zoom);
			UnwrappedTileId neTile = WebMercatorToTileId(neWebMerc, zoom);

			for (int x = swTile.X; x <= neTile.X; x++)
			{
				for (int y = neTile.Y; y <= swTile.Y; y++)
				{
					UnwrappedTileId uwtid = new UnwrappedTileId(zoom, x, y);
					//hack: currently too many tiles are created at lower zoom levels
					//investigate formulas, this worked before
					if (!_canonicalTiles.Contains(uwtid.Canonical))
					{
						_tiles.Add(uwtid);
						_canonicalTiles.Add(uwtid.Canonical);
					}
				}
			}

			return _tiles;
		}

19 View Source File : Context.cs
License : MIT License
Project Creator : alexanderdna

public void ClearStoredBlocks()
        {
            storedBlockIndices.Clear();
            storedBlocks.Clear();
        }

See More Examples