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.

496 lines
18KB

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