internal ContextRuntime GetRootContext()
        {
            if (_rootContext == null)
            {
                _rootContext = new ContextRuntime(_rootServiceInjector, _rootContextConfiguration, Optional <ContextRuntime> .Empty());
            }

            return(_rootContext);
        }
Esempio n. 2
0
        public VehicleModel()
        {
            InteractiveChildIdentifiers = Optional <List <InteractiveChildObjectIdentifier> > .Empty();

            DockingBayGuid = Optional <string> .Empty();
        }
Esempio n. 3
0
 /// <summary>
 /// Constructs a {@code TerminalOp} for streams of objects.
 /// </summary>
 /// @param <T> the type of elements of the stream </param>
 /// <param name="mustFindFirst"> whether the {@code TerminalOp} must produce the
 ///        first element in the encounter order </param>
 /// <returns> a {@code TerminalOp} implementing the find operation </returns>
 public static TerminalOp <T, Optional <T> > makeRef <T>(bool mustFindFirst)
 {
     return(new FindOp <>(mustFindFirst, StreamShape.REFERENCE, Optional.Empty(), Optional::isPresent, FindSink.OfRef::new));
 }
Esempio n. 4
0
        public static VehicleModel BuildFrom(ConstructorBeginCrafting packet)
        {
            switch (packet.TechType.Enum())
            {
            case TechType.Seamoth:
                return(new SeamothModel(packet.TechType, packet.ConstructedItemId, packet.Position, packet.Rotation, Optional <List <InteractiveChildObjectIdentifier> > .OfNullable(packet.InteractiveChildIdentifiers), Optional <NitroxId> .Empty(), packet.Name, packet.HSB, packet.Colours));

            case TechType.Exosuit:
                return(new ExosuitModel(packet.TechType, packet.ConstructedItemId, packet.Position, packet.Rotation, Optional <List <InteractiveChildObjectIdentifier> > .OfNullable(packet.InteractiveChildIdentifiers), Optional <NitroxId> .Empty(), packet.Name, packet.HSB, packet.Colours));

            case TechType.Cyclops:
                return(new CyclopsModel(packet.TechType, packet.ConstructedItemId, packet.Position, packet.Rotation, Optional <List <InteractiveChildObjectIdentifier> > .OfNullable(packet.InteractiveChildIdentifiers), Optional <NitroxId> .Empty(), packet.Name, packet.HSB, packet.Colours));

            case TechType.RocketBase:
                return(null);

            default:
                throw new Exception("Could not build from: " + packet.TechType);
            }
        }
Esempio n. 5
0
        public static Optional <T> GetItemAs <T>(string name) where T : ItemAsset
        {
            var optItem = GetItem(name);

            return(optItem.IsPresent ? Optional <T> .Of(optItem.Value as T) : Optional <T> .Empty());
        }
Esempio n. 6
0
        protected override void Load()
        {
            try {
                var stopwatch = Stopwatch.StartNew();

                Instance = this;

                try {
                    var essPermProvider = new EssentialsPermissionsProvider();
                    R.Permissions = essPermProvider;
                } catch (Exception ex) {
                    Console.Error.WriteLine(ex);
                }

                TaskExecutor = new EssentialsTaskExecutor();

                Logger           = new ConsoleLogger("[uEssentials] ");
                ConnectedPlayers = new Dictionary <ulong, UPlayer>();
                Debug.Listeners.Add(new EssentialsConsoleTraceListener());

                Provider.onServerDisconnected += PlayerDisconnectCallback;
                Provider.onServerConnected    += PlayerConnectCallback;

                Logger.LogInfo("Enabling uEssentials...");

                if (Provider.Players.Count > 0)
                {
                    Provider.Players.ForEach(p => {
                        ConnectedPlayers.Add(p.SteamPlayerID.CSteamID.m_SteamID,
                                             new UPlayer(UnturnedPlayer.FromSteamPlayer(p)));
                    });
                }

                _folder            = Rocket.Core.Environment.PluginsDirectory + "/uEssentials/";
                _translationFolder = Folder + "translations/";
                _dataFolder        = Folder + "data/";
                _modulesFolder     = Folder + "modules/";

                WebResources = new WebResources();
                Config       = new EssConfig();

                var webRscPath = Path.Combine(Folder, WebResources.FileName);
                var configPath = Path.Combine(Folder, Config.FileName);

                WebResources.Load(webRscPath);

                // TODO: Remove
                // Load old webkit/webconfig
                try {
                    if (File.Exists(configPath) && !WebResources.Enabled)
                    {
                        var json = JObject.Parse(File.ReadAllText(configPath));
                        var save = false;

                        foreach (var opt in new[] { "Config", "Kits" })
                        {
                            JToken val;
                            if (json.TryGetValue($"Web{opt}", out val))
                            {
                                if (val.Value <bool>("Enabled"))
                                {
                                    WebResources.Enabled   = true;
                                    WebResources.URLs[opt] = val.Value <string>("Url");
                                    save = true;
                                }
                            }
                        }

                        if (save)
                        {
                            WebResources.Save(webRscPath);
                            WebResources.Load(webRscPath);
                        }
                    }
                } catch (Exception ex) {
                    Debug.Print(ex.ToString());
                }

                // Sync web config with local config.json
                if (WebResources.Loaded.ContainsKey("Config"))
                {
                    File.WriteAllText(configPath, WebResources.Loaded["Config"]);
                }

                Config.Load(configPath);

                CommandOptions = new CommandOptions();
                CommandOptions.Load(Path.Combine(Folder, CommandOptions.FileName));

                Updater        = new GithubUpdater();
                EventManager   = new EventManager();
                CommandManager = new CommandManager();
                ModuleManager  = new ModuleManager();
                HookManager    = new HookManager();

                EssLang.Load();

                new [] {
                    "Plugin version: ~white~" + PLUGIN_VERSION + BUILD_INFO,
                    "Recommended Rocket version: ~white~" + ROCKET_VERSION,
                    "Recommended Unturned version: ~white~" + UNTURNED_VERSION,
                    "Author: ~white~leonardosnt",
                    "Wiki: ~white~uessentials.github.io",
                }.ForEach(text => Logger.LogInfo(text, true));

                EventManager.RegisterAll(GetType().Assembly);

                if (!Config.EnableJoinLeaveMessage)
                {
                    EventManager.Unregister <EssentialsEventHandler>("JoinMessage");
                    EventManager.Unregister <EssentialsEventHandler>("LeaveMessage");
                }

                CommandManager.RegisterAll("Essentials.Commands");

                HookManager.RegisterAll();
                HookManager.LoadAll();

                if (Config.Economy.UseXp)
                {
                    EconomyProvider = Optional <IEconomyProvider> .Of(new ExpEconomyProvider());
                }
                else if (HookManager.GetActiveByType <UconomyHook>().IsPresent)
                {
                    EconomyProvider = Optional <IEconomyProvider> .Of(HookManager.GetActiveByType <UconomyHook>().Value);
                }
                else
                {
                    EconomyProvider = Optional <IEconomyProvider> .Empty();
                }

                /*
                 *  Load native modules
                 */
                Assembly.GetTypes()
                .Where(t => typeof(NativeModule).IsAssignableFrom(t))
                .WhereNot(t => t.IsAbstract)
                .Where(t => {
                    var moduleInfo = (ModuleInfo)t.GetCustomAttributes(typeof(ModuleInfo), false)[0];
                    return(Config.EnabledSystems.Any(s => s.Equals(moduleInfo.Name, StringComparison.OrdinalIgnoreCase)));
                })
                .ForEach(t => {
                    ModuleManager.LoadModule((NativeModule)Activator.CreateInstance(t));
                });

                Logger.LogInfo($"Loaded {CommandManager.Commands.Count()} commands");

                Logger.LogInfo("Loading modules...");
                ModuleManager.LoadAll(ModulesFolder);
                Logger.LogInfo($"Loaded {ModuleManager.RunningModules.Count(t => !(t is NativeModule))} modules");

                if (Config.AutoAnnouncer.Enabled)
                {
                    Config.AutoAnnouncer.Start();
                }

                if (Config.AutoCommands.Enabled)
                {
                    Config.AutoCommands.Start();
                }

                if (!Config.Updater.AlertOnJoin)
                {
                    EventManager.Unregister <EssentialsEventHandler>("UpdateAlert");
                }

                if (Config.ServerFrameRate != -1)
                {
                    var frameRate = Config.ServerFrameRate;

                    if (Config.ServerFrameRate < -1)
                    {
                        frameRate = -1; // Set to default
                    }

                    UnityEngine.Application.targetFrameRate = frameRate;
                }

                if (Config.DisabledCommands.Count != 0)
                {
                    Config.DisabledCommands.ForEach(cmdName => {
                        var command = CommandManager.GetByName(cmdName);

                        if (command == null || command is CommandEssentials)
                        {
                            Logger.LogWarning($"There is no command named '{cmdName}' to disable.");
                        }
                        else
                        {
                            CommandManager.Unregister(command);
                            Logger.LogInfo($"Disabled command: '{command.Name}'");
                        }
                    });
                }

                if (Config.EnableTextCommands)
                {
                    TextCommands = new TextCommands();

                    var textCommandsFile = Path.Combine(Folder, TextCommands.FileName);

                    TextCommands.Load(textCommandsFile);

                    TextCommands.Commands.ForEach(txtCommand => {
                        CommandManager.Register(new TextCommand(txtCommand));
                    });
                }

                if (!Config.EnableDeathMessages)
                {
                    EventManager.Unregister <EssentialsEventHandler>("DeathMessages");
                }

#if EXPERIMENTAL
                Logger.LogWarning("THIS IS AN EXPERIMENTAL BUILD, CAN BE BUGGY.");
                Logger.LogWarning("THIS IS AN EXPERIMENTAL BUILD, CAN BE BUGGY.");
#endif

                Task.Create()
                .Id("Delete Xml Files")
                .Delay(TimeSpan.FromSeconds(1))
                .Async()
                .Action(() => {
                    File.Delete($"{Folder}uEssentials.en.translation.xml");
                    File.Delete($"{Folder}uEssentials.configuration.xml");
                })
                .Submit();

                Task.Create()
                .Id("Unregister Rocket Commands")
                .Delay(TimeSpan.FromSeconds(3))
                .Action(() => UnregisterRocketCommands(true))     // Second check, silently.
                .Submit();

                CommandWindow.ConsoleInput.onInputText += ReloadCallback;
                UnregisterRocketCommands(); // First check.
                Logger.LogInfo($"Enabled ({stopwatch.ElapsedMilliseconds} ms)");
            } catch (Exception e) {
                var msg = new List <string>()
                {
                    "An error occurred while enabling uEssentials.",
                    "If this error is not related with wrong configuration please report",
                    "immediatly here https://github.com/uEssentials/uEssentials/issues",
                    "Error: " + e
                };

                if (!Provider.APP_VERSION.EqualsIgnoreCase(UNTURNED_VERSION))
                {
                    msg.Add("I detected that you are using a different version of the recommended, " +
                            "please update your uEssentials/Unturned.");
                    msg.Add("If you are using the latest uEssentials release, please wait for update.");
                }

                if (Logger == null)
                {
                    Console.BackgroundColor = ConsoleColor.Red;
                    msg.ForEach(Console.WriteLine);
                    Console.BackgroundColor = ConsoleColor.White;
                }
                else
                {
                    msg.ForEach(Logger.LogError);
                }
            }

#if !DEV
            TriggerGaData($"Server/{Parser.getIPFromUInt32(Provider.ip)}");
#endif

#if DEV
            CommandWindow.ConsoleOutput.title = "Unturned Server";
#else
            CheckUpdates();
#endif
        }
 public void OneTest()
 {
     Assert.AreEqual(Unit.INSTANCE, Lrl(One())(Unit.INSTANCE));
     Assert.AreEqual(Optional <Void> .Empty(), Rlr(One())(Optional <Void> .Empty()));
 }
Esempio n. 8
0
            private TestTaskEventHandler()
            {
                StartInvoked = Optional <string> .Empty();

                StopInvoked = Optional <string> .Empty();
            }
Esempio n. 9
0
        public override void Append <TSource, TSnapshotState>(string streamName, int streamVersion, TSource source, Metadata metadata, IAppendResultInterest interest, object @object)
        {
            var entry = _entryAdapterProvider.AsEntry <TSource, TEntry>(source, metadata);

            Insert(streamName, streamVersion, entry);
            Dispatch(streamName, streamVersion, new List <TEntry> {
                entry
            }, null);
            interest.AppendResultedIn(Success.Of <StorageException, Result>(Result.Success), streamName, streamVersion, source, Optional.Empty <TSnapshotState>(), @object);
        }
Esempio n. 10
0
 public DriverMessageImpl()
 {
     _value = Optional <byte[]> .Empty();
 }
 public override void Process(ConstructorBeginCrafting packet, Player player)
 {
     vehicleData.AddVehicle(new VehicleModel(packet.TechType, packet.ConstructedItemGuid, packet.Position, packet.Rotation, Optional <List <InteractiveChildObjectIdentifier> > .OfNullable(packet.InteractiveChildIdentifiers), Optional <string> .Empty(), packet.Name, packet.HSB, packet.Colours));
     playerManager.SendPacketToOtherPlayers(packet, player);
 }
Esempio n. 12
0
        private void MouseTimerTick(MultiplayerClient client)
        {
            int curX = System.Windows.Forms.Cursor.Position.X;
            int curY = System.Windows.Forms.Cursor.Position.Y;

            if (lastX != -1)
            {
                float   velX     = curX - lastX;
                float   velY     = curY - lastY;
                Vector3 velocity = new Vector3(velX / 10f, 0, velY / 10f);
                client.ClientPos += velocity;
                client.Logic.Player.UpdateLocation(client.ClientPos, velocity, Quaternion.identity, Quaternion.identity, Optional <VehicleModel> .Empty(), Optional <string> .Empty());
            }
            lastX = curX;
            lastY = curY;
        }
        /// <summary>
        /// Create a relation from a CoNLL format like:
        /// <pre>
        /// word_index  word  parent_index  incoming_relation
        /// </pre>
        /// </summary>
        protected internal virtual Optional <RelationTriple> MkExtraction(string conll, int listIndex, bool allNominals)
        {
            Pair <SemanticGraph, IList <CoreLabel> > info = MkTree(conll);
            SemanticGraph     tree     = info.first;
            IList <CoreLabel> sentence = info.second;
            // Run extractor
            Optional <RelationTriple> segmented = new RelationTripleSegmenter(allNominals).Segment(tree, Optional.Empty());

            if (segmented.IsPresent() && listIndex == 0)
            {
                return(segmented);
            }
            IList <RelationTriple> extracted = new RelationTripleSegmenter(allNominals).Extract(tree, sentence);

            if (extracted.Count > listIndex)
            {
                return(Optional.Of(extracted[listIndex - (segmented.IsPresent() ? 1 : 0)]));
            }
            return(Optional.Empty());
        }
Esempio n. 14
0
 /// <summary>
 /// Triggers a <see cref="CyclopsDamage"/> packet
 /// </summary>
 public void OnCreateDamagePoint(SubRoot subRoot)
 {
     BroadcastDamageState(subRoot, Optional <DamageInfo> .Empty());
 }
 public static void Postfix(ExosuitGrapplingArm __instance, GrapplingHook ___hook)
 {
     // We send the hook direction to the other player so he sees where the other player exosuit is heading
     NitroxServiceLocator.LocateService <ExosuitModuleEvent>().BroadcastArmAction(TechType.ExosuitGrapplingArmModule, __instance, ExosuitArmAction.startUseTool, Optional <Vector3> .Of(___hook.rb.velocity), Optional <Quaternion> .Empty());
 }
Esempio n. 16
0
        public override void AppendAll <TSource, TSnapshotState>(string streamName, int fromStreamVersion, IEnumerable <TSource> sources, Metadata metadata, IAppendResultInterest interest, object @object)
        {
            var sourcesForEntries   = sources.ToList();
            var entries             = _entryAdapterProvider.AsEntries <TSource, TEntry>(sourcesForEntries, metadata);
            var dispatchableEntries = entries.ToList();

            Insert(streamName, fromStreamVersion, dispatchableEntries);

            Dispatch(streamName, fromStreamVersion, dispatchableEntries, null);
            interest.AppendAllResultedIn(Success.Of <StorageException, Result>(Result.Success), streamName, fromStreamVersion, sourcesForEntries, Optional.Empty <TSnapshotState>(), @object);
        }
Esempio n. 17
0
 public ExitCommand() : base("exit", Optional <string> .Empty(), "Exits the server", new[] { "stop", "halt", "quit", "abort" })
 {
 }
Esempio n. 18
0
        public void TestContextStackingDoesNotGetSameInstance()
        {
            var serviceInjector = TangFactory.GetTang().NewInjector();
            var contextConfig   = GetContextEventHandlerContextConfiguration();

            using (var contextRuntime = new ContextRuntime(serviceInjector, contextConfig, Optional <ContextRuntime> .Empty()))
            {
                var childContextConfiguration = GetContextEventHandlerContextConfiguration();
                using (var childContextRuntime = contextRuntime.SpawnChildContext(childContextConfiguration))
                {
                    Assert.False(ReferenceEquals(
                                     contextRuntime.ContextInjector.GetInstance <TestContextEventHandler>(),
                                     childContextRuntime.ContextInjector.GetInstance <TestContextEventHandler>()));
                }
            }
        }
 public void IsoOptionalTest()
 {
     Assert.IsFalse(SubStL(IsoOptional(tISO))(Optional <bool> .Empty()).IsPresent());
     Assert.AreEqual(MEOW, SubStL(IsoOptional(tISO))(Optional <bool> .From(true)).Get());
 }
Esempio n. 20
0
        public void TestContextStackingParentContext()
        {
            var serviceInjector = TangFactory.GetTang().NewInjector();
            var contextConfig   = GetSimpleContextConfiguration();

            using (var contextRuntime = new ContextRuntime(serviceInjector, contextConfig, Optional <ContextRuntime> .Empty()))
            {
                var childContextConfiguration = GetSimpleContextConfiguration();
                using (var childContextRuntime = contextRuntime.SpawnChildContext(childContextConfiguration))
                {
                    Assert.False(contextRuntime.ParentContext.IsPresent());
                    Assert.True(childContextRuntime.ParentContext.IsPresent());
                    Assert.True(ReferenceEquals(contextRuntime, childContextRuntime.ParentContext.Value));
                }
            }
        }
    public void PlusTest()
    {
        var val = new Random(DateTime.Now.Millisecond).Next();

        Assert.AreEqual(Either <Void, string> .Right(str), Lrl(PlusO <string>())(Either <Void, string> .Right(str)));
        Assert.AreEqual(str, Rlr(PlusO <string>())(str));
        Assert.AreEqual(Either <Optional <string>, int> .Left(Optional <string> .From(str)),
                        Lrl(PlusS <string, int>())(Either <Optional <string>, int> .Left(Optional <string> .From(str))));
        Assert.AreEqual(Either <Optional <string>, int> .Left(Optional <string> .Empty()),
                        Lrl(PlusS <string, int>())(Either <Optional <string>, int> .Left(Optional <string> .Empty())));
        Assert.AreEqual(Either <Optional <string>, int> .Right(val),
                        Lrl(PlusS <string, int>())(Either <Optional <string>, int> .Right(val)));
        Assert.AreEqual(Optional <Either <string, int> > .From(Either <string, int> .Left(str)),
                        Rlr(PlusS <string, int>())(Optional <Either <string, int> > .From(Either <string, int> .Left(str))));
        Assert.AreEqual(Optional <Either <string, int> > .From(Either <string, int> .Right(val)),
                        Rlr(PlusS <string, int>())(Optional <Either <string, int> > .From(Either <string, int> .Right(val))));
        Assert.AreEqual(Optional <Either <string, int> > .Empty(),
                        Rlr(PlusS <string, int>())(Optional <Either <string, int> > .Empty()));
        Assert.AreEqual(Either <Unit, int> .Left(Unit.INSTANCE), Lrl(PlusSO_ <int>())(Either <Unit, int> .Left(Unit.INSTANCE)));
        Assert.AreEqual(Either <Unit, int> .Right(val), Lrl(PlusSO_ <int>())(Either <Unit, int> .Right(val)));
        Assert.AreEqual(Optional <int> .Empty(), Rlr(PlusSO_ <int>())(Optional <int> .Empty()));
        Assert.AreEqual(val, Rlr(PlusSO_ <int>())(Optional <int> .From(val)).Get());
        Assert.AreEqual(Either <Unit, int> .Left(Unit.INSTANCE), Lrl(PlusSO <int>())(Either <Unit, int> .Left(Unit.INSTANCE)));
        Assert.AreEqual(Either <Unit, int> .Right(val), Lrl(PlusSO <int>())(Either <Unit, int> .Right(val)));
        Assert.AreEqual(Optional <int> .Empty(), Rlr(PlusSO <int>())(Optional <int> .Empty()));
        Assert.AreEqual(val, Rlr(PlusSO <int>())(Optional <int> .From(val)).Get());
    }
Esempio n. 22
0
        public void TestUnableToRunMultipleTasksAtTheSameTime()
        {
            var serviceInjector = TangFactory.GetTang().NewInjector();
            var contextConfig   = GetSimpleContextConfiguration();

            using (var contextRuntime = new ContextRuntime(serviceInjector, contextConfig, Optional <ContextRuntime> .Empty()))
            {
                var taskConfig = TaskConfiguration.ConfigurationModule
                                 .Set(TaskConfiguration.Task, GenericType <TestTask> .Class)
                                 .Set(TaskConfiguration.Identifier, "ID")
                                 .Build();

                Thread taskThread = null;

                try
                {
                    var hbMgr = Substitute.For <IHeartBeatManager>();
                    contextRuntime.ContextInjector.BindVolatileInstance(GenericType <IHeartBeatManager> .Class, hbMgr);
                    taskThread = contextRuntime.StartTaskOnNewThread(taskConfig);

                    Assert.True(contextRuntime.TaskRuntime.IsPresent());
                    Assert.True(contextRuntime.GetTaskStatus().IsPresent());

                    // wait for the task to start
                    var testTask = contextRuntime.TaskRuntime.Value.Task as TestTask;
                    testTask.StartEvent.Wait();
                    Assert.Equal(State.RUNNING, contextRuntime.GetTaskStatus().Value.state);

                    Assert.Throws <InvalidOperationException>(() => contextRuntime.StartTaskOnNewThread(taskConfig));
                }
                finally
                {
                    var testTask = contextRuntime.TaskRuntime.Value.Task as TestTask;
                    if (testTask == null)
                    {
                        throw new Exception();
                    }

                    testTask.CountDownEvent.Signal();
                    if (taskThread != null)
                    {
                        taskThread.Join();
                    }
                }
            }
        }
Esempio n. 23
0
        public static Optional <T> GetItemAs <T>(ushort id) where T : ItemAsset
        {
            var optItem = GetItem(id);

            return(optItem.IsPresent ? Optional <T> .Of(optItem.Value as T) : Optional <T> .Empty());
        }
Esempio n. 24
0
        public void TestTwoSuccessiveTasksOnSameContext()
        {
            var serviceInjector = TangFactory.GetTang().NewInjector();
            var contextConfig   = GetSimpleContextConfiguration();

            using (var contextRuntime = new ContextRuntime(serviceInjector, contextConfig, Optional <ContextRuntime> .Empty()))
            {
                var taskConfig = TaskConfiguration.ConfigurationModule
                                 .Set(TaskConfiguration.Task, GenericType <TestTask> .Class)
                                 .Set(TaskConfiguration.OnTaskStop, GenericType <TestTask> .Class)
                                 .Set(TaskConfiguration.Identifier, "ID")
                                 .Build();

                var hbMgr = Substitute.For <IHeartBeatManager>();
                contextRuntime.ContextInjector.BindVolatileInstance(GenericType <IHeartBeatManager> .Class, hbMgr);

                var taskThread = contextRuntime.StartTaskOnNewThread(taskConfig);
                var testTask   = contextRuntime.TaskRuntime.Value.Task as TestTask;
                if (testTask == null)
                {
                    throw new Exception();
                }

                testTask.StartEvent.Wait();
                testTask.CountDownEvent.Signal();
                testTask.StopEvent.Wait();
                taskThread.Join();

                Assert.False(contextRuntime.GetTaskStatus().IsPresent());

                taskThread = contextRuntime.StartTaskOnNewThread(taskConfig);
                var secondTestTask = contextRuntime.TaskRuntime.Value.Task as TestTask;
                if (secondTestTask == null)
                {
                    throw new Exception();
                }

                secondTestTask.StartEvent.Wait();
                Assert.Equal(contextRuntime.GetTaskStatus().Value.state, State.RUNNING);

                Assert.False(ReferenceEquals(testTask, secondTestTask));

                secondTestTask.CountDownEvent.Signal();
                secondTestTask.StopEvent.Wait();
                taskThread.Join();

                Assert.False(contextRuntime.GetTaskStatus().IsPresent());
                secondTestTask.DisposedEvent.Wait();
            }
        }
Esempio n. 25
0
 public VehicleModel()
 {
     InteractiveChildIdentifiers = Optional <List <InteractiveChildObjectIdentifier> > .Empty();
 }
Esempio n. 26
0
        public void TestContextBindServiceBoundInterfaceThrowsException()
        {
            var boundTestServiceConfig = TangFactory.GetTang()
                                         .NewConfigurationBuilder()
                                         .BindImplementation(GenericType <ITestService> .Class, GenericType <TestService> .Class)
                                         .Build();

            var serviceConfiguration = ServiceConfiguration.ConfigurationModule.Build();
            var serviceInjector      = TangFactory.GetTang().NewInjector(Configurations.Merge(serviceConfiguration, boundTestServiceConfig));
            var contextConfig        = Configurations.Merge(GetContextEventHandlerContextConfiguration(), boundTestServiceConfig);

            var ex = Record.Exception(() => new ContextRuntime(serviceInjector, contextConfig, Optional <ContextRuntime> .Empty()));

            // This should throw an Exception because we are binding the interface ITestService twice, once in serviceConfiguration
            // and once in contextConfiguration. The Context injector is forked from the ServiceInjector, which already has the
            // interface bound.
            Assert.True(ex != null);
        }
Esempio n. 27
0
        public void TestIfPresent3()
        {
            Optional <string> test = Optional <string> .Empty();

            test.IfPresent(() => Assert.Fail()).OrElse(() => Assert.Pass());
        }
Esempio n. 28
0
        public void TestBaseServiceWithContextStacking()
        {
            var serviceConfiguration = ServiceConfiguration.ConfigurationModule
                                       .Set(ServiceConfiguration.Services, GenericType <TestService> .Class)
                                       .Build();

            var serviceInjector = TangFactory.GetTang().NewInjector(serviceConfiguration);
            var contextConfig   = GetContextEventHandlerContextConfiguration();

            using (var contextRuntime = new ContextRuntime(serviceInjector, contextConfig, Optional <ContextRuntime> .Empty()))
            {
                var childContextConfiguration = ContextConfiguration.ConfigurationModule
                                                .Set(ContextConfiguration.Identifier, "Context2")
                                                .Build();

                using (var childContextRuntime = contextRuntime.SpawnChildContext(childContextConfiguration))
                {
                    var servicesFromInjector = serviceInjector.GetNamedInstance <ServicesSet, ISet <object> >();

                    // Check that parent service injector does not contain instances of SecondTestService
                    Assert.False(servicesFromInjector.OfType <SecondTestService>().Any());

                    var contextTestService = childContextRuntime.ContextInjector.GetInstance <TestService>();
                    Assert.True(ReferenceEquals(contextTestService, serviceInjector.GetInstance <TestService>()));
                }
            }
        }
Esempio n. 29
0
 public void TestThatAFailedOutcomeIsTransformedToAnEmptyOptional()
 => Assert.Equal(
     Optional.Empty <int>(),
     Failure.Of <Exception, int>(RandomException()).AsOptional());
Esempio n. 30
0
        private Optional <VehicleModel> GetVehicleModel()
        {
            Vehicle vehicle = Player.main.GetVehicle();
            SubRoot sub     = Player.main.GetCurrentSub();

            string     guid;
            Vector3    position;
            Quaternion rotation;
            Vector3    velocity;
            Vector3    angularVelocity;
            TechType   techType;
            float      steeringWheelYaw = 0f, steeringWheelPitch = 0f;
            bool       appliedThrottle = false;

            if (vehicle != null)
            {
                guid     = GuidHelper.GetGuid(vehicle.gameObject);
                position = vehicle.gameObject.transform.position;
                rotation = vehicle.gameObject.transform.rotation;
                techType = CraftData.GetTechType(vehicle.gameObject);

                Rigidbody rigidbody = vehicle.gameObject.GetComponent <Rigidbody>();

                velocity        = rigidbody.velocity;
                angularVelocity = rigidbody.angularVelocity;

                // Required because vehicle is either a SeaMoth or an Exosuit, both types which can't see the fields either.
                steeringWheelYaw   = (float)vehicle.ReflectionGet <Vehicle, Vehicle>("steeringWheelYaw");
                steeringWheelPitch = (float)vehicle.ReflectionGet <Vehicle, Vehicle>("steeringWheelPitch");

                // Vehicles (or the SeaMoth at least) do not have special throttle animations. Instead, these animations are always playing because the player can't even see them (unlike the cyclops which has cameras).
                // So, we need to hack in and try to figure out when thrust needs to be applied.
                if (vehicle && AvatarInputHandler.main.IsEnabled())
                {
                    if (techType == TechType.Seamoth)
                    {
                        bool flag = vehicle.transform.position.y < Ocean.main.GetOceanLevel() && vehicle.transform.position.y < vehicle.worldForces.waterDepth && !vehicle.precursorOutOfWater;
                        appliedThrottle = flag && GameInput.GetMoveDirection().sqrMagnitude > .1f;
                    }
                    else if (techType == TechType.Exosuit)
                    {
                        Exosuit exosuit = vehicle as Exosuit;
                        if (exosuit)
                        {
                            appliedThrottle = (bool)exosuit.ReflectionGet("_jetsActive") && (float)exosuit.ReflectionGet("thrustPower") > 0f;
                        }
                    }
                }
            }
            else if (sub != null && Player.main.isPiloting)
            {
                guid     = GuidHelper.GetGuid(sub.gameObject);
                position = sub.gameObject.transform.position;
                rotation = sub.gameObject.transform.rotation;
                Rigidbody rigidbody = sub.GetComponent <Rigidbody>();
                velocity        = rigidbody.velocity;
                angularVelocity = rigidbody.angularVelocity;
                techType        = TechType.Cyclops;

                SubControl subControl = sub.GetComponent <SubControl>();
                steeringWheelYaw   = (float)subControl.ReflectionGet("steeringWheelYaw");
                steeringWheelPitch = (float)subControl.ReflectionGet("steeringWheelPitch");
                appliedThrottle    = subControl.appliedThrottle && (bool)subControl.ReflectionGet("canAccel");
            }
            else
            {
                return(Optional <VehicleModel> .Empty());
            }

            VehicleModel model = new VehicleModel(techType,
                                                  guid,
                                                  position,
                                                  rotation,
                                                  velocity,
                                                  angularVelocity,
                                                  steeringWheelYaw,
                                                  steeringWheelPitch,
                                                  appliedThrottle);

            return(Optional <VehicleModel> .Of(model));
        }