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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. // unused by design
  23. /// <summary>
  24. /// Modding API implemented as a standalone IPA Plugin.
  25. /// Ideally, GamecraftModdingAPI should be loaded by another mod; not itself
  26. /// </summary>
  27. public class GamecraftModdingAPIPluginTest
  28. #if DEBUG
  29. : IllusionPlugin.IEnhancedPlugin
  30. #endif
  31. {
  32. private static Harmony harmony { get; set; }
  33. public string[] Filter { get; } = new string[] { "Gamecraft", "GamecraftPreview" };
  34. public string Name { get; } = Assembly.GetExecutingAssembly().GetName().Name;
  35. public string Version { get; } = Assembly.GetExecutingAssembly().GetName().Version.ToString();
  36. public string HarmonyID { get; } = "org.git.exmods.modtainers.gamecraftmoddingapi";
  37. public void OnApplicationQuit()
  38. {
  39. GamecraftModdingAPI.Main.Shutdown();
  40. }
  41. public void OnApplicationStart()
  42. {
  43. FileLog.Reset();
  44. Harmony.DEBUG = true;
  45. GamecraftModdingAPI.Main.Init();
  46. Logging.MetaDebugLog($"Version group id {(uint)ApiExclusiveGroups.versionGroup}");
  47. // in case Steam is not installed/running
  48. // this will crash the game slightly later during startup
  49. //SteamInitPatch.ForcePassSteamCheck = true;
  50. // in case running in a VM
  51. //MinimumSpecsCheckPatch.ForcePassMinimumSpecCheck = true;
  52. // disable some Gamecraft analytics
  53. //AnalyticsDisablerPatch.DisableAnalytics = true;
  54. // disable background music
  55. Logging.MetaDebugLog("Audio Mixers: "+string.Join(",", AudioTools.GetMixers()));
  56. //AudioTools.SetVolume(0.0f, "Music"); // The game now sets this from settings again after this is called :(
  57. //Utility.VersionTracking.Enable();//(very) unstable
  58. // debug/test handlers
  59. HandlerBuilder.Builder()
  60. .Name("appinit API debug")
  61. .Handle(EventType.ApplicationInitialized)
  62. .OnActivation(() => { Logging.Log("App Inited event!"); })
  63. .Build();
  64. HandlerBuilder.Builder("menuact API debug")
  65. .Handle(EventType.Menu)
  66. .OnActivation(() => { Logging.Log("Menu Activated event!"); })
  67. .OnDestruction(() => { Logging.Log("Menu Destroyed event!"); })
  68. .Build();
  69. HandlerBuilder.Builder("menuswitch API debug")
  70. .Handle(EventType.MenuSwitchedTo)
  71. .OnActivation(() => { Logging.Log("Menu Switched To event!"); })
  72. .Build();
  73. HandlerBuilder.Builder("gameact API debug")
  74. .Handle(EventType.Menu)
  75. .OnActivation(() => { Logging.Log("Game Activated event!"); })
  76. .OnDestruction(() => { Logging.Log("Game Destroyed event!"); })
  77. .Build();
  78. HandlerBuilder.Builder("gamerel API debug")
  79. .Handle(EventType.GameReloaded)
  80. .OnActivation(() => { Logging.Log("Game Reloaded event!"); })
  81. .Build();
  82. HandlerBuilder.Builder("gameswitch API debug")
  83. .Handle(EventType.GameSwitchedTo)
  84. .OnActivation(() => { Logging.Log("Game Switched To event!"); })
  85. .Build();
  86. HandlerBuilder.Builder("simulationswitch API debug")
  87. .Handle(EventType.SimulationSwitchedTo)
  88. .OnActivation(() => { Logging.Log("Game Mode Simulation Switched To event!"); })
  89. .Build();
  90. HandlerBuilder.Builder("buildswitch API debug")
  91. .Handle(EventType.BuildSwitchedTo)
  92. .OnActivation(() => { Logging.Log("Game Mode Build Switched To event!"); })
  93. .Build();
  94. HandlerBuilder.Builder("menu activated API error thrower test")
  95. .Handle(EventType.Menu)
  96. .OnActivation(() => { throw new Exception("Event Handler always throws an exception!"); })
  97. .Build();
  98. // debug/test commands
  99. if (Dependency.Hell("ExtraCommands"))
  100. {
  101. CommandBuilder.Builder()
  102. .Name("Exit")
  103. .Description("Close Gamecraft immediately, without any prompts")
  104. .Action(() => { UnityEngine.Application.Quit(); })
  105. .Build();
  106. CommandBuilder.Builder()
  107. .Name("SetFOV")
  108. .Description("Set the player camera's field of view")
  109. .Action((float d) => { UnityEngine.Camera.main.fieldOfView = d; })
  110. .Build();
  111. CommandBuilder.Builder()
  112. .Name("MoveLastBlock")
  113. .Description("Move the most-recently-placed block, and any connected blocks by the given offset")
  114. .Action((float x, float y, float z) =>
  115. {
  116. if (GameState.IsBuildMode())
  117. foreach (var block in Block.GetLastPlacedBlock().GetConnectedCubes())
  118. block.Position += new Unity.Mathematics.float3(x, y, z);
  119. else
  120. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  121. }).Build();
  122. CommandBuilder.Builder()
  123. .Name("PlaceAluminium")
  124. .Description("Place a block of aluminium at the given coordinates")
  125. .Action((float x, float y, float z) =>
  126. {
  127. var block = Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x, y, z));
  128. Logging.CommandLog("Block placed with type: " + block.Type);
  129. })
  130. .Build();
  131. CommandBuilder.Builder()
  132. .Name("PlaceAluminiumLots")
  133. .Description("Place a lot of blocks of aluminium at the given coordinates")
  134. .Action((float x, float y, float z) =>
  135. {
  136. Logging.CommandLog("Starting...");
  137. var sw = Stopwatch.StartNew();
  138. for (int i = 0; i < 100; i++)
  139. for (int j = 0; j < 100; j++)
  140. Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x + i, y, z + j));
  141. //Block.Sync();
  142. sw.Stop();
  143. Logging.CommandLog("Finished in " + sw.ElapsedMilliseconds + "ms");
  144. })
  145. .Build();
  146. //With Sync(): 1135ms
  147. //Without Sync(): 134ms
  148. //Async: 348 794ms, doesn't freeze game
  149. //Without Sync() but wait for submission: 530ms
  150. //With Sync() at the end: 380ms
  151. Block b = null;
  152. CommandBuilder.Builder("moveBlockInSim", "Run in build mode first while looking at a block, then in sim to move it up")
  153. .Action(() =>
  154. {
  155. if (b == null)
  156. {
  157. b = new Player(PlayerType.Local).GetBlockLookedAt();
  158. Logging.CommandLog("Block saved: " + b);
  159. }
  160. else
  161. Logging.CommandLog("Block moved to: " + (b.GetSimBody().Position += new float3(0, 2, 0)));
  162. }).Build();
  163. CommandBuilder.Builder("Error", "Throw an error to make sure SimpleCustomCommandEngine's wrapper catches it.")
  164. .Action(() => { throw new Exception("Error Command always throws an error"); })
  165. .Build();
  166. CommandBuilder.Builder("ColorBlock",
  167. "Change color of the block looked at if there's any.")
  168. .Action<string>(str =>
  169. {
  170. if (!Enum.TryParse(str, out BlockColors color))
  171. {
  172. Logging.CommandLog("Color " + str + " not found! Interpreting as 4 color values.");
  173. var s = str.Split(' ');
  174. new Player(PlayerType.Local).GetBlockLookedAt().CustomColor = new float4(float.Parse(s[0]),
  175. float.Parse(s[1]), float.Parse(s[2]), float.Parse(s[3]));
  176. return;
  177. }
  178. new Player(PlayerType.Local).GetBlockLookedAt().Color =
  179. new BlockColor {Color = color};
  180. Logging.CommandLog("Colored block to " + color);
  181. }).Build();
  182. CommandBuilder.Builder("GetBlockByID", "Gets a block based on its object identifier and teleports it up.")
  183. .Action<char>(ch =>
  184. {
  185. foreach (var body in SimBody.GetFromObjectID(ch))
  186. {
  187. Logging.CommandLog("SimBody: " + body);
  188. body.Position += new float3(0, 10, 0);
  189. foreach (var bodyConnectedBody in body.GetConnectedBodies())
  190. {
  191. Logging.CommandLog("Moving " + bodyConnectedBody);
  192. bodyConnectedBody.Position += new float3(0, 10, 0);
  193. }
  194. }
  195. }).Build();
  196. GameClient.SetDebugInfo("lookedAt", LookedAt);
  197. GameClient.SetDebugInfo("InstalledMods", InstalledMods);
  198. /*
  199. CommandManager.AddCommand(new SimpleCustomCommandEngine<float>((float d) => { UnityEngine.Camera.main.fieldOfView = d; },
  200. "SetFOV", "Set the player camera's field of view"));
  201. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  202. (x, y, z) => {
  203. bool success = GamecraftModdingAPI.Blocks.Movement.MoveConnectedBlocks(
  204. GamecraftModdingAPI.Blocks.BlockIdentifiers.LatestBlockID,
  205. new Unity.Mathematics.float3(x, y, z));
  206. if (!success)
  207. {
  208. GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
  209. }
  210. }, "MoveLastBlock", "Move the most-recently-placed block, and any connected blocks by the given offset"));
  211. CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
  212. (x, y, z) => { Blocks.Placement.PlaceBlock(Blocks.BlockIDs.AluminiumCube, new Unity.Mathematics.float3(x, y, z)); },
  213. "PlaceAluminium", "Place a block of aluminium at the given coordinates"));
  214. System.Random random = new System.Random(); // for command below
  215. CommandManager.AddCommand(new SimpleCustomCommandEngine(
  216. () => {
  217. if (!GameState.IsSimulationMode())
  218. {
  219. Logging.CommandLogError("You must be in simulation mode for this to work!");
  220. return;
  221. }
  222. Tasks.Repeatable task = new Tasks.Repeatable(() => {
  223. uint count = 0;
  224. EGID[] eBlocks = Blocks.Signals.GetElectricBlocks();
  225. for (uint i = 0u; i < eBlocks.Length; i++)
  226. {
  227. uint[] ids = Blocks.Signals.GetSignalIDs(eBlocks[i]);
  228. for (uint j = 0u; j < ids.Length; j++)
  229. {
  230. Blocks.Signals.SetSignalByID(ids[j], (float)random.NextDouble());
  231. count++;
  232. }
  233. }
  234. Logging.MetaDebugLog($"Did the thing on {count} inputs");
  235. },
  236. () => { return GameState.IsSimulationMode(); });
  237. Tasks.Scheduler.Schedule(task);
  238. }, "RandomizeSignalsInputs", "Do the thing"));
  239. */
  240. }
  241. // dependency test
  242. if (Dependency.Hell("GamecraftScripting", new Version("0.0.1.0")))
  243. {
  244. Logging.LogWarning("You're in GamecraftScripting dependency hell");
  245. }
  246. else
  247. {
  248. Logging.Log("Compatible GamecraftScripting detected");
  249. }
  250. }
  251. private Player player;
  252. private string LookedAt()
  253. {
  254. if (player == null)
  255. player = new Player(PlayerType.Local);
  256. if (GameState.IsBuildMode())
  257. {
  258. Block block = player.GetBlockLookedAt();
  259. if (block == null) return "Block: none";
  260. return "Block: " + block.Type + "\nColor: " + block.Color + "\n" + "At: " + block.Position
  261. + "\nText: " + block.Label;
  262. }
  263. if (GameState.IsSimulationMode())
  264. {
  265. SimBody body = player.GetSimBodyLookedAt();
  266. if (body == null) return "Body: none";
  267. return "Body: " + (body.Static ? "static" : "non-static")
  268. + "\nAt: " + body.Position + " - rotated: " + body.Rotation
  269. + "\nWith mass: " + body.Mass + " - center: " + body.CenterOfMass
  270. + "\nVelocity: " + body.Velocity + " - angular: " + body.AngularVelocity;
  271. }
  272. return "Switching modes...";
  273. }
  274. private string modsString;
  275. private string InstalledMods()
  276. {
  277. if (modsString != null) return modsString;
  278. StringBuilder sb = new StringBuilder("Installed mods:");
  279. foreach (var plugin in PluginManager.Plugins)
  280. sb.Append("\n" + plugin.Name + " - " + plugin.Version);
  281. return modsString = sb.ToString();
  282. }
  283. public void OnFixedUpdate() { }
  284. public void OnLateUpdate() { }
  285. public void OnLevelWasInitialized(int level) { }
  286. public void OnLevelWasLoaded(int level) { }
  287. public void OnUpdate() { }
  288. [HarmonyPatch]
  289. public class MinimumSpecsPatch
  290. {
  291. public static bool Prefix(ref bool __result)
  292. {
  293. __result = true;
  294. return false;
  295. }
  296. public static MethodInfo TargetMethod()
  297. {
  298. return ((Func<bool>)MinimumSpecsCheck.CheckRequirementsMet).Method;
  299. }
  300. }
  301. }
  302. }