/*********
        ** Public methods
        *********/

        /// <summary>The mod entry point, called after the mod is first loaded.</summary>
        /// <param name="helper">Provides simplified APIs for writing mods.</param>
        public override void Entry(IModHelper helper)
        {
            // Read config.
            this.config = new ConfigManager(this.Helper).GetConfig();

            // Create helper classes that make the mod work.
            ErrorQueue        errorQueue = new ErrorQueue(this.Monitor);
            ContentPackLoader packLoader = new ContentPackLoader(this.Helper, this.Monitor, errorQueue);

            this.serializer          = new DoorPositionSerializer(this.Helper.Data);
            this.timer               = new CallbackTimer();
            this.doorTileInfoManager = new GeneratedDoorTileInfoManager();
            this.generator           = new DoorSpriteGenerator(this.doorTileInfoManager, packLoader.LoadContentPacks(), this.Helper.Multiplayer.ModID, this.Monitor, Game1.graphics.GraphicsDevice);
            this.creator             = new DoorCreator(this.doorTileInfoManager, this.timer, errorQueue, this.Helper.ModRegistry.Get(this.Helper.ModRegistry.ModID).Manifest.Version);
            this.assetLoader         = new DoorAssetLoader(this.Helper.Content);
            this.mapTileSheetManager = new MapTileSheetManager();
            this.manager             = new DoorManager(this.config, this.OnDoorToggled);

            // Apply Harmony patches.
            BetterDoorsMod.Instance = this;
            HarmonyInstance harmony = HarmonyInstance.Create(this.Helper.ModRegistry.ModID);

            harmony.PatchAll(Assembly.GetExecutingAssembly());

            // Attach events.
            this.Enable();
            this.Helper.Events.Multiplayer.PeerContextReceived += this.Multiplayer_PeerContextReceived;
            this.Helper.Events.GameLoop.ReturnedToTitle        += this.GameLoop_ReturnedToTitle;
        }
Example #2
0
 public void StartTimer_CleanupOnDispose_NoExceptions()
 {
     using (var timer = new CallbackTimer(TimerMode.Periodic))
     {
         timer.StartTimer();
     }
 }
Example #3
0
        public void StartActiveLocationSearching()
        {
            if (isActivelySearching)
            {
                if (timer != null)
                {
                    timer.Cancel();
                    timer.Start();
                }
                return;
            }
            isActivelySearching = true;

            currentProvider = locationManager.GetBestProvider(new Criteria {
                AltitudeRequired = false,
                BearingRequired  = false,
                SpeedRequired    = false,
                Accuracy         = Accuracy.Low,
                CostAllowed      = true
            }, true);

            var cachedLocation = locationManager.GetLastKnownLocation(currentProvider);

            if (IsBetterLocation(cachedLocation, lastKnownLocation))
            {
                lastKnownLocation = cachedLocation;
            }

            locationManager.RemoveUpdates(this);
            locationManager.RequestLocationUpdates(currentProvider, 100, 3, this);
            timer = new CallbackTimer(1000 * 30, () => GetLocationAndStopActiveSearching());
            timer.Start();
        }
 /*********
 ** Public methods
 *********/
 /// <summary>Construct an instance.</summary>
 /// <param name="doorTileInfoManager">Manages information about the tiles needed to draw doors.</param>
 /// <param name="timer">Callback timer for door animations.</param>
 /// <param name="errorQueue">Error manager for reading door definitions from map files.</param>
 public DoorCreator(GeneratedDoorTileInfoManager doorTileInfoManager, CallbackTimer timer, ErrorQueue errorQueue, ISemanticVersion modVersion)
 {
     this.doorTileInfoManager = doorTileInfoManager;
     this.errorQueue          = errorQueue;
     this.timer      = timer;
     this.modVersion = modVersion;
 }
Example #5
0
        /*********
        ** Public methods
        *********/

        /// <summary>Construct an instance.</summary>
        /// <param name="position">The position the door is at.</param>
        /// <param name="property">Parsed door info.</param>
        /// <param name="map">The map the door will modify.</param>
        /// <param name="extras">Parsed door extras.</param>
        /// <param name="callbackTimer">Timer for animations.</param>
        public PendingDoor(Point position, MapDoor property, Map map, MapDoorExtras extras, CallbackTimer callbackTimer)
        {
            this.map           = map;
            this.Position      = position;
            this.Property      = property;
            this.extras        = extras;
            this.callbackTimer = callbackTimer;
        }
Example #6
0
        public void StartTimer_StopTimer_NoExceptions()
        {
            using (var timer = new CallbackTimer(TimerMode.Periodic))
            {
                timer.StartTimer();

                timer.StopTimer();
            }
        }
Example #7
0
        private CallbackTimer ScheduleOneTimeAction(TimeSpan interval, Action callback)
        {
            var ct = new CallbackTimer(interval, callback)
            {
                AutoReset = false
            };

            ct.Elapsed += oneTimeTimerElapsed;
            return(ct);
        }
Example #8
0
        private CallbackTimer SchedulePeriodicAction(TimeSpan interval, Action callback)
        {
            var ct = new CallbackTimer(interval, callback)
            {
                AutoReset = false
            };

            ct.Disposed += periodicTimerDisposed;
            ct.Elapsed  += periodicTimerElapsed;
            return(ct);
        }
Example #9
0
        public void StartTimer_OnNewInstance_StartedEventFires()
        {
            using (var timer = new CallbackTimer(TimerMode.Periodic))
            {
                bool eventFired = false;
                timer.Started += (sender, e) => { eventFired = true; };
                timer.StartTimer();

                eventFired.Should().BeTrue();
            }
        }
Example #10
0
        public void StopTimer_OnNewInstance_StoppedEventFires()
        {
            using (var timer = new CallbackTimer(TimerMode.Periodic))
            {
                bool eventFired = false;
                timer.Stopped += (sender, e) => { eventFired = true; };

                timer.StartTimer();
                timer.StopTimer();

                Assert.IsTrue(eventFired);
            }
        }
Example #11
0
        public void StartTimer_WithShortWait_CallbackFired()
        {
            bool callback = false;

            using (var timer = new CallbackTimer(TimerMode.Periodic))
            {
                timer.Callback += (sender, e) => { callback = true; };
                timer.StartTimer();

                Thread.Sleep(50);

                callback.Should().BeTrue();
            }
        }
    void OnGUI()
    {
        initConfiguration();

        // Game Settings

        SlimNetGUILayout.Label("Game", EditorStyles.boldLabel);

        ccfg.GameName           = scfg.GameName = SlimNetGUILayout.TextField("Name", ccfg.GameName);
        ccfg.SimulationAccuracy = scfg.SimulationAccuracy = SlimNetGUILayout.IntSlider("Tick Rate (ms)", ccfg.SimulationAccuracy, 10, 1000);

        // Log settings

        SlimNetGUILayout.Label("Logging", EditorStyles.boldLabel);
        editLogging();

        // Network Settings

        SlimNetGUILayout.Label("Network Simulation (Debug Only)", EditorStyles.boldLabel);

        ccfg.LidgrenSimulatedLoss          = scfg.LidgrenSimulatedLoss = SlimNetGUILayout.PercentSlider("Packet Loss (%)", ccfg.LidgrenSimulatedLoss);
        ccfg.LidgrenSimulatedLatency       = scfg.LidgrenSimulatedLatency = SlimNetGUILayout.MillisecondSlider("Base Latency (ms)", ccfg.LidgrenSimulatedLatency);
        ccfg.LidgrenSimulatedRandomLatency = scfg.LidgrenSimulatedRandomLatency = SlimNetGUILayout.MillisecondSlider("Jitter (ms)", ccfg.LidgrenSimulatedRandomLatency);

        // Server Settings

        SlimNetGUILayout.Label("Server", EditorStyles.boldLabel);

        scfg.ServerMode = SlimNetGUILayout.EnumPopup("Server Mode", scfg.ServerMode);

        // Send buffering for server
        scfg.SendBuffering = SlimNetGUILayout.IntSlider("Send Buffering (ms)", (int)scfg.SendBuffering, 0, 100);

        if (GUI.changed)
        {
            CallbackTimer.SetTimer("writeconfig", DateTime.Now.AddSeconds(1), () =>
            {
                string ccfgSerialized = Utils.Serialize(ccfg);
                string scfgSerialized = Utils.Serialize(scfg);

                SlimNet.Unity.Editor.Utils.WriteTextAsset(SlimNet.Unity.Constants.ClientConfigAssetPath, ccfgSerialized);
                SlimNet.Unity.Editor.Utils.WriteTextAsset(SlimNet.Unity.Constants.ServerConfigAssetPath, scfgSerialized);

                WriteCopy(SlimNet.Constants.ServerConfigNameXml, scfgSerialized);
            });
        }
    }
Example #13
0
        public ActionTimer(ILog log, TimeSpan interval, Action callback, bool oneTime, bool startImmediately)
        {
            this.log = log;

            if (oneTime)
            {
                this.callbackTimer = ScheduleOneTimeAction(interval, callback);
            }
            else
            {
                this.callbackTimer = SchedulePeriodicAction(interval, callback);
            }

            if (startImmediately)
            {
                this.callbackTimer.SetEnabled();
            }
        }
Example #14
0
        public ActionTimer(ILog log, TimeSpan interval, Action callback, bool oneTime, bool startImmediately)
        {
            this.log = log;

            if (oneTime)
            {
                this.callbackTimer = ScheduleOneTimeAction(interval, callback);
            }
            else
            {
                this.callbackTimer = SchedulePeriodicAction(interval, callback);
            }

            if (startImmediately)
            {
                this.callbackTimer.SetEnabled();
            }
        }
Example #15
0
        public void AddTwoHandlers_UseHighDivider_CallbacksFired()
        {
            int callback1Count = 0;
            int callback2Count = 0;
            int divider        = 200;

            using (var timer = new CallbackTimer(TimerMode.Periodic))
            {
                timer.AddCallbackHandler((sender, e) => { callback1Count++; }, 1, null);
                timer.AddCallbackHandler((sender, e) => { callback2Count++; }, divider, null);
                timer.StartTimer();

                Thread.Sleep(500);

                Assert.AreNotEqual(0, callback1Count);
                Assert.AreNotEqual(0, callback2Count);
                Assert.AreEqual(callback1Count / divider, callback2Count);
            }
        }
Example #16
0
        public void AddTwoHandlers_UseHighDivider_CallbacksFired()
        {
            int callback1Count = 0;
            int callback2Count = 0;
            int divider        = 200;

            using (var timer = new CallbackTimer(TimerMode.Periodic))
            {
#if NET4
                timer.AddCallbackHandler((sender, e) => { callback1Count++; }, 1, null);
                timer.AddCallbackHandler((sender, e) => { callback2Count++; }, divider, null);
#else
                timer.AddCallbackHandler((sender, e) => { callback1Count++; }, 1);
                timer.AddCallbackHandler((sender, e) => { callback2Count++; }, divider);
#endif
                timer.StartTimer();

                Thread.Sleep(500);

                callback1Count.Should().BeGreaterThan(0);
                callback2Count.Should().BeGreaterThan(0);
                callback2Count.Should().Be(callback1Count / divider);
            }
        }
Example #17
0
        public void StartActiveLocationSearching()
        {
            if (isActivelySearching) {
                if (timer != null) {
                    timer.Cancel ();
                    timer.Start ();
                }
                return;
            }
            isActivelySearching = true;

            currentProvider = locationManager.GetBestProvider (new Criteria {
                AltitudeRequired = false,
                BearingRequired = false,
                SpeedRequired = false,
                Accuracy = Accuracy.Low,
                CostAllowed = true
            }, true);

            var cachedLocation = locationManager.GetLastKnownLocation (currentProvider);
            if (IsBetterLocation (cachedLocation, lastKnownLocation))
                lastKnownLocation = cachedLocation;

            locationManager.RemoveUpdates (this);
            locationManager.RequestLocationUpdates (currentProvider, 100, 3, this);
            timer = new CallbackTimer (1000 * 30, () => GetLocationAndStopActiveSearching ());
            timer.Start ();
        }
Example #18
0
 private CallbackTimer SchedulePeriodicAction(TimeSpan interval, Action callback)
 {
     var ct = new CallbackTimer(interval, callback) { AutoReset = false };
     ct.Disposed += periodicTimerDisposed;
     ct.Elapsed += periodicTimerElapsed;
     return ct;
 }
Example #19
0
 private CallbackTimer ScheduleOneTimeAction(TimeSpan interval, Action callback)
 {
     var ct = new CallbackTimer(interval, callback) { AutoReset = false };
     ct.Elapsed += oneTimeTimerElapsed;
     return ct;
 }
Example #20
0
        /// <summary>
        /// 지정한 시간 이후에 일정 주기마다 콜백을 실행시킨다.
        /// 콜백은 SafeThread에서 실행이 보장된다.
        /// [Thread-Safe]
        /// </summary>
        /// <param name="callback">콜백</param>
        /// <param name="interval">실행 주기</param>
        /// <param name="after">미룰 시간</param>
        /// <param name="count">반복할 횟수</param>
        /// <returns>취소 토큰</returns>
        public CancellationTokenSource Schedule(Action callback, long interval, long after = 0, long count = 0)
        {
            //if (!Server.isSafeThread)
            //    throw new InvalidOperationException();

            Server.current.logger.Debug("Schedule interval({0}), after({1}), count({2})", interval, after, count);

            var cts = new CancellationTokenSource();
            var timer = new CallbackTimer(callback, cts.Token);
            timer.interval = interval;
            timer.count = count;
            timer.start = Environment.TickCount + after;
            pendingTimers.Enqueue(timer);

            return cts;
        }