Exemplo n.º 1
0
        public void CanLimitTasksPerUpdate( )
        {
            int i = 0;
            um = new UnityManager(2);
            for ( int j = 0; j < 5; j++ )
            {
                ITask task = new ActionTask(( _ ) => i++, false);
                um.EnqueueTask(task);
            }
            um.UnsafeUpdate();
            Assert.AreEqual(2, i, "Didn't just run 2.");
            um.UnsafeUpdate();
            Assert.AreEqual(4, i, "Didn't just run 2.");
            um.UnsafeUpdate();
            Assert.AreEqual(5, i, "Didn't run last one correctly.");

            i = 0;
            um = new UnityManager(1);
            for ( int j = 0; j < 5; j++ )
            {
                ITask task = new ActionTask(( _ ) => i++, false);
                um.EnqueueTask(task);
            }
            for ( int j = 0; j < 5; j++ )
            {
                um.UnsafeUpdate();
                Assert.AreEqual(j + 1, i, "Didn't just run 1.");
            }
        }
Exemplo n.º 2
0
        public void CanNapTask( )
        {
            int i = 0;
            ActionTask task = new ActionTask(( _ ) => _.IsNapping = true, false);
            task.Extend(( _ ) => i = 5);
            tm.EnqueueTask(task);
            tm.UnsafeUpdate();

            for ( int ms = 0; ms < 1000; ms += 1 )
            {
                System.Threading.Thread.Sleep(1);
                if ( task.IsNapping )
                    break;
            }

            Assert.IsTrue(task.IsNapping, "Task not napping.");
            Assert.AreEqual(0, i, "Task extension ran even though it's napping.");

            task.IsNapping = false;
            tm.UnsafeUpdate();

            for ( int ms = 0; ms < 1000; ms += 1 )
            {
                System.Threading.Thread.Sleep(1);
                if ( task.IsCompleted )
                    break;
            }

            Assert.IsTrue(task.IsCompleted, "Task never completed.");
            Assert.AreEqual(5, i, "Task thought it completed, but did not run");
        }
Exemplo n.º 3
0
 public void CancelExtensionsOnAbortSets( )
 {
     int i = 0;
     ActionTask a = new ActionTask(( task ) => i = 1, false, true);
     Assert.IsTrue(a.CancelExtensionsOnAbort);
     a = new ActionTask(( task ) => i = 1, false, false);
     Assert.IsFalse(a.CancelExtensionsOnAbort);
 }
Exemplo n.º 4
0
        public void CanRunSomething( )
        {
            int i = 0;
            ITask task = new ActionTask(( _ ) => i = 5, false);
            um.EnqueueTask(task);
            um.UnsafeUpdate();

            Assert.IsTrue(task.IsCompleted, "Task never completed.");
            Assert.AreEqual(5, i, "Task thought it completed, but did not run");
        }
Exemplo n.º 5
0
        public void CreateAndExecute()
        {
            Counter counter = new Counter();

            ActionTask<Counter> action = new ActionTask<Counter>(counter, c => { c.Increment(); });

            Assert.AreEqual(0, counter.Count);
            action.Execute();
            Assert.AreEqual(1, counter.Count);
        }
Exemplo n.º 6
0
        public static async Task ActionFunctionCalledWhenExecuted()
        {
            bool wasCalled = false;
            var task = new ActionTask(() => wasCalled = true);

            var context = Substitute.For<ITaskContext>();

            await task.ExecuteAsync(context);

            wasCalled.Should().BeTrue();
        }
Exemplo n.º 7
0
 public void CanCancelExtensionsOnAbort( )
 {
     int i = 0;
     ActionTask b = new ActionTask(( task ) =>
     {
         i = 2;
         task.Abort();
     }, false, true);
     b.Extend(( task ) => i = 4);
     (b as ITask).Start();
     Assert.AreEqual(2, i, "Task didn't correctly cancel extensions when aborted.");
 }
Exemplo n.º 8
0
 public void CanCancelExtensions( )
 {
     int i = 0;
     ActionTask a = new ActionTask(( task ) =>
     {
         i = 1;
         task.CancelExtensions();
     }, false);
     a.Extend(( task ) => i = 3);
     (a as ITask).Start();
     Assert.AreEqual(1, i, "Task didn't correctly cancel extensions.");
 }
Exemplo n.º 9
0
 public void CanContinueInTask( )
 {
     int i = 0;
     ActionTask a = new ActionTask(( task ) => i = 1, false);
     a.Extend(( task ) =>
         {
             i++;
             task.Extend(( task2 ) => i++);
         });
     (a as ITask).Start();
     Assert.AreEqual(3, i, "Looks like an extended task doesn't actually continue, when extended in the task.");
 }
Exemplo n.º 10
0
        public void CanCancelExtensions( )
        {
            ActionTask t = new ActionTask(( _ ) => System.Threading.Thread.Sleep(0), false);
            EnumeratorTask a = new EnumeratorTask(SampleTaskWithYield(t), false);
            (a as ITask).Start();
            Assert.IsTrue(a.IsNapping, "Doesn't think it's napping...");
            Assert.IsFalse(a.IsCompleted, "Thinks its done while napping.");
            Assert.AreEqual(6, i, "Ran extensions while napping or didn't run start before napping.");
            a.CancelExtensions();
            a.IsNapping = false;
            (a as ITask).Start();

            Assert.AreEqual(6, i, "Task didn't correctly cancel extensions when aborted.");
        }
Exemplo n.º 11
0
 public void DoesNotForceAwakeByDefault( )
 {
     ActionTask t = new ActionTask(( _ ) => System.Threading.Thread.Sleep(0), false);
     EnumeratorTask a = new EnumeratorTask(SampleTaskWithYield(t), false);
     bool result = (a as ITask).Start();
     Assert.IsTrue(a.IsNapping, "Doesn't think it's napping...");
     Assert.IsFalse(a.IsCompleted, "Thinks its done while napping.");
     Assert.AreEqual(6, i, "Ran extensions while napping or didn't run start before napping.");
     a.IsNapping = false;
     Assert.IsTrue(a.IsNapping, "Forced awake by default.");
     (t as ITask).Start();
     result = (a as ITask).Start();
     Assert.AreEqual(8, i, "After napping didn't continue correctly.");
     Assert.IsFalse(result, "Reported it was still napping once finished.");
     Assert.IsTrue(a.IsCompleted, "Doesn't think its done after napping.");
 }
Exemplo n.º 12
0
        public void CanNapTask( )
        {
            int i = 0;
            ActionTask task = new ActionTask(( _ ) => _.IsNapping = true, false);
            task.Extend(( _ ) => i = 5);
            um.EnqueueTask(task);
            um.UnsafeUpdate();

            Assert.IsTrue(task.IsNapping, "Task not napping.");
            Assert.AreEqual(0, i, "Task extension ran even though it's napping.");

            task.IsNapping = false;
            um.UnsafeUpdate();

            Assert.IsTrue(task.IsCompleted, "Task never completed.");
            Assert.AreEqual(5, i, "Task thought it completed, but did not run");
        }
Exemplo n.º 13
0
        public void CanRunSomething( )
        {
            int i = 0;
            ITask task = new ActionTask(( _ ) => i = 5, false);
            tm.EnqueueTask(task);
            tm.UnsafeUpdate();

            for ( int ms = 0; ms < 10000; ms += 1 )
            {
                System.Threading.Thread.Sleep(1);
                if ( task.IsCompleted )
                    break;
            }

            Assert.IsTrue(task.IsCompleted, "Task never completed.");
            Assert.AreEqual(5, i, "Task thought it completed, but did not run");
        }
Exemplo n.º 14
0
        public void CanAbort( )
        {
            int i = 0;
            ActionTask a = new ActionTask(( task ) => i = 1, false);
            a.Abort();
            Assert.IsTrue(a.Aborted, "Task doesn't think it was aborted.");

            ActionTask b = new ActionTask(( task ) =>
            {
                i = 2;
                task.Abort();
            }, false);
            b.Extend(( task ) =>
            {
                if ( !task.Aborted ) i = 3;
            });
            (b as ITask).Start();
            Assert.IsTrue(b.Aborted, "Task doesn't think it was aborted after continuation.");
            Assert.IsTrue(b.IsCompleted, "Task thinks it didn't complete after abortion.");
            Assert.AreEqual(2, i, "Task's aborted flag didn't set correctly.");
        }
Exemplo n.º 15
0
            public void Should_Create_Edges_Between_Dependencies()
            {
                // Given
                var task1 = new ActionTask("A");
                var task2 = new ActionTask("B");

                task2.AddDependency("A");

                var tasks = new List <CakeTask>
                {
                    task1, task2
                };
                var graph = CakeGraphBuilder.Build(tasks);

                // When
                var result = graph.Edges.SingleOrDefault();

                // Then
                Assert.NotNull(result);
                Assert.Equal("A", result.Start);
                Assert.Equal("B", result.End);
            }
Exemplo n.º 16
0
        [TestCategory("Scheduler_NonDeterministic_Weak")] // May time-out and be inconclusive.
        public void Scheduler_TestPausedScheduler()
        {
            using var scheduler = _root.CreateChildScheduler();

            scheduler.PauseAsync().Wait();

            var worked = new AutoResetEvent(false);

            scheduler.Schedule(ActionTask.Create(
                                   s =>
            {
                worked.Set();
                return(true);
            },
                                   0));

            WaitForNever(worked); // NB: This is non-deterministic, but should not be flaky in the happy case.

            scheduler.Continue();

            WaitForSoon(worked); // NB: This is non-deterministic.
        }
Exemplo n.º 17
0
        public IEnumerator GetFirstStartableTask_ReturnsNullWhenItsAlreadyStarted()
        {
            using (var test = StartTest())
            {
                var task = new ActionTask(test.TaskManager, () => { });

                // wait for the tasks to finish
                foreach (var frame in StartAndWaitForCompletion(task))
                {
                    yield return(frame);
                }

                var task2 = new TestActionTask(test.TaskManager, _ => { });
                var task3 = new TestActionTask(test.TaskManager, _ => { });

                task.Then(task2).Then(task3);

                var top = task3.Test_GetFirstStartableTask();

                Assert.AreSame(null, top);
            }
        }
Exemplo n.º 18
0
        private IHelperSettings GetSettings(ICakeContext context)
        {
            SingletonFactory.Context = context;
            var settings = SingletonFactory.GetHelperSettings();

            settings.TaskTargetFunc = taskName =>
            {
                var task = new ActionTask(taskName);
                return(new CakeTaskBuilder <ActionTask>(task));
            };

            settings.RunTargetFunc = targetName =>
            {
                var report = new CakeReport {
                    { targetName, TimeSpan.Zero, CakeTaskExecutionStatus.Executed }
                };

                return(report);
            };

            return(settings);
        }
            public void Should_Aggregate_Exceptions_From_Actions()
            {
                // Given
                var task    = new ActionTask("task");
                var builder = new CakeTaskBuilder <ActionTask>(task);
                var context = new CakeContextFixture().CreateContext();

                // When
                builder.Does(() => throw new NotImplementedException());
                builder.Does(() => throw new NotSupportedException());
                builder.Does(() => throw new OutOfMemoryException());
                builder.DeferOnError();
                var result = Record.Exception(() => builder.Task.Execute(context));

                // Then
                Assert.IsType <AggregateException>(result);
                var ex = result as AggregateException;

                Assert.Contains(ex.InnerExceptions, x => x.GetType() == typeof(NotImplementedException));
                Assert.Contains(ex.InnerExceptions, x => x.GetType() == typeof(NotSupportedException));
                Assert.Contains(ex.InnerExceptions, x => x.GetType() == typeof(OutOfMemoryException));
            }
Exemplo n.º 20
0
 internal void Execute(IActionResultHandler resultHandler)
 {
     if (Handler.ValidateRPS())
     {
         Handler.IncrementRequest();
         if (Handler.ThreadQueue == null || Handler.ThreadQueue.Type == ThreadQueueType.None)
         {
             if (Handler.Async)
             {
                 OnAsyncExecute(resultHandler);
             }
             else
             {
                 OnExecute(resultHandler);
             }
         }
         else
         {
             ActionTask actionTask = new ActionTask(this, resultHandler);
             var        queue      = Handler.ThreadQueue.GetQueue(this.HttpContext);
             if (Handler.ThreadQueue.Enabled(queue))
             {
                 this.HttpContext.Queue = queue;
                 queue.Enqueue(actionTask);
             }
             else
             {
                 Handler.IncrementError();
                 resultHandler.Error(new Exception($"{Handler.SourceUrl} process error,out of queue limit!"), EventArgs.LogType.Warring, 500);
             }
         }
     }
     else
     {
         Handler.IncrementError();
         resultHandler.Error(new Exception($"{Handler.SourceUrl} process error,out of max rps!"), EventArgs.LogType.Warring, 509);
     }
 }
Exemplo n.º 21
0
    // Defines tasks for turtle movement.
    private void SendTriggeredBirdHome(int curWarblerNum = -1, bool disableAtEnd = false)
    {
        if (curWarblerNum == -1)
        {
            curWarblerNum = GetTriggeredWarbler();
        }

        NPC childNPC = _warblerNPC[curWarblerNum];

        childNPC.GetComponentInChildren <NPCCollider>().transform.localScale = Vector3.zero;
        Task start = new ActionTask(() =>
        {
            childNPC.GetComponentInChildren <Animator>().SetBool(Str.Moving, true);
            childNPC.enabled = false;
            // sound?
        });
        Task prev = start;

        for (int i = 0; i < _warblerRoutes[curWarblerNum].Length; i++)
        {
            Task next = WarblerMove(curWarblerNum, childNPC.transform, _warblerRoutes[curWarblerNum].route[i]);
            prev = prev.Then(next);
        }

        Task finish = new ActionTask(() =>
        {
            if (disableAtEnd)
            {
                childNPC.gameObject.SetActive(false);
            }
            childNPC.GetComponentInChildren <Animator>().SetBool(Str.Moving, false);
            childNPC.transform.rotation = _warblerRoutes[curWarblerNum].route[_warblerRoutes[curWarblerNum].route.Length - 1].rotation;
        });

        prev.Then(finish);

        _taskManager.Do(start);
    }
Exemplo n.º 22
0
        private Task DefineSequence()
        {
            Task start = new ActionTask(() =>
            {
                Context.ResetInputs();
                Context.inPlaceForSequence = false;
            });

            Task moveToInitPos = Context.PlayerMoveToTransform(
                Services.QuestItemRepository.TargetStep1PlayerPosition, // Position target for player
                Services.QuestItemRepository.TargetItemPosition,        // direction target for player
                Services.QuestItemRepository.TargetItemPosition);       // Not totally sure.

            start.Then(moveToInitPos);

            Task phase2Start = Context.LastTask(moveToInitPos);

            Task reset1 = new ActionTask(() => { Context.inPlaceForSequence = false; });

            Task moveToMidPos = Context.PlayerMoveToTransform(
                Services.QuestItemRepository.TargetStep2PlayerPosition,
                Services.QuestItemRepository.TargetItemPosition,
                Services.QuestItemRepository.TargetItemPosition);

            phase2Start.Then(reset1).Then(moveToMidPos);

            Task phase3Start         = Context.LastTask(moveToMidPos);
            Task reset2              = new ActionTask(() => { Context.inPlaceForSequence = false; });
            Task wait4Secs           = new WaitTask(4f);
            Task forceFinalTransform = new ActionTask(() => {
                Context.ForceTransform(Services.QuestItemRepository.TargetStep4PlayerPosition.position, Services.QuestItemRepository.TargetStep4PlayerPosition.rotation);
                Services.UIManager.HideItemPickupPrompt();
            });

            phase3Start.Then(reset2).Then(wait4Secs).Then(forceFinalTransform);

            return(start);
        }
        public IEnumerator NestedProcessShouldChainCorrectly()
        {
            using (var test = StartTest())
            {
                var expected = new List <string> {
                    "BeforeProcess", "ok", "AfterProcess", "ProcessFinally", "AfterProcessFinally"
                };

                var results = new List <string>();

                var beforeProcess = new ActionTask(test.TaskManager, _ => results.Add("BeforeProcess"))
                {
                    Name = "BeforeProcess"
                };
                var processTask = new HelperProcessTask(test.TaskManager, test.ProcessManager, TestApp, @"--sleep 1000 --data ""ok""");

                var processOutputTask = new FuncTask <string, int>(test.TaskManager, (b, previous) => {
                    results.Add(previous);
                    results.Add("AfterProcess");
                    return(1234);
                })
                {
                    Name = "AfterProcess"
                };

                var innerChain = processTask.Then(processOutputTask).Finally((b, exception) => results.Add("ProcessFinally"), "ProcessFinally");

                var outerChain = beforeProcess.Then(innerChain).Finally((b, exception) => results.Add("AfterProcessFinally"), "AfterProcessFinally");

                // wait for the tasks to finish
                foreach (var frame in StartAndWaitForCompletion(innerChain, outerChain))
                {
                    yield return(frame);
                }

                results.Matches(expected);
            }
        }
        private void ScheduleExecutionCore(ScheduleCommandRequest request)
        {
            Trace.WriteLine(string.Format("Scheduling command {0} on {1}", request.Command.CommandText, request.Command.ClientName));

            var task = new ActionTask(() => ExecuteCommandCore(request.Command));

            switch (request.Trigger)
            {
            case Trigger.Single:
                task.AddTrigger(new ExactTimeTrigger(request.FirstDateTime));
                break;

            case Trigger.Daily:
                task.AddTrigger(new DailyTrigger(request.FirstDateTime.TimeOfDay));
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
            _taskManager.AddTask(task);

            Trace.WriteLine("Command will be executed at {0}\r\n" + task.NextTime);
        }
Exemplo n.º 25
0
        [TestCategory("Scheduler_NonDeterministic_Strong")] // Relies on timing.
        public void Scheduler_DisposeChildSchedulers()
        {
            IScheduler parent, child;

            using var ev = new AutoResetEvent(false);

            using (parent = _root.CreateChildScheduler())
            {
                child = parent.CreateChildScheduler();

                child.Schedule(
                    DateTimeOffset.Now.AddMilliseconds(200),
                    ActionTask.Create(
                        s =>
                {
                    ev.Set();
                    return(true);
                },
                        0));
            }

            Assert.IsTrue(!ev.WaitOne(1000));
        }
Exemplo n.º 26
0
        [TestCategory("Scheduler_NonDeterministic_Strong")] // Tests timing.
        public void Scheduler_TestAbsoluteTimer()
        {
            var ltDueTime = TimeSpan.FromSeconds(0.1);
            var eqDueTime = TimeSpan.FromSeconds(0.2);
            var gtDueTime = TimeSpan.FromSeconds(0.3);

            using var scheduler = _root.CreateChildScheduler();

            var worked = new AutoResetEvent(false);

            DateTimeOffset offset = DateTime.UtcNow + eqDueTime;

            scheduler.Schedule(offset, ActionTask.Create(
                                   s =>
            {
                worked.Set();
                return(true);
            },
                                   0));

            Assert.IsFalse(worked.WaitOne(ltDueTime)); // NB: This is non-deterministic.
            Assert.IsTrue(worked.WaitOne(gtDueTime));  // NB: This is non-deterministic.
        }
Exemplo n.º 27
0
    private static Task DefineEndSequence()
    {
        ActionTask firstSequence = new ActionTask(() =>
        {
            Services.UIManager.CutsceneFadeIn();
            inCutscene = true;
        });
        Task waitForTime1 = new WaitTask(2f);

        ActionTask secondSequence = new ActionTask(() =>
        {
            Services.UIManager.CutsceneFadeOut();
            Services.UIManager.HideAllUI();
            PlayerAnimation.Sitting(true);
            FModMusicManager.EndCutscene();
            cutsceneObjectsManager.EndNPCs();
        });

        Task waitForTime2 = new WaitTask(14f);

        ActionTask thirdSequence = new ActionTask(() =>
        {
            Services.UIManager.CutsceneFadeIn();
        });

        Task waitForTime3 = new WaitTask(4f);

        Task endGame = new ActionTask(() =>
        {
            inCutscene = false;
            FModMusicManager.EndMusicLayers();
            UnityEngine.SceneManagement.SceneManager.LoadScene(2);
        });

        firstSequence.Then(waitForTime1).Then(secondSequence).Then(waitForTime2).Then(thirdSequence).Then(waitForTime3).Then(endGame);
        return(firstSequence);
    }
Exemplo n.º 28
0
        public void Scheduler_BigStepForHumanKindSmallStepForTimerKind()
        {
            var err = default(Exception);

            var h = new UnhandledExceptionEventHandler((o, e) =>
            {
                err = (Exception)e.ExceptionObject;
            });

            try
            {
                AppDomain.CurrentDomain.UnhandledException += h;

                using var ph = PhysicalScheduler.Create();
                using var lg = new LogicalScheduler(ph);

                // The BCL has a limit on 0xfffffffe milliseconds, which is some 49 days (see Worker.NormalizeForTimer).
                // If not handled correctly in Worker.cs, those attempts at scheduling would cause the worker to die.
                lg.Schedule(TimeSpan.FromDays(50), ActionTask.Create(_ => true, 1));
                lg.Schedule(DateTimeOffset.Now.AddDays(50), ActionTask.Create(_ => true, 1));

                // Ensure disposal doesn't happen before the worker thread had a chance to evaluate timer expirations,
                // which is what would cause the test process to die on an invalid call to Timer.Change.
                var e = new ManualResetEvent(false);
                lg.Schedule(ActionTask.Create(_ => { e.Set(); return(true); }, 1));
                e.WaitOne();
            }
            finally
            {
                AppDomain.CurrentDomain.UnhandledException -= h;
            }

            if (err != null)
            {
                ExceptionDispatchInfo.Capture(err).Throw();
            }
        }
Exemplo n.º 29
0
    // Use this for initialization
    protected override void Start()
    {
        base.Start();

        scale        = 0;
        totalHp      = hp;
        currentPhase = Phase.Default;
        gameObject.transform.localScale = new Vector3(scale, scale, scale);

        taskManager = new TaskManager();

        scaleUpTask          = new ProgressionTask(ScaleUp, 0);
        enterAppearPhaseTask = new ActionTask(EnterAppearPhase);
        enterSpawnPhaseTask  = new ActionTask(EnterSpawnPhase);
        enterFirePhaseTask   = new ActionTask(EnterFirePhase);
        enterChasePhaseTask  = new ActionTask(EnterChasePhase);
        enterDeadPhaseTask   = new ActionTask(Die);
        spawnTask            = new ProgressionTask(Spawn, 0);
        idleTask             = new WaitTask(3f);
        moveTask             = new ProgressionTask(Move, 0);
        attackTask           = new ProgressionTask(Attack, 0);

        Services.EnemyManager.AddBoss(gameObject);
    }
Exemplo n.º 30
0
        public void CanNapTask( )
        {
            int        i    = 0;
            ActionTask task = new ActionTask((_) => _.IsNapping = true, false);

            task.Extend((_) => i = 5);
            tm.EnqueueTask(task);
            tm.UnsafeUpdate();

            for (int ms = 0; ms < 1000; ms += 1)
            {
                System.Threading.Thread.Sleep(1);
                if (task.IsNapping)
                {
                    break;
                }
            }

            Assert.IsTrue(task.IsNapping, "Task not napping.");
            Assert.AreEqual(0, i, "Task extension ran even though it's napping.");

            task.IsNapping = false;
            tm.UnsafeUpdate();

            for (int ms = 0; ms < 1000; ms += 1)
            {
                System.Threading.Thread.Sleep(1);
                if (task.IsCompleted)
                {
                    break;
                }
            }

            Assert.IsTrue(task.IsCompleted, "Task never completed.");
            Assert.AreEqual(5, i, "Task thought it completed, but did not run");
        }
Exemplo n.º 31
0
        public void UnityFlagFunctional( )
        {
            int        i = 0;
            ActionTask a = new ActionTask((task) =>
            {
                if (task.OnUnityThread)
                {
                    i = 1;
                }
            }, true);

            (a as ITask).Start();
            Assert.AreEqual(1, i, "OnUnityThread reported false, when should be true.");

            a = new ActionTask((task) =>
            {
                if (task.OnUnityThread)
                {
                    i = 2;
                }
            }, false);
            (a as ITask).Start();
            Assert.AreEqual(1, i, "OnUnityThread reported true, when should be false.");
        }
Exemplo n.º 32
0
        public ActionTask Put(ActionTask item)
        {
            try
            {
                //var identity = User.Identity as ClaimsIdentity;
                //int compid = 0, userid = 0;
                //foreach (Claim claim in identity.Claims)
                //{
                //    if (claim.Type == "compid")
                //    {
                //        compid = int.Parse(claim.Value);
                //    }
                //    if (claim.Type == "userid")
                //    {
                //        userid = int.Parse(claim.Value);
                //    }
                //}
                //logger.Info("User ID : {0} , Company Id : {1}", compid, userid);
                //if (compid > 0) {
                var edit = context.ActionTaskDb.Where(x => x.ActionTaskid == item.ActionTaskid).SingleOrDefault();

                edit.Description = item.Description;
                edit.Status      = item.Status;
                edit.UpdatedDate = indianTime;
                context.ActionTaskDb.Attach(edit);
                context.Entry(edit).State = EntityState.Modified;
                context.SaveChanges();
                return(item);
                //}
                //return null;
            }
            catch
            {
                return(null);
            }
        }
Exemplo n.º 33
0
 public void CanExtendTwice( )
 {
     int i = 0;
     ActionTask a = new ActionTask(( task ) => i = 1, false);
     a.Extend(( task ) => i++);
     a.Extend(( task ) => i++);
     (a as ITask).Start();
     Assert.AreEqual(3, i, "Looks like a continued task doesn't actually continue multiple times.");
 }
 private void StopActions()
 {
     ActionTask.StopTestInvokeAction();
 }
Exemplo n.º 35
0
 /// <summary>
 /// Do something! What you do is determined by the argument.
 /// Treats a string as a single character. Wow!
 /// Recognizes a regular expression if it is preceded by ( or , or =.
 /// </summary>
 /// <param name="d">
 /// 1   Output A. Copy B to A. Get the next B.
 /// 2   Copy B to A. Get the next B. (Delete A).
 /// 3   Get the next B. (Delete B).
 /// </param>
 private static void Action(ActionTask d)
 {
     if (d.Equals(ActionTask.OutputA))
     {
         Put(_theA);
     }
     if (d.Equals(ActionTask.OutputA) || d.Equals(ActionTask.CopyBtoA))
     {
         _theA = _theB;
         if (_theA.Equals('\'') || _theA.Equals('"'))
         {
             for (;;)
             {
                 Put(_theA);
                 _theA = Get();
                 if (_theA == _theB)
                 {
                     break;
                 }
                 if (_theA <= '\n')
                 {
                     throw new Exception(string.Format("Error: JSMIN unterminated string literal: {0}\n", _theA));
                 }
                 if (_theA.Equals('\\'))
                 {
                     Put(_theA);
                     _theA = Get();
                 }
             }
         }
     }
     //if (d.Equals(ActionTask.OutputA) || d.Equals(ActionTask.CopyBtoA) || d.Equals(ActionTask.GetNextB))
     //{
     _theB = Next();
     if (_theB.Equals('/') && (_theA.Equals('(') || _theA.Equals(',') || _theA.Equals('=') ||
                               _theA.Equals('[') || _theA.Equals('!') || _theA.Equals(':') ||
                               _theA.Equals('&') || _theA.Equals('|') || _theA.Equals('?')))
     {
         Put(_theA);
         Put(_theB);
         for (;;)
         {
             _theA = Get();
             if (_theA.Equals('/'))
             {
                 break;
             }
             else if (_theA.Equals('\\'))
             {
                 Put(_theA);
                 _theA = Get();
             }
             else if (_theA <= '\n')
             {
                 throw new Exception(string.Format("Error: JSMIN unterminated Regular Expression literal : {0}.\n", _theA));
             }
             Put(_theA);
         }
         _theB = Next();
     }
     //}
 }
Exemplo n.º 36
0
 public void DoesNotDespawnWorkingThread( )
 {
     ThreadManager tm = new ThreadManager(0, 1, TimeSpan.MinValue, TimeSpan.MaxValue, 1, TimeSpan.FromMilliseconds(10));
     tm.SpawnThread();
     ActionTask task = new ActionTask(( _ ) => System.Threading.Thread.Sleep(500), false);
     tm.EnqueueTask(task);
     tm.UnsafeUpdate();
     System.Threading.Thread.Sleep(20);
     tm.UnsafeUpdate();
     Assert.AreEqual(1, tm.NumThreads, "Despawned a thread while working.");
 }
Exemplo n.º 37
0
 public void DedicatedTasksContinueAfterNapping( )
 {
     int i = 0;
     ActionTask task = new ActionTask(( _ ) => _.IsNapping = true, false);
     task.Extend(( _ ) => i = 5);
     tm.SpawnDedicatedThread(task);
     for ( int ms = 0; ms < 1000; ms += 1 )
     {
         System.Threading.Thread.Sleep(1);
         if ( task.IsNapping )
             break;
     }
     Assert.IsTrue(task.IsNapping, "Task didn't nap.");
     Assert.AreEqual(0, i, "Task ran while napping.");
     task.IsNapping = false;
     for ( int ms = 0; ms < 1000; ms += 1 )
     {
         System.Threading.Thread.Sleep(1);
         if ( task.IsCompleted )
             break;
     }
     Assert.AreEqual(5, i, "Task didn't run after napping.");
 }
Exemplo n.º 38
0
        protected override BehaviorTask createTask()
        {
            ActionTask pTask = new ActionTask();

            return(pTask);
        }
Exemplo n.º 39
0
 public void NappingTestsDontCountTowardsLimit( )
 {
     int i = 0;
     um = new UnityManager(1);
     ActionTask task = new ActionTask(( _ ) => _.IsNapping = true, false);
     task.Extend(( _ ) => i = 100);
     um.EnqueueTask(task);
     for ( int j = 0; j < 5; j++ )
     {
         ITask t = new ActionTask(( _ ) => i++, false);
         um.EnqueueTask(t);
     }
     um.UnsafeUpdate();
     Assert.IsTrue(task.IsNapping, "Task didn't start napping.");
     for ( int j = 0; j < 5; j++ )
     {
         um.UnsafeUpdate();
         Assert.AreEqual(j + 1, i, "Didn't just run 1.");
     }
     task.IsNapping = false;
     um.UnsafeUpdate();
     Assert.AreEqual(100, i, "Didn't run awakened task.");
 }
Exemplo n.º 40
0
 public void IsCompletedFunctional( )
 {
     int i = 0;
     ActionTask a = new ActionTask(( task ) => i = 1, false);
     Assert.IsFalse(a.IsCompleted, "Task thinks its completed before it ran.");
     (a as ITask).Start();
     Assert.IsTrue(a.IsCompleted, "Looks like the task doesn't register when it's completed.");
 }
Exemplo n.º 41
0
 public void NappingFunctions( )
 {
     int i = 0;
     ActionTask a = new ActionTask(( task ) => task.IsNapping = true, false);
     a.Extend(( task ) => i++);
     a.Extend(( task ) => i++);
     bool result = (a as ITask).Start();
     Assert.IsTrue(a.IsNapping, "Doesn't think it's napping...");
     Assert.IsFalse(a.IsCompleted, "Thinks its done while napping.");
     Assert.AreEqual(0, i, "Ran extensions while napping.");
     Assert.IsTrue(result, "Didn't report it was napping.");
     a.IsNapping = false;
     result = (a as ITask).Start();
     Assert.AreEqual(2, i, "After napping didn't continue correctly.");
     Assert.IsTrue(a.IsCompleted, "Doesn't think its done after napping.");
     Assert.IsFalse(result, "Reported it was still napping.");
 }
Exemplo n.º 42
0
 public void DoesTask( )
 {
     int i = 0;
     ActionTask a = new ActionTask(( task ) => i = 1, false);
     bool result = (a as ITask).Start();
     Assert.AreEqual(1, i, "Looks like the task didn't execute when instantiated with an action.");
     Assert.IsFalse(result, "Task reported it was sleeping after completing.");
 }
Exemplo n.º 43
0
 public void ExtendsTask( )
 {
     int i = 0;
     ActionTask a = new ActionTask(( task ) => i = 1, false);
     a.Extend(( task ) => i++);
     (a as ITask).Start();
     Assert.AreEqual(2, i, "Looks like a continued task doesn't actually continue.");
 }
Exemplo n.º 44
0
        public void Scheduler_PerformanceCounters_NoTime()
        {
            using var scheduler = _root.CreateChildScheduler();

            const int N = 10;

            for (var i = 0; i < N; i++)
            {
                var worked = new AutoResetEvent(false);

                //
                // Schedule work without due time, and wait for its completion.
                //

                scheduler.Schedule(ActionTask.Create(
                                       s =>
                {
                    worked.Set();
                    return(true);
                },
                                       0));

                //
                // Resume the scheduler if we were previously paused. This accummulates PausedTime to assert on.
                //

                if (i > 0)
                {
                    scheduler.Continue();
                }

                //
                // Wait for the work to be completed.
                //

                worked.WaitOne();

                //
                // Pause the scheduler to wait for all the worker threads to stop processing work.
                //
                // NB: This is critical for the asserts, because accounting happens after the user work completes,
                //     and our user code signals an event, so we end up with a race between threads. By pausing, we
                //     ensure the tasks have drained completely.
                //

                scheduler.PauseAsync().Wait();
            }

            //
            // Check the counters of the child scheduler.
            //

            var childCounters = ((ISchedulerPerformanceCountersProvider)scheduler).QueryPerformanceCounters(includeChildren: false);

            Assert.AreEqual(N, childCounters.TaskExecutionCount);
            Assert.AreEqual(0, childCounters.TimerTickCount);

            Assert.IsTrue(childCounters.Uptime > TimeSpan.Zero);
            Assert.IsTrue(childCounters.PausedTime > TimeSpan.Zero);

            //
            // Check the counters of the root scheduler.
            //

            var rootCounters = _root.QueryPerformanceCounters(includeChildren: true);

            Assert.AreEqual(N, rootCounters.TaskExecutionCount);
            Assert.AreEqual(0, rootCounters.TimerTickCount);

            //
            // Assert struct math on SchedulerPerformanceCounters.
            //

            AssertStructMath(childCounters);
            AssertStructMath(rootCounters);
        }
Exemplo n.º 45
0
        //The action list gui
        public void ShowListGUI()
        {
            if (ownerSystem == null){
                Debug.LogError("Owner System = null !");
                return;
            }

            EditorUtils.TaskSelectionButton<ActionTask>(ownerSystem, (a)=>{ AddAction(a); });

            ValidateList();

            if (actions.Count == 0){
                EditorGUILayout.HelpBox("No Actions", MessageType.None);
                return;
            }

            if (actions.Count == 1)
                return;

            //show the actions
            EditorUtils.ReorderableList(actions, delegate(int i){

                var action = actions[i];
                GUI.color = new Color(1, 1, 1, 0.25f);
                EditorGUILayout.BeginHorizontal("box");

                GUI.color = action.isActive? new Color(1,1,1,0.8f) : new Color(1,1,1,0.25f);
                action.isActive = EditorGUILayout.Toggle(action.isActive, GUILayout.Width(18));

                GUI.backgroundColor = action == currentViewAction? Color.grey : Color.white;
                if (GUILayout.Button(EditorUtils.viewIcon, GUILayout.Width(25), GUILayout.Height(18)))
                    currentViewAction = action == currentViewAction? null : action;
                EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link);
                GUI.backgroundColor = Color.white;

                GUILayout.Label( (action.isPaused? "<b>||</b> " : action.isRunning? "► " : "") + action.summaryInfo, GUILayout.MinWidth(0), GUILayout.ExpandWidth(true));

                if (!Application.isPlaying && GUILayout.Button("X", GUILayout.Width(20))){
                    Undo.RecordObject(ownerSystem.baseObject, "List Remove Task");
                    actions.RemoveAt(i);
                }

                EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link);
                EditorGUILayout.EndHorizontal();
                GUI.color = Color.white;
            });

            executionMode = (ActionsExecutionMode)EditorGUILayout.EnumPopup(executionMode);
        }
Exemplo n.º 46
0
        private IEnumerable <CakeTask> defineTasks()
        {
            var circularTaskA = new ActionTask("circ-a");

            new CakeTaskBuilder <ActionTask>(circularTaskA)
            .IsDependentOn("circ-b");
            yield return(circularTaskA);

            var circularTaskB = new ActionTask("circ-b");

            new CakeTaskBuilder <ActionTask>(circularTaskB)
            .IsDependentOn("circ-c");
            yield return(circularTaskB);

            var circularTaskC = new ActionTask("circ-c");

            new CakeTaskBuilder <ActionTask>(circularTaskC)
            .IsDependentOn("circ-a");
            yield return(circularTaskC);

            var taskA = new ActionTask("a");

            new CakeTaskBuilder <ActionTask>(taskA)
            .Does(() =>
            {
                Thread.Sleep(1000);
                _sb.Append("a");
            });
            yield return(taskA);

            var taskB = new ActionTask("b");

            new CakeTaskBuilder <ActionTask>(taskB)
            .IsDependentOn("a")
            .Does(() => _sb.Append("b"));
            yield return(taskB);

            var taskC = new ActionTask("c");

            new CakeTaskBuilder <ActionTask>(taskC)
            .IsDependentOn("a")
            .Does(() => _sb.Append("c"));
            yield return(taskC);

            var taskD = new ActionTask("d");

            new CakeTaskBuilder <ActionTask>(taskD)
            .Does(() => _sb.Append("d"));
            yield return(taskD);

            var taskE = new ActionTask("e");

            new CakeTaskBuilder <ActionTask>(taskE)
            .IsDependentOn("d")
            .Does(() => _sb.Append("e"));
            yield return(taskE);

            var taskF = new ActionTask("f");

            new CakeTaskBuilder <ActionTask>(taskF)
            .IsDependentOn("e")
            .Does(() =>
            {
                _sb.Append("f");
                return(Task.CompletedTask);
            });
            yield return(taskF);

            var taskG = new ActionTask("g");

            new CakeTaskBuilder <ActionTask>(taskG)
            .IsDependentOn("a")
            .IsDependentOn("b")
            .IsDependentOn("c")
            .IsDependentOn("e")
            .IsDependentOn("f")
            .Does(() => _sb.Append("g"));
            yield return(taskG);

            var taskh1 = new ActionTask("h1");

            new CakeTaskBuilder <ActionTask>(taskh1)
            .Does(() => _sb.Append("h1"));
            yield return(taskh1);

            var taskh2 = new ActionTask("h2");

            new CakeTaskBuilder <ActionTask>(taskh2)
            .Does(() => _sb.Append("h2"));
            yield return(taskh2);

            var taskh = new ActionTask("h");

            new CakeTaskBuilder <ActionTask>(taskh)
            .IsDependentOn("h1")
            .IsDependeeOf("h2")
            .Does(() => _sb.Append("h"));
            yield return(taskh);

            var broken = new ActionTask("broken");

            new CakeTaskBuilder <ActionTask>(broken)
            .Does(() => { throw new Exception(); });
            yield return(broken);

            var error = new ActionTask("error");

            new CakeTaskBuilder <ActionTask>(error)
            .IsDependentOn("b")
            .IsDependentOn("broken")
            .Does(() => {});
            yield return(error);
        }
Exemplo n.º 47
0
 public async Task ExceptionPropagatesOutIfNoFinally()
 {
     var task = new ActionTask(Token, _ => { throw new InvalidOperationException(); })
                .Catch(_ => { });
     await task.StartAsAsync();
 }
Exemplo n.º 48
0
    /*
     * 1. Move player to position. Move camera behind player. ~2s
     * 2. Move Camera to cutsceneCamera, have camera slowly focus on item. Make player walk to tree. ~2s
     * 3. Trigger Quest item repository to take item, trigger sounds and particle effects, smoothly animate it into position and have large particle effect. 2s
     * 4. Fade to white? black? 2s
     * 5. stay there for a sec as music fades. Place player into new position. 3s
     * 6. Fade back in and have player turned around as environment changes are triggered. 2s
     * 7. 1 sec later have player get up and return to normal controls. 1s // turns around!
     */
    private static Task DefineMidSequence()
    {
        // 1. Move player to position. Move camera behind player. ~2s
        Task enterSequence = new DelegateTask(() =>
        {
            inCutscene = true;
        }, () =>
        {
            Services.UIManager.HideItemPickupPrompt();
            return(Services.PlayerMovement.inPlaceForSequence);
        });

        Task waitForTime1 = new WaitTask(1f);

        // 2. Move Camera to cutsceneCamera, have camera slowly focus on item. Make player walk to tree. ~2s
        Task secondSequence = new DelegateTask(() =>
        {
            // Trigger particles?
            // Trigger music?
        }, () =>
        {
            Services.UIManager.HideItemPickupPrompt();
            return(Services.PlayerMovement.inPlaceForSequence);
        });

        Task dropItem = new ActionTask(() => { Services.PlayerItemHolder.DropItem(); });

        Task waitForTime2 = new WaitTask(.66f);

        // 3.Trigger Quest item repository to take item, trigger sounds and particle effects, smoothly animate it into position and have large particle effect. 2s
        ActionTask thirdSequence = new ActionTask(() =>
        {
            Services.QuestItemRepository.StartSequence();

            FModMusicManager.ReturnedItem();
            // Quest item Repository takes Item.
            // trigger other stuff.
        });

        // Add in phase here to show plants growing?????????????????????????????????????

        Task waitForTime3 = new WaitTask(1.5f);

        // 4. Fade to white? black? 2s
        ActionTask fourthSequence = new ActionTask(() =>
        {
            // Fade out?
            Services.UIManager.CutsceneFadeIn();
        });

        // 5. stay there for a sec as music fades. Place player into new position. 3s
        Task waitForTime4 = new WaitTask(4.5f);

        // 6. Fade back in and have player turned around as environment changes are triggered. 2s
        ActionTask fifthSequence = new ActionTask(() =>
        {
            Services.PostProcessingManager.AdvanceStage();
            PlayerAnimation.Sitting(true);
            // Fade in?
            Services.UIManager.CutsceneFadeOut();
            Services.UIManager.HideDialogueEnterPrompt();
        });

        Task waitForTime5 = new WaitTask(1f);

        ActionTask triggerPlantAnims = new ActionTask(() => { cutsceneObjectsManager.Transition(); });

        Task waitForTime6 = new WaitTask(10.5f);
        // 7. 1 sec later have player get up and return to normal controls. 1s
        ActionTask sixthSequence = new ActionTask(() =>
        {
            PlayerAnimation.Sitting(false);
            NPCInteractionManager.FindClosestNPC();
            Services.GameManager.EnterDialogue();
            inCutscene = false;
        });

        enterSequence.Then(waitForTime1).Then(secondSequence).Then(dropItem).Then(waitForTime2).Then(thirdSequence).Then(waitForTime3).Then(fourthSequence).Then(waitForTime4).Then(fifthSequence).Then(waitForTime5).Then(triggerPlantAnims).Then(waitForTime6).Then(sixthSequence);
        return(enterSequence);
    }
Exemplo n.º 49
0
 public async Task StartAwaitSafelyAwaits()
 {
     var task = new ActionTask(Token, _ => { throw new InvalidOperationException(); })
                .Catch(_ => { });
     await task.StartAwait(_ => { });
 }
Exemplo n.º 50
0
        public void UnityFlagFunctional( )
        {
            int i = 0;
            ActionTask a = new ActionTask(( task ) =>
            {
                if ( task.OnUnityThread ) i = 1;
            }, true);
            (a as ITask).Start();
            Assert.AreEqual(1, i, "OnUnityThread reported false, when should be true.");

            a = new ActionTask(( task ) =>
            {
                if ( task.OnUnityThread ) i = 2;
            }, false);
            (a as ITask).Start();
            Assert.AreEqual(1, i, "OnUnityThread reported true, when should be false.");
        }
Exemplo n.º 51
0
        public IActionResult Execute()
        {
            var operationResult = ActionResult ?? ActionTask.GetAwaiter().GetResult();

            return(ExecutePrivate(operationResult));
        }
Exemplo n.º 52
0
    void OnGUI()
    {
        DemoGUIHelpers.setupGUIButtons();


        if (_springTween == null)
        {
            _duration = DemoGUIHelpers.durationSlider(_duration);


            if (GUILayout.Button("Custom Property Tween (wackyDoodleWidth)"))
            {
                PropertyTweens.floatPropertyTo(this, "wackyDoodleWidth", 6f, _duration)
                .setFrom(1f)
                .setLoops(LoopType.PingPong)
                .start();
            }


            if (GUILayout.Button("Position via Property Tween"))
            {
                PropertyTweens.vector3PropertyTo(cube, "position", new Vector3(5f, 5f, 5f), _duration)
                .setLoops(LoopType.PingPong)
                .start();
            }



            if (GUILayout.Button("Tween Party (color, position, scale and rotation)"))
            {
                var party = new TweenParty(_duration);
                party.addTween(cube.GetComponent <Renderer>().material.ZKcolorTo(Color.black))
                .addTween(cube.ZKpositionTo(new Vector3(7f, 4f)))
                .addTween(cube.ZKlocalScaleTo(new Vector3(1f, 4f)))
                .addTween(cube.ZKrotationTo(Quaternion.AngleAxis(180f, Vector3.one)))
                .setLoops(LoopType.PingPong)
                .start();
            }


            if (GUILayout.Button("Tween Chain (same props as the party)"))
            {
                var chain = new TweenChain();
                chain.appendTween(cube.GetComponent <Renderer>().material.ZKcolorTo(Color.black, _duration).setLoops(LoopType.PingPong))
                .appendTween(cube.ZKpositionTo(new Vector3(7f, 4f), _duration).setLoops(LoopType.PingPong))
                .appendTween(cube.ZKlocalScaleTo(new Vector3(1f, 4f), _duration).setLoops(LoopType.PingPong))
                .appendTween(cube.ZKrotationTo(Quaternion.AngleAxis(180f, Vector3.one), _duration).setLoops(LoopType.PingPong))
                .start();
            }


            if (GUILayout.Button("Chaining Tweens Directly (same props as the party)"))
            {
                cube.GetComponent <Renderer>().material.ZKcolorTo(Color.black, _duration).setLoops(LoopType.PingPong)
                .setNextTween
                (
                    cube.ZKpositionTo(new Vector3(7f, 4f), _duration).setLoops(LoopType.PingPong).setNextTween
                    (
                        cube.ZKlocalScaleTo(new Vector3(1f, 4f), _duration).setLoops(LoopType.PingPong).setNextTween
                        (
                            cube.ZKrotationTo(Quaternion.AngleAxis(180f, Vector3.one), _duration).setLoops(LoopType.PingPong)
                        )
                    )
                )
                .start();
            }


            GUILayout.Space(10);
            if (GUILayout.Button("Start Spring Position"))
            {
                _springTween = new TransformSpringTween(cube, TransformTargetType.Position, cube.position);
            }


            if (GUILayout.Button("Start Spring Position (overdamped)"))
            {
                _springTween = new TransformSpringTween(cube, TransformTargetType.Position, cube.position);
                _springTween.dampingRatio     = 1.5f;
                _springTween.angularFrequency = 20f;
            }


            if (GUILayout.Button("Start Spring Scale"))
            {
                _springTween = new TransformSpringTween(cube, TransformTargetType.LocalScale, cube.localScale);
            }
            GUILayout.Space(10);


            if (GUILayout.Button("Run Action Every 1s After 2s Delay"))
            {
                ActionTask.every(2f, 1f, this, task =>
                {
                    // by using the context we get away with not allocating when passing this Action around!
                    (task.context as ZestKitOtherGoodies).methodCalledForDemonstrationPurposes();
                });
            }


            if (GUILayout.Button("ActionTask Interoperability"))
            {
                Debug.Log("The Story: An ActionTask with a 2s delay will be created with a continueWith ActionTask appended to it that will tick every 0.3s for 2s. The original ActionTask will have a waitFor called that is an ActionTask with a 1s delay. Follow?");
                Debug.Log("--- current time: " + Time.time);

                ActionTask.afterDelay(2f, this, task =>
                {
                    Debug.Log("--- root task ticked: " + Time.time);
                }).continueWith
                (
                    ActionTask.create(this, task =>
                {
                    Debug.Log("+++ continueWith task elapsed time: " + task.elapsedTime);
                    if (task.elapsedTime > 2f)
                    {
                        task.stop();
                    }
                })
                    .setDelay(1f)
                    .setRepeats(0.3f)
                ).waitFor
                (
                    ActionTask.afterDelay(1f, this, task =>
                {
                    Debug.Log("--- waitFor ticked: " + Time.time);
                })
                );
            }

            DemoGUIHelpers.easeTypesGUI();
        }
        else
        {
            GUILayout.Label("While the spring tween is active the cube will spring to\n" +
                            "whichever location you click or scale x/y to that location\n" +
                            "if you chose a scale spring. The sliders below let you tweak\n" +
                            "the spring contants.\n\n" +
                            "For the scale tween, try clicking places on a horizontal or vertical\n" +
                            "axis to get a feel for how it works.");

            springSliders();

            var prefix        = _springTween.targetType == TransformTargetType.Position ? "Spring position to:" : "Spring scale to:";
            var mousePosWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            var labelText     = string.Format("{0}\nx: {1:F1}\ny: {2:F1}", prefix, mousePosWorld.x, mousePosWorld.y);
            GUI.Label(new Rect(Input.mousePosition.x, Screen.height - Input.mousePosition.y - 50f, 130f, 50f), labelText);


            if (GUILayout.Button("Stop Spring"))
            {
                _springTween.stop();
                _springTween    = null;
                cube.position   = new Vector3(-1f, -2f);
                cube.localScale = Vector3.one;
            }
        }
    }
Exemplo n.º 53
0
        public void LetsOthersUseNappingThreadsCorrectly( )
        {
            int i = 0;
            object _lock = new object();
            ThreadManager tman = new ThreadManager(1, 1);
            // Using this to test interaction very specifically.
            tman.WaitForThreadSpawns();
            ActionTask task = new ActionTask(( _ ) =>
            {
                _.IsNapping = true;
            }, false);
            task.Extend(( _ ) => i = 100);
            tman.EnqueueTask(task);
            for ( int j = 0; j < 10; j++ )
                tman.EnqueueTask(new ActionTask(( _ ) =>
                {
                    lock ( _lock )
                        i++;
                }, false));

            tman.UnsafeUpdate();
            for ( int j = 0; j < 100; j++ )
                if ( task.IsNapping )
                    break;
                else
                    System.Threading.Thread.Sleep(1);

            for ( int j = 0; j < 10; j++ )
            {
                tman.UnsafeUpdate();
                System.Threading.Thread.Sleep(1);
                lock ( _lock ) Assert.AreEqual(j + 1, i, "Ran some number other than 1 of the Tasks at once on update #" + j);
            }

            task.IsNapping = false;
            tman.UnsafeUpdate();
            System.Threading.Thread.Sleep(1);
            Assert.AreEqual(100, i, "Did not run awakened Task.");

            tman.Dispose();
        }
Exemplo n.º 54
0
        public bool Wakeup(Action action)
        {
            ActionTask task = new ActionTask(action);

            return(Wakeup(task));
        }
Exemplo n.º 55
0
 public void ForceAwakeningFunctions( )
 {
     ActionTask t = new ActionTask(( _ ) => System.Threading.Thread.Sleep(0), false);
     EnumeratorTask a = new EnumeratorTask(SampleTaskWithYield(t), false);
     (a as ITask).Start();
     Assert.IsTrue(a.IsNapping, "Doesn't think it's napping...");
     Assert.IsFalse(a.IsCompleted, "Thinks its done while napping.");
     Assert.AreEqual(6, i, "Ran extensions while napping or didn't run start before napping.");
     a.ForceAwaken();
     (a as ITask).Start();
     Assert.AreEqual(8, i, "After napping didn't continue correctly.");
     Assert.IsTrue(a.IsCompleted, "Doesn't think its done after napping.");
 }
Exemplo n.º 56
0
            private void DoSchedule(ActionTask task)
            {
                _context.Scheduler.Schedule(task);

                _context.TraceSource.StartWith_Scheduling(_context.InstanceId, _valuesIndex, Params._values.Length);
            }
Exemplo n.º 57
0
        void AddAction(ActionTask action)
        {
            if (action is ActionList){
                Debug.LogWarning("Adding an ActionList within an ActionList is not allowed for clarity");
                return;
            }

            #if UNITY_EDITOR
            if (!Application.isPlaying){
                Undo.RecordObject(ownerSystem.baseObject, "List Add Task");
                currentViewAction = action;
            }
            #endif

            actions.Add(action);
            action.SetOwnerSystem(this.ownerSystem);
        }
Exemplo n.º 58
0
        public void ShowNestedActionsGUI()
        {
            if (actions.Count == 1)
                currentViewAction = actions[0];

            if (currentViewAction != null){
                EditorUtils.Separator();
                Task.ShowTaskInspectorGUI(currentViewAction, (a)=>
                {
                    if (a == null){
                        var i = actions.IndexOf(currentViewAction);
                        actions.RemoveAt(i);
                    }
                    currentViewAction = (ActionTask)a;
                });
            }
        }
Exemplo n.º 59
0
        protected override BehaviorTask createTask()
        {
            ActionTask pTask = new ActionTask();

            return pTask;
        }
Exemplo n.º 60
0
 public void DoLoadPreset()
 {
     #if !UNITY_WEBPLAYER
     var path = EditorUtility.OpenFilePanel("Load Preset", "Assets", "actionList");
     if (!string.IsNullOrEmpty(path)){
         var json = System.IO.File.ReadAllText(path);
         var list = JSON.Deserialize<ActionList>(json);
         this.actions = list.actions;
         this.executionMode = list.executionMode;
         this.currentViewAction = null;
         foreach(var a in actions){
             a.SetOwnerSystem(this.ownerSystem);
         }
     }
     #else
     Debug.LogWarning("Preset loading is not possible with WebPlayer as active platform");
     #endif
 }