remove unused serialisation & networking code per discussion

This commit is contained in:
Jesse Plamondon-Willard 2018-12-30 00:01:20 -05:00
parent 713f7d0381
commit 90203315aa
No known key found for this signature in database
GPG Key ID: 7D7C8097B62033CE
33 changed files with 9 additions and 6040 deletions

View File

@ -67,12 +67,6 @@ namespace Omegasis.SaveAnywhere
customMenuOpen = false;
}
/*Notes. Mods that want to support save anywhere will get the api for Save anywhere and then add their clean up code to the events that happen for Before/After Save and Loading.
Example with pseudo code.
SaveAnywhere.api.BeforeSave+=StardustCore.Objects.CleanUpBeforeSave;
We then can use function wrapping (is that what it's called?) to just handle calling the actual function that deals with clean-up code.
*/
/*********
** Private methods
*********/

View File

@ -1,27 +0,0 @@
using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StardustCore.Interfaces
{
/// <summary>
/// Used to extend custom serialization to a variety of items.
/// </summary>
public interface IItemSerializeable
{
/// <summary>
/// Gets the type of object I am trying to parse.
/// </summary>
/// <returns></returns>
Type getCustomType();
/// <summary>
/// Returns the serialization name of the object I am serializing.
/// </summary>
/// <returns></returns>
string GetSerializationName();
}
}

View File

@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StardustCore.Interfaces
{
/// <summary>
/// Used to mark items that are valid tools so we can do things like if(Item is IToolSerializer)
/// </summary>
interface IToolSerializer
{
}
}

View File

@ -1,78 +1,28 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System.Collections.Generic;
using System.IO;
using StardewModdingAPI;
using StardewValley;
using StardewValley.Menus;
using StardewValley.Network;
using StardustCore.Menus;
using StardustCore.ModInfo;
using StardustCore.NetCode;
using StardustCore.Objects;
using StardustCore.Objects.Tools;
using StardustCore.Serialization;
using StardustCore.UIUtilities;
using StardustCore.UIUtilities.SpriteFonts;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
namespace StardustCore
{
/*
*Known issues:
* Clients have a error on Serialization that says they run across unknown XML elements such as core objects. However, inventories for farmhands and modded objects still get serialized properly.
* Inventories get wiped after being returned home from a festival.
*/
public class ModCore : Mod
{
public static IModHelper ModHelper;
public static IMonitor ModMonitor;
public static IManifest Manifest;
public static Serialization.SerializationManager SerializationManager;
public static UIUtilities.TextureManager TextureManager;
public static TextureManager TextureManager;
public static Dictionary<string, TextureManager> TextureManagers;
private Type lastMenuType;
public ModConfig config;
public bool playerJustDisconnected;
public bool justWarped;
public static string ContentDirectory;
public override void Entry(IModHelper helper)
{
ModHelper = Helper;
ModMonitor = Monitor;
Manifest = ModManifest;
//Unused MetaData information. Works in player inventory but not in chests. Besides who really care where an object is from anyways. Also doesn't work 100% like I intended since it only gets base mod object that this runs from, not extensions?
// StardewModdingAPI.Events.GraphicsEvents.OnPostRenderGuiEvent += Metadata.GameEvents_UpdateTick;
//StardewModdingAPI.Events.ControlEvents.MouseChanged += ControlEvents_MouseChanged;
StardewModdingAPI.Events.SaveEvents.AfterSave += SaveEvents_AfterSave;
StardewModdingAPI.Events.SaveEvents.BeforeSave += SaveEvents_BeforeSave;
StardewModdingAPI.Events.SaveEvents.AfterLoad += SaveEvents_AfterLoad;
StardewModdingAPI.Events.MenuEvents.MenuChanged += MenuEvents_MenuChanged;
StardewModdingAPI.Events.MenuEvents.MenuClosed += MenuEvents_MenuClosed;
ModHelper.Events.Multiplayer.PeerContextReceived += Multiplayer_PeerContextReceived;
ModHelper.Events.Multiplayer.ModMessageReceived += Multiplayer_ModMessageReceived;
ModHelper.Events.Multiplayer.PeerDisconnected += Multiplayer_PeerDisconnected;
playerJustDisconnected = false;
ModHelper = this.Helper;
ModMonitor = this.Monitor;
Manifest = this.ModManifest;
IlluminateFramework.Colors.initializeColors();
ContentDirectory = "Content";
@ -82,332 +32,12 @@ namespace StardustCore
TextureManagers = new Dictionary<string, TextureManager>();
TextureManager = new TextureManager();
TextureManager.addTexture("Test1", new Texture2DExtended(ModCore.ModHelper, Manifest,Path.Combine("Content", "Graphics", "MultiTest", "Test1.png")));
TextureManager.addTexture("Test1", new Texture2DExtended(ModCore.ModHelper, Manifest, Path.Combine("Content", "Graphics", "MultiTest", "Test1.png")));
TextureManager.addTexture("Test2", new Texture2DExtended(ModCore.ModHelper, Manifest, Path.Combine("Content", "Graphics", "MultiTest", "Test2.png")));
TextureManager.addTexture("Test3", new Texture2DExtended(ModCore.ModHelper, Manifest, Path.Combine("Content", "Graphics", "MultiTest", "Test3.png")));
TextureManagers.Add(ModManifest.UniqueID, TextureManager);
StardewModdingAPI.Events.ControlEvents.KeyPressed += ControlEvents_KeyPressed;
TextureManagers.Add(this.ModManifest.UniqueID, TextureManager);
ModHelper.Events.World.ObjectListChanged += World_ObjectListChanged;
config = ModHelper.ReadConfig<ModConfig>();
StardewModdingAPI.Events.GameEvents.UpdateTick += GameEvents_UpdateTick;
Helper.Events.Player.Warped += Player_Warped;
ModHelper.Events.GameLoop.ReturnedToTitle += GameLoop_ReturnedToTitle;
}
private void World_ObjectListChanged(object sender, StardewModdingAPI.Events.ObjectListChangedEventArgs e)
{
if (e.Added != null)
{
}
else if (e.Removed != null)
{
}
}
private void Player_Warped(object sender, StardewModdingAPI.Events.WarpedEventArgs e)
{
if (justWarped) return;
SerializationManager.cleanUpInventory();
//SerializationManager.cleanUpWorld();
//SerializationManager.cleanUpStorageContainers();
justWarped = true;
}
private void GameLoop_ReturnedToTitle(object sender, StardewModdingAPI.Events.ReturnedToTitleEventArgs e)
{
if (Game1.player != null)
{
SerializationManager.cleanUpInventory();
//SerializationManager.cleanUpWorld();
//SerializationManager.cleanUpStorageContainers();
//Monitor.Log("Saved the player data after returning to title!");
}
}
private void Multiplayer_PeerDisconnected(object sender, StardewModdingAPI.Events.PeerDisconnectedEventArgs e)
{
this.playerJustDisconnected = true;
//ModMonitor.Log("Peer disconnected! Serializing custom objects");
SerializationManager.cleanUpInventory();
//SerializationManager.cleanUpWorld();
//SerializationManager.cleanUpStorageContainers();
}
private void Multiplayer_ModMessageReceived(object sender, StardewModdingAPI.Events.ModMessageReceivedEventArgs e)
{
//ModMonitor.Log("Get messages from"+e.FromModID);
//ModMonitor.Log("Message type: " + e.Type);
if (e.FromModID == this.ModManifest.UniqueID)
{
if (e.Type == MultiplayerSupport.CleanUpModObjects)
{
SerializationManager.cleanUpInventory();
SerializationManager.cleanUpWorld();
SerializationManager.cleanUpStorageContainers();
}
else if (e.Type == MultiplayerSupport.RestoreModObjects)
{
if (Game1.eventUp) return; //Prevent item duplication.
//ModMonitor.Log("Restoring custom objects.");
SerializationManager.restoreAllModObjects(SerializationManager.trackedObjectList);
}
}
}
private void Multiplayer_PeerContextReceived(object sender, StardewModdingAPI.Events.PeerContextReceivedEventArgs e)
{
if (SerializationManager == null) return;
if (Game1.eventUp)
{
SerializationManager.restoreAllModObjects(SerializationManager.trackedObjectList); //Force a restore and then a serialize save to prevent deletions.
}
//ModMonitor.Log("Got peer context. Serialize/remove all custom objects really quick to prevent loading errors.");
SerializationManager.cleanUpInventory();
//SerializationManager.cleanUpWorld();
//SerializationManager.cleanUpStorageContainers();
}
private void MenuEvents_MenuClosed(object sender, StardewModdingAPI.Events.EventArgsClickableMenuClosed e)
{
if (this.lastMenuType == null)
{
return;
}
else
{
/*
if (lastMenuType == typeof(StardewValley.Menus.SaveGameMenu) ||lastMenuType==typeof(StardewValley.Menus.ShippingMenu))
{
SerializationManager.restoreAllModObjects(SerializationManager.trackedObjectList);
List<long> playerIds = new List<long>();
foreach (Farmer f in Game1.getAllFarmers())
{
if (f == Game1.player) continue;
playerIds.Add(f.uniqueMultiplayerID);
}
ModHelper.Multiplayer.SendMessage<string>(MultiplayerSupport.RestoreModObjects, MultiplayerSupport.RestoreModObjects, new string[] { ModManifest.UniqueID }, playerIds.ToArray());
}
*/
//Only fires in multiplayer since ReadyCheckDialogue only appears in multiplayer
if (lastMenuType == typeof(StardewValley.Menus.ReadyCheckDialog) && Game1.player.canMove==false && Game1.player.isInBed)
{
//ModMonitor.Log("Time to sleep/serialize all objects!");
SerializationManager.cleanUpInventory();
SerializationManager.cleanUpWorld();
SerializationManager.cleanUpStorageContainers();
/*
List<long> playerIds = new List<long>();
foreach (Farmer f in Game1.getAllFarmers())
{
if (f == null) continue;
if (f == Game1.player) continue;
playerIds.Add(f.uniqueMultiplayerID);
}
*/
//ModHelper.Multiplayer.SendMessage<string>(MultiplayerSupport.CleanUpModObjects, MultiplayerSupport.CleanUpModObjects, new string[] { ModManifest.UniqueID }, playerIds.ToArray());
}
}
}
private void MenuEvents_MenuChanged(object sender, StardewModdingAPI.Events.EventArgsClickableMenuChanged e)
{
lastMenuType = Game1.activeClickableMenu.GetType();
}
/// <summary>
/// Returns the value of the data snagged by reflection.
/// </summary>
/// <param name="type"></param>
/// <param name="instance"></param>
/// <param name="fieldName"></param>
/// <returns></returns>
public static object GetInstanceField(Type type, object instance, string fieldName)
{
BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
FieldInfo field = type.GetField(fieldName, bindFlags);
/*
FieldInfo[] meh = type.GetFields(bindFlags);
foreach(var v in meh)
{
if (v.Name == null)
{
continue;
}
Monitor.Log(v.Name);
}
*/
return field.GetValue(instance);
}
public static void SetInstanceField(Type type, object instance, object value, string fieldName)
{
BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Static;
FieldInfo field = type.GetField(fieldName, bindFlags);
field.SetValue(instance, value);
return;
}
private void GameEvents_UpdateTick(object sender, EventArgs e)
{
if (playerJustDisconnected)
{
playerJustDisconnected = false;
if (Game1.activeClickableMenu != null)
{
if (Game1.activeClickableMenu.GetType() == typeof(StardewValley.Menus.TitleMenu)) return;
}
//ModMonitor.Log("Restore objects after peer disconnect!");
SerializationManager.restoreAllModObjects(SerializationManager.trackedObjectList);
}
else if (justWarped && Game1.eventUp==false && Game1.activeClickableMenu==null)
{
justWarped = false;
//ModMonitor.Log("Restore objects after player warping!");
SerializationManager.restoreAllModObjects(SerializationManager.trackedObjectList,true);
}
}
private void ControlEvents_KeyPressed(object sender, StardewModdingAPI.Events.EventArgsKeyPressed e)
{
if(e.KeyPressed.ToString()== config.modularMenuKey && Game1.activeClickableMenu==null)
{
//Game1.activeClickableMenu = new ModularGameMenu(0);
}
}
private void SaveEvents_AfterLoad(object sender, EventArgs e)
{
Game1.game1.Disposed += Game1_Disposed;
string basePath=Path.Combine( ModCore.ModHelper.DirectoryPath, "PlayerData", Game1.player.Name + "_" + Game1.player.uniqueMultiplayerID);
string invPath = Path.Combine(basePath,"PlayerInventory");
string worldPath = Path.Combine(basePath, "ObjectsInWorld");
string trashPath = Path.Combine(basePath,"ModTrashFolder");
string chestPath = Path.Combine(basePath, "StorageContainers");
SerializationManager = new SerializationManager(invPath, trashPath, worldPath, chestPath);
SerializationManager.initializeDefaultSuportedTypes();
SerializationManager.restoreAllModObjects(SerializationManager.trackedObjectList);
List<long> playerIds = new List<long>();
foreach (Farmer f in Game1.getOnlineFarmers())
{
if (f.uniqueMultiplayerID == Game1.player.uniqueMultiplayerID) continue;
playerIds.Add(f.uniqueMultiplayerID);
ModMonitor.Log("Sending Message to peer ID: "+f.uniqueMultiplayerID.ToString());
}
//ModMonitor.Log("Send message to restore mod objects after load!");
ModHelper.Multiplayer.SendMessage<string>(MultiplayerSupport.RestoreModObjects, MultiplayerSupport.RestoreModObjects, new string[] { ModManifest.UniqueID },playerIds.ToArray());
/*
List<KeyValuePair<Vector2, MultiTileComponent>> objs = new List<KeyValuePair<Vector2, MultiTileComponent>>();
MultiTileComponent tile1 = new MultiTileComponent(0,"Tileobj1","A basic tile obj",new Texture2DExtended(ModCore.ModHelper,ModCore.Manifest ,Path.Combine("Content", "Graphics", "MultiTest", "Test1.png")));
MultiTileComponent tile2 = new MultiTileComponent(0,"Tileobj2", "A basic tile obj", new Texture2DExtended(ModCore.ModHelper, ModCore.Manifest, Path.Combine("Content", "Graphics", "MultiTest", "Test2.png")));
MultiTileComponent tile3 = new MultiTileComponent(0,"Tileobj3", "A basic tile obj", new Texture2DExtended(ModCore.ModHelper, ModCore.Manifest, Path.Combine("Content", "Graphics", "MultiTest", "Test3.png")));
objs.Add(new KeyValuePair<Vector2, MultiTileComponent>(new Vector2(0, 0), tile1));
objs.Add(new KeyValuePair<Vector2, MultiTileComponent>(new Vector2(1, 0), tile2));
objs.Add(new KeyValuePair<Vector2, MultiTileComponent>(new Vector2(2, 0), tile3));
MultiTileObject collection= new MultiTileObject("MultiTest", "Trying to get multi object testing working", Vector2.Zero, new Texture2DExtended(ModCore.ModHelper, ModCore.Manifest, Path.Combine("Content", "Graphics", "MultiTest", "Test3.png")), objs, StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.LightColorsList.Purple), "MultiTest");
Game1.player.addItemToInventory(collection);
*/
/*
CoreObject testTile = new CoreObject(new Texture2DExtended(ModCore.ModHelper,ModCore.Manifest, Path.Combine("Content", "Graphics", "MultiTest", "Test3.png")),3, Vector2.Zero,9);
testTile.description = "Hello";
testTile.Name = "test";
testTile.displayName = "test";
Game1.player.addItemToInventory(testTile);
*/
}
private void Game1_Disposed(object sender, EventArgs e)
{
if (Game1.player != null && lastMenuType!= typeof(StardewValley.Menus.TitleMenu))
{
//ModMonitor.Log("Serialize all objects on disposing!");
SerializationManager.cleanUpInventory();
//SerializationManager.cleanUpWorld();
//SerializationManager.cleanUpStorageContainers();
}
}
private void SaveEvents_AfterSave(object sender, EventArgs e)
{
SerializationManager.restoreAllModObjects(SerializationManager.trackedObjectList);
}
private void SaveEvents_BeforeSave(object sender, EventArgs e)
{
//Call the serialization if alone since the ReadyCheckDialogue menu never shows with just 1 player online.
if (Game1.IsMultiplayer == false || (Game1.IsMultiplayer && Game1.getOnlineFarmers().Count==1))
{
//ModMonitor.Log("Serialize all objects before save when only 1 farmer present!");
SerializationManager.cleanUpInventory();
SerializationManager.cleanUpWorld();
SerializationManager.cleanUpStorageContainers();
}
}
private void ControlEvents_MouseChanged(object sender, StardewModdingAPI.Events.EventArgsMouseStateChanged e)
{
//???
return;
if (Game1.activeClickableMenu == null) return;
var MouseState = Mouse.GetState();
if (Game1.activeClickableMenu is StardewValley.Menus.ItemGrabMenu && MouseState.LeftButton == ButtonState.Released)
{
(Game1.activeClickableMenu as StardewValley.Menus.ItemGrabMenu).ItemsToGrabMenu.populateClickableComponentList();
for (int index = 0; index < (Game1.activeClickableMenu as StardewValley.Menus.ItemGrabMenu).ItemsToGrabMenu.inventory.Count; ++index)
{
if ((Game1.activeClickableMenu as StardewValley.Menus.ItemGrabMenu).ItemsToGrabMenu.inventory[index] != null)
{
(Game1.activeClickableMenu as StardewValley.Menus.ItemGrabMenu).ItemsToGrabMenu.inventory[index].myID += 53910;
(Game1.activeClickableMenu as StardewValley.Menus.ItemGrabMenu).ItemsToGrabMenu.inventory[index].upNeighborID += 53910;
(Game1.activeClickableMenu as StardewValley.Menus.ItemGrabMenu).ItemsToGrabMenu.inventory[index].rightNeighborID += 53910;
(Game1.activeClickableMenu as StardewValley.Menus.ItemGrabMenu).ItemsToGrabMenu.inventory[index].downNeighborID = -7777;
(Game1.activeClickableMenu as StardewValley.Menus.ItemGrabMenu).ItemsToGrabMenu.inventory[index].leftNeighborID += 53910;
(Game1.activeClickableMenu as StardewValley.Menus.ItemGrabMenu).ItemsToGrabMenu.inventory[index].fullyImmutable = true;
}
}
// (Game1.activeClickableMenu as ItemGrabMenu).inventory.playerInventory = false;
// Game1.activeClickableMenu =Game1.activeClickableMenu;//new ItemGrabMenu((Game1.activeClickableMenu as ItemGrabMenu).ItemsToGrabMenu.actualInventory,true,true,null,null,null,null,false,false,true,true,true,1,null,-1,null);
}
this.config = ModHelper.ReadConfig<ModConfig>();
}
}
}

View File

@ -1,270 +0,0 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StardewModdingAPI;
using StardewValley;
using StardewValley.Menus;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace StardustCore.ModInfo
{
/// <summary>
/// Handles things like displaying object class types.
/// </summary>
public class Metadata
{
Color ModInfoColor;
string ModName;
/// <summary>
///
/// </summary>
/// <param name="modColor"></param>
/// <param name="modName"></param>
private Metadata(Color ? modColor,string modName="")
{
if (modColor == null) ModInfoColor = Color.Black;
else ModInfoColor =(Color) modColor;
ModName = modName;
}
/// <summary>
/// Parse the name of the mod that this object is from from the Namespace type.
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static string parseModNameFromType(Type t)
{
string s = t.ToString();
string[] array = s.Split('.');
return array[0];
}
/// <summary>
/// Parse the class inside of the mod's namespace that this object is from.
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static string parseClassNameFromType(Type t)
{
string s = t.ToString();
string[] array = s.Split('.');
return array[array.Length-1];
}
/// <summary>
/// TODO: Add the ModClass item check to chest inventory. See if I can grab activeclickable menu and instead hook the inventory component from it.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public static void GameEvents_UpdateTick(object sender, EventArgs e)
{
if (Game1.activeClickableMenu != null)
{
// if (Game1.activeClickableMenu.allClickableComponents == null) return;
try {
List<IClickableMenu> pages = ModCore.ModHelper.Reflection.GetField<List<IClickableMenu>>(Game1.activeClickableMenu, "pages").GetValue();
if (Game1.activeClickableMenu is GameMenu)
{
StardewValley.Menus.IClickableMenu s = pages[(Game1.activeClickableMenu as GameMenu).currentTab];
foreach (var v in s.allClickableComponents)
{
if (v.containsPoint(Game1.getMouseX(), Game1.getMouseY()))
{
if (v == null) continue;
string fire = v.name;
bool num = true;
foreach (var v2 in fire)
{
if (v2 != '0' && v2 != '1' && v2 != '2' && v2 != '3' && v2 != '4' && v2 != '5' && v2 != '6' && v2 != '7' && v2 != '8' && v2 != '9')
{
num = false;
break;
}
else continue;
}
if (num == true)
{
int inv = Convert.ToInt32(v.name);
Item I = (s as StardewValley.Menus.InventoryPage).inventory.actualInventory[inv];
string s1 = parseModNameFromType(I.GetType());
string s2 = parseClassNameFromType(I.GetType());
string s3 = Assembly.GetAssembly(I.GetType()).Location;
s3 = Path.GetFileName(s3);
//DRAW THE INFO BOX!!!
try
{
SpriteBatch b = new SpriteBatch(Game1.graphics.GraphicsDevice);
b.Begin();
float boxX =Game1.getMouseX()- (Game1.viewport.Width * .25f);
float boxY =Game1.getMouseY() - (Game1.viewport.Height * .05f);
float boxWidth= (Game1.viewport.Width * .25f);
float boxHeight = (Game1.viewport.Height*.35f);
Game1.drawDialogueBox((int)boxX,(int) boxY,(int)boxWidth, (int)boxHeight, false, true, null,false);
float xText1XPos = boxX + (Game1.viewport.Width * .08f);
float xText2XPos = boxX + (Game1.viewport.Width * .08f);
if (s1.Length > 12)
{
s1 = "\n" + s1;
xText1XPos = boxX + (Game1.viewport.Width * .025f);
}
if (s2.Length > 12)
{
s2 = "\n" + s2;
xText2XPos = boxX + (Game1.viewport.Width * .025f);
}
if (s3.Length > 12)
{
s3 = "\n" + s3;
xText1XPos = boxX + (Game1.viewport.Width * .025f);
}
Utility.drawTextWithShadow(Game1.spriteBatch, "Mod: ", Game1.smallFont, new Vector2(boxX + (Game1.viewport.Width * .025f), Game1.getMouseY() + (int)(Game1.viewport.Height * .1f)), Color.Black, 1, -1);
Utility.drawTextWithShadow(Game1.spriteBatch, s3, Game1.smallFont, new Vector2(xText1XPos, Game1.getMouseY()+(int)(Game1.viewport.Height*.1f)), Color.Black, 1, -1);
Utility.drawTextWithShadow(Game1.spriteBatch, "Class: ", Game1.smallFont, new Vector2(boxX + (Game1.viewport.Width * .025f), Game1.getMouseY() + (int)(Game1.viewport.Height * .2f)), Color.Black, 1, -1);
Utility.drawTextWithShadow(Game1.spriteBatch, s2, Game1.smallFont, new Vector2(xText2XPos, Game1.getMouseY() + (int)(Game1.viewport.Height * .2f)), I.getCategoryColor(), 1, -1);
b.End();
}
catch(Exception errr)
{
errr.ToString();
}
}
}
// if (v == null) continue;
// Log.AsyncC(v.name);
// Log.AsyncM(v.item.Name);
// (s as StardewValley.Menus.InventoryPage).
}
}
}
catch(Exception err) //Try to parse a menu that isn't the default GameMenu
{
err.ToString();
try
{
List<Item> inventory = (List<Item>)Game1.activeClickableMenu.GetType().GetProperty("inventory").GetValue(Game1.activeClickableMenu, null);
}
catch(Exception errr)
{
errr.ToString();
try
{
IClickableMenu s = (Game1.activeClickableMenu as ItemGrabMenu).ItemsToGrabMenu;
if (s == null) return;
int i = 0;
foreach (var v in s.allClickableComponents)
{
i++;
if (v.containsPoint(Game1.getMouseX(), Game1.getMouseY()))
{
if (v == null || v.name=="") continue;
string fire = v.name;
bool num = true;
foreach (var v2 in fire)
{
if (v2 != '0' && v2 != '1' && v2 != '2' && v2 != '3' && v2 != '4' && v2 != '5' && v2 != '6' && v2 != '7' && v2 != '8' && v2 != '9')
{
num = false;
break;
}
else continue;
}
///NUM ISN't TRUE!?!?!?!?
if (num == true)
{
int inv = Convert.ToInt32(v.name);
Item I = (s as InventoryMenu).actualInventory[inv]; //Inventory Menu is the actual menu under ItemGrabMenu
// Item I = (s as StardewValley.Menus.ItemGrabMenu).inventory.actualInventory[inv]; ///I isn't being grabbed???
string s1 = parseModNameFromType(I.GetType());
string s2 = parseClassNameFromType(I.GetType());
string s3 = Assembly.GetAssembly(I.GetType()).Location;
s3 = Path.GetFileName(s3);
//Draw the info Box!
try
{
float boxX = Game1.getMouseX() - (Game1.viewport.Width * .25f);
float boxY = Game1.getMouseY() - (Game1.viewport.Height * .05f);
float boxWidth = (Game1.viewport.Width * .25f);
float boxHeight = (Game1.viewport.Height * .35f);
Game1.drawDialogueBox((int)boxX, (int)boxY, (int)boxWidth, (int)boxHeight, false, true, null, false);
float xText1XPos = boxX + (Game1.viewport.Width * .08f);
float xText2XPos = boxX + (Game1.viewport.Width * .08f);
if (s1.Length > 12)
{
s1 = "\n" + s1;
xText1XPos = boxX + (Game1.viewport.Width * .025f);
}
if (s2.Length > 12)
{
s2 = "\n" + s2;
xText2XPos = boxX + (Game1.viewport.Width * .025f);
}
if (s3.Length > 12)
{
s3 = "\n" + s3;
xText1XPos = boxX + (Game1.viewport.Width * .025f);
}
Utility.drawTextWithShadow(Game1.spriteBatch, "Mod: ", Game1.smallFont, new Vector2(boxX + (Game1.viewport.Width * .025f), Game1.getMouseY() + (int)(Game1.viewport.Height * .1f)), Color.Black, 1, -1);
Utility.drawTextWithShadow(Game1.spriteBatch, s3, Game1.smallFont, new Vector2(xText1XPos, Game1.getMouseY() + (int)(Game1.viewport.Height * .1f)), Color.Black, 1, -1);
Utility.drawTextWithShadow(Game1.spriteBatch, "Class: ", Game1.smallFont, new Vector2(boxX + (Game1.viewport.Width * .025f), Game1.getMouseY() + (int)(Game1.viewport.Height * .2f)), Color.Black, 1, -1);
Utility.drawTextWithShadow(Game1.spriteBatch, s2, Game1.smallFont, new Vector2(xText2XPos, Game1.getMouseY() + (int)(Game1.viewport.Height * .2f)), I.getCategoryColor(), 1, -1);
}
catch (Exception errrr)
{
errrr.ToString();
}
}
}
// if (v == null) continue;
// Log.AsyncC(v.name);
// Log.AsyncM(v.item.Name);
// (s as StardewValley.Menus.InventoryPage).
}
}
catch(Exception errrr)
{
errrr.ToString();
}
}
}
}
}
}
}

View File

@ -1,65 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Netcode;
using StardustCore.Animations;
namespace StardustCore.NetCode.Graphics
{
public class NetAnimation : Netcode.NetField<Animations.Animation, NetAnimation>
{
public NetRectangle sourceRect;
public NetInt frameDuration;
public NetInt frameDurationUntilNextAnimation;
public NetAnimation()
{
}
public NetAnimation(Animations.Animation animation) : base(animation)
{
this.Set(animation);
}
public override void Set(Animation newValue)
{
this.value = newValue;
}
protected override void ReadDelta(BinaryReader reader, NetVersion version)
{
sourceRect = new NetRectangle();
if (sourceRect == null) throw new Exception("WTF??? Why is netfield null");
if (reader == null) throw new Exception("reader null");
if (value == null) this.Set(new Animation());
sourceRect.Read(reader, version);
Value.sourceRectangle = sourceRect.Value;
frameDuration = new NetInt();
frameDuration.Read(reader, version);
Value.frameDuration = frameDuration.Value;
frameDurationUntilNextAnimation = new NetInt();
frameDurationUntilNextAnimation.Read(reader, version);
Value.frameCountUntilNextAnimation = frameDurationUntilNextAnimation.Value;
}
protected override void WriteDelta(BinaryWriter writer)
{
sourceRect = new NetRectangle(Value.sourceRectangle);
sourceRect.Write(writer);
frameDuration = new NetInt(Value.frameDuration);
frameDuration.Write(writer);
frameDurationUntilNextAnimation = new NetInt(Value.frameCountUntilNextAnimation);
frameDurationUntilNextAnimation.Write(writer);
}
}
}

View File

@ -1,143 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Netcode;
using StardewValley;
using StardewValley.Network;
using StardustCore.Animations;
namespace StardustCore.NetCode.Graphics
{
public class NetAnimationManager : Netcode.NetField<Animations.AnimationManager, NetAnimationManager>
{
public NetAnimationManager()
{
}
public NetAnimationManager(Animations.AnimationManager manager) : base(manager)
{
this.Set(manager);
}
public NetString currentAnimationName;
public NetInt currentAnimationListIndex;
public NetTexture2DExtended objectTexture;
public NetAnimation defaultDrawFrame;
public NetBool enabled;
public NetString animationDataString;
protected override void ReadDelta(BinaryReader reader, NetVersion version)
{
//Checks to see if the current animation is nothing, aka null.
NetBool isNull = new NetBool();
isNull.Read(reader, version);
bool valueIsNull = isNull.Value;
if (isNull)
{
NetTexture2DExtended nullTexture = new NetTexture2DExtended();
nullTexture.Read(reader, version);
NetAnimation nullAnimation = new NetAnimation();
nullAnimation.Read(reader, version);
Value.setExtendedTexture(nullTexture.Value);
Value.defaultDrawFrame = nullAnimation.Value;
return;
}
NetString currentAnimationName = new NetString();
currentAnimationName.Read(reader, version);
NetInt currentIndex = new NetInt();
currentIndex.Read(reader, version);
NetTexture2DExtended text = new NetTexture2DExtended();
text.Read(reader, version);
NetAnimation defaultAnimation = new NetAnimation();
defaultAnimation.Read(reader, version);
NetBool enabled = new NetBool();
enabled.Read(reader, version);
NetString data = new NetString();
data.Read(reader, version);
Value.setExtendedTexture(text.Value);
Value.defaultDrawFrame = defaultAnimation.Value;
Value.enabled = enabled.Value;
//Try and prevent unnecessary parsing.
if (Value.animations == null && !String.IsNullOrEmpty(Value.animationDataString))
{
Value.animations = Animations.AnimationManager.parseAnimationsFromXNB(data.Value);
}
if (!String.IsNullOrEmpty(data.Value))
{
Value.setAnimation(currentAnimationName.Value, currentIndex.Value);
}
else
{
Value.currentAnimation = defaultDrawFrame.Value;
}
}
protected override void WriteDelta(BinaryWriter writer)
{
if (String.IsNullOrEmpty(Value.currentAnimationName))
{
NetBool isNull = new NetBool(true);
writer.Write(isNull);
NetTexture2DExtended defaultTexture = new NetTexture2DExtended(Value.getExtendedTexture());
defaultTexture.Write(writer);
//do read/write null values here!!!
if (Value == null) throw new Exception("DONT WRITE A NULL VALUE!!!!");
NetAnimation drawFrame = new NetAnimation(Value.defaultDrawFrame);
drawFrame.Write(writer);
return;
//throw new Exception("Null string value for currentAnimationName!");
}
else
{
NetBool isNull = new NetBool(false);
writer.Write(isNull);
}
NetString curentAnimationName = new NetString(!String.IsNullOrEmpty(Value.currentAnimationName) ? Value.currentAnimationName : "");
currentAnimationName.Write(writer);
NetInt currentAnimationListIndex = new NetInt(Value.currentAnimationListIndex);
currentAnimationListIndex.Write(writer);
NetTexture2DExtended texture = new NetTexture2DExtended(Value.getExtendedTexture());
texture.Write(writer);
//do read/write null values here!!!
NetAnimation defaultDrawFrame = new NetAnimation(Value.defaultDrawFrame);
defaultDrawFrame.Write(writer);
NetBool enabled = new NetBool(Value.enabled);
enabled.Write(writer);
NetString animationData = new NetString(Value.animationDataString);
animationData.Write(writer);
}
public override void Set(AnimationManager newValue)
{
this.value = newValue;
}
}
}

View File

@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StardustCore.NetCode
{
public class MultiplayerSupport
{
public static string CleanUpModObjects = "Omegasis.StardustCore.MultiplayerSupport.CleanUpModObjects";
public static string RestoreModObjects = "Omegasis.StardustCore.MultiplayerSupport.RestoreModObjects";
}
}

View File

@ -1,99 +0,0 @@
using System;
using System.IO;
using Lidgren.Network;
namespace StardustCore.NetCode
{
public class NetBufferReadStream : Stream
{
private long offset;
public NetBuffer Buffer;
public NetBufferReadStream(NetBuffer buffer)
{
this.Buffer = buffer;
this.offset = buffer.Position;
}
public override bool CanRead
{
get
{
return true;
}
}
public override bool CanSeek
{
get
{
return true;
}
}
public override bool CanWrite
{
get
{
return false;
}
}
public override long Length
{
get
{
return ((long)this.Buffer.LengthBits - this.offset) / 8L;
}
}
public override long Position
{
get
{
return (this.Buffer.Position - this.offset) / 8L;
}
set
{
this.Buffer.Position = this.offset + value * 8L;
}
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count)
{
this.Buffer.ReadBytes(buffer, offset, count);
return count;
}
public override long Seek(long offset, SeekOrigin origin)
{
switch (origin)
{
case SeekOrigin.Begin:
this.Position = offset;
break;
case SeekOrigin.Current:
this.Position += offset;
break;
case SeekOrigin.End:
this.Position = this.Length + offset;
break;
}
return this.Position;
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
}
}

View File

@ -1,97 +0,0 @@
using System;
using System.IO;
using Lidgren.Network;
namespace StardustCore.NetCode
{
public class NetBufferWriteStream : Stream
{
private int offset;
public NetBuffer Buffer;
public NetBufferWriteStream(NetBuffer buffer)
{
this.Buffer = buffer;
this.offset = buffer.LengthBits;
}
public override bool CanRead
{
get
{
return false;
}
}
public override bool CanSeek
{
get
{
return true;
}
}
public override bool CanWrite
{
get
{
return true;
}
}
public override long Length
{
get
{
throw new NotSupportedException();
}
}
public override long Position
{
get
{
return (long)((this.Buffer.LengthBits - this.offset) / 8);
}
set
{
this.Buffer.LengthBits = (int)((long)this.offset + value * 8L);
}
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
switch (origin)
{
case SeekOrigin.Begin:
this.Position = offset;
break;
case SeekOrigin.Current:
this.Position += offset;
break;
case SeekOrigin.End:
throw new NotSupportedException();
}
return this.Position;
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
this.Buffer.Write(buffer, offset, count);
}
}
}

View File

@ -1,30 +0,0 @@
using Netcode;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StardustCore.NetCode
{
public class NetKeyValuePair<K, V, KField, VField> : NetField<KeyValuePair<K, V>, NetKeyValuePair<K, V, KField, VField>> where KField : NetField<K, KField>, new() where VField : NetField<V, VField>, new()
{
public override void Set(KeyValuePair<K, V> newValue)
{
this.value = newValue;
}
protected override void ReadDelta(BinaryReader reader, NetVersion version)
{
throw new NotImplementedException();
}
protected override void WriteDelta(BinaryWriter writer)
{
throw new NotImplementedException();
}
}
}

View File

@ -1,36 +0,0 @@
using Microsoft.Xna.Framework;
using Netcode;
using StardustCore.Objects;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StardustCore.NetCode.NetPairs
{
public class NetVector2MultiTilePair<K,KField>: NetKeyValuePair<Vector2,MultiTileComponent,Netcode.NetVector2,NetCode.Objects.NetMultiTileComponent>
{
public NetVector2MultiTilePair()
{
}
public NetVector2MultiTilePair(KeyValuePair<Vector2,MultiTileComponent> hello)
{
this.Set(Value);
}
public override void Read(BinaryReader reader, NetVersion version)
{
base.Read(reader, version);
}
public override void Write(BinaryWriter writer)
{
base.Write(writer);
}
}
}

View File

@ -1,84 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Netcode;
using StardewValley;
using StardustCore.UIUtilities;
namespace StardustCore.NetCode
{
public class NetTexture2DExtended : Netcode.NetField<UIUtilities.Texture2DExtended, NetTexture2DExtended>
{
public NetTexture2DExtended()
{
}
public NetTexture2DExtended(Texture2DExtended value) : base(value)
{
this.Set(value);
}
public void ReadData(BinaryReader reader, NetVersion version)
{
ReadDelta(reader, version);
}
public override void Set(Texture2DExtended newValue)
{
this.value = newValue;
}
public void WriteData(BinaryWriter writer)
{
WriteDelta(writer);
}
protected override void ReadDelta(BinaryReader reader, NetVersion version)
{
NetString name = new NetString();
name.Read(reader, version);
NetString iD = new NetString();
iD.Read(reader, version);
StardustCore.ModCore.ModMonitor.Log("Name: "+name);
StardustCore.ModCore.ModMonitor.Log("Mod ID:"+iD);
//Texture2D texture = new Texture2D(Game1.graphics.GraphicsDevice,width,height);
if (String.IsNullOrEmpty(iD.Value) || String.IsNullOrEmpty(name.Value))
{
ModCore.ModMonitor.Log("FOR SOME REASON THE TEXTURE INFO IS NULL????");
return;
}
Texture2DExtended texture = ModCore.TextureManagers[iD.Value].getTexture(name.Value);
if (texture == null) throw new Exception("FOR SOME REASON NULL IS BEING READ???");
this.Value = texture;
}
protected override void WriteDelta(BinaryWriter writer)
{
NetString name = new NetString(Value.Name);
name.Write(writer);
NetString iD = new NetString(Value.modID);
iD.Write(writer);
}
}
}

View File

@ -1,160 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using Netcode;
using StardewValley;
using StardustCore.NetCode.Graphics;
using StardustCore.UIUtilities;
namespace StardustCore.NetCode
{
/*
* Need to send default source rect and width
*
*/
public class NetCoreObject : Netcode.NetField<CoreObject, NetCoreObject>
{
public NetInt which;
public NetVector2 tilePos;
public NetRectangle boundingBox;
public NetVector2 position;
public NetInt Decoration_type;
public NetInt rotations;
public NetInt currentRotation;
public NetInt sourceIndexOffset;
public NetVector2 drawPosition;
public NetRectangle sourceRect;
public NetRectangle defaultSourceRect;
public NetRectangle defaultBoundingBox;
public NetString description;
public NetTexture2DExtended texture;
public NetBool flipped;
public NetBool flaggedForPickup;
public NetBool lightGlowAdded;
public NetObjectList<Item> inventory;
public NetInt InventoryMaxSize;
public NetBool itemReadyForHarvest;
public NetBool lightsOn;
public NetString locationName;
public NetColor lightColor;
public NetBool removable;
public NetColor drawColor;
public NetBool useXML;
public NetString serializationName;
//Animation Manager.....
public NetAnimationManager animationManager;
public NetCoreObject()
{
}
public NetCoreObject(CoreObject value) : base(value)
{
Set(value);
}
public override void Set(CoreObject newValue)
{
this.value = newValue;
}
protected override void ReadDelta(BinaryReader reader, NetVersion version)
{
texture = new NetTexture2DExtended();
texture.Read(reader, version);
Value.setExtendedTexture(texture.Value);
which = new NetInt();
which.Read(reader, version);
Value.ParentSheetIndex = which.Value;
tilePos = new NetVector2();
tilePos.Read(reader, version);
Value.TileLocation = tilePos.Value;
InventoryMaxSize = new NetInt();
InventoryMaxSize.Read(reader, version);
Value.inventoryMaxSize = InventoryMaxSize.Value;
sourceRect = new NetRectangle();
sourceRect.Read(reader, version);
Value.sourceRect = sourceRect.Value;
boundingBox = new NetRectangle();
boundingBox.Read(reader, version);
Value.boundingBox.Value = boundingBox.Value;
drawPosition = new NetVector2();
drawPosition.Read(reader, version);
Value.drawPosition = drawPosition.Value;
locationName = new NetString();
locationName.Read(reader, version);
Value.locationsName = locationName.Value;
Value.thisLocation = Game1.getLocationFromName(locationName.Value);
/*
animationManager = new NetAnimationManager();
animationManager.Read(reader, version);
Value.animationManager = animationManager.Value;
*/
}
protected override void WriteDelta(BinaryWriter writer)
{
texture = new NetTexture2DExtended(Value.getExtendedTexture());
texture.Write(writer);
which = new NetInt(Value.ParentSheetIndex);
which.Write(writer);
tilePos = new NetVector2(Value.TileLocation);
tilePos.Write(writer);
InventoryMaxSize = new NetInt(Value.inventoryMaxSize);
InventoryMaxSize.Write(writer);
sourceRect = new NetRectangle(Value.sourceRect);
sourceRect.Write(writer);
boundingBox = new NetRectangle(Value.boundingBox.Value);
sourceRect.Write(writer);
drawPosition = new NetVector2(Value.drawPosition);
drawPosition.Write(writer);
locationName = new NetString(Value.locationsName);
locationName.Write(writer);
/*
if (Value.animationManager == null)
{
throw new Exception("WTF, why is the animation manager null???????????");
}
animationManager = new NetAnimationManager(Value.animationManager);
animationManager.Write(writer);
*/
}
}
}

View File

@ -1,116 +0,0 @@
using Netcode;
using StardustCore.NetCode.Graphics;
using StardustCore.Objects;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StardustCore.NetCode.Objects
{
public class NetMultiTileComponent : Netcode.NetField<MultiTileComponent, NetMultiTileComponent>
{
private NetTexture2DExtended texture;
private NetInt which;
private NetVector2 tilePos;
private NetRectangle sourceRect;
private NetRectangle boundingBox;
private NetVector2 drawPosition;
private NetAnimationManager animationManager;
public NetMultiTileComponent()
{
}
public NetMultiTileComponent(MultiTileComponent obj): base(obj)
{
Set(obj);
}
public NetInt InventoryMaxSize { get; private set; }
public override void Set(MultiTileComponent newValue)
{
this.value = newValue;
}
protected override void ReadDelta(BinaryReader reader, NetVersion version)
{
texture = new NetTexture2DExtended();
texture.Read(reader, version);
which = new NetInt();
which.Read(reader, version);
Value.ParentSheetIndex = which.Value;
tilePos = new NetVector2();
tilePos.Read(reader, version);
Value.TileLocation = tilePos.Value;
InventoryMaxSize = new NetInt();
InventoryMaxSize.Read(reader, version);
Value.inventoryMaxSize = InventoryMaxSize.Value;
sourceRect = new NetRectangle();
sourceRect.Read(reader, version);
Value.sourceRect = sourceRect.Value;
boundingBox = new NetRectangle();
boundingBox.Read(reader, version);
Value.boundingBox.Value = boundingBox.Value;
drawPosition = new NetVector2();
drawPosition.Read(reader, version);
Value.drawPosition = drawPosition.Value;
animationManager = new NetAnimationManager();
animationManager.Read(reader, version);
Value.animationManager = animationManager.Value;
//NetCoreObject obj = new NetCoreObject();
//obj.ReadData(reader, version);
/*
NetMultiTileObject hmm = new NetMultiTileObject();
hmm.Read(reader,version);
Value.containerObject = hmm.Value;
*/
}
protected override void WriteDelta(BinaryWriter writer)
{
//NetCoreObject obj = new NetCoreObject(Value);
//obj.WriteData(writer);
texture = new NetTexture2DExtended(Value.getExtendedTexture());
texture.Write(writer);
which = new NetInt(Value.ParentSheetIndex);
which.Write(writer);
tilePos = new NetVector2(Value.TileLocation);
tilePos.Write(writer);
InventoryMaxSize = new NetInt(Value.inventoryMaxSize);
InventoryMaxSize.Write(writer);
sourceRect = new NetRectangle(Value.sourceRect);
sourceRect.Write(writer);
boundingBox = new NetRectangle(Value.boundingBox.Value);
sourceRect.Write(writer);
drawPosition = new NetVector2(Value.drawPosition);
drawPosition.Write(writer);
animationManager = new NetAnimationManager(Value.animationManager);
animationManager.Write(writer);
//NetMultiTileObject hmm = new NetMultiTileObject(Value.containerObject);
//hmm.Write(writer);
}
}
}

View File

@ -1,81 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Netcode;
using StardustCore.Objects;
namespace StardustCore.NetCode.Objects
{
public class NetMultiTileObject : Netcode.NetField<MultiTileObject, NetMultiTileObject>
{
public NetMultiTileObject()
{
}
public NetMultiTileObject(MultiTileObject obj): base(obj)
{
}
public override void Set(MultiTileObject newValue)
{
this.value = newValue;
}
protected override void ReadDelta(BinaryReader reader, NetVersion version)
{
NetCoreObject obj = new NetCoreObject();
obj.Read(reader, version);
//Values already taken care of in NetCoreObject
NetList<KeyValuePair<Vector2, MultiTileComponent>, NetKeyValuePair<Vector2, MultiTileComponent, NetVector2, NetMultiTileComponent>> netList = new NetList<KeyValuePair<Vector2, MultiTileComponent>, NetKeyValuePair<Vector2, MultiTileComponent, NetVector2, NetMultiTileComponent>>();
netList.Read(reader, version);
if (netList.ToList() == null) throw new Exception("WTF WHY IS NETLIST NULL?!?!?!?!");
foreach(var v in netList.ToList())
{
StardustCore.ModCore.ModMonitor.Log(v.Value.name, StardewModdingAPI.LogLevel.Alert);
}
Value.objects = netList.ToList();
//this.value.objects=netList.ToArray().ToList();
NetColor col = new NetColor();
col.Read(reader, version);
Value.categoryColor = col.Value;
NetString name = new NetString();
name.Read(reader, version);
Value.categoryName = name.Value;
}
protected override void WriteDelta(BinaryWriter writer)
{
NetCoreObject obj = new NetCoreObject(Value);
obj.Write(writer);
NetList<KeyValuePair<Vector2, MultiTileComponent>, NetKeyValuePair<Vector2, MultiTileComponent, NetVector2, NetMultiTileComponent>> netList = new NetList<KeyValuePair<Vector2, MultiTileComponent>, NetKeyValuePair<Vector2, MultiTileComponent, NetVector2, NetMultiTileComponent>>();
if (Value.objects == null) throw new Exception("Trying to write null object list!");
foreach (var v in Value.objects)
{
StardustCore.ModCore.ModMonitor.Log(v.Value.name);
netList.Add(v);
}
netList.Write(writer);
NetColor col = new NetColor(Value.categoryColor);
col.Write(writer);
NetString catName = new NetString(Value.categoryName);
catName.Write(writer);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,244 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StardewValley;
using StardustCore.UIUtilities;
namespace StardustCore.Objects
{
public class MultiTileComponent : CoreObject
{
//Pass in different function pointers that return bool to check if this default code will run. If not
public MultiTileObject containerObject;
public MultiTileComponent()
{
//this.TextureSheet = new Texture2DExtended();
this.NetFields.AddField(new NetCode.NetTexture2DExtended(this.getExtendedTexture()));
}
public MultiTileComponent(CoreObject part)
{
this.name = part.name;
this.description = part.description;
this.TextureSheet = part.getExtendedTexture();
if (part.animationManager != null)
{
this.animationManager = part.animationManager;
}
this.defaultBoundingBox = new Rectangle(0, 0, 16, 16);
this.boundingBox.Value = new Rectangle((int)0 * Game1.tileSize, (int)0* Game1.tileSize, 1 * Game1.tileSize, 1 * Game1.tileSize);
this.NetFields.AddField(new NetCode.NetTexture2DExtended(this.getExtendedTexture()));
this.InitializeBasics(0, Vector2.Zero);
}
public MultiTileComponent(int which,String name, String description, Texture2DExtended texture)
{
this.name = name;
this.displayName = name;
this.description = description;
this.TextureSheet = texture;
this.defaultBoundingBox = new Rectangle(0, 0, 16, 16);
this.boundingBox.Value = new Rectangle((int)0 * Game1.tileSize, (int)0 * Game1.tileSize, 1 * Game1.tileSize, 1 * Game1.tileSize);
this.defaultSourceRect.Width = 16;
this.defaultSourceRect.Height = 16;
this.sourceRect = new Rectangle((which * 16) % TextureSheet.getTexture().Width, (which * 16) / TextureSheet.getTexture().Width * 16, this.defaultSourceRect.Width * 1, this.defaultSourceRect.Height * 1);
this.defaultSourceRect = this.sourceRect;
this.serializationName = this.GetType().ToString();
this.ParentSheetIndex = which;
this.animationManager = new Animations.AnimationManager(texture, new Animations.Animation(this.defaultSourceRect), false);
this.NetFields.AddField(new NetCode.NetTexture2DExtended(this.getExtendedTexture()));
this.InitializeBasics(0, Vector2.Zero);
}
public MultiTileComponent(int which,String name, String description, Animations.AnimationManager animationManager)
{
this.name = name;
this.displayName = name;
this.description = description;
this.animationManager = animationManager;
this.TextureSheet = animationManager.getExtendedTexture();
this.defaultBoundingBox = new Rectangle(0, 0, 16, 16);
this.boundingBox.Value = new Rectangle((int)0 * Game1.tileSize, (int)0 * Game1.tileSize, 1 * Game1.tileSize, 1 * Game1.tileSize);
this.defaultSourceRect.Width = 16;
this.defaultSourceRect.Height = 16;
this.sourceRect = new Rectangle(which * 16 % TextureSheet.getTexture().Width, which * 16 / TextureSheet.getTexture().Width * 16, this.defaultSourceRect.Width * 16, this.defaultSourceRect.Height * 16);
this.defaultSourceRect = this.sourceRect;
this.serializationName = this.GetType().ToString();
this.ParentSheetIndex = which;
this.NetFields.AddField(new NetCode.NetTexture2DExtended(this.getExtendedTexture()));
this.InitializeBasics(0,Vector2.Zero);
}
public override void InitializeBasics(int InvMaxSize, Vector2 tile)
{
this.inventory = new List<Item>();
this.inventoryMaxSize = InvMaxSize;
this.TileLocation = tile;
lightsOn = false;
lightColor = Color.Black;
base.initNetFields();
this.NetFields.AddField(new NetCode.Objects.NetMultiTileComponent(this));
}
public override bool clicked(Farmer who)
{
//Check if shift click to interact with object.
containerObject.RemoveAllObjects();
return true;
}
public override Item getOne()
{
if (this.animationManager != null)
{
var obj = new MultiTileComponent(this.ParentSheetIndex,this.name, this.description, this.animationManager);
obj.containerObject = this.containerObject;
return obj;
}
else
{
var obj = new MultiTileComponent(this.ParentSheetIndex,this.name, this.description, this.TextureSheet);
obj.containerObject = this.containerObject;
return obj;
}
}
public override bool RightClicked(Farmer who)
{
return true;
}
public override bool placementAction(GameLocation location, int x, int y, Farmer who = null)
{
Point point = new Point(x / Game1.tileSize, y / Game1.tileSize);
this.position = new Vector2(point.X, point.Y);
this.TileLocation = new Vector2((float)point.X, (float)point.Y);
this.boundingBox.Value = new Rectangle((int)TileLocation.X * Game1.tileSize, (int)TileLocation.Y * Game1.tileSize, 1 * Game1.tileSize, 1 * Game1.tileSize);
foreach(Farmer farmer in Game1.getAllFarmers())
{
if (location == farmer.currentLocation)
{
if (farmer.GetBoundingBox().Intersects(this.boundingBox.Value))
{
Game1.showRedMessage("Can't place on top of a person.");
bool result = false;
return result;
}
}
}
this.updateDrawPosition();
bool f = Utilities.placementAction(this, location, x, y,StardustCore.ModCore.SerializationManager ,who);
this.thisLocation = Game1.player.currentLocation;
return f;
// Game1.showRedMessage("Can only be placed in House");
// return false;
}
public override void performRemoveAction(Vector2 tileLocation, GameLocation environment)
{
// Game1.showRedMessage("Why3?");
try
{
this.heldObject.Value.performRemoveAction(this.TileLocation, this.thisLocation);
this.heldObject.Value = null;
}
catch(Exception err)
{
}
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(this);
this.thisLocation.removeObject(this.tileLocation, false);
//this.thisLocation.objects.Remove(this.TileLocation);
this.thisLocation = null;
this.locationsName = "";
base.performRemoveAction(tileLocation, environment);
}
public override void draw(SpriteBatch spriteBatch, int x, int y, float alpha = 1f)
{
if (x == -1)
{
spriteBatch.Draw(this.TextureSheet.getTexture(), Game1.GlobalToLocal(Game1.viewport, this.drawPosition), new Rectangle?(this.sourceRect), Color.White * alpha, 0f, Vector2.Zero, (float)Game1.pixelZoom, this.flipped ? SpriteEffects.FlipHorizontally : SpriteEffects.None, (this.Decoration_type == 12) ? 0f : ((float)(this.boundingBox.Bottom - 8) / 10000f));
}
else
{
//The actual planter box being drawn.
if (animationManager == null)
{
if (this.TextureSheet == null)
{
ModCore.ModMonitor.Log("Tex Extended is null???");
}
spriteBatch.Draw(this.TextureSheet.getTexture(), Game1.GlobalToLocal(Game1.viewport, new Vector2((float)(x * Game1.tileSize), y * Game1.tileSize)), new Rectangle?(this.sourceRect), Color.White * alpha, 0f, Vector2.Zero, (float)Game1.pixelZoom, this.flipped ? SpriteEffects.FlipHorizontally : SpriteEffects.None, 0);
// Log.AsyncG("ANIMATION IS NULL?!?!?!?!");
}
else
{
//Log.AsyncC("Animation Manager is working!");
this.animationManager.draw(spriteBatch, this.animationManager.getTexture(), Game1.GlobalToLocal(Game1.viewport, new Vector2((float)(x * Game1.tileSize), y * Game1.tileSize)), new Rectangle?(this.animationManager.currentAnimation.sourceRectangle), Color.White * alpha, 0f, Vector2.Zero, (float)Game1.pixelZoom, this.flipped ? SpriteEffects.FlipHorizontally : SpriteEffects.None, 0);
try
{
this.animationManager.tickAnimation();
// Log.AsyncC("Tick animation");
}
catch (Exception err)
{
ModCore.ModMonitor.Log(err.ToString());
}
}
// spriteBatch.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, new Vector2((float)((double)tileLocation.X * (double)Game1.tileSize + (((double)tileLocation.X * 11.0 + (double)tileLocation.Y * 7.0) % 10.0 - 5.0)) + (float)(Game1.tileSize / 2), (float)((double)tileLocation.Y * (double)Game1.tileSize + (((double)tileLocation.Y * 11.0 + (double)tileLocation.X * 7.0) % 10.0 - 5.0)) + (float)(Game1.tileSize / 2))), new Rectangle?(new Rectangle((int)((double)tileLocation.X * 51.0 + (double)tileLocation.Y * 77.0) % 3 * 16, 128 + this.whichForageCrop * 16, 16, 16)), Color.White, 0.0f, new Vector2(8f, 8f), (float)Game1.pixelZoom, SpriteEffects.None, (float)(((double)tileLocation.Y * (double)Game1.tileSize + (double)(Game1.tileSize / 2) + (((double)tileLocation.Y * 11.0 + (double)tileLocation.X * 7.0) % 10.0 - 5.0)) / 10000.0));
}
}
public override void draw(SpriteBatch spriteBatch, int xNonTile, int yNonTile, float layerDepth, float alpha = 1f)
{
if (Game1.eventUp && Game1.CurrentEvent.isTileWalkedOn(xNonTile / 64, yNonTile / 64))
return;
if ((int)(this.ParentSheetIndex) != 590 && (int)(this.Fragility) != 2)
spriteBatch.Draw(Game1.shadowTexture, Game1.GlobalToLocal(Game1.viewport, new Vector2((float)(xNonTile + 32), (float)(yNonTile + 51 + 4))), new Microsoft.Xna.Framework.Rectangle?(Game1.shadowTexture.Bounds), Color.White * alpha, 0.0f, new Vector2((float)Game1.shadowTexture.Bounds.Center.X, (float)Game1.shadowTexture.Bounds.Center.Y), 4f, SpriteEffects.None, layerDepth - 1E-06f);
SpriteBatch spriteBatch1 = spriteBatch;
Texture2D objectSpriteSheet = Game1.objectSpriteSheet;
Vector2 local = Game1.GlobalToLocal(Game1.viewport, new Vector2((float)(xNonTile + 32 + (this.shakeTimer > 0 ? Game1.random.Next(-1, 2) : 0)), (float)(yNonTile + 32 + (this.shakeTimer > 0 ? Game1.random.Next(-1, 2) : 0))));
Microsoft.Xna.Framework.Rectangle? sourceRectangle = new Microsoft.Xna.Framework.Rectangle?(GameLocation.getSourceRectForObject(this.ParentSheetIndex));
Color color = Color.White * alpha;
double num1 = 0.0;
Vector2 origin = new Vector2(8f, 8f);
Vector2 scale = this.scale;
double num2 = (double)this.scale.Y > 1.0 ? (double)this.getScale().Y : 4.0;
int num3 = (bool)(this.flipped) ? 1 : 0;
double num4 = (double)layerDepth;
spriteBatch1.Draw(TextureSheet.getTexture(), local, sourceRectangle, color, (float)num1, origin, (float)num2, (SpriteEffects)num3, (float)num4);
}
}
}

View File

@ -1,247 +0,0 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StardewValley;
using StardustCore.UIUtilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace StardustCore.Objects
{
public class MultiTileObject : CoreObject
{
public List<KeyValuePair<Vector2,MultiTileComponent>> objects;
public Color categoryColor;
public String categoryName;
public MultiTileObject()
{
}
public MultiTileObject(String Name, String Description,Vector2 tile, Texture2DExtended texture, List<KeyValuePair<Vector2, MultiTileComponent>> Objects, Color CategoryColor, String CategoryName) :base(texture,0,tile,0)
{
this.objects = Objects;
this.TextureSheet = texture;
this.categoryColor = CategoryColor;
this.categoryName = CategoryName;
this.name = Name;
this.displayName = Name;
this.description = Description;
this.animationManager = new Animations.AnimationManager(this.TextureSheet, new Animations.Animation(), false);
foreach(var v in this.objects)
{
v.Value.containerObject = this;
}
InitializeBasics(0, tile);
this.serializationName = this.GetType().ToString();
this.defaultSourceRect = new Rectangle(0, 0, 16, 16);
this.sourceRect = defaultSourceRect;
}
public MultiTileObject(String Name, String Description, Vector2 tile, Animations.AnimationManager animationManager, List<KeyValuePair<Vector2, MultiTileComponent>> Objects, Color CategoryColor, String CategoryName)
{
this.animationManager = animationManager;
this.objects = Objects;
this.TextureSheet =animationManager.getExtendedTexture();
this.name = Name;
this.displayName = Name;
this.description = Description;
InitializeBasics(0, tile);
this.serializationName = this.GetType().ToString();
}
public void RemoveAllObjects()
{
if (Game1.player.isInventoryFull() == false){
foreach (var v in this.objects)
{
v.Value.performRemoveAction(v.Value.TileLocation, v.Value.thisLocation);
}
Game1.player.addItemToInventory(this);
}
return;
}
public override Type getCustomType()
{
return this.GetType();
}
public override string GetSerializationName()
{
return typeof(MultiTileObject).ToString();
}
public override void InitializeBasics(int InvMaxSize, Vector2 tile)
{
this.inventory = new List<Item>();
this.inventoryMaxSize = InvMaxSize;
this.TileLocation = tile;
lightsOn = false;
lightColor = Color.Black;
base.initNetFields();
this.NetFields.AddField(new NetCode.Objects.NetMultiTileObject(this));
}
public override bool placementAction(GameLocation location, int x, int y, Farmer who = null)
{
if (canBePlacedHere(location,new Vector2(x/Game1.tileSize,y/Game1.tileSize)))
{
foreach (var pair in this.objects)
{
pair.Value.placementAction(location, x + (int)(pair.Key.X * Game1.tileSize), y + (int)(pair.Key.Y * Game1.tileSize), who);
}
return true;
}
return false;
}
public override bool canBePlacedHere(GameLocation l, Vector2 tile)
{
bool canBePlaced = true;
foreach (var v in this.objects)
{
canBePlaced=v.Value.canBePlacedHere(l, tile+v.Key);
if (canBePlaced == false) return false;
}
return true;
}
public override bool clicked(Farmer who)
{
foreach (var pair in this.objects)
{
pair.Value.clicked(who);
}
return true;
}
public override bool RightClicked(Farmer who)
{
foreach (var pair in this.objects)
{
pair.Value.RightClicked(who);
}
return true;
}
/// <summary>
/// Need to fix this for sure!!!
/// </summary>
/// <returns></returns>
public override Item getOne()
{
List<KeyValuePair<Vector2, MultiTileComponent>> items = new List<KeyValuePair<Vector2, MultiTileComponent>>();
foreach (var pair in this.objects)
{
items.Add(new KeyValuePair<Vector2, MultiTileComponent>(pair.Key, (pair.Value.getOne()) as MultiTileComponent));
}
if (this.animationManager != null)
{
return new MultiTileObject(this.name, this.description, this.TileLocation, this.animationManager, items, this.categoryColor, this.categoryName);
//throw new NotImplementedException();
}
else
{
return new MultiTileObject(this.name, this.description, this.TileLocation, this.TextureSheet, items, this.categoryColor, this.categoryName);
}
return null;
}
public override void draw(SpriteBatch spriteBatch, int x, int y, float alpha = 1)
{
foreach(var v in this.objects)
{
v.Value.draw(spriteBatch, (int)x+(int)(v.Key.X), (int)y+(int)(v.Key.Y), alpha);
}
//base.draw(spriteBatch, x, y, alpha);
}
public override void draw(SpriteBatch spriteBatch, int xNonTile, int yNonTile, float layerDepth, float alpha = 1)
{
foreach (var v in this.objects)
{
v.Value.draw(spriteBatch, (int)xNonTile+(int)(v.Key.X*Game1.tileSize), (int)yNonTile+ (int)(v.Key.Y * Game1.tileSize), layerDepth, alpha);
}
}
public override void drawWhenHeld(SpriteBatch spriteBatch, Vector2 objectPosition, StardewValley.Farmer f)
{
if (animationManager == null)
{
if (this.objects == null) return;
if (this.sourceRect == null) throw new Exception("Source rect null???");
foreach (var v in this.objects)
{
if (v.Value.getExtendedTexture() == null) throw new Exception("Extended texture is null!");
if (v.Value.getExtendedTexture().getTexture() == null) throw new Exception("Texture is null!");
spriteBatch.Draw(v.Value.getExtendedTexture().getTexture(), objectPosition + new Vector2(v.Key.X * Game1.tileSize, v.Key.Y * Game1.tileSize), this.sourceRect, Color.White, 0f, Vector2.Zero, (float)Game1.pixelZoom, SpriteEffects.None, Math.Max(0f, (float)(f.getStandingY() + 2) / 10000f));
}
}
else
{
foreach (var v in this.objects)
{
if(v.Value.getExtendedTexture() == null) throw new Exception("Extended texture is null!");
if (v.Value.getExtendedTexture().getTexture() == null) throw new Exception("Texture is null!");
spriteBatch.Draw(v.Value.animationManager.getTexture(), objectPosition + new Vector2(v.Key.X * Game1.tileSize, v.Key.Y * Game1.tileSize), this.sourceRect, Color.White, 0f, Vector2.Zero, (float)Game1.pixelZoom, SpriteEffects.None, Math.Max(0f, (float)(f.getStandingY() + 2) / 10000f));
}
}
//base.drawWhenHeld(spriteBatch, objectPosition, f);
}
public override void drawAtNonTileSpot(SpriteBatch spriteBatch, Vector2 location, float layerDepth, float alpha = 1)
{
foreach (var v in this.objects)
{
v.Value.drawAtNonTileSpot(spriteBatch, location+new Vector2(v.Key.X * Game1.tileSize, v.Key.Y * Game1.tileSize), layerDepth, alpha);
}
}
public override void drawInMenu(SpriteBatch spriteBatch, Vector2 location, float scaleSize, float transparency, float layerDepth, bool drawStackNumber, Color c, bool drawShadows)
{
foreach (var v in this.objects)
{
if (animationManager == null)
{
//FIX SCALE SIZE AND POSITION APPROPRIATELY DEPENDING ON # OF OBJECTS!!!
//fsfsd
spriteBatch.Draw(v.Value.getExtendedTexture().getTexture(), location+new Vector2(v.Key.X*16,v.Key.Y*16), this.defaultSourceRect, Color.White * transparency, 0f, new Vector2(0, 0), 1, SpriteEffects.None, layerDepth);
}
else
{
spriteBatch.Draw(v.Value.animationManager.getTexture(), location + new Vector2(v.Key.X*8, v.Key.Y*8), v.Value.animationManager.currentAnimation.sourceRectangle, Color.White * transparency, 0f, new Vector2(0, 0), scaleSize, SpriteEffects.None, layerDepth);
//this.modularCrop.drawInMenu(spriteBatch, location + new Vector2((float)(Game1.tileSize / 2), (float)(Game1.tileSize / 2)), Color.White, 0f,true);
if (Game1.player.CurrentItem != this) animationManager.tickAnimation();
}
}
}
public override Color getCategoryColor()
{
return this.categoryColor;
}
public override string getCategoryName()
{
return this.name;
}
}
}

View File

@ -1,40 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StardustCore.Objects.Tools
{
public class BasicToolInfo
{
/// <summary>
/// The name of the tool.
/// </summary>
public string name;
/// <summary>
/// The upgrade level of the tool.
/// </summary>
public int level;
/// <summary>
/// The description of the tool.
/// </summary>
public string description;
/// <summary>
/// Constructor used to hold generic info shared across all tools.
/// </summary>
/// <param name="Name"></param>
/// <param name="Level"></param>
/// <param name="Description"></param>
public BasicToolInfo(String Name, int Level, string Description)
{
this.name = Name;
this.level = Level;
this.description = Description;
}
}
}

View File

@ -1,142 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StardewModdingAPI;
using StardewValley;
using StardustCore.Interfaces;
using StardustCore.Objects.Tools.SerializationInformation;
using StardustCore.UIUtilities;
namespace StardustCore.Objects.Tools
{
public class ExtendedAxe : StardewValley.Tools.Axe, IItemSerializeable, IToolSerializer
{
public Texture2DExtended texture;
public override string DisplayName { get => this.displayName; set => this.displayName = value; }
public override string Name { get => this.displayName; set => this.displayName = value; }
/// <summary>
/// Generates a default axe. Doens't really do much.
/// </summary>
public ExtendedAxe() : base()
{
this.texture = new Texture2DExtended(StardustCore.ModCore.ModHelper, ModCore.Manifest,Path.Combine("Content","Graphics","Tools","CustomAxe.png"));
}
public ExtendedAxe(BasicToolInfo info, Texture2DExtended texture)
{
this.texture = texture;
this.displayName = info.name;
this.description = info.description;
this.UpgradeLevel = info.level;
}
public ExtendedAxe(SerializedObjectBase dataBase) : base()
{
StardustCore.ModCore.ModMonitor.Log("WTF EVEN " + dataBase.GetType().ToString());
StardustCore.ModCore.ModMonitor.Log((dataBase as Serialization_ExtendedAxe).Name);
this.displayName = "Hello";
this.description = (dataBase as Serialization_ExtendedAxe).Description;
this.texture = StardustCore.ModCore.TextureManager.getTexture((dataBase as Serialization_ExtendedAxe).TextureInformation.Name); //new Texture2DExtended(StardustCore.ModCore.ModHelper, Path.Combine("Content", "Graphics", "Tools", "CustomAxe.png"));
this.UpgradeLevel = (dataBase as Serialization_ExtendedAxe).UpgradeLevel;
}
public override void draw(SpriteBatch b)
{
base.draw(b);
}
public override void drawInMenu(SpriteBatch spriteBatch, Vector2 location, float scaleSize, float transparency, float layerDepth, bool drawStackNumber, Color color, bool drawShadow)
{
spriteBatch.Draw(texture.getTexture(), location + new Vector2(32f, 32f), new Rectangle(0, 0, 16 , 16), color * transparency, 0.0f, new Vector2(8f, 8f), 4f * scaleSize, SpriteEffects.None, layerDepth);
}
public Type getCustomType()
{
return this.GetType();
}
public string GetSerializationName()
{
return this.GetType().ToString();
}
public override int maximumStackSize()
{
return 1;
}
public override bool canBeDropped()
{
return true;
}
public override bool canBeTrashed()
{
return true;
}
public override void setNewTileIndexForUpgradeLevel()
{
//Do nothing.
}
/// <summary>
/// Serializes the said item properly.
/// </summary>
/// <param name="I"></param>
public static void Serialize(Item I)
{
SerializationInformation.Serialization_ExtendedAxe sAxe = new SerializationInformation.Serialization_ExtendedAxe((I as ExtendedAxe));
String savePath = ModCore.SerializationManager.playerInventoryPath;
String fileName = I.Name + ".json";
String resultPath = Path.Combine(savePath, fileName);
int count = 0;
while (File.Exists(resultPath))
{
resultPath=Serialization.SerializationManager.getValidSavePathIfDuplicatesExist(I, savePath,count);
count++;
}
StardustCore.ModCore.ModHelper.WriteJsonFile<SerializedObjectBase>(resultPath, sAxe);
}
/// <summary>
/// Serializes the said item to a chest.
/// </summary>
/// <param name="I"></param>
/// <param name="s"></param>
public static void SerializeToContainer(Item I, string s)
{
SerializationInformation.Serialization_ExtendedAxe sAxe = new SerializationInformation.Serialization_ExtendedAxe((I as ExtendedAxe));
String savePath = s;
String fileName = I.Name + ".json";
String resultPath = Path.Combine(savePath, fileName);
int count = 0;
while (File.Exists(resultPath))
{
resultPath = Serialization.SerializationManager.getValidSavePathIfDuplicatesExist(I, savePath, count);
count++;
}
StardustCore.ModCore.ModHelper.WriteJsonFile<SerializedObjectBase>(resultPath, sAxe);
}
/// <summary>
/// Deserializes the object from a .json.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static ExtendedAxe Deserialize(string data)
{
Serialization_ExtendedAxe axeData= ModCore.ModHelper.ReadJsonFile<Serialization_ExtendedAxe>(data);
return new ExtendedAxe(axeData);
}
}
}

View File

@ -1,142 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StardewModdingAPI;
using StardewValley;
using StardustCore.Interfaces;
using StardustCore.Objects.Tools.SerializationInformation;
using StardustCore.UIUtilities;
namespace StardustCore.Objects.Tools
{
public class ExtendedHoe : StardewValley.Tools.Hoe, IItemSerializeable, IToolSerializer
{
public Texture2DExtended texture;
public override string DisplayName { get => this.displayName; set => this.displayName = value; }
public override string Name { get => this.displayName; set => this.displayName = value; }
/// <summary>
/// Generates a default axe. Doens't really do much.
/// </summary>
public ExtendedHoe() : base()
{
this.texture = new Texture2DExtended(StardustCore.ModCore.ModHelper,ModCore.Manifest ,Path.Combine("Content", "Graphics", "Tools", "CustomAxe.png"));
}
public ExtendedHoe(BasicToolInfo info, Texture2DExtended texture)
{
this.texture = texture;
this.displayName = info.name;
this.description = info.description;
this.UpgradeLevel = info.level;
}
public ExtendedHoe(SerializedObjectBase dataBase) : base()
{
StardustCore.ModCore.ModMonitor.Log("WTF EVEN " + dataBase.GetType().ToString());
StardustCore.ModCore.ModMonitor.Log((dataBase as Serialization_ExtendedHoe).Name);
this.displayName = "Hello";
this.description = (dataBase as Serialization_ExtendedHoe).Description;
this.texture = StardustCore.ModCore.TextureManager.getTexture((dataBase as Serialization_ExtendedHoe).TextureInformation.Name);
this.UpgradeLevel = (dataBase as Serialization_ExtendedHoe).UpgradeLevel;
}
public override bool canBeDropped()
{
return true;
}
public override bool canBeTrashed()
{
return true;
}
public override void draw(SpriteBatch b)
{
base.draw(b);
}
public override void drawInMenu(SpriteBatch spriteBatch, Vector2 location, float scaleSize, float transparency, float layerDepth, bool drawStackNumber, Color color, bool drawShadow)
{
spriteBatch.Draw(texture.getTexture(), location + new Vector2(32f, 32f), new Rectangle(0, 0, 16, 16), color * transparency, 0.0f, new Vector2(8f, 8f), 4f * scaleSize, SpriteEffects.None, layerDepth);
}
public Type getCustomType()
{
return this.GetType();
}
public string GetSerializationName()
{
return this.GetType().ToString();
}
public override int maximumStackSize()
{
return 1;
}
public override void setNewTileIndexForUpgradeLevel()
{
//Do nothing.
}
/// <summary>
/// Serializes the said item properly.
/// </summary>
/// <param name="I"></param>
public static void Serialize(Item I)
{
SerializationInformation.Serialization_ExtendedHoe sAxe = new SerializationInformation.Serialization_ExtendedHoe((I as ExtendedHoe));
String savePath = ModCore.SerializationManager.playerInventoryPath;
String fileName = I.Name + ".json";
String resultPath = Path.Combine(savePath, fileName);
int count = 0;
while (File.Exists(resultPath))
{
resultPath = Serialization.SerializationManager.getValidSavePathIfDuplicatesExist(I, savePath, count);
count++;
}
StardustCore.ModCore.ModHelper.WriteJsonFile<Serialization_ExtendedHoe>(resultPath, sAxe);
}
/// <summary>
/// Serializes the said item to a chest.
/// </summary>
/// <param name="I"></param>
/// <param name="s"></param>
public static void SerializeToContainer(Item I, string s)
{
SerializationInformation.Serialization_ExtendedHoe sAxe = new SerializationInformation.Serialization_ExtendedHoe((I as ExtendedHoe));
String savePath = s;
String fileName = I.Name + ".json";
String resultPath = Path.Combine(savePath, fileName);
int count = 0;
while (File.Exists(resultPath))
{
resultPath = Serialization.SerializationManager.getValidSavePathIfDuplicatesExist(I, savePath, count);
count++;
}
StardustCore.ModCore.ModHelper.WriteJsonFile<SerializedObjectBase>(resultPath, sAxe);
}
/// <summary>
/// Deserializes the object from a .json.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static ExtendedHoe Deserialize(string data)
{
Serialization_ExtendedHoe axeData = ModCore.ModHelper.ReadJsonFile<Serialization_ExtendedHoe>(data);
return new ExtendedHoe(axeData);
}
}
}

View File

@ -1,142 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StardewModdingAPI;
using StardewValley;
using StardustCore.Interfaces;
using StardustCore.Objects.Tools.SerializationInformation;
using StardustCore.UIUtilities;
namespace StardustCore.Objects.Tools
{
public class ExtendedPickaxe : StardewValley.Tools.Pickaxe, IItemSerializeable, IToolSerializer
{
public Texture2DExtended texture;
public override string DisplayName { get => this.displayName; set => this.displayName = value; }
public override string Name { get => this.displayName; set => this.displayName = value; }
/// <summary>
/// Generates a default axe. Doens't really do much.
/// </summary>
public ExtendedPickaxe() : base()
{
this.texture = new Texture2DExtended(StardustCore.ModCore.ModHelper, ModCore.Manifest,Path.Combine("Content", "Graphics", "Tools", "CustomAxe.png"));
}
public ExtendedPickaxe(BasicToolInfo info, Texture2DExtended texture)
{
this.texture = texture;
this.displayName = info.name;
this.description = info.description;
this.UpgradeLevel = info.level;
}
public ExtendedPickaxe(SerializedObjectBase dataBase) : base()
{
StardustCore.ModCore.ModMonitor.Log("WTF EVEN " + dataBase.GetType().ToString());
StardustCore.ModCore.ModMonitor.Log((dataBase as Serialization_ExtendedPickaxe).Name);
this.displayName = "Hello";
this.description = (dataBase as Serialization_ExtendedPickaxe).Description;
this.texture = this.texture = StardustCore.ModCore.TextureManager.getTexture((dataBase as Serialization_ExtendedPickaxe).TextureInformation.Name);
this.UpgradeLevel = (dataBase as Serialization_ExtendedPickaxe).UpgradeLevel;
}
public override bool canBeDropped()
{
return true;
}
public override bool canBeTrashed()
{
return true;
}
public override void draw(SpriteBatch b)
{
base.draw(b);
}
public override void drawInMenu(SpriteBatch spriteBatch, Vector2 location, float scaleSize, float transparency, float layerDepth, bool drawStackNumber, Color color, bool drawShadow)
{
spriteBatch.Draw(texture.getTexture(), location + new Vector2(32f, 32f), new Rectangle(0, 0, 16, 16), color * transparency, 0.0f, new Vector2(8f, 8f), 4f * scaleSize, SpriteEffects.None, layerDepth);
}
public Type getCustomType()
{
return this.GetType();
}
public string GetSerializationName()
{
return this.GetType().ToString();
}
public override int maximumStackSize()
{
return 1;
}
public override void setNewTileIndexForUpgradeLevel()
{
//Do nothing.
}
/// <summary>
/// Serializes the said item properly.
/// </summary>
/// <param name="I"></param>
public static void Serialize(Item I)
{
SerializationInformation.Serialization_ExtendedPickaxe sAxe = new SerializationInformation.Serialization_ExtendedPickaxe((I as ExtendedPickaxe));
String savePath = ModCore.SerializationManager.playerInventoryPath;
String fileName = I.Name + ".json";
String resultPath = Path.Combine(savePath, fileName);
int count = 0;
while (File.Exists(resultPath))
{
resultPath = Serialization.SerializationManager.getValidSavePathIfDuplicatesExist(I, savePath, count);
count++;
}
StardustCore.ModCore.ModHelper.WriteJsonFile<SerializedObjectBase>(resultPath, sAxe);
}
/// <summary>
/// Serializes the said item to a chest.
/// </summary>
/// <param name="I"></param>
/// <param name="s"></param>
public static void SerializeToContainer(Item I, string s)
{
SerializationInformation.Serialization_ExtendedPickaxe sAxe = new SerializationInformation.Serialization_ExtendedPickaxe((I as ExtendedPickaxe));
String savePath = s;
String fileName = I.Name + ".json";
String resultPath = Path.Combine(savePath, fileName);
int count = 0;
while (File.Exists(resultPath))
{
resultPath = Serialization.SerializationManager.getValidSavePathIfDuplicatesExist(I, savePath, count);
count++;
}
StardustCore.ModCore.ModHelper.WriteJsonFile<SerializedObjectBase>(resultPath, sAxe);
}
/// <summary>
/// Deserializes the object from a .json.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static ExtendedPickaxe Deserialize(string data)
{
Serialization_ExtendedPickaxe axeData = ModCore.ModHelper.ReadJsonFile<Serialization_ExtendedPickaxe>(data);
return new ExtendedPickaxe(axeData);
}
}
}

View File

@ -1,156 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StardewModdingAPI;
using StardewValley;
using StardustCore.Interfaces;
using StardustCore.Objects.Tools.SerializationInformation;
using StardustCore.UIUtilities;
namespace StardustCore.Objects.Tools
{
public class ExtendedWateringCan : StardewValley.Tools.WateringCan, IItemSerializeable, IToolSerializer
{
public Texture2DExtended texture;
public override string DisplayName { get => this.displayName; set => this.displayName = value; }
public override string Name { get => this.displayName; set => this.displayName = value; }
/// <summary>
/// Generates a default axe. Doens't really do much.
/// </summary>
public ExtendedWateringCan() : base()
{
this.texture = new Texture2DExtended(StardustCore.ModCore.ModHelper, ModCore.Manifest,Path.Combine("Content", "Graphics", "Tools", "CustomAxe.png"));
this.waterCanMax = 30;
this.WaterLeft = 0;
}
public ExtendedWateringCan(BasicToolInfo info, Texture2DExtended texture, int waterMax, int waterCurrent)
{
this.texture = texture;
this.displayName = info.name;
this.description = info.description;
this.UpgradeLevel = info.level;
this.waterCanMax = waterMax;
this.WaterLeft = waterCurrent;
}
public ExtendedWateringCan(SerializedObjectBase dataBase) : base()
{
StardustCore.ModCore.ModMonitor.Log((dataBase as Serialization_ExtendedWateringCan).Name);
this.displayName = "Hello";
this.description = (dataBase as Serialization_ExtendedWateringCan).Description;
this.texture = StardustCore.ModCore.TextureManager.getTexture((dataBase as Serialization_ExtendedWateringCan).TextureInformation.Name);
this.UpgradeLevel = (dataBase as Serialization_ExtendedWateringCan).UpgradeLevel;
this.waterCanMax= (dataBase as Serialization_ExtendedWateringCan).MaxCapacity;
this.WaterLeft= (dataBase as Serialization_ExtendedWateringCan).WaterLeft;
}
public override void draw(SpriteBatch b)
{
base.draw(b);
}
public override void drawInMenu(SpriteBatch spriteBatch, Vector2 location, float scaleSize, float transparency, float layerDepth, bool drawStackNumber, Color color, bool drawShadow)
{
spriteBatch.Draw(texture.getTexture(), location + new Vector2(32f, 32f), new Rectangle(0, 0, 16, 16), color * transparency, 0.0f, new Vector2(8f, 8f), 4f * scaleSize, SpriteEffects.None, layerDepth);
if (!drawStackNumber || Game1.player.hasWateringCanEnchantment)
return;
spriteBatch.Draw(Game1.mouseCursors, location + new Vector2(4f, 44f), new Rectangle?(new Rectangle(297, 420, 14, 5)), Color.White * transparency, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, layerDepth + 0.0001f);
spriteBatch.Draw(Game1.staminaRect, new Rectangle((int)location.X + 8, (int)location.Y + 64 - 16, (int)((double)this.WaterLeft / (double)this.waterCanMax * 48.0), 8), Color.DodgerBlue * 0.7f * transparency);
}
public override bool canBeDropped()
{
return true;
}
public override bool canBeTrashed()
{
return true;
}
public Type getCustomType()
{
return this.GetType();
}
public string GetSerializationName()
{
return this.GetType().ToString();
}
public override int maximumStackSize()
{
return 1;
}
public override void setNewTileIndexForUpgradeLevel()
{
//Do nothing.
}
public void upgradeWateringCapacity(int amount)
{
this.waterCanMax += amount;
}
/// <summary>
/// Serializes the said item properly.
/// </summary>
/// <param name="I"></param>
public static void Serialize(Item I)
{
SerializationInformation.Serialization_ExtendedWateringCan tool = new SerializationInformation.Serialization_ExtendedWateringCan((I as ExtendedWateringCan));
String savePath = ModCore.SerializationManager.playerInventoryPath;
String fileName = I.Name + ".json";
String resultPath = Path.Combine(savePath, fileName);
int count = 0;
while (File.Exists(resultPath))
{
resultPath = Serialization.SerializationManager.getValidSavePathIfDuplicatesExist(I, savePath, count);
count++;
}
StardustCore.ModCore.ModHelper.WriteJsonFile<SerializedObjectBase>(resultPath, tool);
}
/// <summary>
/// Serializes the said item to a chest.
/// </summary>
/// <param name="I"></param>
/// <param name="s"></param>
public static void SerializeToContainer(Item I, string s)
{
SerializationInformation.Serialization_ExtendedWateringCan tool = new SerializationInformation.Serialization_ExtendedWateringCan((I as ExtendedWateringCan));
String savePath = s;
String fileName = I.Name + ".json";
String resultPath = Path.Combine(savePath, fileName);
int count = 0;
while (File.Exists(resultPath))
{
resultPath = Serialization.SerializationManager.getValidSavePathIfDuplicatesExist(I, savePath, count);
count++;
}
StardustCore.ModCore.ModHelper.WriteJsonFile<SerializedObjectBase>(resultPath, tool);
}
/// <summary>
/// Deserializes the object from a .json.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static ExtendedWateringCan Deserialize(string data)
{
SerializationInformation.Serialization_ExtendedWateringCan toolData = ModCore.ModHelper.ReadJsonFile< SerializationInformation.Serialization_ExtendedWateringCan>(data);
return new ExtendedWateringCan(toolData);
}
}
}

View File

@ -1,43 +0,0 @@
using StardustCore.Interfaces;
using StardustCore.Objects.Tools.SerializationInformation;
using StardustCore.UIUtilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StardustCore.Objects.Tools.SerializationInformation
{
public class Serialization_ExtendedAxe : SerializedObjectBase
{
public string Name;
public string Description;
public int UpgradeLevel;
public Texture2DExtended TextureInformation;
public Serialization_ExtendedAxe() : base()
{
this.SerializationName = GetSerializationName();
}
public Serialization_ExtendedAxe(ExtendedAxe axe) : base()
{
this.UpgradeLevel = axe.UpgradeLevel;
this.Name = axe.Name;
this.Description = axe.description;
this.TextureInformation = axe.texture;
this.SerializationName = GetSerializationName();
}
public override Type getCustomType()
{
return typeof(ExtendedAxe);
}
public override string GetSerializationName()
{
return typeof(ExtendedAxe).ToString();
}
}
}

View File

@ -1,43 +0,0 @@
using StardustCore.Interfaces;
using StardustCore.Objects.Tools.SerializationInformation;
using StardustCore.UIUtilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StardustCore.Objects.Tools.SerializationInformation
{
public class Serialization_ExtendedHoe : SerializedObjectBase
{
public string Name;
public string Description;
public int UpgradeLevel;
public Texture2DExtended TextureInformation;
public Serialization_ExtendedHoe() : base()
{
this.SerializationName = GetSerializationName();
}
public Serialization_ExtendedHoe(ExtendedHoe axe) : base()
{
this.UpgradeLevel = axe.UpgradeLevel;
this.Name = axe.Name;
this.Description = axe.description;
this.TextureInformation = axe.texture;
this.SerializationName = GetSerializationName();
}
public override Type getCustomType()
{
return typeof(ExtendedHoe);
}
public override string GetSerializationName()
{
return typeof(ExtendedHoe).ToString();
}
}
}

View File

@ -1,42 +0,0 @@
using StardustCore.Interfaces;
using StardustCore.UIUtilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StardustCore.Objects.Tools.SerializationInformation
{
public class Serialization_ExtendedPickaxe : SerializedObjectBase
{
public string Name;
public string Description;
public int UpgradeLevel;
public Texture2DExtended TextureInformation;
public Serialization_ExtendedPickaxe() : base()
{
this.SerializationName = GetSerializationName();
}
public Serialization_ExtendedPickaxe(ExtendedPickaxe axe) : base()
{
this.UpgradeLevel = axe.UpgradeLevel;
this.Name = axe.Name;
this.Description = axe.description;
this.TextureInformation = axe.texture;
this.SerializationName = GetSerializationName();
}
public override Type getCustomType()
{
return typeof(ExtendedPickaxe);
}
public override string GetSerializationName()
{
return typeof(ExtendedPickaxe).ToString();
}
}
}

View File

@ -1,46 +0,0 @@
using StardustCore.Interfaces;
using StardustCore.UIUtilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StardustCore.Objects.Tools.SerializationInformation
{
public class Serialization_ExtendedWateringCan : SerializedObjectBase
{
public string Name;
public string Description;
public int UpgradeLevel;
public Texture2DExtended TextureInformation;
public int MaxCapacity;
public int WaterLeft;
public Serialization_ExtendedWateringCan() : base()
{
this.SerializationName = GetSerializationName();
}
public Serialization_ExtendedWateringCan(ExtendedWateringCan tool) : base()
{
this.UpgradeLevel = tool.UpgradeLevel;
this.Name = tool.Name;
this.Description = tool.description;
this.TextureInformation = tool.texture;
this.SerializationName = GetSerializationName();
this.MaxCapacity = tool.waterCanMax;
this.WaterLeft = tool.WaterLeft;
}
public override Type getCustomType()
{
return typeof(ExtendedWateringCan);
}
public override string GetSerializationName()
{
return typeof(ExtendedWateringCan).ToString();
}
}
}

View File

@ -1,29 +0,0 @@
using StardustCore.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StardustCore.Objects.Tools.SerializationInformation
{
public class SerializedObjectBase : IItemSerializeable
{
public string SerializationName;
public SerializedObjectBase()
{
this.SerializationName = this.GetSerializationName();
}
public virtual Type getCustomType()
{
return this.GetType();
}
public virtual string GetSerializationName()
{
return this.GetType().ToString();
}
}
}

View File

@ -1,971 +0,0 @@
using Microsoft.Xna.Framework;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using StardewModdingAPI;
using StardewValley;
using StardewValley.Buildings;
using StardewValley.Objects;
using StardustCore.Interfaces;
using StardustCore.Objects.Tools;
using StardustCore.Objects.Tools.SerializationInformation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace StardustCore.Serialization
{
/// <summary>
/// TODO: Find a way to serialize objects and tools.
/// </summary>
public class SerializationManager
{
public string objectsInWorldPath;
public string playerInventoryPath;
public string serializerTrashPath;
public string storageContainerPath;
public Dictionary<string, SerializerDataNode> acceptedTypes = new Dictionary<string, SerializerDataNode>();
public List<IItemSerializeable> trackedObjectList = new List<IItemSerializeable>();
public SerializationManager(string PlayerInventoryPath,string SerializerTrashPath,string ObjectsInWorldPath,string StorageContainerPath)
{
objectsInWorldPath = ObjectsInWorldPath;
playerInventoryPath = PlayerInventoryPath;
serializerTrashPath = SerializerTrashPath;
storageContainerPath = StorageContainerPath;
verifyAllDirectoriesExist();
}
private void verifyAllDirectoriesExist()
{
if (!Directory.Exists(playerInventoryPath)) Directory.CreateDirectory(playerInventoryPath);
if (!Directory.Exists(serializerTrashPath)) Directory.CreateDirectory(serializerTrashPath);
if (!Directory.Exists(objectsInWorldPath)) Directory.CreateDirectory(objectsInWorldPath);
if (!Directory.Exists(storageContainerPath)) Directory.CreateDirectory(storageContainerPath);
}
public void cleanUpInventory()
{
return;
ProcessDirectoryForDeletion(playerInventoryPath);
//ProcessDirectoryForDeletion(SerializerTrashPath);
List<Item> removalList = new List<Item>();
foreach (Item d in Game1.player.Items)
{
try
{
if (d == null)
{
//Log.AsyncG("WTF");
continue;
}
// Log.AsyncC(d.GetType());
}
catch (Exception err)
{
ModCore.ModMonitor.Log(err.ToString());
}
string s = Convert.ToString((d.GetType()));
if (acceptedTypes.ContainsKey(s))
{
SerializerDataNode t;
bool works = acceptedTypes.TryGetValue(s, out t);
if (works == true)
{
t.serialize.Invoke(d);
removalList.Add(d);
}
}
}
foreach (var i in removalList)
{
Game1.player.removeItemFromInventory(i);
}
if (Game1.IsMasterGame)
{
foreach (Farmer f in Game1.getAllFarmhands())
{
List<Item> farmHandCleaner = new List<Item>();
foreach (Item i in f.Items)
{
if (i == null) continue;
string s = Convert.ToString((i.GetType()));
if (acceptedTypes.ContainsKey(s))
{
SerializerDataNode t;
bool works = acceptedTypes.TryGetValue(s, out t);
if (works == true)
{
farmHandCleaner.Add(i);
}
}
}
foreach(Item i in farmHandCleaner)
{
f.removeItemFromInventory(i);
}
}
}
removalList.Clear();
}
/// <summary>
/// Removes custom objects from the world and saves them to a file.
/// </summary>
public void cleanUpWorld()
{
return;
try
{
ProcessDirectoryForDeletion(objectsInWorldPath);
}
catch(Exception e)
{
ModCore.ModMonitor.Log(e.ToString());
}
List<IItemSerializeable> removalList = new List<IItemSerializeable>();
int countProcessed = 0;
List<Item> idk = new List<Item>();
List<GameLocation> allLocations = new List<GameLocation>();
foreach (GameLocation location in Game1.locations)
{
allLocations.Add(location);
}
foreach(Building b in Game1.getFarm().buildings)
{
allLocations.Add(b.indoors);
}
foreach(GameLocation loc in allLocations)
{
foreach(var layer in loc.objects)
{
foreach(var pair in layer)
{
if (removalList.Contains((pair.Value as CoreObject))) continue;
try
{
if (pair.Value == null)
{
//Log.AsyncG("WTF");
continue;
}
// Log.AsyncC(d.GetType());
}
catch (Exception e)
{
//ModCore.ModMonitor.Log(e.ToString());
}
string s = Convert.ToString((pair.Value.GetType()));
if (acceptedTypes.ContainsKey(s))
{
// Log.AsyncM("Object is of accepted type: " + s);
SerializerDataNode t;
bool works = acceptedTypes.TryGetValue(s, out t);
if (works == true)
{
countProcessed++;
if ((pair.Value as CoreObject).useXML == false)
{
// Log.AsyncY("Saving the object");
//Removes the object from the world and saves it to a file.
t.worldObj.Invoke((pair.Value as CoreObject));
}
else
{
idk.Add((pair.Value as CoreObject));
}
// Log.AsyncC("Progress on saving objects: " + countProcessed + "/" + Lists.trackedObjectList.Count);
removalList.Add((pair.Value as CoreObject));
}
}
}
}
}
foreach (CoreObject d in trackedObjectList)
{
if (removalList.Contains(d)) continue;
try
{
if (d == null)
{
//Log.AsyncG("WTF");
continue;
}
// Log.AsyncC(d.GetType());
}
catch (Exception e)
{
//ModCore.ModMonitor.Log(e.ToString());
}
string s = Convert.ToString((d.GetType()));
if (acceptedTypes.ContainsKey(s))
{
// Log.AsyncM("Object is of accepted type: " + s);
SerializerDataNode t;
bool works = acceptedTypes.TryGetValue(s, out t);
if (works == true)
{
countProcessed++;
if (d.useXML == false)
{
// Log.AsyncY("Saving the object");
//Removes the object from the world and saves it to a file.
t.worldObj.Invoke(d);
}
else
{
idk.Add(d);
}
// Log.AsyncC("Progress on saving objects: " + countProcessed + "/" + Lists.trackedObjectList.Count);
removalList.Add(d);
}
}
}
foreach (var i in removalList)
{
if (i.getCustomType() == typeof(CoreObject))
{
(i as CoreObject).thisLocation.removeObject((i as CoreObject).TileLocation, false);
}
}
foreach (var v in idk)
{
string s = Convert.ToString((v.GetType()));
if (acceptedTypes.ContainsKey(s))
{
SerializerDataNode t;
bool works = acceptedTypes.TryGetValue(s, out t);
if (works == true)
{
countProcessed++;
//If the item is a core object I can validate that it is in the world and not in an inventory.
if ((v is CoreObject))
{
if ((v as CoreObject).useXML == true)
{
t.worldObj.Invoke(v as CoreObject);
}
//Log.AsyncG("Progress on saving objects: " + countProcessed + "/" + Lists.trackedObjectList.Count);
removalList.Add(v as CoreObject);
}
}
}
}
removalList.Clear();
// Log.AsyncM("Revitalize: Done cleaning world for saving.");
}
/// <summary>
/// Clean all of the storage containers in the game from custom objects.
/// </summary>
public void cleanUpStorageContainers()
{
return;
ProcessDirectoryForDeletion(storageContainerPath);
List<Item> removalList = new List<Item>();
foreach (GameLocation loc in Game1.locations)
{
int i = loc.objects.Pairs.Count();
int j = 0;
foreach (KeyValuePair<Vector2, StardewValley.Object> obj in loc.objects.Pairs)
{
j++;
//ModCore.ModMonitor.Log("Parsing location " + loc.Name + " : object number" + j + "/" + i + " : object name: " + obj.Value.name);
//If the object is a chest get the items from it.
if (obj.Value is StardewValley.Objects.Chest) {
int k = (obj.Value as StardewValley.Objects.Chest).items.Count;
int l = 0;
foreach (var item in (obj.Value as StardewValley.Objects.Chest).items)
{
l++;
//ModCore.ModMonitor.Log("Parsing Chest at : " + loc.Name + " X: " + obj.Key.X + " Y: " + obj.Key.Y + " : object number: " + l + "/" + k + "object name: " + item.Name);
if (item is IItemSerializeable) removalList.Add(item);
}
foreach(var v in removalList)
{
(obj.Value as StardewValley.Objects.Chest).items.Remove(v);
SerializerDataNode t;
if (acceptedTypes.ContainsKey((v as IItemSerializeable).GetSerializationName()))
{
acceptedTypes.TryGetValue((v as IItemSerializeable).GetSerializationName(), out t);
string s = Path.Combine(loc.Name, "Chest," + Convert.ToString((int)obj.Key.X) + "," + Convert.ToString((int)obj.Key.Y));
string s2 = Path.Combine(ModCore.SerializationManager.storageContainerPath, s);
if (!Directory.Exists(s)) Directory.CreateDirectory(s2);
t.serializeToContainer.Invoke(v, s2);
}
}
removalList.Clear();
}
}
}
if (Game1.getFarm() == null) return;
if (Game1.getFarm().buildings == null) return;
//Look through all farm buildings for custom items.
foreach (Building building in Game1.getFarm().buildings)
{
if (building == null) continue;
if (String.IsNullOrEmpty(building.nameOfIndoors)) continue;
GameLocation loc =Game1.getLocationFromName(building.nameOfIndoors,true);
//ModCore.ModMonitor.Log("Cleaning up farm building: "+loc.uniqueName.Value);
int i = loc.objects.Pairs.Count();
int j = 0;
foreach (KeyValuePair<Vector2, StardewValley.Object> obj in loc.objects.Pairs)
{
j++;
//ModCore.ModMonitor.Log("Parsing location " + loc.Name + " : object number" + j + "/" + i + " : object name: " + obj.Value.name);
//Look through all chests in all farm buildings.
if (obj.Value is StardewValley.Objects.Chest)
{
int k = (obj.Value as StardewValley.Objects.Chest).items.Count;
int l = 0;
foreach (var item in (obj.Value as StardewValley.Objects.Chest).items)
{
l++;
//ModCore.ModMonitor.Log("Parsing Chest at : " + loc.Name + " X: " + obj.Key.X + " Y: " + obj.Key.Y + " : object number: " + l + "/" + k + "object name: " + item.Name);
if (item is IItemSerializeable) removalList.Add(item);
}
foreach(var v in removalList)
{
(obj.Value as StardewValley.Objects.Chest).items.Remove(v);
SerializerDataNode t;
if(acceptedTypes.ContainsKey((v as IItemSerializeable).GetSerializationName())){
acceptedTypes.TryGetValue((v as IItemSerializeable).GetSerializationName(), out t);
string s = Path.Combine(building.nameOfIndoors, "Chest,"+Convert.ToString( (int)obj.Key.X)+","+Convert.ToString((int)obj.Key.Y));
string s2 = Path.Combine(ModCore.SerializationManager.storageContainerPath, s);
if (!Directory.Exists(s)) Directory.CreateDirectory(s2);
t.serializeToContainer.Invoke(v, s2);
}
}
removalList.Clear();
}
}
}
}
/// <summary>
/// Reloads all modded objects added by this mod back to the game in proper locations.
/// </summary>
/// <param name="thingsToAddBackIn"></param>
public void restoreAllModObjects(List<IItemSerializeable> thingsToAddBackIn, bool onlyInventory=false)
{
return;
processDirectoryForDeserialization(playerInventoryPath,thingsToAddBackIn);
if (onlyInventory) return;
// Log.AsyncG("Done deserializing player inventory.");
try
{
trackedObjectList.Clear(); //clear whatever mod objects I'm tracking
processDirectoryForDeserialization(objectsInWorldPath,thingsToAddBackIn); //restore whatever I'm tracking here when I replace the object back into the world. This also works when loading up the game, not just when saving/loading
processDirectoryForDeserializationIntoContainer(storageContainerPath, thingsToAddBackIn);
}
catch (Exception e)
{
ModCore.ModMonitor.Log(e.ToString());
}
}
public void ProcessDirectoryForDeletion(string targetDirectory)
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
{
File.Delete(fileName);
// File.Delete(fileName);
}
// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
ProcessDirectoryForDeletion(subdirectory);
}
public void serializeXML<T>(Item I)
{
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
var newWriter = new StringWriter();
using (var writer = XmlWriter.Create(newWriter))
{
xmlSerializer.Serialize(writer,I);
}
}
/// <summary>
///
/// </summary>
/// <param name="pathToFile"></param>
/// <param name="thingsToAddBackIn">Typically this would be the trackedObjectList.</param>
public void processDirectoryForDeserialization(string pathToFile,List<IItemSerializeable> thingsToAddBackIn)
{
//StardustCore.ModCore.ModMonitor.Log("Look through dir: " + pathToFile);
string[] fileEntries = Directory.GetFiles(pathToFile);
// Log.AsyncC(pathToFile);
foreach(var fileName in fileEntries)
{
ProcessFileForCleanUp(fileName,thingsToAddBackIn);
// Log.AsyncG(fileName);
}
string[] subDirectories = Directory.GetDirectories(pathToFile);
foreach(var folder in subDirectories)
{
processDirectoryForDeserialization(folder,thingsToAddBackIn);
}
}
public void processDirectoryForDeserializationIntoContainer(string pathToFile, List<IItemSerializeable> thingsToAddBackIn)
{
string[] fileEntries = Directory.GetFiles(pathToFile);
// Log.AsyncC(pathToFile);
foreach (var fileName in fileEntries)
{
ProcessFileForCleanUpIntoContainer(fileName, thingsToAddBackIn);
// Log.AsyncG(fileName);
}
string[] subDirectories = Directory.GetDirectories(pathToFile);
foreach (var folder in subDirectories)
{
processDirectoryForDeserializationIntoContainer(folder, thingsToAddBackIn);
}
}
public void ProcessFileForCleanUp(string path, List<IItemSerializeable> thingsToAddBackIn)
{
try
{
string type = "";
int count = 0;
while (type == "" || type==null)
{
if (count == 0)
{
//THE ERROR LIES HERE AS IT THINKS IT CAN TRY TO BE A CORE OBJECT WHEN IT IS NOT!!!!
CoreObject core_obj = StardustCore.ModCore.ModHelper.ReadJsonFile<CoreObject>(path); //FIND A WAY TO FIX THIS!!!!
type = (core_obj as CoreObject).serializationName;
//ModCore.ModMonitor.Log("UMM THIS CAN't BE RIGHT 1" + type);
}
if (count == 1)
{
//THIS NEEDS TO BE SOMETHING GENERIC!!!
SerializedObjectBase core_obj = StardustCore.ModCore.ModHelper.ReadJsonFile<SerializedObjectBase>(path);
type = (core_obj as SerializedObjectBase).SerializationName;
//ModCore.ModMonitor.Log("UMM THIS CAN't BE RIGHT 2" + type);
}
if (count == 2)
{
ModCore.ModMonitor.Log("A valid type could not be found for the file: "+path);
return;
}
count++;
}
foreach (KeyValuePair<string, SerializerDataNode> pair in acceptedTypes)
{
// Log.AsyncY(pair.Key);
if (pair.Key == type)
{
try
{
//parse from Json Style
// Log.AsyncR("1");
var cObj = pair.Value.parse.Invoke(path);
if (cObj is CoreObject)
{
(cObj as CoreObject).thisLocation = Game1.getLocationFromName((cObj as CoreObject).locationsName);
if ((cObj as CoreObject).thisLocation == null)
{
Game1.player.addItemToInventory(cObj);
// Log.AsyncY("ADDED ITEM TO INVENTORY");
return;
}
else
{
try
{
(cObj as CoreObject).thisLocation.objects.Add((cObj as CoreObject).TileLocation, (StardewValley.Object)cObj);
thingsToAddBackIn.Add(cObj as CoreObject);
}
catch(Exception err)
{
//throw new Exception(err.ToString());
return;
}
//Util.placementAction(cObj, cObj.thisLocation,(int)cObj.tileLocation.X,(int) cObj.tileLocation.Y,null,false);
}
}
else
{
Game1.player.addItemToInventory(cObj);
}
}
catch (Exception e)
{
ModCore.ModMonitor.Log(e.ToString());
// Log.AsyncO(e);
}
}
}
}
catch (Exception err)
{
ModCore.ModMonitor.Log(err.ToString());
//Tool t = StardustCore.ModCore.ModHelper.ReadJsonFile<Tool>(path);
}
}
/*
/// <summary>
/// Process an item from a file back into it's original storage container.
/// </summary>
/// <param name="path"></param>
/// <param name="thingsToAddBackIn"></param>
public void ProcessFileForCleanUpIntoContainer(string path, List<IItemSerializeable> thingsToAddBackIn)
{
//Log.AsyncC(path);
string newLine = Environment.NewLine;
string[] chestArray= path.Split(new string[] { "/"}, StringSplitOptions.None);
string[] chestArray2= path.Split(new string[] { "\\" }, StringSplitOptions.None);
/*
foreach (var v in chestArray)
{
Log.AsyncC("PART OF PATH "+v);
}
foreach (var v in chestArray2)
{
Log.AsyncC("PART OF PATH2 " + v);
}
if (chestArray2.Length > chestArray.Length) chestArray = chestArray2;
GameLocation loc = Game1.getLocationFromName(chestArray[chestArray.Length - 3]);
string[] chest = chestArray[chestArray.Length - 2].Split(',');
StardewValley.Object chestObject;
bool f = loc.objects.TryGetValue(new Microsoft.Xna.Framework.Vector2( Convert.ToInt32(chest[1]),Convert.ToInt32(chest[2])),out chestObject);
if (f == true)
{
ModCore.ModMonitor.Log("YAY");
}
else
{
ModCore.ModMonitor.Log("BOO");
}
string[] ehh = File.ReadAllLines(path);
Item cObj;
string a;
string[] b;
string s = "";
// Log.AsyncC(path);
// Log.AsyncC(data);
SerializedObjectBase obj = StardustCore.ModCore.ModHelper.ReadJsonFile<SerializedObjectBase>(path);
try
{
// Log.AsyncC(obj.thisType);
a = obj.SerializationName;
ModCore.ModMonitor.Log(":THIS IS MY TYPE!!!:" + a);
b = a.Split(',');
s = b.ElementAt(0);
// Log.AsyncC(s);
}
catch (Exception e)
{
ModCore.ModMonitor.Log(e.ToString());
//USE XML STYLE DESERIALIZING
foreach (KeyValuePair<string, SerializerDataNode> pair in acceptedTypes)
{
var word = ParseXMLType(path);
if (pair.Key == word.ToString())
{
cObj = pair.Value.parse.Invoke(path);
if (cObj is CoreObject)
{
(cObj as CoreObject).thisLocation = Game1.getLocationFromName((cObj as CoreObject).locationsName);
(cObj as CoreObject).resetTexture();
if ((cObj as CoreObject).thisLocation == null)
{
// Game1.player.addItemToInventory(cObj);
try
{
Utilities.addItemToOtherInventory((chestObject as StardewValley.Objects.Chest).items, (cObj as CoreObject));
}
catch (Exception err)
{
ModCore.ModMonitor.Log(err.ToString(), LogLevel.Error);
}
// Log.AsyncY("ADDED ITEM TO INVENTORY");
return;
}
else
{
(cObj as CoreObject).thisLocation.objects.Add((cObj as CoreObject).TileLocation, (StardewValley.Object)cObj);
thingsToAddBackIn.Add((cObj as CoreObject));
//Util.placementAction(cObj, cObj.thisLocation,(int)cObj.tileLocation.X,(int) cObj.tileLocation.Y,null,false);
}
}
else
{
try
{
Utilities.addItemToOtherInventory((chestObject as StardewValley.Objects.Chest).items, cObj);
}
catch (Exception err)
{
ModCore.ModMonitor.Log(err.ToString(), LogLevel.Error);
}
}
}
}
// Log.AsyncG("attempting to parse from path and value of s is " + s);
}
// var cObj = parseBagOfHolding(path); //pair.Value.parse.Invoke(path);
// cObj.TextureSheet = Game1.content.Load<Texture2D>(Path.Combine("Revitalize", "CropsNSeeds", "Graphics", "seeds"));
/*
cObj.thisLocation = Game1.getLocationFromName(cObj.locationsName);
if (cObj.thisLocation == null)
{
Game1.player.addItemToInventory(cObj);
return;
}
else
{
cObj.thisLocation.objects.Add(cObj.tileLocation, cObj);
Lists.trackedObjectList.Add(cObj);
//Util.placementAction(cObj, cObj.thisLocation,(int)cObj.tileLocation.X,(int) cObj.tileLocation.Y,null,false);
}
//USE JSON STYLE DESERIALIZNG
if (acceptedTypes.ContainsKey(s))
{
foreach (KeyValuePair<string, SerializerDataNode> pair in acceptedTypes)
{
// Log.AsyncY(pair.Key);
if (pair.Key == s)
{
try
{
//parse from Json Style
// Log.AsyncR("1");
cObj = pair.Value.parse.Invoke(path);
if (cObj is CoreObject)
{
(cObj as CoreObject).thisLocation = Game1.getLocationFromName((cObj as CoreObject).locationsName);
if ((cObj as CoreObject).thisLocation == null)
{
try
{
Utilities.addItemToOtherInventory((chestObject as StardewValley.Objects.Chest).items, (cObj as CoreObject));
foreach (var v in (chestObject as StardewValley.Objects.Chest).items)
{
ModCore.ModMonitor.Log(v.Name);
}
}
catch (Exception err)
{
ModCore.ModMonitor.Log(err.ToString(), LogLevel.Error);
}
// Log.AsyncY("ADDED ITEM TO INVENTORY");
return;
}
else
{
(cObj as CoreObject).thisLocation.objects.Add((cObj as CoreObject).TileLocation, (StardewValley.Object)cObj);
thingsToAddBackIn.Add((cObj as CoreObject));
//Util.placementAction(cObj, cObj.thisLocation,(int)cObj.tileLocation.X,(int) cObj.tileLocation.Y,null,false);
}
}
else
{
try
{
Utilities.addItemToOtherInventory((chestObject as StardewValley.Objects.Chest).items, cObj);
}
catch (Exception err)
{
ModCore.ModMonitor.Log(err.ToString(), LogLevel.Error);
}
}
}
catch (Exception e)
{
ModCore.ModMonitor.Log(e.ToString());
// Log.AsyncO(e);
}
}
}
}
else
{
ModCore.ModMonitor.Log("Error parsing unknown object type: " + s, LogLevel.Error);
}
}
*/
public void ProcessFileForCleanUpIntoContainer(string path, List<IItemSerializeable> thingsToAddBackIn)
{
//Log.AsyncC(path);
string newLine = Environment.NewLine;
string[] chestArray = path.Split(new string[] { "/" }, StringSplitOptions.None);
string[] chestArray2 = path.Split(new string[] { "\\" }, StringSplitOptions.None);
/*
foreach (var v in chestArray)
{
Log.AsyncC("PART OF PATH "+v);
}
foreach (var v in chestArray2)
{
Log.AsyncC("PART OF PATH2 " + v);
}
*/
if (chestArray2.Length > chestArray.Length) chestArray = chestArray2;
GameLocation loc = Game1.getLocationFromName(chestArray[chestArray.Length - 3]);
string[] chest = chestArray[chestArray.Length - 2].Split(',');
StardewValley.Object chestObject;
bool f = loc.objects.TryGetValue(new Microsoft.Xna.Framework.Vector2(Convert.ToInt32(chest[1]), Convert.ToInt32(chest[2])), out chestObject);
try
{
string type = "";
int count = 0;
while (type == "" || type == null)
{
if (count == 0)
{
//THE ERROR LIES HERE AS IT THINKS IT CAN TRY TO BE A CORE OBJECT WHEN IT IS NOT!!!!
CoreObject core_obj = StardustCore.ModCore.ModHelper.ReadJsonFile<CoreObject>(path); //FIND A WAY TO FIX THIS!!!!
type = (core_obj as CoreObject).serializationName;
//ModCore.ModMonitor.Log("UMM THIS CAN't BE RIGHT 1" + type);
}
if (count == 1)
{
//THIS NEEDS TO BE SOMETHING GENERIC!!!
SerializedObjectBase core_obj = StardustCore.ModCore.ModHelper.ReadJsonFile<SerializedObjectBase>(path);
type = (core_obj as SerializedObjectBase).SerializationName;
//ModCore.ModMonitor.Log("UMM THIS CAN't BE RIGHT 2" + type);
}
if (count == 2)
{
ModCore.ModMonitor.Log("A valid type could not be found for the file: " + path);
return;
}
count++;
}
foreach (KeyValuePair<string, SerializerDataNode> pair in acceptedTypes)
{
// Log.AsyncY(pair.Key);
if (pair.Key == type)
{
try
{
//parse from Json Style
// Log.AsyncR("1");
var cObj = pair.Value.parse.Invoke(path);
if (cObj is CoreObject)
{
(cObj as CoreObject).thisLocation = Game1.getLocationFromName((cObj as CoreObject).locationsName);
if ((cObj as CoreObject).thisLocation == null)
{
Utilities.addItemToOtherInventory((chestObject as Chest).items, cObj);
// Log.AsyncY("ADDED ITEM TO INVENTORY");
return;
}
else
{
(cObj as CoreObject).thisLocation.objects.Add((cObj as CoreObject).TileLocation, (StardewValley.Object)cObj);
thingsToAddBackIn.Add(cObj as CoreObject);
//Util.placementAction(cObj, cObj.thisLocation,(int)cObj.tileLocation.X,(int) cObj.tileLocation.Y,null,false);
}
}
else
{
Utilities.addItemToOtherInventory((chestObject as Chest).items, cObj);
}
}
catch (Exception e)
{
ModCore.ModMonitor.Log(e.ToString());
// Log.AsyncO(e);
}
}
}
}
catch (Exception err)
{
ModCore.ModMonitor.Log(err.ToString());
//Tool t = StardustCore.ModCore.ModHelper.ReadJsonFile<Tool>(path);
}
}
/// <summary>
/// ???
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public string ParseXMLType(string path)
{
string[] s = File.ReadAllLines(path);
string returnString = "";
foreach (string v in s)
{
// Log.AsyncC(v);
if (v.Contains("serializationName"))
{
returnString = v.Remove(0, 12);
returnString = returnString.Remove(returnString.Length - 11, 11);
}
}
return returnString;
}
/// <summary>
/// Parse rectangles.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static Microsoft.Xna.Framework.Rectangle parseRectFromJson(string s)
{
s = s.Replace('{', ' ');
s = s.Replace('}', ' ');
s = s.Replace('^', ' ');
s = s.Replace(':', ' ');
string[] parsed = s.Split(' ');
foreach (var v in parsed)
{
//Log.AsyncY(v);
}
return new Microsoft.Xna.Framework.Rectangle(Convert.ToInt32(parsed[2]), Convert.ToInt32(parsed[4]), Convert.ToInt32(parsed[6]), Convert.ToInt32(parsed[8]));
}
/// <summary>
/// Remove all objects that there are a copy of this thing?
/// </summary>
/// <param name="c"></param>
public void removeObjectWithCopy(CoreObject c)
{
foreach(var v in StardustCore.ModCore.SerializationManager.trackedObjectList)
{
if (v.getCustomType() == typeof(CoreObject))
{
if (c.TileLocation == (v as CoreObject).TileLocation && c.thisLocation == (v as CoreObject).thisLocation)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
}
}
}
}
/// <summary>
/// Initializes a list of default supported types added by Stardust Core.
/// </summary>
public void initializeDefaultSuportedTypes()
{
initializeSupportedToolTypes();
initializeSupportedObjectTypes();
}
private void initializeSupportedObjectTypes()
{
this.acceptedTypes.Add(typeof(CoreObject).ToString(), new SerializerDataNode(CoreObject.Serialize, CoreObject.Deserialize, new SerializerDataNode.WorldParsingFunction(CoreObject.Serialize), new SerializerDataNode.SerializingToContainerFunction(CoreObject.SerializeToContainer)));
}
/// <summary>
/// Initializes supported tools made by Stardust Core.
/// </summary>
private void initializeSupportedToolTypes()
{
this.acceptedTypes.Add(typeof(ExtendedAxe).ToString(), new SerializerDataNode(ExtendedAxe.Serialize, ExtendedAxe.Deserialize, null, new SerializerDataNode.SerializingToContainerFunction(ExtendedAxe.SerializeToContainer)));
}
public static string getValidSavePathIfDuplicatesExist(Item I, string path, int number)
{
String savePath = path;
String fileName = I.Name + number + ".json";
String resultPath = Path.Combine(savePath, fileName);
return resultPath;
}
}
}

View File

@ -1,73 +0,0 @@
using StardewValley;
using StardustCore.Objects.Tools.SerializationInformation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StardustCore.Serialization
{
/// <summary>
/// A class that handles saving/loading custom objects to and from the world.
/// </summary>
public class SerializerDataNode
{
/// <summary>
/// A function that handles loading an object back into it's Item form.
/// </summary>
/// <param name="path">The path to the file.</param>
/// <returns></returns>
public delegate Item ParsingFunction(string path);
/// <summary>
/// A function that handles saving an item.
/// </summary>
/// <param name="item"></param>
public delegate void SerializingFunction(Item item);
/// <summary>
/// A function that handles saving an item from/to a container.
/// </summary>
/// <param name="item"></param>
/// <param name="s"></param>
public delegate void SerializingToContainerFunction(Item item, string s);
/// <summary>
/// A function that handles saving.loading items into the world.
/// </summary>
/// <param name="obj"></param>
public delegate void WorldParsingFunction(Item obj);
/// <summary>
/// Saves an object to an inventory.
/// </summary>
public SerializingFunction serialize;
/// <summary>
/// Saves an object to a container
/// </summary>
public SerializingToContainerFunction serializeToContainer;
/// <summary>
/// Loads in an object.
/// </summary>
public ParsingFunction parse;
/// <summary>
/// Loads in an object to the game world.
/// </summary>
public WorldParsingFunction worldObj;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="serializeFunction">A function to be ran to save this object.</param>
/// <param name="parsingFunction">A function to be ran to load this object.</param>
/// <param name="worldObjectParsingFunction">A function to be ran to load this object to the world.</param>
/// <param name="containerSerializationFunction">A function to be ran to save/load objects to storage containers such as chests.</param>
public SerializerDataNode(SerializingFunction serializeFunction, ParsingFunction parsingFunction, WorldParsingFunction worldObjectParsingFunction, SerializingToContainerFunction containerSerializationFunction)
{
serialize = serializeFunction;
parse = parsingFunction;
worldObj = worldObjectParsingFunction;
serializeToContainer = containerSerializationFunction;
}
}
}

View File

@ -87,35 +87,10 @@
<Compile Include="Enums\Directions.cs" />
<Compile Include="Enums\Weather.cs" />
<Compile Include="IlluminateFramework\Colors.cs" />
<Compile Include="Interfaces\ISerializeable.cs" />
<Compile Include="Interfaces\IToolSerializer.cs" />
<Compile Include="Math\Hex.cs" />
<Compile Include="Math\Hex32.cs" />
<Compile Include="Menus\ModualGameMenu.cs" />
<Compile Include="ModConfig.cs" />
<Compile Include="NetCode\Graphics\NetAnimation.cs" />
<Compile Include="NetCode\Graphics\NetAnimationManager.cs" />
<Compile Include="NetCode\MultiplayerSupport.cs" />
<Compile Include="NetCode\NetBufferReadStream.cs" />
<Compile Include="NetCode\NetBufferWriteStream.cs" />
<Compile Include="NetCode\NetKeyValuePair.cs" />
<Compile Include="NetCode\NetPairs\NetVector2MultiTilePair.cs" />
<Compile Include="NetCode\NetTexure2DExtended.cs" />
<Compile Include="NetCode\Objects\NetCoreObject.cs" />
<Compile Include="NetCode\Objects\NetMultiTileComponent.cs" />
<Compile Include="NetCode\Objects\NetMultiTileObject.cs" />
<Compile Include="Objects\MultiTileComponent.cs" />
<Compile Include="Objects\MultiTileObject.cs" />
<Compile Include="Objects\Tools\BasicToolInfo.cs" />
<Compile Include="Objects\Tools\ExtendedAxe.cs" />
<Compile Include="Objects\Tools\ExtendedHoe.cs" />
<Compile Include="Objects\Tools\ExtendedPickaxe.cs" />
<Compile Include="Objects\Tools\ExtendedWateringCan.cs" />
<Compile Include="Objects\Tools\SerializationInformation\Serialization_ExtendedAxe.cs" />
<Compile Include="Objects\Tools\SerializationInformation\Serialization_ExtendedHoe.cs" />
<Compile Include="Objects\Tools\SerializationInformation\Serialization_ExtendedPickaxe.cs" />
<Compile Include="Objects\Tools\SerializationInformation\Serialization_ExtendedWateringCan.cs" />
<Compile Include="Objects\Tools\SerializationInformation\SerializedObjectBase.cs" />
<Compile Include="UIUtilities\IClickableMenuExtended.cs" />
<Compile Include="UIUtilities\LayeredTexture.cs" />
<Compile Include="UIUtilities\MenuComponents\CycleButton.cs" />
@ -130,18 +105,13 @@
<Compile Include="UIUtilities\SpriteFonts\Fonts\Components\TexturedCharacter.cs" />
<Compile Include="UIUtilities\SpriteFonts\Fonts\Components\TexturedString.cs" />
<Compile Include="ModCore.cs" />
<Compile Include="Objects\CoreObject.cs" />
<Compile Include="ModInfo\Metadata.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Serialization\Serialization.cs" />
<Compile Include="Serialization\SerializerDataNode.cs" />
<Compile Include="StaticClass.cs" />
<Compile Include="UIUtilities\MenuComponents\Button.cs" />
<Compile Include="UIUtilities\SpriteFonts\Fonts\VanillaFont.cs" />
<Compile Include="UIUtilities\SpriteFonts\SpriteFont.cs" />
<Compile Include="UIUtilities\Texture2DExtended.cs" />
<Compile Include="UIUtilities\TextureManager.cs" />
<Compile Include="Utilities.cs" />
</ItemGroup>
<ItemGroup>
<None Include="manifest.json" />

View File

@ -1,673 +0,0 @@

using Microsoft.Xna.Framework;
using Netcode;
using StardewModdingAPI;
using StardewValley;
using StardewValley.Characters;
using StardewValley.Locations;
using StardewValley.Objects;
using StardewValley.TerrainFeatures;
using StardewValley.Tools;
using StardustCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using xTile.Dimensions;
namespace StardustCore
{
public class Utilities
{
public static List<CoreObject> masterRemovalList = new List<CoreObject>();
public static string getShortenedDirectory(string modName,string path)
{
string lol = (string)path.Clone();
string[] spliter = lol.Split(new string[] { modName }, StringSplitOptions.None);
return spliter[1];
}
public static string getShortenedDirectory(IModHelper modHelper, string path)
{
string lol = (string)path.Clone();
string[] spliter = lol.Split(new string[] { modHelper.DirectoryPath }, StringSplitOptions.None);
return spliter[1];
}
public static int sellToStorePrice(CoreObject c)
{
return (int)((double)c.Price * (1.0 + (double)c.Quality * 0.25));
}
/// <summary>
/// Create some object debris at my game location.
/// </summary>
/// <param name="objectIndex"></param>
/// <param name="xTile"></param>
/// <param name="yTile"></param>
/// <param name="groundLevel"></param>
/// <param name="itemQuality"></param>
/// <param name="velocityMultiplyer"></param>
/// <param name="location"></param>
public static void createObjectDebris(int objectIndex, int xTile, int yTile, int groundLevel = -1, int itemQuality = 0, float velocityMultiplyer = 1f, GameLocation location = null)
{
if (location == null)
location = Game1.currentLocation;
Debris debris = new Debris(objectIndex, new Vector2((float)(xTile * 64 + 32), (float)(yTile * 64 + 32)), new Vector2((float)Game1.player.getStandingX(), (float)Game1.player.getStandingY()))
{
itemQuality = itemQuality
};
foreach (Chunk chunk in (IEnumerable<Chunk>)debris.Chunks)
{
chunk.xVelocity.Value *= (float)(double)velocityMultiplyer;
chunk.yVelocity.Value *= (float)(double)velocityMultiplyer;
}
if (groundLevel != -1)
debris.chunkFinalYLevel = groundLevel;
location.debris.Add(debris);
}
/// <summary>
/// Place a core object into a game location.
/// </summary>
/// <param name="cObj"></param>
/// <param name="location"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="s"></param>
/// <param name="who"></param>
/// <param name="playSound"></param>
/// <returns></returns>
public static bool placementAction(CoreObject cObj, GameLocation location, int x, int y,Serialization.SerializationManager s, StardewValley.Farmer who = null, bool playSound = true)
{
Vector2 vector = new Vector2((float)(x / Game1.tileSize), (float)(y / Game1.tileSize));
// cObj.health = 10;
if (who != null)
{
if (cObj == null)
{
StardustCore.ModCore.ModMonitor.Log("WHY IS MY COMPONENT NULL???");
}
cObj.owner.Value = who.UniqueMultiplayerID;
}
else
{
cObj.owner.Value = Game1.player.UniqueMultiplayerID;
}
int num = cObj.ParentSheetIndex;
if (num <= 130)
{
if (num == 71)
{
if (location is MineShaft)
{
if ((location as MineShaft).mineLevel != 120 && (location as MineShaft).recursiveTryToCreateLadderDown(vector, "hoeHit", 16))
{
return true;
}
Game1.showRedMessage("Unsuitable Location");
}
return false;
}
if (num == 130)
{
if (location.objects.ContainsKey(vector) || Game1.currentLocation is MineShaft)
{
Game1.showRedMessage("Unsuitable Location");
return false;
}
location.objects.Add(vector, new Chest(true)
{
shakeTimer = 50
});
Game1.playSound("axe");
return true;
}
}
else
{
switch (num)
{
case 143:
case 144:
case 145:
case 146:
case 147:
case 148:
case 149:
case 150:
case 151:
if (location.objects.ContainsKey(vector))
{
return false;
}
new Torch(vector, cObj.ParentSheetIndex, true)
{
shakeTimer = 25
}.placementAction(location, x, y, who);
return true;
default:
if (num == 163)
{
location.objects.Add(vector, new Cask(vector));
Game1.playSound("hammer");
}
break;
}
}
if (cObj.name.Equals("Tapper"))
{
if (location.terrainFeatures.ContainsKey(vector) && location.terrainFeatures[vector] is Tree && (location.terrainFeatures[vector] as Tree).growthStage.Value >= 5 && !(location.terrainFeatures[vector] as Tree).stump.Value && !location.objects.ContainsKey(vector))
{
cObj.TileLocation = vector;
location.objects.Add(vector, cObj);
int treeType = (location.terrainFeatures[vector] as Tree).treeType.Value;
(location.terrainFeatures[vector] as Tree).tapped.Value = true;
switch (treeType)
{
case 1:
cObj.heldObject.Value = new StardewValley.Object(725, 1, false, -1, 0);
cObj.MinutesUntilReady = 13000 - Game1.timeOfDay;
break;
case 2:
cObj.heldObject.Value = new StardewValley.Object(724, 1, false, -1, 0);
cObj.MinutesUntilReady = 16000 - Game1.timeOfDay;
break;
case 3:
cObj.heldObject.Value = new StardewValley.Object(726, 1, false, -1, 0);
cObj.MinutesUntilReady = 10000 - Game1.timeOfDay;
break;
case 7:
cObj.heldObject.Value = new StardewValley.Object(420, 1, false, -1, 0);
cObj.MinutesUntilReady = 3000 - Game1.timeOfDay;
if (!Game1.currentSeason.Equals("fall"))
{
cObj.heldObject.Value = new StardewValley.Object(404, 1, false, -1, 0);
cObj.MinutesUntilReady = 6000 - Game1.timeOfDay;
}
break;
}
Game1.playSound("axe");
return true;
}
return false;
}
else if (cObj.name.Contains("Sapling"))
{
Vector2 key = default(Vector2);
for (int i = x / Game1.tileSize - 2; i <= x / Game1.tileSize + 2; i++)
{
for (int j = y / Game1.tileSize - 2; j <= y / Game1.tileSize + 2; j++)
{
key.X = (float)i;
key.Y = (float)j;
if (location.terrainFeatures.ContainsKey(key) && (location.terrainFeatures[key] is Tree || location.terrainFeatures[key] is FruitTree))
{
Game1.showRedMessage("Too close to another tree");
return false;
}
}
}
if (location.terrainFeatures.ContainsKey(vector))
{
if (!(location.terrainFeatures[vector] is HoeDirt) || (location.terrainFeatures[vector] as HoeDirt).crop != null)
{
return false;
}
location.terrainFeatures.Remove(vector);
}
if (location is Farm && (location.doesTileHaveProperty((int)vector.X, (int)vector.Y, "Diggable", "Back") != null || location.doesTileHavePropertyNoNull((int)vector.X, (int)vector.Y, "Type", "Back").Equals("Grass")))
{
Game1.playSound("dirtyHit");
DelayedAction.playSoundAfterDelay("coin", 100);
location.terrainFeatures.Add(vector, new FruitTree(cObj.ParentSheetIndex));
return true;
}
Game1.showRedMessage("Can't be planted here.");
return false;
}
else
{
//Game1.showRedMessage("STEP 1");
if (cObj.Category == -74)
{
return true;
}
if (!cObj.performDropDownAction(who))
{
CoreObject @object = cObj;
@object.shakeTimer = 50;
@object.TileLocation = vector;
@object.performDropDownAction(who);
if (location.objects.ContainsKey(vector))
{
if (location.objects[vector].ParentSheetIndex != cObj.ParentSheetIndex)
{
Game1.createItemDebris(location.objects[vector], vector * (float)Game1.tileSize, Game1.random.Next(4));
location.objects[vector] = @object;
}
}
else
{
// Game1.showRedMessage("STEP 2");
//ModCore.ModMonitor.Log(vector.ToString());
Vector2 newVec = new Vector2(vector.X, vector.Y);
// cObj.boundingBox.Inflate(32, 32);
location.objects.Add(newVec, cObj);
}
@object.initializeLightSource(vector);
}
if (playSound == true) Game1.playSound("woodyStep");
else
{
ModCore.ModMonitor.Log("restoring item from file");
}
//Log.AsyncM("Placed and object");
cObj.locationsName = location.Name;
s.trackedObjectList.Add(cObj);
return true;
}
}
public static bool addItemToInventoryAndCleanTrackedList(CoreObject I,Serialization.SerializationManager s)
{
if (Game1.player.isInventoryFull() == false)
{
Game1.player.addItemToInventoryBool(I, false);
s.trackedObjectList.Remove(I);
return true;
}
else
{
Random random = new Random(129);
int i = random.Next();
i = i % 4;
Vector2 v2 = new Vector2(Game1.player.getTileX() * Game1.tileSize, Game1.player.getTileY() * Game1.tileSize);
Game1.createItemDebris(I, v2, i);
return false;
}
}
public static Microsoft.Xna.Framework.Rectangle parseRectFromJson(string s)
{
s = s.Replace('{', ' ');
s = s.Replace('}', ' ');
s = s.Replace('^', ' ');
s = s.Replace(':', ' ');
string[] parsed = s.Split(' ');
foreach (var v in parsed)
{
//Log.AsyncY(v);
}
return new Microsoft.Xna.Framework.Rectangle(Convert.ToInt32(parsed[2]), Convert.ToInt32(parsed[4]), Convert.ToInt32(parsed[6]), Convert.ToInt32(parsed[8]));
}
/// <summary>
/// Add an object to a list fo items.
/// </summary>
/// <param name="inventory"></param>
/// <param name="I"></param>
/// <returns></returns>
public static bool addItemToOtherInventory(List<Item> inventory, Item I)
{
if (I == null) return false;
if (isInventoryFull(inventory) == false)
{
if (inventory == null)
{
return false;
}
if (inventory.Count == 0)
{
inventory.Add(I);
return true;
}
for (int i = 0; i < inventory.Capacity; i++)
{
// Log.AsyncC("OK????");
foreach (var v in inventory)
{
if (inventory.Count == 0)
{
addItemToOtherInventory(inventory, I);
return true;
}
if (v == null) continue;
if (v.canStackWith(I))
{
v.addToStack(I.getStack());
return true;
}
}
}
inventory.Add(I);
return true;
}
else
{
return false;
}
}
/// <summary>
/// Add an object to a netList of items.
/// </summary>
/// <param name="inventory"></param>
/// <param name="I"></param>
/// <returns></returns>
public static bool addItemToOtherInventory(NetObjectList<Item> inventory, Item I)
{
if (I == null) return false;
if (isInventoryFull(inventory) == false)
{
if (inventory == null)
{
return false;
}
if (inventory.Count == 0)
{
inventory.Add(I);
return true;
}
for (int i = 0; i < inventory.Capacity; i++)
{
// Log.AsyncC("OK????");
foreach (var v in inventory)
{
if (inventory.Count == 0)
{
addItemToOtherInventory(inventory, I);
return true;
}
if (v == null) continue;
if (v.canStackWith(I))
{
v.addToStack(I.getStack());
return true;
}
}
}
inventory.Add(I);
return true;
}
else
{
return false;
}
}
/// <summary>
/// Checks whether or not the inventory list is full of items.
/// </summary>
/// <param name="inventory"></param>
/// <param name="logInfo"></param>
/// <returns></returns>
public static bool isInventoryFull(List<Item> inventory, bool logInfo = false)
{
if (logInfo)
{
ModCore.ModMonitor.Log("size " + inventory.Count);
ModCore.ModMonitor.Log("max " + inventory.Capacity);
}
if (inventory.Count == inventory.Capacity) return true;
else return false;
}
/// <summary>
/// Checks whether or not the net inventory list is full of items.
/// </summary>
/// <param name="inventory"></param>
/// <param name="logInfo"></param>
/// <returns></returns>
public static bool isInventoryFull(NetObjectList<Item> inventory, bool logInfo = false)
{
if (logInfo)
{
ModCore.ModMonitor.Log("size " + inventory.Count);
ModCore.ModMonitor.Log("max " + inventory.Capacity);
}
if (inventory.Count == inventory.Capacity) return true;
else return false;
}
public static bool isWithinRange(int tileLength,Vector2 positionToCheck)
{
Vector2 v = Game1.player.getTileLocation();
if (v.X < positionToCheck.X - tileLength || v.X > positionToCheck.X + tileLength) return false;
if (v.Y < positionToCheck.Y - tileLength || v.Y > positionToCheck.Y + tileLength) return false;
return true;
}
public static bool isWithinDirectionRange(int direction,int range, Vector2 positionToCheck)
{
Vector2 v = Game1.player.getTileLocation();
if (direction==3 && (v.X >= positionToCheck.X - range)) return true; //face left
if (direction==1 && (v.X <= positionToCheck.X + range)) return true; //face right
if (direction==0 && (v.Y <= positionToCheck.Y + range)) return true; //face up
if (direction==2 && (v.Y >= positionToCheck.Y - range)) return true; //face down
return true;
}
/// <summary>
/// Draws the green mouse cursor plus sign.
/// </summary>
public static void drawGreenPlus()
{
try
{
Game1.spriteBatch.Draw(Game1.mouseCursors, new Vector2(Game1.getMouseX() + 34, Game1.getMouseY() + 34), new Microsoft.Xna.Framework.Rectangle(0, 410, 17, 17), Color.White, 0, new Vector2(0, 0), 2f, Microsoft.Xna.Framework.Graphics.SpriteEffects.None, 0);
}
catch(Exception e)
{
e.ToString();
}
}
public static StardewValley.Object checkRadiusForObject(int radius, string name)
{
for (int x = -radius; x <= radius; x++)
{
for (int y = -radius; y <= radius; y++)
{
bool f = Game1.player.currentLocation.isObjectAt((Game1.player.getTileX() + x) * Game1.tileSize, (Game1.player.getTileY() + y) * Game1.tileSize);
if (f == false) continue;
StardewValley.Object obj = Game1.player.currentLocation.getObjectAt((Game1.player.getTileX() + x) * Game1.tileSize, (Game1.player.getTileY() + y) * Game1.tileSize);
if (obj == null) continue;
if (obj.name == name)
{
return obj;
}
}
}
return null;
}
public static StardewValley.Object checkCardinalForObject(string name)
{
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
if (x == -1 && y == -1) continue; //upper left
if (x == -1 && y == 1) continue; //bottom left
if (x == 1 && y == -1) continue; //upper right
if (x == 1 && y == 1) continue; //bottom right
bool f = Game1.player.currentLocation.isObjectAt((Game1.player.getTileX() + x) * Game1.tileSize, (Game1.player.getTileY() + y) * Game1.tileSize);
if (f == false) continue;
StardewValley.Object obj = Game1.player.currentLocation.getObjectAt((Game1.player.getTileX() + x) * Game1.tileSize, (Game1.player.getTileY() + y) * Game1.tileSize);
if (obj == null) continue;
if (obj.name == name)
{
return obj;
}
}
}
return null;
}
public static void faceDirectionTowardsSomething(Vector2 tileLocation)
{
if (tileLocation.X < Game1.player.getTileX())
{
Game1.player.faceDirection(3);
}
else if (tileLocation.X > Game1.player.getTileX())
{
Game1.player.faceDirection(1);
}
else if (tileLocation.Y < Game1.player.getTileY())
{
Game1.player.faceDirection(0);
}
else if (tileLocation.Y > Game1.player.getTileY())
{
Game1.player.faceDirection(2);
}
}
/// <summary>
/// Checks if a game location contains an object with the exact name passed in.
/// </summary>
/// <param name="location">The location to check.</param>
/// <param name="name">The name of the object to check.</param>
/// <returns></returns>
public static bool doesLocationContainObject(GameLocation location, string name)
{
foreach (KeyValuePair<Vector2, StardewValley.Object> v in location.objects.Pairs)
{
if (name == v.Value.name) return true;
}
return false;
}
public static KeyValuePair<Vector2,TerrainFeature> checkRadiusForTerrainFeature(int radius, Type terrainType)
{
for (int x = -radius; x <= radius; x++)
{
for (int y = -radius; y <= radius; y++)
{
Vector2 pos = new Vector2((Game1.player.getTileX() + x), (Game1.player.getTileY() + y));
bool f = Game1.player.currentLocation.isTerrainFeatureAt((int)pos.X,(int)pos.Y);
if (f == false) continue;
TerrainFeature t = Game1.player.currentLocation.terrainFeatures[pos]; //((Game1.player.getTileX() + x) * Game1.tileSize, (Game1.player.getTileY() + y) * Game1.tileSize);
if (t == null) continue;
if (t.GetType() == terrainType)
{
return new KeyValuePair<Vector2, TerrainFeature> (pos,t);
}
}
}
return new KeyValuePair<Vector2, TerrainFeature>(new Vector2(),null);
}
public static KeyValuePair<Vector2, TerrainFeature> checkCardinalForTerrainFeature(Type terrainType)
{
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
if (x == -1 && y == -1) continue; //upper left
if (x == -1 && y == 1) continue; //bottom left
if (x == 1 && y == -1) continue; //upper right
if (x == 1 && y == 1) continue; //bottom right
Vector2 pos = new Vector2((Game1.player.getTileX() + x), (Game1.player.getTileY() + y));
bool f = Game1.player.currentLocation.isTerrainFeatureAt((int)pos.X, (int)pos.Y);
if (f == false) continue;
TerrainFeature t = Game1.player.currentLocation.terrainFeatures[pos]; //((Game1.player.getTileX() + x) * Game1.tileSize, (Game1.player.getTileY() + y) * Game1.tileSize);
if (t == null) continue;
if (t.GetType() == terrainType)
{
return new KeyValuePair<Vector2, TerrainFeature>(pos, t);
}
}
}
return new KeyValuePair<Vector2, TerrainFeature>(new Vector2(), null);
}
/// <summary>
/// Checks if the game location has this terrain feature.
/// </summary>
/// <param name="location">The game location to check.</param>
/// <param name="terrain">The terrain feature type to check if it exists at said location.</param>
/// <returns></returns>
public static bool doesLocationContainTerrainFeature(GameLocation location, Type terrain)
{
foreach (KeyValuePair<Vector2, StardewValley.TerrainFeatures.TerrainFeature> v in location.terrainFeatures.Pairs)
{
if (terrain == v.Value.GetType()) return true;
}
return false;
}
/// <summary>
/// Get an item from the player's inventory.
/// </summary>
/// <param name="index">The index in the player's inventory of the item.</param>
/// <returns></returns>
public static Item getItemFromInventory(int index)
{
foreach(var v in Game1.player.Items)
{
if (v.ParentSheetIndex == index) return v;
}
return null;
}
/// <summary>
/// Get an item from the player's inventory.
/// </summary>
/// <param name="name">The name of the item in the player's inventory</param>
/// <returns></returns>
public static Item getItemFromInventory(string name)
{
foreach (var v in Game1.player.Items)
{
if (v.Name == name) return v;
}
return null;
}
}
}