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 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Reflection.Emit;
  8. using System.Text;
  9. using GamecraftModdingAPI.App;
  10. using HarmonyLib;
  11. using IllusionInjector;
  12. // test
  13. using GPUInstancer;
  14. using Svelto.ECS;
  15. using RobocraftX.Blocks;
  16. using RobocraftX.Common;
  17. using RobocraftX.SimulationModeState;
  18. using RobocraftX.FrontEnd;
  19. using Unity.Mathematics;
  20. using UnityEngine;
  21. using RobocraftX.Schedulers;
  22. using Svelto.Tasks.ExtraLean;
  23. using uREPL;
  24. using GamecraftModdingAPI.Commands;
  25. using GamecraftModdingAPI.Events;
  26. using GamecraftModdingAPI.Utility;
  27. using GamecraftModdingAPI.Blocks;
  28. using GamecraftModdingAPI.Interface.IMGUI;
  29. using GamecraftModdingAPI.Players;
  30. using UnityEngine.AddressableAssets;
  31. using UnityEngine.AddressableAssets.ResourceLocators;
  32. using UnityEngine.ResourceManagement.AsyncOperations;
  33. using UnityEngine.ResourceManagement.ResourceLocations;
  34. using UnityEngine.ResourceManagement.ResourceProviders;
  35. using Debug = FMOD.Debug;
  36. using EventType = GamecraftModdingAPI.Events.EventType;
  37. using Label = GamecraftModdingAPI.Interface.IMGUI.Label;
  38. namespace GamecraftModdingAPI.Tests
  39. {
  40. #if DEBUG
  41. // unused by design
  42. /// <summary>
  43. /// Modding API implemented as a standalone IPA Plugin.
  44. /// Ideally, GamecraftModdingAPI should be loaded by another mod; not itself
  45. /// </summary>
  46. public class GamecraftModdingAPIPluginTest : IllusionPlugin.IEnhancedPlugin
  47. {
  48. private static Harmony harmony { get; set; }
  49. public override string Name { get; } = Assembly.GetExecutingAssembly().GetName().Name;
  50. public override string Version { get; } = Assembly.GetExecutingAssembly().GetName().Version.ToString();
  51. public string HarmonyID { get; } = "org.git.exmods.modtainers.gamecraftmoddingapi";
  52. public override void OnApplicationQuit()
  53. {
  54. GamecraftModdingAPI.Main.Shutdown();
  55. }
  56. public override void OnApplicationStart()
  57. {
  58. FileLog.Reset();
  59. Harmony.DEBUG = true;
  60. GamecraftModdingAPI.Main.Init();
  61. Logging.MetaDebugLog($"Version group id {(uint)ApiExclusiveGroups.versionGroup}");
  62. // in case Steam is not installed/running
  63. // this will crash the game slightly later during startup
  64. //SteamInitPatch.ForcePassSteamCheck = true;
  65. // in case running in a VM
  66. //MinimumSpecsCheckPatch.ForcePassMinimumSpecCheck = true;
  67. // disable some Gamecraft analytics
  68. //AnalyticsDisablerPatch.DisableAnalytics = true;
  69. // disable background music
  70. Logging.MetaDebugLog("Audio Mixers: " + string.Join(",", AudioTools.GetMixers()));
  71. //AudioTools.SetVolume(0.0f, "Music"); // The game now sets this from settings again after this is called :(
  72. //Utility.VersionTracking.Enable();//(very) unstable
  73. // debug/test handlers
  74. #pragma warning disable 0612
  75. HandlerBuilder.Builder()
  76. .Name("appinit API debug")
  77. .Handle(EventType.ApplicationInitialized)
  78. .OnActivation(() => { Logging.Log("App Inited event!"); })
  79. .Build();
  80. HandlerBuilder.Builder("menuact API debug")
  81. .Handle(EventType.Menu)
  82. .OnActivation(() => { Logging.Log("Menu Activated event!"); })
  83. .OnDestruction(() => { Logging.Log("Menu Destroyed event!"); })
  84. .Build();
  85. HandlerBuilder.Builder("menuswitch API debug")
  86. .Handle(EventType.MenuSwitchedTo)
  87. .OnActivation(() => { Logging.Log("Menu Switched To event!"); })
  88. .Build();
  89. HandlerBuilder.Builder("gameact API debug")
  90. .Handle(EventType.Menu)
  91. .OnActivation(() => { Logging.Log("Game Activated event!"); })
  92. .OnDestruction(() => { Logging.Log("Game Destroyed event!"); })
  93. .Build();
  94. HandlerBuilder.Builder("gamerel API debug")
  95. .Handle(EventType.GameReloaded)
  96. .OnActivation(() => { Logging.Log("Game Reloaded event!"); })
  97. .Build();
  98. HandlerBuilder.Builder("gameswitch API debug")
  99. .Handle(EventType.GameSwitchedTo)
  100. .OnActivation(() => { Logging.Log("Game Switched To event!"); })
  101. .Build();
  102. HandlerBuilder.Builder("simulationswitch API debug")
  103. .Handle(EventType.SimulationSwitchedTo)
  104. .OnActivation(() => { Logging.Log("Game Mode Simulation Switched To event!"); })
  105. .Build();
  106. HandlerBuilder.Builder("buildswitch API debug")
  107. .Handle(EventType.BuildSwitchedTo)
  108. .OnActivation(() => { Logging.Log("Game Mode Build Switched To event!"); })
  109. .Build();
  110. HandlerBuilder.Builder("menu activated API error thrower test")
  111. .Handle(EventType.Menu)
  112. .OnActivation(() => { throw new Exception("Event Handler always throws an exception!"); })
  113. .Build();
  114. #pragma warning restore 0612
  115. /*HandlerBuilder.Builder("enter game from menu test")
  116. .Handle(EventType.Menu)
  117. .OnActivation(() =>
  118. {
  119. Tasks.Scheduler.Schedule(new Tasks.Repeatable(enterGame, shouldRetry, 0.2f));
  120. })
  121. .Build();*/
  122. // debug/test commands
  123. if (Dependency.Hell("ExtraCommands"))
  124. {
  125. CommandBuilder.Builder()
  126. .Name("Exit")
  127. .Description("Close Gamecraft immediately, without any prompts")
  128. .Action(() => { UnityEngine.Application.Quit(); })
  129. .Build();
  130. CommandBuilder.Builder()
  131. .Name("SetFOV")
  132. .Description("Set the player camera's field of view")
  133. .Action((float d) => { UnityEngine.Camera.main.fieldOfView = d; })
  134. .Build();
  135. CommandBuilder.Builder()
  136. .Name("MoveLastBlock")
  137. .Description("Move the most-recently-placed block, and any connected blocks by the given offset")
  138. .Action((float x, float y, float z) =>
  139. {
  140. if (GameState.IsBuildMode())
  141. foreach (var block in Block.GetLastPlacedBlock().GetConnectedCubes())
  142. block.Position += new Unity.Mathematics.float3(x, y, z);
  143. else
  144. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  145. }).Build();
  146. CommandBuilder.Builder()
  147. .Name("PlaceAluminium")
  148. .Description("Place a block of aluminium at the given coordinates")
  149. .Action((float x, float y, float z) =>
  150. {
  151. var block = Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x, y, z));
  152. Logging.CommandLog("Block placed with type: " + block.Type);
  153. })
  154. .Build();
  155. CommandBuilder.Builder()
  156. .Name("PlaceAluminiumLots")
  157. .Description("Place a lot of blocks of aluminium at the given coordinates")
  158. .Action((float x, float y, float z) =>
  159. {
  160. Logging.CommandLog("Starting...");
  161. var sw = Stopwatch.StartNew();
  162. for (int i = 0; i < 100; i++)
  163. for (int j = 0; j < 100; j++)
  164. Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x + i, y, z + j));
  165. //Block.Sync();
  166. sw.Stop();
  167. Logging.CommandLog("Finished in " + sw.ElapsedMilliseconds + "ms");
  168. })
  169. .Build();
  170. Block b = null;
  171. CommandBuilder.Builder("moveBlockInSim", "Run in build mode first while looking at a block, then in sim to move it up")
  172. .Action(() =>
  173. {
  174. if (b == null)
  175. {
  176. b = new Player(PlayerType.Local).GetBlockLookedAt();
  177. Logging.CommandLog("Block saved: " + b);
  178. }
  179. else
  180. Logging.CommandLog("Block moved to: " + (b.GetSimBody().Position += new float3(0, 2, 0)));
  181. }).Build();
  182. CommandBuilder.Builder("Error", "Throw an error to make sure SimpleCustomCommandEngine's wrapper catches it.")
  183. .Action(() => { throw new Exception("Error Command always throws an error"); })
  184. .Build();
  185. CommandBuilder.Builder("ColorBlock",
  186. "Change color of the block looked at if there's any.")
  187. .Action<string>(str =>
  188. {
  189. if (!Enum.TryParse(str, out BlockColors color))
  190. {
  191. Logging.CommandLog("Color " + str + " not found! Interpreting as 4 color values.");
  192. var s = str.Split(' ');
  193. new Player(PlayerType.Local).GetBlockLookedAt().CustomColor = new float4(float.Parse(s[0]),
  194. float.Parse(s[1]), float.Parse(s[2]), float.Parse(s[3]));
  195. return;
  196. }
  197. new Player(PlayerType.Local).GetBlockLookedAt().Color =
  198. new BlockColor { Color = color };
  199. Logging.CommandLog("Colored block to " + color);
  200. }).Build();
  201. CommandBuilder.Builder("GetBlockByID", "Gets a block based on its object identifier and teleports it up.")
  202. .Action<char>(ch =>
  203. {
  204. foreach (var body in SimBody.GetFromObjectID(ch))
  205. {
  206. Logging.CommandLog("SimBody: " + body);
  207. body.Position += new float3(0, 10, 0);
  208. foreach (var bodyConnectedBody in body.GetConnectedBodies())
  209. {
  210. Logging.CommandLog("Moving " + bodyConnectedBody);
  211. bodyConnectedBody.Position += new float3(0, 10, 0);
  212. }
  213. }
  214. }).Build();
  215. CommandBuilder.Builder()
  216. .Name("PlaceConsole")
  217. .Description("Place a bunch of console block with a given text - entering simulation with them crashes the game as the cmd doesn't exist")
  218. .Action((float x, float y, float z) =>
  219. {
  220. Stopwatch sw = new Stopwatch();
  221. sw.Start();
  222. for (int i = 0; i < 100; i++)
  223. {
  224. for (int j = 0; j < 100; j++)
  225. {
  226. var block = Block.PlaceNew<ConsoleBlock>(BlockIDs.ConsoleBlock,
  227. new float3(x + i, y, z + j));
  228. block.Command = "test_command";
  229. }
  230. }
  231. sw.Stop();
  232. Logging.CommandLog($"Blocks placed in {sw.ElapsedMilliseconds} ms");
  233. })
  234. .Build();
  235. CommandBuilder.Builder()
  236. .Name("WireTest")
  237. .Description("Place two blocks and then wire them together")
  238. .Action(() =>
  239. {
  240. LogicGate notBlock = Block.PlaceNew<LogicGate>(BlockIDs.NOTLogicBlock, new float3(1, 2, 0));
  241. LogicGate andBlock = Block.PlaceNew<LogicGate>(BlockIDs.ANDLogicBlock, new float3(2, 2, 0));
  242. // connect NOT Gate output to AND Gate input #2 (ports are zero-indexed, so 1 is 2nd position and 0 is 1st position)
  243. Wire conn = notBlock.Connect(0, andBlock, 1);
  244. Logging.CommandLog(conn.ToString());
  245. })
  246. .Build();
  247. CommandBuilder.Builder("TestChunkHealth", "Sets the chunk looked at to the given health.")
  248. .Action((float val, float max) =>
  249. {
  250. var body = new Player(PlayerType.Local).GetSimBodyLookedAt();
  251. if (body == null) return;
  252. body.CurrentHealth = val;
  253. body.InitialHealth = max;
  254. Logging.CommandLog("Health set to: " + val);
  255. }).Build();
  256. CommandBuilder.Builder("placeBlockGroup", "Places some blocks in a group")
  257. .Action((float x, float y, float z) =>
  258. {
  259. var pos = new float3(x, y, z);
  260. var group = BlockGroup.Create(Block.PlaceNew(BlockIDs.AluminiumCube, pos,
  261. color: BlockColors.Aqua));
  262. Block.PlaceNew(BlockIDs.AluminiumCube, pos += new float3(1, 0, 0), color: BlockColors.Blue)
  263. .BlockGroup = group;
  264. Block.PlaceNew(BlockIDs.AluminiumCube, pos += new float3(1, 0, 0), color: BlockColors.Green)
  265. .BlockGroup = group;
  266. Block.PlaceNew(BlockIDs.AluminiumCube, pos += new float3(1, 0, 0), color: BlockColors.Lime)
  267. .BlockGroup = group;
  268. }).Build();
  269. CommandBuilder.Builder("placeCustomBlock", "Places a custom block, needs a custom catalog and assets.")
  270. .Action((float x, float y, float z) =>
  271. {
  272. Logging.CommandLog("Block placed: " +
  273. Block.PlaceNew<TestBlock>((BlockIDs) 500, new float3(0, 0, 0)));
  274. }).Build();
  275. GameClient.SetDebugInfo("InstalledMods", InstalledMods);
  276. Block.Placed += (sender, args) =>
  277. Logging.MetaDebugLog("Placed block " + args.Type + " with ID " + args.ID);
  278. Block.Removed += (sender, args) =>
  279. Logging.MetaDebugLog("Removed block " + args.Type + " with ID " + args.ID);
  280. /*
  281. CommandManager.AddCommand(new SimpleCustomCommandEngine<float>((float d) => { UnityEngine.Camera.main.fieldOfView = d; },
  282. "SetFOV", "Set the player camera's field of view"));
  283. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  284. (x, y, z) => {
  285. bool success = GamecraftModdingAPI.Blocks.Movement.MoveConnectedBlocks(
  286. GamecraftModdingAPI.Blocks.BlockIdentifiers.LatestBlockID,
  287. new Unity.Mathematics.float3(x, y, z));
  288. if (!success)
  289. {
  290. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  291. }
  292. }, "MoveLastBlock", "Move the most-recently-placed block, and any connected blocks by the given offset"));
  293. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  294. (x, y, z) => { Blocks.Placement.PlaceBlock(Blocks.BlockIDs.AluminiumCube, new Unity.Mathematics.float3(x, y, z)); },
  295. "PlaceAluminium", "Place a block of aluminium at the given coordinates"));
  296. System.Random random = new System.Random(); // for command below
  297. CommandManager.AddCommand(new SimpleCustomCommandEngine(
  298. () => {
  299. if (!GameState.IsSimulationMode())
  300. {
  301. Logging.CommandLogError("You must be in simulation mode for this to work!");
  302. return;
  303. }
  304. Tasks.Repeatable task = new Tasks.Repeatable(() => {
  305. uint count = 0;
  306. EGID[] eBlocks = Blocks.Signals.GetElectricBlocks();
  307. for (uint i = 0u; i < eBlocks.Length; i++)
  308. {
  309. uint[] ids = Blocks.Signals.GetSignalIDs(eBlocks[i]);
  310. for (uint j = 0u; j < ids.Length; j++)
  311. {
  312. Blocks.Signals.SetSignalByID(ids[j], (float)random.NextDouble());
  313. count++;
  314. }
  315. }
  316. Logging.MetaDebugLog($"Did the thing on {count} inputs");
  317. },
  318. () => { return GameState.IsSimulationMode(); });
  319. Tasks.Scheduler.Schedule(task);
  320. }, "RandomizeSignalsInputs", "Do the thing"));
  321. */
  322. }
  323. // dependency test
  324. if (Dependency.Hell("GamecraftScripting", new Version("0.0.1.0")))
  325. {
  326. Logging.LogWarning("You're in GamecraftScripting dependency hell");
  327. }
  328. else
  329. {
  330. Logging.Log("Compatible GamecraftScripting detected");
  331. }
  332. // Interface test
  333. Interface.IMGUI.Group uiGroup = new Group(new Rect(20, 20, 200, 500), "GamecraftModdingAPI_UITestGroup", true);
  334. Interface.IMGUI.Button button = new Button("TEST");
  335. button.OnClick += (b, __) => { Logging.MetaDebugLog($"Click on {((Interface.IMGUI.Button)b).Name}");};
  336. Interface.IMGUI.Button button2 = new Button("TEST2");
  337. button2.OnClick += (b, __) => { Logging.MetaDebugLog($"Click on {((Interface.IMGUI.Button)b).Name}");};
  338. Text uiText = new Text("This is text!", multiline: true);
  339. uiText.OnEdit += (t, txt) => { Logging.MetaDebugLog($"Text in {((Text)t).Name} is now '{txt}'"); };
  340. Label uiLabel = new Label("Label!");
  341. Image uiImg = new Image(name:"Behold this texture!");
  342. uiImg.Enabled = false;
  343. uiGroup.AddElement(button);
  344. uiGroup.AddElement(button2);
  345. uiGroup.AddElement(uiText);
  346. uiGroup.AddElement(uiLabel);
  347. uiGroup.AddElement(uiImg);
  348. Addressables.LoadAssetAsync<Texture2D>("Assets/Art/Textures/UI/FrontEndMap/RCX_Blue_Background_5k.jpg")
  349. .Completed +=
  350. handle =>
  351. {
  352. uiImg.Texture = handle.Result;
  353. uiImg.Enabled = true;
  354. Logging.MetaDebugLog($"Got blue bg asset {handle.Result}");
  355. };
  356. CommandBuilder.Builder("enableCompletions")
  357. .Action(() =>
  358. {
  359. var p = Window.selected.main.parameters;
  360. p.useCommandCompletion = true;
  361. p.useMonoCompletion = true;
  362. p.useGlobalClassCompletion = true;
  363. Log.Output("Submitted: " + Window.selected.submittedCode);
  364. })
  365. .Build();
  366. try
  367. {
  368. CustomBlock.RegisterCustomBlock<TestBlock>();
  369. Logging.MetaDebugLog("Registered test custom block");
  370. }
  371. catch (FileNotFoundException)
  372. {
  373. Logging.MetaDebugLog("Test custom block catalog not found");
  374. }
  375. #if TEST
  376. TestRoot.RunTests();
  377. #endif
  378. }
  379. private string modsString;
  380. private string InstalledMods()
  381. {
  382. if (modsString != null) return modsString;
  383. StringBuilder sb = new StringBuilder("Installed mods:");
  384. foreach (var plugin in PluginManager.Plugins)
  385. sb.Append("\n" + plugin.Name + " - " + plugin.Version);
  386. return modsString = sb.ToString();
  387. }
  388. private bool retry = true;
  389. private bool shouldRetry()
  390. {
  391. return retry;
  392. }
  393. private void enterGame()
  394. {
  395. App.Client app = new App.Client();
  396. App.Game[] myGames = app.MyGames;
  397. Logging.MetaDebugLog($"MyGames count {myGames.Length}");
  398. if (myGames.Length != 0)
  399. {
  400. Logging.MetaDebugLog($"MyGames[0] EGID {myGames[0].EGID}");
  401. retry = false;
  402. try
  403. {
  404. //myGames[0].Description = "test msg pls ignore"; // make sure game exists first
  405. Logging.MetaDebugLog($"Entering game {myGames[0].Name}");
  406. myGames[0].EnterGame();
  407. }
  408. catch (Exception e)
  409. {
  410. Logging.MetaDebugLog($"Failed to enter game; exception: {e}");
  411. retry = true;
  412. }
  413. }
  414. else
  415. {
  416. Logging.MetaDebugLog("MyGames not populated yet :(");
  417. }
  418. }
  419. [HarmonyPatch]
  420. public class MinimumSpecsPatch
  421. {
  422. public static bool Prefix()
  423. {
  424. return false;
  425. }
  426. public static MethodInfo TargetMethod()
  427. {
  428. return ((Action) MinimumSpecsCheck.CheckRequirementsMet).Method;
  429. }
  430. }
  431. [CustomBlock("customCatalog.json", "Assets/Prefabs/Cube.prefab", "strAluminiumCube", SortIndex = 12)]
  432. public class TestBlock : CustomBlock
  433. {
  434. public TestBlock(EGID id) : base(id)
  435. {
  436. }
  437. public TestBlock(uint id) : base(id)
  438. {
  439. }
  440. }
  441. }
  442. #endif
  443. }