public MonitoredDuplexOutputChannel(IDuplexOutputChannel underlyingOutputChannel, ISerializer serializer,
                                            int pingFrequency,
                                            int receiveTimeout,
                                            IThreadDispatcher dispatcher)
        {
            using (EneterTrace.Entering())
            {
                myUnderlyingOutputChannel = underlyingOutputChannel;

                mySerializer     = serializer;
                myPingFrequency  = pingFrequency;
                myReceiveTimeout = receiveTimeout;
                Dispatcher       = dispatcher;

                MonitorChannelMessage aPingMessage = new MonitorChannelMessage(MonitorChannelMessageType.Ping, null);
                myPreserializedPingMessage = mySerializer.Serialize <MonitorChannelMessage>(aPingMessage);

                myPingingTimer = new EneterTimer(OnPingingTimerTick);
                myReceiveTimer = new EneterTimer(OnResponseTimerTick);

                myUnderlyingOutputChannel.ResponseMessageReceived += OnResponseMessageReceived;
                myUnderlyingOutputChannel.ConnectionOpened        += OnConnectionOpened;
                myUnderlyingOutputChannel.ConnectionClosed        += OnConnectionClosed;
            }
        }
Esempio n. 2
0
        public void Flush(IThreadDispatcher threadDispatcher = null, bool deterministic = false)
        {
            OnPreflush(threadDispatcher, deterministic);
            //var start = Stopwatch.GetTimestamp();
            QuickList <NarrowPhaseFlushJob, Buffer <NarrowPhaseFlushJob> > .Create(Pool.SpecializeFor <NarrowPhaseFlushJob>(), 128, out flushJobs);

            PairCache.PrepareFlushJobs(ref flushJobs);
            //We indirectly pass the determinism state; it's used by the constraint remover bookkeeping.
            this.deterministic = deterministic;
            ConstraintRemover.CreateFlushJobs(ref flushJobs);

            if (threadDispatcher == null)
            {
                for (int i = 0; i < flushJobs.Count; ++i)
                {
                    ExecuteFlushJob(ref flushJobs[i]);
                }
            }
            else
            {
                flushJobIndex = -1;
                threadDispatcher.DispatchWorkers(flushWorkerLoop);
            }
            //var end = Stopwatch.GetTimestamp();
            //Console.WriteLine($"Flush stage 3 time (us): {1e6 * (end - start) / Stopwatch.Frequency}");
            flushJobs.Dispose(Pool.SpecializeFor <NarrowPhaseFlushJob>());

            PairCache.Postflush();
            ConstraintRemover.Postflush();

            OnPostflush(threadDispatcher);
        }
        //// ===========================================================================================================
        //// Constructors
        //// ===========================================================================================================

        public BackgroundEditorViewModel(
            ILogger logger,
            IThreadDispatcher threadDispatcher,
            IRegistryWriteService registryWriteService)
            : base(logger, threadDispatcher, registryWriteService, CreateBonusBarViewModel())
        {
        }
Esempio n. 4
0
        public void AttachToDispatcher()
        {
            Dispatcher aDispatcher = WindowsDispatching.StartNewWindowsDispatcher();

            IThreadDispatcherProvider aDispatching       = new WindowsDispatching(aDispatcher);
            IThreadDispatcher         anEneterDispatcher = aDispatching.GetDispatcher();

            ManualResetEvent anInvokeCompleted1 = new ManualResetEvent(false);
            int aThreadId1 = 0;

            anEneterDispatcher.Invoke(() =>
            {
                aThreadId1 = Thread.CurrentThread.ManagedThreadId;
                anInvokeCompleted1.Set();
            });
            anInvokeCompleted1.WaitOne();

            ManualResetEvent anInvokeCompleted2 = new ManualResetEvent(false);
            int aThreadId2 = 0;

            anEneterDispatcher.Invoke(() =>
            {
                aThreadId2 = Thread.CurrentThread.ManagedThreadId;
                anInvokeCompleted2.Set();
            });
            anInvokeCompleted1.WaitOne();

            WindowsDispatching.StopWindowsDispatcher(aDispatcher);

            Assert.AreNotEqual(Thread.CurrentThread.ManagedThreadId, aThreadId1);
            Assert.AreEqual(aThreadId1, aThreadId2);
        }
        public DefaultDuplexInputChannel(string channelId,               // address to listen
                                         IThreadDispatcher dispatcher,   // threading model used to notify messages and events
                                         IThreadDispatcher dispatchingAfterMessageReading,
                                         IInputConnector inputConnector) // listener used for listening to messages
        {
            using (EneterTrace.Entering())
            {
                if (string.IsNullOrEmpty(channelId))
                {
                    EneterTrace.Error(ErrorHandler.NullOrEmptyChannelId);
                    throw new ArgumentException(ErrorHandler.NullOrEmptyChannelId);
                }

                ChannelId = channelId;

                Dispatcher = dispatcher;

                // Internal dispatcher used when the message is decoded.
                // E.g. Shared memory messaging needs to return looping immediately the protocol message is decoded
                //      so that other senders are not blocked.
                myDispatchingAfterMessageReading = dispatchingAfterMessageReading;

                myInputConnector = inputConnector;
            }
        }
Esempio n. 6
0
        public void Flush(IThreadDispatcher threadDispatcher = null)
        {
            var deterministic = threadDispatcher != null && Simulation.Deterministic;

            OnPreflush(threadDispatcher, deterministic);
            //var start = Stopwatch.GetTimestamp();
            flushJobs = new QuickList <NarrowPhaseFlushJob>(128, Pool);
            PairCache.PrepareFlushJobs(ref flushJobs);
            var removalBatchJobCount = ConstraintRemover.CreateFlushJobs(deterministic);

            //Note that we explicitly add the constraint remover jobs here.
            //The constraint remover can be used in two ways- sleeper style, and narrow phase style.
            //In sleeping, we're not actually removing constraints from the simulation completely, so it requires fewer jobs.
            //The constraint remover just lets you choose which jobs to call. The narrow phase needs all of them.
            flushJobs.EnsureCapacity(flushJobs.Count + removalBatchJobCount + 4, Pool);
            flushJobs.AddUnsafely(new NarrowPhaseFlushJob {
                Type = NarrowPhaseFlushJobType.RemoveConstraintsFromBodyLists
            });
            flushJobs.AddUnsafely(new NarrowPhaseFlushJob {
                Type = NarrowPhaseFlushJobType.ReturnConstraintHandles
            });
            flushJobs.AddUnsafely(new NarrowPhaseFlushJob {
                Type = NarrowPhaseFlushJobType.RemoveConstraintFromBatchReferencedHandles
            });
            if (Solver.ActiveSet.Batches.Count > Solver.FallbackBatchThreshold)
            {
                flushJobs.AddUnsafely(new NarrowPhaseFlushJob {
                    Type = NarrowPhaseFlushJobType.RemoveConstraintsFromFallbackBatch
                });
            }
            for (int i = 0; i < removalBatchJobCount; ++i)
            {
                flushJobs.AddUnsafely(new NarrowPhaseFlushJob {
                    Type = NarrowPhaseFlushJobType.RemoveConstraintFromTypeBatch, Index = i
                });
            }

            if (threadDispatcher == null)
            {
                for (int i = 0; i < flushJobs.Count; ++i)
                {
                    ExecuteFlushJob(ref flushJobs[i], Pool);
                }
            }
            else
            {
                flushJobIndex         = -1;
                this.threadDispatcher = threadDispatcher;
                threadDispatcher.DispatchWorkers(flushWorkerLoop);
                this.threadDispatcher = null;
            }
            //var end = Stopwatch.GetTimestamp();
            //Console.WriteLine($"Flush stage 3 time (us): {1e6 * (end - start) / Stopwatch.Frequency}");
            flushJobs.Dispose(Pool);

            PairCache.Postflush();
            ConstraintRemover.Postflush();

            OnPostflush(threadDispatcher);
        }
Esempio n. 7
0
 public void Prepare(float dt, IThreadDispatcher threadDispatcher = null)
 {
     timestepDuration = dt;
     OnPrepare(threadDispatcher);
     PairCache.Prepare(threadDispatcher);
     ConstraintRemover.Prepare(threadDispatcher);
 }
Esempio n. 8
0
 public PackageAddedEventHandler(IRouter router, IThreadDispatcher dispatcher, IViewMain mainView, PackageController controller)
 {
     _mainView   = mainView;
     _controller = controller;
     _router     = router;
     _dispatcher = dispatcher;
 }
        public void Update(IThreadDispatcher threadDispatcher = null)
        {
            if (frameIndex == int.MaxValue)
            {
                frameIndex = 0;
            }
            if (threadDispatcher != null)
            {
                activeRefineContext.RefitAndRefine(ref ActiveTree, Pool, threadDispatcher, frameIndex);
            }
            else
            {
                ActiveTree.RefitAndRefine(Pool, frameIndex);
            }

            //TODO: for now, the inactive/static tree is simply updated like another active tree. This is enormously inefficient compared to the ideal-
            //by nature, static and inactive objects do not move every frame!
            //This should be replaced by a dedicated inactive/static refinement approach. It should also run alongside the active tree to extract more parallelism;
            //in other words, generate jobs from both trees and dispatch over all of them together. No internal dispatch.
            if (threadDispatcher != null)
            {
                staticRefineContext.RefitAndRefine(ref StaticTree, Pool, threadDispatcher, frameIndex);
            }
            else
            {
                StaticTree.RefitAndRefine(Pool, frameIndex);
            }
            ++frameIndex;
        }
Esempio n. 10
0
 public TestEditorViewModel(BonusBarViewModel bonusBar, IThreadDispatcher threadDispatcher = null)
     : base(
         new NullLogger(),
         threadDispatcher ?? new UnitTestThreadDispatcher(),
         new DoNothingRegistryWriteService(),
         bonusBar)
 {
 }
Esempio n. 11
0
 public TcpServer(int serverPort, IThreadDispatcher threadDispatcher, IProtocolFactory protocolFactory, ILogger logger, IAppDocument appDocument)
 {
     ServerPort       = serverPort;
     ThreadDispatcher = threadDispatcher;
     ProtocolFactory  = protocolFactory;
     Logger           = logger;
     AppDocument      = appDocument;
 }
 public IDuplexOutputChannel CreateDuplexOutputChannel(string channelId, string responseReceiverId)
 {
     using (EneterTrace.Entering())
     {
         IThreadDispatcher aDispatcher = OutputChannelThreading.GetDispatcher();
         return(new DefaultDuplexOutputChannel(channelId, responseReceiverId, aDispatcher, myDispatcherAfterMessageDecoded, myOutputConnectorFactory));
     }
 }
Esempio n. 13
0
 public PackageController(IThreadDispatcher threadDispatcher, ICommandDispatcher commandDispatcher, IQueryDispatcher queryDispatcher, ViewCollection views)
 {
     _views = views;
     _views.SetController(this);
     _commandDispatcher = commandDispatcher;
     _queryDispatcher   = queryDispatcher;
     _threadDispatcher  = threadDispatcher;
 }
Esempio n. 14
0
 public ContactEvents(TEventHandler eventHandler, BufferPool pool, IThreadDispatcher threadDispatcher, int initialListenerCapacity = 32)
 {
     this.EventHandler     = eventHandler;
     this.pool             = pool;
     this.threadDispatcher = threadDispatcher;
     pendingWorkerAdds     = new QuickList <PendingNewEntry> [threadDispatcher == null ? 1: threadDispatcher.ThreadCount];
     listeners             = new QuickDictionary <CollidableReference, QuickList <PreviousCollisionData>, CollidableReferenceComparer>(initialListenerCapacity, pool);
 }
 /// <summary>
 /// Creates the input channel which can receive messages from the output channel and send response messages.
 /// </summary>
 /// <remarks>
 /// In addition it expects receiving ping messages from each connected client within a specified time and sends
 /// ping messages to each connected client in a specified frequency.
 /// </remarks>
 /// <param name="channelId">input channel address. It must comply to underlying messaging</param>
 /// <returns>monitoring duplex input channel</returns>
 public IDuplexInputChannel CreateDuplexInputChannel(string channelId)
 {
     using (EneterTrace.Entering())
     {
         IDuplexInputChannel anUnderlyingChannel = myUnderlyingMessaging.CreateDuplexInputChannel(channelId);
         IThreadDispatcher   aThreadDispatcher   = InputChannelThreading.GetDispatcher();
         return(new MonitoredDuplexInputChannel(anUnderlyingChannel, Serializer, (int)PingFrequency.TotalMilliseconds, (int)ReceiveTimeout.TotalMilliseconds, aThreadDispatcher));
     }
 }
 public IDuplexInputChannel CreateDuplexInputChannel(string channelId)
 {
     using (EneterTrace.Entering())
     {
         IThreadDispatcher aDispatcher      = InputChannelThreading.GetDispatcher();
         IInputConnector   anInputConnector = myInputConnectorFactory.CreateInputConnector(channelId);
         return(new DefaultDuplexInputChannel(channelId, aDispatcher, myDispatcherAfterMessageDecoded, anInputConnector));
     }
 }
Esempio n. 17
0
        public BaseViewModel(IView view, IComponentContext container)
        {
            this.View             = view;
            this.View.DataContext = this;

            this.Container     = container;
            this.DialogInvoker = this.Container.Resolve <IDialogInvoker>();
            this.Dispatcher    = this.Container.Resolve <IThreadDispatcher>();
        }
 /// <summary>
 /// Creates synchronous duplex typed message sender that sends a request message and then
 /// waits until the response message is received.
 /// </summary>
 /// <typeparam name="TResponse">Response message type.</typeparam>
 /// <typeparam name="TRequest">Request message type.</typeparam>
 /// <returns></returns>
 public ISyncDuplexTypedMessageSender <TResponse, TRequest> CreateSyncDuplexTypedMessageSender <TResponse, TRequest>()
 {
     using (EneterTrace.Entering())
     {
         IThreadDispatcher aThreadDispatcher = SyncDuplexTypedSenderThreadMode.GetDispatcher();
         SyncTypedMessageSender <TResponse, TRequest> aSender = new SyncTypedMessageSender <TResponse, TRequest>(SyncResponseReceiveTimeout, Serializer, aThreadDispatcher);
         return(aSender);
     }
 }
Esempio n. 19
0
        public void Flush(IThreadDispatcher threadDispatcher = null, bool deterministic = false)
        {
            OnPreflush(threadDispatcher, deterministic);
            //var start = Stopwatch.GetTimestamp();
            var jobPool = Pool.SpecializeFor <NarrowPhaseFlushJob>();

            QuickList <NarrowPhaseFlushJob, Buffer <NarrowPhaseFlushJob> > .Create(jobPool, 128, out flushJobs);

            PairCache.PrepareFlushJobs(ref flushJobs);
            //We indirectly pass the determinism state; it's used by the constraint remover bookkeeping.
            this.deterministic = deterministic;
            var removalBatchJobCount = ConstraintRemover.CreateFlushJobs();

            //Note that we explicitly add the constraint remover jobs here.
            //The constraint remover can be used in two ways- deactivation style, and narrow phase style.
            //In deactivation, we're not actually removing constraints from the simulation completely, so it requires fewer jobs.
            //The constraint remover just lets you choose which jobs to call. The narrow phase needs all of them.
            flushJobs.EnsureCapacity(flushJobs.Count + removalBatchJobCount + 3, jobPool);
            flushJobs.AddUnsafely(new NarrowPhaseFlushJob {
                Type = NarrowPhaseFlushJobType.RemoveConstraintsFromBodyLists
            });
            flushJobs.AddUnsafely(new NarrowPhaseFlushJob {
                Type = NarrowPhaseFlushJobType.ReturnConstraintHandles
            });
            flushJobs.AddUnsafely(new NarrowPhaseFlushJob {
                Type = NarrowPhaseFlushJobType.RemoveConstraintFromBatchReferencedHandles
            });
            for (int i = 0; i < removalBatchJobCount; ++i)
            {
                flushJobs.AddUnsafely(new NarrowPhaseFlushJob {
                    Type = NarrowPhaseFlushJobType.RemoveConstraintFromTypeBatch, Index = i
                });
            }

            if (threadDispatcher == null)
            {
                for (int i = 0; i < flushJobs.Count; ++i)
                {
                    ExecuteFlushJob(ref flushJobs[i], Pool);
                }
            }
            else
            {
                flushJobIndex         = -1;
                this.threadDispatcher = threadDispatcher;
                threadDispatcher.DispatchWorkers(flushWorkerLoop);
                this.threadDispatcher = null;
            }
            //var end = Stopwatch.GetTimestamp();
            //Console.WriteLine($"Flush stage 3 time (us): {1e6 * (end - start) / Stopwatch.Frequency}");
            flushJobs.Dispose(Pool.SpecializeFor <NarrowPhaseFlushJob>());

            PairCache.Postflush();
            ConstraintRemover.Postflush();

            OnPostflush(threadDispatcher);
        }
 /// <summary>
 /// Creates duplex output channel which can send and receive messages from the duplex input channel using UDP.
 /// </summary>
 /// <remarks>
 /// It can create duplex output channels for unicast, multicast or broadcast communication.
 /// If the property UnicastCommunication is set to true then it creates the output channel for the unicast communication.
 /// It means it can send messages to one particular input channel and receive messages only from that input channel.
 /// If the property UnicastCommunication is set to false then it creates the output channel for mulitcast or broadcast communication.
 /// It means it can send mulitcast or broadcast messages which can be received by multiple input channels.
 /// It can also receive multicast and broadcast messages.<br/>
 /// <br/>
 /// This method allows to specify the id of the created output channel.
 /// <example>
 /// Creating the duplex output channel for unicast communication (e.g. for client-service communication)
 /// with a specific output channel id.
 /// <code>
 /// IMessagingSystemFactory aMessaging = new UdpMessagingSystemFactory();
 /// string aSessionId = Guid.NewGuid().ToString();
 /// IDuplexOutputChannel anOutputChannel = aMessaging.CreateDuplexOutputChannel("udp://127.0.0.1:8765/", aSessionId);
 /// </code>
 /// </example>
 /// <example>
 /// Creating the duplex output channel which can send messages to a particular UDP address and
 /// which can recieve messages on a specific UDP address and which can receive mulitcast messages.
 /// <code>
 /// IProtocolFormatter aProtocolFormatter = new EasyProtocolFormatter();
 /// IMessagingSystemFactory aMessaging = new UdpMessagingSystemFactory(aProtocolFormatter)
 /// {
 ///     // Setup the factory to create channels for mulitcast or broadcast communication.
 ///     UnicastCommunication = false,
 ///
 ///     // Specify the mulitcast group to receive messages from.
 ///     MulticastGroupToReceive = "234.4.5.6"
 /// };
 ///
 /// // Create output channel which can send messages to the input channel listening to udp://127.0.0.1:8095/
 /// // and which is listening to udp://127.0.0.1:8099/ and which can also receive messages sent for the mulitcast
 /// // group 234.4.5.6.
 /// IDuplexOutputChannel anOutputChannel = aMessaging.CreateDuplexOutputChannel("udp://127.0.0.1:8095/", "udp://127.0.0.1:8099/");
 /// </code>
 /// </example>
 /// </remarks>
 /// <param name="channelId">Identifies the receiving duplex input channel. The channel id must be a valid URI address e.g. udp://127.0.0.1:8090/</param>
 /// <param name="responseReceiverId">
 /// Unique identifier of the output channel.<br/>
 /// In unicast communication the identifier can be a string e.g. GUID which represents the session between output and input channel.<br/>
 /// In mulitcast or broadcast communication the identifier must be a valid URI address which will be used by the output channel
 /// to receive messages from input channels.<br/>
 /// <br/>
 /// If the parameter is null then in case of unicast communication a unique id is generated automatically.
 /// In case of multicast or broadcast communication the address udp://0.0.0.0:0/ is used which means the the output channel will
 /// listen to random free port on all available IP addresses.
 /// </param>
 /// <returns>duplex output channel</returns>
 public IDuplexOutputChannel CreateDuplexOutputChannel(string channelId, string responseReceiverId)
 {
     using (EneterTrace.Entering())
     {
         IThreadDispatcher       aDispatcher       = OutputChannelThreading.GetDispatcher();
         IOutputConnectorFactory aConnectorFactory = new UdpConnectorFactory(myProtocolFormatter, ReuseAddress, ResponseReceiverPort, UnicastCommunication, AllowSendingBroadcasts, Ttl, MulticastGroupToReceive, MulticastLoopback, MaxAmountOfConnections);
         return(new DefaultDuplexOutputChannel(channelId, responseReceiverId, aDispatcher, myDispatcherAfterMessageDecoded, aConnectorFactory));
     }
 }
Esempio n. 21
0
 /// <summary>
 /// Creates duplex output channel which can send and receive messages from the duplex input channel using shared memory.
 /// </summary>
 /// <param name="channelId">Identifies the input channel which shall be connected.
 /// The channel id is the name of the memory-mapped file that
 /// is used to send and receive messages.
 /// </param>
 /// <param name="responseReceiverId">Identifies the input channel which shall be connected.
 /// The channel id is the name of the memory-mapped file that
 /// is used to send and receive messages.
 /// </param>
 /// <returns>duplex output channel</returns>
 public IDuplexOutputChannel CreateDuplexOutputChannel(string channelId, string responseReceiverId)
 {
     using (EneterTrace.Entering())
     {
         IThreadDispatcher       aDispatcher = OutputChannelThreading.GetDispatcher();
         IThreadDispatcher       aDispatcherAfterMessageDecoded = myDispatchingAfterMessageDecoded.GetDispatcher();
         IOutputConnectorFactory aConnectorFactory = new SharedMemoryConnectorFactory(myProtocolFormatter, ConnectTimeout, SendTimeout, MaxMessageSize, SharedMemorySecurity);
         return(new DefaultDuplexOutputChannel(channelId, responseReceiverId, aDispatcher, aDispatcherAfterMessageDecoded, aConnectorFactory));
     }
 }
Esempio n. 22
0
 public void TestInitialize()
 {
     _mockMainView   = Substitute.For <IViewMain>();
     _mockController = new PackageControllerMockBundle().MockController;
     _mockDispatcher = Substitute.For <IThreadDispatcher>();
     _mockDispatcher.Dispatch(Arg.Invoke());
     _handler = new PackageIndexRouteHandler(_mockDispatcher, _mockMainView, _mockController);
     _package = new PackageDto(Guid.NewGuid());
     _route   = new PackageIndexRoute();
 }
Esempio n. 23
0
 /// <summary>
 /// Creates duplex output channel which can send and receive messages from the duplex input channel using HTTP.
 /// </summary>
 /// <remarks>
 /// The channel id must be a valid URI address e.g. http://127.0.0.1:8090/something/
 /// </remarks>
 /// <param name="channelId">Identifies the input channel which shall be connected. The channel id must be a valid URI address e.g. http://127.0.0.1:8090/</param>
 /// <param name="responseReceiverId">Unique identifier of the output channel. If null then the id is generated automatically.</param>
 /// <returns>duplex output channel</returns>
 public IDuplexOutputChannel CreateDuplexOutputChannel(string channelId, string responseReceiverId)
 {
     using (EneterTrace.Entering())
     {
         IThreadDispatcher       aDispatcher = OutputChannelThreading.GetDispatcher();
         IThreadDispatcher       aDispatcherAfterMessageDecoded = myDispatchingAfterMessageDecoded.GetDispatcher();
         IOutputConnectorFactory aClientConnectorFactory        = new HttpOutputConnectorFactory(myProtocolFormatter, myPollingFrequency);
         return(new DefaultDuplexOutputChannel(channelId, responseReceiverId, aDispatcher, aDispatcherAfterMessageDecoded, aClientConnectorFactory));
     }
 }
        //// ===========================================================================================================
        //// Constructors
        //// ===========================================================================================================

        protected EditorViewModel(
            ILogger logger,
            IThreadDispatcher threadDispatcher,
            IRegistryWriteService registryWriteService,
            BonusBarViewModel bonusBar)
        {
            Logger               = Param.VerifyNotNull(logger, nameof(logger));
            ThreadDispatcher     = Param.VerifyNotNull(threadDispatcher, nameof(threadDispatcher));
            RegistryWriteService = Param.VerifyNotNull(registryWriteService, nameof(registryWriteService));
            BonusBar             = Param.VerifyNotNull(bonusBar, nameof(bonusBar));
        }
Esempio n. 25
0
 /// <summary>
 ///  Creates the duplex input channel which can receive and send messages to the duplex output channel using shared memory.
 /// </summary>
 /// <param name="channelId">Address which shell be used for listening.
 /// It is the name of the memory-mapped file that will be used to send and receive messages.
 /// </param>
 /// <returns>duplex input channel</returns>
 public IDuplexInputChannel CreateDuplexInputChannel(string channelId)
 {
     using (EneterTrace.Entering())
     {
         IInputConnectorFactory aConnectorFactory = new SharedMemoryConnectorFactory(myProtocolFormatter, ConnectTimeout, SendTimeout, MaxMessageSize, SharedMemorySecurity);
         IThreadDispatcher      aThreadDispatcher = InputChannelThreading.GetDispatcher();
         IInputConnector        anInputConnector  = aConnectorFactory.CreateInputConnector(channelId);
         IThreadDispatcher      aDispatcherAfterMessageDecoded = myDispatchingAfterMessageDecoded.GetDispatcher();
         return(new DefaultDuplexInputChannel(channelId, aThreadDispatcher, aDispatcherAfterMessageDecoded, anInputConnector));
     }
 }
Esempio n. 26
0
        /// <summary>
        /// Creates the duplex output channel sending messages to the duplex input channel and receiving response messages by using WebSocket.
        /// </summary>
        /// <param name="channelId">Identifies the receiving duplex input channel. The channel id must be a valid URI address e.g. ws://127.0.0.1:8090/</param>
        /// <param name="responseReceiverId">Identifies the response receiver of this duplex output channel.</param>
        /// <returns>duplex output channel</returns>
        public IDuplexOutputChannel CreateDuplexOutputChannel(string channelId, string responseReceiverId)
        {
            using (EneterTrace.Entering())
            {
                IThreadDispatcher       aDispatcher = OutputChannelThreading.GetDispatcher();
                IOutputConnectorFactory aFactory    = new WebSocketOutputConnectorFactory(myProtocolFormatter, ClientSecurityStreamFactory,
                                                                                          (int)ConnectTimeout.TotalMilliseconds, (int)SendTimeout.TotalMilliseconds, (int)ReceiveTimeout.TotalMilliseconds,
                                                                                          (int)PingFrequency.TotalMilliseconds,
                                                                                          ResponseReceiverPort);

                return(new DefaultDuplexOutputChannel(channelId, responseReceiverId, aDispatcher, myDispatcherAfterMessageDecoded, aFactory));
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Awakens a list of set indices.
        /// </summary>
        /// <param name="setIndices">List of set indices to wake up.</param>
        /// <param name="threadDispatcher">Thread dispatcher to use when waking the bodies. Pass null to run on a single thread.</param>
        public void AwakenSets(ref QuickList <int, Buffer <int> > setIndices, IThreadDispatcher threadDispatcher = null)
        {
            QuickList <int, Buffer <int> > .Create(pool.SpecializeFor <int>(), setIndices.Count, out var uniqueSetIndices);

            var uniqueSet = new IndexSet(pool, bodies.Sets.Length);

            AccumulateUniqueIndices(ref setIndices, ref uniqueSet, ref uniqueSetIndices);
            uniqueSet.Dispose(pool);

            //Note that we use the same codepath as multithreading, we just don't use a multithreaded dispatch to execute jobs.
            //TODO: It would probably be a good idea to add a little heuristic to avoid doing multithreaded dispatches if there are only like 5 total bodies.
            //Shouldn't matter too much- the threaded variant should only really be used when doing big batched changes, so having a fixed constant cost isn't that bad.
            int threadCount = threadDispatcher == null ? 1 : threadDispatcher.ThreadCount;

            //Note that direct wakes always reset activity states. I suspect this is sufficiently universal that no one will ever want the alternative,
            //even though the narrowphase does avoid resetting activity states for the sake of faster resleeping when possible.
            var(phaseOneJobCount, phaseTwoJobCount) = PrepareJobs(ref uniqueSetIndices, true, threadCount);

            if (threadCount > 1)
            {
                this.jobIndex = -1;
                this.jobCount = phaseOneJobCount;
                threadDispatcher.DispatchWorkers(phaseOneWorkerDelegate);
            }
            else
            {
                for (int i = 0; i < phaseOneJobCount; ++i)
                {
                    ExecutePhaseOneJob(i);
                }
            }

            if (threadCount > 1)
            {
                this.jobIndex = -1;
                this.jobCount = phaseTwoJobCount;
                threadDispatcher.DispatchWorkers(phaseTwoWorkerDelegate);
            }
            else
            {
                for (int i = 0; i < phaseTwoJobCount; ++i)
                {
                    ExecutePhaseTwoJob(i);
                }
            }

            DisposeForCompletedAwakenings(ref uniqueSetIndices);

            uniqueSetIndices.Dispose(pool.SpecializeFor <int>());
        }
Esempio n. 28
0
        public void Timestep(Simulation simulation, float dt, IThreadDispatcher threadDispatcher = null)
        {
            simulation.Sleep(threadDispatcher);
            Slept?.Invoke(dt, threadDispatcher);

            simulation.IntegrateVelocitiesBoundsAndInertias(dt, threadDispatcher);
            BeforeCollisionDetection?.Invoke(dt, threadDispatcher);

            simulation.CollisionDetection(dt, threadDispatcher);
            CollisionsDetected?.Invoke(dt, threadDispatcher);


            int     count = simulation.Bodies.ActiveSet.Count;
            ref var baseConveyorSettings = ref simulation.Bodies.ActiveSet.ConveyorSettings[0];
        /// <summary>
        /// Creates duplex output channel which can send and receive messages from the duplex input channel using TCP.
        /// </summary>
        /// <remarks>
        /// <example>
        /// Creating the duplex output channel.
        /// <code>
        /// IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory();
        /// IDuplexOutputChannel anOutputChannel = aMessaging.CreateDuplexOutputChannel("tcp://127.0.0.1:8765/");
        /// </code>
        /// </example>
        /// </remarks>
        /// <param name="channelId">Identifies the input channel which shall be connected. The channel id must be a valid URI address e.g. tcp://127.0.0.1:8090/ </param>
        /// <returns>duplex output channel</returns>
        public IDuplexOutputChannel CreateDuplexOutputChannel(string channelId)
        {
            using (EneterTrace.Entering())
            {
                IThreadDispatcher       aDispatcher = OutputChannelThreading.GetDispatcher();
                IOutputConnectorFactory anOutputConnectorFactory = new TcpOutputConnectorFactory(
                    myProtocolFormatter, ClientSecurityStreamFactory,
                    (int)ConnectTimeout.TotalMilliseconds, (int)SendTimeout.TotalMilliseconds, (int)ReceiveTimeout.TotalMilliseconds,
                    SendBufferSize, ReceiveBufferSize,
                    ReuseAddress, ResponseReceiverPort);

                return(new DefaultDuplexOutputChannel(channelId, null, aDispatcher, myDispatcherAfterMessageDecoded, anOutputConnectorFactory));
            }
        }
 public DepartureBoardViewModel(ILogger <DepartureBoardViewModel> logger,
                                IThreadDispatcher threadDispatcher,
                                IStopAreaViewModelFactory stopAreaVmFactory,
                                IStopPointViewModelFactory stopPointVmFactory,
                                IDepartureViewModelFactory departureVmFactory,
                                IDeviationViewModelFactory deviationVmFactory)
 {
     this.logger             = logger;
     this.threadDispatcher   = threadDispatcher;
     this.stopAreaVmFactory  = stopAreaVmFactory;
     this.stopPointVmFactory = stopPointVmFactory;
     this.departureVmFactory = departureVmFactory;
     this.deviationVmFactory = deviationVmFactory;
 }
Esempio n. 31
0
 public UnityLogger(IThreadDispatcher dispatcher)
 {
     _dispatcher = dispatcher;
 }