public static IEnumerable <Mod> SearchForCircularReferences(IEnumerable <Mod> mods) { Dictionary <string, Mod> modsByPackage = mods.ToDictionary(o => o.PackageName); List <KeyValuePair <Mod, Mod> > warned = new List <KeyValuePair <Mod, Mod> >(); foreach (var item in mods) { var match = item.RequiredModPackages.SingleOrDefault(o => modsByPackage.TryGetValue(o, out var m) && m.RequiredModPackages.Contains(item.PackageName)); if (match != null) { var second = modsByPackage[match]; if (!warned.Any(o => (o.Key.PackageName == item.PackageName && o.Value.PackageName == second.PackageName) || (o.Key.PackageName == second.PackageName && o.Value.PackageName == item.PackageName))) { warned.Add(new KeyValuePair <Mod, Mod>(item, second)); IGConsole.Error($"Circular reference found between <b>{item.Name}</b> and <b>{second.Name}</b>, neither were loaded."); } } else { yield return(item); } } }
private static GameObject MakePlayerModel() { if (PlayerModelPrefab == null) { //Load model on Unity's main thread MulTUNG.SynchronizationContext.Send(_ => BuildPlayerPrefab(), null); //Check if the prefab is still null if (PlayerModelPrefab == null) { IGConsole.Error("Couldn't load player model!"); return(null); } } //Create a new parent object that will contain the model GameObject player = new GameObject("Remote Player"); GameObject newModel = GameObject.Instantiate(PlayerModelPrefab, player.transform); newModel.SetActive(true); //Offset its local position by half of the model height newModel.transform.localPosition = new Vector3(0, -1.65f / 2, 0); return(player); }
static bool Prefix() { watch = new Stopwatch(); watch.Start(); if (legacySave) { return(true); } if (!File.Exists(GetVanillaSave())) { return(true); } PlayerPosition player = GetPlayerPosition(); Datum[] data = GetDatumsToSave(); FileStream fs = new FileStream(GetSavePath(), FileMode.Create); BinaryFormatter formatter = new BinaryFormatter(); try { formatter.Serialize(fs, player); formatter.Serialize(fs, data); } catch (Exception e) { IGConsole.Error($"Saving failed with {e.ToString()}"); } finally { fs.Close(); } return(false); }
public override bool Execute(IEnumerable <string> arguments) { if (MyMod.SetUpdateRate == null) { IGConsole.Error("This command can only be used while in-game!"); return(true); } if (!arguments.Any()) { IGConsole.Log($"<b>Current update rate:</b> {MyMod.CurrentUpdateRate} tps"); return(true); } string arg = arguments.First(); if (float.TryParse(arg, out float num)) { MyMod.SetUpdateRate(num); return(true); } else { IGConsole.Error("tps must be a decimal number"); } return(false); }
public static IEnumerable <Mod> Order(IEnumerable <Mod> mods) { mods = SearchForCircularReferences(mods).ToList(); Dictionary <string, Mod> modsByPackage = mods.ToDictionary(o => o.PackageName); List <Mod> ret = new List <Mod>(); foreach (var item in mods) { Push(item); } ret.AddRange(mods.Where(o => !ret.Contains(o))); return(ret); void Push(Mod mod) { bool exit = true; foreach (var item in mod.RequiredModPackages) { if (!modsByPackage.TryGetValue(item, out var req)) { IGConsole.Error($"Mod {mod.Name} requires mod {item}"); exit = true; } if (req != null && !exit && !ret.Contains(req)) { ret.Add(req); } } } }
public override bool Execute(IEnumerable <string> arguments) { if (arguments.Count() != 1) { IGConsole.Error("Usage: find component_name"); return(false); } Assembly asm = typeof(UnityEngine.Object).Assembly; Type componentType = asm.GetType($"UnityEngine.{arguments.ElementAt(0)}"); if (componentType == null) { IGConsole.Error($"{arguments.ElementAt(0)} is not a type"); return(false); } if (!componentType.IsSubclassOf(typeof(Component))) { IGConsole.Error($"{arguments.ElementAt(0)} is not a Component"); return(false); } Component[] matches = (Component[])GameObject.FindObjectsOfType(componentType); foreach (Component component in matches) { IGConsole.Log($"\"{component.name}\" is at {component.transform.position}"); } return(true); }
public override bool Execute(IEnumerable <string> arguments) { if (SceneManager.GetActiveScene().name != "gameplay") { IGConsole.Error("Only usable on gameplay"); return(false); } placer.Board(4, 4, new Vector3(0f, 1f, 0f), Quaternion.identity); return(true); }
private void OnPlayerIDAttribution(PlayerIDAttribution packet) { if (ID.HasValue) { IGConsole.Error("Received unexpected IDAttribution"); return; } ID = packet.ID; IGConsole.Log($"ID set to {ID.Value}"); SendPacket(new IDAttibutionACK()); }
public override bool Execute(IEnumerable <string> arguments) { if (SceneManager.GetActiveScene().name != "gameplay") { IGConsole.Error("Not currently in a world"); return(false); } legacySave = true; SaveManager.SaveAll(); return(true); }
private static void Connect(string address, int port) { if (connection != null && connection.Status == Status.Connected) { IGConsole.Error("Already connected, disconnect first"); return; } IGConsole.Log($"Connecting to {address}:{port}"); connection = new ClientConnection(address, port); if (!Directory.Exists(savesPath)) { Directory.CreateDirectory(savesPath); } DeleteSave(); SaveManager.SaveName = "multiplayer/_"; SceneManager.LoadScene("gameplay"); }
public override bool Execute(IEnumerable <string> arguments) { if (arguments.Count() != 1) { IGConsole.Error("Usage: connect host[:port]"); return(false); } string[] parts = arguments.ElementAt(0).Split(':'); int port = 4545; if (parts.Length > 1) { port = Int32.Parse(parts[1]); } Connect(parts[0], port); return(true); }
private void GameplayInit(Scene arg0, Scene arg1) { if (SceneManager.GetActiveScene().name != "gameplay") { return; } SceneManager.activeSceneChanged -= GameplayInit; inGameplay = true; GameObject playerObject = GameObject.Find("FirstPersonCharacter"); if (playerObject == null) { IGConsole.Error("Could not find player object"); return; } player = playerObject.transform; SceneManager.activeSceneChanged += DisconnectOnLeave; }
public void HandlePackets() { while (receiveQueue.Count > 0) { Packet packet = receiveQueue.Dequeue(); try { OnPacketReceived(packet); } catch (Exception e) { IGConsole.Error(e.ToString()); } } if (inGameplay) { SyncPlayerPos(); } }
public override bool Execute(IEnumerable <string> arguments) { if (arguments.Count() == 0) { IGConsole.Error("Usage: findobj name"); return(false); } string name = string.Join(" ", arguments.ToArray()); GameObject found = GameObject.Find(name); if (found != null) { IGConsole.Log($"{found.name} found at {found.transform.position}"); } else { IGConsole.Error("Object not found"); } return(true); }
private void ReceiveThread() { IGConsole.Log("Starting receiver thread"); while (status != Status.Disconnected) { if (client.Available > 0) { try { BinaryFormatter formatter = new BinaryFormatter(); Packet packet = formatter.Deserialize(client.GetStream()) as Packet; receiveQueue.Enqueue(packet); } catch (Exception e) { IGConsole.Error(e.ToString()); } } Thread.Sleep(30); } IGConsole.Log("Receiver thread stopped"); }
/// <summary> /// Search for mods on <see cref="ModsDirectory"/>. /// </summary> /// <returns>Mods.</returns> public static IEnumerable <Mod> GetMods() { if (!Directory.Exists(ModsDirectory)) { Directory.CreateDirectory(ModsDirectory); } foreach (var item in Directory.GetFiles(ModsDirectory, "*.dll")) { if (Path.GetFileNameWithoutExtension(item).EndsWith("-disabled")) { continue; } Mod mod = null; try { mod = GetMod(item); } catch (Exception ex) { string name = Path.GetFileNameWithoutExtension(item); MDebug.WriteLine($"[ERROR] Mod {name} failed to load."); MDebug.WriteLine("More details:\n" + ex, 2); IGConsole.Error($"Failed to load mod {name}."); } mod.RequiredModPackages = mod.GetType().GetCustomAttributes(false) .OfType <RequireModAttribute>() .Select(o => o.ModPackage) .ToArray(); if (mod != null) { yield return(mod); } } }
private void OpenFile() { if (!File.Exists(FilePath)) { IGConsole.Error($"Couldn't find file at '{FilePath}'."); SoundPlayer.PlaySoundGlobal(Sounds.FailDoSomething); return; } Data = new BitArray(File.ReadAllBytes(FilePath)); if (BigEndian) { Data = new BitArray(Data .Cast <bool>() .Select((x, i) => new { Index = i, Value = x }) .GroupBy(x => x.Index / 8) .Select(x => x.Select(v => v.Value).Reverse().ToList()) .SelectMany(o => o) .ToArray()); } }
private void Init() { if (boardPlacer != null) { return; } boardPlacer = GameObject.FindObjectOfType <BoardPlacer>(); if (!boardPlacer) { IGConsole.Error("Could not find BoardPlacer"); return; } IGConsole.Log("Board placer found"); _SetChildCircuitsMegaMeshStatus = boardPlacer.GetType() .GetMethod("SetChildCircuitsMegaMeshStatus", BindingFlags.NonPublic | BindingFlags.Instance); if (_SetChildCircuitsMegaMeshStatus == null) { IGConsole.Error("Could not get SCCMMS method"); return; } IGConsole.Log("Got SCCMMS method"); }
private void SendThread() { IGConsole.Log("Starting sender thread"); while (status != Status.Disconnected) { if (sendQueue.Count > 0) { Packet packet = sendQueue.Dequeue(); BinaryFormatter formatter = new BinaryFormatter(); try { formatter.Serialize(client.GetStream(), packet); //Console.Log($"Sent {packet.GetType().ToString()}"); } catch (Exception e) { IGConsole.Error(e.ToString()); Disconnect(); } } Thread.Sleep(30); } IGConsole.Log("Sender thread stopped"); }
private void LoadError(string str, string mod) { IGConsole.Error($"Failed to load mod {mod}."); MDebug.WriteLine("[ERROR] " + str); }
private void OnUnhandledPacket(Packet packet) { IGConsole.Error($"Unhandled packet type {packet.GetType().ToString()}"); }
/// <summary> /// Load coroutine, yields every now and then to delay /// loading /// </summary> private static IEnumerator LoadCoroutine() { loading = true; Stopwatch watch = new Stopwatch(); watch.Start(); #if DEBUG IGConsole.Log($"Loading better save {GetSavePath()}"); #endif FileStream fs = new FileStream(GetSavePath(), FileMode.Open); BinaryFormatter formatter = new BinaryFormatter(); PlayerPosition player; Datum[] data; try { player = formatter.Deserialize(fs) as PlayerPosition; data = formatter.Deserialize(fs) as Datum[]; } catch (Exception e) { IGConsole.Error($"Loading failed with {e.ToString()}"); yield break; } finally { fs.Close(); } #if DEBUG IGConsole.Log($"Length of data {data.Length}"); #endif foreach (SaveThisObject obj in UnityEngine.Object.FindObjectsOfType <SaveThisObject>()) { UnityEngine.Object.Destroy(obj.gameObject); } BehaviorManager.AllowedToUpdate = false; MegaBoardMeshManager.MegaBoardMeshesOfColor.Clear(); SetPlayerPosition(player); int size = data.Length; maxProgress = size; for (int index = 0; index < size; index++) { Loader.Instantiate(data[index]); if ((index + 1) % instancesPerFrame == 0) { progress = index; yield return(new WaitForEndOfFrame()); } } SaveManager.RecalculateAllClustersEverywhereWithDelay(); MegaMesh.GenerateNewMegaMesh(); MegaBoardMeshManager.GenerateAllMegaBoardMeshes(); watch.Stop(); loading = false; if (UIManager.SomeOtherMenuIsOpen) { SaveManager.SaveAll(); } IGConsole.Log($"Loaded save in {watch.Elapsed.ToString()}"); }
public void Connect(IPEndPoint endPoint) { DisconnectReason = null; NetPeerConfiguration config = new NetPeerConfiguration("MulTUNG"); Client = new NetClient(config); Client.Start(); var approval = Client.CreateMessage(); approval.Write(MulTUNG.Version.ToString()); approval.Write(Username); var conn = Client.Connect(endPoint, approval); ThreadPool.QueueUserWorkItem(o => { var c = o as NetConnection; int elapsed = 0; while (true) { Thread.Sleep(50); elapsed += 50; if ((c.Status != NetConnectionStatus.Connected && elapsed >= Constants.WaitForConnection) || DisconnectReason != null) { Network.IsClient = false; string status = MulTUNG.Status = "Couldn't connect to remote server." + (DisconnectReason != null ? " Check the console for more details." : ""); IGConsole.Error("Couldn't connect to remote server: " + DisconnectReason); Thread.Sleep(3000); MulTUNG.ShowMainMenuCanvases(); MulTUNG.ShowStatusWindow = false; MulTUNG.Status = ""; break; } else if (c.Status == NetConnectionStatus.Connected) { Network.IsClient = true; MulTUNG.SynchronizationContext.Send(_ => { SaveManager.SaveName = MulTUNG.ForbiddenSaveName; World.DeleteSave(); SceneManager.LoadScene("gameplay"); EverythingHider.HideEverything(); }, null); while (ModUtilities.IsOnMainMenu) { Thread.Sleep(500); } Thread.Sleep(1000); IsInGameplay = true; EnterEvent.Set(); InitWorld(); break; } } }, conn); ThreadPool.QueueUserWorkItem(_ => { NetIncomingMessage msg; while (Client.Status == NetPeerStatus.Running) { msg = Client.WaitMessage(int.MaxValue); if (msg == null) { continue; } switch (msg.MessageType) { case NetIncomingMessageType.Data: var packet = PacketDeserializer.DeserializePacket(new MessagePacketReader(msg)); if (Network.ProcessPacket(packet, this.PlayerID)) { PacketLog.LogReceive(packet); } break; case NetIncomingMessageType.StatusChanged: var status = (NetConnectionStatus)msg.ReadByte(); Log.WriteLine("Status: " + status); if (status == NetConnectionStatus.Disconnected) { string reason = msg.ReadString(); if (!string.IsNullOrEmpty(reason)) { DisconnectReason = reason; } Disconnect(); } LastStatus = Client.ConnectionStatus; break; } Client.Recycle(msg); } }); }