Skip to content

Commit

Permalink
2.0 update! Configs, commands, yay!
Browse files Browse the repository at this point in the history
  • Loading branch information
gardenappl committed Aug 7, 2018
1 parent bf9703f commit da9bbf8
Show file tree
Hide file tree
Showing 10 changed files with 516 additions and 53 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
bin
obj
obj
*.sln
*.vs
228 changes: 228 additions & 0 deletions Config.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Terraria;
using Terraria.ID;
using Terraria.Localization;
using Terraria.ModLoader;

namespace OmniSwing
{
//so I spent like half a day coding this
//tML says they'll add ModConfig soon, what do I do?
static class Config
{
public static List<int> BlacklistedItemIDs = new List<int>();
public static List<int> WhitelistedItemIDs = new List<int>();

static List<string> ErrorLines = new List<string>();

static string ConfigFolderPath = Path.Combine(Main.SavePath, "Mod Configs");
static string ConfigPath = Path.Combine(ConfigFolderPath, "OmniSwing.txt");

public static void Load()
{
if(!Directory.Exists(ConfigFolderPath))
{
OmniSwing.Log("Mod Config directory not found, creating...");
Directory.CreateDirectory(ConfigFolderPath);
}

if(File.Exists(ConfigPath))
{
Reset();
ReadConfig();
}
else
{
OmniSwing.Log("Config file not found, creating default...");
SetDefaults();
SaveConfig();
}
}

static void ReadConfig()
{
int lineNumber = 0;
using(var reader = new StreamReader(ConfigPath))
{
while(!reader.EndOfStream)
{
lineNumber++;
string line = reader.ReadLine().Split('#')[0].Trim();
if(line.Length == 0)
continue;

if(line[0] == '!')
{
line = line.Remove(0, 1).Trim();
ParseConfigLine(line, lineNumber, WhitelistedItemIDs);
}
else
{
ParseConfigLine(line, lineNumber, BlacklistedItemIDs);
}
}
}
}

static void ParseConfigLine(string line, int lineNumber, List<int> idList)
{
int id = 0;
if(Int32.TryParse(line, out id))
{
if(id <= 0 || id >= ItemID.Count)
throw new Exception(id + " is not a valid Vanilla Item ID!");
idList.Add(id);
}
else
{
string[] splitLine = line.Split(':');
if(splitLine.Length < 2)
throw new Exception("Wrong config file format at line " + lineNumber);

var mod = ModLoader.GetMod(splitLine[0]);
if(mod == null)
{
ErrorLines.Add(line);
return;
}
id = mod.ItemType(splitLine[1]);
if(id == 0)
{
ErrorLines.Add(line);
return;
}
idList.Add(id);
}
}

public static void SetDefaults()
{
Reset();
BlacklistedItemIDs = new List<int>(new int[]
{
ItemID.MagicDagger,
ItemID.PhoenixBlaster
});
}

static void Reset()
{
ErrorLines.Clear();
BlacklistedItemIDs.Clear();
WhitelistedItemIDs.Clear();
}

public static void SaveConfig()
{
File.WriteAllLines(ConfigPath, new string[]
{
"# This is the OmniSwing configuration file. Please use the /omniSwing command to modify this.",
"# (or edit this manually if you know what you're doing)",
"# Each line is a new blacklisted item.",
"# If it's a Vanilla item, add the item ID directly.",
"# If it's a modded item, specify its name in this format:",
"# InternalModName:InternalItemName",
"# (use WMITF's Internal Name button to see the internal names)",
"# Any item that starts with an exclamation mark ! will auto-swing even if it's not a weapon (whitelist)",
"# Anything that comes after a # sign will be ignored (like these comments)",
});
foreach(int id in BlacklistedItemIDs)
{
if(id < ItemID.Count)
{
File.AppendAllLines(ConfigPath, new string[] { id + " # " + Lang.GetItemNameValue(id) });
}
else if(id < ItemLoader.ItemCount)
{
var item = new Item();
item.SetDefaults();
if(item.modItem != null)
{
string modName = item.modItem.mod.Name;
string itemName = item.modItem.Name;
File.AppendAllLines(ConfigPath, new string[] { modName + ':' + itemName + " # " + Lang.GetItemNameValue(id) });
}
}
}
foreach(int id in WhitelistedItemIDs)
{
if(id < ItemID.Count)
{
File.AppendAllLines(ConfigPath, new string[] { "! " + id + " # " + Lang.GetItemNameValue(id) });
}
else if(id < ItemLoader.ItemCount)
{
var item = new Item();
item.SetDefaults();
if(item.modItem != null)
{
string modName = item.modItem.mod.Name;
string itemName = item.modItem.Name;
File.AppendAllLines(ConfigPath, new string[] { "! " + modName + ':' + itemName + " # " + Lang.GetItemNameValue(id) });
}
}
}
}

public static void PrintErrors()
{
if(ErrorLines.Count == 0)
return;
Main.NewText(Language.GetTextValue("Mods.OmniSwing.ConfigLineError1"), Colors.RarityRed);
Main.NewText(Language.GetTextValue("Mods.OmniSwing.ConfigLineError2"), Colors.RarityRed);
Main.NewText(Language.GetTextValue("Mods.OmniSwing.ConfigLineError3"), Colors.RarityRed);
foreach(var line in ErrorLines)
Main.NewText(line, Colors.RarityRed);
Main.NewText(Language.GetTextValue("Mods.OmniSwing.ConfigLineError4"), Colors.RarityRed);
}

public class MultiplayerSyncWorld : ModWorld
{
public override void NetSend(BinaryWriter writer)
{
writer.Write(BlacklistedItemIDs.Count);
foreach(int id in BlacklistedItemIDs)
writer.Write(id);

writer.Write(WhitelistedItemIDs.Count);
foreach(int id in WhitelistedItemIDs)
writer.Write(id);
}

public override void NetReceive(BinaryReader reader)
{
ErrorLines.Clear();

int count = reader.ReadInt32();
BlacklistedItemIDs = new List<int>(count);
for(int i = 0; i < count; i++)
BlacklistedItemIDs.Add(reader.ReadInt32());

count = reader.ReadInt32();
WhitelistedItemIDs = new List<int>(count);
for(int i = 0; i < count; i++)
WhitelistedItemIDs.Add(reader.ReadInt32());
}
}

public class MultiplayerSyncPlayer : ModPlayer
{
public override void OnEnterWorld(Player player)
{
if(ErrorLines.Count > 0)
{
PrintErrors();
}
}

public override void PlayerDisconnect(Player player)
{
Config.Load();
}
}
}
}
12 changes: 12 additions & 0 deletions Localization/en-US.lang
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
ConfigLineError1=[OmniSwing configuration]
ConfigLineError2=There was an error while loading the OmniSwing configuration file.
ConfigLineError3=These items weren't loaded:
ConfigLineError4=Either the mods are disabled, or the names are incorrect.

CommandDescription=Allows disabling or enabling OmniSwing on an item you hold in your hand.
CommandWhitelistAdded={0} added to OmniSwing whitelist.
CommandWhitelistRemoved={0} removed from OmniSwing whitelist.
CommandBlacklistAdded={0} added to OmniSwing blacklist.
CommandBlacklistRemoved={0} removed from OmniSwing blacklist.
CommandUsage=You're not holding any item!
CommandServerOnly=This command can only be executed by the server owner.
12 changes: 12 additions & 0 deletions Localization/ru-RU.lang
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
ConfigLineError1=[конфигурация OmniSwing]
ConfigLineError2=Во время загрузки конфигурации OmniSwing произошла ошибка.
ConfigLineError3=Эти предметы не были найдены в игре:
ConfigLineError4=Либо эти моды выключены, либо вы неправильно указали имена предметов.

CommandDescription=Позволяет включать/выключать авто-использование предмета, который вы держите руке.
CommandWhitelistAdded=OmniSwing включен для предмета: {0}
CommandWhitelistRemoved=OmniSwing выключен для предмета: {0}
CommandBlacklistAdded=OmniSwing выключен для предмета: {0}
CommandBlacklistRemoved=OmniSwing включен для предмета: {0}
CommandUsage=У вас в руке нет предмета!
CommandServerOnly=Эту команду может исользовать только владелец сервера.
105 changes: 60 additions & 45 deletions OmniSwing.cs
Original file line number Diff line number Diff line change
@@ -1,68 +1,83 @@

using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Terraria;
using Terraria.ID;
using Terraria.Localization;
using Terraria.ModLoader;

namespace OmniSwing
{
public class OmniSwing : Mod
{
//Hamstar's Mod Helpers integration
public override void PostSetupContent()
{
Config.Load();
}

public override void HandlePacket(BinaryReader reader, int whoAmI)
{
if(Main.netMode == NetmodeID.Server)
return;

var messageType = (MessageType)reader.ReadByte();
int itemID = reader.ReadInt32();
switch(messageType)
{
case MessageType.BlacklistItemAdd:
Config.BlacklistedItemIDs.Add(itemID);
break;
case MessageType.WhitelistItemAdd:
Config.WhitelistedItemIDs.Add(itemID);
break;
case MessageType.BlacklistItemRemove:
Config.BlacklistedItemIDs.Remove(itemID);
break;
case MessageType.WhitelistItemRemove:
Config.WhitelistedItemIDs.Add(itemID);
break;
}
}

public enum MessageType : byte
{
BlacklistItemAdd = 0,
WhitelistItemAdd = 1,
BlacklistItemRemove = 2,
WhitelistItemRemove = 3
}

#region Hamstar's Mod Helpers integration

public static string GithubUserName { get { return "goldenapple3"; } }
public static string GithubProjectName { get { return "OmniSwing"; } }
}

class SwingGlobalItem : GlobalItem
{
public override void SetDefaults(Item item)

public static string ConfigFileRelativePath { get { return "Mod Configs/OmniSwing.txt"; } }

public static void ReloadConfigFromFile()
{
if(ShouldAutoSwing(item))
item.autoReuse = true;
Config.Load();
Config.PrintErrors();
}
public override bool CanUseItem(Item item, Player player)

public static void ResetConfigFromDefaults()
{
if(ShouldAutoSwing(item))
item.autoReuse = true;
return base.CanUseItem(item, player);
Config.SetDefaults();
Config.SaveConfig();
}

static bool ShouldAutoSwing(Item item)

#endregion

public static void Log(object message)
{
try
{
if(item.damage <= 0 || item.summon || item.sentry)
return false;

if(item.shoot > 0)
{
var projectile = new Projectile();
projectile.SetDefaults(item.shoot);
//Magic Missile-type projectiles get buggy with auto-swing
return projectile.aiStyle != 9;
}
return true;
}
catch(NullReferenceException e)
{
return false;
}
ErrorLogger.Log(String.Format("[OmniSwing][{0}] {1}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"), message));
}
}

//spear fix by CrimsHallowHero
class SwingGlobalProjectile : GlobalProjectile
{
public override void AI(Projectile projectile)

public static void Log(string message, params object[] formatData)
{
if((projectile.aiStyle == 19 || projectile.aiStyle == 699) && projectile.timeLeft > Main.player[projectile.owner].itemAnimation)
{
projectile.timeLeft = Main.player[projectile.owner].itemAnimation;
projectile.netUpdate = true;
}
ErrorLogger.Log(String.Format("[OmniSwing][{0}] {1}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"), String.Format(message, formatData)));
}
}
}
}
Loading

0 comments on commit da9bbf8

Please sign in to comment.