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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. #pragma warning disable 0612
  60. HandlerBuilder.Builder()
  61. .Name("appinit API debug")
  62. .Handle(EventType.ApplicationInitialized)
  63. .OnActivation(() => { Logging.Log("App Inited event!"); })
  64. .Build();
  65. HandlerBuilder.Builder("menuact API debug")
  66. .Handle(EventType.Menu)
  67. .OnActivation(() => { Logging.Log("Menu Activated event!"); })
  68. .OnDestruction(() => { Logging.Log("Menu Destroyed event!"); })
  69. .Build();
  70. HandlerBuilder.Builder("menuswitch API debug")
  71. .Handle(EventType.MenuSwitchedTo)
  72. .OnActivation(() => { Logging.Log("Menu Switched To event!"); })
  73. .Build();
  74. HandlerBuilder.Builder("gameact API debug")
  75. .Handle(EventType.Menu)
  76. .OnActivation(() => { Logging.Log("Game Activated event!"); })
  77. .OnDestruction(() => { Logging.Log("Game Destroyed event!"); })
  78. .Build();
  79. HandlerBuilder.Builder("gamerel API debug")
  80. .Handle(EventType.GameReloaded)
  81. .OnActivation(() => { Logging.Log("Game Reloaded event!"); })
  82. .Build();
  83. HandlerBuilder.Builder("gameswitch API debug")
  84. .Handle(EventType.GameSwitchedTo)
  85. .OnActivation(() => { Logging.Log("Game Switched To event!"); })
  86. .Build();
  87. HandlerBuilder.Builder("simulationswitch API debug")
  88. .Handle(EventType.SimulationSwitchedTo)
  89. .OnActivation(() => { Logging.Log("Game Mode Simulation Switched To event!"); })
  90. .Build();
  91. HandlerBuilder.Builder("buildswitch API debug")
  92. .Handle(EventType.BuildSwitchedTo)
  93. .OnActivation(() => { Logging.Log("Game Mode Build Switched To event!"); })
  94. .Build();
  95. HandlerBuilder.Builder("menu activated API error thrower test")
  96. .Handle(EventType.Menu)
  97. .OnActivation(() => { throw new Exception("Event Handler always throws an exception!"); })
  98. .Build();
  99. #pragma warning restore 0612
  100. /*HandlerBuilder.Builder("enter game from menu test")
  101. .Handle(EventType.Menu)
  102. .OnActivation(() =>
  103. {
  104. Tasks.Scheduler.Schedule(new Tasks.Repeatable(enterGame, shouldRetry, 0.2f));
  105. })
  106. .Build();*/
  107. // debug/test commands
  108. if (Dependency.Hell("ExtraCommands"))
  109. {
  110. CommandBuilder.Builder()
  111. .Name("Exit")
  112. .Description("Close Gamecraft immediately, without any prompts")
  113. .Action(() => { UnityEngine.Application.Quit(); })
  114. .Build();
  115. CommandBuilder.Builder()
  116. .Name("SetFOV")
  117. .Description("Set the player camera's field of view")
  118. .Action((float d) => { UnityEngine.Camera.main.fieldOfView = d; })
  119. .Build();
  120. CommandBuilder.Builder()
  121. .Name("MoveLastBlock")
  122. .Description("Move the most-recently-placed block, and any connected blocks by the given offset")
  123. .Action((float x, float y, float z) =>
  124. {
  125. if (GameState.IsBuildMode())
  126. foreach (var block in Block.GetLastPlacedBlock().GetConnectedCubes())
  127. block.Position += new Unity.Mathematics.float3(x, y, z);
  128. else
  129. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  130. }).Build();
  131. CommandBuilder.Builder()
  132. .Name("PlaceAluminium")
  133. .Description("Place a block of aluminium at the given coordinates")
  134. .Action((float x, float y, float z) =>
  135. {
  136. var block = Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x, y, z));
  137. Logging.CommandLog("Block placed with type: " + block.Type);
  138. })
  139. .Build();
  140. CommandBuilder.Builder()
  141. .Name("PlaceAluminiumLots")
  142. .Description("Place a lot of blocks of aluminium at the given coordinates")
  143. .Action((float x, float y, float z) =>
  144. {
  145. Logging.CommandLog("Starting...");
  146. var sw = Stopwatch.StartNew();
  147. for (int i = 0; i < 100; i++)
  148. for (int j = 0; j < 100; j++)
  149. Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x + i, y, z + j));
  150. //Block.Sync();
  151. sw.Stop();
  152. Logging.CommandLog("Finished in " + sw.ElapsedMilliseconds + "ms");
  153. })
  154. .Build();
  155. //With Sync(): 1135ms
  156. //Without Sync(): 134ms
  157. //Async: 348 794ms, doesn't freeze game
  158. //Without Sync() but wait for submission: 530ms
  159. //With Sync() at the end: 380ms
  160. Block b = null;
  161. CommandBuilder.Builder("moveBlockInSim", "Run in build mode first while looking at a block, then in sim to move it up")
  162. .Action(() =>
  163. {
  164. if (b == null)
  165. {
  166. b = new Player(PlayerType.Local).GetBlockLookedAt();
  167. Logging.CommandLog("Block saved: " + b);
  168. }
  169. else
  170. Logging.CommandLog("Block moved to: " + (b.GetSimBody().Position += new float3(0, 2, 0)));
  171. }).Build();
  172. CommandBuilder.Builder("Error", "Throw an error to make sure SimpleCustomCommandEngine's wrapper catches it.")
  173. .Action(() => { throw new Exception("Error Command always throws an error"); })
  174. .Build();
  175. CommandBuilder.Builder("ColorBlock",
  176. "Change color of the block looked at if there's any.")
  177. .Action<string>(str =>
  178. {
  179. if (!Enum.TryParse(str, out BlockColors color))
  180. {
  181. Logging.CommandLog("Color " + str + " not found! Interpreting as 4 color values.");
  182. var s = str.Split(' ');
  183. new Player(PlayerType.Local).GetBlockLookedAt().CustomColor = new float4(float.Parse(s[0]),
  184. float.Parse(s[1]), float.Parse(s[2]), float.Parse(s[3]));
  185. return;
  186. }
  187. new Player(PlayerType.Local).GetBlockLookedAt().Color =
  188. new BlockColor { Color = color };
  189. Logging.CommandLog("Colored block to " + color);
  190. }).Build();
  191. CommandBuilder.Builder("GetBlockByID", "Gets a block based on its object identifier and teleports it up.")
  192. .Action<char>(ch =>
  193. {
  194. foreach (var body in SimBody.GetFromObjectID(ch))
  195. {
  196. Logging.CommandLog("SimBody: " + body);
  197. body.Position += new float3(0, 10, 0);
  198. foreach (var bodyConnectedBody in body.GetConnectedBodies())
  199. {
  200. Logging.CommandLog("Moving " + bodyConnectedBody);
  201. bodyConnectedBody.Position += new float3(0, 10, 0);
  202. }
  203. }
  204. }).Build();
  205. CommandBuilder.Builder()
  206. .Name("PlaceConsole")
  207. .Description("Place a bunch of console block with a given text - entering simulation with them crashes the game as the cmd doesn't exist")
  208. .Action((float x, float y, float z) =>
  209. {
  210. Stopwatch sw = new Stopwatch();
  211. sw.Start();
  212. for (int i = 0; i < 100; i++)
  213. {
  214. for (int j = 0; j < 100; j++)
  215. {
  216. var block = Block.PlaceNew<ConsoleBlock>(BlockIDs.ConsoleBlock,
  217. new float3(x + i, y, z + j));
  218. block.Command = "test_command";
  219. }
  220. }
  221. sw.Stop();
  222. Logging.CommandLog($"Blocks placed in {sw.ElapsedMilliseconds} ms");
  223. })
  224. .Build();
  225. CommandBuilder.Builder()
  226. .Name("WireTest")
  227. .Description("Place two blocks and then wire them together")
  228. .Action(() =>
  229. {
  230. LogicGate notBlock = Block.PlaceNew<LogicGate>(BlockIDs.NOTLogicBlock, new float3(1, 2, 0));
  231. LogicGate andBlock = Block.PlaceNew<LogicGate>(BlockIDs.ANDLogicBlock, new float3(2, 2, 0));
  232. // connect NOT Gate output to AND Gate input #2 (ports are zero-indexed, so 1 is 2nd position and 0 is 1st position)
  233. Wire conn = notBlock.Connect(0, andBlock, 1);
  234. Logging.CommandLog(conn.ToString());
  235. })
  236. .Build();
  237. GameClient.SetDebugInfo("InstalledMods", InstalledMods);
  238. Block.Placed += (sender, args) =>
  239. Logging.MetaDebugLog("Placed block " + args.Type + " with ID " + args.ID);
  240. Block.Removed += (sender, args) =>
  241. Logging.MetaDebugLog("Removed block " + args.Type + " with ID " + args.ID);
  242. /*
  243. CommandManager.AddCommand(new SimpleCustomCommandEngine<float>((float d) => { UnityEngine.Camera.main.fieldOfView = d; },
  244. "SetFOV", "Set the player camera's field of view"));
  245. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  246. (x, y, z) => {
  247. bool success = GamecraftModdingAPI.Blocks.Movement.MoveConnectedBlocks(
  248. GamecraftModdingAPI.Blocks.BlockIdentifiers.LatestBlockID,
  249. new Unity.Mathematics.float3(x, y, z));
  250. if (!success)
  251. {
  252. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  253. }
  254. }, "MoveLastBlock", "Move the most-recently-placed block, and any connected blocks by the given offset"));
  255. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  256. (x, y, z) => { Blocks.Placement.PlaceBlock(Blocks.BlockIDs.AluminiumCube, new Unity.Mathematics.float3(x, y, z)); },
  257. "PlaceAluminium", "Place a block of aluminium at the given coordinates"));
  258. System.Random random = new System.Random(); // for command below
  259. CommandManager.AddCommand(new SimpleCustomCommandEngine(
  260. () => {
  261. if (!GameState.IsSimulationMode())
  262. {
  263. Logging.CommandLogError("You must be in simulation mode for this to work!");
  264. return;
  265. }
  266. Tasks.Repeatable task = new Tasks.Repeatable(() => {
  267. uint count = 0;
  268. EGID[] eBlocks = Blocks.Signals.GetElectricBlocks();
  269. for (uint i = 0u; i < eBlocks.Length; i++)
  270. {
  271. uint[] ids = Blocks.Signals.GetSignalIDs(eBlocks[i]);
  272. for (uint j = 0u; j < ids.Length; j++)
  273. {
  274. Blocks.Signals.SetSignalByID(ids[j], (float)random.NextDouble());
  275. count++;
  276. }
  277. }
  278. Logging.MetaDebugLog($"Did the thing on {count} inputs");
  279. },
  280. () => { return GameState.IsSimulationMode(); });
  281. Tasks.Scheduler.Schedule(task);
  282. }, "RandomizeSignalsInputs", "Do the thing"));
  283. */
  284. }
  285. // dependency test
  286. if (Dependency.Hell("GamecraftScripting", new Version("0.0.1.0")))
  287. {
  288. Logging.LogWarning("You're in GamecraftScripting dependency hell");
  289. }
  290. else
  291. {
  292. Logging.Log("Compatible GamecraftScripting detected");
  293. }
  294. #if TEST
  295. TestRoot.RunTests();
  296. #endif
  297. }
  298. private string modsString;
  299. private string InstalledMods()
  300. {
  301. if (modsString != null) return modsString;
  302. StringBuilder sb = new StringBuilder("Installed mods:");
  303. foreach (var plugin in PluginManager.Plugins)
  304. sb.Append("\n" + plugin.Name + " - " + plugin.Version);
  305. return modsString = sb.ToString();
  306. }
  307. private bool retry = true;
  308. private bool shouldRetry()
  309. {
  310. return retry;
  311. }
  312. private void enterGame()
  313. {
  314. App.Client app = new App.Client();
  315. App.Game[] myGames = app.MyGames;
  316. Logging.MetaDebugLog($"MyGames count {myGames.Length}");
  317. if (myGames.Length != 0)
  318. {
  319. Logging.MetaDebugLog($"MyGames[0] EGID {myGames[0].EGID}");
  320. retry = false;
  321. try
  322. {
  323. //myGames[0].Description = "test msg pls ignore"; // make sure game exists first
  324. Logging.MetaDebugLog($"Entering game {myGames[0].Name}");
  325. myGames[0].EnterGame();
  326. }
  327. catch (Exception e)
  328. {
  329. Logging.MetaDebugLog($"Failed to enter game; exception: {e}");
  330. retry = true;
  331. }
  332. }
  333. else
  334. {
  335. Logging.MetaDebugLog("MyGames not populated yet :(");
  336. }
  337. }
  338. public void OnFixedUpdate() { }
  339. public void OnLateUpdate() { }
  340. public void OnLevelWasInitialized(int level) { }
  341. public void OnLevelWasLoaded(int level) { }
  342. public void OnUpdate() { }
  343. [HarmonyPatch]
  344. public class MinimumSpecsPatch
  345. {
  346. public static bool Prefix()
  347. {
  348. return false;
  349. }
  350. public static MethodInfo TargetMethod()
  351. {
  352. return ((Action) MinimumSpecsCheck.CheckRequirementsMet).Method;
  353. }
  354. }
  355. }
  356. }