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.

GamecraftModdingAPIPluginTest.cs 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. using System;
  2. using System.Diagnostics;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using HarmonyLib;
  7. using IllusionInjector;
  8. // test
  9. using Svelto.ECS;
  10. using RobocraftX.Blocks;
  11. using RobocraftX.Common;
  12. using RobocraftX.SimulationModeState;
  13. using RobocraftX.FrontEnd;
  14. using Unity.Mathematics;
  15. using GamecraftModdingAPI.Commands;
  16. using GamecraftModdingAPI.Events;
  17. using GamecraftModdingAPI.Utility;
  18. using GamecraftModdingAPI.Blocks;
  19. using GamecraftModdingAPI.Players;
  20. namespace GamecraftModdingAPI.Tests
  21. {
  22. // unused by design
  23. /// <summary>
  24. /// Modding API implemented as a standalone IPA Plugin.
  25. /// Ideally, GamecraftModdingAPI should be loaded by another mod; not itself
  26. /// </summary>
  27. public class GamecraftModdingAPIPluginTest
  28. #if DEBUG
  29. : IllusionPlugin.IEnhancedPlugin
  30. #endif
  31. {
  32. private static Harmony harmony { get; set; }
  33. public string[] Filter { get; } = new string[] { "Gamecraft", "GamecraftPreview" };
  34. public string Name { get; } = Assembly.GetExecutingAssembly().GetName().Name;
  35. public string Version { get; } = Assembly.GetExecutingAssembly().GetName().Version.ToString();
  36. public string HarmonyID { get; } = "org.git.exmods.modtainers.gamecraftmoddingapi";
  37. public void OnApplicationQuit()
  38. {
  39. GamecraftModdingAPI.Main.Shutdown();
  40. }
  41. public void OnApplicationStart()
  42. {
  43. FileLog.Reset();
  44. Harmony.DEBUG = true;
  45. GamecraftModdingAPI.Main.Init();
  46. Logging.MetaDebugLog($"Version group id {(uint)ApiExclusiveGroups.versionGroup}");
  47. // in case Steam is not installed/running
  48. // this will crash the game slightly later during startup
  49. //SteamInitPatch.ForcePassSteamCheck = true;
  50. // in case running in a VM
  51. //MinimumSpecsCheckPatch.ForcePassMinimumSpecCheck = true;
  52. // disable some Gamecraft analytics
  53. //AnalyticsDisablerPatch.DisableAnalytics = true;
  54. // disable background music
  55. Logging.MetaDebugLog("Audio Mixers: " + string.Join(",", AudioTools.GetMixers()));
  56. //AudioTools.SetVolume(0.0f, "Music"); // The game now sets this from settings again after this is called :(
  57. //Utility.VersionTracking.Enable();//(very) unstable
  58. // debug/test handlers
  59. HandlerBuilder.Builder()
  60. .Name("appinit API debug")
  61. .Handle(EventType.ApplicationInitialized)
  62. .OnActivation(() => { Logging.Log("App Inited event!"); })
  63. .Build();
  64. HandlerBuilder.Builder("menuact API debug")
  65. .Handle(EventType.Menu)
  66. .OnActivation(() => { Logging.Log("Menu Activated event!"); })
  67. .OnDestruction(() => { Logging.Log("Menu Destroyed event!"); })
  68. .Build();
  69. HandlerBuilder.Builder("menuswitch API debug")
  70. .Handle(EventType.MenuSwitchedTo)
  71. .OnActivation(() => { Logging.Log("Menu Switched To event!"); })
  72. .Build();
  73. HandlerBuilder.Builder("gameact API debug")
  74. .Handle(EventType.Menu)
  75. .OnActivation(() => { Logging.Log("Game Activated event!"); })
  76. .OnDestruction(() => { Logging.Log("Game Destroyed event!"); })
  77. .Build();
  78. HandlerBuilder.Builder("gamerel API debug")
  79. .Handle(EventType.GameReloaded)
  80. .OnActivation(() => { Logging.Log("Game Reloaded event!"); })
  81. .Build();
  82. HandlerBuilder.Builder("gameswitch API debug")
  83. .Handle(EventType.GameSwitchedTo)
  84. .OnActivation(() => { Logging.Log("Game Switched To event!"); })
  85. .Build();
  86. HandlerBuilder.Builder("simulationswitch API debug")
  87. .Handle(EventType.SimulationSwitchedTo)
  88. .OnActivation(() => { Logging.Log("Game Mode Simulation Switched To event!"); })
  89. .Build();
  90. HandlerBuilder.Builder("buildswitch API debug")
  91. .Handle(EventType.BuildSwitchedTo)
  92. .OnActivation(() => { Logging.Log("Game Mode Build Switched To event!"); })
  93. .Build();
  94. HandlerBuilder.Builder("menu activated API error thrower test")
  95. .Handle(EventType.Menu)
  96. .OnActivation(() => { throw new Exception("Event Handler always throws an exception!"); })
  97. .Build();
  98. /*HandlerBuilder.Builder("enter game from menu test")
  99. .Handle(EventType.Menu)
  100. .OnActivation(() =>
  101. {
  102. Tasks.Scheduler.Schedule(new Tasks.Repeatable(enterGame, shouldRetry, 0.2f));
  103. })
  104. .Build();*/
  105. // debug/test commands
  106. if (Dependency.Hell("ExtraCommands"))
  107. {
  108. CommandBuilder.Builder()
  109. .Name("Exit")
  110. .Description("Close Gamecraft immediately, without any prompts")
  111. .Action(() => { UnityEngine.Application.Quit(); })
  112. .Build();
  113. CommandBuilder.Builder()
  114. .Name("SetFOV")
  115. .Description("Set the player camera's field of view")
  116. .Action((float d) => { UnityEngine.Camera.main.fieldOfView = d; })
  117. .Build();
  118. CommandBuilder.Builder()
  119. .Name("MoveLastBlock")
  120. .Description("Move the most-recently-placed block, and any connected blocks by the given offset")
  121. .Action((float x, float y, float z) =>
  122. {
  123. if (GameState.IsBuildMode())
  124. foreach (var block in Block.GetLastPlacedBlock().GetConnectedCubes())
  125. block.Position += new Unity.Mathematics.float3(x, y, z);
  126. else
  127. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  128. }).Build();
  129. CommandBuilder.Builder()
  130. .Name("PlaceAluminium")
  131. .Description("Place a block of aluminium at the given coordinates")
  132. .Action((float x, float y, float z) =>
  133. {
  134. var block = Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x, y, z));
  135. Logging.CommandLog("Block placed with type: " + block.Type);
  136. })
  137. .Build();
  138. CommandBuilder.Builder()
  139. .Name("PlaceAluminiumLots")
  140. .Description("Place a lot of blocks of aluminium at the given coordinates")
  141. .Action((float x, float y, float z) =>
  142. {
  143. Logging.CommandLog("Starting...");
  144. var sw = Stopwatch.StartNew();
  145. for (int i = 0; i < 100; i++)
  146. for (int j = 0; j < 100; j++)
  147. Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x + i, y, z + j));
  148. //Block.Sync();
  149. sw.Stop();
  150. Logging.CommandLog("Finished in " + sw.ElapsedMilliseconds + "ms");
  151. })
  152. .Build();
  153. //With Sync(): 1135ms
  154. //Without Sync(): 134ms
  155. //Async: 348 794ms, doesn't freeze game
  156. //Without Sync() but wait for submission: 530ms
  157. //With Sync() at the end: 380ms
  158. Block b = null;
  159. CommandBuilder.Builder("moveBlockInSim", "Run in build mode first while looking at a block, then in sim to move it up")
  160. .Action(() =>
  161. {
  162. if (b == null)
  163. {
  164. b = new Player(PlayerType.Local).GetBlockLookedAt();
  165. Logging.CommandLog("Block saved: " + b);
  166. }
  167. else
  168. Logging.CommandLog("Block moved to: " + (b.GetSimBody().Position += new float3(0, 2, 0)));
  169. }).Build();
  170. CommandBuilder.Builder("Error", "Throw an error to make sure SimpleCustomCommandEngine's wrapper catches it.")
  171. .Action(() => { throw new Exception("Error Command always throws an error"); })
  172. .Build();
  173. CommandBuilder.Builder("ColorBlock",
  174. "Change color of the block looked at if there's any.")
  175. .Action<string>(str =>
  176. {
  177. if (!Enum.TryParse(str, out BlockColors color))
  178. {
  179. Logging.CommandLog("Color " + str + " not found! Interpreting as 4 color values.");
  180. var s = str.Split(' ');
  181. new Player(PlayerType.Local).GetBlockLookedAt().CustomColor = new float4(float.Parse(s[0]),
  182. float.Parse(s[1]), float.Parse(s[2]), float.Parse(s[3]));
  183. return;
  184. }
  185. new Player(PlayerType.Local).GetBlockLookedAt().Color =
  186. new BlockColor { Color = color };
  187. Logging.CommandLog("Colored block to " + color);
  188. }).Build();
  189. CommandBuilder.Builder("GetBlockByID", "Gets a block based on its object identifier and teleports it up.")
  190. .Action<char>(ch =>
  191. {
  192. foreach (var body in SimBody.GetFromObjectID(ch))
  193. {
  194. Logging.CommandLog("SimBody: " + body);
  195. body.Position += new float3(0, 10, 0);
  196. foreach (var bodyConnectedBody in body.GetConnectedBodies())
  197. {
  198. Logging.CommandLog("Moving " + bodyConnectedBody);
  199. bodyConnectedBody.Position += new float3(0, 10, 0);
  200. }
  201. }
  202. }).Build();
  203. CommandBuilder.Builder()
  204. .Name("PlaceConsole")
  205. .Description("Place a bunch of console block with a given text - entering simulation with them crashes the game as the cmd doesn't exist")
  206. .Action((float x, float y, float z) =>
  207. {
  208. Stopwatch sw = new Stopwatch();
  209. sw.Start();
  210. for (int i = 0; i < 100; i++)
  211. {
  212. for (int j = 0; j < 100; j++)
  213. {
  214. var block = Block.PlaceNew<ConsoleBlock>(BlockIDs.ConsoleBlock,
  215. new float3(x + i, y, z + j));
  216. block.Command = "test_command";
  217. }
  218. }
  219. sw.Stop();
  220. Logging.CommandLog($"Blocks placed in {sw.ElapsedMilliseconds} ms");
  221. })
  222. .Build();
  223. GameClient.SetDebugInfo("InstalledMods", InstalledMods);
  224. Block.Placed += (sender, args) =>
  225. Logging.MetaDebugLog("Placed block " + args.Type + " with ID " + args.ID);
  226. Block.Removed += (sender, args) =>
  227. Logging.MetaDebugLog("Removed block " + args.Type + " with ID " + args.ID);
  228. /*
  229. CommandManager.AddCommand(new SimpleCustomCommandEngine<float>((float d) => { UnityEngine.Camera.main.fieldOfView = d; },
  230. "SetFOV", "Set the player camera's field of view"));
  231. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  232. (x, y, z) => {
  233. bool success = GamecraftModdingAPI.Blocks.Movement.MoveConnectedBlocks(
  234. GamecraftModdingAPI.Blocks.BlockIdentifiers.LatestBlockID,
  235. new Unity.Mathematics.float3(x, y, z));
  236. if (!success)
  237. {
  238. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  239. }
  240. }, "MoveLastBlock", "Move the most-recently-placed block, and any connected blocks by the given offset"));
  241. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  242. (x, y, z) => { Blocks.Placement.PlaceBlock(Blocks.BlockIDs.AluminiumCube, new Unity.Mathematics.float3(x, y, z)); },
  243. "PlaceAluminium", "Place a block of aluminium at the given coordinates"));
  244. System.Random random = new System.Random(); // for command below
  245. CommandManager.AddCommand(new SimpleCustomCommandEngine(
  246. () => {
  247. if (!GameState.IsSimulationMode())
  248. {
  249. Logging.CommandLogError("You must be in simulation mode for this to work!");
  250. return;
  251. }
  252. Tasks.Repeatable task = new Tasks.Repeatable(() => {
  253. uint count = 0;
  254. EGID[] eBlocks = Blocks.Signals.GetElectricBlocks();
  255. for (uint i = 0u; i < eBlocks.Length; i++)
  256. {
  257. uint[] ids = Blocks.Signals.GetSignalIDs(eBlocks[i]);
  258. for (uint j = 0u; j < ids.Length; j++)
  259. {
  260. Blocks.Signals.SetSignalByID(ids[j], (float)random.NextDouble());
  261. count++;
  262. }
  263. }
  264. Logging.MetaDebugLog($"Did the thing on {count} inputs");
  265. },
  266. () => { return GameState.IsSimulationMode(); });
  267. Tasks.Scheduler.Schedule(task);
  268. }, "RandomizeSignalsInputs", "Do the thing"));
  269. */
  270. }
  271. // dependency test
  272. if (Dependency.Hell("GamecraftScripting", new Version("0.0.1.0")))
  273. {
  274. Logging.LogWarning("You're in GamecraftScripting dependency hell");
  275. }
  276. else
  277. {
  278. Logging.Log("Compatible GamecraftScripting detected");
  279. }
  280. #if TEST
  281. TestRoot.RunTests();
  282. #endif
  283. }
  284. private string modsString;
  285. private string InstalledMods()
  286. {
  287. if (modsString != null) return modsString;
  288. StringBuilder sb = new StringBuilder("Installed mods:");
  289. foreach (var plugin in PluginManager.Plugins)
  290. sb.Append("\n" + plugin.Name + " - " + plugin.Version);
  291. return modsString = sb.ToString();
  292. }
  293. private bool retry = true;
  294. private bool shouldRetry()
  295. {
  296. return retry;
  297. }
  298. private void enterGame()
  299. {
  300. App.Client app = new App.Client();
  301. App.Game[] myGames = app.MyGames;
  302. Logging.MetaDebugLog($"MyGames count {myGames.Length}");
  303. if (myGames.Length != 0)
  304. {
  305. Logging.MetaDebugLog($"MyGames[0] EGID {myGames[0].EGID}");
  306. retry = false;
  307. try
  308. {
  309. //myGames[0].Description = "test msg pls ignore"; // make sure game exists first
  310. Logging.MetaDebugLog($"Entering game {myGames[0].Name}");
  311. myGames[0].EnterGame();
  312. }
  313. catch (Exception e)
  314. {
  315. Logging.MetaDebugLog($"Failed to enter game; exception: {e}");
  316. retry = true;
  317. }
  318. }
  319. else
  320. {
  321. Logging.MetaDebugLog("MyGames not populated yet :(");
  322. }
  323. }
  324. public void OnFixedUpdate() { }
  325. public void OnLateUpdate() { }
  326. public void OnLevelWasInitialized(int level) { }
  327. public void OnLevelWasLoaded(int level) { }
  328. public void OnUpdate() { }
  329. [HarmonyPatch]
  330. public class MinimumSpecsPatch
  331. {
  332. public static bool Prefix()
  333. {
  334. return false;
  335. }
  336. public static MethodInfo TargetMethod()
  337. {
  338. return ((Action) MinimumSpecsCheck.CheckRequirementsMet).Method;
  339. }
  340. }
  341. }
  342. }