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.

435 lines
16KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Reflection.Emit;
  7. using System.Text;
  8. using HarmonyLib;
  9. using IllusionInjector;
  10. // test
  11. using GPUInstancer;
  12. using Svelto.ECS;
  13. using RobocraftX.Blocks;
  14. using RobocraftX.Common;
  15. using RobocraftX.SimulationModeState;
  16. using RobocraftX.FrontEnd;
  17. using Unity.Mathematics;
  18. using UnityEngine;
  19. using RobocraftX.Schedulers;
  20. using Svelto.Tasks.ExtraLean;
  21. using uREPL;
  22. using GamecraftModdingAPI.Commands;
  23. using GamecraftModdingAPI.Events;
  24. using GamecraftModdingAPI.Utility;
  25. using GamecraftModdingAPI.Blocks;
  26. using GamecraftModdingAPI.Players;
  27. using EventType = GamecraftModdingAPI.Events.EventType;
  28. namespace GamecraftModdingAPI.Tests
  29. {
  30. #if DEBUG
  31. // unused by design
  32. /// <summary>
  33. /// Modding API implemented as a standalone IPA Plugin.
  34. /// Ideally, GamecraftModdingAPI should be loaded by another mod; not itself
  35. /// </summary>
  36. public class GamecraftModdingAPIPluginTest : IllusionPlugin.IEnhancedPlugin
  37. {
  38. private static Harmony harmony { get; set; }
  39. public override string Name { get; } = Assembly.GetExecutingAssembly().GetName().Name;
  40. public override string Version { get; } = Assembly.GetExecutingAssembly().GetName().Version.ToString();
  41. public string HarmonyID { get; } = "org.git.exmods.modtainers.gamecraftmoddingapi";
  42. public override void OnApplicationQuit()
  43. {
  44. GamecraftModdingAPI.Main.Shutdown();
  45. }
  46. public override void OnApplicationStart()
  47. {
  48. FileLog.Reset();
  49. Harmony.DEBUG = true;
  50. GamecraftModdingAPI.Main.Init();
  51. Logging.MetaDebugLog($"Version group id {(uint)ApiExclusiveGroups.versionGroup}");
  52. // in case Steam is not installed/running
  53. // this will crash the game slightly later during startup
  54. //SteamInitPatch.ForcePassSteamCheck = true;
  55. // in case running in a VM
  56. //MinimumSpecsCheckPatch.ForcePassMinimumSpecCheck = true;
  57. // disable some Gamecraft analytics
  58. //AnalyticsDisablerPatch.DisableAnalytics = true;
  59. // disable background music
  60. Logging.MetaDebugLog("Audio Mixers: " + string.Join(",", AudioTools.GetMixers()));
  61. //AudioTools.SetVolume(0.0f, "Music"); // The game now sets this from settings again after this is called :(
  62. //Utility.VersionTracking.Enable();//(very) unstable
  63. // debug/test handlers
  64. #pragma warning disable 0612
  65. HandlerBuilder.Builder()
  66. .Name("appinit API debug")
  67. .Handle(EventType.ApplicationInitialized)
  68. .OnActivation(() => { Logging.Log("App Inited event!"); })
  69. .Build();
  70. HandlerBuilder.Builder("menuact API debug")
  71. .Handle(EventType.Menu)
  72. .OnActivation(() => { Logging.Log("Menu Activated event!"); })
  73. .OnDestruction(() => { Logging.Log("Menu Destroyed event!"); })
  74. .Build();
  75. HandlerBuilder.Builder("menuswitch API debug")
  76. .Handle(EventType.MenuSwitchedTo)
  77. .OnActivation(() => { Logging.Log("Menu Switched To event!"); })
  78. .Build();
  79. HandlerBuilder.Builder("gameact API debug")
  80. .Handle(EventType.Menu)
  81. .OnActivation(() => { Logging.Log("Game Activated event!"); })
  82. .OnDestruction(() => { Logging.Log("Game Destroyed event!"); })
  83. .Build();
  84. HandlerBuilder.Builder("gamerel API debug")
  85. .Handle(EventType.GameReloaded)
  86. .OnActivation(() => { Logging.Log("Game Reloaded event!"); })
  87. .Build();
  88. HandlerBuilder.Builder("gameswitch API debug")
  89. .Handle(EventType.GameSwitchedTo)
  90. .OnActivation(() => { Logging.Log("Game Switched To event!"); })
  91. .Build();
  92. HandlerBuilder.Builder("simulationswitch API debug")
  93. .Handle(EventType.SimulationSwitchedTo)
  94. .OnActivation(() => { Logging.Log("Game Mode Simulation Switched To event!"); })
  95. .Build();
  96. HandlerBuilder.Builder("buildswitch API debug")
  97. .Handle(EventType.BuildSwitchedTo)
  98. .OnActivation(() => { Logging.Log("Game Mode Build Switched To event!"); })
  99. .Build();
  100. HandlerBuilder.Builder("menu activated API error thrower test")
  101. .Handle(EventType.Menu)
  102. .OnActivation(() => { throw new Exception("Event Handler always throws an exception!"); })
  103. .Build();
  104. #pragma warning restore 0612
  105. /*HandlerBuilder.Builder("enter game from menu test")
  106. .Handle(EventType.Menu)
  107. .OnActivation(() =>
  108. {
  109. Tasks.Scheduler.Schedule(new Tasks.Repeatable(enterGame, shouldRetry, 0.2f));
  110. })
  111. .Build();*/
  112. // debug/test commands
  113. if (Dependency.Hell("ExtraCommands"))
  114. {
  115. CommandBuilder.Builder()
  116. .Name("Exit")
  117. .Description("Close Gamecraft immediately, without any prompts")
  118. .Action(() => { UnityEngine.Application.Quit(); })
  119. .Build();
  120. CommandBuilder.Builder()
  121. .Name("SetFOV")
  122. .Description("Set the player camera's field of view")
  123. .Action((float d) => { UnityEngine.Camera.main.fieldOfView = d; })
  124. .Build();
  125. CommandBuilder.Builder()
  126. .Name("MoveLastBlock")
  127. .Description("Move the most-recently-placed block, and any connected blocks by the given offset")
  128. .Action((float x, float y, float z) =>
  129. {
  130. if (GameState.IsBuildMode())
  131. foreach (var block in Block.GetLastPlacedBlock().GetConnectedCubes())
  132. block.Position += new Unity.Mathematics.float3(x, y, z);
  133. else
  134. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  135. }).Build();
  136. CommandBuilder.Builder()
  137. .Name("PlaceAluminium")
  138. .Description("Place a block of aluminium at the given coordinates")
  139. .Action((float x, float y, float z) =>
  140. {
  141. var block = Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x, y, z));
  142. Logging.CommandLog("Block placed with type: " + block.Type);
  143. })
  144. .Build();
  145. CommandBuilder.Builder()
  146. .Name("PlaceAluminiumLots")
  147. .Description("Place a lot of blocks of aluminium at the given coordinates")
  148. .Action((float x, float y, float z) =>
  149. {
  150. Logging.CommandLog("Starting...");
  151. var sw = Stopwatch.StartNew();
  152. for (int i = 0; i < 100; i++)
  153. for (int j = 0; j < 100; j++)
  154. Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x + i, y, z + j));
  155. //Block.Sync();
  156. sw.Stop();
  157. Logging.CommandLog("Finished in " + sw.ElapsedMilliseconds + "ms");
  158. })
  159. .Build();
  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. CommandBuilder.Builder("TestChunkHealth", "Sets the chunk looked at to the given health.")
  238. .Action((float val, float max) =>
  239. {
  240. var body = new Player(PlayerType.Local).GetSimBodyLookedAt();
  241. if (body == null) return;
  242. body.CurrentHealth = val;
  243. body.InitialHealth = max;
  244. Logging.CommandLog("Health set to: " + val);
  245. }).Build();
  246. CommandBuilder.Builder("placeBlockGroup", "Places some blocks in a group")
  247. .Action((float x, float y, float z) =>
  248. {
  249. var pos = new float3(x, y, z);
  250. var group = BlockGroup.Create(Block.PlaceNew(BlockIDs.AluminiumCube, pos,
  251. color: BlockColors.Aqua));
  252. Block.PlaceNew(BlockIDs.AluminiumCube, pos += new float3(1, 0, 0), color: BlockColors.Blue)
  253. .BlockGroup = group;
  254. Block.PlaceNew(BlockIDs.AluminiumCube, pos += new float3(1, 0, 0), color: BlockColors.Green)
  255. .BlockGroup = group;
  256. Block.PlaceNew(BlockIDs.AluminiumCube, pos += new float3(1, 0, 0), color: BlockColors.Lime)
  257. .BlockGroup = group;
  258. }).Build();
  259. GameClient.SetDebugInfo("InstalledMods", InstalledMods);
  260. Block.Placed += (sender, args) =>
  261. Logging.MetaDebugLog("Placed block " + args.Type + " with ID " + args.ID);
  262. Block.Removed += (sender, args) =>
  263. Logging.MetaDebugLog("Removed block " + args.Type + " with ID " + args.ID);
  264. /*
  265. CommandManager.AddCommand(new SimpleCustomCommandEngine<float>((float d) => { UnityEngine.Camera.main.fieldOfView = d; },
  266. "SetFOV", "Set the player camera's field of view"));
  267. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  268. (x, y, z) => {
  269. bool success = GamecraftModdingAPI.Blocks.Movement.MoveConnectedBlocks(
  270. GamecraftModdingAPI.Blocks.BlockIdentifiers.LatestBlockID,
  271. new Unity.Mathematics.float3(x, y, z));
  272. if (!success)
  273. {
  274. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  275. }
  276. }, "MoveLastBlock", "Move the most-recently-placed block, and any connected blocks by the given offset"));
  277. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  278. (x, y, z) => { Blocks.Placement.PlaceBlock(Blocks.BlockIDs.AluminiumCube, new Unity.Mathematics.float3(x, y, z)); },
  279. "PlaceAluminium", "Place a block of aluminium at the given coordinates"));
  280. System.Random random = new System.Random(); // for command below
  281. CommandManager.AddCommand(new SimpleCustomCommandEngine(
  282. () => {
  283. if (!GameState.IsSimulationMode())
  284. {
  285. Logging.CommandLogError("You must be in simulation mode for this to work!");
  286. return;
  287. }
  288. Tasks.Repeatable task = new Tasks.Repeatable(() => {
  289. uint count = 0;
  290. EGID[] eBlocks = Blocks.Signals.GetElectricBlocks();
  291. for (uint i = 0u; i < eBlocks.Length; i++)
  292. {
  293. uint[] ids = Blocks.Signals.GetSignalIDs(eBlocks[i]);
  294. for (uint j = 0u; j < ids.Length; j++)
  295. {
  296. Blocks.Signals.SetSignalByID(ids[j], (float)random.NextDouble());
  297. count++;
  298. }
  299. }
  300. Logging.MetaDebugLog($"Did the thing on {count} inputs");
  301. },
  302. () => { return GameState.IsSimulationMode(); });
  303. Tasks.Scheduler.Schedule(task);
  304. }, "RandomizeSignalsInputs", "Do the thing"));
  305. */
  306. }
  307. // dependency test
  308. if (Dependency.Hell("GamecraftScripting", new Version("0.0.1.0")))
  309. {
  310. Logging.LogWarning("You're in GamecraftScripting dependency hell");
  311. }
  312. else
  313. {
  314. Logging.Log("Compatible GamecraftScripting detected");
  315. }
  316. CommandBuilder.Builder("enableCompletions")
  317. .Action(() =>
  318. {
  319. var p = Window.selected.main.parameters;
  320. p.useCommandCompletion = true;
  321. p.useMonoCompletion = true;
  322. p.useGlobalClassCompletion = true;
  323. Log.Output("Submitted: " + Window.selected.submittedCode);
  324. })
  325. .Build();
  326. /*JObject o1 = JObject.Parse(File.ReadAllText(@"Gamecraft_Data\StreamingAssets\aa\Windows\catalog.json"));
  327. JObject o2 = JObject.Parse(File.ReadAllText(@"customCatalog.json"));
  328. o1.Merge(o2, new JsonMergeSettings {MergeArrayHandling = MergeArrayHandling.Union});
  329. File.WriteAllText(@"Gamecraft_Data\StreamingAssets\aa\Windows\catalog.json", o1.ToString());*/
  330. CustomBlock.Prep().RunOn(ExtraLean.UIScheduler);
  331. #if TEST
  332. TestRoot.RunTests();
  333. #endif
  334. }
  335. private string modsString;
  336. private string InstalledMods()
  337. {
  338. if (modsString != null) return modsString;
  339. StringBuilder sb = new StringBuilder("Installed mods:");
  340. foreach (var plugin in PluginManager.Plugins)
  341. sb.Append("\n" + plugin.Name + " - " + plugin.Version);
  342. return modsString = sb.ToString();
  343. }
  344. private bool retry = true;
  345. private bool shouldRetry()
  346. {
  347. return retry;
  348. }
  349. private void enterGame()
  350. {
  351. App.Client app = new App.Client();
  352. App.Game[] myGames = app.MyGames;
  353. Logging.MetaDebugLog($"MyGames count {myGames.Length}");
  354. if (myGames.Length != 0)
  355. {
  356. Logging.MetaDebugLog($"MyGames[0] EGID {myGames[0].EGID}");
  357. retry = false;
  358. try
  359. {
  360. //myGames[0].Description = "test msg pls ignore"; // make sure game exists first
  361. Logging.MetaDebugLog($"Entering game {myGames[0].Name}");
  362. myGames[0].EnterGame();
  363. }
  364. catch (Exception e)
  365. {
  366. Logging.MetaDebugLog($"Failed to enter game; exception: {e}");
  367. retry = true;
  368. }
  369. }
  370. else
  371. {
  372. Logging.MetaDebugLog("MyGames not populated yet :(");
  373. }
  374. }
  375. [HarmonyPatch]
  376. public class MinimumSpecsPatch
  377. {
  378. public static bool Prefix()
  379. {
  380. return false;
  381. }
  382. public static MethodInfo TargetMethod()
  383. {
  384. return ((Action) MinimumSpecsCheck.CheckRequirementsMet).Method;
  385. }
  386. }
  387. }
  388. #endif
  389. }