Exemplo n.º 1
0
        public void TestCreatingActorWithItem_FromBlueprint()
        {
            string yaml = @"- Name: Servitor
  MandatoryAdjectives:
    - Rusty
    - Strong
    - Tough
  Stats:
    Fight: 30
    Loyalty: 20
  MandatoryItems:
    - Name: Chronometer
      Stats:
        Value: 10";

            var room = InARoom(out IWorld w);

            w.AllStats.GetOrAdd("Loyalty");

            var actorFactory = new ActorFactory {
                Blueprints = Compiler.Instance.Deserializer.Deserialize <List <ActorBlueprint> >(yaml)
            };
            var servitor = actorFactory.Create(w, room, null, actorFactory.Blueprints.Single(), null);

            Assert.AreEqual("Servitor", servitor.Name);
            Assert.Contains("Rusty", servitor.Adjectives.Select(a => a.Name).ToArray());
            Assert.Contains("Strong", servitor.Adjectives.Select(a => a.Name).ToArray());
            Assert.Contains("Tough", servitor.Adjectives.Select(a => a.Name).ToArray());

            Assert.AreEqual(10, servitor.Items.Single().BaseStats[Stat.Value]);
            Assert.AreEqual("Chronometer", servitor.Items.Single().Name);
        }
Exemplo n.º 2
0
        public void Should_bind_channels_for_each_method()
        {
            var subject = new Subject();

            ActorFactory <Subject> factory = ActorFactory.Create <Subject>(x =>
            {
                x.ConstructedBy(() => subject);

                x.ConnectPublicMethods();
                x.ConnectPropertyChannels();
            });

            ActorRef actor = factory.GetActor();

            subject.ShouldNotBeNull();

            actor.Send <Message <A> >();
            actor.Send <Request <B> >();
            actor.Send <Response <C> >();
            actor.Send <Message <D> >();

            subject.FutureA.WaitUntilCompleted(5.Seconds()).ShouldBeTrue();
            subject.FutureB.WaitUntilCompleted(5.Seconds()).ShouldBeTrue();
            subject.FutureC.WaitUntilCompleted(5.Seconds()).ShouldBeTrue();
            subject.FutureD.WaitUntilCompleted(5.Seconds()).ShouldBeTrue();
        }
Exemplo n.º 3
0
        public void TestCreateActors_AppropriateToFaction()
        {
            var adj    = new AdjectiveFactory();
            var items  = new ItemFactory();
            var actors = new ActorFactory();

            var world   = new World();
            var faction = new Faction("Fish overloards", FactionRole.Wildlife);

            world.Factions.Add(faction);
            world.ActorFactory = actors;
            world.ItemFactory  = items;

            actors.Blueprints = new List <ActorBlueprint> {
                new ActorBlueprint()
                {
                    Name = "Captain Haddock"
                }
            };

            var room = new Room("Tank Bay", world, 't')
            {
                ControllingFaction = faction
            };

            Assert.IsEmpty(room.Actors);
            actors.Create(world, room, faction, null);

            Assert.IsTrue(room.Actors.Any());
            Assert.GreaterOrEqual(room.Actors.Count(a => a.FactionMembership.Contains(faction)), 1, "Expected room to be populated with some actors belonging to the controlling faction");
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ActorUnitTestingRuntime"/> class.
        /// </summary>
        internal ActorUnitTestingRuntime(Configuration configuration, Type actorType, IRandomValueGenerator valueGenerator)
            : base(configuration, valueGenerator)
        {
            if (!actorType.IsSubclassOf(typeof(Actor)))
            {
                this.Assert(false, "Type '{0}' is not an actor.", actorType.FullName);
            }

            var id = new ActorId(actorType, null, this);

            this.Instance = ActorFactory.Create(actorType);
            IActorManager actorManager;

            if (this.Instance is StateMachine stateMachine)
            {
                actorManager = new StateMachineManager(this, stateMachine, Guid.Empty);
            }
            else
            {
                actorManager = new ActorManager(this, this.Instance, Guid.Empty);
            }

            this.ActorInbox = new EventQueue(actorManager);
            this.Instance.Configure(this, id, actorManager, this.ActorInbox);
            this.Instance.SetupEventHandlers();

            this.LogWriter.LogCreateActor(this.Instance.Id, null, null);

            this.IsActorWaitingToReceiveEvent = false;
        }
Exemplo n.º 5
0
        public SubscriptionRouterService(IServiceBus bus, string network)
        {
            _peerUri = bus.ControlBus.Endpoint.Address.Uri;

            _network = network;

            _peerId = NewId.NextGuid();

            _observers = new List <SubscriptionObserver>();
            _listeners = new List <BusSubscriptionEventListener>();

            _unregister = () => true;

            _peerUri = bus.ControlBus.Endpoint.Address.Uri;

            var connector = new BusSubscriptionConnector(bus);

            _peerCache = ActorFactory.Create <PeerCache>(x =>
            {
                x.ConstructedBy((fiber, scheduler, inbox) =>
                                new PeerCache(fiber, scheduler, connector, _peerId, _peerUri));
                x.UseSharedScheduler();
                x.HandleOnPoolFiber();
            })
                         .GetActor();
        }
Exemplo n.º 6
0
        /// <summary>
        /// Spawns a monster with given SNOId in given position.
        /// </summary>
        /// <param name="monsterSNOId">The SNOId of the monster.</param>
        /// <param name="position">The position to spawn it.</param>
        public void SpawnMonster(int monsterSNOId, Vector3D position)
        {
            var monster = ActorFactory.Create(this, monsterSNOId, new TagMap());

            //monster.Scale = 1.35f; // this shoudln't be here
            monster.EnterWorld(position);
        }
Exemplo n.º 7
0
        public void Newly_created_account_should_have_correct_balence_and_credit()
        {
            ActorRef      account = ActorFactory.Create(inbox => new AccountActor(inbox, 100.0m)).GetActor();
            Future <bool> result  = new Future <bool>();

            decimal balance         = 0xDEADBEEF;
            decimal availableCredit = 0xDEADBEEF;
            decimal creditLimit     = 0xDEADBEEF;

            AnonymousActor.New(inbox =>
            {
                account.Request(new QueryAccountBalance(), inbox)
                .Receive <AccountBalance>(message =>
                {
                    balance         = message.Balance;
                    availableCredit = message.AvailableCredit;
                    creditLimit     = message.CreditLimit;

                    Console.WriteLine("Balance={0}, Credit={1}, Limit={2}",
                                      balance, availableCredit, creditLimit);
                    result.Complete(true);
                });
            });

            result.WaitUntilCompleted(5.Seconds());
            Assert.True(balance == 0 && availableCredit == 100.0m && creditLimit == 100.0m);
        }
Exemplo n.º 8
0
        }   // end of XmlLevelData WriteToXml()

        protected GameActor ActorFromString(string actorName)
        {
            GameActor ret = null;

            var staticActor = ActorManager.GetActor(actorName);

            if (staticActor == null)
            {
                var splitName  = actorName.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                var nsQualName = splitName[0];
                splitName   = nsQualName.Split('.');
                actorName   = splitName[splitName.Length - 1];
                staticActor = ActorManager.GetActor(actorName);
            }

            if (staticActor != null)
            {
                ret = ActorFactory.Create(staticActor);
            }
            else
            {
                Debug.Assert(false, "Why can't find the actor for: '" + actorName + "'!!");
            }

            return(ret);
        }
Exemplo n.º 9
0
        public TraceChannelImpl()
        {
            _factory = ActorFactory.Create(inbox => new TraceActor(inbox));
            _inbox   = _factory.GetActor();

            _dispose = _inbox.ExitOnDispose();
        }
Exemplo n.º 10
0
        /// <summary>
        /// Creates a new actor of the specified <see cref="Type"/>.
        /// </summary>
        private Actor CreateActor(ActorId id, Type type, string name, Actor creator, Guid opGroupId)
        {
            this.Assert(type.IsSubclassOf(typeof(Actor)), "Type '{0}' is not an actor.", type.FullName);

            // Using ulong.MaxValue because a Create operation cannot specify
            // the id of its target, because the id does not exist yet.
            this.Scheduler.ScheduleNextEnabledOperation();
            ResetProgramCounter(creator);

            if (id is null)
            {
                id = new ActorId(type, name, this);
            }
            else
            {
                this.Assert(id.Runtime is null || id.Runtime == this, "Unbound actor id '{0}' was created by another runtime.", id.Value);
                this.Assert(id.Type == type.FullName, "Cannot bind actor id '{0}' of type '{1}' to an actor of type '{2}'.",
                            id.Value, id.Type, type.FullName);
                id.Bind(this);
            }

            // The operation group id of the actor is set using the following precedence:
            // (1) To the specified actor creation operation group id, if it is non-empty.
            // (2) To the operation group id of the creator actor, if it exists and is non-empty.
            // (3) To the empty operation group id.
            if (opGroupId == Guid.Empty && creator != null)
            {
                opGroupId = creator.OperationGroupId;
            }

            Actor         actor = ActorFactory.Create(type);
            IActorManager actorManager;

            if (actor is StateMachine stateMachine)
            {
                actorManager = new MockStateMachineManager(this, stateMachine, opGroupId);
            }
            else
            {
                actorManager = new MockActorManager(this, actor, opGroupId);
            }

            IEventQueue eventQueue = new MockEventQueue(actorManager, actor);

            actor.Configure(this, id, actorManager, eventQueue);
            actor.SetupEventHandlers();

            if (this.Configuration.ReportActivityCoverage)
            {
                this.ReportActivityCoverageOfActor(actor);
            }

            bool result = this.Scheduler.RegisterOperation(new ActorOperation(actor));

            this.Assert(result, "Actor id '{0}' is used by an existing or previously halted actor.", id.Value);
            this.LogWriter.LogCreateActor(id, creator?.Id.Name, creator?.Id.Type);

            return(actor);
        }
        public void An_active_auction()
        {
            Id = CombGuid.Generate();

            ActorFactory <Auction> factory = ActorFactory.Create((f, i) => new Auction(f, i, Id));

            Auction = factory.GetActor();
        }
Exemplo n.º 12
0
        public void SummonMonster(int actorSNO)
        {
            var monster = ActorFactory.Create(User.World, actorSNO, new TagMap());

            monster.Scale = 1.35f;  // TODO: look this up properly
            monster.EnterWorld(this.SpawnPosition);
            this.World.BuffManager.AddBuff(User, monster, new Implementations.SummonedBuff());
        }
Exemplo n.º 13
0
        public PeerCache(ISubscriptionObserver observer, Guid clientId, Uri controlUri)
        {
            _peers   = new DictionaryCache <Uri, ActorRef>();
            _peerIds = new DictionaryCache <Guid, Uri>();

            _peerHandlerFactory = ActorFactory.Create((f, s, i) => new PeerHandler(i, observer));

            // create a peer for our local client
            WithPeer(clientId, controlUri, x => { }, true);
        }
Exemplo n.º 14
0
        public void TestActorFactory_SlotCreation()
        {
            string yamlDefaultSlots =
                @"
Head: 1
Hands: 1
Legs: 2
Chest: 1
";

            string yaml = @"
- Name: Pirate
- Name: Scorpion
  Slots:
    Head: 1
    Tail: 1
    Legs: 6
";
            var    room = InARoom(out IWorld w);



            var actorFactory = new ActorFactory()
            {
                Blueprints   = Compiler.Instance.Deserializer.Deserialize <List <ActorBlueprint> >(yaml),
                DefaultSlots = Compiler.Instance.Deserializer.Deserialize <SlotCollection>(yamlDefaultSlots),
            };

            var scorpion = actorFactory.Create(w, room, null, actorFactory.Blueprints[1], null);

            Assert.AreEqual(1, scorpion.AvailableSlots["Head"]);
            Assert.AreEqual(1, scorpion.AvailableSlots["Tail"]);
            Assert.AreEqual(6, scorpion.AvailableSlots["Legs"]);


            var pirate = actorFactory.Create(w, room, null, actorFactory.Blueprints[0], null);

            Assert.AreEqual(1, pirate.AvailableSlots["Head"]);
            Assert.AreEqual(1, pirate.AvailableSlots["Hands"]);
            Assert.AreEqual(2, pirate.AvailableSlots["Legs"]);
            Assert.AreEqual(1, pirate.AvailableSlots["Chest"]);
        }
Exemplo n.º 15
0
        public void ActorLoadedEvent()
        {
            Actor actor = ActorFactory.Create();

            actor.LoadedEvent += new LoadedEventHandler <LoadedEventArgs <IActor> >(DetectActorEvent);
            actor.Load();
            bool found = actorLoadedDetected;

            actorLoadedDetected = false;
            Assert.AreEqual(true, found);
        }
Exemplo n.º 16
0
        public void SummonMonsterInFront(int actorSNO)
        {
            float    userFacing = (float)Math.Acos(this.User.RotationW) * 2f;
            Vector3D spawnPos   = new Vector3D(User.Position.X + 8 * (float)Math.Cos(userFacing),
                                               User.Position.Y + 8 * (float)Math.Sin(userFacing),
                                               User.Position.Z);

            var monster = ActorFactory.Create(User.World, actorSNO, new TagMap());

            monster.Scale = 1.35f;  // TODO: look this up properly
            monster.EnterWorld(spawnPos);
            this.World.BuffManager.AddBuff(User, monster, new Implementations.SummonedBuff());
        }
Exemplo n.º 17
0
        public void A_stream_of_messages_is_received()
        {
            ActorFactory <Agent> agentFactory = ActorFactory.Create(inbox => new Agent(inbox));

            ActorRef agent = agentFactory.GetActor();

            for (int i = 0; i < _count; i++)
            {
                agent.Send(new Add
                {
                    Value = i
                });

                if (i == 100)
                {
                    agent.Send <Suspend>();
                }

                if (i == 500)
                {
                    agent.Send <Resume>();
                }
            }

            _response = new Future <Status>();
            var actor = AnonymousActor.New(inbox =>
            {
                Action loop = null;
                loop        = () =>
                {
                    agent.Request(new Status(), inbox)
                    .Receive <Response <Status> >(response =>
                    {
                        if (response.Body.Count == _count)
                        {
                            _response.Complete(response.Body);
                        }
                        else
                        {
                            loop();
                        }
                    });
                };

                loop();
            });

            _response.WaitUntilCompleted(8.Seconds());
        }
Exemplo n.º 18
0
        public async Task EnsureOrder(ActorAffinity affinity)
        {
            int [] given = { 1, 4 };
            var    actor = ActorFactory.Create <ITypedSequenceTest, TypedSequenceTestImpl>(() => new TypedSequenceTestImpl(), affinity);

            Task t1 = actor.Add(3000, given[0]);
            Task t2 = actor.Add(1000, given[1]);

            await Task.WhenAll(t1, t2);

            int[] result = await actor.GetElements();

            // after ActoR tasks have been executed the order should be ok
            Assert.Equal(given, result);
        }
Exemplo n.º 19
0
        public void An_agent_is_paused()
        {
            ActorFactory <Agent> agentFactory = ActorFactory.Create(inbox => new Agent(inbox));

            ActorRef agent = agentFactory.GetActor();

            _first  = new Update();
            _second = new Update();

            agent.Send(_first);
            agent.Send <Suspend>();
            agent.Send(_second);

            _first.WaitUntilCompleted(2.Seconds());
            _second.WaitUntilCompleted(2.Seconds());
        }
Exemplo n.º 20
0
        public ActorFactory <TController> CreateFactory <TController>(Func <Inbox, TController> createInstance)
            where TController : class, IServiceController
        {
            ActorFactory <TController> factory = ActorFactory.Create <TController>(x =>
            {
                x.ConstructedBy(inbox =>
                {
                    TController instance = createInstance(inbox);

                    _workflowBinder.Bind(inbox, instance);

                    return(instance);
                });
            });

            return(factory);
        }
Exemplo n.º 21
0
        bool SameMessageTypeTest <TInput, TConsumer>(int messageCount, Future <int> complete, Func <TInput> messageProvider)
        {
            var latch = new CountdownLatch(messageCount, complete.Complete);

            ActorFactory <TestActor <TConsumer> > factory = ActorFactory.Create(inbox => new TestActor <TConsumer>(inbox, latch));
            ActorRef actor = factory.GetActor();

            for (int i = 0; i < messageCount; i++)
            {
                actor.Send(messageProvider());
            }

            bool completed = complete.WaitUntilCompleted(30.Seconds());

            actor.Exit();

            return(completed);
        }
Exemplo n.º 22
0
        public void TestFactionActorsYaml()
        {
            var adj = new AdjectiveFactory();

            var yaml = @"
- Name: Centipede
  OptionalAdjectives:
    - Giant
    - Rusty
    - Strong
    - Tough
  Stats:
    Fight: 30
- Name: Crab
  Identifier: 24a1c3ad-fcdf-4c00-acf7-627e7f70c181
  Dialogue: 
    Verb: talk
    Next: 566ae926-a1fe-4209-9a15-fce026dbc5d1
  OptionalAdjectives:
    - Strong
  Stats:
    Fight: 40
";

            var actorFactory = new ActorFactory {
                Blueprints = Compiler.Instance.Deserializer.Deserialize <List <ActorBlueprint> >(yaml)
            };

            Assert.GreaterOrEqual(actorFactory.Blueprints.Count, 2);

            var room = InARoom(out IWorld w);

            var actor = actorFactory.Create(w, room, null, actorFactory.Blueprints[1], null);

            Assert.AreEqual("Crab", actor.Name);
            Assert.AreEqual("Strong", actor.Adjectives.Single().Name);

            Assert.AreEqual(40, actor.BaseStats[Stat.Fight]);

            Assert.AreEqual(new Guid("566ae926-a1fe-4209-9a15-fce026dbc5d1"), actor.Dialogue.Next);
            Assert.AreEqual(new Guid("24a1c3ad-fcdf-4c00-acf7-627e7f70c181"), actor.Identifier);
        }
Exemplo n.º 23
0
        public void Run()
        {
            _ringNodeFactory = ActorFactory.Create(inbox => new RingNode(inbox));

            Stopwatch timer = Stopwatch.StartNew();

            int nodeCount  = 100;
            int roundCount = 1000;

            Run(nodeCount, roundCount);

            timer.Stop();

            Console.WriteLine("Ring Benchmark");

            Console.WriteLine("Processed {0} rings with {1} nodes in {2}ms", roundCount, nodeCount,
                              timer.ElapsedMilliseconds);

            Console.WriteLine("That's {0} messages per second!",
                              ((long)nodeCount * roundCount * 1000) / timer.ElapsedMilliseconds);
        }
Exemplo n.º 24
0
        public void TestActorFactory_ExplicitActions()
        {
            string yaml = @"
- Name: Scorpion
  Slots:
    Head: 1
    Tail: 1
    Legs: 6
  SkipDefaultActions: true
  Actions:
    - Type: FightAction
";
            var    room = InARoom(out IWorld w);

            var actorFactory = new ActorFactory {
                Blueprints = Compiler.Instance.Deserializer.Deserialize <List <ActorBlueprint> >(yaml)
            };
            var scorpion = actorFactory.Create(w, room, null, actorFactory.Blueprints[0], null);

            Assert.IsInstanceOf <FightAction>(scorpion.BaseActions.Single(), "Expected Scorpion to be capable of nothing but fighting");
        }
Exemplo n.º 25
0
        public void Adding_an_actor_to_a_registry()
        {
            _auctionFactory = ActorFactory.Create(inbox => new Auction(inbox));

            _auctionId = CombGuid.Generate();

            ActorRef auction = _auctionFactory.GetActor();

            ActorRegistry registry = ActorRegistryFactory.New(x =>
            {
                //x.Remote(r => r.ListenTo("rm://234.0.0.7:40001"));
            });

            registry.Register(_auctionId, auction);

            _response = new Future <Response <Bid> >();

            AnonymousActor.New(inbox =>
            {
                registry.Request <Bid>(new BidImpl(27.42m),
                                       header => { header.DestinationAddress = new ActorUrn(_auctionId); }, inbox)
                .Receive <Response <Bid> >(x => _response.Complete);
            });

            _response.WaitUntilCompleted(5.Seconds()).ShouldBeTrue();

            // need to proxy the channel with headers somehow...

            // untyped channel => channel mapper -> actor instance

            // DestinationAddress -> set by outbound channel proxy on message<>
            // SourceAddress -> set by outbound channel proxy when available (not likely)
            // ResponseAddress -> set by outbound channel for ResponseChannel on Request to map to channel
            // Id -> system assigned id
            // DestinationAddress = urn:actor:554FC958-4661-4FE9-94F5-21D190417BCC
        }
Exemplo n.º 26
0
        /// <summary>
        /// Loads all markers for the scene.
        /// </summary>
        public void LoadMarkers()
        {
            this.GizmoSpawningLocations = new List <PRTransform> [26]; // LocationA to LocationZ

            // TODO: We should be instead loading actors but let them get revealed based on quest/triggers/player proximity. /raist.

            foreach (var markerSet in this.MarkerSets)
            {
                var markerSetData = MPQStorage.Data.Assets[SNOGroup.MarkerSet][markerSet].Data as Mooege.Common.MPQ.FileFormats.MarkerSet;
                if (markerSetData == null)
                {
                    return;
                }

                foreach (var marker in markerSetData.Markers)
                {
                    switch (marker.Type)
                    {
                    case Mooege.Common.MPQ.FileFormats.MarkerType.AmbientSound:
                    case Mooege.Common.MPQ.FileFormats.MarkerType.Light:
                    case Mooege.Common.MPQ.FileFormats.MarkerType.Particle:
                    case Mooege.Common.MPQ.FileFormats.MarkerType.SubScenePosition:
                    case Mooege.Common.MPQ.FileFormats.MarkerType.AudioVolume:
                        // nothing to do for these here, client load them on its own
                        break;

                    case Mooege.Common.MPQ.FileFormats.MarkerType.Script:
                        Logger.Trace("Ignoring marker {0} in {1} ({2}) because scripts are not handled yet", marker.Name, markerSetData.FileName, markerSetData.Header.SNOId);
                        break;

                    case Mooege.Common.MPQ.FileFormats.MarkerType.Event:
                        Logger.Trace("Ignoring marker {0} in {1} ({2}) because events are not handled yet", marker.Name, markerSetData.FileName, markerSetData.Header.SNOId);
                        break;

                    case Mooege.Common.MPQ.FileFormats.MarkerType.MinimapMarker:
                        Logger.Trace("Ignoring marker {0} in {1} ({2}) because minimap marker are not handled yet", marker.Name, markerSetData.FileName, markerSetData.Header.SNOId);

                        break;

                    case Mooege.Common.MPQ.FileFormats.MarkerType.Actor:

                        var actor = ActorFactory.Create(this.World, marker.SNOHandle.Id, marker.TagMap);     // try to create it.
                        if (actor == null)
                        {
                            continue;
                        }

                        var position = marker.PRTransform.Vector3D + this.Position;     // calculate the position for the actor.
                        actor.RotationW    = marker.PRTransform.Quaternion.W;
                        actor.RotationAxis = marker.PRTransform.Quaternion.Vector3D;

                        actor.EnterWorld(position);
                        break;

                    case Mooege.Common.MPQ.FileFormats.MarkerType.Encounter:

                        var encounter = marker.SNOHandle.Target as Mooege.Common.MPQ.FileFormats.Encounter;
                        var actorsno  = RandomHelper.RandomItem(encounter.Spawnoptions, x => x.Probability);
                        var actor2    = ActorFactory.Create(this.World, actorsno.SNOSpawn, marker.TagMap);  // try to create it.
                        if (actor2 == null)
                        {
                            continue;
                        }

                        var position2 = marker.PRTransform.Vector3D + this.Position;     // calculate the position for the actor.
                        actor2.RotationW    = marker.PRTransform.Quaternion.W;
                        actor2.RotationAxis = marker.PRTransform.Quaternion.Vector3D;

                        actor2.EnterWorld(position2);

                        break;

                    default:

                        // Save gizmo locations. They are used to spawn loots and gizmos randomly in a level area
                        if ((int)marker.Type >= (int)Mooege.Common.MPQ.FileFormats.MarkerType.GizmoLocationA && (int)marker.Type <= (int)Mooege.Common.MPQ.FileFormats.MarkerType.GizmoLocationZ)
                        {
                            int index = (int)marker.Type - 50;     // LocationA has id 50...

                            if (GizmoSpawningLocations[index] == null)
                            {
                                GizmoSpawningLocations[index] = new List <PRTransform>();
                            }

                            marker.PRTransform.Vector3D += this.Position;
                            GizmoSpawningLocations[index].Add(marker.PRTransform);
                        }
                        else
                        {
                            Logger.Warn("Unhandled marker type {0} in actor loading", marker.Type);
                        }


                        break;
                    }
                }
            }
        }
Exemplo n.º 27
0
        public void Charging_an_account_async_should_still_adjust_the_balence()
        {
            ActorRef account = ActorFactory.Create(inbox => new AccountActor(inbox, 100.0m)).GetActor();

            decimal balance         = 0xDEADBEEF;
            decimal availableCredit = 0xDEADBEEF;
            decimal creditLimit     = 0xDEADBEEF;

            #region  Charge 3 times with 10.0 async

            AnonymousActor.New(inbox =>
            {
                account.Send(new ChargeAccount()
                {
                    Amount = 10
                });
            });

            AnonymousActor.New(inbox =>
            {
                account.Send(new ChargeAccount()
                {
                    Amount = 10
                });
            });

            AnonymousActor.New(inbox =>
            {
                account.Send(new ChargeAccount()
                {
                    Amount = 10
                });
            });

            #endregion

            #region Loop until available credit is correct but fail if more than 50 times

            for (int i = 0; availableCredit != 70.0m && i < 100; i++)
            {
                Future <bool> result = new Future <bool>();

                //Fire of listeners serially and with some time apart
                AnonymousActor.New(inbox =>
                {
                    account.Request(new QueryAccountBalance(), inbox)
                    .Receive <AccountBalance>(message =>
                    {
                        balance         = message.Balance;
                        availableCredit = message.AvailableCredit;
                        creditLimit     = message.CreditLimit;

                        Console.WriteLine("Balance={0}, Credit={1}, Limit={2}",
                                          balance,
                                          availableCredit,
                                          creditLimit);

                        Thread.Sleep(1000);
                        result.Complete(true);
                    });
                });
                result.WaitUntilCompleted(5.Seconds());
                Console.WriteLine("Listener {0} completed", i);
                Thread.Sleep(1000);

                Assert.True(i < 50);
            }

            #endregion

            Assert.True(balance == 30 && availableCredit == 70.0m && creditLimit == 100.0m);
        }
            }   // end of EditObjectUpdateObj CancelNewItemSelector()

            public void SelectNewItemSelector(UiSelector selector)
            {
                UiSelector.GroupData groupData = selector.SelectedItem as UiSelector.GroupData;
                if (groupData != null)
                {
                    // sub group was activated
                    Foley.PlayProgrammingMoveOut();
                }
                else
                {
                    Instrumentation.IncrementCounter(Instrumentation.CounterId.AddItem);

                    GameActor thingToColor   = null;
                    GameActor thingToDistort = null;

                    //Object item = selector.ObjectSelectedItem;

                    ActorMenuItem item = selector.ObjectSelectedItem as ActorMenuItem;
                    if (item != null)
                    {
                        if (item.StaticActor != null)
                        {
                            if (addPositionIsExplicit)
                            {
                                ///Client has requested a specific position to add this guy.
                                ///Give the people what they want.
                                thingToColor = parent.AddActor(
                                    ActorFactory.Create(item.StaticActor),
                                    new Vector3(addPosition, float.MaxValue),
                                    InGame.inGame.shared.camera.Rotation);

                                // Reset
                                addPositionIsExplicit = false;
                            }
                            else
                            {
                                /// Default is to add at the cursor position.
                                thingToColor = parent.AddActorAtCursor(ActorFactory.Create(item.StaticActor));
                            }

                            // Give a ref to the actor to the HelpCard.  If it's active it
                            // can then program the actor's brain.
                            InGame.inGame.shared.addItemHelpCard.Actor = thingToColor as GameActor;
                        }
                        else if (item.TextureFilename.StartsWith("filter.path"))
                        {
                            if (parent.UnderBudget)
                            {
                                /// If the waypoint editor is active, let it handle this.
                                if (!shared.editWayPoint.Active)
                                {
                                    int pathType = 0;
                                    if (item.TextureFilename.EndsWith("road"))
                                    {
                                        pathType = Road.LastRoadCreated;
                                    }
                                    else if (item.TextureFilename.Contains("wall"))
                                    {
                                        pathType = Road.LastWallCreated;
                                    }
                                    else if (item.TextureFilename.Contains("flora"))
                                    {
                                        pathType = Road.LastVegCreated;
                                    }
                                    Road.GenIndex = pathType;
                                    Vector3 pos = addPositionIsExplicit
                                        ? new Vector3(addPosition, float.MaxValue)
                                        : parent.cursor3D.Position;
                                    shared.editWayPoint.NewPath(pos, shared.curObjectColor);
                                }
                            }
                            else
                            {
                                Instrumentation.IncrementCounter(Instrumentation.CounterId.AddItemNoBudget);

                                Foley.PlayNoBudget();
                            }
                        }
                    }
                    else
                    {
                        Debug.Assert(false, "How did this happen?");
                    }


                    if (thingToColor != null)
                    {
                        Foley.PlayProgrammingAdd();

                        shared.curObjectColor = ColorPalette.GetIndexFromColor(thingToColor.ClassColor);
                        //                        thingToColor.Classcolor = ColorPalette.GetColorFromIndex(shared.curObjectColor);
                        thingToDistort = thingToColor;
                    }

                    if (thingToDistort != null)
                    {
                        parent.DistortionPulse(thingToDistort, true);
                    }

                    newItemSelectorShim.Deactivate();

                    InGame.IsLevelDirty = true;
                }
            }   // end of EditObjectUpdateObj SelectNewItemSelector()
Exemplo n.º 29
0
 static private CruiseMissile NextAvailable()
 {
     return(ActorFactory.Create(ActorManager.GetActor("CruiseMissile")) as CruiseMissile);
 }
Exemplo n.º 30
0
        /// <summary>
        /// Creates a new actor of the specified <see cref="Type"/>.
        /// </summary>
        private Actor CreateActor(ActorId id, Type type, string name, Actor creator, EventGroup group)
        {
            this.Assert(type.IsSubclassOf(typeof(Actor)), "Type '{0}' is not an actor.", type.FullName);

            // Using ulong.MaxValue because a Create operation cannot specify
            // the id of its target, because the id does not exist yet.
            this.Scheduler.ScheduleNextOperation();
            ResetProgramCounter(creator);

            if (id is null)
            {
                id = new ActorId(type, name, this);
            }
            else
            {
                this.Assert(id.Runtime is null || id.Runtime == this, "Unbound actor id '{0}' was created by another runtime.", id.Value);
                this.Assert(id.Type == type.FullName, "Cannot bind actor id '{0}' of type '{1}' to an actor of type '{2}'.",
                            id.Value, id.Type, type.FullName);
                id.Bind(this);
            }

            // If a group was not provided, inherit the current event group from the creator (if any).
            if (group == null && creator != null)
            {
                group = creator.Manager.CurrentEventGroup;
            }

            Actor         actor = ActorFactory.Create(type);
            IActorManager actorManager;

            if (actor is StateMachine stateMachine)
            {
                actorManager = new MockStateMachineManager(this, stateMachine, group);
            }
            else
            {
                actorManager = new MockActorManager(this, actor, group);
            }

            IEventQueue eventQueue = new MockEventQueue(actorManager, actor);

            actor.Configure(this, id, actorManager, eventQueue);
            actor.SetupEventHandlers();

            if (this.Configuration.ReportActivityCoverage)
            {
                this.ReportActivityCoverageOfActor(actor);
            }

            bool result = this.Scheduler.RegisterOperation(new ActorOperation(actor));

            this.Assert(result, "Actor id '{0}' is used by an existing or previously halted actor.", id.Value);
            if (actor is StateMachine)
            {
                this.LogWriter.LogCreateStateMachine(id, creator?.Id.Name, creator?.Id.Type);
            }
            else
            {
                this.LogWriter.LogCreateActor(id, creator?.Id.Name, creator?.Id.Type);
            }

            return(actor);
        }