|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415 |
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Reflection;
- using System.Reflection.Emit;
- using System.Text;
-
- using HarmonyLib;
- using IllusionInjector;
- // test
- using GPUInstancer;
- using Svelto.ECS;
- using RobocraftX.Blocks;
- using RobocraftX.Common;
- using RobocraftX.SimulationModeState;
- using RobocraftX.FrontEnd;
- using Unity.Mathematics;
- using UnityEngine;
-
- using GamecraftModdingAPI.Commands;
- using GamecraftModdingAPI.Events;
- using GamecraftModdingAPI.Utility;
- using GamecraftModdingAPI.Blocks;
- using GamecraftModdingAPI.Players;
- using EventType = GamecraftModdingAPI.Events.EventType;
-
- namespace GamecraftModdingAPI.Tests
- {
- #if DEBUG
- // unused by design
- /// <summary>
- /// Modding API implemented as a standalone IPA Plugin.
- /// Ideally, GamecraftModdingAPI should be loaded by another mod; not itself
- /// </summary>
- public class GamecraftModdingAPIPluginTest : IllusionPlugin.IEnhancedPlugin
- {
-
- private static Harmony harmony { get; set; }
-
- public override string Name { get; } = Assembly.GetExecutingAssembly().GetName().Name;
-
- public override string Version { get; } = Assembly.GetExecutingAssembly().GetName().Version.ToString();
-
- public string HarmonyID { get; } = "org.git.exmods.modtainers.gamecraftmoddingapi";
-
- public override void OnApplicationQuit()
- {
- GamecraftModdingAPI.Main.Shutdown();
- }
-
- public override void OnApplicationStart()
- {
- FileLog.Reset();
- Harmony.DEBUG = true;
- GamecraftModdingAPI.Main.Init();
- Logging.MetaDebugLog($"Version group id {(uint)ApiExclusiveGroups.versionGroup}");
- // in case Steam is not installed/running
- // this will crash the game slightly later during startup
- //SteamInitPatch.ForcePassSteamCheck = true;
- // in case running in a VM
- //MinimumSpecsCheckPatch.ForcePassMinimumSpecCheck = true;
- // disable some Gamecraft analytics
- //AnalyticsDisablerPatch.DisableAnalytics = true;
- // disable background music
- Logging.MetaDebugLog("Audio Mixers: " + string.Join(",", AudioTools.GetMixers()));
- //AudioTools.SetVolume(0.0f, "Music"); // The game now sets this from settings again after this is called :(
-
- //Utility.VersionTracking.Enable();//(very) unstable
-
- // debug/test handlers
- #pragma warning disable 0612
- HandlerBuilder.Builder()
- .Name("appinit API debug")
- .Handle(EventType.ApplicationInitialized)
- .OnActivation(() => { Logging.Log("App Inited event!"); })
- .Build();
-
- HandlerBuilder.Builder("menuact API debug")
- .Handle(EventType.Menu)
- .OnActivation(() => { Logging.Log("Menu Activated event!"); })
- .OnDestruction(() => { Logging.Log("Menu Destroyed event!"); })
- .Build();
-
- HandlerBuilder.Builder("menuswitch API debug")
- .Handle(EventType.MenuSwitchedTo)
- .OnActivation(() => { Logging.Log("Menu Switched To event!"); })
- .Build();
-
- HandlerBuilder.Builder("gameact API debug")
- .Handle(EventType.Menu)
- .OnActivation(() => { Logging.Log("Game Activated event!"); })
- .OnDestruction(() => { Logging.Log("Game Destroyed event!"); })
- .Build();
-
- HandlerBuilder.Builder("gamerel API debug")
- .Handle(EventType.GameReloaded)
- .OnActivation(() => { Logging.Log("Game Reloaded event!"); })
- .Build();
-
- HandlerBuilder.Builder("gameswitch API debug")
- .Handle(EventType.GameSwitchedTo)
- .OnActivation(() => { Logging.Log("Game Switched To event!"); })
- .Build();
-
- HandlerBuilder.Builder("simulationswitch API debug")
- .Handle(EventType.SimulationSwitchedTo)
- .OnActivation(() => { Logging.Log("Game Mode Simulation Switched To event!"); })
- .Build();
-
- HandlerBuilder.Builder("buildswitch API debug")
- .Handle(EventType.BuildSwitchedTo)
- .OnActivation(() => { Logging.Log("Game Mode Build Switched To event!"); })
- .Build();
-
- HandlerBuilder.Builder("menu activated API error thrower test")
- .Handle(EventType.Menu)
- .OnActivation(() => { throw new Exception("Event Handler always throws an exception!"); })
- .Build();
- #pragma warning restore 0612
- /*HandlerBuilder.Builder("enter game from menu test")
- .Handle(EventType.Menu)
- .OnActivation(() =>
- {
- Tasks.Scheduler.Schedule(new Tasks.Repeatable(enterGame, shouldRetry, 0.2f));
- })
- .Build();*/
-
- // debug/test commands
- if (Dependency.Hell("ExtraCommands"))
- {
- CommandBuilder.Builder()
- .Name("Exit")
- .Description("Close Gamecraft immediately, without any prompts")
- .Action(() => { UnityEngine.Application.Quit(); })
- .Build();
-
- CommandBuilder.Builder()
- .Name("SetFOV")
- .Description("Set the player camera's field of view")
- .Action((float d) => { UnityEngine.Camera.main.fieldOfView = d; })
- .Build();
-
- CommandBuilder.Builder()
- .Name("MoveLastBlock")
- .Description("Move the most-recently-placed block, and any connected blocks by the given offset")
- .Action((float x, float y, float z) =>
- {
- if (GameState.IsBuildMode())
- foreach (var block in Block.GetLastPlacedBlock().GetConnectedCubes())
- block.Position += new Unity.Mathematics.float3(x, y, z);
- else
- GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
- }).Build();
-
- CommandBuilder.Builder()
- .Name("PlaceAluminium")
- .Description("Place a block of aluminium at the given coordinates")
- .Action((float x, float y, float z) =>
- {
- var block = Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x, y, z));
- Logging.CommandLog("Block placed with type: " + block.Type);
- })
- .Build();
-
- CommandBuilder.Builder()
- .Name("PlaceAluminiumLots")
- .Description("Place a lot of blocks of aluminium at the given coordinates")
- .Action((float x, float y, float z) =>
- {
- Logging.CommandLog("Starting...");
- var sw = Stopwatch.StartNew();
- for (int i = 0; i < 100; i++)
- for (int j = 0; j < 100; j++)
- Block.PlaceNew(BlockIDs.AluminiumCube, new float3(x + i, y, z + j));
- //Block.Sync();
- sw.Stop();
- Logging.CommandLog("Finished in " + sw.ElapsedMilliseconds + "ms");
- })
- .Build();
-
- Block b = null;
- CommandBuilder.Builder("moveBlockInSim", "Run in build mode first while looking at a block, then in sim to move it up")
- .Action(() =>
- {
- if (b == null)
- {
- b = new Player(PlayerType.Local).GetBlockLookedAt();
- Logging.CommandLog("Block saved: " + b);
- }
- else
- Logging.CommandLog("Block moved to: " + (b.GetSimBody().Position += new float3(0, 2, 0)));
- }).Build();
-
- CommandBuilder.Builder("Error", "Throw an error to make sure SimpleCustomCommandEngine's wrapper catches it.")
- .Action(() => { throw new Exception("Error Command always throws an error"); })
- .Build();
-
- CommandBuilder.Builder("ColorBlock",
- "Change color of the block looked at if there's any.")
- .Action<string>(str =>
- {
- if (!Enum.TryParse(str, out BlockColors color))
- {
- Logging.CommandLog("Color " + str + " not found! Interpreting as 4 color values.");
- var s = str.Split(' ');
- new Player(PlayerType.Local).GetBlockLookedAt().CustomColor = new float4(float.Parse(s[0]),
- float.Parse(s[1]), float.Parse(s[2]), float.Parse(s[3]));
- return;
- }
- new Player(PlayerType.Local).GetBlockLookedAt().Color =
- new BlockColor { Color = color };
- Logging.CommandLog("Colored block to " + color);
-
- }).Build();
-
- CommandBuilder.Builder("GetBlockByID", "Gets a block based on its object identifier and teleports it up.")
- .Action<char>(ch =>
- {
- foreach (var body in SimBody.GetFromObjectID(ch))
- {
- Logging.CommandLog("SimBody: " + body);
- body.Position += new float3(0, 10, 0);
- foreach (var bodyConnectedBody in body.GetConnectedBodies())
- {
- Logging.CommandLog("Moving " + bodyConnectedBody);
- bodyConnectedBody.Position += new float3(0, 10, 0);
- }
- }
- }).Build();
-
- CommandBuilder.Builder()
- .Name("PlaceConsole")
- .Description("Place a bunch of console block with a given text - entering simulation with them crashes the game as the cmd doesn't exist")
- .Action((float x, float y, float z) =>
- {
- Stopwatch sw = new Stopwatch();
- sw.Start();
- for (int i = 0; i < 100; i++)
- {
- for (int j = 0; j < 100; j++)
- {
- var block = Block.PlaceNew<ConsoleBlock>(BlockIDs.ConsoleBlock,
- new float3(x + i, y, z + j));
- block.Command = "test_command";
- }
- }
-
- sw.Stop();
- Logging.CommandLog($"Blocks placed in {sw.ElapsedMilliseconds} ms");
- })
- .Build();
-
- CommandBuilder.Builder()
- .Name("WireTest")
- .Description("Place two blocks and then wire them together")
- .Action(() =>
- {
- LogicGate notBlock = Block.PlaceNew<LogicGate>(BlockIDs.NOTLogicBlock, new float3(1, 2, 0));
- LogicGate andBlock = Block.PlaceNew<LogicGate>(BlockIDs.ANDLogicBlock, new float3(2, 2, 0));
- // connect NOT Gate output to AND Gate input #2 (ports are zero-indexed, so 1 is 2nd position and 0 is 1st position)
- Wire conn = notBlock.Connect(0, andBlock, 1);
- Logging.CommandLog(conn.ToString());
- })
- .Build();
-
- CommandBuilder.Builder("TestChunkHealth", "Sets the chunk looked at to the given health.")
- .Action((float val, float max) =>
- {
- var body = new Player(PlayerType.Local).GetSimBodyLookedAt();
- if (body == null) return;
- body.CurrentHealth = val;
- body.InitialHealth = max;
- Logging.CommandLog("Health set to: " + val);
- }).Build();
-
- CommandBuilder.Builder("placeBlockGroup", "Places some blocks in a group")
- .Action((float x, float y, float z) =>
- {
- var pos = new float3(x, y, z);
- var group = BlockGroup.Create(Block.PlaceNew(BlockIDs.AluminiumCube, pos,
- color: BlockColors.Aqua));
- Block.PlaceNew(BlockIDs.AluminiumCube, pos += new float3(1, 0, 0), color: BlockColors.Blue)
- .BlockGroup = group;
- Block.PlaceNew(BlockIDs.AluminiumCube, pos += new float3(1, 0, 0), color: BlockColors.Green)
- .BlockGroup = group;
- Block.PlaceNew(BlockIDs.AluminiumCube, pos += new float3(1, 0, 0), color: BlockColors.Lime)
- .BlockGroup = group;
- }).Build();
-
- GameClient.SetDebugInfo("InstalledMods", InstalledMods);
- Block.Placed += (sender, args) =>
- Logging.MetaDebugLog("Placed block " + args.Type + " with ID " + args.ID);
- Block.Removed += (sender, args) =>
- Logging.MetaDebugLog("Removed block " + args.Type + " with ID " + args.ID);
-
- /*
- CommandManager.AddCommand(new SimpleCustomCommandEngine<float>((float d) => { UnityEngine.Camera.main.fieldOfView = d; },
- "SetFOV", "Set the player camera's field of view"));
- CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
- (x, y, z) => {
- bool success = GamecraftModdingAPI.Blocks.Movement.MoveConnectedBlocks(
- GamecraftModdingAPI.Blocks.BlockIdentifiers.LatestBlockID,
- new Unity.Mathematics.float3(x, y, z));
- if (!success)
- {
- GamecraftModdingAPI.Utility.Logging.CommandLogError("Blocks can only be moved in Build mode!");
- }
- }, "MoveLastBlock", "Move the most-recently-placed block, and any connected blocks by the given offset"));
- CommandManager.AddCommand(new SimpleCustomCommandEngine<float, float, float>(
- (x, y, z) => { Blocks.Placement.PlaceBlock(Blocks.BlockIDs.AluminiumCube, new Unity.Mathematics.float3(x, y, z)); },
- "PlaceAluminium", "Place a block of aluminium at the given coordinates"));
- System.Random random = new System.Random(); // for command below
- CommandManager.AddCommand(new SimpleCustomCommandEngine(
- () => {
- if (!GameState.IsSimulationMode())
- {
- Logging.CommandLogError("You must be in simulation mode for this to work!");
- return;
- }
- Tasks.Repeatable task = new Tasks.Repeatable(() => {
- uint count = 0;
- EGID[] eBlocks = Blocks.Signals.GetElectricBlocks();
- for (uint i = 0u; i < eBlocks.Length; i++)
- {
- uint[] ids = Blocks.Signals.GetSignalIDs(eBlocks[i]);
- for (uint j = 0u; j < ids.Length; j++)
- {
- Blocks.Signals.SetSignalByID(ids[j], (float)random.NextDouble());
- count++;
- }
- }
- Logging.MetaDebugLog($"Did the thing on {count} inputs");
- },
- () => { return GameState.IsSimulationMode(); });
- Tasks.Scheduler.Schedule(task);
- }, "RandomizeSignalsInputs", "Do the thing"));
- */
- }
-
- // dependency test
- if (Dependency.Hell("GamecraftScripting", new Version("0.0.1.0")))
- {
- Logging.LogWarning("You're in GamecraftScripting dependency hell");
- }
- else
- {
- Logging.Log("Compatible GamecraftScripting detected");
- }
-
- #if TEST
- TestRoot.RunTests();
- #endif
- }
-
- private string modsString;
- private string InstalledMods()
- {
- if (modsString != null) return modsString;
- StringBuilder sb = new StringBuilder("Installed mods:");
- foreach (var plugin in PluginManager.Plugins)
- sb.Append("\n" + plugin.Name + " - " + plugin.Version);
- return modsString = sb.ToString();
- }
-
- private bool retry = true;
-
- private bool shouldRetry()
- {
- return retry;
- }
-
- private void enterGame()
- {
- App.Client app = new App.Client();
- App.Game[] myGames = app.MyGames;
- Logging.MetaDebugLog($"MyGames count {myGames.Length}");
- if (myGames.Length != 0)
- {
- Logging.MetaDebugLog($"MyGames[0] EGID {myGames[0].EGID}");
- retry = false;
- try
- {
- //myGames[0].Description = "test msg pls ignore"; // make sure game exists first
- Logging.MetaDebugLog($"Entering game {myGames[0].Name}");
- myGames[0].EnterGame();
- }
- catch (Exception e)
- {
- Logging.MetaDebugLog($"Failed to enter game; exception: {e}");
- retry = true;
- }
- }
- else
- {
- Logging.MetaDebugLog("MyGames not populated yet :(");
- }
- }
-
- [HarmonyPatch]
- public class MinimumSpecsPatch
- {
- public static bool Prefix()
- {
- return false;
- }
-
- public static MethodInfo TargetMethod()
- {
- return ((Action) MinimumSpecsCheck.CheckRequirementsMet).Method;
- }
- }
- }
- #endif
- }
|