A stable modding interface between Techblox and mods https://mod.exmods.org/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

268 lines
10KB

  1. using System;
  2. using System.Linq;
  3. using System.Reflection;
  4. using HarmonyLib;
  5. // test
  6. using Svelto.ECS;
  7. using RobocraftX.Blocks;
  8. using RobocraftX.Common;
  9. using RobocraftX.SimulationModeState;
  10. using RobocraftX.FrontEnd;
  11. using Unity.Mathematics;
  12. using GamecraftModdingAPI.Commands;
  13. using GamecraftModdingAPI.Events;
  14. using GamecraftModdingAPI.Utility;
  15. using GamecraftModdingAPI.Blocks;
  16. using GamecraftModdingAPI.Players;
  17. namespace GamecraftModdingAPI.Tests
  18. {
  19. // unused by design
  20. /// <summary>
  21. /// Modding API implemented as a standalone IPA Plugin.
  22. /// Ideally, GamecraftModdingAPI should be loaded by another mod; not itself
  23. /// </summary>
  24. public class GamecraftModdingAPIPluginTest
  25. #if DEBUG
  26. : IllusionPlugin.IEnhancedPlugin
  27. #endif
  28. {
  29. private static Harmony harmony { get; set; }
  30. public string[] Filter { get; } = new string[] { "Gamecraft", "GamecraftPreview" };
  31. public string Name { get; } = Assembly.GetExecutingAssembly().GetName().Name;
  32. public string Version { get; } = Assembly.GetExecutingAssembly().GetName().Version.ToString();
  33. public string HarmonyID { get; } = "org.git.exmods.modtainers.gamecraftmoddingapi";
  34. public void OnApplicationQuit()
  35. {
  36. GamecraftModdingAPI.Main.Shutdown();
  37. }
  38. public void OnApplicationStart()
  39. {
  40. FileLog.Reset();
  41. Harmony.DEBUG = true;
  42. GamecraftModdingAPI.Main.Init();
  43. Logging.MetaDebugLog($"Version group id {(uint)ApiExclusiveGroups.versionGroup}");
  44. // in case Steam is not installed/running
  45. // this will crash the game slightly later during startup
  46. //SteamInitPatch.ForcePassSteamCheck = true;
  47. // in case running in a VM
  48. //MinimumSpecsCheckPatch.ForcePassMinimumSpecCheck = true;
  49. // disable some Gamecraft analytics
  50. //AnalyticsDisablerPatch.DisableAnalytics = true;
  51. // disable background music
  52. Logging.MetaDebugLog("Audio Mixers: "+string.Join(",", AudioTools.GetMixers()));
  53. //AudioTools.SetVolume(0.0f, "Music"); // The game now sets this from settings again after this is called :(
  54. //Utility.VersionTracking.Enable();//(very) unstable
  55. // debug/test handlers
  56. HandlerBuilder.Builder()
  57. .Name("appinit API debug")
  58. .Handle(EventType.ApplicationInitialized)
  59. .OnActivation(() => { Logging.Log("App Inited event!"); })
  60. .Build();
  61. HandlerBuilder.Builder("menuact API debug")
  62. .Handle(EventType.Menu)
  63. .OnActivation(() => { Logging.Log("Menu Activated event!"); })
  64. .OnDestruction(() => { Logging.Log("Menu Destroyed event!"); })
  65. .Build();
  66. HandlerBuilder.Builder("menuswitch API debug")
  67. .Handle(EventType.MenuSwitchedTo)
  68. .OnActivation(() => { Logging.Log("Menu Switched To event!"); })
  69. .Build();
  70. HandlerBuilder.Builder("gameact API debug")
  71. .Handle(EventType.Menu)
  72. .OnActivation(() => { Logging.Log("Game Activated event!"); })
  73. .OnDestruction(() => { Logging.Log("Game Destroyed event!"); })
  74. .Build();
  75. HandlerBuilder.Builder("gamerel API debug")
  76. .Handle(EventType.GameReloaded)
  77. .OnActivation(() => { Logging.Log("Game Reloaded event!"); })
  78. .Build();
  79. HandlerBuilder.Builder("gameswitch API debug")
  80. .Handle(EventType.GameSwitchedTo)
  81. .OnActivation(() => { Logging.Log("Game Switched To event!"); })
  82. .Build();
  83. HandlerBuilder.Builder("simulationswitch API debug")
  84. .Handle(EventType.SimulationSwitchedTo)
  85. .OnActivation(() => { Logging.Log("Game Mode Simulation Switched To event!"); })
  86. .Build();
  87. HandlerBuilder.Builder("buildswitch API debug")
  88. .Handle(EventType.BuildSwitchedTo)
  89. .OnActivation(() => { Logging.Log("Game Mode Build Switched To event!"); })
  90. .Build();
  91. HandlerBuilder.Builder("menu activated API error thrower test")
  92. .Handle(EventType.Menu)
  93. .OnActivation(() => { throw new Exception("Event Handler always throws an exception!"); })
  94. .Build();
  95. // debug/test commands
  96. if (Dependency.Hell("ExtraCommands"))
  97. {
  98. CommandBuilder.Builder()
  99. .Name("Exit")
  100. .Description("Close Gamecraft immediately, without any prompts")
  101. .Action(() => { UnityEngine.Application.Quit(); })
  102. .Build();
  103. CommandBuilder.Builder()
  104. .Name("SetFOV")
  105. .Description("Set the player camera's field of view")
  106. .Action((float d) => { UnityEngine.Camera.main.fieldOfView = d; })
  107. .Build();
  108. CommandBuilder.Builder()
  109. .Name("MoveLastBlock")
  110. .Description("Move the most-recently-placed block, and any connected blocks by the given offset")
  111. .Action((float x, float y, float z) =>
  112. {
  113. if (GameState.IsBuildMode())
  114. foreach (var block in Block.GetLastPlacedBlock().GetConnectedCubes())
  115. block.Position += new Unity.Mathematics.float3(x, y, z);
  116. else
  117. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  118. }).Build();
  119. CommandBuilder.Builder()
  120. .Name("PlaceAluminium")
  121. .Description("Place a block of aluminium at the given coordinates")
  122. .Action((float x, float y, float z) => { Block.PlaceNew(Blocks.BlockIDs.AluminiumCube, new Unity.Mathematics.float3(x, y, z)); })
  123. .Build();
  124. CommandBuilder.Builder("getBlock")
  125. .Action(() => uREPL.Log.Output(new Player(Players.PlayerType.Local).GetBlockLookedAt()+"")).Build();
  126. CommandBuilder.Builder("Error", "Throw an error to make sure SimpleCustomCommandEngine's wrapper catches it.")
  127. .Action(() => { throw new Exception("Error Command always throws an error"); })
  128. .Build();
  129. CommandBuilder.Builder("ColorBlock",
  130. "Change color of the block looked at if there's any.")
  131. .Action<string>(str =>
  132. {
  133. if (!Enum.TryParse(str, out BlockColors color))
  134. {
  135. Logging.CommandLog("Color " + str + " not found! Interpreting as 4 color values.");
  136. var s = str.Split(' ');
  137. new Player(PlayerType.Local).GetBlockLookedAt().CustomColor = new float4(float.Parse(s[0]),
  138. float.Parse(s[1]), float.Parse(s[2]), float.Parse(s[3]));
  139. return;
  140. }
  141. new Player(PlayerType.Local).GetBlockLookedAt().Color =
  142. new BlockColor {Color = color};
  143. Logging.CommandLog("Colored block to " + color);
  144. }).Build();
  145. GameClient.SetDebugInfo("lookedAt", LookedAt);
  146. /*
  147. CommandManager.AddCommand(new SimpleCustomCommandEngine<float>((float d) => { UnityEngine.Camera.main.fieldOfView = d; },
  148. "SetFOV", "Set the player camera's field of view"));
  149. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  150. (x, y, z) => {
  151. bool success = GamecraftModdingAPI.Blocks.Movement.MoveConnectedBlocks(
  152. GamecraftModdingAPI.Blocks.BlockIdentifiers.LatestBlockID,
  153. new Unity.Mathematics.float3(x, y, z));
  154. if (!success)
  155. {
  156. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  157. }
  158. }, "MoveLastBlock", "Move the most-recently-placed block, and any connected blocks by the given offset"));
  159. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  160. (x, y, z) => { Blocks.Placement.PlaceBlock(Blocks.BlockIDs.AluminiumCube, new Unity.Mathematics.float3(x, y, z)); },
  161. "PlaceAluminium", "Place a block of aluminium at the given coordinates"));
  162. System.Random random = new System.Random(); // for command below
  163. CommandManager.AddCommand(new SimpleCustomCommandEngine(
  164. () => {
  165. if (!GameState.IsSimulationMode())
  166. {
  167. Logging.CommandLogError("You must be in simulation mode for this to work!");
  168. return;
  169. }
  170. Tasks.Repeatable task = new Tasks.Repeatable(() => {
  171. uint count = 0;
  172. EGID[] eBlocks = Blocks.Signals.GetElectricBlocks();
  173. for (uint i = 0u; i < eBlocks.Length; i++)
  174. {
  175. uint[] ids = Blocks.Signals.GetSignalIDs(eBlocks[i]);
  176. for (uint j = 0u; j < ids.Length; j++)
  177. {
  178. Blocks.Signals.SetSignalByID(ids[j], (float)random.NextDouble());
  179. count++;
  180. }
  181. }
  182. Logging.MetaDebugLog($"Did the thing on {count} inputs");
  183. },
  184. () => { return GameState.IsSimulationMode(); });
  185. Tasks.Scheduler.Schedule(task);
  186. }, "RandomizeSignalsInputs", "Do the thing"));
  187. */
  188. }
  189. // dependency test
  190. if (Dependency.Hell("GamecraftScripting", new Version("0.0.1.0")))
  191. {
  192. Logging.LogWarning("You're in GamecraftScripting dependency hell");
  193. }
  194. else
  195. {
  196. Logging.Log("Compatible GamecraftScripting detected");
  197. }
  198. }
  199. private Player player;
  200. private string LookedAt()
  201. {
  202. if (player == null)
  203. player = new Player(Players.PlayerType.Local);
  204. Block block = player.GetBlockLookedAt();
  205. if (block == null) return "Block: none";
  206. return "Block: " + block.Type + "\nColor: " + block.Color + "\n" + "At: " + block.Position;
  207. }
  208. public void OnFixedUpdate() { }
  209. public void OnLateUpdate() { }
  210. public void OnLevelWasInitialized(int level) { }
  211. public void OnLevelWasLoaded(int level) { }
  212. public void OnUpdate() { }
  213. [HarmonyPatch]
  214. public class MinimumSpecsPatch
  215. {
  216. public static bool Prefix(ref bool __result)
  217. {
  218. __result = true;
  219. return false;
  220. }
  221. public static MethodInfo TargetMethod()
  222. {
  223. return ((Func<bool>)MinimumSpecsCheck.CheckRequirementsMet).Method;
  224. }
  225. }
  226. }
  227. }