Example #1
0
        //constructor
        public DDR3DRAM(DDR3Enum type, uint clock_factor, uint tWR, uint tWTR)
        {
            timing = new Timing();
            switch (type) {
                case DDR3Enum.DDR3_2Gb_x8_1066_8_8_8:
                    DDR3_2Gb_x8_1066_8_8_8();
                    break;
                case DDR3Enum.DDR3_2Gb_x8_1333_10_10_10:
                    DDR3_2Gb_x8_1333_10_10_10();
                    break;
                case DDR3Enum.DDR3_2Gb_x8_1600_11_11_11:
                    DDR3_2Gb_x8_1600_11_11_11();
                    break;
                case DDR3Enum.PCM_2Gb_x8_1066_36_8_8:
                    PCM_2Gb_x8_1066_36_8_8();
                    break;
            }

            if (tWR != 0)
                timing.tWR = tWR;

            if (tWTR != 0)
                timing.tWTR = tWTR;

            timing.scale(clock_factor);

            /*
            if (tCCD != 0)
                timing.tCCD = tCCD;

            if (tBL != 0)
                timing.tBL = tBL;
            */
        }
Example #2
0
		public Timing GetTimingData( float realTime ) { 
			Timing t = new Timing();
			t.totalBeats = realTime / beatTime;
			t.measures = (int)(t.totalBeats / beatsPerMeasure);
			t.beats = t.totalBeats % beatsPerMeasure + 1;
			return t;
		}
Example #3
0
        static int Main()
        {
            int[] nums = new int[100000];
            BuildArray(nums);

            Timing tObj = new Timing();
            tObj.startTime();
            DisplayNums(nums);
            tObj.stopTime();

            Console.WriteLine("time (.NET):" + tObj.Result().TotalSeconds);

            return 0;
        }
		public SqlTrigger(MethodInfo method, Timing timing)
		{
			this.method = method;
			this.timing = timing;
		}
Example #5
0
        public void PostLoadPlayer(Exiled.API.Features.Player player)
        {
            Player databasePlayer = player.GetDatabasePlayer();


            if (!string.IsNullOrEmpty(databasePlayer.BadgeName))
            {
                UserGroup group = ServerStatic.GetPermissionsHandler()._groups[databasePlayer.BadgeName];


                if (databasePlayer.BadgeExpire >= DateTime.Now)
                {
                    player.ReferenceHub.serverRoles.SetGroup(group, false, true, true);
                    if (ServerStatic.PermissionsHandler._members.ContainsKey(player.UserId))
                    {
                        ServerStatic.PermissionsHandler._members.Remove(player.UserId);
                    }

                    ServerStatic.PermissionsHandler._members.Add(player.UserId, databasePlayer.BadgeName);
                    BadgeSetEvent args = new BadgeSetEvent();
                    args.Player       = player;
                    args.NewBadgeName = databasePlayer.BadgeName;
                    pluginInstance.Events.OnBadgeSet(args);
                }
                else
                {
                    BadgeRemovedEvent args = new BadgeRemovedEvent();
                    args.Player              = player;
                    args.BadgeName           = databasePlayer.BadgeName;
                    databasePlayer.BadgeName = "";

                    if (ServerStatic.PermissionsHandler._members.ContainsKey(player.UserId))
                    {
                        ServerStatic.PermissionsHandler._members.Remove(player.UserId);
                    }
                    if (ServerStatic.RolesConfig.GetStringDictionary("Members").ContainsKey(player.UserId))
                    {
                        UserGroup previous = ServerStatic.GetPermissionsHandler()._groups[ServerStatic.RolesConfig.GetStringDictionary("Members")[player.UserId]];
                        ServerStatic.PermissionsHandler._members.Add(player.UserId, ServerStatic.RolesConfig.GetStringDictionary("Members")[player.UserId]);
                        player.ReferenceHub.serverRoles.SetGroup(previous, false, true, true);
                    }
                    pluginInstance.Events.OnBadgeRemoved(args);
                }
            }

            Timing.CallDelayed(1.5f, () =>
            {
                if (!string.IsNullOrEmpty(databasePlayer.ColorPreference) && databasePlayer.ColorPreference != "None")
                {
                    if (player.CheckPermission("scputils.changecolor") || player.CheckPermission("scputils.playersetcolor") || databasePlayer.KeepPreferences || pluginInstance.Config.KeepColorWithoutPermission)
                    {
                        player.RankColor = databasePlayer.ColorPreference;
                    }
                    else
                    {
                        databasePlayer.ColorPreference = "";
                    }
                }

                if (databasePlayer.HideBadge == true)
                {
                    if (player.CheckPermission("scputils.badgevisibility") || databasePlayer.KeepPreferences || pluginInstance.Config.KeepBadgeVisibilityWithoutPermission)
                    {
                        player.BadgeHidden = true;
                    }
                    else
                    {
                        databasePlayer.HideBadge = false;
                    }
                }


                if (!string.IsNullOrEmpty(databasePlayer.CustomNickName) && databasePlayer.CustomNickName != "None")
                {
                    if (player.CheckPermission("scputils.changenickname") || player.CheckPermission("scputils.playersetname") || databasePlayer.KeepPreferences || pluginInstance.Config.KeepNameWithoutPermission)
                    {
                        player.DisplayNickname = databasePlayer.CustomNickName;
                    }
                    else
                    {
                        databasePlayer.CustomNickName = "";
                    }
                }

                if (pluginInstance.Config.AutoKickBannedNames && pluginInstance.Functions.CheckNickname(player.Nickname) && !player.CheckPermission("scputils.bypassnickrestriction"))
                {
                    Timing.CallDelayed(2f, () =>
                    {
                        player.Kick("Auto-Kick: " + pluginInstance.Config.AutoKickBannedNameMessage, "SCPUtils");
                    });
                }
            });

            if (databasePlayer.UserNotified.Count() <= 0)
            {
                return;
            }

            if (databasePlayer.UserNotified[databasePlayer.UserNotified.Count() - 1] == false)
            {
                player.ClearBroadcasts();
                player.Broadcast(pluginInstance.Config.OfflineWarnNotification);
                databasePlayer.UserNotified[databasePlayer.UserNotified.Count() - 1] = true;
            }
        }
		public TriggerEventArgs(IDb db, Timing timing) : base()
		{
			this.db = db;
			this.timing = timing;
		}
Example #7
0
        private void SaveTiming(Timing timing)
        {
            var rootTiming = new TimingPoco
            {
                Id = timing.Id,
                ParentTimingId = timing.IsRoot ? (Guid?)null : timing.ParentTiming.Id,
                Name = timing.Name,
                StartMilliseconds = (double)timing.StartMilliseconds,
                DurationMilliseconds = (double)timing.DurationMilliseconds
            };

            Timings.Insert(rootTiming);

            if (timing.HasChildren)
            {
                foreach (var child in timing.Children)
                {
                    SaveTiming(child);
                }
            }

            if (timing.HasCustomTimings)
            {
                foreach (var customTimingsKV in timing.CustomTimings)
                {
                    SaveCustomTimings(timing, customTimingsKV);
                }
            }
        }
Example #8
0
	private void SetCurrentTimingDSPTime () {
		double dspTimeSinceStart = AudioSettings.dspTime - dspStartTime;
		currentTiming = settings.GetTimingData ((float)dspTimeSinceStart);
	}
Example #9
0
 private void FlattenTimings(Timing timing, List<Timing> timingsCollection)
 {
     timingsCollection.Add(timing);
     if (timing.HasChildren)
     {
         timing.Children.ForEach(x => FlattenTimings(x, timingsCollection));
     }
 }
Example #10
0
        private static int ActualRun(string commandName, ITemplateEngineHost host, ITelemetryLogger telemetryLogger, New3Callbacks callbacks, string[] args, string hivePath)
        {
            if (args.Any(x => string.Equals(x, "--debug:version", StringComparison.Ordinal)))
            {
                ShowVersion();
                return(0);
            }

            if (args.Any(x => string.Equals(x, "--debug:attach", StringComparison.Ordinal)))
            {
                Console.ReadLine();
            }

            int customHiveFlagIndex = args.ToList().IndexOf("--debug:custom-hive");

            if (customHiveFlagIndex >= 0)
            {
                if (customHiveFlagIndex + 1 >= args.Length)
                {
                    Reporter.Error.WriteLine("--debug:custom-hive requires 1 arg indicating the absolute or relative path to the custom hive".Bold().Red());
                    return(1);
                }

                hivePath = args[customHiveFlagIndex + 1];
                if (hivePath.StartsWith("-"))
                {
                    Reporter.Error.WriteLine("--debug:custom-hive requires 1 arg indicating the absolute or relative path to the custom hive".Bold().Red());
                    return(1);
                }
            }

            if (args.Length == 0)
            {
                telemetryLogger.TrackEvent(commandName + TelemetryConstants.CalledWithNoArgsEventSuffix);
            }

            INewCommandInput commandInput = new NewCommandInputCli(commandName);
            New3Command      instance     = new New3Command(commandName, host, telemetryLogger, callbacks, commandInput, hivePath);

            commandInput.OnExecute(instance.ExecuteAsync);

            int result;

            try
            {
                using (Timing.Over(host, "Execute"))
                {
                    result = commandInput.Execute(args);
                }
            }
            catch (Exception ex)
            {
                AggregateException ax = ex as AggregateException;

                while (ax != null && ax.InnerExceptions.Count == 1)
                {
                    ex = ax.InnerException;
                    ax = ex as AggregateException;
                }

                Reporter.Error.WriteLine(ex.Message.Bold().Red());

                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                    ax = ex as AggregateException;

                    while (ax != null && ax.InnerExceptions.Count == 1)
                    {
                        ex = ax.InnerException;
                        ax = ex as AggregateException;
                    }

                    Reporter.Error.WriteLine(ex.Message.Bold().Red());
                }

                Reporter.Error.WriteLine(ex.StackTrace.Bold().Red());
                result = 1;
            }

            return(result);
        }
Example #11
0
 public Timer(Timing clock, int seconds, int timeLast)
     : this(clock, seconds)
 {
     this.TimeLast = timeLast;
 }
Example #12
0
        public virtual void FinishTraining()
        {
            Timing.Tick("Counting characters...");
            ClassicCounter <ChineseCharacterBasedLexicon.Symbol> charCounter = new ClassicCounter <ChineseCharacterBasedLexicon.Symbol>();

            // first find all chars that occur only once
            foreach (IList <TaggedWord> labels in trainingSentences)
            {
                foreach (TaggedWord label in labels)
                {
                    string word = label.Word();
                    if (word.Equals(LexiconConstants.Boundary))
                    {
                        continue;
                    }
                    for (int j = 0; j < length; j++)
                    {
                        ChineseCharacterBasedLexicon.Symbol sym = ChineseCharacterBasedLexicon.Symbol.CannonicalSymbol(word[j]);
                        charCounter.IncrementCount(sym);
                    }
                    charCounter.IncrementCount(ChineseCharacterBasedLexicon.Symbol.EndWord);
                }
            }
            ICollection <ChineseCharacterBasedLexicon.Symbol> singletons = Counters.KeysBelow(charCounter, 1.5);

            knownChars = Generics.NewHashSet(charCounter.KeySet());
            Timing.Tick("Counting nGrams...");
            GeneralizedCounter[] POSspecificCharNGrams = new GeneralizedCounter[ContextLength + 1];
            for (int i = 0; i <= ContextLength; i++)
            {
                POSspecificCharNGrams[i] = new GeneralizedCounter(i + 2);
            }
            ClassicCounter <string> POSCounter = new ClassicCounter <string>();
            IList <ISerializable>   context    = new List <ISerializable>(ContextLength + 1);

            foreach (IList <TaggedWord> words in trainingSentences)
            {
                foreach (TaggedWord taggedWord in words)
                {
                    string word = taggedWord.Word();
                    string tag  = taggedWord.Tag();
                    tagIndex.Add(tag);
                    if (word.Equals(LexiconConstants.Boundary))
                    {
                        continue;
                    }
                    POSCounter.IncrementCount(tag);
                    for (int i_1 = 0; i_1 <= size; i_1++)
                    {
                        ChineseCharacterBasedLexicon.Symbol sym;
                        ChineseCharacterBasedLexicon.Symbol unknownCharClass = null;
                        context.Clear();
                        context.Add(tag);
                        if (i_1 < size)
                        {
                            char thisCh = word[i_1];
                            sym = ChineseCharacterBasedLexicon.Symbol.CannonicalSymbol(thisCh);
                            if (singletons.Contains(sym))
                            {
                                unknownCharClass = UnknownCharClass(sym);
                                charCounter.IncrementCount(unknownCharClass);
                            }
                        }
                        else
                        {
                            sym = ChineseCharacterBasedLexicon.Symbol.EndWord;
                        }
                        POSspecificCharNGrams[0].IncrementCount(context, sym);
                        // POS-specific 1-gram
                        if (unknownCharClass != null)
                        {
                            POSspecificCharNGrams[0].IncrementCount(context, unknownCharClass);
                        }
                        // for unknown ch model
                        // context is constructed incrementally:
                        // tag prevChar prevPrevChar
                        // this could be made faster using .sublist like in score
                        for (int j = 1; j <= ContextLength; j++)
                        {
                            // poly grams
                            if (i_1 - j < 0)
                            {
                                context.Add(ChineseCharacterBasedLexicon.Symbol.BeginWord);
                                POSspecificCharNGrams[j].IncrementCount(context, sym);
                                if (unknownCharClass != null)
                                {
                                    POSspecificCharNGrams[j].IncrementCount(context, unknownCharClass);
                                }
                                // for unknown ch model
                                break;
                            }
                            else
                            {
                                ChineseCharacterBasedLexicon.Symbol prev = ChineseCharacterBasedLexicon.Symbol.CannonicalSymbol(word[i_1 - j]);
                                if (singletons.Contains(prev))
                                {
                                    context.Add(UnknownCharClass(prev));
                                }
                                else
                                {
                                    context.Add(prev);
                                }
                                POSspecificCharNGrams[j].IncrementCount(context, sym);
                                if (unknownCharClass != null)
                                {
                                    POSspecificCharNGrams[j].IncrementCount(context, unknownCharClass);
                                }
                            }
                        }
                    }
                }
            }
            // for unknown ch model
            POSDistribution = Distribution.GetDistribution(POSCounter);
            Timing.Tick("Creating character prior distribution...");
            charDistributions = Generics.NewHashMap();
            //    charDistributions = Generics.newHashMap();  // 1.5
            //    charCounter.incrementCount(Symbol.UNKNOWN, singletons.size());
            int numberOfKeys = charCounter.Size() + singletons.Count;
            Distribution <ChineseCharacterBasedLexicon.Symbol> prior = Distribution.GoodTuringSmoothedCounter(charCounter, numberOfKeys);

            charDistributions[Java.Util.Collections.EmptyList] = prior;
            for (int i_2 = 0; i_2 <= ContextLength; i_2++)
            {
                ICollection <KeyValuePair <IList <ISerializable>, ClassicCounter <ChineseCharacterBasedLexicon.Symbol> > > counterEntries = POSspecificCharNGrams[i_2].LowestLevelCounterEntrySet();
                Timing.Tick("Creating " + counterEntries.Count + " character " + (i_2 + 1) + "-gram distributions...");
                foreach (KeyValuePair <IList <ISerializable>, ClassicCounter <ChineseCharacterBasedLexicon.Symbol> > entry in counterEntries)
                {
                    context = entry.Key;
                    ClassicCounter <ChineseCharacterBasedLexicon.Symbol> c         = entry.Value;
                    Distribution <ChineseCharacterBasedLexicon.Symbol>   thisPrior = charDistributions[context.SubList(0, context.Count - 1)];
                    double priorWeight = thisPrior.GetNumberOfKeys() / 200.0;
                    Distribution <ChineseCharacterBasedLexicon.Symbol> newDist = Distribution.DynamicCounterWithDirichletPrior(c, thisPrior, priorWeight);
                    charDistributions[context] = newDist;
                }
            }
        }
Example #13
0
        public static void OnLoadedSpawnPoints()
        {
            Log.Debug("OnLoadedSpawnPoints", CustomEscape.Singleton.Config.Debug);
            Timing.CallDelayed(.5f, () =>
            {
                foreach (var kvp in _escapePosDict)
                {
                    Object.Destroy(kvp.Value);
                }

                _escapePosDict.Clear();

                _pointsPointList = Points.GetPointList(CustomEscape.Singleton.Config.PointsFileName);

                Log.Debug(
                    "Raw points: " + _pointsPointList.RawPoints.Count + " " +
                    string.Join(",", _pointsPointList.RawPoints.Select(x => x.RoomType)),
                    CustomEscape.Singleton.Config.Debug);
                Log.Debug(
                    "Fixed points: " + _pointsPointList.FixedPoints.Count + " " +
                    string.Join(",", _pointsPointList.FixedPoints.Select(x => x.Room)),
                    CustomEscape.Singleton.Config.Debug);
                Log.Debug(
                    "Escape points: " + CustomEscape.Singleton.Config.EscapePoints.Count + " " +
                    string.Join(",",
                                CustomEscape.Singleton.Config.EscapePoints.Select(x => x.Key)),
                    CustomEscape.Singleton.Config.Debug);

                foreach (var escapePoint in CustomEscape.Singleton.Config.EscapePoints)
                {
                    FixedPoint fixedPoint = _pointsPointList.FixedPoints.FirstOrDefault(x => x.Id == escapePoint.Key);
                    if (fixedPoint == null)
                    {
                        Log.Error("Unknown Id while trying to create escape point: " + escapePoint.Key);
                        continue;
                    }

                    var escapePos = GameObject.CreatePrimitive(PrimitiveType.Sphere);
                    _escapePosDict.Add(fixedPoint.Id, escapePos);
                    escapePos.name = fixedPoint.Id;

                    Log.Debug("created a sphere " + fixedPoint.Id, CustomEscape.Singleton.Config.Debug);
                    escapePos.transform.localScale =
                        new Vector3(0.001f, 0.001f, 0.001f); // stop bumping into that shit
                    escapePos.transform.localPosition = fixedPoint.Position;
                    Log.Debug(
                        $"modified the sphere '{fixedPoint.Id}': {escapePos.transform.localScale}, {escapePos.transform.localPosition}",
                        CustomEscape.Singleton.Config.Debug);

                    var collider = escapePos.GetComponent <SphereCollider>();
                    Log.Debug($"got a collider of '{fixedPoint.Id}': '{collider}'",
                              CustomEscape.Singleton.Config.Debug);
                    collider.isTrigger = true;
                    collider.radius    = escapePoint.Value.EscapeRadius;
                    Log.Debug($"modified the collider: {collider.center}, {collider.radius}, {collider.isTrigger}",
                              CustomEscape.Singleton.Config.Debug);

                    escapePos.AddComponent <CustomEscapeComponent>();
                    Log.Debug($"attached an escape component to '{fixedPoint.Id}'",
                              CustomEscape.Singleton.Config.Debug);
                }
            });
        }
Example #14
0
 public void ShowNotification(string message, float displayTime = 1.5f)
 {
     Timing.RunCoroutine(DisplayNotification(message, displayTime));
 }
        public static IEnumerator <float> CheckForSnap()
        {
            // We wait for 8 seconds to verify that everyone has spawned and been counted by the above function
            yield return(Timing.WaitForSeconds(8f));

            var random = new System.Random();

            if (hubNotSpawnedList.Count > 0)
            {
                Log.Info($"Server snap detected! We have {hubNotSpawnedList.Count} non-spawned players!");
            }

            // Iterate over the total number of players counted
            for (int i = 0; i < iTotalPlayers; i++)
            {
                // If everyone has been spawned, stop looping!
                if (hubNotSpawnedList.Count <= 0)
                {
                    break;
                }

                int      teamnum     = (int)Char.GetNumericValue(sRespawnQueueArray[0]);
                bool     tospawn     = false;
                RoleType roletospawn = RoleType.None;

                switch (teamnum)
                {
                // SCP
                case 0:
                {
                    if (iSCPCount > 0)
                    {
                        iSCPCount--;
                    }
                    else
                    {
                        tospawn = true;
                        int scprand = random.Next(0, 4);
                        switch (scprand)
                        {
                        case 0:
                            roletospawn = RoleType.Scp049;
                            break;

                        case 1:
                            roletospawn = RoleType.Scp096;
                            break;

                        case 2:
                            roletospawn = RoleType.Scp173;
                            break;

                        case 3:
                            roletospawn = RoleType.Scp106;
                            break;

                        case 4:
                            roletospawn = RoleType.Scp079;
                            break;
                        }
                    }
                    break;
                }

                // Chaos / Facility
                case 1:
                {
                    if (bChaosOnStart)
                    {
                        if (iTotalChaos > 0)
                        {
                            iTotalChaos--;
                        }
                        else
                        {
                            tospawn     = true;
                            roletospawn = RoleType.ChaosInsurgency;
                        }
                        break;
                    }
                    else
                    {
                        if (iFacilityGuardCount > 0)
                        {
                            iFacilityGuardCount--;
                        }
                        else
                        {
                            tospawn     = true;
                            roletospawn = RoleType.FacilityGuard;
                        }
                        break;
                    }
                }

                // Scientist
                case 3:
                {
                    if (iScientistCount > 0)
                    {
                        iScientistCount--;
                    }
                    else
                    {
                        tospawn     = true;
                        roletospawn = RoleType.Scientist;
                    }
                    break;
                }

                // Class D
                case 4:
                {
                    if (iClassDCount > 0)
                    {
                        iClassDCount--;
                    }
                    else
                    {
                        tospawn     = true;
                        roletospawn = RoleType.ClassD;
                    }
                    break;
                }
                }

                sRespawnQueueArray = RemoveFromArrayAt(sRespawnQueueArray, 0);

                if (tospawn)
                {
                    int    index;
                    Player playertospawn;

                    // Loop over max clients till we find a replacement
                    for (int j = 0; j < iMaxPlayers; j++)
                    {
                        index         = random.Next(hubNotSpawnedList.Count());
                        playertospawn = Player.Get(hubNotSpawnedList[index]);
                        hubNotSpawnedList.Remove(hubNotSpawnedList[index]);
                        if (playertospawn.Role == RoleType.Spectator && playertospawn != null && !playertospawn.IsOverwatchEnabled)
                        {
                            Log.Info($"Spawning in valid player {playertospawn.Nickname} as {Enum.GetName(typeof(RoleType), roletospawn)}");

                            playertospawn.SetRole(roletospawn);
                            playertospawn.Broadcast(10, $"{PlayerEvents.MSG_PREFIX} Since you didn't spawn naturally you were put in as a {Enum.GetName(typeof(RoleType), roletospawn)}");
                            break;
                        }
                    }
                }
            }

            // Second pass to make sure we have all the required SCP's Spawned!
            sRespawnQueueArray = sRespawnQueue.ToCharArray();
            iTotalPlayers      = 0;
            iSCPCount          = 0;
            int iNeededSCPCount = 0;
            int i049Count       = 0;
            int i079Count       = 0;
            int i106Count       = 0;
            int i173Count       = 0;
            int i096Count       = 0;
            int i93953Count     = 0;
            int i93989Count     = 0;

            foreach (Player rh in Player.List)
            {
                if (rh != null)
                {
                    iTotalPlayers++;
                    switch (rh.Role)
                    {
                    case RoleType.Scp049:
                        iSCPCount++;
                        i049Count++;
                        Log.Info($"Found {rh.UserId} (SCP-049)");
                        break;

                    case RoleType.Scp079:
                        iSCPCount++;
                        i079Count++;
                        Log.Info($"Found {rh.UserId} (SCP-079)");
                        break;

                    case RoleType.Scp106:
                        iSCPCount++;
                        i106Count++;
                        Log.Info($"Found {rh.UserId} (SCP-106)");
                        break;

                    case RoleType.Scp173:
                        iSCPCount++;
                        i173Count++;
                        Log.Info($"Found {rh.UserId} (SCP-173)");
                        break;

                    case RoleType.Scp096:
                        iSCPCount++;
                        i096Count++;
                        Log.Info($"Found {rh.UserId} (SCP-096)");
                        break;

                    case RoleType.Scp93953:
                        iSCPCount++;
                        i93953Count++;
                        Log.Info($"Found {rh.UserId} (SCP-939-53)");
                        break;

                    case RoleType.Scp93989:
                        iSCPCount++;
                        i93989Count++;
                        Log.Info($"Found {rh.UserId} (SCP-939-89)");
                        break;

                    default:
                        Log.Info($"Found {rh.UserId} (Not SCP)");
                        break;
                    }
                }
            }


            for (int i = 0; i < iTotalPlayers; i++)
            {
                int teamnum = (int)Char.GetNumericValue(sRespawnQueueArray[0]);

                if (teamnum == 0)
                {
                    iNeededSCPCount++;
                }
                sRespawnQueueArray = RemoveFromArrayAt(sRespawnQueueArray, 0);
            }

            Log.Info($"Needed SCP's: {iNeededSCPCount} SCP's Counted: {iSCPCount}");
            if (iSCPCount < iNeededSCPCount)
            {
                Log.Info("Not enough SCP's Spawned! Correcting now.");
                for (int i = 0; i < (iNeededSCPCount - iSCPCount); i++)
                {
                    Player   playertospawn;
                    RoleType roletospawn = RoleType.None;
                    for (int j = 0; j < iMaxPlayers; j++)
                    {
                        playertospawn = GetRandomPlayer();
                        if (playertospawn != null && !playertospawn.IsOverwatchEnabled && NotSCP(playertospawn))
                        {
                            if (i096Count == 0)
                            {
                                i096Count++;
                                roletospawn = RoleType.Scp096;
                            }
                            else if (i079Count == 0)
                            {
                                i079Count++;
                                roletospawn = RoleType.Scp079;
                            }
                            else if (i173Count == 0)
                            {
                                i173Count++;
                                roletospawn = RoleType.Scp173;
                            }
                            else if (i106Count == 0)
                            {
                                i106Count++;
                                roletospawn = RoleType.Scp106;
                            }
                            else if (i049Count == 0)
                            {
                                i049Count++;
                                roletospawn = RoleType.Scp049;
                            }
                            else if (i93953Count == 0)
                            {
                                i93953Count++;
                                roletospawn = RoleType.Scp93953;
                            }
                            else if (i93989Count == 0)
                            {
                                i93989Count++;
                                roletospawn = RoleType.Scp93989;
                            }
                            else
                            {
                                int scprand = random.Next(0, 4);
                                switch (scprand)
                                {
                                case 0:
                                    roletospawn = RoleType.Scp049;
                                    break;

                                case 1:
                                    roletospawn = RoleType.Scp096;
                                    break;

                                case 2:
                                    roletospawn = RoleType.Scp173;
                                    break;

                                case 3:
                                    roletospawn = RoleType.Scp106;
                                    break;

                                case 4:
                                    roletospawn = RoleType.Scp079;
                                    break;
                                }
                            }
                            Log.Info($"Spawning in valid player {playertospawn.Nickname} as {Enum.GetName(typeof(RoleType), roletospawn)} to fix the SCP Count!");

                            playertospawn.SetRole(roletospawn);
                            playertospawn.Broadcast(10, $"{PlayerEvents.MSG_PREFIX} Since not enough SCP's spawned your were put in as a {Enum.GetName(typeof(RoleType), roletospawn)}");
                            break;
                        }
                    }
                }
            }

            /*foreach (GameObject o in PlayerManager.players)
             * {
             *      ReferenceHub hub = o.GetComponent<ReferenceHub>();
             *      if (isDeveloper(hub))
             *      {
             *              hub.SetRankName("KILL TARGET");
             *              hub.SetvvRankColor("pink");
             *      }
             * }*/
        }
Example #16
0
 public void Wander(TrackedPath path, float startDelay)
 {
     path_     = path;
     IsStarted = true;
     Timing.RunCoroutine(WanderCo(startDelay).CancelWith(this.gameObject));
 }
Example #17
0
 protected override void Tick(Entity target, object payload)
 {
     Timing.RunCoroutine(AbilityRoutine(target, payload));
 }
Example #18
0
        public override float Process(Npc npc)
        {
            if (!npc.NPCPlayer.ReferenceHub.characterClassManager.IsAnyScp())
            {
                if (npc.AvailableWeapons.Count > 0)
                {
                    if (!npc.ItemHeld.IsWeapon(false))
                    {
                        npc.ItemHeld = npc.AvailableWeapons.Keys.ElementAt(0);
                        return(0.5f);
                    }

                    npc.Stop();
                    Vector3    heading = (npc.CurrentAIPlayerTarget.Position - npc.NPCPlayer.Position);
                    Quaternion lookRot = Quaternion.LookRotation(heading.normalized);
                    npc.NPCPlayer.Rotations = new Vector2(lookRot.eulerAngles.x, lookRot.eulerAngles.y);
                    bool       miss         = Plugin.Random.Next(0, 100) >= accuracy;
                    int        hitbox_value = Plugin.Random.Next(0, 100);
                    HitBoxType hitbox       = HitBoxType.NULL;
                    int        min          = int.MaxValue;
                    foreach (HitBoxType box in hitboxes.Keys)
                    {
                        if (hitbox_value < hitboxes[box] && hitboxes[box] <= min)
                        {
                            min    = hitboxes[box];
                            hitbox = box;
                        }
                    }

                    npc.NPCPlayer.ReferenceHub.weaponManager.CallCmdShoot(miss ? npc.gameObject : npc.CurrentAIPlayerTarget.GameObject, hitbox, npc.NPCPlayer.CameraTransform.forward, npc.NPCPlayer.Position, npc.CurrentAIPlayerTarget.Position);

                    bool end = !npc.CurrentAIPlayerTarget.IsAlive;

                    if (use_ammo)
                    {
                        npc.AvailableWeapons[npc.ItemHeld]--;
                        if (npc.AvailableWeapons[npc.ItemHeld] <= 0)
                        {
                            npc.NPCPlayer.ReferenceHub.weaponManager.RpcReload(npc.NPCPlayer.ReferenceHub.weaponManager.curWeapon);
                            npc.AvailableWeapons[npc.ItemHeld] = (int)npc.NPCPlayer.ReferenceHub.weaponManager.weapons[npc.NPCPlayer.ReferenceHub.weaponManager.curWeapon].maxAmmo;
                            if (end)
                            {
                                npc.FireEvent(new Events.NPCTargetKilledEvent(npc, npc.CurrentAIPlayerTarget));
                                IsFinished = true;
                            }
                            return(npc.NPCPlayer.ReferenceHub.weaponManager.weapons[npc.NPCPlayer.ReferenceHub.weaponManager.curWeapon].reloadingTime);
                        }
                    }


                    if (end)
                    {
                        npc.FireEvent(new Events.NPCTargetKilledEvent(npc, npc.CurrentAIPlayerTarget));
                        IsFinished = true;
                        return(0f);
                    }
                }
                else
                {
                    IsFinished = true;
                    return(0f);
                }
                return(firerate * Plugin.Instance.Config.NpcFireCooldownMultiplier * npc.NPCPlayer.ReferenceHub.weaponManager._fireCooldown);
            }
            else
            {
                float cd = 0f;
                npc.OnTargetLostBehaviour = Npc.TargetLostBehaviour.STOP;
                npc.Follow(npc.CurrentAIPlayerTarget);
                if (Vector3.Distance(npc.CurrentAIPlayerTarget.Position, npc.NPCPlayer.Position) <= 1.5f)
                {
                    if (npc.NPCPlayer.Role.Is939())
                    {
                        npc.NPCPlayer.GameObject.GetComponent <Scp939PlayerScript>().CallCmdShoot(npc.CurrentAIPlayerTarget.GameObject);
                    }
                    else
                    {
                        switch (npc.NPCPlayer.Role)
                        {
                        case RoleType.Scp106:
                            npc.NPCPlayer.GameObject.GetComponent <Scp106PlayerScript>().CallCmdMovePlayer(npc.CurrentAIPlayerTarget.GameObject, ServerTime.time);
                            cd = 2f;
                            break;

                        case RoleType.Scp173:
                            npc.NPCPlayer.GameObject.GetComponent <Scp173PlayerScript>().CallCmdHurtPlayer(npc.CurrentAIPlayerTarget.GameObject);
                            break;

                        case RoleType.Scp049:
                            npc.CurrentAIPlayerTarget.Hurt(99999f, DamageTypes.Scp049, npc.NPCPlayer.Nickname);
                            cd = PlayableScps.Scp049.KillCooldown;
                            break;

                        case RoleType.Scp0492:
                            npc.NPCPlayer.GameObject.GetComponent <Scp049_2PlayerScript>().CallCmdShootAnim();
                            npc.NPCPlayer.GameObject.GetComponent <Scp049_2PlayerScript>().CallCmdHurtPlayer(npc.CurrentAIPlayerTarget.GameObject);
                            cd = 1f;
                            break;
                        }
                    }
                    if (!npc.CurrentAIPlayerTarget.IsAlive)
                    {
                        npc.AttachedCoroutines.Add(MEC.Timing.CallDelayed(0.1f, () =>
                        {
                            npc.FireEvent(new Events.NPCTargetKilledEvent(npc, npc.CurrentAIPlayerTarget));
                        }));

                        npc.Stop();

                        Player target = npc.CurrentAIPlayerTarget;

                        npc.CurrentAIPlayerTarget = null;

                        if (npc.ProcessSCPLogic && npc.NPCPlayer.Role == RoleType.Scp049)
                        {
                            npc.AttachedCoroutines.Add(Timing.RunCoroutine(ReviveCoroutine(npc, target)));
                            IsFinished = true;
                            return(PlayableScps.Scp049.TimeToRevive + 0.5f);
                        }
                    }
                }
                return(cd);
            }
        }
		private void DisplayTiming (Timing timing)
		{
			HudScreen.DisplayTiming (timing);
		}
Example #20
0
 public AM2302(int pinNumber)
 {
     _timing = Timing.Instance;
     _pin    = CreatePin(pinNumber);
     _th     = new Thread(GetMeasure);
 }
		public TriggerAttribute(Timing timing) : base()
		{
			this.timing = timing;
		}
Example #22
0
 private void OnDestroy()
 {
     Timing.KillCoroutines(coroutineHandle);
     Exiled.Events.Handlers.Player.ChangingGroup -= OnChangingGroup;
 }
        /// <summary>
        /// Saves parameter Timing to the dbo.MiniProfilerTimings table.
        /// </summary>
        protected virtual void SaveTiming(DbConnection conn, MiniProfiler profiler, Timing t)
        {
            const string sql =
            @"insert into MiniProfilerTimings
            (Id,
             MiniProfilerId,
             ParentTimingId,
             Name,
             Depth,
             StartMilliseconds,
             DurationMilliseconds,
             DurationWithoutChildrenMilliseconds,
             SqlTimingsDurationMilliseconds,
             IsRoot,
             HasChildren,
             IsTrivial,
             HasSqlTimings,
             HasDuplicateSqlTimings,
             ExecutedReaders,
             ExecutedScalars,
             ExecutedNonQueries)
            values      (@Id,
             @MiniProfilerId,
             @ParentTimingId,
             @Name,
             @Depth,
             @StartMilliseconds,
             @DurationMilliseconds,
             @DurationWithoutChildrenMilliseconds,
             @SqlTimingsDurationMilliseconds,
             @IsRoot,
             @HasChildren,
             @IsTrivial,
             @HasSqlTimings,
             @HasDuplicateSqlTimings,
             @ExecutedReaders,
             @ExecutedScalars,
             @ExecutedNonQueries)";

            conn.Execute(sql, new
            {
                Id = t.Id,
                MiniProfilerId = profiler.Id,
                ParentTimingId = t.IsRoot ? (Guid?)null : t.ParentTiming.Id,
                Name = t.Name.Truncate(200),
                Depth = t.Depth,
                StartMilliseconds = t.StartMilliseconds,
                DurationMilliseconds = t.DurationMilliseconds,
                DurationWithoutChildrenMilliseconds = t.DurationWithoutChildrenMilliseconds,
                SqlTimingsDurationMilliseconds = t.SqlTimingsDurationMilliseconds,
                IsRoot = t.IsRoot,
                HasChildren = t.HasChildren,
                IsTrivial = t.IsTrivial,
                HasSqlTimings = t.HasSqlTimings,
                HasDuplicateSqlTimings = t.HasDuplicateSqlTimings,
                ExecutedReaders = t.ExecutedReaders,
                ExecutedScalars = t.ExecutedScalars,
                ExecutedNonQueries = t.ExecutedNonQueries
            });

            if (t.HasSqlTimings)
            {
                foreach (var st in t.SqlTimings)
                {
                    SaveSqlTiming(conn, profiler, st);
                }
            }

            if (t.HasChildren)
            {
                foreach (var child in t.Children)
                {
                    SaveTiming(conn, profiler, child);
                }
            }
        }
Example #24
0
 public void ColorFade(Color start, Color end, float timer, bool autoreverses)
 {
     Timing.RunCoroutine(ColorCo(start, end, timer, autoreverses));
 }
Example #25
0
 /// <summary>
 /// The assert SQL timings exist.
 /// </summary>
 /// <param name="timing">The timing.</param>
 /// <param name="count">The count.</param>
 private void AssertSqlTimingsExist(Timing timing, int count)
 {
     Assert.That(_conn.Query<int>("select count(*) from MiniProfilerSqlTimings where ParentTimingId = @Id ", new { timing.Id }).Single() == count);
 }
Example #26
0
 private void OnStart()
 {
     ScpCommand.allowSwaps = true;
     Timing.CallDelayed(PluginClass.Config.SwapRequestTimeout, () => ScpCommand.allowSwaps = false);
 }
Example #27
0
        public async Task Step_WithParallelTasks_RealTime()
        {
            Thread.Sleep(1000); // calm down there stupid laptop
            var profiler = Options.StartProfiler("root");

            Timing timing10 = null,
                   timing11 = null,
                   timing20 = null,
                   timing21 = null,
                   timing30 = null,
                   timing31 = null;

            // Add 100ms to root
            await Task.Delay(100).ConfigureAwait(false);

            // Start tasks in parallel
            var whenAllTask = Task.WhenAll(
                Task.Run(async() =>
            {
                // timing10: 100 + 100 = 200 ms
                using (timing10 = MiniProfiler.Current.Step("step1.0 (Task.Run)"))
                {
                    await Task.Delay(100).ConfigureAwait(false);

                    await Task.Run(async() =>
                    {
                        using (timing11 = MiniProfiler.Current.Step("step1.1 (Task.Run)"))
                        {
                            await Task.Delay(100).ConfigureAwait(false);
                        }
                    }).ConfigureAwait(false);
                }
            }),
                Task.Factory.StartNew(async() =>
            {
                // timing20: 200 + 100 = 300 ms
                using (timing20 = MiniProfiler.Current.Step("step2.0 (Task.Factory.StartNew)"))
                {
                    await Task.Delay(200).ConfigureAwait(false);

                    await Task.Run(async() =>
                    {
                        using (timing21 = MiniProfiler.Current.Step("step2.1 (Task.Run)"))
                        {
                            await Task.Delay(100).ConfigureAwait(false);
                        }
                    }).ConfigureAwait(false);
                }
                // Important to Unwrap() when using the not-for-mortals StartNew()
            }).Unwrap(),
                Task.Factory.StartNew(async() =>
            {
                // timing30: 300 + 100 = 400 ms
                using (timing30 = MiniProfiler.Current.Step("step3.0 (Task.Factory.StartNew:LongRunning)"))
                {
                    await Task.Delay(300).ConfigureAwait(false);

                    await Task.Run(async() =>
                    {
                        using (timing31 = MiniProfiler.Current.Step("step3.1 (Task.Run)"))
                        {
                            await Task.Delay(100).ConfigureAwait(false);
                        }
                    }).ConfigureAwait(false);
                }
                // Important to Unwrap() when using the not-for-mortals StartNew()
            }, TaskCreationOptions.LongRunning).Unwrap()
                );

            await whenAllTask;

            profiler.Stop();

            // Full diagnostic output
            Output.WriteLine(profiler.RenderPlainText());

            // 100ms + longest running task (step3.0 with 300 + 100 ms) = 500ms
            AssertNear(500, profiler.DurationMilliseconds, 125);

            // Parent durations are sum of itself and children
            AssertNear(200, timing10.DurationMilliseconds, 50);
            AssertNear(100, timing11.DurationMilliseconds, 50);

            AssertNear(300, timing20.DurationMilliseconds, 50);
            AssertNear(100, timing21.DurationMilliseconds, 50);

            AssertNear(400, timing30.DurationMilliseconds, 50);
            AssertNear(100, timing31.DurationMilliseconds, 50);
        }
Example #28
0
 private void OnRestart()
 {
     Timing.KillCoroutines(ScpCommand.reqCoroutines.Values.ToArray());
     ScpCommand.reqCoroutines.Clear();
 }
Example #29
0
        private void SaveCustomTimings(Timing timing, KeyValuePair<string, List<CustomTiming>> customTimingsKV)
        {
            var key = customTimingsKV.Key;
            var value = customTimingsKV.Value;

            foreach (var customTiming in value)
            {
                var customTimingPoco = new CustomTimingPoco
                {
                    Id = customTiming.Id,
                    Key = key,
                    TimingId = timing.Id,
                    CommandString = customTiming.CommandString,
                    ExecuteType = customTiming.ExecuteType,
                    StackTraceSnippet = customTiming.StackTraceSnippet,
                    StartMilliseconds = customTiming.StartMilliseconds,
                    DurationMilliseconds = customTiming.DurationMilliseconds,
                    FirstFetchDurationMilliseconds = customTiming.FirstFetchDurationMilliseconds
                };

                CustomTimings.Insert(customTimingPoco);
            }
        }
Example #30
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="line">[00111:00000100]</param>
        private void ParseDataField(string[] arr)
        {
            int[] key = line2key(arr[0]);// 001 00
            List<string> val = line2arr(arr[1]);// 00 01 AW 00
            switch (key[1])
            {
                case 1:  //BGM
                    for (int i = 0; i < val.Count; i++)
                    {
                        if (val[i] == "00")
                            continue;
                        string fn;
                        if (wavDict.TryGetValue(val[i], out fn))
                        {
                            Event e = new Event();
                            e.Section = key[0];
                            e.Filename = fn;
                            e.Offset = 1.0 * i / val.Count;
                            map.EventList.Add(e);
                        }
                    }
                    break;
                case 2:  //beat change
                    {
                        int Section = key[0];
                        int Offset = 0;
                        Timing target = map.TimingList.Find(t => t.Section == Section && t.Offset == Offset);
                        if (target == null)
                        {
                            Timing t = new Timing();
                            t.beat = double.Parse(arr[1]);
                            t.Section = Section;
                            t.Offset = Offset;
                            map.TimingList.Add(t);
                        }else
                            target.beat = double.Parse(arr[1]);
                    }
                    break;
                case 3:   //hardcode bpm
                    for (int i = 0; i < val.Count; i++)
                    {
                        if (val[i] == "00")
                            continue;
                        Timing t = new Timing();
                        t.Section = key[0];
                        t.Offset = 1.0 * i / val.Count;
                        t.bpm = Convert.ToInt32(val[i], 16);
                        t.changed = true;
                        map.TimingList.Add(t);
                    }
                    break;
                case 8:  //pre-defined bpm
                    for (int i = 0; i < val.Count; i++)
                    {
                        if (val[i] == "00")
                            continue;
                        double bpm;
                        if (map.BpmDict.TryGetValue(val[i], out bpm))
                        {
                            Timing t = new Timing();
                            t.Section = key[0];
                            t.Offset = 1.0 * i / val.Count;
                            t.bpm = bpm;
                            t.changed = true;
                            map.TimingList.Add(t);
                        }
                    }
                    break;
                case 11:
                case 12:
                case 13:
                case 14:
                case 15:
                case 16:
                case 18:
                case 19:
                    {
                        for (int i = 0; i < val.Count; i++)
                        {
                            if (val[i] == "00")
                                continue;
                            int col = key[1] == 16 ? 0 : (key[1] < 16 ? key[1] - 10 : key[1] - 12);
                            if (longType == 2 && val[i] == longObj && pendingNote[col] != null)
                            {
                                pendingNote[col].SectionEnd = key[0];
                                pendingNote[col].OffsetEnd = 1.0 * i / val.Count;
                                pendingNote[col].Type = NoteType.ManiaLong;
                                pendingNote[col] = null;
                                continue;
                            }
                            Note n = new Note();
                            n.Column = col;
                            n.SectionStart = key[0];
                            n.OffsetStart = 1.0 * i / val.Count;
                            n.Type = NoteType.Normal;
                            n.Sound = SampleManager.Get(val[i]);
                            map.NoteList.Add(n);
                            if(col>map.Column-1)
                                map.Column = col + 1; //reset map column
                            if (col == 0)
                                map.Special = true;
                            if (longType == 2)
                                pendingNote[col] = n;
                        }
                    }
                    break;
                case 51:
                case 52:
                case 53:
                case 54:
                case 55:
                case 56:
                case 58:
                case 59:
                    {
                        if (longType != 1)
                            break;
                        for (int i = 0; i < val.Count; i++)
                        {
                            if (val[i] == "00")
                                continue;
                            int col = key[1] == 56 ? 0 : (key[1] < 56 ? key[1] - 50 : key[1] - 52);
                            if (pendingNote[col] != null)
                            {
                                pendingNote[col].SectionEnd = key[0];
                                pendingNote[col].OffsetEnd = 1.0 * i / val.Count;
                                pendingNote[col] = null;
                                continue;
                            }
                            else
                            {
                                Note n = new Note();
                                n.Column = col;
                                n.SectionStart = key[0];
                                n.OffsetStart = 1.0 * i / val.Count;
                                n.Type = NoteType.ManiaLong;
                                n.Sound = SampleManager.Get(val[i]);
                                map.NoteList.Add(n);
                                if (col > map.Column - 1)
                                    map.Column = col + 1; //reset map column
                                if (col == 0)
                                    map.Special = true;
                                pendingNote[col] = n;
                            }

                        }
                    }
                    break;
            }
        }
 /// <summary>
 /// Starts timing an event. Throws an exception if an event
 /// of the same type was started but not stopped.
 /// </summary>
 /// <param name="metric"></param>
 /// <returns></returns>
 public TimingEvent StartEvent(Metric metric)
 {
     lock (metricsLock)
     {
         if (inFlightTimings.ContainsKey(metric))
             throw new InvalidOperationException("Unable to start multiple events for the same metric. Metric = " + metric);
         inFlightTimings[metric] = new Timing(CurrentTime);
     }
     return new TimingEvent(this, metric);
 }
		public void ParallelTaskWithOneActionTest()
		{
			var timings = new ConcurrentBag<Timing>();

			Action action = () =>
			{
				var timing = new Timing();

				timing.StartTime = DateTime.Now;
				Thread.Sleep(500);
				timing.FinishTime = DateTime.Now;

				timings.Add(timing);
			};

			var task = ParallelTask.StartNew(action, 10);
			task.Wait();

			DateTime maxStartTime = timings.Select(t => t.StartTime).Max();
			DateTime maxFinishTime = timings.Select(t => t.FinishTime).Min();

			foreach(var timing in timings)
			{
				Console.WriteLine(String.Format("{0} - {1}", timing.StartTime, timing.FinishTime));
			}

			Assert.IsTrue(maxStartTime < maxFinishTime);
		}
Example #33
0
        public void OnRoundStart(RoundStartEvent ev)
        {
            SOTNGamemode.pluginConfig.ReloadConfig();
            Map    map = plugin.Server.Map;
            String gameInstructions = "\nEach round consists of at least one 049-2, with a max of 4.\nIf one of the 049-2 kills you, you become one of them.\nIf you want to survive, either kill all of the zombies and supress the infection, or power on all of the generators to lift the lockdown and get an O5,\nwhich can open the entrance zone.";

            if (Status.gamemodeEnabled)
            {
                Status.gamemodeRoundActive = true;
                Status.HaltLCZD            = true;
                Timing.RunCoroutine(Functions.ResetLCZ());
                List <Player> players = ev.Server.GetPlayers();
                if (Status.activeGameType == Status.gameTypes.Regular)
                {
                    foreach (Player p in players)
                    {
                        p.SendConsoleMessage(gameInstructions);
                    }
                    int numberOfStartingInfected = 0;
                    if (players.Count < 5)
                    {
                        numberOfStartingInfected = 1;
                    }
                    else if (10 > players.Count && players.Count > 5)
                    {
                        numberOfStartingInfected = 2;
                    }
                    else if (players.Count > 10)
                    {
                        numberOfStartingInfected = 3;
                    }
                    else if (players.Count > 13)
                    {
                        numberOfStartingInfected = 4;
                    }
                    Random        getInfectedIndex = new Random();
                    List <Player> playersToInfect  = new List <Player>();
                    int           newfriendIndex   = 0;
                    for (int i = 0; i < numberOfStartingInfected; i++)
                    {
                        newfriendIndex = getInfectedIndex.Next(0, players.Count);
                        playersToInfect.Add(players[newfriendIndex]);
                        players.Remove(players[newfriendIndex]);
                    }
                    List <RoomType> genericExcluded  = new List <RoomType>(new RoomType[] { RoomType.HCZ_ARMORY, RoomType.SCP_106, RoomType.SCP_939, RoomType.TESLA_GATE, RoomType.MICROHID, RoomType.CHECKPOINT_B, RoomType.CHECKPOINT_A, RoomType.SCP_049, RoomType.ENTRANCE_CHECKPOINT, RoomType.SCP_096 });
                    List <Vector>   humanSpawnPoints = Functions.FetchSpawnpoints(ZoneType.HCZ, genericExcluded);
                    int             spawnPIndex      = 0;
                    foreach (Player player in playersToInfect)
                    {
                        player.ChangeRole(Role.SCP_049_2, true, false, true);
                        player.SetHealth(SOTNGamemode.pluginConfig.scp0492hp);
                        player.Teleport(plugin.Server.Map.GetSpawnPoints(Role.SCP_049)[0]);
                    }
                    Random randomSpawnIndex = new Random();
                    foreach (Player player in players)
                    {
                        player.ChangeRole(Role.CLASSD, true, false, true);
                        if (humanSpawnPoints.Count == spawnPIndex)
                        {
                            spawnPIndex = 0;
                        }
                        int rSI = randomSpawnIndex.Next(0, humanSpawnPoints.Count);
                        player.Teleport(humanSpawnPoints[rSI]);
                    }
                    List <RoomType> generatorExcluded = new List <RoomType>(new RoomType[] { RoomType.HCZ_ARMORY, RoomType.SCP_939, RoomType.TESLA_GATE, RoomType.MICROHID, RoomType.CHECKPOINT_B, RoomType.CHECKPOINT_A, RoomType.SCP_372, RoomType.SERVER_ROOM, RoomType.ENTRANCE_CHECKPOINT, RoomType.SCP_096 });
                    List <Vector>   tabletSpawnPoints = Functions.FetchSpawnpoints(ZoneType.HCZ, generatorExcluded);
                    Random          tabletSpawnRNG    = new Random();
                    for (int i = 0; i < 5; i++)
                    {
                        int tabletSpawnIndex = tabletSpawnRNG.Next(0, tabletSpawnPoints.Count);
                        map.SpawnItem(ItemType.WEAPON_MANAGER_TABLET, tabletSpawnPoints[tabletSpawnIndex], Vector.Zero);
                        tabletSpawnPoints.Remove(tabletSpawnPoints[tabletSpawnIndex]);
                    }
                    List <RoomType> keycardExcluded    = new List <RoomType>(new RoomType[] { RoomType.HCZ_ARMORY, RoomType.SCP_939, RoomType.MICROHID, RoomType.SCP_372, RoomType.ENTRANCE_CHECKPOINT, RoomType.SCP_096 });
                    List <Vector>   keycardSpawnPoints = Functions.FetchSpawnpoints(ZoneType.HCZ, generatorExcluded);
                    Random          keyCardSpawnRNG    = new Random();
                    for (int i = 0; i < 3; i++)
                    {
                        int keycardSpawnIndex = keyCardSpawnRNG.Next(0, keycardSpawnPoints.Count);
                        map.SpawnItem(ItemType.MTF_COMMANDER_KEYCARD, keycardSpawnPoints[keycardSpawnIndex], Vector.Zero);
                        keycardSpawnPoints.Remove(keycardSpawnPoints[keycardSpawnIndex]);
                    }
                    Functions.Lockdown(true);

                    map.Broadcast(10, "Welcome to <b>Survival of The Nerdiest!</b>\nIf you've never played this gamemode before, please press `/~", false);
                }
            }
        }
Example #34
0
 protected override void StartAbility(Entity target, object payload)
 {
     base.StartAbility(target, payload);
     Timing.RunCoroutine(AbilityRoutine(target, payload));
 }
Example #35
0
        private void processBMS(string[] files)
        {
            string dir = ofdLoad.FileName.Substring(0, ofdLoad.FileName.LastIndexOf('\\') + 1);
            string ext;
            successFile = 0;
            failedFile = 0;
            for (int i = 0; i < files.Length; i++)
            {
                map = new Beatmap();
                wavDict.Clear();
                SampleManager.sampleDict.Clear();
                pendingNote = new Note[10];
                longType = 1;
                longObj = string.Empty;
                try
                {
                    using (FileStream fs = new FileStream(files[i], FileMode.Open))
                    {
                        using (StreamReader sr = new StreamReader(fs, Encoding.Default))
                        {
                            while (!sr.EndOfStream)
                            {
                                string line = sr.ReadLine();
                                if (line.IndexOf('#') < 0)
                                    continue;
                                line = line.Substring(1);
                                //try split with :
                                if (line.IndexOf(':') > 0)
                                {
                                    string[] arr = line.Split(':');
                                    if (arr.Length == 2)
                                    {
                                        arr[0] = arr[0].Trim();
                                        arr[1] = arr[1].Trim();
                                        if (arr[0].Length == 5)
                                        {
                                            ParseDataField(arr);
                                            continue;
                                        }
                                    }
                                }
                                //try split with space
                                int spaceInx = line.IndexOf(' ');
                                if (spaceInx > 0)
                                {
                                    string[] arr = new string[2];
                                    arr[0] = line.Substring(0, spaceInx).Trim().ToUpper();
                                    arr[1] = line.Substring(spaceInx).Trim();
                                    if (arr[0].StartsWith("BPM") && arr[0].Length == 5)
                                    {
                                        string key = arr[0].Substring(3, 2);
                                        map.BpmDict.Add(key, double.Parse(arr[1]));
                                        continue;
                                    }
                                    if (arr[0].StartsWith("WAV") && arr[0].Length == 5)
                                    {
                                        string key = arr[0].Substring(3, 2);
                                        arr[1] = Beatmap.GetSampleFilename(dir,arr[1], out ext);
                                        if (arr[1] !="")
                                        {
                                            SampleManager.Add(key, arr[1]);
                                            wavDict.Add(key, arr[1]);
                                        }
                                        continue;
                                    }
                                    switch (arr[0])
                                    {
                                        case "PLAYER":
                                            if (int.Parse(arr[1]) != 1)
                                            {
                                                throw new Exception("Can not convert 2 player bms file.");
                                            }
                                            break;
                                        case "TITLE":
                                            map.Title = arr[1];
                                            break;
                                        case "ARTIST":
                                            map.Artist = arr[1];
                                            break;
                                        case "BPM":
                                            Timing t = new Timing();
                                            t.Section = 0;
                                            t.Offset = 0;
                                            t.CustomSampleSet = 2;
                                            t.bpm = double.Parse(arr[1]);
                                            t.changed = true;
                                            t.beat = 1;
                                            map.TimingList.Add(t);
                                            break;
                                        case "STAGEFILE":
                                            map.Background = arr[1];
                                            break;
                                        case "PLAYLEVEL":
                                            map.Diff = "Lv." + arr[1];
                                            break;
                                        case "RANK":
                                            //rank = 0~3  / insane~easy
                                            int rank = int.Parse(arr[1]);
                                            map.HPRate = 9 - rank * 2;
                                            map.HPRate = Math.Max(3, Math.Min(9, map.HPRate));// 3~9
                                            break;
                                        case "LNTYPE":
                                            longType = int.Parse(arr[1]);
                                            break;
                                        case "LNOBJ":
                                            longObj = arr[1];
                                            break;
                                    }
                                }
                            }
                        }
                    }

                    for (int j = 0; j < pendingNote.Length; j++)
                    {
                        if (pendingNote[j] != null)
                            throw new Exception("Something wrong with the bms");
                    }
                    if (tb_artist.Text.Trim() != "")
                        map.Artist = tb_artist.Text;
                    if (tb_title.Text.Trim() != "")
                        map.Title = tb_title.Text;
                    if (tb_version.Text.Trim() != "")
                        map.Diff = tb_version.Text;
                    if (tb_source.Text.Trim() != "")
                        map.Source = tb_source.Text;
                    map.Save(files[i],useDir,!cb_ignoreWav.Checked);
                    if (map.LastNoteTime > lastMapTime)
                        lastMapTime = map.LastNoteTime;
                    successFile++;
                    tbResult.Text += string.Format("[Done] title:{0} notes:{1}\r\n", map.Title,map.NoteList.Count);
                }
                catch (Exception ex)
                {
                    failedFile++;
                    tbResult.Text += "[Error] " + ex.Message + "\r\n";
                }
            }
        }
Example #36
0
        public IEnumerator <float> RunInSeconds(Action action, float delay)
        {
            yield return(Timing.WaitForSeconds(delay));

            action();
        }
		public void ParallelTaskWithMultipleActionsTest()
		{
			var actions = new Action[10];
			var timings = new ConcurrentBag<Timing>();

			for (int i = 0; i < actions.Length; i++)
			{
				actions[i] = () =>
				{
					var timing = new Timing();

					timing.StartTime = DateTime.Now;
					Thread.Sleep(500);
					timing.FinishTime = DateTime.Now;

					timings.Add(timing);
				};
			}

			var task = ParallelTask.StartNew(actions);
			task.Wait();

			DateTime maxStartTime = timings.Select(t => t.StartTime).Max();
			DateTime maxFinishTime = timings.Select(t => t.FinishTime).Min();

			foreach (var timing in timings)
			{
				Console.WriteLine(String.Format("{0} - {1}", timing.StartTime, timing.FinishTime));
			}

			Assert.IsTrue(maxStartTime < maxFinishTime);
		}
Example #38
0
        public string StartVote(string command, Player player)
        {
            string rMessage = "";

            if (VoteKick.cVoteRanks.Count > 0 && !VoteKick.cVoteRanks.Contains(player.GetRankName()))
            {
                return("Your rank is not allowed to initiate a vote kick.");
            }
            else if (VoteKick.isPlayerXP && (int.Parse(File.ReadAllText(FileManager.GetAppFolder() + "PlayerXP"
                                                                        + Path.DirectorySeparatorChar.ToString() + player.SteamId + ".txt").Split(':')[0]) < VoteKick.cVoteLevel))
            {
                return($"You must be at least level {VoteKick.cVoteLevel} to initiate a vote kick.");
            }

            if (isRoundStarted)
            {
                if (!isVoting)
                {
                    string[] args = VoteKick.StringToStringArray(command.Replace("votekick ", ""));

                    if (args.Length > 0)
                    {
                        string steamid  = "";
                        Player myPlayer = VoteKick.GetPlayer(args[0], out myPlayer);
                        if (myPlayer != null)
                        {
                            steamid = myPlayer.SteamId;
                        }
                        else if (ulong.TryParse(args[0], out ulong a))
                        {
                            steamid = a.ToString();
                        }

                        target = VoteKick.GetPlayer(steamid);
                        if (target != null)
                        {
                            if (player.SteamId != target.SteamId)
                            {
                                if (!VoteKick.cImmuneRanks.Contains(target.GetRankName().ToLower()))
                                {
                                    caller = player;
                                    if (!onCooldown)
                                    {
                                        b.CallRpcAddElement($"<color=#10EE00>{caller.Name}</color> has initiated a vote kick against <color=#FF0000>{target.Name}</color>. To vote, press [`] or [~] and type <color=#10EE00>.voteyes</color> or <color=#FF0000>.voteno</color>.", 10, false);
                                        rMessage = "Vote has been started.";
                                        isVoting = true;

                                        Timing.RunCoroutine(RunInSeconds(() => EndVote(), VoteKick.cTimeout));
                                    }
                                    else
                                    {
                                        rMessage = $"You cannot start a vote kick for another {vCooldown} second{(vCooldown == 1 ? "" : "s")}.";
                                    }
                                }
                                else
                                {
                                    rMessage = "You cannot vote kick this player.";
                                }
                            }
                            else
                            {
                                rMessage = "You cannot initiate a vote on yourself.";
                            }
                        }
                        else
                        {
                            rMessage = "Invalid player.";
                        }
                    }
                }
                else
                {
                    rMessage = "There is already a vote in progress.";
                }
            }
            else
            {
                rMessage = "Round must be started to initiate vote kick.";
            }
            return(rMessage);
        }
		private void UpdateScore (Timing timing)
		{
			switch (timing) {
			case Timing.Great:
				HudScreen.AddToScore (SCORE_FOR_GREAT);
				break;
			case Timing.Good:
				HudScreen.AddToScore (SCORE_FOR_GOOD);
				break;
			case Timing.SoSo:
				HudScreen.AddToScore (SCORE_FOR_SOSO);
				break;
			case Timing.None:
				break;
			default:
				throw new ArgumentException (string.Format ("Unrecognized MatchResult type: {0}", timing));
			}
		}
 public void OnEventRaised() => Timing.RunCoroutine(RotateCoroutine().CancelWith(gameObject));
Example #41
0
 public Timer(Timing clock, int seconds)
 {
     this.Clock = clock;
     this.Seconds = seconds;
 }
Example #42
0
 private void Awake()
 {
     _reactor.Setup();
     _coroutine = Timing.RunCoroutine(Update(), _segment);
 }
Example #43
0
 private void OnEnable() =>
 Timing.ResumeCoroutines(_coroutine);
Example #44
0
 private void OnDisable() =>
 Timing.PauseCoroutines(_coroutine);
Example #45
0
	private void SetCurrentTimingDeltaTime () {
		currentTiming = settings.GetTimingData (timeSinceStart);
		timeSinceStart += Time.deltaTime;
	}
Example #46
0
 private double getNoteTime(Note n, bool head = true)
 {
     Timing t = new Timing();
     t.Section = head ? n.SectionStart : n.SectionEnd;
     t.Offset = head ? n.OffsetStart : n.OffsetEnd;
     int index = TimingList.BinarySearch(t);
     if (index < 0)
         index = ~index;
     if (index > TimingList.Count)
         index = TimingList.Count;
     Timing target = TimingList[index==0?0:index - 1];
     return ((t.Section + t.Offset) - (target.Section + target.Offset)) * (60000 * 4 / target.bpm) * target.beat + target.Time;
 }
Example #47
0
 public void Initialize( Timing timing )
 {
     this.shotTiming = timing;
 }
Example #48
0
 public void DisplayTiming(Timing timing)
 {
     TapTiming = timing;
     isNewlyTapped = true;
 }
Example #49
0
 /// <summary>
 /// Build the subtree of <see cref="Timing"/> objects with <paramref name="parent"/> at the top.
 /// Used recursively.
 /// </summary>
 /// <param name="parent">Parent <see cref="Timing"/> to be evaluated.</param>
 /// <param name="timingsLookupByParent">Key: parent timing Id; Value: collection of all <see cref="Timing"/> objects under the given parent.</param>
 private void PopulateChildTimings(Timing parent, ILookup<Guid, Timing> timingsLookupByParent)
 {
     if (timingsLookupByParent.Contains(parent.Id))
     {
         foreach (var timing in timingsLookupByParent[parent.Id].OrderBy(x => x.StartMilliseconds))
         {
             parent.AddChild(timing);
             PopulateChildTimings(timing, timingsLookupByParent);
         }
     }
 }
Example #50
0
 /// <summary>
 /// Checks if the current frame is within a given number of seconds from the closest beat.
 /// </summary>
 /// <param name="precision">How many seconds from the beat count as "on beat".</param>
 /// <param name="timing">Will return the timing of the current beat (Timing.early, Timing.onBeat, or Timing.late).</param>
 public bool IsOnBeat(float precision, out Timing timing)
 {
     if (_beatFrame) {
         timing = Timing.onBeat;
         return true;
     }
     float prevDist = Mathf.Abs((float)(_beatTimer - _prevBeat.timeStamp));
     float nextDist = Mathf.Abs((float)(_beatTimer - _nextBeat.timeStamp));
     if (nextDist < prevDist) {
         timing = Timing.early;
     }
     else {
         timing = Timing.late;
     }
     if (Mathf.Min(nextDist, prevDist) <= precision) {
         return true;
     }
     return false;
 }
        void InitializeModules()
        {
            repo = new Repository();

            if (modules.Count > 0) {
                modules.Clear();
            }

            drawing = new Drawing();
            drawing.Enabled = false; // manual updating (so it only happens when XNA wants to draw)
            drawing.Subscribe(repo.Delegater);

            timing = new Timing();
            timing.Subscribe(repo.Delegater);

            cameras = new Cameras();
            cameras.Subscribe(repo.Delegater);

            modules.Add(drawing);
            modules.Add(timing);
            modules.Add(cameras);
        }
Example #52
0
 /// <summary>
 /// Checks if the current frame is within a given number of seconds from the closest beat.
 /// </summary>
 /// <param name="precision">How many seconds from the beat count as "on beat".</param>
 /// <param name="timeDifference">Returns the number of seconds to the closest beat.</param>
 /// <param name="timing">Will return the timing of the current beat (Timing.early, Timing.onBeat, or Timing.late).</param>
 public bool IsOnBeat(float precision, out float timeDifference, out Timing timing)
 {
     if (_beatFrame) {
         timeDifference = 0f;
         timing = Timing.onBeat;
         return true;
     }
     float prevDist = Mathf.Abs((float)(_beatTimer - _prevBeat.timeStamp));
     float nextDist = Mathf.Abs((float)(_beatTimer - _nextBeat.timeStamp));
     if (nextDist < prevDist) {
         timing = Timing.early;
     }
     else {
         timing = Timing.late;
     }
     timeDifference = Mathf.Min(prevDist, nextDist);
     return (timeDifference <= precision);
 }
Example #53
0
        /// <summary>
        /// Saves parameter Timing to the timings table.
        /// </summary>
        private void SaveTiming(MiniProfiler profiler, Timing t)
        {
            var timingPoco = new TimingPoco
            {
                Id = t.Id.ToString(),
                MiniProfilerId = profiler.Id.ToString(),
                ParentTimingId =  t.IsRoot ? (string)null : t.ParentTiming.Id.ToString(),
                Name = Truncate(t.Name, 200),
                Depth = t.Depth,
                StartMilliseconds = (double)t.StartMilliseconds,
                DurationMilliseconds = (double)t.DurationMilliseconds,
                DurationWithoutChildrenMilliseconds = (double)t.DurationWithoutChildrenMilliseconds,
                SqlTimingsDurationMilliseconds = (double)t.SqlTimingsDurationMilliseconds,
                IsRoot = t.IsRoot,
                HasChildren = t.HasChildren,
                IsTrivial = t.IsTrivial,
                HasSqlTimings = t.HasSqlTimings,
                HasDuplicateSqlTimings = t.HasDuplicateSqlTimings,
                ExecutedReaders = t.ExecutedReaders,
                ExecutedScalars = t.ExecutedScalars,
                ExecutedNonQueries = t.ExecutedNonQueries
            };

            Timings.Insert(timingPoco);

            if (t.HasSqlTimings)
            {
                foreach (var st in t.SqlTimings)
                {
                    SaveSqlTiming(profiler, st);
                }
            }

            if (t.HasChildren)
            {
                foreach (var child in t.Children)
                {
                    SaveTiming(profiler, child);
                }
            }
        }
Example #54
0
 public Benchmark(string name)
 {
     this.name = name;
     timing    = new Timing();
 }