/// <summary>
 /// Adds the female bases to the list.
 /// </summary>
 /// <param name="file">The current file.</param>
 private void AddFemaleBaseToList(FileInfo file)
 {
     if (file.Name.Contains("farmer_girl_base.png"))
     {
         PackHelper.FemaleBaseTextureList.Add(CurrentContentPack.LoadAsset <Texture2D>("Base/farmer_girl_base.png"));
     }
 }
 /// <summary>
 /// Adds female shoes to the texture list.
 /// </summary>
 /// <param name="file">Current file</param>
 private void AddFemaleShoes(FileInfo file)
 {
     if (file.Name.Contains("female_shoes"))
     {
         PackHelper.FemaleShoeTextureList.Add(CurrentContentPack.LoadAsset <Texture2D>(Path.Combine("Shoes", file.Name)));
     }
 }
Beispiel #3
0
 /// <summary>
 /// Finds female faces and nose and adds them to the dictionary.
 /// </summary>
 /// <param name="file">The current file</param>
 /// <param name="currentPackFemaleFaceNoseDict">Dictionary for current pack</param>
 private void FindFemaleFaceNose(FileInfo file, Dictionary <string, Texture2D> currentPackFemaleFaceNoseDict)
 {
     if (file.Name.Contains("female_face"))
     {
         currentPackFemaleFaceNoseDict.Add(file.Name, CurrentContentPack.LoadAsset <Texture2D>(Path.Combine("FaceAndNose", file.Name)));
     }
 }
Beispiel #4
0
        public static Map Load(string path, IModHelper helper, bool syncTexturesToClients, IContentPack contentPack)
        {
            Dictionary <TileSheet, Texture2D> tilesheets = Helper.Reflection.GetField <Dictionary <TileSheet, Texture2D> >(Game1.mapDisplayDevice, "m_tileSheetTextures").GetValue();
            Map    map      = tmx2map(Path.Combine(contentPack != null ? contentPack.DirectoryPath : helper.DirectoryPath, path));
            string fileName = new FileInfo(path).Name;

            Monitor.Log(path);
            foreach (TileSheet t in map.TileSheets)
            {
                t.ImageSource = t.ImageSource.Replace(".png", "");
                string[] seasons       = new string[] { "summer_", "fall_", "winter_" };
                string   tileSheetPath = path.Replace(fileName, t.ImageSource + ".png");

                FileInfo tileSheetFile        = new FileInfo(Path.Combine(contentPack != null ? contentPack.DirectoryPath : helper.DirectoryPath, tileSheetPath));
                FileInfo tileSheetFileVanilla = new FileInfo(Path.Combine(PyUtils.getContentFolder(), "Content", t.ImageSource + ".xnb"));
                if (tileSheetFile.Exists && !tileSheetFileVanilla.Exists && tilesheets.Find(k => k.Key.ImageSource == t.ImageSource).Key == null)
                {
                    Texture2D tilesheet = contentPack != null?contentPack.LoadAsset <Texture2D>(tileSheetPath) : helper.Content.Load <Texture2D>(tileSheetPath);

                    tilesheet.inject(t.ImageSource);
                    tilesheet.inject("Maps/" + t.ImageSource);

                    if (syncTexturesToClients && Game1.IsMultiplayer && Game1.IsServer)
                    {
                        foreach (Farmer farmhand in Game1.otherFarmers.Values)
                        {
                            PyNet.sendGameContent(t.ImageSource, tilesheet, farmhand, (b) => Monitor.Log("Syncing " + t.ImageSource + " to " + farmhand.Name + ": " + (b ? "successful" : "failed"), b ? LogLevel.Info : LogLevel.Warn));
                        }
                    }

                    if (t.ImageSource.Contains("spring_"))
                    {
                        foreach (string season in seasons)
                        {
                            string   seasonPath = path.Replace(fileName, t.ImageSource.Replace("spring_", season));
                            FileInfo seasonFile = new FileInfo(Path.Combine(contentPack != null ? contentPack.DirectoryPath : helper.DirectoryPath, seasonPath + ".png"));
                            if (seasonFile.Exists && tilesheets.Find(k => k.Key.ImageSource == t.ImageSource.Replace("spring_", season)).Key == null)
                            {
                                Texture2D seasonTilesheet = contentPack != null?contentPack.LoadAsset <Texture2D>(seasonPath + ".png") : helper.Content.Load <Texture2D>(seasonPath + ".png");

                                string seasonTextureName = t.ImageSource.Replace("spring_", season);
                                seasonTilesheet.inject(seasonTextureName);
                                seasonTilesheet.inject("Maps/" + seasonTextureName);

                                if (syncTexturesToClients && Game1.IsMultiplayer && Game1.IsServer)
                                {
                                    foreach (Farmer farmhand in Game1.otherFarmers.Values)
                                    {
                                        PyNet.sendGameContent(new string[] { seasonTextureName, "Maps/" + seasonTextureName }, seasonTilesheet, farmhand, (b) => Monitor.Log("Syncing " + seasonTextureName + " to " + farmhand.Name + ": " + (b ? "successful" : "failed"), b ? LogLevel.Info : LogLevel.Warn));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            map.LoadTileSheets(Game1.mapDisplayDevice);
            return(map);
        }
Beispiel #5
0
        public static bool doesExist(bool failed, TileSheet t, IContentPack contentPack, IModHelper helper, string tileSheetPath)
        {
            if (!failed)
            {
                FileInfo tileSheetFile        = new FileInfo(Path.Combine(contentPack != null ? contentPack.DirectoryPath : helper.DirectoryPath, tileSheetPath));
                FileInfo tileSheetFileVanilla = new FileInfo(Path.Combine(PyUtils.ContentPath, "Content", t.ImageSource + ".xnb"));

                return(tileSheetFile.Exists && !tileSheetFileVanilla.Exists);
            }
            else
            {
                Texture2D ts  = null;
                Texture2D tsv = null;
                try
                {
                    ts = contentPack != null?contentPack.LoadAsset <Texture2D>(tileSheetPath) : helper.Content.Load <Texture2D>(tileSheetPath);

                    tsv = helper.Content.Load <Texture2D>(tileSheetPath, ContentSource.GameContent);
                }
                catch
                {
                }

                return(ts != null && tsv == null);
            }
        }
        private void LoadMonsters(IContentPack contentPack)
        {
            Monitor.Log($"Loading Content Pack: {contentPack.Manifest.Name}{contentPack.Manifest.Version} by {contentPack.Manifest.Author}");

            //Start loading custom monsters.
            DirectoryInfo monInfo = new DirectoryInfo(Path.Combine(contentPack.DirectoryPath, "Monsters"));

            if (monInfo.Exists)
            {
                foreach (var dir in monInfo.EnumerateDirectories())
                {
                    string relPath = $"Monsters/{dir.Name}";
                    mData = contentPack.ReadJsonFile <MonsterData>($"{relPath}/monster.json");

                    if (mData == null)
                    {
                        continue;
                    }

                    mData.mSprite    = contentPack.LoadAsset <AnimatedSprite>($"{relPath}/monster.png");
                    mData.mSpriteStr = $"{relPath}/monster.png";


                    this.monsters.Add(mData);
                    //Load the data up.
                }
            }
        }
        public static Map Load(string path, IModHelper helper, bool syncTexturesToClients, IContentPack contentPack)
        {
            Map map = contentPack != null?contentPack.LoadAsset <Map>(path) : helper.Content.Load <Map>(path);

            map?.LoadTileSheets(Game1.mapDisplayDevice);
            return(map);
        }
Beispiel #8
0
        public Shop(ShopPack pack, IContentPack contentPack)
        {
            ShopName             = pack.ShopName;
            OpenConditions       = pack.When;
            ClosedMessage        = pack.ClosedMessage;
            ShopPrice            = pack.ShopPrice;
            StoreCurrency        = pack.StoreCurrency;
            CategoriesToSellHere = pack.CategoriesToSellHere;
            ItemStocks           = pack.ItemStocks;
            Quote = pack.Quote;
            MaxNumItemsSoldInStore = pack.MaxNumItemsSoldInStore;

            //try and load in the portrait
            if (pack.PortraitPath != null)
            {
                try
                {
                    Portrait = contentPack.LoadAsset <Texture2D>(pack.PortraitPath);
                }
                catch (Exception ex)
                {
                    ModEntry.monitor.Log(ex.Message, LogLevel.Warn);
                }
            }
        }
Beispiel #9
0
        /// <summary>Preload an asset from the content pack if necessary.</summary>
        /// <param name="contentPack">The content pack.</param>
        /// <param name="key">The asset key.</param>
        /// <returns>Returns whether any assets were preloaded.</returns>
        public bool PreloadIfNeeded(IContentPack contentPack, string key)
        {
            key = this.GetRealPath(contentPack, key) ?? throw new FileNotFoundException($"The file '{key}' does not exist in the {contentPack.Manifest.Name} content patch folder.");
            bool anyLoaded = false;

            // PNG asset
            if (this.IsPngPath(key))
            {
                string actualAssetKey = contentPack.GetActualAssetKey(key);
                if (!this.PngTextureCache.ContainsKey(actualAssetKey))
                {
                    this.PngTextureCache[actualAssetKey] = contentPack.LoadAsset <Texture2D>(key);
                    anyLoaded = true;
                }
            }

            // map PNG tilesheets
            if (this.TryLoadMap(contentPack, key, out Map map))
            {
                string relativeRoot = contentPack.GetActualAssetKey(""); // warning: this depends on undocumented SMAPI implementation details
                foreach (TileSheet tilesheet in map.TileSheets)
                {
                    // ignore if not a PNG in the content pack
                    if (!tilesheet.ImageSource.StartsWith(relativeRoot) || Path.GetExtension(tilesheet.ImageSource).Equals(".png", StringComparison.InvariantCultureIgnoreCase))
                    {
                        continue;
                    }

                    // ignore if local file doesn't exist
                    string relativePath = this.GetRealPath(contentPack, tilesheet.ImageSource.Substring(relativeRoot.Length + 1));
                    if (relativePath == null)
                    {
                        continue;
                    }

                    // load asset
                    string actualAssetKey = contentPack.GetActualAssetKey(relativePath);
                    if (!this.PngTextureCache.ContainsKey(actualAssetKey))
                    {
                        this.PngTextureCache[actualAssetKey] = contentPack.LoadAsset <Texture2D>(relativePath);
                        anyLoaded = true;
                    }
                }
            }

            return(anyLoaded);
        }
 public Texture2DExtended(IContentPack content, string path)
 {
     this.Name    = Path.GetFileNameWithoutExtension(path);
     this.path    = path;
     this.content = content;
     this.texture = content.LoadAsset <Texture2D>(path);
     this.helper  = null;
     this.modID   = content.Manifest.UniqueID;
 }
 public Texture2DExtended(IContentPack ContentPack, string modID, string path)
 {
     this.Name    = Path.GetFileNameWithoutExtension(path);
     this.path    = path;
     this.texture = ContentPack.LoadAsset <Texture2D>(path);
     this.helper  = null;
     this.modID   = modID;
     this.source  = ContentSource.ModFolder;
 }
Beispiel #12
0
        /// <summary>Get the sprite at the passed relative path.</summary>
        /// <param name="path">The relative (to the content pack) path for the sprite.</param>
        /// <param name="contentPack">The content pack that should contain the sprite.</param>
        /// <returns>The sprite at the passed path.</returns>
        private Texture2D GetSpriteByPath(string path, IContentPack contentPack)
        {
            if (File.Exists(Path.Combine(contentPack.DirectoryPath, path)))
            {
                return(contentPack.LoadAsset <Texture2D>(path));
            }

            return(null);
        }
Beispiel #13
0
        /// <summary>Get the current values.</summary>
        /// <param name="input">The input argument, if applicable.</param>
        public IEnumerable <string> GetValues(string input)
        {
            RecolorTokenArguments inputData = RecolorTokenArguments.Parse(input);

            if (!(inputData.Equals(previousInputData_)))
            {
                mustUpdateContext_ = true;
            }
            previousInputData_ = inputData;

            IContentPack contentPack = Utility.GetContentPackFromModInfo(helper_.ModRegistry.Get(inputData.ContentPackName));

            monitor_.Log($"Content pack {contentPack.Manifest.UniqueID} requests recoloring of {inputData.AssetName}.");
            monitor_.Log($"Recolor with {inputData.MaskPath} and {Utility.ColorToHtml(inputData.BlendColor)}");

            // "gamecontent" means loading from game folder.
            Texture2D source = inputData.SourcePath.ToLowerInvariant() == "gamecontent"
                             ? helper_.Content.Load <Texture2D>(inputData.AssetName, ContentSource.GameContent)
                             : contentPack.LoadAsset <Texture2D>(inputData.SourcePath);

            Texture2D extracted = inputData.MaskPath.ToLowerInvariant() != "none"
                                ? ExtractSubImage(source,
                                                  contentPack.LoadAsset <Texture2D>(inputData.MaskPath),
                                                  inputData.DesaturationMode)
                                : source;

            Texture2D target = ColorBlend(extracted, inputData.BlendColor);

            // ATTENTION: In order to load files we just generated we need at least ContentPatcher 1.18.3 .
            string generatedFilePath         = GenerateFilePath(inputData);
            string generatedFilePathAbsolute = Path.Combine(contentPack.DirectoryPath, generatedFilePath);

            Directory.CreateDirectory(Path.GetDirectoryName(generatedFilePathAbsolute));
            using (FileStream fs = new FileStream(generatedFilePathAbsolute, FileMode.Create)) {
                target.SaveAsPng(fs, target.Width, target.Height);
                fs.Close();
            }

            monitor_.Log($"Generated file {generatedFilePathAbsolute}, returning relative path {generatedFilePath}");

            helper_.Content.InvalidateCache(inputData.AssetName);

            yield return(generatedFilePath);
        }
        public static Texture2D GetTextureAsset(IContentPack contentPack, string textureName)
        {
            var key = new Tuple <string, string>(contentPack.Manifest.UniqueID, textureName);

            if (!_contentPackAssets.ContainsKey(key))
            {
                _contentPackAssets[key] = contentPack.LoadAsset <Texture2D>(textureName);
            }
            return(_contentPackAssets[key]);
        }
 /// <summary>Preload an asset from the content pack if necessary.</summary>
 /// <typeparam name="T">The asset type.</typeparam>
 /// <param name="contentPack">The content pack.</param>
 /// <param name="key">The asset key.</param>
 public void PreloadIfNeeded <T>(IContentPack contentPack, string key)
 {
     if (this.IsPng <T>(key))
     {
         string actualAssetKey = contentPack.GetActualAssetKey(key);
         if (!this.PngTextureCache.ContainsKey(actualAssetKey))
         {
             this.PngTextureCache[actualAssetKey] = contentPack.LoadAsset <Texture2D>(key);
         }
     }
 }
Beispiel #16
0
        /*********
        ** Public Methods
        *********/
        /// <summary>Loads content from the content pack folder.</summary>
        /// <typeparam name="T">The expected data type to load.</typeparam>
        /// <param name="contentPack">The content pack to to load content from.</param>
        /// <param name="key">The relative file path within the content pack (case-insensitive).</param>
        /// <param name="result">The loaded asset.</param>
        /// <returns><see langword="true"/>, if the loading was successful; otherwise, <see langword="false"/>.</returns>
        /// <exception cref="ArgumentException">Thrown if <paramref name="key"/> is empty or contains invalid characters.</exception>
        /// <exception cref="ContentLoadException">Thrown if the asset couldn't be loaded (e.g. because it doesn't exist).</exception>
        public static bool TryLoadAsset <T>(this IContentPack contentPack, string key, out T result)
            where T : class
        {
            if (File.Exists(Path.Combine(contentPack.DirectoryPath, key)))
            {
                result = contentPack.LoadAsset <T>(key);
                return(true);
            }

            result = null;
            return(false);
        }
        public CustomSet(IContentPack pack, bool addToCatalogue = true, bool injectTileSheets = true)
        {
            Walls  = pack.HasFile("walls.png") ? pack.LoadAsset <Texture2D>("walls.png") : null;
            Floors = pack.HasFile("floors.png") ? pack.LoadAsset <Texture2D>("floors.png") : null;

            if (pack.HasFile("settings.json"))
            {
                Settings = pack.LoadAsset <Settings>("settings.json");
            }

            Pack = pack;

            if (addToCatalogue)
            {
                AddToCatalogue();
            }

            if (injectTileSheets)
            {
                InjectTileSheets();
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="contentPack"></param>
        /// <param name="farm"></param>
        private void LoadIcon(IModHelper helper, IContentPack contentPack, CustomFarm farm)
        {
            string IconFile;

            IconFile = Path.Combine(contentPack.DirectoryPath, "icon.png");
            if (File.Exists(IconFile))
            {
                farm.IconSource = contentPack.LoadAsset <Texture2D>("icon.png");
            }
            else
            {
                farm.IconSource = helper.Content.Load <Texture2D>(Path.Combine("Resource", "missingIcon.png"));
            }
        }
        /// <summary>Get an asset from the content pack of <see cref="PngTextureCache"/>.</summary>
        /// <typeparam name="T">The asset type.</typeparam>
        /// <param name="contentPack">The content pack.</param>
        /// <param name="key">The asset key.</param>
        public T Load <T>(IContentPack contentPack, string key)
        {
            // load from PNG cache if applicable
            if (this.IsPng <T>(key))
            {
                string actualAssetKey = contentPack.GetActualAssetKey(key);
                if (this.PngTextureCache.TryGetValue(actualAssetKey, out Texture2D texture))
                {
                    return((T)(object)texture);
                }
            }

            // load from pack
            return(contentPack.LoadAsset <T>(key));
        }
Beispiel #20
0
        public static Map Load(string path, IModHelper helper, bool syncTexturesToClients, IContentPack contentPack)
        {
            Map map = contentPack != null?contentPack.LoadAsset <Map>(path) : helper.Content.Load <Map>(path);

            for (int index = 0; index < map.TileSheets.Count; ++index)
            {
                if (string.IsNullOrWhiteSpace(Path.GetDirectoryName(map.TileSheets[index].ImageSource)))
                {
                    map.TileSheets[index].ImageSource = Path.Combine("Maps", Path.GetFileName(map.TileSheets[index].ImageSource));
                }
            }

            map?.LoadTileSheets(Game1.mapDisplayDevice);
            return(map);
        }
Beispiel #21
0
        /// <summary>Load all .png files from specified directory into the correct sprite list.</summary>
        /// <param name="directory">The absolute directory containing the .png files.</param>
        /// <param name="contentPack">The content pack currently being loaded.</param>
        /// <param name="season">The season to load the images into.</param>
        private void LoadFilesFromDirectory(string directory, IContentPack contentPack, Season season)
        {
            foreach (var file in Directory.GetFiles(directory))
            {
                if (!file.EndsWith(".png"))
                {
                    Monitor.Log($"Invalid file in season folder: {file}");
                    return;
                }

                string    relativeDirectory = GetRelativeDirectory(directory);
                string    relativePath      = Path.Combine(relativeDirectory, Path.GetFileName(file));
                Texture2D grass             = contentPack.LoadAsset <Texture2D>(relativePath);
                if (grass == null)
                {
                    Monitor.Log($"Failed to get grass sprite. Path expected: {relativePath}");
                }
                else
                {
                    switch (season)
                    {
                    case Season.Spring:
                    {
                        SpringGrassSprites.Add(grass);
                        break;
                    }

                    case Season.Summer:
                    {
                        SummerGrassSprites.Add(grass);
                        break;
                    }

                    case Season.Fall:
                    {
                        FallGrassSprites.Add(grass);
                        break;
                    }

                    case Season.Winter:
                    {
                        WinterGrassSprites.Add(grass);
                        break;
                    }
                    }
                }
            }
        }
Beispiel #22
0
        internal static void ApplyLocation(IContentPack contentPack, Location location)
        {
            try
            {
                GameLocation loc;
                xTile.Map    map = contentPack.LoadAsset <xTile.Map>(location.FileName);
                switch (location.Type)
                {
                case "Cellar":
                    loc = new StardewValley.Locations.Cellar(map, location.MapName)
                    {
                        objects = new SerializableDictionary <Microsoft.Xna.Framework.Vector2, StardewValley.Object>()
                    };
                    break;

                case "BathHousePool":
                    loc = new StardewValley.Locations.BathHousePool(map, location.MapName);
                    break;

                case "Decoratable":
                    loc = new Locations.DecoratableLocation(map, location.MapName);
                    break;

                case "Desert":
                    loc = new Locations.Desert(map, location.MapName);
                    break;

                case "Greenhouse":
                    loc = new Locations.Greenhouse(map, location.MapName);
                    break;

                case "Sewer":
                    loc = new Locations.Sewer(map, location.MapName);
                    break;

                default:
                    loc = new GameLocation(map, location.MapName);
                    break;
                }
                loc.isOutdoors = location.Outdoor;
                loc.isFarm     = location.Farmable;
                Game1.locations.Add(loc);
            }
            catch (Exception err)
            {
                ModEntry.Logger.ExitGameImmediately("Unable to add custom location, a unexpected error occured: " + location, err);
            }
        }
Beispiel #23
0
 public T Load <T>(IAssetInfo asset)
 {
     if (asset.AssetName.StartsWith("Animals"))
     {
         string[] splitAssetName = asset.AssetName.Split(System.IO.Path.DirectorySeparatorChar);
         string   chickenType    = splitAssetName[splitAssetName.Length - 1];
         int      isBaby         = 0;
         if (chickenType.StartsWith("Baby"))
         {
             isBaby      = 1;
             chickenType = chickenType.Substring("Baby".Length);
         }
         if (customChickenTextures.ContainsKey(chickenType))
         {
             T      animalTexture;
             string texturePath = customChickenTextures[chickenType][isBaby];
             if (!animalSourcePack.ContainsKey(chickenType))
             {
                 animalTexture = smapiHelper.Content.Load <T>(texturePath, ContentSource.ModFolder);
             }
             else
             {
                 IContentPack contentPack = contentPackNames[animalSourcePack[chickenType]];
                 animalTexture = contentPack.LoadAsset <T>(texturePath);
             }
             return(animalTexture);
         }
     }
     else if (asset.AssetName.StartsWith("LooseSprites"))
     {
         string[] splitAssetName = asset.AssetName.Split(System.IO.Path.DirectorySeparatorChar);
         string   eggType        = splitAssetName[splitAssetName.Length - 1];
         T        eggTexture;
         string   texturePath = System.IO.Path.Combine("assets", "eggs", eggType + ".png");
         if (!eggSourcePack.ContainsKey(eggType))
         {
             eggTexture = smapiHelper.Content.Load <T>(texturePath, ContentSource.ModFolder);
         }
         else
         {
             IContentPack contentPack = contentPackNames[eggSourcePack[eggType]];
             eggTexture = contentPack.LoadAsset <T>(texturePath);
         }
         return(eggTexture);
     }
     return(default(T));
 }
Beispiel #24
0
        /// <summary>Get an asset from the content pack of <see cref="PngTextureCache"/>.</summary>
        /// <typeparam name="T">The asset type.</typeparam>
        /// <param name="contentPack">The content pack.</param>
        /// <param name="key">The asset key.</param>
        public T Load <T>(IContentPack contentPack, string key)
        {
            key = this.GetRealPath(contentPack, key) ?? throw new FileNotFoundException($"The file '{key}' does not exist in the {contentPack.Manifest.Name} content patch folder.");

            // load from PNG cache if applicable
            if (typeof(T) == typeof(Texture2D) && this.IsPngPath(key))
            {
                string actualAssetKey = contentPack.GetActualAssetKey(key);
                if (this.PngTextureCache.TryGetValue(actualAssetKey, out Texture2D texture))
                {
                    return((T)(object)texture);
                }
            }

            // load from pack
            return(contentPack.LoadAsset <T>(key));
        }
Beispiel #25
0
        /// <summary>Loads all the sprites from the specified directory into the correct sprite pool.</summary>
        /// <param name="directory">The absolute directory containing the sprites.</param>
        /// <param name="contentPack">The content pack currently being loaded.</param>
        /// <param name="season">The season to load the images into.</param>
        private void LoadSpritesFromDirectory(string directory, IContentPack contentPack, ContentPackConfig contentPackConfig, string season)
        {
            foreach (var file in Directory.GetFiles(directory))
            {
                // ensure file is an image file
                if (!file.EndsWith(".png"))
                {
                    this.Monitor.Log($"Invalid file in folder: {file}");
                    continue;
                }

                // get the grass texture
                var relativePath = Path.Combine(season, Path.GetFileName(file));

                // a rare bug on Unix causes Directory.GetFiles(string) to return invalid files, it'll return a list of the expected files as well as a copy of each file but prefixed with "._"
                // these files don't actually exist and cause the below to throw an exception, I tried checking if the files started with "._" but that didn't work, in the end silently
                // catching the exception and ignoring it seemed to be the only way for it to work. silently catching shouldn't be a problem here as that shouldn't throw any other exception anyway
                Texture2D grassTexture;
                try { grassTexture = contentPack.LoadAsset <Texture2D>(relativePath); }
                catch { continue; }

                if (grassTexture == null)
                {
                    this.Monitor.Log($"Failed to get grass sprite. Path expected: {relativePath}");
                    continue;
                }

                // add the texture to the correct sprite pool
                var whiteListedLocations = contentPackConfig.WhiteListedLocations ?? new List <string>();
                whiteListedLocations.AddRange(contentPackConfig.WhiteListedGrass.FirstOrDefault(whiteListedGrass => whiteListedGrass.Key.ToLower() == new FileInfo(file).Name.ToLower()).Value ?? new List <string>());

                var blackListedLocations = contentPackConfig.BlackListedLocations ?? new List <string>();
                blackListedLocations.AddRange(contentPackConfig.BlackListedGrass.FirstOrDefault(blackListedGrass => blackListedGrass.Key.ToLower() == new FileInfo(file).Name.ToLower()).Value ?? new List <string>());

                switch (season)
                {
                case "spring": SpringSpritePool.AddCustomGrass(grassTexture, whiteListedLocations, blackListedLocations); break;

                case "summer": SummerSpritePool.AddCustomGrass(grassTexture, whiteListedLocations, blackListedLocations); break;

                case "fall": FallSpritePool.AddCustomGrass(grassTexture, whiteListedLocations, blackListedLocations); break;

                case "winter": WinterSpritePool.AddCustomGrass(grassTexture, whiteListedLocations, blackListedLocations); break;
                }
            }
        }
Beispiel #26
0
        /// <summary>Try to load an asset key as a map file.</summary>
        /// <param name="contentPack">The content pack to load.</param>
        /// <param name="key">The asset key in the content pack.</param>
        /// <param name="map">The loaded map.</param>
        /// <returns>Returns whether the map was successfully loaded.</returns>
        private bool TryLoadMap(IContentPack contentPack, string key, out Map map)
        {
            // ignore if we know it's not a map
            if (!key.EndsWith(".tbin", StringComparison.InvariantCultureIgnoreCase) && !key.EndsWith(".xnb", StringComparison.InvariantCultureIgnoreCase))
            {
                map = null;
                return(false);
            }

            // try to load map
            try
            {
                map = contentPack.LoadAsset <Map>(key);
                return(true);
            }
            catch
            {
                map = null;
                return(false);
            }
        }
Beispiel #27
0
        public static Map Load(string path, IModHelper helper, bool syncTexturesToClients, IContentPack contentPack)
        {
            Map map = contentPack != null?contentPack.LoadAsset <Map>(path) : helper.Content.Load <Map>(path);

            for (int index = 0; index < map.TileSheets.Count; ++index)
            {
                if (string.IsNullOrWhiteSpace(Path.GetDirectoryName(map.TileSheets[index].ImageSource)))
                {
                    map.TileSheets[index].ImageSource = Path.Combine("Maps", Path.GetFileName(map.TileSheets[index].ImageSource));
                }
            }

            if (!(Game1.mapDisplayDevice is PyDisplayDevice))
            {
                bool adjustForCompat = helper.ModRegistry.IsLoaded("DigitalCarbide.SpriteMaster");
                Game1.mapDisplayDevice = new PyDisplayDevice(Game1.content, Game1.graphics.GraphicsDevice, adjustForCompat);
            }

            map?.LoadTileSheets(Game1.mapDisplayDevice);

            return(map);
        }
Beispiel #28
0
        private Texture2D LoadTexture(IContentPack pack, string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return(null);
            }

            try
            {
                if (pack.HasFile(path))
                {
                    return(pack.LoadAsset <Texture2D>(path));
                }

                return(Game1.content.Load <Texture2D>(path));
            }
            catch (ContentLoadException ex)
            {
                this.Monitor.Log($"({pack.Manifest.UniqueID}) Cannot load texture `{path}`: {ex.Message}");

                return(null);
            }
        }
        public void LoadTexture(IContentPack pack)
        {
            _pack    = pack;
            _texture = _pack.LoadAsset <Texture2D>(Sheet);

            if (Frames > 1)
            {
                _texture = new AnimatedTexture2D(_texture, _texture.Width, _texture.Height / Frames, AnimationSpeed, Looped, Scale);
            }
            else if (Scale > 1)
            {
                _texture = new ScaledTexture2D(_texture, Scale);
            }

            if (!Tags.Contains("CustomMovie"))
            {
                Tags.Add("CustomMovie");
            }

            if (!Tags.Contains("CMovieID:" + Id))
            {
                Tags.Add("CMovieID:" + Id);
            }
        }
Beispiel #30
0
        /// <summary>Load the passed content pack.</summary>
        /// <param name="contentPack">The content pack to load.</param>
        private void LoadContentPack(IContentPack contentPack)
        {
            this.Monitor.Log($"Loading content pack: {contentPack.Manifest.Name}", LogLevel.Info);

            // load each tree
            var modDirectory = new DirectoryInfo(contentPack.DirectoryPath);

            foreach (var treePath in modDirectory.EnumerateDirectories())
            {
                // ensure tree.png exists
                var isValid = true;
                if (!File.Exists(Path.Combine(treePath.FullName, "tree.png")))
                {
                    this.Monitor.Log($"tree.png couldn't be found for {contentPack.Manifest.Name}.", LogLevel.Error);
                    isValid = false;
                }

                // ensure content.json exists
                if (!File.Exists(Path.Combine(treePath.FullName, "content.json")))
                {
                    this.Monitor.Log($"content.json couldn't be found for {contentPack.Manifest.Name}.", LogLevel.Error);
                    isValid = false;
                }

                if (!isValid)
                {
                    continue;
                }

                var treeTexture = contentPack.LoadAsset <Texture2D>(Path.Combine(treePath.Name, "tree.png"));
                var treeData    = contentPack.ReadJsonFile <TreeData>(Path.Combine(treePath.Name, "content.json"));
                if (treeData == null)
                {
                    this.Monitor.Log($"Content.json couldn't be found for: {treePath.Name}.", LogLevel.Error);
                    continue;
                }

                treeData.ResolveTokens();
                if (!treeData.IsValid())
                {
                    this.Monitor.Log($"Validation for treeData for: {treePath.Name} failed, skipping.", LogLevel.Error);
                    continue;
                }

                // ensure the tree can be loaded (using IncludeIfModIsPresent)
                {
                    var loadTree = true;
                    if (treeData.IncludeIfModIsPresent != null && treeData.IncludeIfModIsPresent.Count > 0)
                    {
                        // set this to false so it can be set to true if a required mod is found
                        loadTree = false;
                        foreach (var requiredMod in treeData.IncludeIfModIsPresent)
                        {
                            if (!this.Helper.ModRegistry.IsLoaded(requiredMod))
                            {
                                continue;
                            }

                            loadTree = true;
                            break;
                        }
                    }
                    if (!loadTree)
                    {
                        this.Monitor.Log("Tree won't get loaded as no mods specified in 'IncludeIfModIsPresent' were present.", LogLevel.Info);
                        continue;
                    }
                }

                // ensure the tree can be loaded (using ExcludeIfModIsPresent)
                {
                    var loadTree = true;
                    if (treeData.ExcludeIfModIsPresent != null && treeData.ExcludeIfModIsPresent.Count > 0)
                    {
                        foreach (var unwantedMod in treeData.ExcludeIfModIsPresent)
                        {
                            if (!this.Helper.ModRegistry.IsLoaded(unwantedMod))
                            {
                                continue;
                            }

                            loadTree = false;
                            break;
                        }
                    }
                    if (!loadTree)
                    {
                        this.Monitor.Log("Tree won't get loaded as a mod specified in 'ExcludeIfModIsPresent' was present.", LogLevel.Info);
                        continue;
                    }
                }

                // ensure the tree hasn't been added by another mod
                if (LoadedTrees.Where(tree => tree.Name.ToLower() == treePath.Name.ToLower()).Any())
                {
                    this.Monitor.Log($"A tree by the name: {treePath.Name} has already been added.", LogLevel.Error);
                    continue;
                }

                // get the tree type, use the api as they're save persitant
                var treeType = Api.GetTreeType(treePath.Name);

                // add the tree to the loaded trees
                LoadedTrees.Add(new CustomTree(treeType, treePath.Name, treeData, treeTexture));
            }
        }