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.

405 lines
15KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Reflection;
  5. using System.Text;
  6. using TechbloxModdingAPI.App;
  7. using HarmonyLib;
  8. using IllusionInjector;
  9. // test
  10. using RobocraftX.FrontEnd;
  11. using Unity.Mathematics;
  12. using UnityEngine;
  13. using Svelto.Tasks;
  14. using Svelto.Tasks.Lean;
  15. using TechbloxModdingAPI.Blocks;
  16. using TechbloxModdingAPI.Commands;
  17. using TechbloxModdingAPI.Players;
  18. using TechbloxModdingAPI.Tasks;
  19. using TechbloxModdingAPI.Utility;
  20. namespace TechbloxModdingAPI.Tests
  21. {
  22. #if DEBUG
  23. // unused by design
  24. /// <summary>
  25. /// Modding API implemented as a standalone IPA Plugin.
  26. /// Ideally, TechbloxModdingAPI should be loaded by another mod; not itself
  27. /// </summary>
  28. class TechbloxModdingAPIPluginTest : IllusionPlugin.IEnhancedPlugin
  29. {
  30. private static Harmony harmony { get; set; }
  31. public override string Name { get; } = Assembly.GetExecutingAssembly().GetName().Name;
  32. public override string Version { get; } = Assembly.GetExecutingAssembly().GetName().Version.ToString();
  33. public string HarmonyID { get; } = "org.git.exmods.modtainers.techbloxmoddingapi";
  34. public override void OnApplicationQuit()
  35. {
  36. Main.Shutdown();
  37. }
  38. public override void OnApplicationStart()
  39. {
  40. FileLog.Reset();
  41. Harmony.DEBUG = true;
  42. Main.Init();
  43. Logging.MetaDebugLog($"Version group id {ApiExclusiveGroups.versionGroup}");
  44. // disable background music
  45. Logging.MetaDebugLog("Audio Mixers: " + string.Join(",", AudioTools.GetMixers()));
  46. //AudioTools.SetVolume(0.0f, "Music"); // The game now sets this from settings again after this is called :(
  47. //Utility.VersionTracking.Enable();//(very) unstable
  48. // debug/test handlers
  49. Client.EnterMenu += (sender, args) => throw new Exception("Test handler always throws an exception!");
  50. Client.EnterMenu += (sender, args) => Console.WriteLine("EnterMenu handler after erroring handler");
  51. Game.Enter += (s, a) =>
  52. {
  53. Player.LocalPlayer.SeatEntered += (sender, args) =>
  54. Console.WriteLine($"Player {Player.LocalPlayer} entered seat {args.Seat}");
  55. Player.LocalPlayer.SeatExited += (sender, args) =>
  56. Console.WriteLine($"Player {Player.LocalPlayer} exited seat {args.Seat}");
  57. };
  58. // debug/test commands
  59. if (Dependency.Hell("ExtraCommands"))
  60. {
  61. CommandBuilder.Builder()
  62. .Name("Exit")
  63. .Description("Close Techblox immediately, without any prompts")
  64. .Action(() => { UnityEngine.Application.Quit(); })
  65. .Build();
  66. CommandBuilder.Builder()
  67. .Name("SetFOV")
  68. .Description("Set the player camera's field of view")
  69. .Action((float d) => { UnityEngine.Camera.main.fieldOfView = d; })
  70. .Build();
  71. CommandBuilder.Builder()
  72. .Name("MoveLastBlock")
  73. .Description("Move the most-recently-placed block, and any connected blocks by the given offset")
  74. .Action((float x, float y, float z) =>
  75. {
  76. if (GameState.IsBuildMode())
  77. foreach (var block in Block.GetLastPlacedBlock().GetConnectedCubes())
  78. block.Position += new Unity.Mathematics.float3(x, y, z);
  79. else
  80. Logging.CommandLogError("Blocks can only be moved in Build mode!");
  81. }).Build();
  82. CommandBuilder.Builder()
  83. .Name("PlaceAluminium")
  84. .Description("Place a block of aluminium at the given coordinates")
  85. .Action((float x, float y, float z) =>
  86. {
  87. var block = Block.PlaceNew(BlockIDs.Cube, new float3(x, y, z));
  88. Logging.CommandLog("Block placed with type: " + block.Type);
  89. })
  90. .Build();
  91. CommandBuilder.Builder()
  92. .Name("PlaceAluminiumLots")
  93. .Description("Place a lot of blocks of aluminium at the given coordinates")
  94. .Action((float x, float y, float z) =>
  95. {
  96. Logging.CommandLog("Starting...");
  97. var sw = Stopwatch.StartNew();
  98. for (int i = 0; i < 100; i++)
  99. for (int j = 0; j < 100; j++)
  100. Block.PlaceNew(BlockIDs.Cube, new float3(x + i, y, z + j));
  101. sw.Stop();
  102. Logging.CommandLog("Finished in " + sw.ElapsedMilliseconds + "ms");
  103. })
  104. .Build();
  105. Block b = null;
  106. CommandBuilder.Builder("moveBlockInSim", "Run in build mode first while looking at a block, then in sim to move it up")
  107. .Action(() =>
  108. {
  109. if (b == null)
  110. {
  111. b = new Player(PlayerType.Local).GetBlockLookedAt();
  112. Logging.CommandLog("Block saved: " + b);
  113. }
  114. else
  115. Logging.CommandLog("Block moved to: " + (b.GetSimBody().Position += new float3(0, 2, 0)));
  116. }).Build();
  117. CommandBuilder.Builder("Error", "Throw an error to make sure SimpleCustomCommandEngine's wrapper catches it.")
  118. .Action(() => { throw new Exception("Error Command always throws an error"); })
  119. .Build();
  120. CommandBuilder.Builder("ColorBlock",
  121. "Change color of the block looked at if there's any.")
  122. .Action<string>(str =>
  123. {
  124. if (!Enum.TryParse(str, out BlockColors color))
  125. {
  126. Logging.CommandLog("Color " + str + " not found! Interpreting as 4 color values.");
  127. var s = str.Split(' ');
  128. new Player(PlayerType.Local).GetBlockLookedAt().CustomColor = new float4(float.Parse(s[0]),
  129. float.Parse(s[1]), float.Parse(s[2]), float.Parse(s[3]));
  130. return;
  131. }
  132. new Player(PlayerType.Local).GetBlockLookedAt().Color = color;
  133. Logging.CommandLog("Colored block to " + color);
  134. }).Build();
  135. CommandBuilder.Builder("MoveBlockByID", "Gets a block based on its object identifier and teleports it up.")
  136. .Action<char>(ch =>
  137. {
  138. foreach (var body in SimBody.GetFromObjectID(ch))
  139. {
  140. Logging.CommandLog("SimBody: " + body);
  141. body.Position += new float3(0, 10, 0);
  142. foreach (var bodyConnectedBody in body.GetConnectedBodies())
  143. {
  144. Logging.CommandLog("Moving " + bodyConnectedBody);
  145. bodyConnectedBody.Position += new float3(0, 10, 0);
  146. }
  147. }
  148. }).Build();
  149. CommandBuilder.Builder("TestChunkHealth", "Sets the chunk looked at to the given health.")
  150. .Action((float val, float max) =>
  151. {
  152. var body = new Player(PlayerType.Local).GetSimBodyLookedAt();
  153. if (body == null) return;
  154. body.CurrentHealth = val;
  155. body.InitialHealth = max;
  156. Logging.CommandLog("Health set to: " + val);
  157. }).Build();
  158. CommandBuilder.Builder("placeBlockGroup", "Places some blocks in a group")
  159. .Action((float x, float y, float z) =>
  160. {
  161. var pos = new float3(x, y, z);
  162. var group = BlockGroup.Create(new Block(BlockIDs.Cube, pos) {Color = BlockColors.Aqua});
  163. new Block(BlockIDs.Cube, pos += new float3(1, 0, 0))
  164. {Color = BlockColors.Blue, BlockGroup = group};
  165. new Block(BlockIDs.Cube, pos += new float3(1, 0, 0))
  166. {Color = BlockColors.Green, BlockGroup = group};
  167. new Block(BlockIDs.Cube, pos + new float3(1, 0, 0))
  168. {Color = BlockColors.Lime, BlockGroup = group};
  169. }).Build();
  170. CommandBuilder.Builder("placeCustomBlock", "Places a custom block, needs a custom catalog and assets.")
  171. .Action((float x, float y, float z) =>
  172. {
  173. Logging.CommandLog("Block placed: " +
  174. Block.PlaceNew((BlockIDs) 500, new float3(0, 0, 0)));
  175. }).Build();
  176. CommandBuilder.Builder("toggleTimeMode", "Enters or exits simulation.")
  177. .Action((float x, float y, float z) =>
  178. {
  179. Game.CurrentGame().ToggleTimeMode();
  180. }).Build();
  181. CommandBuilder.Builder("testColorBlock", "Tests coloring a block to default color")
  182. .Action(() => Player.LocalPlayer.GetBlockLookedAt().Color = BlockColors.Default).Build();
  183. CommandBuilder.Builder("testMaterialBlock", "Tests materialing a block to default material")
  184. .Action(() => Player.LocalPlayer.GetBlockLookedAt().Material = BlockMaterial.Default).Build();
  185. CommandBuilder.Builder("testGameName", "Tests changing the game name")
  186. .Action(() => Game.CurrentGame().Name = "Test").Build();
  187. CommandBuilder.Builder("makeBlockStatic", "Makes a block you look at static")
  188. .Action(() => Player.LocalPlayer.GetBlockLookedAt().Static = true).Build();
  189. Game.AddPersistentDebugInfo("InstalledMods", InstalledMods);
  190. /*Block.Placed += (sender, args) =>
  191. Logging.MetaDebugLog("Placed block " + args.Block);
  192. Block.Removed += (sender, args) =>
  193. Logging.MetaDebugLog("Removed block " + args.Block);*/
  194. }
  195. // dependency test
  196. if (Dependency.Hell("TechbloxScripting", new Version("0.0.1.0")))
  197. {
  198. Logging.LogWarning("You're in TechbloxScripting dependency hell");
  199. }
  200. else
  201. {
  202. Logging.Log("Compatible TechbloxScripting detected");
  203. }
  204. // Interface test
  205. /*Group uiGroup = new Group(new Rect(20, 20, 200, 500), "TechbloxModdingAPI_UITestGroup", true);
  206. var button = new Button("TEST");
  207. button.OnClick += (b, __) => { Logging.MetaDebugLog($"Click on {((Interface.IMGUI.Button)b).Name}");};
  208. var button2 = new Button("TEST2");
  209. button2.OnClick += (b, __) => { Logging.MetaDebugLog($"Click on {((Interface.IMGUI.Button)b).Name}");};
  210. Text uiText = new Text("<Input!>", multiline: true);
  211. uiText.OnEdit += (t, txt) => { Logging.MetaDebugLog($"Text in {((Text)t).Name} is now '{txt}'"); };
  212. Label uiLabel = new Label("Label!");
  213. Image uiImg = new Image(name:"Behold this texture!");
  214. uiImg.Enabled = false;
  215. uiGroup.AddElement(button);
  216. uiGroup.AddElement(button2);
  217. uiGroup.AddElement(uiText);
  218. uiGroup.AddElement(uiLabel);
  219. uiGroup.AddElement(uiImg);*/
  220. /*Addressables.LoadAssetAsync<Texture2D>("Assets/Art/Textures/UI/FrontEndMap/RCX_Blue_Background_5k.jpg")
  221. .Completed +=
  222. handle =>
  223. {
  224. uiImg.Texture = handle.Result;
  225. uiImg.Enabled = true;
  226. Logging.MetaDebugLog($"Got blue bg asset {handle.Result}");
  227. };*/
  228. /*((FasterList<GuiInputMap.GuiInputMapElement>)AccessTools.Property(typeof(GuiInputMap), "GuiInputsButtonDown").GetValue(null))
  229. .Add(new GuiInputMap.GuiInputMapElement(RewiredConsts.Action.ToggleCommandLine, GuiIn))*/
  230. /*Game.Enter += (sender, e) =>
  231. {
  232. ushort lastKey = ushort.MaxValue;
  233. foreach (var kv in FullGameFields._dataDb.GetValues<CubeListData>()
  234. .OrderBy(kv=>ushort.Parse(kv.Key)))
  235. {
  236. var data = (CubeListData) kv.Value;
  237. ushort currentKey = ushort.Parse(kv.Key);
  238. var toReplace = new Dictionary<string, string>
  239. {
  240. {"Scalable", ""}, {"Qtr", "Quarter"}, {"RNeg", "Rounded Negative"},
  241. {"Neg", "Negative"}, {"Tetra", "Tetrahedron"},
  242. {"RWedge", "Rounded Wedge"}, {"RTetra", "Rounded Tetrahedron"}
  243. };
  244. string name = LocalizationService.Localize(data.CubeNameKey).Split(' ').Select(str =>
  245. str.Length > 0 ? char.ToUpper(str[0]) + str.Substring(1) : str).Aggregate((a, b) => a + b)
  246. .Replace("-", "");
  247. foreach (var rkv in toReplace)
  248. {
  249. name = Regex.Replace(name, rkv.Key + "([A-Z]|$)", rkv.Value + "$1");
  250. }
  251. Console.WriteLine($"{name}{(currentKey != lastKey + 1 ? $" = {currentKey}" : "")},");
  252. lastKey = currentKey;
  253. }
  254. };*/
  255. /*Game.Enter += (sender, e) =>
  256. {
  257. ushort lastKey = ushort.MaxValue;
  258. Console.WriteLine("Materials:\n" + FullGameFields._dataDb.GetValues<MaterialPropertiesData>()
  259. .OrderBy(kv => ushort.Parse(kv.Key))
  260. .Select(kv =>
  261. {
  262. ushort currentKey = ushort.Parse(kv.Key);
  263. string result = $"{((MaterialPropertiesData)kv.Value).Name}{(currentKey != lastKey + 1 ? $" = {kv.Key}" : "")},";
  264. lastKey = currentKey;
  265. return result;
  266. })
  267. .Aggregate((a, b) => a + "\n" + b));
  268. };*/
  269. CommandBuilder.Builder("takeScreenshot", "Enables the screenshot taker")
  270. .Action(() =>
  271. {
  272. Game.CurrentGame().EnableScreenshotTaker();
  273. }).Build();
  274. CommandBuilder.Builder("testPositionDefault", "Tests the Block.Position property's default value.")
  275. .Action(() =>
  276. {
  277. IEnumerator<TaskContract> Loop()
  278. {
  279. for (int i = 0; i < 2; i++)
  280. {
  281. Console.WriteLine("A");
  282. var block = Block.PlaceNew(BlockIDs.Cube, 1);
  283. Console.WriteLine("B");
  284. while (!block.Exists)
  285. yield return Yield.It;
  286. Console.WriteLine("C");
  287. block.Remove();
  288. Console.WriteLine("D");
  289. while (block.Exists)
  290. yield return Yield.It;
  291. Console.WriteLine("E - Pos: " + block.Position);
  292. block.Position = 4;
  293. Console.WriteLine("F - Pos: " + block.Position);
  294. }
  295. }
  296. Loop().RunOn(Scheduler.leanRunner);
  297. }).Build();
  298. CommandBuilder.Builder("importAssetBundle")
  299. .Action(() =>
  300. {
  301. Logging.CommandLog("Importing asset bundle...");
  302. var ab = AssetBundle.LoadFromFile(
  303. @"filepath");
  304. Logging.CommandLog("Imported asset bundle: " + ab);
  305. var assets = ab.LoadAllAssets();
  306. Logging.CommandLog("Loaded " + assets.Length + " assets");
  307. foreach (var asset in assets)
  308. {
  309. Logging.CommandLog(asset);
  310. }
  311. }).Build();
  312. bool shouldTestGhostBlock = false;
  313. CommandBuilder.Builder("testGhostBlock")
  314. .Action(() =>
  315. {
  316. if (shouldTestGhostBlock)
  317. {
  318. shouldTestGhostBlock = false;
  319. Logging.CommandLog("Test disabled");
  320. }
  321. shouldTestGhostBlock = true;
  322. Scheduler.Schedule(new Repeatable(() =>
  323. {
  324. var ghostBlock = Player.LocalPlayer.GetGhostBlock();
  325. if (ghostBlock == null) return;
  326. ghostBlock.Position = Player.LocalPlayer.Position + 2;
  327. ghostBlock.Color = new BlockColor(BlockColors.Lime);
  328. }, () => shouldTestGhostBlock));
  329. Logging.CommandLog("Test enabled");
  330. }).Build();
  331. Client.EnterMenu += (sender, args) => Scheduler.Schedule(new Once(() => Client.Instance.CloseBetaPopup()));
  332. Game.Enter += (sender, args) =>
  333. Console.WriteLine(
  334. $"Current game selection data: {FullGameFields._gameSelectionData.gameMode} - {FullGameFields._gameSelectionData.saveType}");
  335. #if TEST
  336. TestRoot.RunTests();
  337. #endif
  338. }
  339. private string modsString;
  340. private string InstalledMods()
  341. {
  342. if (modsString != null) return modsString;
  343. StringBuilder sb = new StringBuilder("Installed mods:");
  344. foreach (var plugin in PluginManager.Plugins)
  345. sb.Append("\n" + plugin.Name + " - " + plugin.Version);
  346. return modsString = sb.ToString();
  347. }
  348. [HarmonyPatch]
  349. public class MinimumSpecsPatch
  350. {
  351. public static bool Prefix(ref bool __result)
  352. {
  353. __result = true;
  354. return false;
  355. }
  356. public static MethodInfo TargetMethod()
  357. {
  358. return ((Func<bool>) MinimumSpecsCheck.CheckRequirementsMet).Method;
  359. }
  360. }
  361. }
  362. #endif
  363. }