Skip to content

Commit

Permalink
Initial setup work.
Browse files Browse the repository at this point in the history
  • Loading branch information
MrPurple6411 committed Jan 13, 2023
1 parent 571b468 commit 1df6689
Show file tree
Hide file tree
Showing 38 changed files with 1,897 additions and 113 deletions.
4 changes: 3 additions & 1 deletion Example mod/Example mod.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@
<HintPath>$(Dependencies)\UnityEngine.UI.dll</HintPath>
<Private>False</Private>
</Reference>
<ProjectReference Include="..\SMLHelper\SMLHelper.csproj" />
<ProjectReference Include="..\SMLHelper\SMLHelper.csproj">
<Private>False</Private>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="BepInEx.Core" Version="5.4.21" />
Expand Down
12 changes: 12 additions & 0 deletions Example mod/Mod.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@
using BepInEx;
using BepInEx.Logging;
using SMLHelper.Utility;
using SMLHelper.DependencyInjection;

[BepInPlugin(GUID, MODNAME, VERSION)]
[BepInDependency("com.ahk1221.smlhelper", BepInDependency.DependencyFlags.HardDependency)]
public class ExampleMod: BaseUnityPlugin
{
private const string
Expand All @@ -35,6 +37,16 @@ internal class SaveData : SaveDataCache

public void Awake()
{
// Create
var builder = PrefabManager.CreateBuilder(this);
// Add
builder.Assets.AddCustomPrefab(new NuclearBattery());
builder.Assets.AddService<IGreeting, SayHi>();
// Run
builder.Build();
// Get Service
builder.GetService<IGreeting>().Greetings();

LogSource = base.Logger;

/// Here, we are setting up a instance of <see cref="Config"/>, which will automatically generate an
Expand Down
46 changes: 46 additions & 0 deletions Example mod/NuclearBatteryExample.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
namespace SMLHelper.Examples;

using System.Collections;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using SMLHelper.API;
using SMLHelper.Assets;
using SMLHelper.Assets.PrefabTemplates;
using SMLHelper.DependencyInjection;
using SMLHelper.Handlers;
using UnityEngine;

public class NuclearBattery : CustomPrefab
{
public override PrefabInfo PrefabInfo { get; protected set; } = PrefabInfo.WithTechType("NuclearBattery", "Nuclear Battery", "Nuclear Battery that makes me go yes")
.WithIcon(SpriteManager.Get(TechType.PrecursorIonBattery));

[InjectionSetup]
private void Setup(ManualLogSource logger)
{
if (Chainloader.PluginInfos.ContainsKey("DecorationsMod"))
{
logger.LogDebug("Found Decorations mod. Adding compatibility patch");
CraftDataHandler.SetEquipmentType(PrefabInfo.TechType, EquipmentType.Hand);
CraftDataHandler.SetQuickSlotType(PrefabInfo.TechType, QuickSlotType.Selectable);
}

logger.LogDebug($"{nameof(NuclearBattery)} Patched.");
}

public override IEnumerator GetGameObjectAsync(IOut<GameObject> gameObject)
{
var battery = new EnergySourceTemplate(69420)
{
ModelData = new CBModelData
{
UseIonModelsAsBase = true
}
};

var task = new TaskResult<GameObject>();
yield return battery.GetPrefabAsync(task);

gameObject.Set(task.Get());
}
}
42 changes: 42 additions & 0 deletions SMLHelper/API/CBModelData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@

using UnityEngine;

namespace SMLHelper.API;

public class CBModelData
{
/// <summary>
/// The custom skin for the item.<br/>
/// This property is optional and will default to the standard texture for batteries or power cells.
/// </summary>
public Texture2D CustomTexture { get; set; }

/// <summary>
/// The custom bump texture for the item.<br/>
/// This property is optional and will default to the standard bump texture for batteries or power cells.
/// </summary>
public Texture2D CustomNormalMap { get; set; }

/// <summary>
/// The custom Spec Texture for the item.<br/>
/// This property is optional and will default to the standard spec texture for batteries or power cells.
/// </summary>
public Texture2D CustomSpecMap { get; set; }

/// <summary>
/// The custom lighting texture for the item.<br/>
/// This property is optional and will default to the standard illum texture for batteries or power cells.
/// </summary>
public Texture2D CustomIllumMap { get; set; }

/// <summary>
/// The custom lighting strength for the item.<br/>
/// This property is will default to 1.0f if the <see cref="CustomIllumMap"/> is set but will use the default value for batteries or power cells if no <see cref="CustomIllumMap"/> is set.
/// </summary>
public float CustomIllumStrength { get; set; } = 1.0f;

/// <summary>
/// Change this value if you want your item to use the Ion battery or powercell model as its base.
/// </summary>
public bool UseIonModelsAsBase { get; set; } = false;
}
15 changes: 15 additions & 0 deletions SMLHelper/API/CbBattery.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace SMLHelper.API;

/// <summary>
/// A class that holds all the necessary elements of a custom battery to be patched.
/// </summary>
public class CbBattery : CbItem
{
/// <summary>
/// Patches the data of this instance into a new custom Battery.
/// </summary>
public void Patch()
{
Patch(ItemTypes.Battery);
}
}
84 changes: 84 additions & 0 deletions SMLHelper/API/CbDatabase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
namespace SMLHelper.API;

using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using UnityEngine;
using Assets;
using System.Linq;

internal static class CbDatabase
{
public const string BatteryCraftTab = "BatteryTab";
public const string PowCellCraftTab = "PowCellTab";
public const string ElecCraftTab = "Electronics";
public const string ResCraftTab = "Resources";

public static readonly string[] BatteryCraftPath = new[] { ResCraftTab, BatteryCraftTab };
public static readonly string[] PowCellCraftPath = new[] { ResCraftTab, PowCellCraftTab };

public static string ExecutingFolder { get; } = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

public static List<CbCore> BatteryItems { get; } = new List<CbCore>();
public static List<CbCore> PowerCellItems { get; } = new List<CbCore>();

public static Dictionary<TechType, CBModelData> BatteryModels { get; } = new Dictionary<TechType, CBModelData>();
public static Dictionary<TechType, CBModelData> PowerCellModels { get; } = new Dictionary<TechType, CBModelData>();

public static HashSet<TechType> TrackItems { get; } = new HashSet<TechType>();

private static bool? _placeBatteriesFeatureEnabled = null;

public static bool PlaceBatteriesFeatureEnabled
{
get
{
if(_placeBatteriesFeatureEnabled == null || !_placeBatteriesFeatureEnabled.HasValue)
{
var decorationsMod = BepInEx.Bootstrap.Chainloader.PluginInfos.Values.Where((x) => x.Metadata.Name == "DecorationsMod" && x.Instance.enabled).FirstOrFallback(null);
Assembly decorationsModAssembly = null;
if(decorationsMod != null)
{
decorationsModAssembly = AppDomain.CurrentDomain.GetAssemblies().Where(x => x.Location == decorationsMod.Location).FirstOrFallback(decorationsModAssembly);
}
if(decorationsModAssembly != null)
{
Type decorationsModConfig = decorationsModAssembly.GetType("DecorationsMod.ConfigSwitcher", false);
if(decorationsModConfig != null)
{
FieldInfo enablePlaceBatteriesField = decorationsModConfig.GetField("EnablePlaceBatteries", BindingFlags.Public | BindingFlags.Static);
if(enablePlaceBatteriesField != null)
_placeBatteriesFeatureEnabled = (bool)enablePlaceBatteriesField.GetValue(null);
}
}
}
return _placeBatteriesFeatureEnabled != null && _placeBatteriesFeatureEnabled.Value;
}
}

private static GameObject _precursorionbattery;
private static GameObject _precursorionpowercell;
private static GameObject _battery;
private static GameObject _powercell;

public static GameObject IonBattery()
{
return _precursorionbattery ??= Resources.Load<GameObject>("worldentities/tools/precursorionbattery");
}

public static GameObject IonPowerCell()
{
return _precursorionpowercell ??= Resources.Load<GameObject>("worldentities/tools/precursorionpowercell");
}

public static GameObject Battery()
{
return _battery ??= Resources.Load<GameObject>("worldentities/tools/battery");
}

public static GameObject PowerCell()
{
return _powercell ??= Resources.Load<GameObject>("worldentities/tools/powercell");
}
}
136 changes: 136 additions & 0 deletions SMLHelper/API/CbItem.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
namespace SMLHelper.API;

using System;
using System.Collections.Generic;
using Assets;
using SMLHelper.Utility;
using UnityEngine;
#if SUBNAUTICA
using Sprite = Atlas.Sprite;
#endif

/// <summary>
/// A class that holds all the necessary elements of a custom battery or power cell.
/// </summary>
public abstract class CbItem
{
/// <summary>
/// The full capacity of energy of the item.
/// </summary>
public int EnergyCapacity { get; set; } = -1;

/// <summary>
/// The internal ID for the custom item.
/// </summary>
public string ID { get; set; }

/// <summary>
/// The display name of the custom item shown in-game.
/// </summary>
public string Name { get; set; }

/// <summary>
/// The flavor text for the custom item shown in-game when viewing it from a PDA screen.
/// </summary>
public string FlavorText { get; set; }

/// <summary>
/// The materials required to craft the item.<para/>
/// If you want multiple copies of the same material, include multiple entries of that <see cref="TechType"/>.<para/>
/// If this list is empty, a default recipe of a single <see cref="TechType.Titanium"/> will be applied instead.
/// </summary>
public List<TechType> CraftingMaterials { get; set; } = new List<TechType>();

/// <summary>
/// What item must be obtained, scanned, or built to unlock the battery and power cell.<para/>
/// By default, the item will be unlocked at the start of the game.
/// </summary>
public TechType UnlocksWith { get; set; } = TechType.None;

/// <summary>
/// The custom sprite for the item's icon.<br/>
/// This value is optional and will default to the standard icon for batteries or power cells.
/// </summary>
public Sprite CustomIcon { get; set; }

/// <summary>
/// The custom data that will make up your batteries model.<br/>
/// This value is optional and will default to the standard model for batteries or power cells if left as null.
/// </summary>
public CBModelData CBModelData { get; set; }

/// <summary>
/// Override this optional value if you want to make changes to the your item's <see cref="GameObject"/> as it is being spawned from prefab.<br/>
/// Use this if you want to add or modify components of your item.
/// </summary>
/// <param name="gameObject">The item's gameobject.</param>
public Action<GameObject> EnhanceGameObject { get; set; }

/// <summary>
/// Override this to <c>false</c> if you do not want CustomBatteries to manage addeding of this item to the Fabricator crafting tree.<br/>
/// This property is <c>true</c> by default.
/// </summary>
public bool AddToFabricator { get; set; } = true;

private TechType _techType = TechType.None;

/// <summary>
/// After <see cref="CbBattery.Patch"/> method is invoked, this property will contain the <see cref="TechType"/> value for this item.
/// </summary>
public TechType TechType
{
get
{
if (_techType == TechType.None)
{
throw new InvalidOperationException("The Patch method must be called before you can access the TechType value.");
}

return _techType;
}
}

internal void Patch(ItemTypes itemType)
{
string name = this.GetType().Assembly.GetName().Name;
InternalLogger.Info($"Received Custom {itemType} pack from '{name}'");

// Check for required data
string errors = string.Empty;

if (this.EnergyCapacity <= 0)
errors += "Missing required data 'EnergyCapacity" + Environment.NewLine;

if (string.IsNullOrEmpty(this.ID))
errors += "Missing required data 'ID'" + Environment.NewLine;

if (string.IsNullOrEmpty(this.Name))
errors += "Missing required data 'Name'" + Environment.NewLine;

if (string.IsNullOrEmpty(this.FlavorText))
errors += "Missing required data 'FlavorText'";

if (!string.IsNullOrEmpty(errors))
{
string msg = "Unable to patch:" + Environment.NewLine + errors;
InternalLogger.Error(msg);
throw new InvalidOperationException(msg);
}

// Prepare
var item = new CustomItem(this, itemType)
{
PluginPackName = name,
FriendlyName = this.Name,
Description = this.FlavorText,
PowerCapacity = this.EnergyCapacity,
RequiredForUnlock = this.UnlocksWith,
Parts = this.CraftingMaterials
};

// Patch
item.Patch();

_techType = item.TechType;
}
}
15 changes: 15 additions & 0 deletions SMLHelper/API/CbPowerCell.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace SMLHelper.API;

/// <summary>
/// A class that holds all the necessary elements of a custom power cell to be patched.
/// </summary>
public class CbPowerCell : CbItem
{
/// <summary>
/// Patches the data of this instance into a new custom Power Cell.
/// </summary>
public void Patch()
{
Patch(ItemTypes.PowerCell);
}
}
Loading

0 comments on commit 1df6689

Please sign in to comment.