Пример #1
0
        public override void OnApplicationStart()
        {
            try
            {
                if (File.Exists(FileName))
                {
                    var dict = (ProxyObject)JSON.Load(File.ReadAllText(FileName));
                    foreach (var keyValuePair in dict)
                    {
                        myPrefs[keyValuePair.Key] = ToObject(keyValuePair.Key, keyValuePair.Value);
                    }
                    MelonLogger.Log($"Loaded {dict.Count} prefs from PlayerPrefs.json");
                }
            }
            catch (Exception ex)
            {
                MelonLogger.LogError($"Unable to load PlayerPrefs.json: {ex}");
            }

            HookICall <TrySetFloatDelegate>(nameof(PlayerPrefs.TrySetFloat), TrySetFloat);
            HookICall <TrySetIntDelegate>(nameof(PlayerPrefs.TrySetInt), TrySetInt);
            HookICall <TrySetStringDelegate>(nameof(PlayerPrefs.TrySetSetString), TrySetString);

            HookICall <GetFloatDelegate>(nameof(PlayerPrefs.GetFloat), GetFloat);
            HookICall <GetIntDelegate>(nameof(PlayerPrefs.GetInt), GetInt);
            HookICall <GetStringDelegate>(nameof(PlayerPrefs.GetString), GetString);

            HookICall <HasKeyDelegate>(nameof(PlayerPrefs.HasKey), HasKey);
            HookICall <DeleteKeyDelegate>(nameof(PlayerPrefs.DeleteKey), DeleteKey);

            HookICall <VoidDelegate>(nameof(PlayerPrefs.DeleteAll), DeleteAll);
            HookICall <VoidDelegate>(nameof(PlayerPrefs.Save), Save);
        }
Пример #2
0
        public static bool ApiSnifferStatic(IntPtr @this, IntPtr dictionary, IntPtr someRef, IntPtr methodInfo)
        {
            var result = ourOriginalApiPopulate(@this, dictionary, someRef, methodInfo);

            try
            {
                var apiModel = new ApiModel(@this);
                if (!apiModel.Populated)
                {
                    return(result);
                }

                var maybeUser = apiModel.TryCast <APIUser>();
                if (maybeUser != null)
                {
                    FavCatMod.Database?.UpdateStoredPlayer(maybeUser);
                }
                var maybeAvatar = apiModel.TryCast <ApiAvatar>();
                if (maybeAvatar != null)
                {
                    FavCatMod.Database?.UpdateStoredAvatar(maybeAvatar);
                }
                var maybeWorld = apiModel.TryCast <ApiWorld>();
                if (maybeWorld != null)
                {
                    FavCatMod.Database?.UpdateStoredWorld(maybeWorld);
                }
            }
            catch (Exception ex)
            {
                MelonLogger.LogError($"Exception in API sniffer patch: {ex}");
            }

            return(result);
        }
Пример #3
0
        public void OnVeryLateUpdate(Camera _)
        {
            if (ourHadUpdateThisFrame)
            {
                return;
            }

            ourHadUpdateThisFrame = true;

            var toRun = ourToMainThreadQueue.ToList();

            ourToMainThreadQueue.Clear();

            foreach (var action in toRun)
            {
                try
                {
                    action();
                }
                catch (Exception ex)
                {
                    MelonLogger.LogError(ex.ToString());
                }
            }
        }
Пример #4
0
        private static bool CanUseCustomAvatarPatch(IntPtr thisPtr, IntPtr apiUserPtr, ref int denyReason)
        {
            var result = ourCanUseCustomAvatarDelegate(thisPtr, apiUserPtr, ref denyReason);

            try
            {
                if (!SwitchAvatarCookie.ourInSwitch || SwitchAvatarCookie.ourApiAvatar == null)
                {
                    return(result);
                }

                var apiAvatar     = SwitchAvatarCookie.ourApiAvatar;
                var avatarManager = SwitchAvatarCookie.ourAvatarManager;

                var vrcPlayer = avatarManager.field_Private_VRCPlayer_0;
                if (vrcPlayer == null)
                {
                    return(result);
                }

                if (vrcPlayer == VRCPlayer.field_Internal_Static_VRCPlayer_0) // never apply to self
                {
                    return(result);
                }

                var apiUser = vrcPlayer.prop_Player_0?.prop_APIUser_0;
                if (apiUser == null)
                {
                    return(result);
                }

                var userId = apiUser.id;
                if (!AdvancedSafetySettings.IncludeFriendsInHides && APIUser.IsFriendsWith(userId))
                {
                    return(result);
                }

                if (AdvancedSafetySettings.HidesAbideByShowAvatar &&
                    AdvancedSafetyMod.IsAvatarExplicitlyShown(userId))
                {
                    return(result);
                }

                if (ourBlockedAvatarAuthors.ContainsKey(apiAvatar.authorId) ||
                    ourBlockedAvatars.ContainsKey(apiAvatar.id))
                {
                    MelonLogger.Log(
                        $"Hiding avatar on {apiUser.displayName} because it or its author is hidden");
                    denyReason = 3;
                    return(false);
                }
            }
            catch (Exception ex)
            {
                MelonLogger.LogError($"Exception in CanUseCustomAvatarPatch: {ex}");
            }

            return(result);
        }
Пример #5
0
        private static ISupportModule Initialize()
        {
            LogSupport.RemoveAllHandlers();
            if (true)
            {
                LogSupport.InfoHandler += MelonLogger.Log;
            }
            LogSupport.WarningHandler += MelonLogger.LogWarning;
            LogSupport.ErrorHandler   += MelonLogger.LogError;
            if (true)
            {
                LogSupport.TraceHandler += MelonLogger.Log;
            }

            ClassInjector.DoHook += Imports.Hook;
            GetUnityVersionNumbers(out var major, out var minor, out var patch);
            UnityVersionHandler.Initialize(major, minor, patch);

            // Il2CppSystem.Console.SetOut(new Il2CppSystem.IO.StreamWriter(Il2CppSystem.IO.Stream.Null));
            try
            {
                var il2CppSystemAssembly = Assembly.Load("Il2Cppmscorlib");

                var consoleType      = il2CppSystemAssembly.GetType("Il2CppSystem.Console");
                var streamWriterType = il2CppSystemAssembly.GetType("Il2CppSystem.IO.StreamWriter");
                var streamType       = il2CppSystemAssembly.GetType("Il2CppSystem.IO.Stream");

                var setOutMethod     = consoleType.GetMethod("SetOut", BindingFlags.Static | BindingFlags.Public);
                var nullStreamField  = streamType.GetProperty("Null", BindingFlags.Static | BindingFlags.Public).GetGetMethod();
                var streamWriterCtor = streamWriterType.GetConstructor(new[] { streamType });

                var nullStream  = nullStreamField.Invoke(null, new object[0]);
                var steamWriter = streamWriterCtor.Invoke(new[] { nullStream });
                setOutMethod.Invoke(null, new[] { steamWriter });
            }
            catch (Exception ex)
            {
                MelonLogger.LogError($"Console cleaning failed: {ex}");
            }

            SetAsLastSiblingDelegateField = IL2CPP.ResolveICall <SetAsLastSiblingDelegate>("UnityEngine.Transform::SetAsLastSibling");

            ClassInjector.RegisterTypeInIl2Cpp <MelonLoaderComponent>();
            //MelonLogger.Log("ClassInjector.RegisterTypeInIl2Cpp<MelonLoaderComponent> done");
            MelonLoaderComponent.Create();
            //MelonLogger.Log("MelonLoaderComponent.Create() done");
            SceneManager.sceneLoaded = (
                (SceneManager.sceneLoaded == null)
                ? new Action <Scene, LoadSceneMode>(OnSceneLoad)
                : Il2CppSystem.Delegate.Combine(SceneManager.sceneLoaded, (UnityAction <Scene, LoadSceneMode>) new Action <Scene, LoadSceneMode>(OnSceneLoad)).Cast <UnityAction <Scene, LoadSceneMode> >()
                );
            Camera.onPostRender = (
                (Camera.onPostRender == null)
                ? new Action <Camera>(OnPostRender)
                : Il2CppSystem.Delegate.Combine(Camera.onPostRender, (Camera.CameraCallback) new Action <Camera>(OnPostRender)).Cast <Camera.CameraCallback>()
                );

            return(new Module());
        }
Пример #6
0
        private IEnumerator WaitAndRegisterEmojiButtons()
        {
            while (QuickMenu.prop_QuickMenu_0 == null)
            {
                yield return(null);
            }

            var emojiMenuRoot = QuickMenu.prop_QuickMenu_0.transform.Find("EmojiMenu");

            if (emojiMenuRoot == null)
            {
                MelonLogger.LogError("Emoji menu root not found");
                yield break;
            }

            var emojiMenu = emojiMenuRoot.GetComponent <EmojiMenu>();

            var storeGo = new GameObject("ClonedPageStore");

            storeGo.transform.SetParent(emojiMenu.transform);
            storeGo.SetActive(false);

            for (var index = 0; index < emojiMenu.pages.Count; index++)
            {
                var pageGo = emojiMenu.pages[index];

                var clone = new GameObject($"Page{index}Button", new [] { Il2CppType.Of <RectTransform>() });
                clone.transform.SetParent(storeGo.transform, false);
                var grid = clone.AddComponent <GridLayoutGroup>();
                grid.constraint      = GridLayoutGroup.Constraint.FixedColumnCount;
                grid.cellSize        = new Vector2(33, 33);
                grid.startAxis       = GridLayoutGroup.Axis.Horizontal;
                grid.startCorner     = GridLayoutGroup.Corner.UpperLeft;
                grid.constraintCount = 3;

                foreach (var buttonXformObject in pageGo.transform)
                {
                    var buttonTransform = buttonXformObject.Cast <Transform>();
                    if (!buttonTransform.gameObject.activeSelf)
                    {
                        continue;
                    }

                    var buttonClone = Object.Instantiate(buttonTransform.gameObject, clone.transform, false);
                    CleanStuff(buttonClone);
                }

                var index1 = index;
                ExpansionKitApi.RegisterSimpleMenuButton(ExpandedMenu.EmojiQuickMenu, "", () =>
                {
                    emojiMenu.pages[emojiMenu.field_Private_Int32_0].SetActive(false);
                    pageGo.SetActive(true);
                    emojiMenu.field_Private_Int32_0 = index1;
                }, buttonGo =>
                {
                    Object.Instantiate(clone, buttonGo.transform, false);
                });
            }
        }
Пример #7
0
        private static IEnumerable <CodeInstruction> UnhollowerTranspiler(MethodBase method, IEnumerable <CodeInstruction> instructionsIn)
        {
            List <CodeInstruction> instructions = new List <CodeInstruction>(instructionsIn);
            PatchInfo patchInfo        = HarmonySharedState.GetPatchInfo(method);
            IntPtr    copiedMethodInfo = patchInfo.copiedMethodInfoPointer;

            bool found        = false;
            int  replaceIdx   = 0;
            int  replaceCount = 0;

            for (int i = instructions.Count - 2; i >= 0; --i)
            {
                if (instructions[i].opcode != OpCodes.Ldsfld)
                {
                    continue;
                }

                found = true;
                CodeInstruction next = instructions[i + 1];
                if (next.opcode == OpCodes.Call && ((MethodInfo)next.operand).Name == "il2cpp_object_get_virtual_method")
                {
                    // Virtual method: Replace the sequence
                    // - ldarg.0
                    // - call native int[UnhollowerBaseLib] UnhollowerBaseLib.IL2CPP::Il2CppObjectBaseToPtr(class [UnhollowerBaseLib] UnhollowerBaseLib.Il2CppObjectBase)
                    // - ldsfld native int SomeClass::NativeMethodInfoPtr_Etc
                    // - call native int[UnhollowerBaseLib] UnhollowerBaseLib.IL2CPP::il2cpp_object_get_virtual_method(native int, native int)

                    replaceIdx   = i - 2;
                    replaceCount = 4;
                }
                else
                {
                    // Everything else: Just replace the static load
                    replaceIdx   = i;
                    replaceCount = 1;
                }
                break;
            }

            if (!found)
            {
                MelonLogger.LogError("Harmony transpiler could not rewrite Unhollower method. Expect a stack overflow.");
                return(instructions);
            }

            CodeInstruction[] replacement =
            {
                new CodeInstruction(OpCodes.Ldc_I8, copiedMethodInfo.ToInt64()),
                new CodeInstruction(OpCodes.Conv_I)
            };

            instructions.RemoveRange(replaceIdx, replaceCount);
            instructions.InsertRange(replaceIdx, replacement);

            return(instructions);
        }
Пример #8
0
 public static void Calibrate(GameObject avatarRoot)
 {
     CalibrateCore(avatarRoot).ContinueWith(t =>
     {
         if (t.Exception != null)
         {
             MelonLogger.LogError($"Task failed with exception: {t.Exception}");
         }
     });
 }
Пример #9
0
        /// <summary>
        /// Sets the specified GameObject as a prefab for given settings category. The prefab will be instantiated each time "Undo changes" is pressed, in addition to instantiating it on menu creation.
        /// </summary>
        /// <param name="categoryName">String passed as first parameter of <see cref="MelonPrefs.RegisterCategory"/></param>
        /// <param name="categoryUi">Prefab that acts as category settings UI</param>
        public static void RegisterCustomSettingsCategory(string categoryName, GameObject categoryUi)
        {
            if (CustomCategoryUIs.ContainsKey(categoryName))
            {
                MelonLogger.LogError($"Custom UI for category {categoryName} is already registered");
                return;
            }

            CustomCategoryUIs[categoryName] = categoryUi;
        }
Пример #10
0
 public static void NoAwait(this Task task)
 {
     task.ContinueWith(tsk =>
     {
         if (tsk.IsFaulted)
         {
             MelonLogger.LogError($"Free-floating Task failed with exception: {tsk.Exception}");
         }
     });
 }
Пример #11
0
 private static void Prefix(DifficultySelect __instance)
 {
     if (MelonHandler.Mods.Any(it => it.Info.SystemType.Name == nameof(SongDataLoader)))
     {
         IEnumerator coroutine = ChangeNamesDS(__instance);
         MelonCoroutines.Start(coroutine);
     }
     else
     {
         MelonLogger.LogError("Custom Song Data mod not detected, Custom difficulty names will not run");
     }
 }
Пример #12
0
        public override void OnUpdate()
        {
            if (Input.GetKeyDown(KeyCode.Keypad5))
            {
                foreach (GameObject gameObject in GlobalUtils.GetAllGameObjects())
                {
                    MelonLogger.Log($"|{gameObject.name}| {gameObject.transform.position}");
                }
            }


            if (Input.GetKeyDown(KeyCode.Keypad8))
            {
                try
                {
                    Rigidbody CC = GlobalUtils.GetPlayer().GetComponent <Rigidbody>();
                    MelonLogger.Log(CC.velocity);
                }
                catch (Exception EX)
                {
                    MelonLogger.LogError(EX.ToString());
                    throw;
                }
            }

            if (Input.GetKeyDown(KeyCode.Keypad2))
            {
                try
                {
                    GameObject player = GlobalUtils.GetPlayer();
                    MelonLogger.Log(player.transform.position);
                }
                catch (Exception EX)
                {
                    MelonLogger.LogError(EX.ToString());
                    throw;
                }
            }

            if (Input.GetKeyDown(KeyCode.Keypad9))
            {
                try
                {
                    GameObject loli = GlobalUtils.GetLoli();
                    MelonLogger.Log(loli.transform.position);
                }
                catch (Exception EX)
                {
                    MelonLogger.LogError(EX.ToString());
                    throw;
                }
            }
        }
Пример #13
0
        private void TransportLayer_OnConnectionClosed(ITransportConnection connection, ConnectionClosedReason reason)
        {
            if (connection.ConnectedTo != ServerId)
            {
                MelonLogger.LogError("Connection with non-server ID was closed - but we're a client???");
                return;
            }

            ui.SetState(MultiplayerUIState.PreConnect);
            MelonLogger.LogError("Got P2P connection error " + reason.ToString());
            Disconnect();
        }
Пример #14
0
        List <AudioClip> LoadClipsFromDir(string soundsPath)
        {
            List <AudioClip> audioClips = new List <AudioClip>();

            string path = Directory.GetCurrentDirectory() + "\\" + soundsPath;

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            List <string> list = Directory.GetFiles(path).ToList <string>();

            for (int i = list.Count - 1; i >= 0; i--)
            {
                if (list[i].Contains(".wav"))
                {
                    list[i] = Path.GetFileName(list[i]);
                }
                else
                {
                    list.RemoveAt(i);
                }
            }
            for (int j = 0; j < list.Count; j++)
            {
                string wavText = Path.GetFileNameWithoutExtension(list[j]);
                wavText = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(wavText);
                byte[] wav              = File.ReadAllBytes(soundsPath + list[j]);
                WAV    wav2             = new WAV(wav);
                bool   failedContructor = wav2.failedContructor;
                if (failedContructor)
                {
                    MelonLogger.LogError("Could not read " + list[j]);
                }
                else
                {
                    AudioClip audioClip = AudioClip.Create(wavText, wav2.SampleCount, 1, wav2.Frequency, false);
                    audioClip.SetData(wav2.LeftChannel, 0);
                    if (audioClip != null)
                    {
                        audioClips.Add(audioClip);
                        MelonLogger.Log("Added " + list[j]);
                    }
                    else
                    {
                        MelonLogger.LogError("Failed To Read " + list[j]);
                    }
                }
            }

            return(audioClips);
        }
Пример #15
0
        public static IEnumerator SearchAvatars(string query)
        {
            Helpers.Log("Starting Search For: " + query + "..");
            if (BetterEmmVRC.BetterEmmVRC.NetworkLib.authToken == null)
            {
                yield return(new WaitForEndOfFrame());
            }
            CustomAvatarFavorites.SearchedAvatars.Clear();
            string url = BetterEmmVRC.BetterEmmVRC.NetworkLib.baseURL + "/api/avatar/search";

            System.Collections.Generic.Dictionary <string, string> dictionary = new System.Collections.Generic.Dictionary <string, string>();
            dictionary["query"] = query;
            Helpers.Log("Making Request..");
            Task <string> request = HTTPRequest.post(url, dictionary);

            while (!request.IsCompleted && !request.IsFaulted)
            {
                yield return(new WaitForEndOfFrame());
            }
            if (!request.IsFaulted)
            {
                Helpers.Log("Success!");
                Avatar[] array = Decoder.Decode(request.Result).Make <Avatar[]>();
                if (array != null)
                {
                    foreach (Avatar avatar in array)
                    {
                        CustomAvatarFavorites.SearchedAvatars.Add(avatar.apiAvatar());
                    }
                }
                CustomAvatarFavorites.avText.GetComponentInChildren <Text>().text = "(" + CustomAvatarFavorites.SearchedAvatars.Count.ToString() + ") Result(s): " + query;
            }
            else
            {
                string             str       = "Asynchronous net post failed: ";
                AggregateException exception = request.Exception;
                MelonLogger.LogError(str + ((exception != null) ? exception.ToString() : null));
                VRCUiPopupManager.field_Private_Static_VRCUiPopupManager_0.ShowStandardPopup("emmVRC", "Your search could not be processed.", "Dismiss", delegate()
                {
                    VRCUiPopupManager.field_Private_Static_VRCUiPopupManager_0.HideCurrentPopup();
                }, null);
            }
            CustomAvatarFavorites.SearchAvatarList.scrollRect.movementType = ScrollRect.MovementType.Unrestricted;
            CustomAvatarFavorites.SearchAvatarList.RenderElement(CustomAvatarFavorites.SearchedAvatars);
            CustomAvatarFavorites.SearchAvatarList.scrollRect.movementType = ScrollRect.MovementType.Elastic;
            if (CustomAvatarFavorites.SearchAvatarList.expandButton.gameObject.transform.Find("ToggleIcon").GetComponentInChildren <Image>().sprite == CustomAvatarFavorites.SearchAvatarList.expandSprite)
            {
                CustomAvatarFavorites.SearchAvatarList.ToggleExtend();
            }
            CustomAvatarFavorites.Searching = true;
            yield break;
        }
Пример #16
0
 private static bool MoveNextPatchC(IntPtr thisPtr)
 {
     try
     {
         using (new AvatarManagerCookie(new AMEnumC(thisPtr).field_Public_VRCAvatarManager_0))
             return(SafeInvokeMoveNext(ourMoveNextC, thisPtr));
     }
     catch (Exception ex)
     {
         MelonLogger.LogError($"Error when wrapping avatar creation: {ex}");
         return(false);
     }
 }
Пример #17
0
        public override void OnApplicationStart()
        {
            Directory.CreateDirectory($"{Dir}");
            if (File.Exists(Config))
            {
                MelonLogger.Log("Reading config file");
                using (StreamReader sr = File.OpenText(Config))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        try
                        {
                            if (s.StartsWith("#"))
                            {
                                continue;
                            }

                            if (s.StartsWith("CycleUp"))
                            {
                                CycleUp = (KeyCode)Enum.Parse(typeof(KeyCode), s.Substring(s.IndexOf(char.Parse("=")) + 1));
                            }
                            if (s.StartsWith("CycleDown"))
                            {
                                CycleDown = (KeyCode)Enum.Parse(typeof(KeyCode), s.Substring(s.IndexOf(char.Parse("=")) + 1));
                            }
                            if (s.StartsWith("CycleIfPlaced"))
                            {
                                CycleIfPlaced = bool.Parse(s.Substring(s.IndexOf(char.Parse("=")) + 1));
                            }
                        }
                        catch (Exception e)
                        {
                            MelonLogger.LogError("Malformed line " + s);
                            e.GetType(); //just to get rid of the warning lol
                        }
                    }
                }
            }
            else
            {
                MelonLogger.Log("Creating config file");
                using (StreamWriter sw = File.CreateText(Config))
                {
                    sw.WriteLine("CycleUp=" + CycleUp);
                    sw.WriteLine("CycleDown=" + CycleDown);
                    sw.WriteLine("CycleIfPlaced=" + CycleIfPlaced);
                }
                MelonLogger.Log("Done Creating");
            }
        }
Пример #18
0
        private static IntPtr ObjectInstantiatePatch(IntPtr assetPtr, Vector3 pos, Quaternion rot,
                                                     byte allowCustomShaders, byte isUI, byte validate, IntPtr nativeMethodPointer, ObjectInstantiateDelegate originalInstantiateDelegate)
        {
            if (AvatarManagerCookie.CurrentManager == null || assetPtr == IntPtr.Zero)
            {
                return(originalInstantiateDelegate(assetPtr, pos, rot, allowCustomShaders, isUI, validate, nativeMethodPointer));
            }

            var avatarManager = AvatarManagerCookie.CurrentManager;
            var vrcPlayer     = avatarManager.field_Private_VRCPlayer_0;

            if (vrcPlayer == null)
            {
                return(originalInstantiateDelegate(assetPtr, pos, rot, allowCustomShaders, isUI, validate, nativeMethodPointer));
            }

            if (vrcPlayer == VRCPlayer.field_Internal_Static_VRCPlayer_0) // never apply to self
            {
                return(originalInstantiateDelegate(assetPtr, pos, rot, allowCustomShaders, isUI, validate, nativeMethodPointer));
            }

            var go = new Object(assetPtr).TryCast <GameObject>();

            if (go == null)
            {
                return(originalInstantiateDelegate(assetPtr, pos, rot, allowCustomShaders, isUI, validate, nativeMethodPointer));
            }

            var wasActive = go.activeSelf;

            go.SetActive(false);
            var result = originalInstantiateDelegate(assetPtr, pos, rot, allowCustomShaders, isUI, validate, nativeMethodPointer);

            go.SetActive(wasActive);
            if (result == IntPtr.Zero)
            {
                return(result);
            }
            var instantiated = new GameObject(result);

            try
            {
                CleanAvatar(AvatarManagerCookie.CurrentManager, instantiated);
            }
            catch (Exception ex)
            {
                MelonLogger.LogError($"Exception when cleaning avatar: {ex}");
            }

            return(result);
        }
Пример #19
0
        internal static GameObject GetNewWorkbenchInstance()
        {
            GameObject workbenchPrefab = assetBundle.LoadAsset <GameObject>(ASSET_PATH);

            if (workbenchPrefab is null)
            {
                MelonLogger.LogError("Workbench prefab is null!");
                return(null);
            }
            else
            {
                return(GameObject.Instantiate(workbenchPrefab));
            }
        }
Пример #20
0
        // Async operations
        //Task<Facepunch.Steamworks.Data.Image?> task_asyncLoadPlayerIcon;
        //public bool isPlayerIconLoaded = false;

        public static void LoadFord()
        {
            fordBundle = AssetBundle.LoadFromFile("ford.ford");
            if (fordBundle == null)
            {
                MelonLogger.LogError("Failed to load Ford asset bundle");
            }

            GameObject fordPrefab = fordBundle.LoadAsset("Assets/Ford.prefab").Cast <GameObject>();

            if (fordPrefab == null)
            {
                MelonLogger.LogError("Failed to load Ford from the asset bundle???");
            }
        }
Пример #21
0
        public static void AdvancedInvitesHandleInvite(Notification notification)
        {
#if DEBUG
            try
            {
                GetAdvancedInvitesInviteDelegate(notification);
            }
            catch (Exception e)
            {
                MelonLogger.LogError($"Beep boop, Something went wrong trying to used advanced invites {e}");
            }
#else
            Delegates.GetAdvancedInvitesInviteDelegate(notification);
#endif
        }
Пример #22
0
        public static void GiveUniqueAppearances(SteamId userID, Transform root, TMPro.TextMeshPro text)
        {
            Color32 DevRed   = new Color32(230, 0, 10, 255);
            Color32 AquaBlue = new Color32(64, 224, 208, 255);
            Color32 LGPurple = new Color32(155, 89, 182, 255);

            // Someone Somewhere
            if (userID == 76561198078346603)
            {
                GameObject crownObj = root.Find("Spine_01SHJnt/Spine_02SHJnt/Spine_TopSHJnt/Neck_01SHJnt/Neck_02SHJnt/Neck_TopSHJnt/Head_Crown").gameObject;
                //GameObject glassesObj = root.Find("Spine_01SHJnt/Spine_02SHJnt/Spine_TopSHJnt/Neck_01SHJnt/Neck_02SHJnt/Neck_TopSHJnt/Head_Glasses").gameObject;
                crownObj.SetActive(true);
                //glassesObj.SetActive(true);

                text.color = DevRed;
            }

            // zCubed
            if (userID == 76561198078927044)
            {
                text.color = DevRed;
            }

            //Maranara
            if (userID == 76561198088708478)
            {
                root.parent.parent.parent.Find("geoGrp/brett_body").GetComponent <SkinnedMeshRenderer>().materials[1].color = new Color(0.5141f, 1, 0.6199f);
                GameObject weaponWings = PlayerRep.fordBundle.LoadAsset("Assets/WeaponWings.prefab").Cast <GameObject>();
                if (weaponWings == null)
                {
                    MelonLogger.LogError("Failed to load WeaponWings from bundle.");
                }
                else
                {
                    GameObject wingInstance = GameObject.Instantiate(weaponWings);
                    wingInstance.transform.parent           = root.Find("Spine_01SHJnt");
                    wingInstance.transform.localPosition    = Vector3.zero;
                    wingInstance.transform.localEulerAngles = new Vector3(-0.042f, 0.057f, 30.129f);
                }
                text.color = DevRed;
            }

            // Camobiwon
            if (userID == 76561198060337335)
            {
                text.color = LGPurple;
            }
        }
Пример #23
0
        private void ApplySettings()
        {
            activeSettings.Enabled         = MelonPrefs.GetBool(SettingsCategory, nameof(Settings.Enabled));
            activeSettings.SpeedMultiplier = MelonPrefs.GetFloat(SettingsCategory, nameof(Settings.SpeedMultiplier));
            activeSettings.DoubleClickTime = MelonPrefs.GetFloat(SettingsCategory, nameof(Settings.DoubleClickTime));

            if (Enum.TryParse(MelonPrefs.GetString(SettingsCategory, nameof(Settings.Forward)), out KeyCode forward))
            {
                activeSettings.Forward = forward;
            }
            else
            {
                MelonLogger.LogError("Failed to parse KeyCode Forward");
            }

            if (Enum.TryParse(MelonPrefs.GetString(SettingsCategory, nameof(Settings.Backward)), out KeyCode backward))
            {
                activeSettings.Backward = backward;
            }
            else
            {
                MelonLogger.LogError("Failed to parse KeyCode Backward");
            }

            if (Enum.TryParse(MelonPrefs.GetString(SettingsCategory, nameof(Settings.Left)), out KeyCode left))
            {
                activeSettings.Left = left;
            }
            else
            {
                MelonLogger.LogError("Failed to parse KeyCode Left");
            }

            if (Enum.TryParse(MelonPrefs.GetString(SettingsCategory, nameof(Settings.Right)), out KeyCode right))
            {
                activeSettings.Right = right;
            }
            else
            {
                MelonLogger.LogError("Failed to parse KeyCode Right");
            }

            activeSettings.AxisDeadZone       = MelonPrefs.GetFloat(SettingsCategory, nameof(Settings.AxisDeadZone));
            activeSettings.AxisClickThreshold = MelonPrefs.GetFloat(SettingsCategory, nameof(Settings.AxisClickThreshold));

            SetLocomotion();
        }
Пример #24
0
        // Prints the properties of a given component type
        public static void PrintComponentProps <T>(GameObject go)
        {
            try
            {
                if (go == null)
                {
                    MelonLogger.LogError("go was null???");
                }

                T t = go.GetComponent <T>();

                if (t == null)
                {
                    MelonLogger.LogError("Couldn't find component " + t.GetType().Name);
                }

                MelonLogger.Log("====== Component type " + t.ToString() + "======");

                System.Reflection.PropertyInfo[] props = typeof(T).GetProperties();

                foreach (var pi in props)
                {
                    //if (pi.PropertyType.IsPrimitive)
                    try
                    {
                        var val = pi.GetValue(t);
                        if (val != null)
                        {
                            MelonLogger.Log(pi.Name + ": " + val.ToString());
                        }
                        else
                        {
                            MelonLogger.Log(pi.Name + ": null");
                        }
                    }
                    catch
                    {
                        MelonLogger.LogError("Error tring to get property " + pi.Name);
                    }
                }
            }
            catch
            {
                MelonLogger.LogError("i don't know anymore");
            }
        }
Пример #25
0
        private static void ProcessQueue(Queue <Action> queue)
        {
            var toRun = queue.ToList();

            queue.Clear();

            foreach (var action in toRun)
            {
                try
                {
                    action();
                }
                catch (Exception ex)
                {
                    MelonLogger.LogError(ex.ToString());
                }
            }
        }
Пример #26
0
        public void StopServer()
        {
            ui.SetState(MultiplayerUIState.PreConnect);
            IsRunning = false;

            try
            {
                foreach (PlayerRep r in playerObjects.Values)
                {
                    r.Delete();
                }
            }
            catch (Exception)
            {
                MelonLogger.LogError("Caught exception destroying player objects");
            }

            playerObjects.Clear();
            playerNames.Clear();
            smallPlayerIds.Clear();
            largePlayerIds.Clear();
            smallIdCounter = 1;

            P2PMessage shutdownMsg = new P2PMessage();

            shutdownMsg.WriteByte((byte)MessageType.ServerShutdown);

            foreach (SteamId p in players)
            {
                playerConnections[p].SendMessage(shutdownMsg, MessageSendType.Reliable);
                playerConnections[p].Disconnect();
            }

            players.Clear();

            transportLayer.OnMessageReceived  -= TransportLayer_OnMessageReceived;
            transportLayer.OnConnectionClosed -= TransportLayer_OnConnectionClosed;
            GunHooks.OnGunFire                -= GunHooks_OnGunFire;
            PlayerHooks.OnPlayerGrabObject    -= PlayerHooks_OnPlayerGrabObject;
            PlayerHooks.OnPlayerReleaseObject -= PlayerHooks_OnPlayerReleaseObject;
            transportLayer.StopListening();

            MultiplayerMod.OnLevelWasLoadedEvent -= MultiplayerMod_OnLevelWasLoadedEvent;
        }
        private static void SetFirepoint(GunExtras.GunConfig handConfig, Target.TargetHandType hand)
        {
            Gun desiredGun = KataConfig.I.GetGun(hand);

            if (desiredGun == null)
            {
                MelonLogger.LogError("Can not find gun");
                return;
            }

            if (handConfig != null && handConfig.firepoint != null)
            {
                desiredGun.firepoint.localPosition = new Vector3(handConfig.firepoint.x, handConfig.firepoint.y, handConfig.firepoint.z);
            }
            else
            {
                desiredGun.firepoint = desiredGun.firepointDefaultPosition;
            }
        }
Пример #28
0
        public override void OnApplicationStart()
        {
            MelonPrefs.RegisterCategory("ComfyVRMenu", "Comfy VR Menu");
            MelonPrefs.RegisterBool("ComfyVRMenu", "EnableComfyVRMenu", true, "Enable Comfy VR Menu");

            _comfyVRMenu = MelonPrefs.GetBool("ComfyVRMenu", "EnableComfyVRMenu");

            var harmony = HarmonyInstance.Create("ComfyVRMenu");

            var method = PlaceUiMethod;

            if (method == null)
            {
                MelonLogger.LogError("Couldn't find VRCUiManager PlaceUi method to patch.");
                return;
            }

            harmony.Patch(typeof(VRCUiManager).GetMethod(method.Name), GetPatch(nameof(Main.PlaceUiPatch)));
        }
        private static Stream Send(string url, string method = "GET", string data = null, bool compress = true)
        {
            // disable SSL encryption
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };

            // set session headers
            var request = WebRequest.Create(new Uri(BackendUrl + url));

            request.Headers.Add("Accept-Encoding", "deflate");
            request.Method = method;

            if (method != "GET" && !string.IsNullOrWhiteSpace(data))
            {
                // set request body
                var bytes = (compress) ? SimpleZlib.CompressToBytes(data, zlibConst.Z_BEST_COMPRESSION) : Encoding.UTF8.GetBytes(data);

                request.ContentType   = "application/json";
                request.ContentLength = bytes.Length;

                if (compress)
                {
                    request.Headers.Add("Content-Encoding", "deflate");
                }

                using var stream = request.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);
            }

            // get response stream
            try
            {
                var response = request.GetResponse();
                return(response.GetResponseStream());
            }
            catch (Exception e)
            {
                MelonLogger.LogError(e.ToString());
            }

            return(null);
        }
Пример #30
0
        public override void VRChat_OnUiManagerInit()
        {
            AssetsHandler.Load();

            try
            {
                if (FavCatSettings.IsEnableAvatarFavs)
                {
                    AvatarModule = new AvatarModule();
                }
            }
            catch (Exception ex)
            {
                MelonLogger.LogError($"Exception in avatar module init: {ex}");
            }

            try
            {
                if (FavCatSettings.IsEnableWorldFavs)
                {
                    myWorldsModule = new WorldsModule();
                }
            }
            catch (Exception ex)
            {
                MelonLogger.LogError($"Exception in world module init: {ex}");
            }

            try
            {
                if (FavCatSettings.IsEnablePlayerFavs)
                {
                    myPlayerModule = new PlayersModule();
                }
            }
            catch (Exception ex)
            {
                MelonLogger.LogError($"Exception in player module init: {ex}");
            }

            MelonLogger.Log("Initialized!");
            ourInitDone = true;
        }