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.

508 lines
19KB

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