A stable modding interface between Techblox and mods https://mod.exmods.org/
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

402 wiersze
14KB

  1. using System;
  2. using System.Diagnostics;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using HarmonyLib;
  7. using IllusionInjector;
  8. // test
  9. using Svelto.ECS;
  10. using RobocraftX.Blocks;
  11. using RobocraftX.Common;
  12. using RobocraftX.SimulationModeState;
  13. using RobocraftX.FrontEnd;
  14. using Unity.Mathematics;
  15. using GamecraftModdingAPI.Commands;
  16. using GamecraftModdingAPI.Events;
  17. using GamecraftModdingAPI.Utility;
  18. using GamecraftModdingAPI.Blocks;
  19. using GamecraftModdingAPI.Players;
  20. namespace GamecraftModdingAPI.Tests
  21. {
  22. #if DEBUG
  23. // unused by design
  24. /// <summary>
  25. /// Modding API implemented as a standalone IPA Plugin.
  26. /// Ideally, GamecraftModdingAPI should be loaded by another mod; not itself
  27. /// </summary>
  28. public class GamecraftModdingAPIPluginTest : 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.gamecraftmoddingapi";
  34. public override void OnApplicationQuit()
  35. {
  36. GamecraftModdingAPI.Main.Shutdown();
  37. }
  38. public override void OnApplicationStart()
  39. {
  40. FileLog.Reset();
  41. Harmony.DEBUG = true;
  42. GamecraftModdingAPI.Main.Init();
  43. Logging.MetaDebugLog($"Version group id {(uint)ApiExclusiveGroups.versionGroup}");
  44. // in case Steam is not installed/running
  45. // this will crash the game slightly later during startup
  46. //SteamInitPatch.ForcePassSteamCheck = true;
  47. // in case running in a VM
  48. //MinimumSpecsCheckPatch.ForcePassMinimumSpecCheck = true;
  49. // disable some Gamecraft analytics
  50. //AnalyticsDisablerPatch.DisableAnalytics = true;
  51. // disable background music
  52. Logging.MetaDebugLog("Audio Mixers: " + string.Join(",", AudioTools.GetMixers()));
  53. //AudioTools.SetVolume(0.0f, "Music"); // The game now sets this from settings again after this is called :(
  54. //Utility.VersionTracking.Enable();//(very) unstable
  55. // debug/test handlers
  56. #pragma warning disable 0612
  57. HandlerBuilder.Builder()
  58. .Name("appinit API debug")
  59. .Handle(EventType.ApplicationInitialized)
  60. .OnActivation(() => { Logging.Log("App Inited event!"); })
  61. .Build();
  62. HandlerBuilder.Builder("menuact API debug")
  63. .Handle(EventType.Menu)
  64. .OnActivation(() => { Logging.Log("Menu Activated event!"); })
  65. .OnDestruction(() => { Logging.Log("Menu Destroyed event!"); })
  66. .Build();
  67. HandlerBuilder.Builder("menuswitch API debug")
  68. .Handle(EventType.MenuSwitchedTo)
  69. .OnActivation(() => { Logging.Log("Menu Switched To event!"); })
  70. .Build();
  71. HandlerBuilder.Builder("gameact API debug")
  72. .Handle(EventType.Menu)
  73. .OnActivation(() => { Logging.Log("Game Activated event!"); })
  74. .OnDestruction(() => { Logging.Log("Game Destroyed event!"); })
  75. .Build();
  76. HandlerBuilder.Builder("gamerel API debug")
  77. .Handle(EventType.GameReloaded)
  78. .OnActivation(() => { Logging.Log("Game Reloaded event!"); })
  79. .Build();
  80. HandlerBuilder.Builder("gameswitch API debug")
  81. .Handle(EventType.GameSwitchedTo)
  82. .OnActivation(() => { Logging.Log("Game Switched To event!"); })
  83. .Build();
  84. HandlerBuilder.Builder("simulationswitch API debug")
  85. .Handle(EventType.SimulationSwitchedTo)
  86. .OnActivation(() => { Logging.Log("Game Mode Simulation Switched To event!"); })
  87. .Build();
  88. HandlerBuilder.Builder("buildswitch API debug")
  89. .Handle(EventType.BuildSwitchedTo)
  90. .OnActivation(() => { Logging.Log("Game Mode Build Switched To event!"); })
  91. .Build();
  92. HandlerBuilder.Builder("menu activated API error thrower test")
  93. .Handle(EventType.Menu)
  94. .OnActivation(() => { throw new Exception("Event Handler always throws an exception!"); })
  95. .Build();
  96. #pragma warning restore 0612
  97. /*HandlerBuilder.Builder("enter game from menu test")
  98. .Handle(EventType.Menu)
  99. .OnActivation(() =>
  100. {
  101. Tasks.Scheduler.Schedule(new Tasks.Repeatable(enterGame, shouldRetry, 0.2f));
  102. })
  103. .Build();*/
  104. // debug/test commands
  105. if (Dependency.Hell("ExtraCommands"))
  106. {
  107. CommandBuilder.Builder()
  108. .Name("Exit")
  109. .Description("Close Gamecraft immediately, without any prompts")
  110. .Action(() => { UnityEngine.Application.Quit(); })
  111. .Build();
  112. CommandBuilder.Builder()
  113. .Name("SetFOV")
  114. .Description("Set the player camera's field of view")
  115. .Action((float d) => { UnityEngine.Camera.main.fieldOfView = d; })
  116. .Build();
  117. CommandBuilder.Builder()
  118. .Name("MoveLastBlock")
  119. .Description("Move the most-recently-placed block, and any connected blocks by the given offset")
  120. .Action((float x, float y, float z) =>
  121. {
  122. if (GameState.IsBuildMode())
  123. foreach (var block in Block.GetLastPlacedBlock().GetConnectedCubes())
  124. block.Position += new Unity.Mathematics.float3(x, y, z);
  125. else
  126. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  127. }).Build();
  128. CommandBuilder.Builder()
  129. .Name("PlaceAluminium")
  130. .Description("Place a block of aluminium at the given coordinates")
  131. .Action((float x, float y, float z) =>
  132. {
  133. var block = Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x, y, z));
  134. Logging.CommandLog("Block placed with type: " + block.Type);
  135. })
  136. .Build();
  137. CommandBuilder.Builder()
  138. .Name("PlaceAluminiumLots")
  139. .Description("Place a lot of blocks of aluminium at the given coordinates")
  140. .Action((float x, float y, float z) =>
  141. {
  142. Logging.CommandLog("Starting...");
  143. var sw = Stopwatch.StartNew();
  144. for (int i = 0; i < 100; i++)
  145. for (int j = 0; j < 100; j++)
  146. Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x + i, y, z + j));
  147. //Block.Sync();
  148. sw.Stop();
  149. Logging.CommandLog("Finished in " + sw.ElapsedMilliseconds + "ms");
  150. })
  151. .Build();
  152. //With Sync(): 1135ms
  153. //Without Sync(): 134ms
  154. //Async: 348 794ms, doesn't freeze game
  155. //Without Sync() but wait for submission: 530ms
  156. //With Sync() at the end: 380ms
  157. Block b = null;
  158. CommandBuilder.Builder("moveBlockInSim", "Run in build mode first while looking at a block, then in sim to move it up")
  159. .Action(() =>
  160. {
  161. if (b == null)
  162. {
  163. b = new Player(PlayerType.Local).GetBlockLookedAt();
  164. Logging.CommandLog("Block saved: " + b);
  165. }
  166. else
  167. Logging.CommandLog("Block moved to: " + (b.GetSimBody().Position += new float3(0, 2, 0)));
  168. }).Build();
  169. CommandBuilder.Builder("Error", "Throw an error to make sure SimpleCustomCommandEngine's wrapper catches it.")
  170. .Action(() => { throw new Exception("Error Command always throws an error"); })
  171. .Build();
  172. CommandBuilder.Builder("ColorBlock",
  173. "Change color of the block looked at if there's any.")
  174. .Action<string>(str =>
  175. {
  176. if (!Enum.TryParse(str, out BlockColors color))
  177. {
  178. Logging.CommandLog("Color " + str + " not found! Interpreting as 4 color values.");
  179. var s = str.Split(' ');
  180. new Player(PlayerType.Local).GetBlockLookedAt().CustomColor = new float4(float.Parse(s[0]),
  181. float.Parse(s[1]), float.Parse(s[2]), float.Parse(s[3]));
  182. return;
  183. }
  184. new Player(PlayerType.Local).GetBlockLookedAt().Color =
  185. new BlockColor { Color = color };
  186. Logging.CommandLog("Colored block to " + color);
  187. }).Build();
  188. CommandBuilder.Builder("GetBlockByID", "Gets a block based on its object identifier and teleports it up.")
  189. .Action<char>(ch =>
  190. {
  191. foreach (var body in SimBody.GetFromObjectID(ch))
  192. {
  193. Logging.CommandLog("SimBody: " + body);
  194. body.Position += new float3(0, 10, 0);
  195. foreach (var bodyConnectedBody in body.GetConnectedBodies())
  196. {
  197. Logging.CommandLog("Moving " + bodyConnectedBody);
  198. bodyConnectedBody.Position += new float3(0, 10, 0);
  199. }
  200. }
  201. }).Build();
  202. CommandBuilder.Builder()
  203. .Name("PlaceConsole")
  204. .Description("Place a bunch of console block with a given text - entering simulation with them crashes the game as the cmd doesn't exist")
  205. .Action((float x, float y, float z) =>
  206. {
  207. Stopwatch sw = new Stopwatch();
  208. sw.Start();
  209. for (int i = 0; i < 100; i++)
  210. {
  211. for (int j = 0; j < 100; j++)
  212. {
  213. var block = Block.PlaceNew<ConsoleBlock>(BlockIDs.ConsoleBlock,
  214. new float3(x + i, y, z + j));
  215. block.Command = "test_command";
  216. }
  217. }
  218. sw.Stop();
  219. Logging.CommandLog($"Blocks placed in {sw.ElapsedMilliseconds} ms");
  220. })
  221. .Build();
  222. CommandBuilder.Builder()
  223. .Name("WireTest")
  224. .Description("Place two blocks and then wire them together")
  225. .Action(() =>
  226. {
  227. LogicGate notBlock = Block.PlaceNew<LogicGate>(BlockIDs.NOTLogicBlock, new float3(1, 2, 0));
  228. LogicGate andBlock = Block.PlaceNew<LogicGate>(BlockIDs.ANDLogicBlock, new float3(2, 2, 0));
  229. // connect NOT Gate output to AND Gate input #2 (ports are zero-indexed, so 1 is 2nd position and 0 is 1st position)
  230. Wire conn = notBlock.Connect(0, andBlock, 1);
  231. Logging.CommandLog(conn.ToString());
  232. })
  233. .Build();
  234. CommandBuilder.Builder("TestChunkHealth", "Sets the chunk looked at to the given health.")
  235. .Action((float val, float max) =>
  236. {
  237. var body = new Player(PlayerType.Local).GetSimBodyLookedAt();
  238. if (body == null) return;
  239. body.CurrentHealth = val;
  240. body.InitialHealth = max;
  241. Logging.CommandLog("Health set to: " + val);
  242. }).Build();
  243. GameClient.SetDebugInfo("InstalledMods", InstalledMods);
  244. Block.Placed += (sender, args) =>
  245. Logging.MetaDebugLog("Placed block " + args.Type + " with ID " + args.ID);
  246. Block.Removed += (sender, args) =>
  247. Logging.MetaDebugLog("Removed block " + args.Type + " with ID " + args.ID);
  248. /*
  249. CommandManager.AddCommand(new SimpleCustomCommandEngine<float>((float d) => { UnityEngine.Camera.main.fieldOfView = d; },
  250. "SetFOV", "Set the player camera's field of view"));
  251. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  252. (x, y, z) => {
  253. bool success = GamecraftModdingAPI.Blocks.Movement.MoveConnectedBlocks(
  254. GamecraftModdingAPI.Blocks.BlockIdentifiers.LatestBlockID,
  255. new Unity.Mathematics.float3(x, y, z));
  256. if (!success)
  257. {
  258. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  259. }
  260. }, "MoveLastBlock", "Move the most-recently-placed block, and any connected blocks by the given offset"));
  261. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  262. (x, y, z) => { Blocks.Placement.PlaceBlock(Blocks.BlockIDs.AluminiumCube, new Unity.Mathematics.float3(x, y, z)); },
  263. "PlaceAluminium", "Place a block of aluminium at the given coordinates"));
  264. System.Random random = new System.Random(); // for command below
  265. CommandManager.AddCommand(new SimpleCustomCommandEngine(
  266. () => {
  267. if (!GameState.IsSimulationMode())
  268. {
  269. Logging.CommandLogError("You must be in simulation mode for this to work!");
  270. return;
  271. }
  272. Tasks.Repeatable task = new Tasks.Repeatable(() => {
  273. uint count = 0;
  274. EGID[] eBlocks = Blocks.Signals.GetElectricBlocks();
  275. for (uint i = 0u; i < eBlocks.Length; i++)
  276. {
  277. uint[] ids = Blocks.Signals.GetSignalIDs(eBlocks[i]);
  278. for (uint j = 0u; j < ids.Length; j++)
  279. {
  280. Blocks.Signals.SetSignalByID(ids[j], (float)random.NextDouble());
  281. count++;
  282. }
  283. }
  284. Logging.MetaDebugLog($"Did the thing on {count} inputs");
  285. },
  286. () => { return GameState.IsSimulationMode(); });
  287. Tasks.Scheduler.Schedule(task);
  288. }, "RandomizeSignalsInputs", "Do the thing"));
  289. */
  290. }
  291. // dependency test
  292. if (Dependency.Hell("GamecraftScripting", new Version("0.0.1.0")))
  293. {
  294. Logging.LogWarning("You're in GamecraftScripting dependency hell");
  295. }
  296. else
  297. {
  298. Logging.Log("Compatible GamecraftScripting detected");
  299. }
  300. #if TEST
  301. TestRoot.RunTests();
  302. #endif
  303. }
  304. private string modsString;
  305. private string InstalledMods()
  306. {
  307. if (modsString != null) return modsString;
  308. StringBuilder sb = new StringBuilder("Installed mods:");
  309. foreach (var plugin in PluginManager.Plugins)
  310. sb.Append("\n" + plugin.Name + " - " + plugin.Version);
  311. return modsString = sb.ToString();
  312. }
  313. private bool retry = true;
  314. private bool shouldRetry()
  315. {
  316. return retry;
  317. }
  318. private void enterGame()
  319. {
  320. App.Client app = new App.Client();
  321. App.Game[] myGames = app.MyGames;
  322. Logging.MetaDebugLog($"MyGames count {myGames.Length}");
  323. if (myGames.Length != 0)
  324. {
  325. Logging.MetaDebugLog($"MyGames[0] EGID {myGames[0].EGID}");
  326. retry = false;
  327. try
  328. {
  329. //myGames[0].Description = "test msg pls ignore"; // make sure game exists first
  330. Logging.MetaDebugLog($"Entering game {myGames[0].Name}");
  331. myGames[0].EnterGame();
  332. }
  333. catch (Exception e)
  334. {
  335. Logging.MetaDebugLog($"Failed to enter game; exception: {e}");
  336. retry = true;
  337. }
  338. }
  339. else
  340. {
  341. Logging.MetaDebugLog("MyGames not populated yet :(");
  342. }
  343. }
  344. [HarmonyPatch]
  345. public class MinimumSpecsPatch
  346. {
  347. public static bool Prefix()
  348. {
  349. return false;
  350. }
  351. public static MethodInfo TargetMethod()
  352. {
  353. return ((Action) MinimumSpecsCheck.CheckRequirementsMet).Method;
  354. }
  355. }
  356. }
  357. #endif
  358. }