Esempio n. 1
0
 public void CreatePath(Coord target)
 {
     // Create new path if current is not already going to target
     if (path == null)
     {
         path      = EnvironmentUtility.GetPath(coord.x, coord.y, target.x, target.y);
         pathIndex = 0;
     }
     else
     {
         bool a = (pathIndex >= path.Length), b = false, c = false;
         if (path.Length != 0)
         {
             b = (path[path.Length - 1] != target);
             if (pathIndex != 0)
             {
                 c = (path[pathIndex - 1] != moveTargetCoord);
             }
         }
         if (a || b || c)
         {
             path      = EnvironmentUtility.GetPath(coord.x, coord.y, target.x, target.y);
             pathIndex = 0;
         }
     }
 }
Esempio n. 2
0
    void OnDrawGizmosSelected()
    {
        if (Application.isPlaying)
        {
            var surroundings = Environment.Sense(coord);
            Gizmos.color = Color.white;
            if (surroundings.nearestFoodSource != null)
            {
                Gizmos.DrawLine(transform.position, surroundings.nearestFoodSource.transform.position);
            }
            if (surroundings.nearestWaterTile != Coord.invalid)
            {
                Gizmos.DrawLine(transform.position, Environment.tileCentres[surroundings.nearestWaterTile.x, surroundings.nearestWaterTile.y]);
            }

            if (currentAction == CreatureAction.GoingToFood)
            {
                var path = EnvironmentUtility.GetPath(coord.x, coord.y, foodTarget.coord.x, foodTarget.coord.y);
                Gizmos.color = Color.black;
                for (int i = 0; i < path.Length; i++)
                {
                    Gizmos.DrawSphere(Environment.tileCentres[path[i].x, path[i].y], .2f);
                }
            }
        }
    }
Esempio n. 3
0
    public static Animal SensePredators(Animal e)
    {
        float radius = Animal.maxViewDistance * 1f / 5f;
        List <LivingEntity> hunters = new List <LivingEntity>();

        foreach (Species s in predatorsBySpecies[e.species])
        {
            hunters.AddRange(speciesMaps[s].GetEntities(e.coord, radius));
        }
        float minDist = radius * radius + 1;

        if (hunters.Count == 0)
        {
            return(null);
        }
        Animal predator = null;

        foreach (LivingEntity hunter in hunters)
        {
            if (EnvironmentUtility.TileIsVisibile(e.coord.x, e.coord.y, hunter.coord.x, hunter.coord.y))
            {
                if ((hunter as Animal).currentAction == CreatureAction.GoingToFood)
                {
                    if (Coord.SqrDistance(e.coord, hunter.coord) < minDist)
                    {
                        predator = hunter as Animal;
                        minDist  = Coord.SqrDistance(e.coord, hunter.coord);
                    }
                }
            }
        }
        return(predator);
    }
Esempio n. 4
0
    public LivingEntity ClosestEntity(Coord origin, float viewDistance)
    {
        List <RegionInfo> visibleRegions = GetRegionsInView(origin, viewDistance);
        LivingEntity      closestEntity  = null;
        float             closestSqrDst  = viewDistance * viewDistance + 0.01f;

        for (int i = 0; i < visibleRegions.Count; i++)
        {
            // Stop searching if current closest entity is closer than the dst to the region edge
            // All remaining regions will be further as well, since sorted by dst
            if (closestSqrDst <= visibleRegions[i].sqrDstToClosestEdge)
            {
                break;
            }

            Coord regionCoord = visibleRegions[i].coord;

            for (int j = 0; j < map[regionCoord.x, regionCoord.y].Count; j++)
            {
                LivingEntity entity = map[regionCoord.x, regionCoord.y][j];
                float        sqrDst = Coord.SqrDistance(entity.coord, origin);
                if (sqrDst < closestSqrDst)
                {
                    if (EnvironmentUtility.TileIsVisibile(origin.x, origin.y, entity.coord.x, entity.coord.y))
                    {
                        closestSqrDst = sqrDst;
                        closestEntity = entity;
                    }
                }
            }
        }

        return(closestEntity);
    }
Esempio n. 5
0
    public List <LivingEntity> GetEntities(Coord origin, float viewDistance)
    {
        List <RegionInfo> visibleRegions = GetRegionsInView(origin, viewDistance);
        float             sqrViewDst     = viewDistance * viewDistance;
        var visibleEntities = new List <LivingEntity>();

        for (int i = 0; i < visibleRegions.Count; i++)
        {
            Coord regionCoord = visibleRegions[i].coord;

            for (int j = 0; j < map[regionCoord.x, regionCoord.y].Count; j++)
            {
                LivingEntity entity = map[regionCoord.x, regionCoord.y][j];
                float        sqrDst = Coord.SqrDistance(entity.coord, origin);
                if (sqrDst < sqrViewDst)
                {
                    if (EnvironmentUtility.TileIsVisibile(origin.x, origin.y, entity.coord.x, entity.coord.y))
                    {
                        visibleEntities.Add(entity);
                    }
                }
            }
        }

        return(visibleEntities);
    }
Esempio n. 6
0
        /****
        ** General log output
        ****/
        /// <summary>Log the initial header with general SMAPI and system details.</summary>
        /// <param name="modsPath">The path from which mods will be loaded.</param>
        /// <param name="customSettings">The custom SMAPI settings.</param>
        public void LogIntro(string modsPath, IDictionary <string, object> customSettings)
        {
            // get platform label
            string platformLabel = EnvironmentUtility.GetFriendlyPlatformName(Constants.Platform);

            if ((Constants.GameFramework == GameFramework.Xna) != (Constants.Platform == Platform.Windows))
            {
                platformLabel += $" with {Constants.GameFramework}";
            }

            // init logging
            this.Monitor.Log($"SMAPI {Constants.ApiVersion} with Stardew Valley {Constants.GameVersion} on {platformLabel}", LogLevel.Info);
            this.Monitor.Log($"Mods go here: {modsPath}", LogLevel.Info);
            if (modsPath != Constants.DefaultModsPath)
            {
                this.Monitor.Log("(Using custom --mods-path argument.)");
            }
            this.Monitor.Log($"Log started at {DateTime.UtcNow:s} UTC");

            // log custom settings
            if (customSettings.Any())
            {
                this.Monitor.Log($"Loaded with custom settings: {string.Join(", ", customSettings.OrderBy(p => p.Key).Select(p => $"{p.Key}: {p.Value}"))}");
            }
        }
Esempio n. 7
0
    public static LivingEntity SenseFood(Coord coord, Animal self, System.Func <LivingEntity, LivingEntity, int> foodPreference)
    {
        var foodSources = new List <LivingEntity> ();

        List <Species> prey = preyBySpecies[self.species];

        for (int i = 0; i < prey.Count; i++)
        {
            Map speciesMap = speciesMaps[prey[i]];

            foodSources.AddRange(speciesMap.GetEntities(coord, Animal.maxViewDistance));
        }

        // Sort food sources based on preference function
        foodSources.Sort((a, b) => foodPreference(self, a).CompareTo(foodPreference(self, b)));

        // Return first visible food source
        for (int i = 0; i < foodSources.Count; i++)
        {
            Coord targetCoord = foodSources[i].coord;
            if (EnvironmentUtility.TileIsVisibile(coord.x, coord.y, targetCoord.x, targetCoord.y))
            {
                return(foodSources[i]);
            }
        }

        return(null);
    }
        public Startup()
        {
            var envName = EnvironmentUtility.GetCurrentEnvironment();

            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{envName}.json", optional: true, reloadOnChange: true)
                          .AddEnvironmentVariables(Api.ApiBasicConfiguration?.EnvironmentVariablesPrefix);

            Api.ConfigurationRoot = builder.Build();

            Api.ConfigurationRoot.GetSection("ApiSettings").Bind(Api.ApiSettings);
            Api.ConfigurationRoot.GetSection("HealthcheckSettings").Bind(Api.HealthcheckSettings);
            Api.ConfigurationRoot.GetSection("LogSettings").Bind(Api.LogSettings);
            Api.ConfigurationRoot.GetSection("QueueSettings").Bind(Api.QueueSettings);
            Api.ConfigurationRoot.GetSection("DatabaseSettings").Bind(Api.DatabaseSettings);
            Api.ConfigurationRoot.GetSection("DocsSettings").Bind(Api.DocsSettings);
            Api.ConfigurationRoot.GetSection("ShutdownSettings").Bind(Api.ShutdownSettings);
            Api.ConfigurationRoot.GetSection("CacheSettings").Bind(Api.CacheSettings);

            //Create this lógic to keep retrocompatibility because we change the IpRateLimiting section name to RateLimiting
            var ipRateLimitingSection = Api.ConfigurationRoot.GetSection("IpRateLimiting");

            if (ipRateLimitingSection.Exists())
            {
                ipRateLimitingSection.Bind(Api.RateLimitingAdditional);
            }
            else
            {
                Api.ConfigurationRoot.GetSection("RateLimiting").Bind(Api.RateLimitingAdditional);
            }
        }
Esempio n. 9
0
        /// <summary>Interactively locate the game install path to update.</summary>
        /// <param name="platform">The current platform.</param>
        /// <param name="specifiedPath">The path specified as a command-line argument (if any), which should override automatic path detection.</param>
        private DirectoryInfo InteractivelyGetInstallPath(Platform platform, string specifiedPath)
        {
            // get executable name
            string executableFilename = EnvironmentUtility.GetExecutableName(platform);

            // validate specified path
            if (specifiedPath != null)
            {
                var dir = new DirectoryInfo(specifiedPath);
                if (!dir.Exists)
                {
                    this.PrintError($"You specified --game-path \"{specifiedPath}\", but that folder doesn't exist.");
                    return(null);
                }
                if (!dir.EnumerateFiles(executableFilename).Any())
                {
                    this.PrintError($"You specified --game-path \"{specifiedPath}\", but that folder doesn't contain the Stardew Valley executable.");
                    return(null);
                }
                return(dir);
            }

            // get installed paths
            DirectoryInfo[] defaultPaths = (
                from path in this.GetDefaultInstallPaths(platform).Distinct(StringComparer.InvariantCultureIgnoreCase)
                let dir = new DirectoryInfo(path)
                          where dir.Exists && dir.EnumerateFiles(executableFilename).Any()
                          select dir
                )
                                           .GroupBy(x => x.FullName) //adding duplicate paths check
                                           .Select(y => y.First())
                                           .ToArray();
            ;

            // choose where to install
            if (defaultPaths.Any())
            {
                var lst = new List <Tuple <string, string> >();
                foreach (var path in defaultPaths)
                {
                    lst.Add(new Tuple <string, string>(path.FullName, path.FullName));
                }
                lst.Add(new Tuple <string, string>(null, "[I will choose a path myself]"));

                var result = InteractivelyChoose("There are the following options:", lst, "Where do you want to install/uninstall SMAPI?");

                if (result != null)
                {
                    return(new DirectoryInfo(result));
                }
                else
                {
                    return(InteractivelySelectPath(platform, executableFilename));
                }
            }

            // ask user
            this.PrintInfo("Oops, couldn't find the game automatically.");
            return(this.InteractivelySelectPath(platform, executableFilename));
        }
Esempio n. 10
0
    protected virtual void ChooseNextAction()
    {
        Surroundings surroundings = Environment.Sense(coord);

        if (surroundings.nearestFoodSource != null)
        {
            currentAction = CreatureAction.GoingToFood;
            foodTarget    = surroundings.nearestFoodSource;
        }

        // If exploring, move to random tile
        if (currentAction == CreatureAction.Exploring)
        {
            StartMoveToCoord(Environment.GetNextTileWeighted(coord, moveFromCoord));
        }
        else if (currentAction == CreatureAction.GoingToFood)
        {
            if (Coord.AreNeighbours(coord, foodTarget.coord))
            {
                currentAction = CreatureAction.Eating;
            }
            else
            {
                StartMoveToCoord(EnvironmentUtility.GetNextInPath(coord.x, coord.y, foodTarget.coord.x, foodTarget.coord.y));
            }
        }
    }
Esempio n. 11
0
 protected void CreatePath(Coord target)
 {
     // Create new path if current is not already going to target
     if (path == null || pathIndex >= path.Length || (path[path.Length - 1] != target || path[pathIndex - 1] != moveTargetCoord))
     {
         path      = EnvironmentUtility.GetPath(coord.x, coord.y, target.x, target.y);
         pathIndex = 0;
     }
 }
Esempio n. 12
0
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // 환경 검사
            MessageBox.Show($"EnvironmentType : {EnvironmentUtility.Type}\n{EnvironmentUtility.GetEnvironment().Version}", "실행된 환경");

            // 기본 블럭 추가
            listBlock.Items.Add(new EventBlock(new GCommand("this", "Loaded", "프로그램이 시작될 때", typeof(void), GCommand.CommandType.Event)));
            listBlock.Items.Add(new EventBlock(new GCommand("this", "Closing", "프로그램이 종료될 때", typeof(void), GCommand.CommandType.Event)));

            listBlock.Items.Add(new IfBlock());
            listBlock.Items.Add(new IfElseBlock());
            listBlock.Items.Add(new SetBlock());

            listBlock.Items.Add(new GateBlock());
            listBlock.Items.Add(new CompareBlock());

            listBlock.Items.Add(new EmptyListBlock());
            listBlock.Items.Add(new ItemBlock());
            listBlock.Items.Add(new ListAddBlock());

            listBlock.Items.Add(new ComputeBlock(GCompute.OperatorType.PLUS));
            listBlock.Items.Add(new ComputeBlock(GCompute.OperatorType.MINUS));
            listBlock.Items.Add(new ComputeBlock(GCompute.OperatorType.MULTIPLY));
            listBlock.Items.Add(new ComputeBlock(GCompute.OperatorType.DIVISION));
            listBlock.Items.Add(new ComputeBlock(GCompute.OperatorType.MODULO));

            listBlock.Items.Add(new StringCatBlock());
            listBlock.Items.Add(new LengthBlock());

            listBlock.Items.Add(new LoopInfinityBlock());
            listBlock.Items.Add(new LoopNBlock());

            // 확장 블럭 추가
            if (Directory.Exists("Extensions"))
            {
                var extension = new ExtensionManager("Extensions");
                foreach (var target in extension.Extensions)
                {
                    foreach (BaseBlock block in extension.ConvertToBlocks(target))
                    {
                        block.IsPreview = true;
                        listBlock.Items.Add(block);
                    }
                }
            }

            // 간격 및 이벤트 설정
            foreach (BaseBlock block in listBlock.Items)
            {
                block.Margin = new Thickness(0, 0, 0, 10);
                SetBlockEvent(block);
            }
        }
Esempio n. 13
0
    protected virtual void OnDrawGizmosSelected()
    {
        if (Application.isPlaying)
        {
            var surroundings = Environment.Sense(coord);
            Gizmos.color = Color.white;
            Gizmos.DrawWireSphere(transform.position, Animal.maxViewDistance);
            if (surroundings.nearestFoodSource != null)
            {
                Gizmos.DrawLine(transform.position, surroundings.nearestFoodSource.transform.position);
            }
            if (surroundings.nearestWaterTile != Coord.invalid)
            {
                Gizmos.DrawLine(transform.position, Environment.tileCentres[surroundings.nearestWaterTile.x, surroundings.nearestWaterTile.y]);
            }
            if (currentAction == CreatureAction.Exploring)
            {
                Gizmos.color = Color.red;
                Gizmos.DrawSphere(Environment.tileCentres[moveFromCoord.x, moveFromCoord.y], .2f);

                Gizmos.color = Color.green;
                Gizmos.DrawSphere(Environment.tileCentres[moveTargetCoord.x, moveTargetCoord.y], .2f);
            }
            if (currentAction == CreatureAction.GoingToMate)
            {
                Gizmos.color = Color.black;
                if (path != null)
                {
                    for (int i = 0; i < path.Length; i++)
                    {
                        Gizmos.DrawSphere(Environment.tileCentres[path[i].x, path[i].y], .2f);
                    }
                }
            }

            if (currentAction == CreatureAction.GoingToFood)
            {
                var path = EnvironmentUtility.GetPath(coord.x, coord.y, foodTarget.coord.x, foodTarget.coord.y);
                Gizmos.color = Color.black;
                if (path != null)
                {
                    for (int i = 0; i < path.Length; i++)
                    {
                        Gizmos.DrawSphere(Environment.tileCentres[path[i].x, path[i].y], .2f);
                    }
                }
            }
        }
    }
Esempio n. 14
0
        /*********
        ** Public methods
        *********/
        /// <summary>Run the install or uninstall script.</summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            // set up assembly resolution
            string installerPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            Program.DllSearchPath = EnvironmentUtility.DetectPlatform() == Platform.Windows
                ? Path.Combine(installerPath, "internal", "Windows", "smapi-internal")
                : Path.Combine(installerPath, "smapi-internal");
            AppDomain.CurrentDomain.AssemblyResolve += Program.CurrentDomain_AssemblyResolve;

            // launch installer
            var installer = new InteractiveInstaller();

            installer.Run(args);
        }
Esempio n. 15
0
        /// <summary>
        /// Run internal.
        /// </summary>
        protected override void RunInternal()
        {
            CefRuntime.Load();

            var mainArgs = new CefMainArgs(EnvironmentUtility.GetCommandLineArgs());

            var app = new App();

            app.BrowserCreated += (s, e) =>
            {
                CefBrowser = e.CefBrowser;
            };

            CefRuntime.ExecuteProcess(mainArgs, app, IntPtr.Zero);
        }
Esempio n. 16
0
        public Bootstrapper()
        {
            var environment = EnvironmentUtility.GetCommandLineVariable("APP_ENVIRONMENT");

            _configuration = new ConfigurationBuilder()
                             .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                             .AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true)
                             .Build();

            var locale = _configuration.GetValue <string>("AppLocale");

            EnvironmentUtility.SetCurrentLocale(locale);

            MappingConfig.Configure();
        }
Esempio n. 17
0
        public static void SetupSerilog(
            this IServiceCollection services,
            string domain,
            string application,
            LoggerSettings settings,
            List <string> ignoredRoutes)
        {
            var loggerBuilder = new LoggerBuilder();

            if (settings?.NewRelicOptions?.Enabled == true && string.IsNullOrWhiteSpace(settings?.NewRelicOptions?.LicenseKey))
            {
                settings.NewRelicOptions.LicenseKey = Environment.GetEnvironmentVariable("NEW_RELIC_LICENSE_KEY");
            }

            Log.Logger = loggerBuilder
                         .UseSuggestedSetting(domain, application)
                         .SetupSeq(settings?.SeqOptions)
                         .SetupSplunk(settings?.SplunkOptions)
                         .SetupNewRelic(settings?.NewRelicOptions)
                         .SetupDataDog(settings?.DataDogOptions)
                         .BuildLogger();

            if (settings?.DebugEnabled ?? false)
            {
                loggerBuilder.EnableDebug();
            }

            var config = new SerilogConfiguration
            {
                Version              = Api.ApiSettings.BuildVersion,
                InformationTitle     = settings?.TitlePrefix + CommunicationLogger.DefaultInformationTitle,
                ErrorTitle           = settings?.TitlePrefix + CommunicationLogger.DefaultErrorTitle,
                BlacklistRequest     = settings?.GetJsonBlacklistRequest(),
                BlacklistResponse    = settings?.JsonBlacklistResponse,
                HeaderBlacklist      = settings?.HeaderBlacklist,
                QueryStringBlacklist = settings?.QueryStringBlacklist,
                RequestKeyProperty   = RequestKeyServiceExtension.RequestKeyHeaderName,
                AccountIdProperty    = AccountIdServiceExtension.AccountIdHeaderName,
                TimeElapsedProperty  = TimeElapsedServiceExtension.TimeElapsedHeaderName,
                IgnoredRoutes        = ignoredRoutes
            };

            StaticSimpleLogger.UpdateVersion(Api.ApiSettings.BuildVersion);
            StaticSimpleLogger.UpdateEnvironment(EnvironmentUtility.GetCurrentEnvironment());

            services.SetupSerilog(config);
            services.AddScoped <ISimpleLogger, SimpleLogger>();
        }
Esempio n. 18
0
        /// <summary>
        /// Initializes the cef on current thread.
        /// </summary>
        private void InitializeCefOnCurrentThread()
        {
            Logger.Info("Initializing CEF.");

            CefRuntime.Load();

            var cefSettings = new CefSettings
            {
                MultiThreadedMessageLoop = IsMultiThreadedMessageLoop,
                SingleProcess            = false,
                LogSeverity             = CefLogSeverity.Warning,
                LogFile                 = LogsDirectoryPath + "/cef.log",
                CachePath               = CacheDirectoryPath,
                ResourcesDirPath        = PathUtility.WorkingDirectory,
                LocalesDirPath          = PathUtility.WorkingDirectory + "/locales",
                RemoteDebuggingPort     = RemoteDebuggingPort,
                NoSandbox               = true,
                CommandLineArgsDisabled = !CommandLineArgsEnabled
            };

            // arguments
            var arguments = new List <string>();

            if (CommandLineArgsEnabled)
            {
                arguments.AddRange(EnvironmentUtility.GetCommandLineArgs());
            }

            if (!D3D11Enabled && !arguments.Contains(Argument.DisableD3D11.Value))
            {
                arguments.Add(Argument.DisableD3D11.Value);
            }

            // initialize
            var mainArgs = new CefMainArgs(arguments.ToArray());
            var app      = new App();

            app.ContextInitialized += (s, args) =>
            {
                OnInitialize();
            };

            CefRuntime.Initialize(mainArgs, cefSettings, app, IntPtr.Zero);

            Logger.Info("CEF initialized.");
        }
Esempio n. 19
0
        /// <summary>Assert that the game is available.</summary>
        /// <remarks>This must be checked *before* any references to <see cref="Constants"/>, and this method should not reference <see cref="Constants"/> itself to avoid errors in Mono.</remarks>
        private static void AssertGamePresent()
        {
            Platform platform         = EnvironmentUtility.DetectPlatform();
            string   gameAssemblyName = platform == Platform.Windows ? "Stardew Valley" : "StardewValley";

            if (Type.GetType($"StardewValley.Game1, {gameAssemblyName}", throwOnError: false) == null)
            {
                Program.PrintErrorAndExit(
                    "Oops! SMAPI can't find the game. "
                    + (Assembly.GetCallingAssembly().Location.Contains(Path.Combine("internal", "Windows")) || Assembly.GetCallingAssembly().Location.Contains(Path.Combine("internal", "Mono"))
                        ? "It looks like you're running SMAPI from the download package, but you need to run the installed version instead. "
                        : "Make sure you're running StardewModdingAPI.exe in your game folder. "
                       )
                    + "See the readme.txt file for details."
                    );
            }
        }
Esempio n. 20
0
        public IActionResult GetAppInfo()
        {
            this.DisableLogging();

            return(Ok(new HomeDetails
            {
                RIP = GracefullShutdownState.RequestsInProgress,
                Service = Api.ApiBasicConfiguration?.ApiName,
                BuildVersion = Api.ApiSettings?.BuildVersion,
                Environment = EnvironmentUtility.GetCurrentEnvironment(),
                RequestKey = RequestKey.Value,
                Application = Api.ApiSettings.Application,
                Domain = Api.ApiSettings.Domain,
                JsonSerializer = Api.ApiSettings.JsonSerializer,
                EnvironmentPrefix = Api.ApiBasicConfiguration.EnvironmentVariablesPrefix,
                TimezoneInfo = new TimezoneInfo(HttpContextAccessor)
            }));
        }
        public override bool Execute()
        {
            // set to false first.
            IsEnvironmentValid = false;

            Target = Target.ToLower();

            if (_environments.ContainsKey(Target))
            {
                var env = _environments[Target];
                if (env == null)
                {
                    IsEnvironmentValid = false;
                    return(true);
                }

                IsEnvironmentValid = true;
                EnvironmentUtility.Apply(env);
                return(true);
            }
            try {
                ArrayList targetLists = _msbuild.CreateTargetLists(new[] {
                    Target
                }, false);
                var result = _msbuild.ExecuteTargets(new ITaskItem[] {
                    null
                }, null, null, targetLists, false, false, BuildEngine3, Log, targetOutputs, false, false, null);

                if (result)
                {
                    _environments.Add(Target, Environment.GetEnvironmentVariables());
                    IsEnvironmentValid = true;
                    return(true);
                }
            } catch {
                // any failure here really means that it should just assume it didn't work.
            }

            _environments.Add(Target, null);
            IsEnvironmentValid = false;

            return(true);
        }
Esempio n. 22
0
    public static Building senseBuilding(BuildingTypes buildingType, Human self, System.Func <ICoordInterface, ICoordInterface, int> preferenceFunc)
    {
        Coord           coord            = self.coord;
        List <Building> visibleBuildings = buildingMaps[buildingType].GetEntities(coord, Animal.maxViewDistance);

        visibleBuildings.Sort((a, b) => Coord.CoordPenalty(self, a).CompareTo(Coord.CoordPenalty(self, b)));

        // Return first visible food source
        for (int i = 0; i < visibleBuildings.Count; i++)
        {
            Coord targetCoord = visibleBuildings[i].coord;
            if (EnvironmentUtility.TileIsVisibile(coord.x, coord.y, targetCoord.x, targetCoord.y))
            {
                return(visibleBuildings[i]);
            }
        }

        return(null);
    }
Esempio n. 23
0
        public static Scope EnterBackgroundProcessingMode()
        {
            Thread.BeginThreadAffinity();
            IntPtr hThread = SafeNativeMethods.GetCurrentThread();

            if (EnvironmentUtility.IsWindowsVistaOrLater() && UnsafeNativeMethods.SetThreadPriority(hThread,
                                                                                                    Win32.THREAD_MODE_BACKGROUND_BEGIN))
            {
                // OS supports background processing; return Scope that exits this mode
                return(Scope.Create(() =>
                {
                    UnsafeNativeMethods.SetThreadPriority(hThread, Win32.THREAD_MODE_BACKGROUND_END);
                    Thread.EndThreadAffinity();
                }));
            }

            // OS doesn't support background processing mode (or setting it failed)
            Thread.EndThreadAffinity();
            return(Scope.Empty);
        }
        /*********
        ** Private methods
        *********/
        /// <summary>Get the font glyph data for a MonoGame font.</summary>
        /// <param name="font">The sprite font.</param>
        private IDictionary <char, object> GetGlyphs(SpriteFont font)
        {
            Platform platform = EnvironmentUtility.DetectPlatform();
            IDictionary <char, object> glyphs = new Dictionary <char, object>();

            if (platform == Platform.Windows)
            {
                // get internal sprite data
                IList <Rectangle> glyphData    = this.RequireField <List <Rectangle> >(font, "glyphData");
                IList <Rectangle> croppingData = this.RequireField <List <Rectangle> >(font, "croppingData");
                IList <Vector3>   kerning      = this.RequireField <List <Vector3> >(font, "kerning");

                // replicate MonoGame structure for consistency (and readability)
                for (int i = 0; i < font.Characters.Count; i++)
                {
                    char ch = font.Characters[i];
                    glyphs[ch] = new
                    {
                        BoundsInTexture = glyphData[i],
                        Cropping        = croppingData[i],
                        Character       = ch,

                        LeftSideBearing  = kerning[i].X,
                        Width            = kerning[i].Y,
                        RightSideBearing = kerning[i].Z,

                        WidthIncludingBearings = kerning[i].X + kerning[i].Y + kerning[i].Z
                    };
                }
            }
            else
            {
                //use Mono exclusive method
                foreach (DictionaryEntry entry in this.RequireMethod <IDictionary>(font, "GetGlyphs"))
                {
                    glyphs.Add((char)entry.Key, entry.Value);
                }
            }

            return(glyphs);
        }
Esempio n. 25
0
        private bool ExecuteCommand(string command, string parameters)
        {
            if (string.IsNullOrEmpty(command))
            {
                return(true);
            }

            var psi = new ProcessStartInfo {
                FileName               = command.Contains("\\") ? command : EnvironmentUtility.FindInPath(command, PackageDirectory + ";" + EnvironmentUtility.EnvironmentPath),
                Arguments              = parameters,
                CreateNoWindow         = false,
                RedirectStandardError  = true,
                RedirectStandardOutput = true,
                UseShellExecute        = false,
                WorkingDirectory       = PackageDirectory
            };

            if (!psi.FileName.Contains("\\"))
            {
                Logger.Error("Target execute command does not have a full path. '{0}'", psi.FileName);
            }

            try {
                var proc   = Process.Start(psi);
                var stdOut = Task.Factory.StartNew(() => proc.StandardOutput.ReadToEnd());
                var stdErr = Task.Factory.StartNew(() => proc.StandardError.ReadToEnd());

                proc.WaitForExit();

                if (proc.ExitCode != 0)
                {
                    Logger.Error("Failed Execute Command StdOut: \r\n{0}", stdOut.Result);
                    Logger.Error("Failed Execute Command StdError: \r\n{0}", stdErr.Result);
                    return(false);
                }
                return(true);
            } catch (Exception e) {
                Logger.Error(e);
            }
            return(false);
        }
Esempio n. 26
0
    // Start is called before the first frame update


    // Update is called once per frame
    protected override void OnDrawGizmosSelected()
    {
        if (Application.isPlaying)
        {
            Gizmos.color = Color.yellow;
            Gizmos.DrawLine(transform.position, Environment.tileCentres[buildingPlace.x, buildingPlace.y]);
            if (currentAction == CreatureAction.WorkingAtFarm)
            {
                var path = EnvironmentUtility.GetPath(coord.x, coord.y, foodTarget.coord.x, foodTarget.coord.y);
                Gizmos.color = Color.black;
                if (path != null)
                {
                    for (int i = 0; i < path.Length; i++)
                    {
                        Gizmos.DrawSphere(Environment.tileCentres[path[i].x, path[i].y], .2f);
                    }
                }
            }
        }
        base.OnDrawGizmosSelected();
    }
Esempio n. 27
0
        internal static void EnsureCanonicalFoldersArePresent()
        {
            var root = PackageManagerSettings.CoAppRootDirectory;
            // try to make a convenience symlink:  %SYSTEMDRIVE%:\apps
            var appsdir = "{0}:\\apps".format(root[0]);

            if (!Directory.Exists(appsdir) && !File.Exists(appsdir))
            {
                Symlink.MakeDirectoryLink("{0}:\\apps".format(root[0]), root);
            }

            var pathext = EnvironmentUtility.GetSystemEnvironmentVariable("PATHEXT");

            if (pathext.IndexOf(".lnk", StringComparison.CurrentCultureIgnoreCase) == -1)
            {
                EnvironmentUtility.SetSystemEnvironmentVariable("PATHEXT", pathext + ";.lnk");
            }

            foreach (var path in CanonicalFolders.Select(folder => Path.Combine(root, folder)).Where(path => !Directory.Exists(path)))
            {
                Directory.CreateDirectory(path);
            }

            // make sure system paths are updated.
            var binPath = Path.Combine(root, "bin");
            var psPath  = Path.Combine(root, "powershell");

            if (!EnvironmentUtility.SystemPath.Contains(binPath))
            {
                EnvironmentUtility.SystemPath = EnvironmentUtility.SystemPath.Prepend(binPath);
            }
            if (!EnvironmentUtility.PowershellModulePath.Contains(psPath))
            {
                EnvironmentUtility.PowershellModulePath = EnvironmentUtility.PowershellModulePath.Prepend(psPath);
            }

            EnvironmentUtility.BroadcastChange();
        }
Esempio n. 28
0
    public static LivingEntity FindEntityOfSpecies(Coord coord, Animal self, Species species, System.Func <LivingEntity, LivingEntity, int> movepenalty)
    {
        var entities = new List <LivingEntity> ();

        Map speciesMap = speciesMaps[species];

        entities.AddRange(speciesMap.GetEntities(coord, Animal.maxViewDistance));

        // Sort food sources based on preference function
        entities.Sort((a, b) => movepenalty(self, a).CompareTo(movepenalty(self, b)));

        // Return first visible food source
        for (int i = 0; i < entities.Count; i++)
        {
            Coord targetCoord = entities[i].coord;
            if (EnvironmentUtility.TileIsVisibile(coord.x, coord.y, targetCoord.x, targetCoord.y))
            {
                return(entities[i]);
            }
        }

        return(null);
    }
Esempio n. 29
0
        public Startup()
        {
            var envName = EnvironmentUtility.GetCurrentEnvironment();

            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{envName}.json", optional: true, reloadOnChange: true)
                          .AddEnvironmentVariables(Api.ApiBasicConfiguration?.EnvironmentVariablesPrefix);

            Api.ConfigurationRoot = builder.Build();

            Api.ConfigurationRoot.GetSection("ApiSettings").Bind(Api.ApiSettings);
            Api.ConfigurationRoot.GetSection("HealthcheckSettings").Bind(Api.HealthcheckSettings);
            Api.ConfigurationRoot.GetSection("LogSettings").Bind(Api.LogSettings);
            Api.ConfigurationRoot.GetSection("QueueSettings").Bind(Api.QueueSettings);
            Api.ConfigurationRoot.GetSection("DatabaseSettings").Bind(Api.DatabaseSettings);
            Api.ConfigurationRoot.GetSection("DocsSettings").Bind(Api.DocsSettings);
            Api.ConfigurationRoot.GetSection("ShutdownSettings").Bind(Api.ShutdownSettings);
            Api.ConfigurationRoot.GetSection("IpRateLimiting").Bind(Api.IpRateLimitingAdditional);
            Api.ConfigurationRoot.GetSection("CacheSettings").Bind(Api.CacheSettings);
            Api.ConfigurationRoot.GetSection("WorkerSettings").Bind(Api.WorkerSettings);
        }
Esempio n. 30
0
        /*********
        ** Public methods
        *********/
        /// <summary>Find all valid Stardew Valley install folders.</summary>
        /// <remarks>This checks default game locations, and on Windows checks the Windows registry for GOG/Steam install data. A folder is considered 'valid' if it contains the Stardew Valley executable for the current OS.</remarks>
        public IEnumerable <DirectoryInfo> Scan()
        {
            // get OS info
            Platform platform           = EnvironmentUtility.DetectPlatform();
            string   executableFilename = EnvironmentUtility.GetExecutableName(platform);

            // get install paths
            IEnumerable <string> paths = this
                                         .GetCustomInstallPaths(platform)
                                         .Concat(this.GetDefaultInstallPaths(platform))
                                         .Select(PathUtilities.NormalizePathSeparators)
                                         .Distinct(StringComparer.OrdinalIgnoreCase);

            // yield valid folders
            foreach (string path in paths)
            {
                DirectoryInfo folder = new DirectoryInfo(path);
                if (folder.Exists && folder.EnumerateFiles(executableFilename).Any())
                {
                    yield return(folder);
                }
            }
        }