prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
using BepInEx; using UnityEngine; using UnityEngine.SceneManagement; using System; using HarmonyLib; using System.IO; using Ultrapain.Patches; using System.Linq; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Reflection; using Steamworks; using Unity.Audio; using System.Text; using System.Collections.Generic; using UnityEngine.AddressableAssets; using UnityEngine.AddressableAssets.ResourceLocators; using UnityEngine.ResourceManagement.ResourceLocations; using UnityEngine.UIElements; using PluginConfig.API; namespace Ultrapain { [BepInPlugin(PLUGIN_GUID, PLUGIN_NAME, PLUGIN_VERSION)] [BepInDependency("com.eternalUnion.pluginConfigurator", "1.6.0")] public class Plugin : BaseUnityPlugin { public const string PLUGIN_GUID = "com.eternalUnion.ultraPain"; public const string PLUGIN_NAME = "Ultra Pain"; public const string PLUGIN_VERSION = "1.1.0"; public static Plugin instance; private static bool addressableInit = false; public static T LoadObject<T>(string path) { if (!addressableInit) { Addressables.InitializeAsync().WaitForCompletion(); addressableInit = true; } return Addressables.LoadAssetAsync<T>(path).WaitForCompletion(); } public static Vector3 PredictPlayerPosition(Collider safeCollider, float speedMod) { Transform target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f) return target.position; RaycastHit raycastHit; if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == safeCollider) return target.position; else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { return raycastHit.point; } else { Vector3 projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod; return new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z); } } public static GameObject projectileSpread; public static GameObject homingProjectile; public static GameObject hideousMassProjectile; public static GameObject decorativeProjectile2; public static GameObject shotgunGrenade; public static GameObject beam; public static GameObject turretBeam; public static
GameObject lightningStrikeExplosiveSetup;
public static GameObject lightningStrikeExplosive; public static GameObject lighningStrikeWindup; public static GameObject explosion; public static GameObject bigExplosion; public static GameObject sandExplosion; public static GameObject virtueInsignia; public static GameObject rocket; public static GameObject revolverBullet; public static GameObject maliciousCannonBeam; public static GameObject lightningBoltSFX; public static GameObject revolverBeam; public static GameObject blastwave; public static GameObject cannonBall; public static GameObject shockwave; public static GameObject sisyphiusExplosion; public static GameObject sisyphiusPrimeExplosion; public static GameObject explosionWaveKnuckleblaster; public static GameObject chargeEffect; public static GameObject maliciousFaceProjectile; public static GameObject hideousMassSpear; public static GameObject coin; public static GameObject sisyphusDestroyExplosion; //public static GameObject idol; public static GameObject ferryman; public static GameObject minosPrime; //public static GameObject maliciousFace; public static GameObject somethingWicked; public static Turret turret; public static GameObject turretFinalFlash; public static GameObject enrageEffect; public static GameObject v2flashUnparryable; public static GameObject ricochetSfx; public static GameObject parryableFlash; public static AudioClip cannonBallChargeAudio; public static Material gabrielFakeMat; public static Sprite blueRevolverSprite; public static Sprite greenRevolverSprite; public static Sprite redRevolverSprite; public static Sprite blueShotgunSprite; public static Sprite greenShotgunSprite; public static Sprite blueNailgunSprite; public static Sprite greenNailgunSprite; public static Sprite blueSawLauncherSprite; public static Sprite greenSawLauncherSprite; public static GameObject rocketLauncherAlt; public static GameObject maliciousRailcannon; // Variables public static float SoliderShootAnimationStart = 1.2f; public static float SoliderGrenadeForce = 10000f; public static float SwordsMachineKnockdownTimeNormalized = 0.8f; public static float SwordsMachineCoreSpeed = 80f; public static float MinGrenadeParryVelocity = 40f; public static GameObject _lighningBoltSFX; public static GameObject lighningBoltSFX { get { if (_lighningBoltSFX == null) _lighningBoltSFX = ferryman.gameObject.transform.Find("LightningBoltChimes").gameObject; return _lighningBoltSFX; } } private static bool loadedPrefabs = false; public void LoadPrefabs() { if (loadedPrefabs) return; loadedPrefabs = true; // Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab projectileSpread = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab homingProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab decorativeProjectile2 = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab"); // Assets/Prefabs/Attacks and Projectiles/Grenade.prefab shotgunGrenade = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Grenade.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab turretBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab beam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab lightningStrikeExplosiveSetup = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab"); // Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab lighningStrikeWindup = LoadObject<GameObject>("Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab"); //[bundle-0][assets/prefabs/enemies/idol.prefab] //idol = LoadObject<GameObject>("assets/prefabs/enemies/idol.prefab"); // Assets/Prefabs/Enemies/Ferryman.prefab ferryman = LoadObject<GameObject>("Assets/Prefabs/Enemies/Ferryman.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab explosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab bigExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab sandExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab"); // Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab virtueInsignia = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab hideousMassProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab"); // Assets/Particles/Enemies/RageEffect.prefab enrageEffect = LoadObject<GameObject>("Assets/Particles/Enemies/RageEffect.prefab"); // Assets/Particles/Flashes/V2FlashUnparriable.prefab v2flashUnparryable = LoadObject<GameObject>("Assets/Particles/Flashes/V2FlashUnparriable.prefab"); // Assets/Prefabs/Attacks and Projectiles/Rocket.prefab rocket = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Rocket.prefab"); // Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab revolverBullet = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab maliciousCannonBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab revolverBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab blastwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab"); // Assets/Prefabs/Enemies/MinosPrime.prefab minosPrime = LoadObject<GameObject>("Assets/Prefabs/Enemies/MinosPrime.prefab"); // Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab cannonBall = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab"); // get from Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab cannonBallChargeAudio = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab").transform.Find("RocketLauncher/Armature/Body_Bone/HologramDisplay").GetComponent<AudioSource>().clip; // Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab shockwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab sisyphiusExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab sisyphiusPrimeExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab explosionWaveKnuckleblaster = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab - [bundle-0][assets/prefabs/explosionlightning variant.prefab] lightningStrikeExplosive = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab"); // Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab rocketLauncherAlt = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab"); // Assets/Prefabs/Weapons/Railcannon Malicious.prefab maliciousRailcannon = LoadObject<GameObject>("Assets/Prefabs/Weapons/Railcannon Malicious.prefab"); //Assets/Particles/SoundBubbles/Ricochet.prefab ricochetSfx = LoadObject<GameObject>("Assets/Particles/SoundBubbles/Ricochet.prefab"); //Assets/Particles/Flashes/Flash.prefab parryableFlash = LoadObject<GameObject>("Assets/Particles/Flashes/Flash.prefab"); //Assets/Prefabs/Attacks and Projectiles/Spear.prefab hideousMassSpear = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Spear.prefab"); //Assets/Prefabs/Enemies/Wicked.prefab somethingWicked = LoadObject<GameObject>("Assets/Prefabs/Enemies/Wicked.prefab"); //Assets/Textures/UI/SingleRevolver.png blueRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/SingleRevolver.png"); //Assets/Textures/UI/RevolverSpecial.png greenRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSpecial.png"); //Assets/Textures/UI/RevolverSharp.png redRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSharp.png"); //Assets/Textures/UI/Shotgun.png blueShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun.png"); //Assets/Textures/UI/Shotgun1.png greenShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun1.png"); //Assets/Textures/UI/Nailgun2.png blueNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Nailgun2.png"); //Assets/Textures/UI/NailgunOverheat.png greenNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/NailgunOverheat.png"); //Assets/Textures/UI/SawbladeLauncher.png blueSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncher.png"); //Assets/Textures/UI/SawbladeLauncherOverheat.png greenSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncherOverheat.png"); //Assets/Prefabs/Attacks and Projectiles/Coin.prefab coin = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Coin.prefab"); //Assets/Materials/GabrielFake.mat gabrielFakeMat = LoadObject<Material>("Assets/Materials/GabrielFake.mat"); //Assets/Prefabs/Enemies/Turret.prefab turret = LoadObject<GameObject>("Assets/Prefabs/Enemies/Turret.prefab").GetComponent<Turret>(); //Assets/Particles/Flashes/GunFlashDistant.prefab turretFinalFlash = LoadObject<GameObject>("Assets/Particles/Flashes/GunFlashDistant.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab sisyphusDestroyExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab"); //Assets/Prefabs/Effects/Charge Effect.prefab chargeEffect = LoadObject<GameObject>("Assets/Prefabs/Effects/Charge Effect.prefab"); //Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab maliciousFaceProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab"); } public static bool ultrapainDifficulty = false; public static bool realUltrapainDifficulty = false; public static GameObject currentDifficultyButton; public static GameObject currentDifficultyPanel; public static Text currentDifficultyInfoText; public void OnSceneChange(Scene before, Scene after) { StyleIDs.RegisterIDs(); ScenePatchCheck(); string mainMenuSceneName = "b3e7f2f8052488a45b35549efb98d902"; string bootSequenceSceneName = "4f8ecffaa98c2614f89922daf31fa22d"; string currentSceneName = SceneManager.GetActiveScene().name; if (currentSceneName == mainMenuSceneName) { LoadPrefabs(); //Canvas/Difficulty Select (1)/Violent Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Difficulty Select (1)"); GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect); currentDifficultyButton = ultrapainButton; ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value; ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5; RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>(); ultrapainTrans.anchoredPosition = new Vector2(20f, -104f); //Canvas/Difficulty Select (1)/Violent Info GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect); currentDifficultyPanel = info; currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>(); currentDifficultyInfoText.text = ConfigManager.pluginInfo.value; Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>(); currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--"; currentDifficultyHeaderText.resizeTextForBestFit = true; currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap; currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate; info.SetActive(false); EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>(); evt.triggers.Clear(); /*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(false));*/ EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit }; trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false)); evt.triggers.Add(trigger1); evt.triggers.Add(trigger2); foreach(EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>()) { if (trigger.gameObject == ultrapainButton) continue; EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false)); trigger.triggers.Add(closeTrigger); } } else if(currentSceneName == bootSequenceSceneName) { LoadPrefabs(); //Canvas/Difficulty Select (1)/Violent Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Intro/Difficulty Select"); GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect); currentDifficultyButton = ultrapainButton; ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value; ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5; RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>(); ultrapainTrans.anchoredPosition = new Vector2(20f, -104f); //Canvas/Difficulty Select (1)/Violent Info GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect); currentDifficultyPanel = info; currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>(); currentDifficultyInfoText.text = ConfigManager.pluginInfo.value; Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>(); currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--"; currentDifficultyHeaderText.resizeTextForBestFit = true; currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap; currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate; info.SetActive(false); EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>(); evt.triggers.Clear(); /*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(false));*/ EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit }; trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false)); evt.triggers.Add(trigger1); evt.triggers.Add(trigger2); foreach (EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>()) { if (trigger.gameObject == ultrapainButton) continue; EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false)); trigger.triggers.Add(closeTrigger); } } // LOAD CUSTOM PREFABS HERE TO AVOID MID GAME LAG MinosPrimeCharge.CreateDecoy(); GameObject shockwaveSisyphus = SisyphusInstructionist_Start.shockwave; } public static class StyleIDs { private static bool registered = false; public static void RegisterIDs() { registered = false; if (MonoSingleton<StyleHUD>.Instance == null) return; MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.grenadeBoostStyleText.guid, ConfigManager.grenadeBoostStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.rocketBoostStyleText.guid, ConfigManager.rocketBoostStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverStyleText.guid, ConfigManager.orbStrikeRevolverStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverChargedStyleText.guid, ConfigManager.orbStrikeRevolverChargedStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeElectricCannonStyleText.guid, ConfigManager.orbStrikeElectricCannonStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeMaliciousCannonStyleText.guid, ConfigManager.orbStrikeMaliciousCannonStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.maliciousChargebackStyleText.guid, ConfigManager.maliciousChargebackStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.sentryChargebackStyleText.guid, ConfigManager.sentryChargebackStyleText.formattedString); registered = true; Debug.Log("Registered all style ids"); } private static FieldInfo idNameDict = typeof(StyleHUD).GetField("idNameDict", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); public static void UpdateID(string id, string newName) { if (!registered || StyleHUD.Instance == null) return; (idNameDict.GetValue(StyleHUD.Instance) as Dictionary<string, string>)[id] = newName; } } public static Harmony harmonyTweaks; public static Harmony harmonyBase; private static MethodInfo GetMethod<T>(string name) { return typeof(T).GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } private static Dictionary<MethodInfo, HarmonyMethod> methodCache = new Dictionary<MethodInfo, HarmonyMethod>(); private static HarmonyMethod GetHarmonyMethod(MethodInfo method) { if (methodCache.TryGetValue(method, out HarmonyMethod harmonyMethod)) return harmonyMethod; else { harmonyMethod = new HarmonyMethod(method); methodCache.Add(method, harmonyMethod); return harmonyMethod; } } private static void PatchAllEnemies() { if (!ConfigManager.enemyTweakToggle.value) return; if (ConfigManager.friendlyFireDamageOverrideToggle.value) { harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<PhysicalShockwave>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<VirtueInsignia>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_FF>("Prefix"))); harmonyTweaks.Patch(GetMethod<Flammable>("Burn"), prefix: GetHarmonyMethod(GetMethod<Flammable_Burn_FF>("Prefix"))); harmonyTweaks.Patch(GetMethod<FireZone>("OnTriggerStay"), prefix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Postfix"))); } harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("UpdateModifiers"), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_UpdateModifiers>("Postfix"))); harmonyTweaks.Patch(GetMethod<StatueBoss>("Start"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Start_Patch>("Postfix"))); if (ConfigManager.cerberusDashToggle.value) harmonyTweaks.Patch(GetMethod<StatueBoss>("StopDash"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopDash_Patch>("Postfix"))); if(ConfigManager.cerberusParryable.value) { harmonyTweaks.Patch(GetMethod<StatueBoss>("StopTracking"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopTracking_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<StatueBoss>("Stomp"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Stomp_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Statue>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Statue_GetHurt_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Drone_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Drone>("Shoot"), prefix: GetHarmonyMethod(GetMethod<Drone_Shoot_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("PlaySound"), prefix: GetHarmonyMethod(GetMethod<Drone_PlaySound_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Update"), postfix: GetHarmonyMethod(GetMethod<Drone_Update>("Postfix"))); if(ConfigManager.droneHomeToggle.value) { harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Drone_Death_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Drone_GetHurt_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Ferryman>("Start"), postfix: GetHarmonyMethod(GetMethod<FerrymanStart>("Postfix"))); if(ConfigManager.ferrymanComboToggle.value) harmonyTweaks.Patch(GetMethod<Ferryman>("StopMoving"), postfix: GetHarmonyMethod(GetMethod<FerrymanStopMoving>("Postfix"))); if(ConfigManager.filthExplodeToggle.value) harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch2>("Prefix"))); if(ConfigManager.fleshPrisonSpinAttackToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<FleshPrisonShoot>("Postfix"))); if (ConfigManager.hideousMassInsigniaToggle.value) { harmonyTweaks.Patch(GetMethod<Projectile>("Explode"), postfix: GetHarmonyMethod(GetMethod<Projectile_Explode_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Mass>("ShootExplosive"), postfix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Postfix")), prefix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Prefix"))); } harmonyTweaks.Patch(GetMethod<SpiderBody>("Start"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<SpiderBody>("ChargeBeam"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ChargeBeam>("Postfix"))); harmonyTweaks.Patch(GetMethod<SpiderBody>("BeamChargeEnd"), prefix: GetHarmonyMethod(GetMethod<MaliciousFace_BeamChargeEnd>("Prefix"))); if (ConfigManager.maliciousFaceHomingProjectileToggle.value) { harmonyTweaks.Patch(GetMethod<SpiderBody>("ShootProj"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ShootProj_Patch>("Postfix"))); } if (ConfigManager.maliciousFaceRadianceOnEnrage.value) harmonyTweaks.Patch(GetMethod<SpiderBody>("Enrage"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Enrage_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Mindflayer>("Start"), postfix: GetHarmonyMethod(GetMethod<Mindflayer_Start_Patch>("Postfix"))); if (ConfigManager.mindflayerShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<Mindflayer>("ShootProjectiles"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_ShootProjectiles_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_MF>("Prefix"))); } if (ConfigManager.mindflayerTeleportComboToggle.value) { harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Mindflayer>("MeleeTeleport"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_MeleeTeleport_Patch>("Prefix"))); //harmonyTweaks.Patch(GetMethod<SwingCheck2>("DamageStop"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_DamageStop_Patch>("Postfix"))); } if (ConfigManager.minosPrimeRandomTeleportToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("Postfix"))); if (ConfigManager.minosPrimeTeleportTrail.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("Teleport"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("TeleportPostfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Start"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Dropkick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Dropkick>("Prefix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Combo"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Combo>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("StopAction"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_StopAction>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Ascend"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Ascend>("Prefix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Death"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Death>("Prefix"))); if (ConfigManager.minosPrimeCrushAttackToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("RiderKick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_RiderKick>("Prefix"))); if (ConfigManager.minosPrimeComboExplosiveEndToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_ProjectileCharge>("Prefix"))); if (ConfigManager.schismSpreadAttackToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ShootProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ShootProjectile_Patch>("Postfix"))); if (ConfigManager.soliderShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<Solider_Start_Patch>("Postfix"))); } if(ConfigManager.soliderCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_SpawnProjectile_Patch>("Postfix"))); if (ConfigManager.soliderShootGrenadeToggle.value || ConfigManager.soliderShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_ThrowProjectile_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Stalker>("SandExplode"), prefix: GetHarmonyMethod(GetMethod<Stalker_SandExplode_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SandificationZone>("Enter"), postfix: GetHarmonyMethod(GetMethod<SandificationZone_Enter_Patch>("Postfix"))); if (ConfigManager.strayCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Swing>("Postfix"))); if (ConfigManager.strayShootToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_Start_Patch1>("Postfix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ThrowProjectile_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<SwingEnd>("Prefix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("DamageEnd"), prefix: GetHarmonyMethod(GetMethod<DamageEnd>("Prefix"))); } if(ConfigManager.streetCleanerCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<Streetcleaner>("Start"), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Start_Patch>("Postfix"))); if(ConfigManager.streetCleanerPredictiveDodgeToggle.value) harmonyTweaks.Patch(GetMethod<BulletCheck>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<BulletCheck_OnTriggerEnter_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("Start"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Start>("Postfix"))); if (ConfigManager.swordsMachineNoLightKnockbackToggle.value || ConfigManager.swordsMachineSecondPhaseMode.value != ConfigManager.SwordsMachineSecondPhase.None) { harmonyTweaks.Patch(GetMethod<SwordsMachine>("Knockdown"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Knockdown_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("Down"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Prefix"))); //harmonyTweaks.Patch(GetMethod<SwordsMachine>("SetSpeed"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_SetSpeed_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("EndFirstPhase"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Prefix"))); } if (ConfigManager.swordsMachineExplosiveSwordToggle.value) { harmonyTweaks.Patch(GetMethod<ThrownSword>("Start"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<ThrownSword>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_OnTriggerEnter_Patch>("Postfix"))); } harmonyTweaks.Patch(GetMethod<Turret>("Start"), postfix: GetHarmonyMethod(GetMethod<TurretStart>("Postfix"))); if(ConfigManager.turretBurstFireToggle.value) { harmonyTweaks.Patch(GetMethod<Turret>("Shoot"), prefix: GetHarmonyMethod(GetMethod<TurretShoot>("Prefix"))); harmonyTweaks.Patch(GetMethod<Turret>("StartAiming"), postfix: GetHarmonyMethod(GetMethod<TurretAim>("Postfix"))); } harmonyTweaks.Patch(GetMethod<Explosion>("Start"), postfix: GetHarmonyMethod(GetMethod<V2CommonExplosion>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2FirstStart>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2FirstUpdate>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2FirstShootWeapon>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2SecondStart>("Postfix"))); //if(ConfigManager.v2SecondStartEnraged.value) // harmonyTweaks.Patch(GetMethod<BossHealthBar>("OnEnable"), postfix: GetHarmonyMethod(GetMethod<V2SecondEnrage>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2SecondUpdate>("Prefix"))); //harmonyTweaks.Patch(GetMethod<V2>("AltShootWeapon"), postfix: GetHarmonyMethod(GetMethod<V2AltShootWeapon>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("SwitchWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondSwitchWeapon>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Prefix")), postfix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Postfix"))); if(ConfigManager.v2SecondFastCoinToggle.value) harmonyTweaks.Patch(GetMethod<V2>("ThrowCoins"), prefix: GetHarmonyMethod(GetMethod<V2SecondFastCoin>("Prefix"))); harmonyTweaks.Patch(GetMethod<Cannonball>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<V2RocketLauncher>("CannonBallTriggerPrefix"))); if (ConfigManager.v2FirstSharpshooterToggle.value || ConfigManager.v2SecondSharpshooterToggle.value) { harmonyTweaks.Patch(GetMethod<EnemyRevolver>("PrepareAltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverPrepareAltFire>("Prefix"))); harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverBullet>("Prefix"))); harmonyTweaks.Patch(GetMethod<EnemyRevolver>("AltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverAltShoot>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Virtue_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Drone>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Virtue_SpawnInsignia_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Virtue_Death_Patch>("Prefix"))); if (ConfigManager.sisyInstJumpShockwave.value) { harmonyTweaks.Patch(GetMethod<Sisyphus>("Start"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Sisyphus>("Update"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Update>("Postfix"))); } if(ConfigManager.sisyInstBoulderShockwave.value) harmonyTweaks.Patch(GetMethod<Sisyphus>("SetupExplosion"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_SetupExplosion>("Postfix"))); if(ConfigManager.sisyInstStrongerExplosion.value) harmonyTweaks.Patch(GetMethod<Sisyphus>("StompExplosion"), prefix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_StompExplosion>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("Awake"), postfix: GetHarmonyMethod(GetMethod<LeviathanTail_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("BigSplash"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_BigSplash>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_SwingEnd>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("Start"), postfix: GetHarmonyMethod(GetMethod<Leviathan_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurst"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurstStart"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurstStart>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<Leviathan_FixedUpdate>("Prefix"))); if (ConfigManager.somethingWickedSpear.value) { harmonyTweaks.Patch(GetMethod<Wicked>("Start"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_GetHit>("Postfix"))); } if(ConfigManager.somethingWickedSpawnOn43.value) { harmonyTweaks.Patch(GetMethod<ObjectActivator>("Activate"), prefix: GetHarmonyMethod(GetMethod<ObjectActivator_Activate>("Prefix"))); harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<JokeWicked_GetHit>("Postfix"))); } if (ConfigManager.panopticonFullPhase.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Panopticon_Start>("Postfix"))); if (ConfigManager.panopticonAxisBeam.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnInsignia>("Prefix"))); if (ConfigManager.panopticonSpinAttackToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<Panopticon_HomingProjectileAttack>("Postfix"))); if (ConfigManager.panopticonBlackholeProj.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnBlackHole"), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnBlackHole>("Postfix"))); if (ConfigManager.panopticonBalanceEyes.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnFleshDrones"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Postfix"))); if (ConfigManager.panopticonBlueProjToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Update"), transpiler: GetHarmonyMethod(GetMethod<Panopticon_BlueProjectile>("Transpiler"))); if (ConfigManager.idolExplosionToggle.value) harmonyTweaks.Patch(GetMethod<Idol>("Death"), postfix: GetHarmonyMethod(GetMethod<Idol_Death_Patch>("Postfix"))); // ADDME /* harmonyTweaks.Patch(GetMethod<GabrielSecond>("Start"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("BasicCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_BasicCombo>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("FastCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_FastCombo>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("CombineSwords"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_CombineSwords>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("ThrowCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_ThrowCombo>("Postfix"))); */ } private static void PatchAllPlayers() { if (!ConfigManager.playerTweakToggle.value) return; harmonyTweaks.Patch(GetMethod<Punch>("CheckForProjectile"), prefix: GetHarmonyMethod(GetMethod<Punch_CheckForProjectile_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch1>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Collision"), prefix: GetHarmonyMethod(GetMethod<Grenade_Collision_Patch>("Prefix"))); if (ConfigManager.rocketBoostToggle.value) harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_Patch>("Prefix"))); if (ConfigManager.rocketGrabbingToggle.value) harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate_Patch>("Prefix"))); if (ConfigManager.orbStrikeToggle.value) { harmonyTweaks.Patch(GetMethod<Coin>("Start"), postfix: GetHarmonyMethod(GetMethod<Coin_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Punch>("BlastCheck"), prefix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Postfix"))); harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide>("Prefix"))); harmonyTweaks.Patch(GetMethod<Coin>("DelayedReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_DelayedReflectRevolver>("Postfix"))); harmonyTweaks.Patch(GetMethod<Coin>("ReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Postfix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Prefix")), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Postfix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("ExecuteHits"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Prefix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("HitSomething"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Prefix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("Start"), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_Start>("Prefix"))); harmonyTweaks.Patch(GetMethod<Cannonball>("Explode"), prefix: GetHarmonyMethod(GetMethod<Cannonball_Explode>("Prefix"))); harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_CollideOrbital>("Prefix"))); } if(ConfigManager.chargedRevRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<Revolver>("Update"), prefix: GetHarmonyMethod(GetMethod<Revolver_Update>("Prefix"))); if(ConfigManager.coinRegSpeedMulti.value != 1 || ConfigManager.sharpshooterRegSpeedMulti.value != 1 || ConfigManager.railcannonRegSpeedMulti.value != 1 || ConfigManager.rocketFreezeRegSpeedMulti.value != 1 || ConfigManager.rocketCannonballRegSpeedMulti.value != 1 || ConfigManager.nailgunAmmoRegSpeedMulti.value != 1 || ConfigManager.sawAmmoRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<WeaponCharges>("Charge"), prefix: GetHarmonyMethod(GetMethod<WeaponCharges_Charge>("Prefix"))); if(ConfigManager.nailgunHeatsinkRegSpeedMulti.value != 1 || ConfigManager.sawHeatsinkRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<Nailgun>("Update"), prefix: GetHarmonyMethod(GetMethod<NailGun_Update>("Prefix"))); if(ConfigManager.staminaRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<NewMovement>("Update"), prefix: GetHarmonyMethod(GetMethod<NewMovement_Update>("Prefix"))); if(ConfigManager.playerHpDeltaToggle.value || ConfigManager.maxPlayerHp.value != 100 || ConfigManager.playerHpSupercharge.value != 200 || ConfigManager.whiplashHardDamageCap.value != 50 || ConfigManager.whiplashHardDamageSpeed.value != 1) { harmonyTweaks.Patch(GetMethod<NewMovement>("GetHealth"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHealth>("Prefix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("SuperCharge"), prefix: GetHarmonyMethod(GetMethod<NewMovement_SuperCharge>("Prefix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("Respawn"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Respawn>("Postfix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("Start"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Transpiler"))); harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), transpiler: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate>("Transpiler"))); harmonyTweaks.Patch(GetMethod<NewMovement>("ForceAntiHP"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_ForceAntiHP>("Transpiler"))); } // ADDME harmonyTweaks.Patch(GetMethod<Revolver>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Revolver_Shoot>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Shotgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Transpiler")), prefix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Postfix"))); harmonyTweaks.Patch(GetMethod<Shotgun>("ShootSinks"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_ShootSinks>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Nailgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_Shoot>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Nailgun>("SuperSaw"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_SuperSaw>("Transpiler"))); if (ConfigManager.hardDamagePercent.normalizedValue != 1) harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Prefix")), postfix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Postfix"))); harmonyTweaks.Patch(GetMethod<HealthBar>("Start"), postfix: GetHarmonyMethod(GetMethod<HealthBar_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<HealthBar>("Update"), transpiler: GetHarmonyMethod(GetMethod<HealthBar_Update>("Transpiler"))); foreach (HealthBarTracker hb in HealthBarTracker.instances) { if (hb != null) hb.SetSliderRange(); } harmonyTweaks.Patch(GetMethod<Harpoon>("Start"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Start>("Postfix"))); if(ConfigManager.screwDriverHomeToggle.value) harmonyTweaks.Patch(GetMethod<Harpoon>("Punched"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Punched>("Postfix"))); if(ConfigManager.screwDriverSplitToggle.value) harmonyTweaks.Patch(GetMethod<Harpoon>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<Harpoon_OnTriggerEnter_Patch>("Prefix"))); } private static void PatchAllMemes() { if (ConfigManager.enrageSfxToggle.value) harmonyTweaks.Patch(GetMethod<EnrageEffect>("Start"), postfix: GetHarmonyMethod(GetMethod<EnrageEffect_Start>("Postfix"))); if(ConfigManager.funnyDruidKnightSFXToggle.value) { harmonyTweaks.Patch(GetMethod<Mandalore>("FullBurst"), postfix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Postfix")), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<Mandalore>("FullerBurst"), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullerBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Explode"), prefix: GetHarmonyMethod(GetMethod<Drone_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Drone_Explode>("Postfix"))); } if (ConfigManager.fleshObamiumToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Prefix"))); if (ConfigManager.obamapticonToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Prefix"))); } public static bool methodsPatched = false; public static void ScenePatchCheck() { if(methodsPatched && !ultrapainDifficulty) { harmonyTweaks.UnpatchSelf(); methodsPatched = false; } else if(!methodsPatched && ultrapainDifficulty) { PatchAll(); } } public static void PatchAll() { harmonyTweaks.UnpatchSelf(); methodsPatched = false; if (!ultrapainDifficulty) return; if(realUltrapainDifficulty && ConfigManager.discordRichPresenceToggle.value) harmonyTweaks.Patch(GetMethod<DiscordController>("SendActivity"), prefix: GetHarmonyMethod(GetMethod<DiscordController_SendActivity_Patch>("Prefix"))); if (realUltrapainDifficulty && ConfigManager.steamRichPresenceToggle.value) harmonyTweaks.Patch(GetMethod<SteamFriends>("SetRichPresence"), prefix: GetHarmonyMethod(GetMethod<SteamFriends_SetRichPresence_Patch>("Prefix"))); PatchAllEnemies(); PatchAllPlayers(); PatchAllMemes(); methodsPatched = true; } public static string workingPath; public static string workingDir; public static AssetBundle bundle; public static AudioClip druidKnightFullAutoAud; public static AudioClip druidKnightFullerAutoAud; public static AudioClip druidKnightDeathAud; public static AudioClip enrageAudioCustom; public static GameObject fleshObamium; public static GameObject obamapticon; public void Awake() { instance = this; workingPath = Assembly.GetExecutingAssembly().Location; workingDir = Path.GetDirectoryName(workingPath); Logger.LogInfo($"Working path: {workingPath}, Working dir: {workingDir}"); try { bundle = AssetBundle.LoadFromFile(Path.Combine(workingDir, "ultrapain")); druidKnightFullAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullauto.wav"); druidKnightFullerAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullerauto.wav"); druidKnightDeathAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/death.wav"); enrageAudioCustom = bundle.LoadAsset<AudioClip>("assets/ultrapain/sfx/enraged.wav"); fleshObamium = bundle.LoadAsset<GameObject>("assets/ultrapain/fleshprison/fleshobamium.prefab"); obamapticon = bundle.LoadAsset<GameObject>("assets/ultrapain/panopticon/obamapticon.prefab"); } catch (Exception e) { Logger.LogError($"Could not load the asset bundle:\n{e}"); } // DEBUG /*string logPath = Path.Combine(Environment.CurrentDirectory, "log.txt"); Logger.LogInfo($"Saving to {logPath}"); List<string> assetPaths = new List<string>() { "fonts.bundle", "videos.bundle", "shaders.bundle", "particles.bundle", "materials.bundle", "animations.bundle", "prefabs.bundle", "physicsmaterials.bundle", "models.bundle", "textures.bundle", }; //using (FileStream log = File.Open(logPath, FileMode.OpenOrCreate, FileAccess.Write)) //{ foreach(string assetPath in assetPaths) { Logger.LogInfo($"Attempting to load {assetPath}"); AssetBundle bundle = AssetBundle.LoadFromFile(Path.Combine(bundlePath, assetPath)); bundles.Add(bundle); //foreach (string name in bundle.GetAllAssetNames()) //{ // string line = $"[{bundle.name}][{name}]\n"; // log.Write(Encoding.ASCII.GetBytes(line), 0, line.Length); //} bundle.LoadAllAssets(); } //} */ // Plugin startup logic Logger.LogInfo($"Plugin {PluginInfo.PLUGIN_GUID} is loaded!"); harmonyTweaks = new Harmony(PLUGIN_GUID + "_tweaks"); harmonyBase = new Harmony(PLUGIN_GUID + "_base"); harmonyBase.Patch(GetMethod<DifficultySelectButton>("SetDifficulty"), postfix: GetHarmonyMethod(GetMethod<DifficultySelectPatch>("Postfix"))); harmonyBase.Patch(GetMethod<DifficultyTitle>("Check"), postfix: GetHarmonyMethod(GetMethod<DifficultyTitle_Check_Patch>("Postfix"))); harmonyBase.Patch(typeof(PrefsManager).GetConstructor(new Type[0]), postfix: GetHarmonyMethod(GetMethod<PrefsManager_Ctor>("Postfix"))); harmonyBase.Patch(GetMethod<PrefsManager>("EnsureValid"), prefix: GetHarmonyMethod(GetMethod<PrefsManager_EnsureValid>("Prefix"))); harmonyBase.Patch(GetMethod<Grenade>("Explode"), prefix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Prefix")), postfix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Postfix"))); LoadPrefabs(); ConfigManager.Initialize(); SceneManager.activeSceneChanged += OnSceneChange; } } public static class Tools { private static Transform _target; private static Transform target { get { if(_target == null) _target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); return _target; } } public static Vector3 PredictPlayerPosition(float speedMod, Collider enemyCol = null) { Vector3 projectedPlayerPos; if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f) { return target.position; } RaycastHit raycastHit; if (enemyCol != null && Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == enemyCol) { projectedPlayerPos = target.position; } else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { projectedPlayerPos = raycastHit.point; } else { projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod; projectedPlayerPos = new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z); } return projectedPlayerPos; } } // Asset destroyer tracker /*[HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object) })] public class TempClass1 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object), typeof(float) })] public class TempClass2 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object) })] public class TempClass3 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object), typeof(bool) })] public class TempClass4 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } }*/ }
Ultrapain/Plugin.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static ConfigPanel leviathanPanel;\n public static ConfigPanel somethingWickedPanel;\n public static ConfigPanel panopticonPanel;\n public static ConfigPanel idolPanel;\n // GLOBAL ENEMY CONFIG\n public static BoolField friendlyFireDamageOverrideToggle;\n public static FloatSliderField friendlyFireDamageOverrideExplosion;\n public static FloatSliderField friendlyFireDamageOverrideProjectile;\n public static FloatSliderField friendlyFireDamageOverrideFire;\n public static FloatSliderField friendlyFireDamageOverrideMelee;", "score": 0.8681924939155579 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static ConfigPanel cerberusPanel;\n public static ConfigPanel dronePanel;\n public static ConfigPanel filthPanel;\n public static ConfigPanel hideousMassPanel;\n public static ConfigPanel maliciousFacePanel;\n public static ConfigPanel mindflayerPanel;\n public static ConfigPanel schismPanel;\n public static ConfigPanel soliderPanel;\n public static ConfigPanel stalkerPanel;\n public static ConfigPanel strayPanel;", "score": 0.8630756735801697 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " }\n // ROOT PANEL\n public static BoolField enemyTweakToggle;\n private static ConfigPanel enemyPanel;\n public static BoolField playerTweakToggle;\n private static ConfigPanel playerPanel;\n public static BoolField discordRichPresenceToggle;\n public static BoolField steamRichPresenceToggle;\n public static StringField pluginName;\n public static StringMultilineField pluginInfo;", "score": 0.854292631149292 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static ConfigPanel streetCleanerPanel;\n public static ConfigPanel swordsMachinePanel;\n public static ConfigPanel virtuePanel;\n public static ConfigPanel ferrymanPanel;\n public static ConfigPanel turretPanel;\n public static ConfigPanel fleshPrisonPanel;\n public static ConfigPanel minosPrimePanel;\n public static ConfigPanel v2FirstPanel;\n public static ConfigPanel v2SecondPanel;\n public static ConfigPanel sisyInstPanel;", "score": 0.8458529710769653 }, { "filename": "Ultrapain/Patches/Stray.cs", "retrieved_chunk": " public GameObject standardProjectile;\n public GameObject standardDecorativeProjectile;\n public int comboRemaining = ConfigManager.strayShootCount.value;\n public bool inCombo = false;\n public float lastSpeed = 1f;\n public enum AttackMode\n {\n ProjectileCombo,\n FastHoming\n }", "score": 0.8402191996574402 } ]
csharp
GameObject lightningStrikeExplosiveSetup;
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using XiaoFeng; using FayElf.Plugins.WeChat.OfficialAccount.Model; /**************************************************************** * Copyright © (2022) www.fayelf.com All Rights Reserved. * * Author : jacky * * QQ : 7092734 * * Email : [email protected] * * Site : www.fayelf.com * * Create Time : 2022-03-16 10:55:30 * * Version : v 1.0.0 * * CLR Version : 4.0.30319.42000 * *****************************************************************/ namespace FayElf.Plugins.WeChat.OfficialAccount { /// <summary> /// 自定义菜单操作类 /// </summary> public class Menu { #region 构造器 /// <summary> /// 无参构造器 /// </summary> public Menu() { this.Config = Config.Current; } #endregion #region 属性 /// <summary> /// 配置 /// </summary> public Config Config { get; set; } #endregion #region 方法 #region 创建菜单 /// <summary> /// 创建菜单 /// </summary> /// <param name="buttons">菜单列表</param> /// <returns></returns> public BaseResult CreateMenu(List<
ButtonModel> buttons) {
if (buttons == null || buttons.Count == 0) return new BaseResult { ErrCode = 500, ErrMsg = "数据不能为空." }; var config = this.Config.GetConfig(WeChatType.OfficeAccount); return Common.Execute(config.AppID, config.AppSecret, token => { var response = XiaoFeng.Http.HttpHelper.GetHtml(new XiaoFeng.Http.HttpRequest { Method = "POST", Address = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + token.AccessToken, BodyData = buttons.ToJson() }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return response.Html.JsonToObject<BaseResult>(); } else { return new BaseResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); } #endregion #region 删除菜单 /// <summary> /// 删除菜单 /// </summary> /// <returns></returns> public BaseResult DeleteMenu() { var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = XiaoFeng.Http.HttpHelper.GetHtml(new XiaoFeng.Http.HttpRequest { Method = "GET", Address = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + token.AccessToken }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return response.Html.JsonToObject<BaseResult>(); } else { return new BaseResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); } #endregion #region 获取自定义菜单 /// <summary> /// 获取自定义菜单 /// </summary> /// <returns></returns> public MenuModel GetMenu() { var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = XiaoFeng.Http.HttpHelper.GetHtml(new XiaoFeng.Http.HttpRequest { Method = "GET", Address = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + token.AccessToken }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return response.Html.JsonToObject<MenuModel>(); } else { return new MenuModel { ErrCode = 500, ErrMsg = "请求失败." }; } }); } #endregion #endregion } }
OfficialAccount/Menu.cs
zhuovi-FayElf.Plugins.WeChat-5725d1e
[ { "filename": "OfficialAccount/Subscribe.cs", "retrieved_chunk": " #endregion\n #region 删除模板\n /// <summary>\n /// 删除模板\n /// </summary>\n /// <param name=\"priTmplId\">要删除的模板id</param>\n /// <returns></returns>\n public BaseResult DeleteTemplate(string priTmplId)\n {\n var config = this.Config.GetConfig(WeChatType.Applets);", "score": 0.8319902420043945 }, { "filename": "OfficialAccount/Model/MenuModel.cs", "retrieved_chunk": " #endregion\n #region 属性\n /// <summary>\n /// 菜单对象\n /// </summary>\n [JsonElement(\"menu\")]\n public Button Menu { get; set; }\n #endregion\n #region 方法\n #endregion", "score": 0.8191357851028442 }, { "filename": "Model/Config.cs", "retrieved_chunk": " /// <summary>\n /// 开放平台配置\n /// </summary>\n [Description(\"开放平台配置\")]\n public WeChatConfig OpenPlatform { get; set; } = new WeChatConfig();\n /// <summary>\n /// 获取配置\n /// </summary>\n /// <param name=\"weChatType\">配置类型</param>\n /// <returns></returns>", "score": 0.8110744953155518 }, { "filename": "Applets/Applets.cs", "retrieved_chunk": " #endregion\n #region 获取用户encryptKey\n /// <summary>\n /// 获取用户encryptKey\n /// </summary>\n /// <param name=\"session\">Session数据</param>\n /// <returns></returns>\n public UserEncryptKeyData GetUserEncryptKey(JsCodeSessionData session)\n {\n var config = this.Config.GetConfig(WeChatType.Applets);", "score": 0.8102439641952515 }, { "filename": "Applets/Applets.cs", "retrieved_chunk": " }\n });\n }\n #endregion\n #region 获取用户手机号\n /// <summary>\n /// 获取用户手机号\n /// </summary>\n /// <param name=\"code\">手机号获取凭证</param>\n /// <returns></returns>", "score": 0.8094196319580078 } ]
csharp
ButtonModel> buttons) {
using HarmonyLib; using UnityEngine; namespace Ultrapain.Patches { class Solider_Start_Patch { static void Postfix(ZombieProjectiles __instance, ref
GameObject ___decProjectile, ref GameObject ___projectile, ref EnemyIdentifier ___eid, ref Animator ___anim) {
if (___eid.enemyType != EnemyType.Soldier) return; /*___projectile = Plugin.soliderBullet; if (Plugin.decorativeProjectile2.gameObject != null) ___decProjectile = Plugin.decorativeProjectile2.gameObject;*/ __instance.gameObject.AddComponent<SoliderShootCounter>(); } } class Solider_SpawnProjectile_Patch { static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid, ref GameObject ___origWP) { if (___eid.enemyType != EnemyType.Soldier) return; ___eid.weakPoint = null; } } class SoliderGrenadeFlag : MonoBehaviour { public GameObject tempExplosion; } class Solider_ThrowProjectile_Patch { static void Postfix(ZombieProjectiles __instance, ref GameObject ___currentProjectile, ref EnemyIdentifier ___eid, ref GameObject ___player, ref Animator ___anim, ref float ___coolDown) { if (___eid.enemyType != EnemyType.Soldier) return; ___currentProjectile.GetComponent<ProjectileSpread>().spreadAmount = 10; ___currentProjectile.SetActive(true); SoliderShootCounter counter = __instance.gameObject.GetComponent<SoliderShootCounter>(); if (counter.remainingShots > 0) { counter.remainingShots -= 1; if (counter.remainingShots != 0) { ___anim.Play("Shoot", 0, Plugin.SoliderShootAnimationStart / 2f); ___anim.fireEvents = true; __instance.DamageStart(); ___coolDown = 0; } else { counter.remainingShots = ConfigManager.soliderShootCount.value; if (ConfigManager.soliderShootGrenadeToggle.value) { GameObject grenade = GameObject.Instantiate(Plugin.shotgunGrenade.gameObject, ___currentProjectile.transform.position, ___currentProjectile.transform.rotation); grenade.transform.Translate(Vector3.forward * 0.5f); Vector3 targetPos = Plugin.PredictPlayerPosition(__instance.GetComponent<Collider>(), ___eid.totalSpeedModifier); grenade.transform.LookAt(targetPos); Rigidbody rb = grenade.GetComponent<Rigidbody>(); //rb.maxAngularVelocity = 10000; //foreach (Rigidbody r in grenade.GetComponentsInChildren<Rigidbody>()) // r.maxAngularVelocity = 10000; rb.AddForce(grenade.transform.forward * Plugin.SoliderGrenadeForce); //rb.velocity = ___currentProjectile.transform.forward * Plugin.instance.SoliderGrenadeForce; rb.useGravity = false; grenade.GetComponent<Grenade>().enemy = true; grenade.GetComponent<Grenade>().CanCollideWithPlayer(true); grenade.AddComponent<SoliderGrenadeFlag>(); } } } //counter.remainingShots = ConfigManager.soliderShootCount.value; } } class Grenade_Explode_Patch { static bool Prefix(Grenade __instance, out bool __state) { __state = false; SoliderGrenadeFlag flag = __instance.GetComponent<SoliderGrenadeFlag>(); if (flag == null) return true; flag.tempExplosion = GameObject.Instantiate(__instance.explosion); __state = true; foreach(Explosion e in flag.tempExplosion.GetComponentsInChildren<Explosion>()) { e.damage = ConfigManager.soliderGrenadeDamage.value; e.maxSize *= ConfigManager.soliderGrenadeSize.value; e.speed *= ConfigManager.soliderGrenadeSize.value; } __instance.explosion = flag.tempExplosion; return true; } static void Postfix(Grenade __instance, bool __state) { if (!__state) return; SoliderGrenadeFlag flag = __instance.GetComponent<SoliderGrenadeFlag>(); GameObject.Destroy(flag.tempExplosion); } } class SoliderShootCounter : MonoBehaviour { public int remainingShots = ConfigManager.soliderShootCount.value; } }
Ultrapain/Patches/Solider.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Schism.cs", "retrieved_chunk": "using HarmonyLib;\nusing System.ComponentModel;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class ZombieProjectile_ShootProjectile_Patch\n {\n static void Postfix(ZombieProjectiles __instance, ref GameObject ___currentProjectile, Animator ___anim, EnemyIdentifier ___eid)\n {\n /*Projectile proj = ___currentProjectile.GetComponent<Projectile>();", "score": 0.9158387184143066 }, { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": "using HarmonyLib;\nusing System.Reflection;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class Mindflayer_Start_Patch\n {\n static void Postfix(Mindflayer __instance, ref EnemyIdentifier ___eid)\n {\n __instance.gameObject.AddComponent<MindflayerPatch>();", "score": 0.8709108829498291 }, { "filename": "Ultrapain/Patches/Virtue.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class Virtue_Start_Patch\n {\n static void Postfix(Drone __instance, ref EnemyIdentifier ___eid)\n {\n VirtueFlag flag = __instance.gameObject.AddComponent<VirtueFlag>();\n flag.virtue = __instance;", "score": 0.8625016808509827 }, { "filename": "Ultrapain/Patches/Filth.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class SwingCheck2_CheckCollision_Patch2\n {\n static bool Prefix(SwingCheck2 __instance, Collider __0, EnemyIdentifier ___eid)\n {\n if (__0.gameObject.tag != \"Player\")\n return true;", "score": 0.859668493270874 }, { "filename": "Ultrapain/Patches/Stalker.cs", "retrieved_chunk": "using HarmonyLib;\nusing ULTRAKILL.Cheats;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n public class Stalker_SandExplode_Patch\n {\n static bool Prefix(Stalker __instance, ref int ___difficulty, ref EnemyIdentifier ___eid, int __0,\n ref bool ___exploding, ref float ___countDownAmount, ref float ___explosionCharge,\n ref Color ___currentColor, Color[] ___lightColors, AudioSource ___lightAud, AudioClip[] ___lightSounds,", "score": 0.859129011631012 } ]
csharp
GameObject ___decProjectile, ref GameObject ___projectile, ref EnemyIdentifier ___eid, ref Animator ___anim) {
using UnityEngine; namespace SimplestarGame { public class TemplateTexts : MonoBehaviour { [SerializeField]
ButtonPressDetection buttonHi;
[SerializeField] ButtonPressDetection buttonHello; [SerializeField] ButtonPressDetection buttonGood; [SerializeField] ButtonPressDetection buttonOK; [SerializeField] TMPro.TMP_InputField inputField; void Start() { this.buttonHi.onReleased += this.OnClickHi; this.buttonHello.onReleased += this.OnClickHello; this.buttonGood.onReleased += this.OnClickGood; this.buttonOK.onReleased += this.OnClickOK; } void OnClickOK() { this.inputField.text = "OK!"; } void OnClickGood() { this.inputField.text = "Good!"; } void OnClickHello() { this.inputField.text = "Hello."; } void OnClickHi() { this.inputField.text = "Hi."; } } }
Assets/SimplestarGame/Network/Scripts/Sample/TemplateTexts.cs
simplestargame-SimpleChatPhoton-4ebfbd5
[ { "filename": "Assets/SimplestarGame/Network/Scripts/Tools/FPSCounter.cs", "retrieved_chunk": "using UnityEngine;\nnamespace SimplestarGame\n{\n public class FPSCounter : MonoBehaviour\n {\n void Update()\n {\n if (SceneContext.Instance.fpsText == null)\n {\n return;", "score": 0.7887877225875854 }, { "filename": "Assets/SimplestarGame/Network/Scripts/Tools/SimpleCameraController.cs", "retrieved_chunk": "#if ENABLE_INPUT_SYSTEM\nusing UnityEngine.InputSystem;\n#endif\nusing UnityEngine;\nnamespace UnityTemplateProjects\n{\n public class SimpleCameraController : MonoBehaviour\n {\n [SerializeField] TMPro.TMP_InputField inputField;\n class CameraState", "score": 0.7886538505554199 }, { "filename": "Assets/SimplestarGame/Network/Scripts/Tools/FaceCamera.cs", "retrieved_chunk": "using UnityEngine;\nnamespace SimplestarGame\n{\n public class FaceCamera : MonoBehaviour\n {\n void Start()\n {\n this.mainCameraTransform = Camera.main.transform;\n }\n void LateUpdate()", "score": 0.7838646173477173 }, { "filename": "Assets/SimplestarGame/Network/Scripts/Runner/Game/NetworkGame.cs", "retrieved_chunk": "using Fusion;\nusing System;\nusing System.Linq;\nusing UnityEngine;\nnamespace SimplestarGame\n{\n public class NetworkGame : NetworkBehaviour\n {\n [SerializeField] Vector3[] spawnPoints;\n [SerializeField] Color[] playerColors;", "score": 0.7695273756980896 }, { "filename": "Assets/SimplestarGame/Network/Scripts/Scene/SceneContext.cs", "retrieved_chunk": "using UnityEngine;\nnamespace SimplestarGame\n{\n public class SceneContext : MonoBehaviour\n {\n [SerializeField] internal NetworkPlayerInput PlayerInput;\n [SerializeField] internal TMPro.TextMeshProUGUI fpsText;\n [SerializeField] internal TMPro.TextMeshProUGUI hostClientText;\n [SerializeField] internal ButtonPressDetection buttonUp;\n [SerializeField] internal ButtonPressDetection buttonDown;", "score": 0.7611380815505981 } ]
csharp
ButtonPressDetection buttonHi;
using Microsoft.AspNetCore.Mvc; using WebApi.Models; using WebApi.Services; namespace WebApi.Controllers { [Route("api/[controller]")] [ApiController] [Consumes("application/json")] [Produces("application/json")] public class ChatController : ControllerBase { private readonly IValidationService _validation; private readonly IOpenAIService _openai; private readonly ILogger<ChatController> _logger; public ChatController(IValidationService validation, IOpenAIService openai, ILogger<ChatController> logger) { this._validation = validation ?? throw new ArgumentNullException(nameof(validation)); this._openai = openai ?? throw new ArgumentNullException(nameof(openai)); this._logger = logger ?? throw new ArgumentNullException(nameof(logger)); } [HttpPost("completions", Name = "ChatCompletions")] [ProducesResponseType(typeof(ChatCompletionResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status401Unauthorized)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] public async Task<IActionResult> Post([FromBody]
ChatCompletionRequest req) {
var validation = this._validation.ValidateHeaders<ChatCompletionRequestHeaders>(this.Request.Headers); if (validation.Validated != true) { return await Task.FromResult(validation.ActionResult); } var pvr = this._validation.ValidatePayload(req); if (pvr.Validated != true) { return await Task.FromResult(pvr.ActionResult); } var res = await this._openai.GetChatCompletionAsync(pvr.Payload.Prompt); return new OkObjectResult(res); } } }
src/IssueSummaryApi/Controllers/ChatController.cs
Azure-Samples-vs-apim-cuscon-powerfx-500a170
[ { "filename": "src/IssueSummaryApi/Controllers/GitHubController.cs", "retrieved_chunk": " [HttpGet(\"issues\", Name = \"Issues\")]\n [ProducesResponseType(typeof(GitHubIssueCollectionResponse), StatusCodes.Status200OK)]\n [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status401Unauthorized)]\n [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)]\n public async Task<IActionResult> GetIssues([FromQuery] GitHubApiRequestQueries req)\n {\n var hvr = this._validation.ValidateHeaders<GitHubApiRequestHeaders>(this.Request.Headers);\n if (hvr.Validated != true)\n {\n return await Task.FromResult(hvr.ActionResult);", "score": 0.8617610931396484 }, { "filename": "src/IssueSummaryApi/Controllers/GitHubController.cs", "retrieved_chunk": " [ProducesResponseType(typeof(GitHubIssueItemResponse), StatusCodes.Status200OK)]\n [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status401Unauthorized)]\n [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)]\n public async Task<IActionResult> GetIssue(int id, [FromQuery] GitHubApiRequestQueries req)\n {\n var validation = this._validation.ValidateHeaders<GitHubApiRequestHeaders>(this.Request.Headers);\n if (validation.Validated != true)\n {\n return await Task.FromResult(validation.ActionResult);\n }", "score": 0.8483625650405884 }, { "filename": "src/IssueSummaryApi/Controllers/GitHubController.cs", "retrieved_chunk": " [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status401Unauthorized)]\n [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)]\n public async Task<IActionResult> GetIssueSummary(int id, [FromQuery] GitHubApiRequestQueries req)\n {\n var validation = this._validation.ValidateHeaders<GitHubApiRequestHeaders>(this.Request.Headers);\n if (validation.Validated != true)\n {\n return await Task.FromResult(validation.ActionResult);\n }\n var qvr = this._validation.ValidateQueries(req);", "score": 0.8179060816764832 }, { "filename": "src/IssueSummaryApi/Services/OpenAIService.cs", "retrieved_chunk": " private readonly IOpenAIHelper _helper;\n public OpenAIService(IOpenAIHelper helper)\n {\n this._helper = helper ?? throw new ArgumentNullException(nameof(helper));\n }\n public async Task<ChatCompletionResponse> GetChatCompletionAsync(string prompt)\n {\n var res = await this._helper.GetChatCompletionAsync(prompt);\n return res;\n }", "score": 0.774531364440918 }, { "filename": "src/IssueSummaryApi/Controllers/GitHubController.cs", "retrieved_chunk": " var qvr = this._validation.ValidateQueries(req);\n if (qvr.Validated != true)\n {\n return await Task.FromResult(qvr.ActionResult);\n }\n var res = await this._github.GetIssueAsync(id, validation.Headers, qvr.Queries);\n return new OkObjectResult(res);\n }\n [HttpGet(\"issues/{id}/summary\", Name = \"IssueSummaryById\")]\n [ProducesResponseType(typeof(GitHubIssueItemSummaryResponse), StatusCodes.Status200OK)]", "score": 0.7470828294754028 } ]
csharp
ChatCompletionRequest req) {
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WAGIapp.AI.AICommands { internal class AddNoteCommand : Command { public override string
Name => "add-note";
public override string Description => "Adds a note to the list"; public override string Format => "add-note | text to add to the list"; public override async Task<string> Execute(Master caller, string[] args) { if (args.Length < 2) return "error! not enough parameters"; caller.Notes.Add(args[1]); return "Note added"; } } }
WAGIapp/AI/AICommands/AddNoteCommand.cs
Woltvint-WAGI-d808927
[ { "filename": "WAGIapp/AI/AICommands/RemoveNoteCommand.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace WAGIapp.AI.AICommands\n{\n internal class RemoveNoteCommand : Command\n {\n public override string Name => \"remove-note\";", "score": 0.975655198097229 }, { "filename": "WAGIapp/AI/AICommands/SearchWebCommand.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace WAGIapp.AI.AICommands\n{\n internal class SearchWebCommand : Command\n {\n public override string Name => \"search-web\";", "score": 0.9575464725494385 }, { "filename": "WAGIapp/AI/AICommands/GoalReachedCommand.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace WAGIapp.AI.AICommands\n{\n internal class GoalReachedCommand : Command\n {\n public override string Name => \"goal-reached\";", "score": 0.9534977078437805 }, { "filename": "WAGIapp/AI/AICommands/NoActionCommand.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Security.Cryptography.X509Certificates;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace WAGIapp.AI.AICommands\n{\n internal class NoActionCommand : Command\n {", "score": 0.8927481770515442 }, { "filename": "WAGIapp/AI/OpenAI.cs", "retrieved_chunk": "/*using OpenAI.Chat;\nusing OpenAI.Models;\nusing OpenAI;*/\nusing System.Net.Http.Headers;\nusing System.Text.Json;\nnamespace WAGIapp.AI\n{\n internal class OpenAI\n {\n public static async Task<string> GetChatCompletion(string model, List<ChatMessage> messages, int maxTokens = 8192)", "score": 0.8264211416244507 } ]
csharp
Name => "add-note";
/* Copyright (c) 2023 Xavier Arpa López Thomas Peter ('Kingdox') Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; namespace Kingdox.UniFlux.Core.Internal { /// <summary> /// The `FuncFluxParam` class represents a flux that stores functions with one parameter of type `TParam` and a return value of type `TReturn`. /// It provides a dictionary to store the functions and methods to subscribe and trigger the stored functions. /// </summary> /// <typeparam name="TKey">The type of the keys used to store the functions in the dictionary.</typeparam> /// <typeparam name="TParam">The type of the parameter passed to the functions stored in the dictionary.</typeparam> /// <typeparam name="TReturn">The return type of the functions stored in the dictionary.</typeparam> internal sealed class FuncFluxParam<TKey, TParam, TReturn> : IFluxParamReturn<TKey, TParam, TReturn, Func<TParam, TReturn>> { /// <summary> /// A dictionary that stores functions with one parameter of type `TParam` and a return value of type `TReturn`. /// </summary> internal readonly Dictionary<TKey, Func<TParam, TReturn>> dictionary = new Dictionary<TKey, Func<TParam, TReturn>>(); /// <summary> /// Subscribes the provided function to the dictionary with the specified key when `condition` is true. /// If `condition` is false and the dictionary contains the specified key, the function is removed from the dictionary. /// </summary> void IStore<TKey, Func<TParam, TReturn>>.Store(in bool condition, TKey key, Func<TParam, TReturn> func) { if(dictionary.TryGetValue(key, out var values)) { if (condition) dictionary[key] += func; else { values -= func; if (values is null) dictionary.Remove(key); else dictionary[key] = values; } } else if (condition) dictionary.Add(key, func); } /// <summary> /// Triggers the function stored in the dictionary with the specified key and parameter, and returns its return value. /// If the dictionary does not contain the specified key, returns the default value of type `TReturn`. /// </summary> TReturn
IFluxParamReturn<TKey, TParam, TReturn, Func<TParam, TReturn>>.Dispatch(TKey key, TParam param) {
if(dictionary.TryGetValue(key, out var _actions)) { return _actions.Invoke(param); } return default; } } }
Runtime/Core/Internal/FuncFluxParam.cs
xavierarpa-UniFlux-a2d46de
[ { "filename": "Runtime/Core/Internal/FuncFlux.cs", "retrieved_chunk": " else if (condition) dictionary.Add(key, func);\n }\n // <summary>\n /// Triggers the function stored in the dictionary with the specified key and returns its return value. \n /// If the dictionary does not contain the specified key, returns the default value of type `TReturn`.\n /// </summary>\n TReturn IFluxReturn<TKey, TReturn, Func<TReturn>>.Dispatch(TKey key)\n {\n if(dictionary.TryGetValue(key, out var _actions)) \n {", "score": 0.9542196393013 }, { "filename": "Runtime/Core/Internal/FuncFlux.cs", "retrieved_chunk": " /// <summary>\n /// A dictionary that stores functions with no parameters and a return value of type `TReturn`.\n /// </summary>\n internal readonly Dictionary<TKey, Func<TReturn>> dictionary = new Dictionary<TKey, Func<TReturn>>();\n /// <summary>\n /// Subscribes the provided function to the dictionary with the specified key when `condition` is true. \n /// If `condition` is false and the dictionary contains the specified key, the function is removed from the dictionary.\n /// </summary>\n void IStore<TKey, Func<TReturn>>.Store(in bool condition, TKey key, Func<TReturn> func) \n {", "score": 0.9358430504798889 }, { "filename": "Runtime/Core/Internal/ActionFluxParam.cs", "retrieved_chunk": " {\n if (condition) values.Add(action);\n else values.Remove(action);\n }\n else if (condition) dictionary.Add(key, new HashSet<Action<TValue>>(){action});\n }\n ///<summary>\n /// Triggers the function stored in the dictionary with the specified key and set the parameter as argument \n ///</summary>\n void IFluxParam<TKey, TValue, Action<TValue>>.Dispatch(TKey key, TValue param)", "score": 0.8893826007843018 }, { "filename": "Runtime/Core/Internal/FuncFlux.cs", "retrieved_chunk": "namespace Kingdox.UniFlux.Core.Internal\n{\n /// <summary>\n /// The `FuncFlux` class represents a flux that stores functions with no parameters and a return value of type `TReturn`.\n /// It provides a dictionary to store the functions and methods to subscribe and trigger the stored functions.\n /// </summary>\n /// <typeparam name=\"TKey\">The type of the keys used to store the functions in the dictionary.</typeparam>\n /// <typeparam name=\"TReturn\">The return type of the functions stored in the dictionary.</typeparam>\n internal sealed class FuncFlux<TKey, TReturn> : IFluxReturn<TKey, TReturn, Func<TReturn>>\n {", "score": 0.8879778385162354 }, { "filename": "Runtime/Core/Internal/IFlux.cs", "retrieved_chunk": " /// <summary>\n /// TKey TParam TReturn\n /// </summary>\n internal interface IFluxParamReturn<in TKey, in TParam, out TReturn, in TStorage> : IStore<TKey, TStorage>\n {\n /// <summary>\n /// Dispatch the TKey with TParam and return TReturn\n /// </summary>\n TReturn Dispatch(TKey key, TParam param);\n }", "score": 0.8850042819976807 } ]
csharp
IFluxParamReturn<TKey, TParam, TReturn, Func<TParam, TReturn>>.Dispatch(TKey key, TParam param) {
using UnityEngine; namespace SimplestarGame { public class TemplateTexts : MonoBehaviour { [SerializeField] ButtonPressDetection buttonHi; [SerializeField] ButtonPressDetection buttonHello; [SerializeField] ButtonPressDetection buttonGood; [SerializeField]
ButtonPressDetection buttonOK;
[SerializeField] TMPro.TMP_InputField inputField; void Start() { this.buttonHi.onReleased += this.OnClickHi; this.buttonHello.onReleased += this.OnClickHello; this.buttonGood.onReleased += this.OnClickGood; this.buttonOK.onReleased += this.OnClickOK; } void OnClickOK() { this.inputField.text = "OK!"; } void OnClickGood() { this.inputField.text = "Good!"; } void OnClickHello() { this.inputField.text = "Hello."; } void OnClickHi() { this.inputField.text = "Hi."; } } }
Assets/SimplestarGame/Network/Scripts/Sample/TemplateTexts.cs
simplestargame-SimpleChatPhoton-4ebfbd5
[ { "filename": "Assets/SimplestarGame/Network/Scripts/Scene/SceneContext.cs", "retrieved_chunk": "using UnityEngine;\nnamespace SimplestarGame\n{\n public class SceneContext : MonoBehaviour\n {\n [SerializeField] internal NetworkPlayerInput PlayerInput;\n [SerializeField] internal TMPro.TextMeshProUGUI fpsText;\n [SerializeField] internal TMPro.TextMeshProUGUI hostClientText;\n [SerializeField] internal ButtonPressDetection buttonUp;\n [SerializeField] internal ButtonPressDetection buttonDown;", "score": 0.8849689960479736 }, { "filename": "Assets/SimplestarGame/Network/Scripts/Tools/ButtonPressDetection.cs", "retrieved_chunk": "using UnityEngine;\nusing UnityEngine.EventSystems;\nusing System;\nnamespace SimplestarGame\n{\n public class ButtonPressDetection : MonoBehaviour, IPointerDownHandler, IPointerUpHandler\n {\n internal Action onPressed;\n internal Action onReleased;\n internal bool IsPressed { get; private set; } = false;", "score": 0.8120307922363281 }, { "filename": "Assets/SimplestarGame/Network/Scripts/Runner/Player/PlayerAgent.cs", "retrieved_chunk": "using Fusion;\nusing UnityEngine;\nnamespace SimplestarGame\n{\n public class PlayerAgent : NetworkBehaviour\n {\n [SerializeField] TMPro.TextMeshPro textMeshPro;\n [Networked] internal int Token { get; set; }\n [Networked(OnChanged = nameof(OnChangedMessage), OnChangedTargets = OnChangedTargets.Proxies)] NetworkString<_64> Message { get; set; }\n [Networked(OnChanged = nameof(OnChangedColor), OnChangedTargets = OnChangedTargets.All)] Color Color { get; set; }", "score": 0.7988179922103882 }, { "filename": "Assets/SimplestarGame/Network/Scripts/Runner/Game/NetworkGame.cs", "retrieved_chunk": "using Fusion;\nusing System;\nusing System.Linq;\nusing UnityEngine;\nnamespace SimplestarGame\n{\n public class NetworkGame : NetworkBehaviour\n {\n [SerializeField] Vector3[] spawnPoints;\n [SerializeField] Color[] playerColors;", "score": 0.7879906892776489 }, { "filename": "Assets/SimplestarGame/Network/Scripts/Tools/SimpleCameraController.cs", "retrieved_chunk": "#if ENABLE_INPUT_SYSTEM\nusing UnityEngine.InputSystem;\n#endif\nusing UnityEngine;\nnamespace UnityTemplateProjects\n{\n public class SimpleCameraController : MonoBehaviour\n {\n [SerializeField] TMPro.TMP_InputField inputField;\n class CameraState", "score": 0.775604248046875 } ]
csharp
ButtonPressDetection buttonOK;
namespace CalloutInterfaceAPI.Records { using LSPD_First_Response.Engine.Scripting.Entities; /// <summary> /// Represents a vehicle record looked up on the computer. /// </summary> public class VehicleRecord :
EntityRecord<Rage.Vehicle> {
/// <summary> /// Initializes a new instance of the <see cref="VehicleRecord"/> class. /// </summary> /// <param name="vehicle">The Rage.Vehicle to base the record on.</param> public VehicleRecord(Rage.Vehicle vehicle) : base(vehicle) { } /// <summary> /// Gets the vehicle's class. /// </summary> public string Class { get; internal set; } = "Unknown"; /// <summary> /// Gets the vehicle's color. /// </summary> public string Color { get; internal set; } = "Unknown"; /// <summary> /// Gets the vehicle insurance status. /// </summary> public VehicleDocumentStatus InsuranceStatus { get; internal set; } = VehicleDocumentStatus.Valid; /// <summary> /// Gets the vehicle's license plate. /// </summary> public string LicensePlate { get; internal set; } = "Unknown"; /// <summary> /// Gets the vehicle's license plate style. /// </summary> public Rage.LicensePlateStyle LicensePlateStyle { get; internal set; } = Rage.LicensePlateStyle.BlueOnWhite1; /// <summary> /// Gets the vehicle's make. /// </summary> public string Make { get; internal set; } = "Unknown"; /// <summary> /// Gets the vehicle's model. /// </summary> public string Model { get; internal set; } = "Unknown"; /// <summary> /// Gets the vehicle's owner. /// </summary> public string OwnerName { get; internal set; } = "Unknown"; /// <summary> /// Gets the vehicle owner's persona. /// </summary> public Persona OwnerPersona { get; internal set; } = null; /// <summary> /// Gets the vehicle registration status. /// </summary> public VehicleDocumentStatus RegistrationStatus { get; internal set; } = VehicleDocumentStatus.Valid; } }
CalloutInterfaceAPI/Records/VehicleRecord.cs
Immersive-Plugins-Team-CalloutInterfaceAPI-2c5a303
[ { "filename": "CalloutInterfaceAPI/Records/PedRecord.cs", "retrieved_chunk": "namespace CalloutInterfaceAPI.Records\n{\n using System;\n using LSPD_First_Response.Engine.Scripting.Entities;\n /// <summary>\n /// Represents a ped record.\n /// </summary>\n public class PedRecord : EntityRecord<Rage.Ped>\n {\n /// <summary>", "score": 0.9064043760299683 }, { "filename": "CalloutInterfaceAPI/Records/VehicleDatabase.cs", "retrieved_chunk": "namespace CalloutInterfaceAPI.Records\n{\n using System;\n using System.Collections.Generic;\n using CalloutInterfaceAPI.External;\n /// <summary>\n /// Represents a database of vehicle records.\n /// </summary>\n internal class VehicleDatabase : RecordDatabase<Rage.Vehicle, VehicleRecord>\n {", "score": 0.897749662399292 }, { "filename": "CalloutInterfaceAPI/Records/Computer.cs", "retrieved_chunk": "namespace CalloutInterfaceAPI.Records\n{\n using LSPD_First_Response.Engine.Scripting.Entities;\n /// <summary>\n /// The police computer.\n /// </summary>\n public static class Computer\n {\n private static readonly PedDatabase PedDatabase = new PedDatabase();\n private static readonly VehicleDatabase VehicleDatabase = new VehicleDatabase();", "score": 0.8862557411193848 }, { "filename": "CalloutInterfaceAPI/Records/PedDatabase.cs", "retrieved_chunk": "namespace CalloutInterfaceAPI.Records\n{\n using System;\n using System.Collections.Generic;\n using LSPD_First_Response.Engine.Scripting.Entities;\n /// <summary>\n /// Represents a database of ped records.\n /// </summary>\n internal class PedDatabase : RecordDatabase<Rage.Ped, PedRecord>\n {", "score": 0.8754992485046387 }, { "filename": "CalloutInterfaceAPI/Records/EntityRecord.cs", "retrieved_chunk": "namespace CalloutInterfaceAPI.Records\n{\n using System;\n /// <summary>\n /// Represents a single entity.\n /// </summary>\n /// <typeparam name=\"TEntity\">The type of entity for the record.</typeparam>\n public abstract class EntityRecord<TEntity>\n where TEntity : Rage.Entity\n {", "score": 0.8573459982872009 } ]
csharp
EntityRecord<Rage.Vehicle> {
using BepInEx; using UnityEngine; using UnityEngine.SceneManagement; using System; using HarmonyLib; using System.IO; using Ultrapain.Patches; using System.Linq; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Reflection; using Steamworks; using Unity.Audio; using System.Text; using System.Collections.Generic; using UnityEngine.AddressableAssets; using UnityEngine.AddressableAssets.ResourceLocators; using UnityEngine.ResourceManagement.ResourceLocations; using UnityEngine.UIElements; using PluginConfig.API; namespace Ultrapain { [BepInPlugin(PLUGIN_GUID, PLUGIN_NAME, PLUGIN_VERSION)] [BepInDependency("com.eternalUnion.pluginConfigurator", "1.6.0")] public class Plugin : BaseUnityPlugin { public const string PLUGIN_GUID = "com.eternalUnion.ultraPain"; public const string PLUGIN_NAME = "Ultra Pain"; public const string PLUGIN_VERSION = "1.1.0"; public static Plugin instance; private static bool addressableInit = false; public static T LoadObject<T>(string path) { if (!addressableInit) { Addressables.InitializeAsync().WaitForCompletion(); addressableInit = true; } return Addressables.LoadAssetAsync<T>(path).WaitForCompletion(); } public static Vector3 PredictPlayerPosition(Collider safeCollider, float speedMod) { Transform target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f) return target.position; RaycastHit raycastHit; if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == safeCollider) return target.position; else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { return raycastHit.point; } else { Vector3 projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod; return new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z); } } public static GameObject projectileSpread; public static GameObject homingProjectile; public static GameObject hideousMassProjectile; public static GameObject decorativeProjectile2; public static GameObject shotgunGrenade; public static GameObject beam; public static GameObject turretBeam; public static GameObject lightningStrikeExplosiveSetup; public static GameObject lightningStrikeExplosive; public static GameObject lighningStrikeWindup; public static GameObject explosion; public static GameObject bigExplosion; public static GameObject sandExplosion; public static GameObject virtueInsignia; public static GameObject rocket; public static GameObject revolverBullet; public static GameObject maliciousCannonBeam; public static GameObject lightningBoltSFX; public static GameObject revolverBeam; public static GameObject blastwave; public static GameObject cannonBall; public static GameObject shockwave; public static GameObject sisyphiusExplosion; public static GameObject sisyphiusPrimeExplosion; public static GameObject explosionWaveKnuckleblaster; public static GameObject chargeEffect; public static GameObject maliciousFaceProjectile; public static GameObject hideousMassSpear; public static GameObject coin; public static GameObject sisyphusDestroyExplosion; //public static GameObject idol; public static GameObject ferryman; public static GameObject minosPrime; //public static GameObject maliciousFace; public static GameObject somethingWicked; public static Turret turret; public static GameObject turretFinalFlash; public static GameObject enrageEffect; public static GameObject v2flashUnparryable; public static GameObject ricochetSfx; public static GameObject parryableFlash; public static AudioClip cannonBallChargeAudio; public static Material gabrielFakeMat; public static Sprite blueRevolverSprite; public static Sprite greenRevolverSprite; public static Sprite redRevolverSprite; public static Sprite blueShotgunSprite; public static Sprite greenShotgunSprite; public static Sprite blueNailgunSprite; public static Sprite greenNailgunSprite; public static Sprite blueSawLauncherSprite; public static Sprite greenSawLauncherSprite; public static GameObject rocketLauncherAlt; public static GameObject maliciousRailcannon; // Variables public static float SoliderShootAnimationStart = 1.2f; public static float SoliderGrenadeForce = 10000f; public static float SwordsMachineKnockdownTimeNormalized = 0.8f; public static float SwordsMachineCoreSpeed = 80f; public static float MinGrenadeParryVelocity = 40f; public static GameObject _lighningBoltSFX; public static GameObject lighningBoltSFX { get { if (_lighningBoltSFX == null) _lighningBoltSFX = ferryman.gameObject.transform.Find("LightningBoltChimes").gameObject; return _lighningBoltSFX; } } private static bool loadedPrefabs = false; public void LoadPrefabs() { if (loadedPrefabs) return; loadedPrefabs = true; // Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab projectileSpread = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab homingProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab decorativeProjectile2 = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab"); // Assets/Prefabs/Attacks and Projectiles/Grenade.prefab shotgunGrenade = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Grenade.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab turretBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab beam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab lightningStrikeExplosiveSetup = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab"); // Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab lighningStrikeWindup = LoadObject<GameObject>("Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab"); //[bundle-0][assets/prefabs/enemies/idol.prefab] //idol = LoadObject<GameObject>("assets/prefabs/enemies/idol.prefab"); // Assets/Prefabs/Enemies/Ferryman.prefab ferryman = LoadObject<GameObject>("Assets/Prefabs/Enemies/Ferryman.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab explosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab bigExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab sandExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab"); // Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab virtueInsignia = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab hideousMassProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab"); // Assets/Particles/Enemies/RageEffect.prefab enrageEffect = LoadObject<GameObject>("Assets/Particles/Enemies/RageEffect.prefab"); // Assets/Particles/Flashes/V2FlashUnparriable.prefab v2flashUnparryable = LoadObject<GameObject>("Assets/Particles/Flashes/V2FlashUnparriable.prefab"); // Assets/Prefabs/Attacks and Projectiles/Rocket.prefab rocket = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Rocket.prefab"); // Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab revolverBullet = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab maliciousCannonBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab revolverBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab blastwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab"); // Assets/Prefabs/Enemies/MinosPrime.prefab minosPrime = LoadObject<GameObject>("Assets/Prefabs/Enemies/MinosPrime.prefab"); // Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab cannonBall = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab"); // get from Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab cannonBallChargeAudio = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab").transform.Find("RocketLauncher/Armature/Body_Bone/HologramDisplay").GetComponent<AudioSource>().clip; // Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab shockwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab sisyphiusExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab sisyphiusPrimeExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab explosionWaveKnuckleblaster = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab - [bundle-0][assets/prefabs/explosionlightning variant.prefab] lightningStrikeExplosive = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab"); // Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab rocketLauncherAlt = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab"); // Assets/Prefabs/Weapons/Railcannon Malicious.prefab maliciousRailcannon = LoadObject<GameObject>("Assets/Prefabs/Weapons/Railcannon Malicious.prefab"); //Assets/Particles/SoundBubbles/Ricochet.prefab ricochetSfx = LoadObject<GameObject>("Assets/Particles/SoundBubbles/Ricochet.prefab"); //Assets/Particles/Flashes/Flash.prefab parryableFlash = LoadObject<GameObject>("Assets/Particles/Flashes/Flash.prefab"); //Assets/Prefabs/Attacks and Projectiles/Spear.prefab hideousMassSpear = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Spear.prefab"); //Assets/Prefabs/Enemies/Wicked.prefab somethingWicked = LoadObject<GameObject>("Assets/Prefabs/Enemies/Wicked.prefab"); //Assets/Textures/UI/SingleRevolver.png blueRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/SingleRevolver.png"); //Assets/Textures/UI/RevolverSpecial.png greenRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSpecial.png"); //Assets/Textures/UI/RevolverSharp.png redRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSharp.png"); //Assets/Textures/UI/Shotgun.png blueShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun.png"); //Assets/Textures/UI/Shotgun1.png greenShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun1.png"); //Assets/Textures/UI/Nailgun2.png blueNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Nailgun2.png"); //Assets/Textures/UI/NailgunOverheat.png greenNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/NailgunOverheat.png"); //Assets/Textures/UI/SawbladeLauncher.png blueSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncher.png"); //Assets/Textures/UI/SawbladeLauncherOverheat.png greenSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncherOverheat.png"); //Assets/Prefabs/Attacks and Projectiles/Coin.prefab coin = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Coin.prefab"); //Assets/Materials/GabrielFake.mat gabrielFakeMat = LoadObject<Material>("Assets/Materials/GabrielFake.mat"); //Assets/Prefabs/Enemies/Turret.prefab turret = LoadObject<GameObject>("Assets/Prefabs/Enemies/Turret.prefab").GetComponent<Turret>(); //Assets/Particles/Flashes/GunFlashDistant.prefab turretFinalFlash = LoadObject<GameObject>("Assets/Particles/Flashes/GunFlashDistant.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab sisyphusDestroyExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab"); //Assets/Prefabs/Effects/Charge Effect.prefab chargeEffect = LoadObject<GameObject>("Assets/Prefabs/Effects/Charge Effect.prefab"); //Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab maliciousFaceProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab"); } public static bool ultrapainDifficulty = false; public static bool realUltrapainDifficulty = false; public static
GameObject currentDifficultyButton;
public static GameObject currentDifficultyPanel; public static Text currentDifficultyInfoText; public void OnSceneChange(Scene before, Scene after) { StyleIDs.RegisterIDs(); ScenePatchCheck(); string mainMenuSceneName = "b3e7f2f8052488a45b35549efb98d902"; string bootSequenceSceneName = "4f8ecffaa98c2614f89922daf31fa22d"; string currentSceneName = SceneManager.GetActiveScene().name; if (currentSceneName == mainMenuSceneName) { LoadPrefabs(); //Canvas/Difficulty Select (1)/Violent Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Difficulty Select (1)"); GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect); currentDifficultyButton = ultrapainButton; ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value; ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5; RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>(); ultrapainTrans.anchoredPosition = new Vector2(20f, -104f); //Canvas/Difficulty Select (1)/Violent Info GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect); currentDifficultyPanel = info; currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>(); currentDifficultyInfoText.text = ConfigManager.pluginInfo.value; Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>(); currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--"; currentDifficultyHeaderText.resizeTextForBestFit = true; currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap; currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate; info.SetActive(false); EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>(); evt.triggers.Clear(); /*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(false));*/ EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit }; trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false)); evt.triggers.Add(trigger1); evt.triggers.Add(trigger2); foreach(EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>()) { if (trigger.gameObject == ultrapainButton) continue; EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false)); trigger.triggers.Add(closeTrigger); } } else if(currentSceneName == bootSequenceSceneName) { LoadPrefabs(); //Canvas/Difficulty Select (1)/Violent Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Intro/Difficulty Select"); GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect); currentDifficultyButton = ultrapainButton; ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value; ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5; RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>(); ultrapainTrans.anchoredPosition = new Vector2(20f, -104f); //Canvas/Difficulty Select (1)/Violent Info GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect); currentDifficultyPanel = info; currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>(); currentDifficultyInfoText.text = ConfigManager.pluginInfo.value; Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>(); currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--"; currentDifficultyHeaderText.resizeTextForBestFit = true; currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap; currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate; info.SetActive(false); EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>(); evt.triggers.Clear(); /*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(false));*/ EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit }; trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false)); evt.triggers.Add(trigger1); evt.triggers.Add(trigger2); foreach (EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>()) { if (trigger.gameObject == ultrapainButton) continue; EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false)); trigger.triggers.Add(closeTrigger); } } // LOAD CUSTOM PREFABS HERE TO AVOID MID GAME LAG MinosPrimeCharge.CreateDecoy(); GameObject shockwaveSisyphus = SisyphusInstructionist_Start.shockwave; } public static class StyleIDs { private static bool registered = false; public static void RegisterIDs() { registered = false; if (MonoSingleton<StyleHUD>.Instance == null) return; MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.grenadeBoostStyleText.guid, ConfigManager.grenadeBoostStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.rocketBoostStyleText.guid, ConfigManager.rocketBoostStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverStyleText.guid, ConfigManager.orbStrikeRevolverStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverChargedStyleText.guid, ConfigManager.orbStrikeRevolverChargedStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeElectricCannonStyleText.guid, ConfigManager.orbStrikeElectricCannonStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeMaliciousCannonStyleText.guid, ConfigManager.orbStrikeMaliciousCannonStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.maliciousChargebackStyleText.guid, ConfigManager.maliciousChargebackStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.sentryChargebackStyleText.guid, ConfigManager.sentryChargebackStyleText.formattedString); registered = true; Debug.Log("Registered all style ids"); } private static FieldInfo idNameDict = typeof(StyleHUD).GetField("idNameDict", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); public static void UpdateID(string id, string newName) { if (!registered || StyleHUD.Instance == null) return; (idNameDict.GetValue(StyleHUD.Instance) as Dictionary<string, string>)[id] = newName; } } public static Harmony harmonyTweaks; public static Harmony harmonyBase; private static MethodInfo GetMethod<T>(string name) { return typeof(T).GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } private static Dictionary<MethodInfo, HarmonyMethod> methodCache = new Dictionary<MethodInfo, HarmonyMethod>(); private static HarmonyMethod GetHarmonyMethod(MethodInfo method) { if (methodCache.TryGetValue(method, out HarmonyMethod harmonyMethod)) return harmonyMethod; else { harmonyMethod = new HarmonyMethod(method); methodCache.Add(method, harmonyMethod); return harmonyMethod; } } private static void PatchAllEnemies() { if (!ConfigManager.enemyTweakToggle.value) return; if (ConfigManager.friendlyFireDamageOverrideToggle.value) { harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<PhysicalShockwave>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<VirtueInsignia>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_FF>("Prefix"))); harmonyTweaks.Patch(GetMethod<Flammable>("Burn"), prefix: GetHarmonyMethod(GetMethod<Flammable_Burn_FF>("Prefix"))); harmonyTweaks.Patch(GetMethod<FireZone>("OnTriggerStay"), prefix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Postfix"))); } harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("UpdateModifiers"), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_UpdateModifiers>("Postfix"))); harmonyTweaks.Patch(GetMethod<StatueBoss>("Start"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Start_Patch>("Postfix"))); if (ConfigManager.cerberusDashToggle.value) harmonyTweaks.Patch(GetMethod<StatueBoss>("StopDash"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopDash_Patch>("Postfix"))); if(ConfigManager.cerberusParryable.value) { harmonyTweaks.Patch(GetMethod<StatueBoss>("StopTracking"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopTracking_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<StatueBoss>("Stomp"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Stomp_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Statue>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Statue_GetHurt_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Drone_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Drone>("Shoot"), prefix: GetHarmonyMethod(GetMethod<Drone_Shoot_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("PlaySound"), prefix: GetHarmonyMethod(GetMethod<Drone_PlaySound_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Update"), postfix: GetHarmonyMethod(GetMethod<Drone_Update>("Postfix"))); if(ConfigManager.droneHomeToggle.value) { harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Drone_Death_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Drone_GetHurt_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Ferryman>("Start"), postfix: GetHarmonyMethod(GetMethod<FerrymanStart>("Postfix"))); if(ConfigManager.ferrymanComboToggle.value) harmonyTweaks.Patch(GetMethod<Ferryman>("StopMoving"), postfix: GetHarmonyMethod(GetMethod<FerrymanStopMoving>("Postfix"))); if(ConfigManager.filthExplodeToggle.value) harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch2>("Prefix"))); if(ConfigManager.fleshPrisonSpinAttackToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<FleshPrisonShoot>("Postfix"))); if (ConfigManager.hideousMassInsigniaToggle.value) { harmonyTweaks.Patch(GetMethod<Projectile>("Explode"), postfix: GetHarmonyMethod(GetMethod<Projectile_Explode_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Mass>("ShootExplosive"), postfix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Postfix")), prefix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Prefix"))); } harmonyTweaks.Patch(GetMethod<SpiderBody>("Start"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<SpiderBody>("ChargeBeam"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ChargeBeam>("Postfix"))); harmonyTweaks.Patch(GetMethod<SpiderBody>("BeamChargeEnd"), prefix: GetHarmonyMethod(GetMethod<MaliciousFace_BeamChargeEnd>("Prefix"))); if (ConfigManager.maliciousFaceHomingProjectileToggle.value) { harmonyTweaks.Patch(GetMethod<SpiderBody>("ShootProj"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ShootProj_Patch>("Postfix"))); } if (ConfigManager.maliciousFaceRadianceOnEnrage.value) harmonyTweaks.Patch(GetMethod<SpiderBody>("Enrage"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Enrage_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Mindflayer>("Start"), postfix: GetHarmonyMethod(GetMethod<Mindflayer_Start_Patch>("Postfix"))); if (ConfigManager.mindflayerShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<Mindflayer>("ShootProjectiles"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_ShootProjectiles_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_MF>("Prefix"))); } if (ConfigManager.mindflayerTeleportComboToggle.value) { harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Mindflayer>("MeleeTeleport"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_MeleeTeleport_Patch>("Prefix"))); //harmonyTweaks.Patch(GetMethod<SwingCheck2>("DamageStop"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_DamageStop_Patch>("Postfix"))); } if (ConfigManager.minosPrimeRandomTeleportToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("Postfix"))); if (ConfigManager.minosPrimeTeleportTrail.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("Teleport"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("TeleportPostfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Start"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Dropkick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Dropkick>("Prefix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Combo"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Combo>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("StopAction"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_StopAction>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Ascend"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Ascend>("Prefix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Death"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Death>("Prefix"))); if (ConfigManager.minosPrimeCrushAttackToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("RiderKick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_RiderKick>("Prefix"))); if (ConfigManager.minosPrimeComboExplosiveEndToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_ProjectileCharge>("Prefix"))); if (ConfigManager.schismSpreadAttackToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ShootProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ShootProjectile_Patch>("Postfix"))); if (ConfigManager.soliderShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<Solider_Start_Patch>("Postfix"))); } if(ConfigManager.soliderCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_SpawnProjectile_Patch>("Postfix"))); if (ConfigManager.soliderShootGrenadeToggle.value || ConfigManager.soliderShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_ThrowProjectile_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Stalker>("SandExplode"), prefix: GetHarmonyMethod(GetMethod<Stalker_SandExplode_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SandificationZone>("Enter"), postfix: GetHarmonyMethod(GetMethod<SandificationZone_Enter_Patch>("Postfix"))); if (ConfigManager.strayCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Swing>("Postfix"))); if (ConfigManager.strayShootToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_Start_Patch1>("Postfix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ThrowProjectile_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<SwingEnd>("Prefix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("DamageEnd"), prefix: GetHarmonyMethod(GetMethod<DamageEnd>("Prefix"))); } if(ConfigManager.streetCleanerCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<Streetcleaner>("Start"), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Start_Patch>("Postfix"))); if(ConfigManager.streetCleanerPredictiveDodgeToggle.value) harmonyTweaks.Patch(GetMethod<BulletCheck>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<BulletCheck_OnTriggerEnter_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("Start"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Start>("Postfix"))); if (ConfigManager.swordsMachineNoLightKnockbackToggle.value || ConfigManager.swordsMachineSecondPhaseMode.value != ConfigManager.SwordsMachineSecondPhase.None) { harmonyTweaks.Patch(GetMethod<SwordsMachine>("Knockdown"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Knockdown_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("Down"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Prefix"))); //harmonyTweaks.Patch(GetMethod<SwordsMachine>("SetSpeed"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_SetSpeed_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("EndFirstPhase"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Prefix"))); } if (ConfigManager.swordsMachineExplosiveSwordToggle.value) { harmonyTweaks.Patch(GetMethod<ThrownSword>("Start"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<ThrownSword>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_OnTriggerEnter_Patch>("Postfix"))); } harmonyTweaks.Patch(GetMethod<Turret>("Start"), postfix: GetHarmonyMethod(GetMethod<TurretStart>("Postfix"))); if(ConfigManager.turretBurstFireToggle.value) { harmonyTweaks.Patch(GetMethod<Turret>("Shoot"), prefix: GetHarmonyMethod(GetMethod<TurretShoot>("Prefix"))); harmonyTweaks.Patch(GetMethod<Turret>("StartAiming"), postfix: GetHarmonyMethod(GetMethod<TurretAim>("Postfix"))); } harmonyTweaks.Patch(GetMethod<Explosion>("Start"), postfix: GetHarmonyMethod(GetMethod<V2CommonExplosion>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2FirstStart>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2FirstUpdate>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2FirstShootWeapon>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2SecondStart>("Postfix"))); //if(ConfigManager.v2SecondStartEnraged.value) // harmonyTweaks.Patch(GetMethod<BossHealthBar>("OnEnable"), postfix: GetHarmonyMethod(GetMethod<V2SecondEnrage>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2SecondUpdate>("Prefix"))); //harmonyTweaks.Patch(GetMethod<V2>("AltShootWeapon"), postfix: GetHarmonyMethod(GetMethod<V2AltShootWeapon>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("SwitchWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondSwitchWeapon>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Prefix")), postfix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Postfix"))); if(ConfigManager.v2SecondFastCoinToggle.value) harmonyTweaks.Patch(GetMethod<V2>("ThrowCoins"), prefix: GetHarmonyMethod(GetMethod<V2SecondFastCoin>("Prefix"))); harmonyTweaks.Patch(GetMethod<Cannonball>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<V2RocketLauncher>("CannonBallTriggerPrefix"))); if (ConfigManager.v2FirstSharpshooterToggle.value || ConfigManager.v2SecondSharpshooterToggle.value) { harmonyTweaks.Patch(GetMethod<EnemyRevolver>("PrepareAltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverPrepareAltFire>("Prefix"))); harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverBullet>("Prefix"))); harmonyTweaks.Patch(GetMethod<EnemyRevolver>("AltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverAltShoot>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Virtue_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Drone>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Virtue_SpawnInsignia_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Virtue_Death_Patch>("Prefix"))); if (ConfigManager.sisyInstJumpShockwave.value) { harmonyTweaks.Patch(GetMethod<Sisyphus>("Start"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Sisyphus>("Update"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Update>("Postfix"))); } if(ConfigManager.sisyInstBoulderShockwave.value) harmonyTweaks.Patch(GetMethod<Sisyphus>("SetupExplosion"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_SetupExplosion>("Postfix"))); if(ConfigManager.sisyInstStrongerExplosion.value) harmonyTweaks.Patch(GetMethod<Sisyphus>("StompExplosion"), prefix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_StompExplosion>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("Awake"), postfix: GetHarmonyMethod(GetMethod<LeviathanTail_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("BigSplash"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_BigSplash>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_SwingEnd>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("Start"), postfix: GetHarmonyMethod(GetMethod<Leviathan_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurst"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurstStart"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurstStart>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<Leviathan_FixedUpdate>("Prefix"))); if (ConfigManager.somethingWickedSpear.value) { harmonyTweaks.Patch(GetMethod<Wicked>("Start"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_GetHit>("Postfix"))); } if(ConfigManager.somethingWickedSpawnOn43.value) { harmonyTweaks.Patch(GetMethod<ObjectActivator>("Activate"), prefix: GetHarmonyMethod(GetMethod<ObjectActivator_Activate>("Prefix"))); harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<JokeWicked_GetHit>("Postfix"))); } if (ConfigManager.panopticonFullPhase.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Panopticon_Start>("Postfix"))); if (ConfigManager.panopticonAxisBeam.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnInsignia>("Prefix"))); if (ConfigManager.panopticonSpinAttackToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<Panopticon_HomingProjectileAttack>("Postfix"))); if (ConfigManager.panopticonBlackholeProj.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnBlackHole"), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnBlackHole>("Postfix"))); if (ConfigManager.panopticonBalanceEyes.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnFleshDrones"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Postfix"))); if (ConfigManager.panopticonBlueProjToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Update"), transpiler: GetHarmonyMethod(GetMethod<Panopticon_BlueProjectile>("Transpiler"))); if (ConfigManager.idolExplosionToggle.value) harmonyTweaks.Patch(GetMethod<Idol>("Death"), postfix: GetHarmonyMethod(GetMethod<Idol_Death_Patch>("Postfix"))); // ADDME /* harmonyTweaks.Patch(GetMethod<GabrielSecond>("Start"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("BasicCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_BasicCombo>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("FastCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_FastCombo>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("CombineSwords"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_CombineSwords>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("ThrowCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_ThrowCombo>("Postfix"))); */ } private static void PatchAllPlayers() { if (!ConfigManager.playerTweakToggle.value) return; harmonyTweaks.Patch(GetMethod<Punch>("CheckForProjectile"), prefix: GetHarmonyMethod(GetMethod<Punch_CheckForProjectile_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch1>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Collision"), prefix: GetHarmonyMethod(GetMethod<Grenade_Collision_Patch>("Prefix"))); if (ConfigManager.rocketBoostToggle.value) harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_Patch>("Prefix"))); if (ConfigManager.rocketGrabbingToggle.value) harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate_Patch>("Prefix"))); if (ConfigManager.orbStrikeToggle.value) { harmonyTweaks.Patch(GetMethod<Coin>("Start"), postfix: GetHarmonyMethod(GetMethod<Coin_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Punch>("BlastCheck"), prefix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Postfix"))); harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide>("Prefix"))); harmonyTweaks.Patch(GetMethod<Coin>("DelayedReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_DelayedReflectRevolver>("Postfix"))); harmonyTweaks.Patch(GetMethod<Coin>("ReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Postfix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Prefix")), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Postfix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("ExecuteHits"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Prefix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("HitSomething"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Prefix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("Start"), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_Start>("Prefix"))); harmonyTweaks.Patch(GetMethod<Cannonball>("Explode"), prefix: GetHarmonyMethod(GetMethod<Cannonball_Explode>("Prefix"))); harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_CollideOrbital>("Prefix"))); } if(ConfigManager.chargedRevRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<Revolver>("Update"), prefix: GetHarmonyMethod(GetMethod<Revolver_Update>("Prefix"))); if(ConfigManager.coinRegSpeedMulti.value != 1 || ConfigManager.sharpshooterRegSpeedMulti.value != 1 || ConfigManager.railcannonRegSpeedMulti.value != 1 || ConfigManager.rocketFreezeRegSpeedMulti.value != 1 || ConfigManager.rocketCannonballRegSpeedMulti.value != 1 || ConfigManager.nailgunAmmoRegSpeedMulti.value != 1 || ConfigManager.sawAmmoRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<WeaponCharges>("Charge"), prefix: GetHarmonyMethod(GetMethod<WeaponCharges_Charge>("Prefix"))); if(ConfigManager.nailgunHeatsinkRegSpeedMulti.value != 1 || ConfigManager.sawHeatsinkRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<Nailgun>("Update"), prefix: GetHarmonyMethod(GetMethod<NailGun_Update>("Prefix"))); if(ConfigManager.staminaRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<NewMovement>("Update"), prefix: GetHarmonyMethod(GetMethod<NewMovement_Update>("Prefix"))); if(ConfigManager.playerHpDeltaToggle.value || ConfigManager.maxPlayerHp.value != 100 || ConfigManager.playerHpSupercharge.value != 200 || ConfigManager.whiplashHardDamageCap.value != 50 || ConfigManager.whiplashHardDamageSpeed.value != 1) { harmonyTweaks.Patch(GetMethod<NewMovement>("GetHealth"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHealth>("Prefix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("SuperCharge"), prefix: GetHarmonyMethod(GetMethod<NewMovement_SuperCharge>("Prefix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("Respawn"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Respawn>("Postfix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("Start"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Transpiler"))); harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), transpiler: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate>("Transpiler"))); harmonyTweaks.Patch(GetMethod<NewMovement>("ForceAntiHP"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_ForceAntiHP>("Transpiler"))); } // ADDME harmonyTweaks.Patch(GetMethod<Revolver>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Revolver_Shoot>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Shotgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Transpiler")), prefix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Postfix"))); harmonyTweaks.Patch(GetMethod<Shotgun>("ShootSinks"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_ShootSinks>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Nailgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_Shoot>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Nailgun>("SuperSaw"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_SuperSaw>("Transpiler"))); if (ConfigManager.hardDamagePercent.normalizedValue != 1) harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Prefix")), postfix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Postfix"))); harmonyTweaks.Patch(GetMethod<HealthBar>("Start"), postfix: GetHarmonyMethod(GetMethod<HealthBar_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<HealthBar>("Update"), transpiler: GetHarmonyMethod(GetMethod<HealthBar_Update>("Transpiler"))); foreach (HealthBarTracker hb in HealthBarTracker.instances) { if (hb != null) hb.SetSliderRange(); } harmonyTweaks.Patch(GetMethod<Harpoon>("Start"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Start>("Postfix"))); if(ConfigManager.screwDriverHomeToggle.value) harmonyTweaks.Patch(GetMethod<Harpoon>("Punched"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Punched>("Postfix"))); if(ConfigManager.screwDriverSplitToggle.value) harmonyTweaks.Patch(GetMethod<Harpoon>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<Harpoon_OnTriggerEnter_Patch>("Prefix"))); } private static void PatchAllMemes() { if (ConfigManager.enrageSfxToggle.value) harmonyTweaks.Patch(GetMethod<EnrageEffect>("Start"), postfix: GetHarmonyMethod(GetMethod<EnrageEffect_Start>("Postfix"))); if(ConfigManager.funnyDruidKnightSFXToggle.value) { harmonyTweaks.Patch(GetMethod<Mandalore>("FullBurst"), postfix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Postfix")), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<Mandalore>("FullerBurst"), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullerBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Explode"), prefix: GetHarmonyMethod(GetMethod<Drone_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Drone_Explode>("Postfix"))); } if (ConfigManager.fleshObamiumToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Prefix"))); if (ConfigManager.obamapticonToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Prefix"))); } public static bool methodsPatched = false; public static void ScenePatchCheck() { if(methodsPatched && !ultrapainDifficulty) { harmonyTweaks.UnpatchSelf(); methodsPatched = false; } else if(!methodsPatched && ultrapainDifficulty) { PatchAll(); } } public static void PatchAll() { harmonyTweaks.UnpatchSelf(); methodsPatched = false; if (!ultrapainDifficulty) return; if(realUltrapainDifficulty && ConfigManager.discordRichPresenceToggle.value) harmonyTweaks.Patch(GetMethod<DiscordController>("SendActivity"), prefix: GetHarmonyMethod(GetMethod<DiscordController_SendActivity_Patch>("Prefix"))); if (realUltrapainDifficulty && ConfigManager.steamRichPresenceToggle.value) harmonyTweaks.Patch(GetMethod<SteamFriends>("SetRichPresence"), prefix: GetHarmonyMethod(GetMethod<SteamFriends_SetRichPresence_Patch>("Prefix"))); PatchAllEnemies(); PatchAllPlayers(); PatchAllMemes(); methodsPatched = true; } public static string workingPath; public static string workingDir; public static AssetBundle bundle; public static AudioClip druidKnightFullAutoAud; public static AudioClip druidKnightFullerAutoAud; public static AudioClip druidKnightDeathAud; public static AudioClip enrageAudioCustom; public static GameObject fleshObamium; public static GameObject obamapticon; public void Awake() { instance = this; workingPath = Assembly.GetExecutingAssembly().Location; workingDir = Path.GetDirectoryName(workingPath); Logger.LogInfo($"Working path: {workingPath}, Working dir: {workingDir}"); try { bundle = AssetBundle.LoadFromFile(Path.Combine(workingDir, "ultrapain")); druidKnightFullAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullauto.wav"); druidKnightFullerAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullerauto.wav"); druidKnightDeathAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/death.wav"); enrageAudioCustom = bundle.LoadAsset<AudioClip>("assets/ultrapain/sfx/enraged.wav"); fleshObamium = bundle.LoadAsset<GameObject>("assets/ultrapain/fleshprison/fleshobamium.prefab"); obamapticon = bundle.LoadAsset<GameObject>("assets/ultrapain/panopticon/obamapticon.prefab"); } catch (Exception e) { Logger.LogError($"Could not load the asset bundle:\n{e}"); } // DEBUG /*string logPath = Path.Combine(Environment.CurrentDirectory, "log.txt"); Logger.LogInfo($"Saving to {logPath}"); List<string> assetPaths = new List<string>() { "fonts.bundle", "videos.bundle", "shaders.bundle", "particles.bundle", "materials.bundle", "animations.bundle", "prefabs.bundle", "physicsmaterials.bundle", "models.bundle", "textures.bundle", }; //using (FileStream log = File.Open(logPath, FileMode.OpenOrCreate, FileAccess.Write)) //{ foreach(string assetPath in assetPaths) { Logger.LogInfo($"Attempting to load {assetPath}"); AssetBundle bundle = AssetBundle.LoadFromFile(Path.Combine(bundlePath, assetPath)); bundles.Add(bundle); //foreach (string name in bundle.GetAllAssetNames()) //{ // string line = $"[{bundle.name}][{name}]\n"; // log.Write(Encoding.ASCII.GetBytes(line), 0, line.Length); //} bundle.LoadAllAssets(); } //} */ // Plugin startup logic Logger.LogInfo($"Plugin {PluginInfo.PLUGIN_GUID} is loaded!"); harmonyTweaks = new Harmony(PLUGIN_GUID + "_tweaks"); harmonyBase = new Harmony(PLUGIN_GUID + "_base"); harmonyBase.Patch(GetMethod<DifficultySelectButton>("SetDifficulty"), postfix: GetHarmonyMethod(GetMethod<DifficultySelectPatch>("Postfix"))); harmonyBase.Patch(GetMethod<DifficultyTitle>("Check"), postfix: GetHarmonyMethod(GetMethod<DifficultyTitle_Check_Patch>("Postfix"))); harmonyBase.Patch(typeof(PrefsManager).GetConstructor(new Type[0]), postfix: GetHarmonyMethod(GetMethod<PrefsManager_Ctor>("Postfix"))); harmonyBase.Patch(GetMethod<PrefsManager>("EnsureValid"), prefix: GetHarmonyMethod(GetMethod<PrefsManager_EnsureValid>("Prefix"))); harmonyBase.Patch(GetMethod<Grenade>("Explode"), prefix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Prefix")), postfix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Postfix"))); LoadPrefabs(); ConfigManager.Initialize(); SceneManager.activeSceneChanged += OnSceneChange; } } public static class Tools { private static Transform _target; private static Transform target { get { if(_target == null) _target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); return _target; } } public static Vector3 PredictPlayerPosition(float speedMod, Collider enemyCol = null) { Vector3 projectedPlayerPos; if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f) { return target.position; } RaycastHit raycastHit; if (enemyCol != null && Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == enemyCol) { projectedPlayerPos = target.position; } else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { projectedPlayerPos = raycastHit.point; } else { projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod; projectedPlayerPos = new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z); } return projectedPlayerPos; } } // Asset destroyer tracker /*[HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object) })] public class TempClass1 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object), typeof(float) })] public class TempClass2 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object) })] public class TempClass3 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object), typeof(bool) })] public class TempClass4 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } }*/ }
Ultrapain/Plugin.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " };\n maliciousFaceRadianceOnEnrage.TriggerValueChangeEvent();\n maliciousFaceRadianceAmount = new IntField(maliciousFaceRadianceOnEnrageDiv, \"Radiance level\", \"maliciousFaceRadianceAmount\", 1, 0, int.MaxValue);\n new ConfigHeader(maliciousFacePanel, \"Homing Projectile\");\n maliciousFaceHomingProjectileToggle = new BoolField(maliciousFacePanel, \"Enabled\", \"maliciousFaceHomingProjectileToggle\", true);\n maliciousFaceHomingProjectileToggle.presetLoadPriority = 1;\n ConfigDivision maliciousFaceHomingProjecileDiv = new ConfigDivision(maliciousFacePanel, \"maliciousFaceHomingProjecileDiv\");\n maliciousFaceHomingProjectileToggle.onValueChange += (BoolField.BoolValueChangeEvent e) =>\n {\n maliciousFaceHomingProjecileDiv.interactable = e.value;", "score": 0.7763427495956421 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " dirtyField = true;\n };\n screwDriverHomeToggle.TriggerValueChangeEvent();\n screwDriverHomeDestroyMagnets = new BoolField(screwDriverHomeDiv, \"Destroy magnets on attach\", \"screwDriverHomeDestroyMagnets\", true);\n screwDriverHomePierceDamage = new FloatField(screwDriverHomeDiv, \"Pierce damage\", \"screwDriverHomePierceDamage\", 2f, 0f, float.MaxValue);\n new ConfigHeader(playerPanel, \"Orbital Strike\", 26);\n new ConfigHeader(playerPanel, \"(Tweaks for coin-knuckleblaster)\", 16);\n orbStrikeToggle = new BoolField(playerPanel, \"Enabled\", \"orbStrikeToggle\", true);\n orbStrikeToggle.presetLoadPriority = 1;\n ConfigDivision orbStrikeDiv = new ConfigDivision(playerPanel, \"orbStrikeDiv\");", "score": 0.7748490571975708 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " v2SecondPanel.icon = Plugin.LoadObject<Sprite>(\"Assets/Textures/UI/Spawn Menu/V2 2nd.png\");\n\t\t\tleviathanPanel = new ConfigPanel(enemyPanel, \"Leviathan\", \"leviathanPanel\", ConfigPanel.PanelFieldType.StandardWithIcon);\n leviathanPanel.icon = Plugin.LoadObject<Sprite>(\"Assets/Textures/UI/Spawn Menu/Leviathan.png\");\n\t\t\tnew ConfigHeader(enemyPanel, \"Prime Bosses\");\n fleshPrisonPanel = new ConfigPanel(enemyPanel, \"Flesh Prison\", \"fleshPrisonPanel\", ConfigPanel.PanelFieldType.StandardWithIcon);\n fleshPrisonPanel.icon = Plugin.LoadObject<Sprite>(\"Assets/Textures/UI/Spawn Menu/FleshPrison.png\");\n\t\t\tminosPrimePanel = new ConfigPanel(enemyPanel, \"Minos Prime\", \"minosPrimePanel\", ConfigPanel.PanelFieldType.StandardWithIcon);\n minosPrimePanel.icon = Plugin.LoadObject<Sprite>(\"Assets/Textures/UI/Spawn Menu/MinosPrime.png\");\n\t\t\tpanopticonPanel = new ConfigPanel(enemyPanel, \"Flesh Panopticon\", \"panopticonPanel\", ConfigPanel.PanelFieldType.StandardWithIcon);\n panopticonPanel.icon = Plugin.LoadObject<Sprite>(\"Assets/Textures/UI/Spawn Menu/FleshPanopticon.png\");", "score": 0.770901083946228 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " dirtyField = true;\n };\n maliciousFaceHomingProjectileToggle.TriggerValueChangeEvent();\n maliciousFaceHomingProjectileCount = new IntField(maliciousFaceHomingProjecileDiv, \"Projectile count\", \"maliciousFaceHomingProjectileCount\", 5, 0, int.MaxValue);\n maliciousFaceHomingProjectileDamage = new IntField(maliciousFaceHomingProjecileDiv, \"Projectile damage\", \"maliciousFaceHomingProjectileDamage\", 25, 0, int.MaxValue);\n maliciousFaceHomingProjectileSpeed = new FloatField(maliciousFaceHomingProjecileDiv, \"Projectile speed\", \"maliciousFaceHomingProjectileSpeed\", 20f, 0f, float.MaxValue);\n maliciousFaceHomingProjectileTurnSpeed = new FloatField(maliciousFaceHomingProjecileDiv, \"Projectile turn speed\", \"maliciousFaceHomingProjectileTurnSpeed\", 0.7f, 0f, float.MaxValue);\n new ConfigHeader(maliciousFacePanel, \"Beam Count\");\n maliciousFaceBeamCountNormal = new IntField(maliciousFacePanel, \"Normal state\", \"maliciousFaceBeamCountNormal\", 1, 0, int.MaxValue);\n maliciousFaceBeamCountEnraged = new IntField(maliciousFacePanel, \"Enraged state\", \"maliciousFaceBeamCountEnraged\", 2, 0, int.MaxValue);", "score": 0.7634921669960022 }, { "filename": "Ultrapain/Patches/HideousMass.cs", "retrieved_chunk": " insignia.transform.Rotate(new Vector3(90f, 0, 0));\n }\n }\n }\n public class HideousMassHoming\n {\n static bool Prefix(Mass __instance, EnemyIdentifier ___eid)\n {\n __instance.explosiveProjectile = GameObject.Instantiate(Plugin.hideousMassProjectile);\n HideousMassProjectile flag = __instance.explosiveProjectile.AddComponent<HideousMassProjectile>();", "score": 0.7570598125457764 } ]
csharp
GameObject currentDifficultyButton;
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace TreeifyTask { public class TaskNode : ITaskNode { private static Random rnd = new Random(); private readonly List<Task> taskObjects = new(); private readonly List<ITaskNode> childTasks = new(); private bool hasCustomAction; private Func<
IProgressReporter, CancellationToken, Task> action = async (rep, tok) => await Task.Yield();
public event ProgressReportingEventHandler Reporting; private bool seriesRunnerIsBusy; private bool concurrentRunnerIsBusy; public TaskNode() { this.Id = rnd.Next() + string.Empty; this.Reporting += OnSelfReporting; } public TaskNode(string Id) : this() { this.Id = Id ?? rnd.Next() + string.Empty; } public TaskNode(string Id, Func<IProgressReporter, CancellationToken, Task> cancellableProgressReportingAsyncFunction) : this(Id) { this.SetAction(cancellableProgressReportingAsyncFunction); } #region Props public string Id { get; set; } public double ProgressValue { get; private set; } public object ProgressState { get; private set; } public TaskStatus TaskStatus { get; private set; } public ITaskNode Parent { get; set; } public IEnumerable<ITaskNode> ChildTasks => this.childTasks; #endregion Props public void AddChild(ITaskNode childTask) { childTask = childTask ?? throw new ArgumentNullException(nameof(childTask)); childTask.Parent = this; // Ensure this after setting its parent as this EnsureNoCycles(childTask); childTask.Reporting += OnChildReporting; childTasks.Add(childTask); } private class ActionReport { public ActionReport() { this.TaskStatus = TaskStatus.NotStarted; this.ProgressValue = 0; this.ProgressState = null; } public ActionReport(ITaskNode task) { this.Id = task.Id; this.TaskStatus = task.TaskStatus; this.ProgressState = task.ProgressState; this.ProgressValue = task.ProgressValue; } public string Id { get; set; } public TaskStatus TaskStatus { get; set; } public double ProgressValue { get; set; } public object ProgressState { get; set; } public override string ToString() { return $"Id={Id},({TaskStatus}, {ProgressValue}, {ProgressState})"; } } private ActionReport selfActionReport = new(); private void OnSelfReporting(object sender, ProgressReportingEventArgs eventArgs) { TaskStatus = selfActionReport.TaskStatus = eventArgs.TaskStatus; ProgressValue = selfActionReport.ProgressValue = eventArgs.ProgressValue; ProgressState = selfActionReport.ProgressState = eventArgs.ProgressState; } private void OnChildReporting(object sender, ProgressReportingEventArgs eventArgs) { // Child task that reports var cTask = sender as ITaskNode; var allReports = childTasks.Select(t => new ActionReport(t)); if (hasCustomAction) { allReports = allReports.Append(selfActionReport); } this.TaskStatus = allReports.Any(v => v.TaskStatus == TaskStatus.InDeterminate) ? TaskStatus.InDeterminate : TaskStatus.InProgress; this.TaskStatus = allReports.Any(v => v.TaskStatus == TaskStatus.Failed) ? TaskStatus.Failed : this.TaskStatus; if (this.TaskStatus == TaskStatus.Failed) { this.ProgressState = new AggregateException($"{Id}: One or more error occurred in child tasks.", childTasks.Where(v => v.TaskStatus == TaskStatus.Failed && v.ProgressState is Exception) .Select(c => c.ProgressState as Exception)); } this.ProgressValue = allReports.Select(t => t.ProgressValue).Average(); SafeRaiseReportingEvent(this, new ProgressReportingEventArgs { ProgressValue = this.ProgressValue, TaskStatus = this.TaskStatus, ChildTasksRunningInParallel = concurrentRunnerIsBusy, ProgressState = seriesRunnerIsBusy ? cTask.ProgressState : this.ProgressState }); } public async Task ExecuteConcurrently(CancellationToken cancellationToken, bool throwOnError) { if (concurrentRunnerIsBusy || seriesRunnerIsBusy) return; concurrentRunnerIsBusy = true; ResetChildrenProgressValues(); foreach (var child in childTasks) { taskObjects.Add(child.ExecuteConcurrently(cancellationToken, throwOnError)); } taskObjects.Add(ExceptionHandledAction(cancellationToken, throwOnError)); if (taskObjects.Any()) { await Task.WhenAll(taskObjects); } if (throwOnError && taskObjects.Any(t => t.IsFaulted)) { var exs = taskObjects.Where(t => t.IsFaulted).Select(t => t.Exception); throw new AggregateException($"Internal error occurred while executing task - {Id}.", exs); } concurrentRunnerIsBusy = false; if (TaskStatus != TaskStatus.Failed) { if (cancellationToken.IsCancellationRequested) Report(TaskStatus.Cancelled, 0); else Report(TaskStatus.Completed, 100); } } private async Task ExceptionHandledAction(CancellationToken cancellationToken, bool throwOnError) { try { await action(this, cancellationToken); } catch (OperationCanceledException) { // Don't throw this as an error as we have to come out of await. } catch (Exception ex) { this.Report(TaskStatus.Failed, this.ProgressValue, ex); if (throwOnError) { throw new AggregateException($"Internal error occurred while executing the action of task - {Id}.", ex); } } } public async Task ExecuteInSeries(CancellationToken cancellationToken, bool throwOnError) { if (seriesRunnerIsBusy || concurrentRunnerIsBusy) return; seriesRunnerIsBusy = true; ResetChildrenProgressValues(); try { foreach (var child in childTasks) { if (cancellationToken.IsCancellationRequested) break; await child.ExecuteInSeries(cancellationToken, throwOnError); } await ExceptionHandledAction(cancellationToken, throwOnError); } catch (Exception ex) { if (throwOnError) { throw new AggregateException($"Internal error occurred while executing task - {Id}.", ex); } } seriesRunnerIsBusy = false; if (TaskStatus != TaskStatus.Failed) { if (cancellationToken.IsCancellationRequested) Report(TaskStatus.Cancelled, 0); else Report(TaskStatus.Completed, 100); } } public IEnumerable<ITaskNode> ToFlatList() { return FlatList(this); } private void SafeRaiseReportingEvent(object sender, ProgressReportingEventArgs args) { this.Reporting?.Invoke(sender, args); } private void ResetChildrenProgressValues() { taskObjects.Clear(); foreach (var task in childTasks) { task.ResetStatus(); } } /// <summary> /// Throws <see cref="AsyncTasksCycleDetectedException"/> /// </summary> /// <param name="newTask"></param> private void EnsureNoCycles(ITaskNode newTask) { var thisNode = this as ITaskNode; HashSet<ITaskNode> hSet = new HashSet<ITaskNode>(); while (true) { if (thisNode.Parent is null) { break; } if (hSet.Contains(thisNode)) { throw new TaskNodeCycleDetectedException(thisNode, newTask); } hSet.Add(thisNode); thisNode = thisNode.Parent; } var existingTask = FlatList(thisNode).FirstOrDefault(t => t == newTask); if (existingTask != null) { throw new TaskNodeCycleDetectedException(newTask, existingTask.Parent); } } private IEnumerable<ITaskNode> FlatList(ITaskNode root) { yield return root; foreach (var ct in root.ChildTasks) { foreach (var item in FlatList(ct)) yield return item; } } public void RemoveChild(ITaskNode childTask) { childTask.Reporting -= OnChildReporting; childTasks.Remove(childTask); } public void Report(TaskStatus taskStatus, double progressValue, object progressState = null) { SafeRaiseReportingEvent(this, new ProgressReportingEventArgs { ChildTasksRunningInParallel = concurrentRunnerIsBusy, TaskStatus = taskStatus, ProgressValue = progressValue, ProgressState = progressState }); } public void SetAction(Func<IProgressReporter, CancellationToken, Task> cancellableProgressReportingAction) { cancellableProgressReportingAction = cancellableProgressReportingAction ?? throw new ArgumentNullException(nameof(cancellableProgressReportingAction)); hasCustomAction = true; action = cancellableProgressReportingAction; } public void ResetStatus() { this.TaskStatus = TaskStatus.NotStarted; this.ProgressState = null; this.ProgressValue = 0; } public override string ToString() { return $"Id={Id},({TaskStatus}, {ProgressValue}, {ProgressState})"; } } }
Source/TreeifyTask/TaskTree/TaskNode.cs
intuit-TreeifyTask-4b124d4
[ { "filename": "Source/TreeifyTask.BlazorSample/TaskDataModel/code.cs", "retrieved_chunk": " {\n }\n class AT\n {\n public AT(string id,\n CancellableAsyncActionDelegate action,\n params AT[] children)\n {\n Id = id;\n Action = action;", "score": 0.8548704385757446 }, { "filename": "Source/TreeifyTask/TaskTree/TaskNodeCycleDetectedException.cs", "retrieved_chunk": "using System;\nusing System.Runtime.Serialization;\nnamespace TreeifyTask\n{\n [Serializable]\n public class TaskNodeCycleDetectedException : Exception\n {\n public ITaskNode NewTask { get; }\n public ITaskNode ParentTask { get; }\n public string MessageStr { get; private set; }", "score": 0.8385899662971497 }, { "filename": "Source/TreeifyTask.BlazorSample/TaskDataModel/code.cs", "retrieved_chunk": "using System;\nusing System.Threading.Tasks;\nnamespace TreeifyTask.BlazorSample\n{\n delegate Task CancellableAsyncActionDelegate(Pr reporter, Tk token);\n class Pr\n {\n public void report() { }\n }\n struct Tk", "score": 0.8349185585975647 }, { "filename": "Source/TreeifyTask.BlazorSample/TaskDataModel/code.cs", "retrieved_chunk": " Children = children;\n }\n public string Id { get; }\n public CancellableAsyncActionDelegate Action { get; }\n public AT[] Children { get; }\n }\n public class CodeTry\n {\n public void SyntaxCheck()\n {", "score": 0.8347249031066895 }, { "filename": "Source/TreeifyTask/TaskTree/ProgressReportingEventArgs.cs", "retrieved_chunk": "using System;\nnamespace TreeifyTask\n{\n public class ProgressReportingEventArgs : EventArgs\n {\n public TaskStatus TaskStatus { get; set; }\n public double ProgressValue { get; set; }\n public object ProgressState { get; set; }\n public bool ChildTasksRunningInParallel { get; set; }\n }", "score": 0.8321987986564636 } ]
csharp
IProgressReporter, CancellationToken, Task> action = async (rep, tok) => await Task.Yield();
#nullable enable using System; using System.Net.Http; using System.Threading; using Cysharp.Threading.Tasks; using Mochineko.Relent.UncertainResult; using Mochineko.YouTubeLiveStreamingClient.Responses; using UniRx; using UnityEngine; namespace Mochineko.YouTubeLiveStreamingClient { /// <summary> /// Collects and provides live chat messages from YouTube Data API v3. /// </summary> public sealed class LiveChatMessagesCollector : IDisposable { private readonly HttpClient httpClient; private readonly IAPIKeyProvider apiKeyProvider; private readonly string videoID; private readonly uint maxResultsOfMessages; private readonly bool dynamicInterval; private readonly bool verbose; private readonly CancellationTokenSource cancellationTokenSource = new(); private readonly Subject<
VideosAPIResponse> onVideoInformationUpdated = new();
public IObservable<VideosAPIResponse> OnVideoInformationUpdated => onVideoInformationUpdated; private readonly Subject<LiveChatMessageItem> onMessageCollected = new(); public IObservable<LiveChatMessageItem> OnMessageCollected => onMessageCollected; private bool isCollecting = false; private string? liveChatID = null; private string? nextPageToken = null; private float intervalSeconds; public LiveChatMessagesCollector( HttpClient httpClient, string apiKey, string videoID, uint maxResultsOfMessages = 500, bool dynamicInterval = false, float intervalSeconds = 5f, bool verbose = true) { if (string.IsNullOrEmpty(apiKey)) { throw new ArgumentException($"{nameof(apiKey)} must no be empty."); } if (string.IsNullOrEmpty(videoID)) { throw new ArgumentException($"{nameof(videoID)} must no be empty."); } this.httpClient = httpClient; this.apiKeyProvider = new SingleAPIKeyProvider(apiKey); this.videoID = videoID; this.maxResultsOfMessages = maxResultsOfMessages; this.dynamicInterval = dynamicInterval; this.intervalSeconds = intervalSeconds; this.verbose = verbose; } // TODO: Check private LiveChatMessagesCollector( HttpClient httpClient, string[] apiKeys, string videoID, uint maxResultsOfMessages = 500, bool dynamicInterval = false, float intervalSeconds = 5f, bool verbose = true) { if (apiKeys.Length == 0) { throw new ArgumentException($"{nameof(apiKeys)} must not be empty."); } if (string.IsNullOrEmpty(videoID)) { throw new ArgumentException($"{nameof(videoID)} must no be empty."); } this.httpClient = httpClient; this.apiKeyProvider = new MultiAPIKeyProvider(apiKeys); this.videoID = videoID; this.maxResultsOfMessages = maxResultsOfMessages; this.dynamicInterval = dynamicInterval; this.intervalSeconds = intervalSeconds; this.verbose = verbose; } public void Dispose() { cancellationTokenSource.Dispose(); } /// <summary> /// Begins collecting live chat messages. /// </summary> public void BeginCollection() { if (isCollecting) { return; } isCollecting = true; BeginCollectionAsync(cancellationTokenSource.Token) .Forget(); } private async UniTask BeginCollectionAsync( CancellationToken cancellationToken) { await UniTask.SwitchToThreadPool(); while (!cancellationToken.IsCancellationRequested) { await UpdateAsync(cancellationToken); try { await UniTask.Delay( TimeSpan.FromSeconds(intervalSeconds), cancellationToken: cancellationToken ); } // Catch cancellation catch (OperationCanceledException) { return; } } } private async UniTask UpdateAsync(CancellationToken cancellationToken) { if (liveChatID == null) { await GetLiveChatIDAsync(cancellationToken); // Succeeded to get live chat ID if (liveChatID != null) { await PollLiveChatMessagesAsync(liveChatID, cancellationToken); } } else { await PollLiveChatMessagesAsync(liveChatID, cancellationToken); } } private async UniTask GetLiveChatIDAsync(CancellationToken cancellationToken) { if (verbose) { Debug.Log($"[YouTubeLiveStreamingClient] Getting live chat ID from video ID:{videoID}..."); } var result = await VideosAPI.GetVideoInformationAsync( httpClient, apiKeyProvider.APIKey, videoID, cancellationToken); VideosAPIResponse response; switch (result) { case IUncertainSuccessResult<VideosAPIResponse> success: { if (verbose) { Debug.Log($"[YouTubeLiveStreamingClient] Succeeded to get video API response."); } response = success.Result; break; } case LimitExceededResult<VideosAPIResponse> limitExceeded: { if (verbose) { Debug.LogWarning( $"[YouTubeLiveStreamingClient] Failed to get live chat ID because -> {limitExceeded.Message}."); } if (apiKeyProvider.TryChangeKey()) { if (verbose) { Debug.Log( $"[YouTubeLiveStreamingClient] Change API key and continue."); } // Use another API key from next time return; } else { Debug.LogError( $"[YouTubeLiveStreamingClient] Failed to change API key."); return; } } case IUncertainRetryableResult<VideosAPIResponse> retryable: { if (verbose) { Debug.Log( $"[YouTubeLiveStreamingClient] Retryable failed to get live chat ID because -> {retryable.Message}."); } return; } case IUncertainFailureResult<VideosAPIResponse> failure: { Debug.LogError( $"[YouTubeLiveStreamingClient] Failed to get live chat ID because -> {failure.Message}"); return; } default: throw new UncertainResultPatternMatchException(nameof(result)); } if (response.Items.Count == 0) { if (verbose) { Debug.Log($"[YouTubeLiveStreamingClient] No items are found in response from video ID:{videoID}."); } return; } var liveChatID = response.Items[0].LiveStreamingDetails.ActiveLiveChatId; if (!string.IsNullOrEmpty(liveChatID)) { if (verbose) { Debug.Log( $"[YouTubeLiveStreamingClient] Succeeded to get live chat ID:{liveChatID} from video ID:{videoID}."); } this.liveChatID = liveChatID; onVideoInformationUpdated.OnNext(response); } else { Debug.LogError($"[YouTubeLiveStreamingClient] LiveChatID is null or empty from video ID:{videoID}."); } } private async UniTask PollLiveChatMessagesAsync( string liveChatID, CancellationToken cancellationToken) { if (verbose) { Debug.Log($"[YouTubeLiveStreamingClient] Polling live chat messages..."); } var result = await LiveChatMessagesAPI.GetLiveChatMessagesAsync( httpClient, apiKeyProvider.APIKey, liveChatID, cancellationToken, pageToken: nextPageToken, maxResults: maxResultsOfMessages); LiveChatMessagesAPIResponse response; switch (result) { case IUncertainSuccessResult<LiveChatMessagesAPIResponse> success: { if (verbose) { Debug.Log( $"[YouTubeLiveStreamingClient] Succeeded to get live chat messages: {success.Result.Items.Count} messages with next page token:{success.Result.NextPageToken}."); } response = success.Result; this.nextPageToken = response.NextPageToken; if (dynamicInterval) { this.intervalSeconds = response.PollingIntervalMillis / 1000f; } break; } case LimitExceededResult<LiveChatMessagesAPIResponse> limitExceeded: { if (verbose) { Debug.LogWarning( $"[YouTubeLiveStreamingClient] Failed to get live chat messages because -> {limitExceeded.Message}."); } if (apiKeyProvider.TryChangeKey()) { if (verbose) { Debug.Log( $"[YouTubeLiveStreamingClient] Change API key and continue."); } // Use another API key from next time return; } else { Debug.LogError( $"[YouTubeLiveStreamingClient] Failed to change API key."); return; } } case IUncertainRetryableResult<LiveChatMessagesAPIResponse> retryable: { if (verbose) { Debug.Log( $"[YouTubeLiveStreamingClient] Retryable failed to get live chat messages because -> {retryable.Message}."); } return; } case IUncertainFailureResult<LiveChatMessagesAPIResponse> failure: { Debug.LogError( $"[YouTubeLiveStreamingClient] Failed to get live chat messages because -> {failure.Message}"); return; } default: throw new UncertainResultPatternMatchException(nameof(result)); } // NOTE: Publish event on the main thread. await UniTask.SwitchToMainThread(cancellationToken); foreach (var item in response.Items) { if (verbose) { Debug.Log( $"[YouTubeLiveStreamingClient] Collected live chat message: {item.Snippet.DisplayMessage} from {item.AuthorDetails.DisplayName} at {item.Snippet.PublishedAt}."); } onMessageCollected.OnNext(item); } await UniTask.SwitchToThreadPool(); } } }
Assets/Mochineko/YouTubeLiveStreamingClient/LiveChatMessagesCollector.cs
mochi-neko-youtube-live-streaming-client-unity-b712d77
[ { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient.Samples/LiveChatMessagesCollectionDemo.cs", "retrieved_chunk": " {\n [SerializeField]\n private string apiKeyPath = string.Empty;\n [SerializeField]\n private string videoIDOrURL = string.Empty;\n [SerializeField, Range(200, 2000)]\n private uint maxResultsOfMessages = 500;\n [SerializeField]\n private float intervalSeconds = 5f;\n private static readonly HttpClient HttpClient = new();", "score": 0.8703665733337402 }, { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/LiveChatMessagesAPIResponse.cs", "retrieved_chunk": " [JsonProperty(\"etag\"), JsonRequired]\n public string Etag { get; private set; } = string.Empty;\n [JsonProperty(\"nextPageToken\"), JsonRequired]\n public string NextPageToken { get; private set; } = string.Empty;\n [JsonProperty(\"pollingIntervalMillis\"), JsonRequired]\n public uint PollingIntervalMillis { get; private set; }\n [JsonProperty(\"pageInfo\"), JsonRequired]\n public PageInfo PageInfo { get; private set; } = new();\n [JsonProperty(\"items\"), JsonRequired]\n public List<LiveChatMessageItem> Items { get; private set; } = new();", "score": 0.8114621639251709 }, { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/VideoSnippet.cs", "retrieved_chunk": " [JsonProperty(\"channelId\"), JsonRequired]\n public string ChannelId { get; private set; } = string.Empty;\n [JsonProperty(\"title\"), JsonRequired]\n public string Title { get; private set; } = string.Empty;\n [JsonProperty(\"description\"), JsonRequired]\n public string Description { get; private set; } = string.Empty;\n [JsonProperty(\"thumbnails\"), JsonRequired]\n public VideoThumbnails Thumbnails { get; private set; } = new();\n [JsonProperty(\"channelTitle\"), JsonRequired]\n public string ChannelTitle { get; private set; } = string.Empty;", "score": 0.7838356494903564 }, { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient.Samples/LiveChatMessagesCollectionDemo.cs", "retrieved_chunk": " collector = new LiveChatMessagesCollector(\n HttpClient,\n apiKey,\n videoID,\n maxResultsOfMessages: maxResultsOfMessages,\n dynamicInterval: false,\n intervalSeconds: intervalSeconds,\n verbose: true);\n // Register events\n collector", "score": 0.7819973826408386 }, { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/SuperStickerDetails.cs", "retrieved_chunk": " public string AmountMicros { get; private set; } = string.Empty;\n [JsonProperty(\"currency\"), JsonRequired]\n public string Currency { get; private set; } = string.Empty;\n [JsonProperty(\"amountDisplayString\"), JsonRequired]\n public string AmountDisplayString { get; private set; } = string.Empty;\n [JsonProperty(\"tier\"), JsonRequired]\n public uint Tier { get; private set; }\n }\n}", "score": 0.779681921005249 } ]
csharp
VideosAPIResponse> onVideoInformationUpdated = new();
using System.Collections.Generic; using UnityEditor; using UnityEditor.Timeline; using UnityEngine; using UnityEngine.Timeline; namespace dev.kemomimi.TimelineExtension.AbstractValueControlTrack.Editor { internal static class AbstractColorValueControlTrackEditorUtility { internal static Color PrimaryColor = new(0.5f, 0.5f, 1f); } [CustomTimelineEditor(typeof(AbstractColorValueControlTrack))] public class AbstractColorValueControlTrackCustomEditor : TrackEditor { public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding) { track.name = "CustomTrack"; var options = base.GetTrackOptions(track, binding); options.trackColor = AbstractColorValueControlTrackEditorUtility.PrimaryColor; return options; } } [CustomTimelineEditor(typeof(AbstractColorValueControlClip))] public class AbstractColorValueControlCustomEditor : ClipEditor { Dictionary<
AbstractColorValueControlClip, Texture2D> textures = new();
public override ClipDrawOptions GetClipOptions(TimelineClip clip) { var clipOptions = base.GetClipOptions(clip); clipOptions.icons = null; clipOptions.highlightColor = AbstractColorValueControlTrackEditorUtility.PrimaryColor; return clipOptions; } public override void DrawBackground(TimelineClip clip, ClipBackgroundRegion region) { var tex = GetGradientTexture(clip); if (tex) GUI.DrawTexture(region.position, tex); } public override void OnClipChanged(TimelineClip clip) { GetGradientTexture(clip, true); } Texture2D GetGradientTexture(TimelineClip clip, bool update = false) { var tex = Texture2D.whiteTexture; var customClip = clip.asset as AbstractColorValueControlClip; if (!customClip) return tex; var gradient = customClip.Value; if (gradient == null) return tex; if (update) { textures.Remove(customClip); } else { textures.TryGetValue(customClip, out tex); if (tex) return tex; } var b = (float)(clip.blendInDuration / clip.duration); tex = new Texture2D(128, 1); for (int i = 0; i < tex.width; ++i) { var t = (float)i / tex.width; var color = customClip.Value; //get max color element var max = Mathf.Max(color.r, color.g, color.b); if (max > 1f) { color.r /= max; color.g /= max; color.b /= max; } color.a = 1f; if (b > 0f) color.a = Mathf.Min(t / b, 1f); tex.SetPixel(i, 0, color); } tex.Apply(); if (textures.ContainsKey(customClip)) { textures[customClip] = tex; } else { textures.Add(customClip, tex); } return tex; } } [CanEditMultipleObjects] [CustomEditor(typeof(AbstractColorValueControlClip))] public class AbstractColorValueControlClipEditor : UnityEditor.Editor { public override void OnInspectorGUI() { DrawDefaultInspector(); } } }
Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractColorValueControlTrackCustomEditor.cs
nmxi-Unity_AbstractTimelineExtention-b518049
[ { "filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractBoolValueControlTrackCustomEditor.cs", "retrieved_chunk": " return options;\n }\n }\n [CustomTimelineEditor(typeof(AbstractBoolValueControlClip))]\n public class AbstractBoolValueControlCustomEditor : ClipEditor\n {\n Dictionary<AbstractBoolValueControlClip, Texture2D> textures = new();\n public override ClipDrawOptions GetClipOptions(TimelineClip clip)\n {\n var clipOptions = base.GetClipOptions(clip);", "score": 0.914694607257843 }, { "filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractBoolValueControlTrackCustomEditor.cs", "retrieved_chunk": " }\n [CustomTimelineEditor(typeof(AbstractBoolValueControlTrack))]\n public class AbstractBoolValueControlTrackCustomEditor : TrackEditor\n {\n public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding)\n {\n track.name = \"CustomTrack\";\n var options = base.GetTrackOptions(track, binding);\n options.trackColor = AbstractBoolValueControlTrackEditorUtility.PrimaryColor;\n // Debug.Log(binding.GetType());", "score": 0.8968713283538818 }, { "filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractIntValueControlTrackCustomEditor.cs", "retrieved_chunk": " }\n [CustomTimelineEditor(typeof(AbstractIntValueControlClip))]\n public class AbstractIntValueControlCustomEditor : ClipEditor\n {\n public override ClipDrawOptions GetClipOptions(TimelineClip clip)\n {\n var clipOptions = base.GetClipOptions(clip);\n clipOptions.icons = null;\n clipOptions.highlightColor = AbstractIntValueControlTrackEditorUtility.PrimaryColor;\n return clipOptions;", "score": 0.8945640325546265 }, { "filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractFloatValueControlTrackCustomEditor.cs", "retrieved_chunk": " }\n [CustomTimelineEditor(typeof(AbstractFloatValueControlClip))]\n public class AbstractFloatValueControlCustomEditor : ClipEditor\n {\n public override ClipDrawOptions GetClipOptions(TimelineClip clip)\n {\n var clipOptions = base.GetClipOptions(clip);\n clipOptions.icons = null;\n clipOptions.highlightColor = AbstractFloatValueControlTrackEditorUtility.PrimaryColor;\n return clipOptions;", "score": 0.8931856155395508 }, { "filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractIntValueControlTrackCustomEditor.cs", "retrieved_chunk": " [CustomTimelineEditor(typeof(AbstractIntValueControlTrack))]\n public class AbstractIntValueControlTrackCustomEditor : TrackEditor\n {\n public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding)\n {\n track.name = \"CustomTrack\";\n var options = base.GetTrackOptions(track, binding);\n options.trackColor = AbstractIntValueControlTrackEditorUtility.PrimaryColor;\n return options;\n }", "score": 0.8841721415519714 } ]
csharp
AbstractColorValueControlClip, Texture2D> textures = new();
using GraphNotifications.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using StackExchange.Redis; using System; using System.Text; using System.Threading; namespace GraphNotifications.Services { /// <summary> /// Implements connection to Redis /// </summary> public class CacheService : ICacheService { private readonly ILogger<CacheService> _logger; private readonly
IRedisFactory _redisFactory;
private static readonly Encoding encoding = Encoding.UTF8; public CacheService(IRedisFactory redisFactory, ILogger<CacheService> logger) { _redisFactory = redisFactory; _logger = logger; } public async Task<bool> AddAsync<T>(string key, T value, TimeSpan? expiry = default(TimeSpan?)) { try { var redis = _redisFactory.GetCache(); if (redis == null) throw new ArgumentNullException("Redis Cache is null"); _logger.LogInformation($"Adding value to redis {key}"); // TODO move this out to it's own UTIL Class var jsonString = JsonConvert.SerializeObject(value); return await redis.StringSetAsync(key, encoding.GetBytes(jsonString), expiry); } catch (RedisConnectionException ex) { _redisFactory.ForceReconnect(); _logger.LogError(ex, "Redis Connection Error"); throw; } catch(Exception ex) { _logger.LogError(ex, $"Redis Add Error for - {key}"); throw; } } public async Task<T> GetAsync<T>(string key) { try { var redis = _redisFactory.GetCache(); if (redis == null) throw new ArgumentNullException("Redis Cache is null"); var value = await redis.StringGetAsync(key); if (!value.HasValue) { return default(T); } return JsonConvert.DeserializeObject<T>(value); } catch (RedisConnectionException ex) { _redisFactory.ForceReconnect(); _logger.LogError(ex, "Redis Connection Error"); throw; } catch (Exception ex) { _logger.LogError(ex, $"Redis Get Error for - {key}"); throw; } } public async Task<bool> DeleteAsync(string key) { try { var redis = _redisFactory.GetCache(); if (redis == null) throw new ArgumentNullException("Redis Cache is null"); return await redis.KeyDeleteAsync(key); } catch (RedisConnectionException ex) { _redisFactory.ForceReconnect(); _logger.LogError(ex, "Redis Connection Error"); throw; } catch (Exception ex) { _logger.LogError(ex, $"Redis Get Error for - {key}"); throw; } } } }
Services/CacheService.cs
microsoft-GraphNotificationBroker-b1564aa
[ { "filename": "Services/CertificateService.cs", "retrieved_chunk": "namespace GraphNotifications.Services\n{\n /// <summary>\n /// Implements methods to retrieve certificates from Azure Key Vault\n /// </summary>\n public class CertificateService : ICertificateService\n {\n private readonly AppSettings _settings;\n private readonly ILogger _logger;\n private readonly Uri _keyVaultUrl;", "score": 0.9092317819595337 }, { "filename": "Services/RedisFactory.cs", "retrieved_chunk": " /// </summary> \n public class RedisFactory : IRedisFactory\n {\n private static Lazy<IConnectionMultiplexer> _multiplexer;\n private static Lazy<IDatabase> _cache;\n private bool _disposed = false;\n private readonly AppSettings _settings;\n private readonly ILogger<RedisFactory> _logger;\n // Force Reconnect variables\n static long lastReconnectTicks = DateTimeOffset.MinValue.UtcTicks;", "score": 0.8820860981941223 }, { "filename": "Models/SubscriptionRecord.cs", "retrieved_chunk": "namespace GraphNotifications.Models\n{\n /// <summary>\n /// Subscription record saved in subscription store\n /// </summary>\n public class SubscriptionRecord : SubscriptionDefinition\n {\n /// <summary>\n /// The ID of the graph subscription\n /// </summary>", "score": 0.8599600791931152 }, { "filename": "Services/IRedisFactory.cs", "retrieved_chunk": "using StackExchange.Redis;\nnamespace GraphNotifications.Services\n{\n public interface IRedisFactory : IDisposable\n {\n IDatabase GetCache();\n void ForceReconnect();\n }\n}", "score": 0.8478767275810242 }, { "filename": "Services/ICacheService.cs", "retrieved_chunk": "namespace GraphNotifications.Services\n{\n /// <summary>\n /// \n /// </summary> \n public interface ICacheService\n {\n Task<bool> AddAsync<T>(string key, T value, TimeSpan? expiry = default(TimeSpan?));\n Task<T> GetAsync<T>(string key);\n Task<bool> DeleteAsync(string key);", "score": 0.8382726907730103 } ]
csharp
IRedisFactory _redisFactory;
using HarmonyLib; using ULTRAKILL.Cheats; using UnityEngine; namespace Ultrapain.Patches { public class Stalker_SandExplode_Patch { static bool Prefix(Stalker __instance, ref int ___difficulty, ref EnemyIdentifier ___eid, int __0, ref bool ___exploding, ref float ___countDownAmount, ref float ___explosionCharge, ref Color ___currentColor, Color[] ___lightColors, AudioSource ___lightAud, AudioClip[] ___lightSounds, ref bool ___blinking,
Machine ___mach, ref bool ___exploded, Transform ___target) {
bool removeStalker = true; if (!(StockMapInfo.Instance != null && StockMapInfo.Instance.levelName == "GOD DAMN THE SUN" && __instance.transform.parent != null && __instance.transform.parent.name == "Wave 1" && __instance.transform.parent.parent != null && __instance.transform.parent.parent.name.StartsWith("5 Stuff"))) { removeStalker = false; } GameObject explosion = Object.Instantiate<GameObject>(__instance.explosion, __instance.transform.position + Vector3.up * 2.5f, Quaternion.identity); if (__0 != 1) { explosion.transform.localScale *= 1.5f; } if (___eid.stuckMagnets.Count > 0) { float num = 0.75f; if (___eid.stuckMagnets.Count > 1) { num -= 0.125f * (float)(___eid.stuckMagnets.Count - 1); } explosion.transform.localScale *= num; } SandificationZone zone = explosion.GetComponentInChildren<SandificationZone>(); zone.buffDamage = zone.buffHealth = zone.buffSpeed = false; if (ConfigManager.stalkerSpreadHealthRad.value) zone.healthBuff = ___eid.healthBuffModifier + ConfigManager.stalkerSpreadHealthAddition.value; else zone.healthBuff = 0; if (ConfigManager.stalkerSpreadDamageRad.value) zone.damageBuff = ___eid.damageBuffModifier + ConfigManager.stalkerSpreadDamageAddition.value; else zone.damageBuff = 0; if (ConfigManager.stalkerSpreadSpeedRad.value) zone.speedBuff = ___eid.speedBuffModifier + ConfigManager.stalkerSpreadSpeedAddition.value; else zone.speedBuff = 0; if ((!removeStalker || ___eid.blessed || InvincibleEnemies.Enabled) && __0 != 1) { ___exploding = false; ___countDownAmount = 0f; ___explosionCharge = 0f; ___currentColor = ___lightColors[0]; ___lightAud.clip = ___lightSounds[0]; ___blinking = false; return false; } ___exploded = true; if (!___mach.limp) { ___mach.GoLimp(); ___eid.Death(); } if (___target != null) { if (MonoSingleton<StalkerController>.Instance.CheckIfTargetTaken(___target)) { MonoSingleton<StalkerController>.Instance.targets.Remove(___target); } EnemyIdentifier enemyIdentifier; if (___target.TryGetComponent<EnemyIdentifier>(out enemyIdentifier) && enemyIdentifier.buffTargeter == ___eid) { enemyIdentifier.buffTargeter = null; } } if (___eid.drillers.Count != 0) { for (int i = ___eid.drillers.Count - 1; i >= 0; i--) { Object.Destroy(___eid.drillers[i].gameObject); } } __instance.gameObject.SetActive(false); Object.Destroy(__instance.gameObject); return false; } } public class SandificationZone_Enter_Patch { static void Postfix(SandificationZone __instance, Collider __0) { if (__0.gameObject.layer == 10 || __0.gameObject.layer == 11) { EnemyIdentifierIdentifier component = __0.gameObject.GetComponent<EnemyIdentifierIdentifier>(); if (component && component.eid && !component.eid.dead && component.eid.enemyType != EnemyType.Stalker) { EnemyIdentifier eid = component.eid; if (eid.damageBuffModifier < __instance.damageBuff) eid.DamageBuff(__instance.damageBuff); if (eid.speedBuffModifier < __instance.speedBuff) eid.SpeedBuff(__instance.speedBuff); if (eid.healthBuffModifier < __instance.healthBuff) eid.HealthBuff(__instance.healthBuff); } } } } }
Ultrapain/Patches/Stalker.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": " }\n else\n patch.swingComboLeft = 2;*/\n }\n }\n class Mindflayer_MeleeTeleport_Patch\n {\n public static Vector3 deltaPosition = new Vector3(0, -10, 0);\n static bool Prefix(Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___goingLeft, ref Animator ___anim, ref bool ___enraged)\n {", "score": 0.8234509229660034 }, { "filename": "Ultrapain/Patches/V2Second.cs", "retrieved_chunk": " }\n class V2SecondFastCoin\n {\n static MethodInfo switchWeapon = typeof(V2).GetMethod(\"SwitchWeapon\", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);\n static bool Prefix(V2 __instance, ref int ___coinsToThrow, ref bool ___aboutToShoot, ref Transform ___overrideTarget, ref Rigidbody ___overrideTargetRb,\n ref Transform ___target, Animator ___anim, ref bool ___shootingForCoin, ref int ___currentWeapon, ref float ___shootCooldown, ref bool ___aiming)\n {\n if (___coinsToThrow == 0)\n {\n return false;", "score": 0.8214255571365356 }, { "filename": "Ultrapain/Patches/Turret.cs", "retrieved_chunk": " static void Postfix(Turret __instance)\n {\n __instance.gameObject.AddComponent<TurretFlag>();\n }\n }\n class TurretShoot\n {\n static bool Prefix(Turret __instance, ref EnemyIdentifier ___eid, ref RevolverBeam ___beam, ref Transform ___shootPoint,\n ref float ___aimTime, ref float ___maxAimTime, ref float ___nextBeepTime, ref float ___flashTime)\n {", "score": 0.8193617463111877 }, { "filename": "Ultrapain/Patches/Leviathan.cs", "retrieved_chunk": " }\n return false;\n }\n }\n class Leviathan_ProjectileBurst\n {\n static bool Prefix(LeviathanHead __instance, Animator ___anim,\n ref int ___projectilesLeftInBurst, ref float ___projectileBurstCooldown, ref bool ___inAction)\n {\n if (!__instance.active)", "score": 0.8189136981964111 }, { "filename": "Ultrapain/Patches/Leviathan.cs", "retrieved_chunk": " class Leviathan_FixedUpdate\n {\n public static float projectileForward = 10f;\n static bool Roll(float chancePercent)\n {\n return UnityEngine.Random.Range(0, 99.9f) <= chancePercent;\n }\n static bool Prefix(LeviathanHead __instance, LeviathanController ___lcon, ref bool ___projectileBursting, float ___projectileBurstCooldown,\n Transform ___shootPoint, ref bool ___trackerIgnoreLimits, Animator ___anim, ref int ___previousAttack)\n {", "score": 0.8186993598937988 } ]
csharp
Machine ___mach, ref bool ___exploded, Transform ___target) {
using BepInEx; using UnityEngine; using UnityEngine.SceneManagement; using System; using HarmonyLib; using System.IO; using Ultrapain.Patches; using System.Linq; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Reflection; using Steamworks; using Unity.Audio; using System.Text; using System.Collections.Generic; using UnityEngine.AddressableAssets; using UnityEngine.AddressableAssets.ResourceLocators; using UnityEngine.ResourceManagement.ResourceLocations; using UnityEngine.UIElements; using PluginConfig.API; namespace Ultrapain { [BepInPlugin(PLUGIN_GUID, PLUGIN_NAME, PLUGIN_VERSION)] [BepInDependency("com.eternalUnion.pluginConfigurator", "1.6.0")] public class Plugin : BaseUnityPlugin { public const string PLUGIN_GUID = "com.eternalUnion.ultraPain"; public const string PLUGIN_NAME = "Ultra Pain"; public const string PLUGIN_VERSION = "1.1.0"; public static Plugin instance; private static bool addressableInit = false; public static T LoadObject<T>(string path) { if (!addressableInit) { Addressables.InitializeAsync().WaitForCompletion(); addressableInit = true; } return Addressables.LoadAssetAsync<T>(path).WaitForCompletion(); } public static Vector3 PredictPlayerPosition(Collider safeCollider, float speedMod) { Transform target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f) return target.position; RaycastHit raycastHit; if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == safeCollider) return target.position; else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { return raycastHit.point; } else { Vector3 projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod; return new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z); } } public static GameObject projectileSpread; public static GameObject homingProjectile; public static GameObject hideousMassProjectile; public static GameObject decorativeProjectile2; public static GameObject shotgunGrenade; public static GameObject beam; public static GameObject turretBeam; public static GameObject lightningStrikeExplosiveSetup; public static GameObject lightningStrikeExplosive; public static GameObject lighningStrikeWindup; public static GameObject explosion; public static GameObject bigExplosion; public static GameObject sandExplosion; public static GameObject virtueInsignia; public static GameObject rocket; public static GameObject revolverBullet; public static GameObject maliciousCannonBeam; public static GameObject lightningBoltSFX; public static GameObject revolverBeam; public static GameObject blastwave; public static GameObject cannonBall; public static GameObject shockwave; public static GameObject sisyphiusExplosion; public static GameObject sisyphiusPrimeExplosion; public static GameObject explosionWaveKnuckleblaster; public static GameObject chargeEffect; public static GameObject maliciousFaceProjectile; public static GameObject hideousMassSpear; public static GameObject coin; public static GameObject sisyphusDestroyExplosion; //public static GameObject idol; public static GameObject ferryman; public static GameObject minosPrime; //public static GameObject maliciousFace; public static GameObject somethingWicked; public static Turret turret; public static
GameObject turretFinalFlash;
public static GameObject enrageEffect; public static GameObject v2flashUnparryable; public static GameObject ricochetSfx; public static GameObject parryableFlash; public static AudioClip cannonBallChargeAudio; public static Material gabrielFakeMat; public static Sprite blueRevolverSprite; public static Sprite greenRevolverSprite; public static Sprite redRevolverSprite; public static Sprite blueShotgunSprite; public static Sprite greenShotgunSprite; public static Sprite blueNailgunSprite; public static Sprite greenNailgunSprite; public static Sprite blueSawLauncherSprite; public static Sprite greenSawLauncherSprite; public static GameObject rocketLauncherAlt; public static GameObject maliciousRailcannon; // Variables public static float SoliderShootAnimationStart = 1.2f; public static float SoliderGrenadeForce = 10000f; public static float SwordsMachineKnockdownTimeNormalized = 0.8f; public static float SwordsMachineCoreSpeed = 80f; public static float MinGrenadeParryVelocity = 40f; public static GameObject _lighningBoltSFX; public static GameObject lighningBoltSFX { get { if (_lighningBoltSFX == null) _lighningBoltSFX = ferryman.gameObject.transform.Find("LightningBoltChimes").gameObject; return _lighningBoltSFX; } } private static bool loadedPrefabs = false; public void LoadPrefabs() { if (loadedPrefabs) return; loadedPrefabs = true; // Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab projectileSpread = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab homingProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab decorativeProjectile2 = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab"); // Assets/Prefabs/Attacks and Projectiles/Grenade.prefab shotgunGrenade = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Grenade.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab turretBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab beam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab lightningStrikeExplosiveSetup = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab"); // Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab lighningStrikeWindup = LoadObject<GameObject>("Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab"); //[bundle-0][assets/prefabs/enemies/idol.prefab] //idol = LoadObject<GameObject>("assets/prefabs/enemies/idol.prefab"); // Assets/Prefabs/Enemies/Ferryman.prefab ferryman = LoadObject<GameObject>("Assets/Prefabs/Enemies/Ferryman.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab explosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab bigExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab sandExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab"); // Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab virtueInsignia = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab hideousMassProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab"); // Assets/Particles/Enemies/RageEffect.prefab enrageEffect = LoadObject<GameObject>("Assets/Particles/Enemies/RageEffect.prefab"); // Assets/Particles/Flashes/V2FlashUnparriable.prefab v2flashUnparryable = LoadObject<GameObject>("Assets/Particles/Flashes/V2FlashUnparriable.prefab"); // Assets/Prefabs/Attacks and Projectiles/Rocket.prefab rocket = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Rocket.prefab"); // Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab revolverBullet = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab maliciousCannonBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab revolverBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab blastwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab"); // Assets/Prefabs/Enemies/MinosPrime.prefab minosPrime = LoadObject<GameObject>("Assets/Prefabs/Enemies/MinosPrime.prefab"); // Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab cannonBall = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab"); // get from Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab cannonBallChargeAudio = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab").transform.Find("RocketLauncher/Armature/Body_Bone/HologramDisplay").GetComponent<AudioSource>().clip; // Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab shockwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab sisyphiusExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab sisyphiusPrimeExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab explosionWaveKnuckleblaster = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab - [bundle-0][assets/prefabs/explosionlightning variant.prefab] lightningStrikeExplosive = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab"); // Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab rocketLauncherAlt = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab"); // Assets/Prefabs/Weapons/Railcannon Malicious.prefab maliciousRailcannon = LoadObject<GameObject>("Assets/Prefabs/Weapons/Railcannon Malicious.prefab"); //Assets/Particles/SoundBubbles/Ricochet.prefab ricochetSfx = LoadObject<GameObject>("Assets/Particles/SoundBubbles/Ricochet.prefab"); //Assets/Particles/Flashes/Flash.prefab parryableFlash = LoadObject<GameObject>("Assets/Particles/Flashes/Flash.prefab"); //Assets/Prefabs/Attacks and Projectiles/Spear.prefab hideousMassSpear = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Spear.prefab"); //Assets/Prefabs/Enemies/Wicked.prefab somethingWicked = LoadObject<GameObject>("Assets/Prefabs/Enemies/Wicked.prefab"); //Assets/Textures/UI/SingleRevolver.png blueRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/SingleRevolver.png"); //Assets/Textures/UI/RevolverSpecial.png greenRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSpecial.png"); //Assets/Textures/UI/RevolverSharp.png redRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSharp.png"); //Assets/Textures/UI/Shotgun.png blueShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun.png"); //Assets/Textures/UI/Shotgun1.png greenShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun1.png"); //Assets/Textures/UI/Nailgun2.png blueNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Nailgun2.png"); //Assets/Textures/UI/NailgunOverheat.png greenNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/NailgunOverheat.png"); //Assets/Textures/UI/SawbladeLauncher.png blueSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncher.png"); //Assets/Textures/UI/SawbladeLauncherOverheat.png greenSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncherOverheat.png"); //Assets/Prefabs/Attacks and Projectiles/Coin.prefab coin = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Coin.prefab"); //Assets/Materials/GabrielFake.mat gabrielFakeMat = LoadObject<Material>("Assets/Materials/GabrielFake.mat"); //Assets/Prefabs/Enemies/Turret.prefab turret = LoadObject<GameObject>("Assets/Prefabs/Enemies/Turret.prefab").GetComponent<Turret>(); //Assets/Particles/Flashes/GunFlashDistant.prefab turretFinalFlash = LoadObject<GameObject>("Assets/Particles/Flashes/GunFlashDistant.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab sisyphusDestroyExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab"); //Assets/Prefabs/Effects/Charge Effect.prefab chargeEffect = LoadObject<GameObject>("Assets/Prefabs/Effects/Charge Effect.prefab"); //Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab maliciousFaceProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab"); } public static bool ultrapainDifficulty = false; public static bool realUltrapainDifficulty = false; public static GameObject currentDifficultyButton; public static GameObject currentDifficultyPanel; public static Text currentDifficultyInfoText; public void OnSceneChange(Scene before, Scene after) { StyleIDs.RegisterIDs(); ScenePatchCheck(); string mainMenuSceneName = "b3e7f2f8052488a45b35549efb98d902"; string bootSequenceSceneName = "4f8ecffaa98c2614f89922daf31fa22d"; string currentSceneName = SceneManager.GetActiveScene().name; if (currentSceneName == mainMenuSceneName) { LoadPrefabs(); //Canvas/Difficulty Select (1)/Violent Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Difficulty Select (1)"); GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect); currentDifficultyButton = ultrapainButton; ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value; ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5; RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>(); ultrapainTrans.anchoredPosition = new Vector2(20f, -104f); //Canvas/Difficulty Select (1)/Violent Info GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect); currentDifficultyPanel = info; currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>(); currentDifficultyInfoText.text = ConfigManager.pluginInfo.value; Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>(); currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--"; currentDifficultyHeaderText.resizeTextForBestFit = true; currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap; currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate; info.SetActive(false); EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>(); evt.triggers.Clear(); /*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(false));*/ EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit }; trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false)); evt.triggers.Add(trigger1); evt.triggers.Add(trigger2); foreach(EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>()) { if (trigger.gameObject == ultrapainButton) continue; EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false)); trigger.triggers.Add(closeTrigger); } } else if(currentSceneName == bootSequenceSceneName) { LoadPrefabs(); //Canvas/Difficulty Select (1)/Violent Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Intro/Difficulty Select"); GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect); currentDifficultyButton = ultrapainButton; ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value; ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5; RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>(); ultrapainTrans.anchoredPosition = new Vector2(20f, -104f); //Canvas/Difficulty Select (1)/Violent Info GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect); currentDifficultyPanel = info; currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>(); currentDifficultyInfoText.text = ConfigManager.pluginInfo.value; Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>(); currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--"; currentDifficultyHeaderText.resizeTextForBestFit = true; currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap; currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate; info.SetActive(false); EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>(); evt.triggers.Clear(); /*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(false));*/ EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit }; trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false)); evt.triggers.Add(trigger1); evt.triggers.Add(trigger2); foreach (EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>()) { if (trigger.gameObject == ultrapainButton) continue; EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false)); trigger.triggers.Add(closeTrigger); } } // LOAD CUSTOM PREFABS HERE TO AVOID MID GAME LAG MinosPrimeCharge.CreateDecoy(); GameObject shockwaveSisyphus = SisyphusInstructionist_Start.shockwave; } public static class StyleIDs { private static bool registered = false; public static void RegisterIDs() { registered = false; if (MonoSingleton<StyleHUD>.Instance == null) return; MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.grenadeBoostStyleText.guid, ConfigManager.grenadeBoostStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.rocketBoostStyleText.guid, ConfigManager.rocketBoostStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverStyleText.guid, ConfigManager.orbStrikeRevolverStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverChargedStyleText.guid, ConfigManager.orbStrikeRevolverChargedStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeElectricCannonStyleText.guid, ConfigManager.orbStrikeElectricCannonStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeMaliciousCannonStyleText.guid, ConfigManager.orbStrikeMaliciousCannonStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.maliciousChargebackStyleText.guid, ConfigManager.maliciousChargebackStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.sentryChargebackStyleText.guid, ConfigManager.sentryChargebackStyleText.formattedString); registered = true; Debug.Log("Registered all style ids"); } private static FieldInfo idNameDict = typeof(StyleHUD).GetField("idNameDict", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); public static void UpdateID(string id, string newName) { if (!registered || StyleHUD.Instance == null) return; (idNameDict.GetValue(StyleHUD.Instance) as Dictionary<string, string>)[id] = newName; } } public static Harmony harmonyTweaks; public static Harmony harmonyBase; private static MethodInfo GetMethod<T>(string name) { return typeof(T).GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } private static Dictionary<MethodInfo, HarmonyMethod> methodCache = new Dictionary<MethodInfo, HarmonyMethod>(); private static HarmonyMethod GetHarmonyMethod(MethodInfo method) { if (methodCache.TryGetValue(method, out HarmonyMethod harmonyMethod)) return harmonyMethod; else { harmonyMethod = new HarmonyMethod(method); methodCache.Add(method, harmonyMethod); return harmonyMethod; } } private static void PatchAllEnemies() { if (!ConfigManager.enemyTweakToggle.value) return; if (ConfigManager.friendlyFireDamageOverrideToggle.value) { harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<PhysicalShockwave>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<VirtueInsignia>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_FF>("Prefix"))); harmonyTweaks.Patch(GetMethod<Flammable>("Burn"), prefix: GetHarmonyMethod(GetMethod<Flammable_Burn_FF>("Prefix"))); harmonyTweaks.Patch(GetMethod<FireZone>("OnTriggerStay"), prefix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Postfix"))); } harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("UpdateModifiers"), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_UpdateModifiers>("Postfix"))); harmonyTweaks.Patch(GetMethod<StatueBoss>("Start"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Start_Patch>("Postfix"))); if (ConfigManager.cerberusDashToggle.value) harmonyTweaks.Patch(GetMethod<StatueBoss>("StopDash"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopDash_Patch>("Postfix"))); if(ConfigManager.cerberusParryable.value) { harmonyTweaks.Patch(GetMethod<StatueBoss>("StopTracking"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopTracking_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<StatueBoss>("Stomp"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Stomp_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Statue>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Statue_GetHurt_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Drone_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Drone>("Shoot"), prefix: GetHarmonyMethod(GetMethod<Drone_Shoot_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("PlaySound"), prefix: GetHarmonyMethod(GetMethod<Drone_PlaySound_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Update"), postfix: GetHarmonyMethod(GetMethod<Drone_Update>("Postfix"))); if(ConfigManager.droneHomeToggle.value) { harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Drone_Death_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Drone_GetHurt_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Ferryman>("Start"), postfix: GetHarmonyMethod(GetMethod<FerrymanStart>("Postfix"))); if(ConfigManager.ferrymanComboToggle.value) harmonyTweaks.Patch(GetMethod<Ferryman>("StopMoving"), postfix: GetHarmonyMethod(GetMethod<FerrymanStopMoving>("Postfix"))); if(ConfigManager.filthExplodeToggle.value) harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch2>("Prefix"))); if(ConfigManager.fleshPrisonSpinAttackToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<FleshPrisonShoot>("Postfix"))); if (ConfigManager.hideousMassInsigniaToggle.value) { harmonyTweaks.Patch(GetMethod<Projectile>("Explode"), postfix: GetHarmonyMethod(GetMethod<Projectile_Explode_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Mass>("ShootExplosive"), postfix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Postfix")), prefix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Prefix"))); } harmonyTweaks.Patch(GetMethod<SpiderBody>("Start"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<SpiderBody>("ChargeBeam"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ChargeBeam>("Postfix"))); harmonyTweaks.Patch(GetMethod<SpiderBody>("BeamChargeEnd"), prefix: GetHarmonyMethod(GetMethod<MaliciousFace_BeamChargeEnd>("Prefix"))); if (ConfigManager.maliciousFaceHomingProjectileToggle.value) { harmonyTweaks.Patch(GetMethod<SpiderBody>("ShootProj"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ShootProj_Patch>("Postfix"))); } if (ConfigManager.maliciousFaceRadianceOnEnrage.value) harmonyTweaks.Patch(GetMethod<SpiderBody>("Enrage"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Enrage_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Mindflayer>("Start"), postfix: GetHarmonyMethod(GetMethod<Mindflayer_Start_Patch>("Postfix"))); if (ConfigManager.mindflayerShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<Mindflayer>("ShootProjectiles"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_ShootProjectiles_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_MF>("Prefix"))); } if (ConfigManager.mindflayerTeleportComboToggle.value) { harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Mindflayer>("MeleeTeleport"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_MeleeTeleport_Patch>("Prefix"))); //harmonyTweaks.Patch(GetMethod<SwingCheck2>("DamageStop"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_DamageStop_Patch>("Postfix"))); } if (ConfigManager.minosPrimeRandomTeleportToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("Postfix"))); if (ConfigManager.minosPrimeTeleportTrail.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("Teleport"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("TeleportPostfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Start"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Dropkick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Dropkick>("Prefix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Combo"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Combo>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("StopAction"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_StopAction>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Ascend"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Ascend>("Prefix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Death"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Death>("Prefix"))); if (ConfigManager.minosPrimeCrushAttackToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("RiderKick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_RiderKick>("Prefix"))); if (ConfigManager.minosPrimeComboExplosiveEndToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_ProjectileCharge>("Prefix"))); if (ConfigManager.schismSpreadAttackToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ShootProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ShootProjectile_Patch>("Postfix"))); if (ConfigManager.soliderShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<Solider_Start_Patch>("Postfix"))); } if(ConfigManager.soliderCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_SpawnProjectile_Patch>("Postfix"))); if (ConfigManager.soliderShootGrenadeToggle.value || ConfigManager.soliderShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_ThrowProjectile_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Stalker>("SandExplode"), prefix: GetHarmonyMethod(GetMethod<Stalker_SandExplode_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SandificationZone>("Enter"), postfix: GetHarmonyMethod(GetMethod<SandificationZone_Enter_Patch>("Postfix"))); if (ConfigManager.strayCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Swing>("Postfix"))); if (ConfigManager.strayShootToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_Start_Patch1>("Postfix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ThrowProjectile_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<SwingEnd>("Prefix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("DamageEnd"), prefix: GetHarmonyMethod(GetMethod<DamageEnd>("Prefix"))); } if(ConfigManager.streetCleanerCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<Streetcleaner>("Start"), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Start_Patch>("Postfix"))); if(ConfigManager.streetCleanerPredictiveDodgeToggle.value) harmonyTweaks.Patch(GetMethod<BulletCheck>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<BulletCheck_OnTriggerEnter_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("Start"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Start>("Postfix"))); if (ConfigManager.swordsMachineNoLightKnockbackToggle.value || ConfigManager.swordsMachineSecondPhaseMode.value != ConfigManager.SwordsMachineSecondPhase.None) { harmonyTweaks.Patch(GetMethod<SwordsMachine>("Knockdown"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Knockdown_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("Down"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Prefix"))); //harmonyTweaks.Patch(GetMethod<SwordsMachine>("SetSpeed"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_SetSpeed_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("EndFirstPhase"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Prefix"))); } if (ConfigManager.swordsMachineExplosiveSwordToggle.value) { harmonyTweaks.Patch(GetMethod<ThrownSword>("Start"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<ThrownSword>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_OnTriggerEnter_Patch>("Postfix"))); } harmonyTweaks.Patch(GetMethod<Turret>("Start"), postfix: GetHarmonyMethod(GetMethod<TurretStart>("Postfix"))); if(ConfigManager.turretBurstFireToggle.value) { harmonyTweaks.Patch(GetMethod<Turret>("Shoot"), prefix: GetHarmonyMethod(GetMethod<TurretShoot>("Prefix"))); harmonyTweaks.Patch(GetMethod<Turret>("StartAiming"), postfix: GetHarmonyMethod(GetMethod<TurretAim>("Postfix"))); } harmonyTweaks.Patch(GetMethod<Explosion>("Start"), postfix: GetHarmonyMethod(GetMethod<V2CommonExplosion>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2FirstStart>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2FirstUpdate>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2FirstShootWeapon>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2SecondStart>("Postfix"))); //if(ConfigManager.v2SecondStartEnraged.value) // harmonyTweaks.Patch(GetMethod<BossHealthBar>("OnEnable"), postfix: GetHarmonyMethod(GetMethod<V2SecondEnrage>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2SecondUpdate>("Prefix"))); //harmonyTweaks.Patch(GetMethod<V2>("AltShootWeapon"), postfix: GetHarmonyMethod(GetMethod<V2AltShootWeapon>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("SwitchWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondSwitchWeapon>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Prefix")), postfix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Postfix"))); if(ConfigManager.v2SecondFastCoinToggle.value) harmonyTweaks.Patch(GetMethod<V2>("ThrowCoins"), prefix: GetHarmonyMethod(GetMethod<V2SecondFastCoin>("Prefix"))); harmonyTweaks.Patch(GetMethod<Cannonball>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<V2RocketLauncher>("CannonBallTriggerPrefix"))); if (ConfigManager.v2FirstSharpshooterToggle.value || ConfigManager.v2SecondSharpshooterToggle.value) { harmonyTweaks.Patch(GetMethod<EnemyRevolver>("PrepareAltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverPrepareAltFire>("Prefix"))); harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverBullet>("Prefix"))); harmonyTweaks.Patch(GetMethod<EnemyRevolver>("AltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverAltShoot>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Virtue_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Drone>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Virtue_SpawnInsignia_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Virtue_Death_Patch>("Prefix"))); if (ConfigManager.sisyInstJumpShockwave.value) { harmonyTweaks.Patch(GetMethod<Sisyphus>("Start"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Sisyphus>("Update"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Update>("Postfix"))); } if(ConfigManager.sisyInstBoulderShockwave.value) harmonyTweaks.Patch(GetMethod<Sisyphus>("SetupExplosion"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_SetupExplosion>("Postfix"))); if(ConfigManager.sisyInstStrongerExplosion.value) harmonyTweaks.Patch(GetMethod<Sisyphus>("StompExplosion"), prefix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_StompExplosion>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("Awake"), postfix: GetHarmonyMethod(GetMethod<LeviathanTail_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("BigSplash"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_BigSplash>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_SwingEnd>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("Start"), postfix: GetHarmonyMethod(GetMethod<Leviathan_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurst"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurstStart"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurstStart>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<Leviathan_FixedUpdate>("Prefix"))); if (ConfigManager.somethingWickedSpear.value) { harmonyTweaks.Patch(GetMethod<Wicked>("Start"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_GetHit>("Postfix"))); } if(ConfigManager.somethingWickedSpawnOn43.value) { harmonyTweaks.Patch(GetMethod<ObjectActivator>("Activate"), prefix: GetHarmonyMethod(GetMethod<ObjectActivator_Activate>("Prefix"))); harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<JokeWicked_GetHit>("Postfix"))); } if (ConfigManager.panopticonFullPhase.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Panopticon_Start>("Postfix"))); if (ConfigManager.panopticonAxisBeam.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnInsignia>("Prefix"))); if (ConfigManager.panopticonSpinAttackToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<Panopticon_HomingProjectileAttack>("Postfix"))); if (ConfigManager.panopticonBlackholeProj.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnBlackHole"), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnBlackHole>("Postfix"))); if (ConfigManager.panopticonBalanceEyes.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnFleshDrones"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Postfix"))); if (ConfigManager.panopticonBlueProjToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Update"), transpiler: GetHarmonyMethod(GetMethod<Panopticon_BlueProjectile>("Transpiler"))); if (ConfigManager.idolExplosionToggle.value) harmonyTweaks.Patch(GetMethod<Idol>("Death"), postfix: GetHarmonyMethod(GetMethod<Idol_Death_Patch>("Postfix"))); // ADDME /* harmonyTweaks.Patch(GetMethod<GabrielSecond>("Start"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("BasicCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_BasicCombo>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("FastCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_FastCombo>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("CombineSwords"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_CombineSwords>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("ThrowCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_ThrowCombo>("Postfix"))); */ } private static void PatchAllPlayers() { if (!ConfigManager.playerTweakToggle.value) return; harmonyTweaks.Patch(GetMethod<Punch>("CheckForProjectile"), prefix: GetHarmonyMethod(GetMethod<Punch_CheckForProjectile_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch1>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Collision"), prefix: GetHarmonyMethod(GetMethod<Grenade_Collision_Patch>("Prefix"))); if (ConfigManager.rocketBoostToggle.value) harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_Patch>("Prefix"))); if (ConfigManager.rocketGrabbingToggle.value) harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate_Patch>("Prefix"))); if (ConfigManager.orbStrikeToggle.value) { harmonyTweaks.Patch(GetMethod<Coin>("Start"), postfix: GetHarmonyMethod(GetMethod<Coin_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Punch>("BlastCheck"), prefix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Postfix"))); harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide>("Prefix"))); harmonyTweaks.Patch(GetMethod<Coin>("DelayedReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_DelayedReflectRevolver>("Postfix"))); harmonyTweaks.Patch(GetMethod<Coin>("ReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Postfix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Prefix")), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Postfix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("ExecuteHits"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Prefix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("HitSomething"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Prefix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("Start"), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_Start>("Prefix"))); harmonyTweaks.Patch(GetMethod<Cannonball>("Explode"), prefix: GetHarmonyMethod(GetMethod<Cannonball_Explode>("Prefix"))); harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_CollideOrbital>("Prefix"))); } if(ConfigManager.chargedRevRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<Revolver>("Update"), prefix: GetHarmonyMethod(GetMethod<Revolver_Update>("Prefix"))); if(ConfigManager.coinRegSpeedMulti.value != 1 || ConfigManager.sharpshooterRegSpeedMulti.value != 1 || ConfigManager.railcannonRegSpeedMulti.value != 1 || ConfigManager.rocketFreezeRegSpeedMulti.value != 1 || ConfigManager.rocketCannonballRegSpeedMulti.value != 1 || ConfigManager.nailgunAmmoRegSpeedMulti.value != 1 || ConfigManager.sawAmmoRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<WeaponCharges>("Charge"), prefix: GetHarmonyMethod(GetMethod<WeaponCharges_Charge>("Prefix"))); if(ConfigManager.nailgunHeatsinkRegSpeedMulti.value != 1 || ConfigManager.sawHeatsinkRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<Nailgun>("Update"), prefix: GetHarmonyMethod(GetMethod<NailGun_Update>("Prefix"))); if(ConfigManager.staminaRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<NewMovement>("Update"), prefix: GetHarmonyMethod(GetMethod<NewMovement_Update>("Prefix"))); if(ConfigManager.playerHpDeltaToggle.value || ConfigManager.maxPlayerHp.value != 100 || ConfigManager.playerHpSupercharge.value != 200 || ConfigManager.whiplashHardDamageCap.value != 50 || ConfigManager.whiplashHardDamageSpeed.value != 1) { harmonyTweaks.Patch(GetMethod<NewMovement>("GetHealth"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHealth>("Prefix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("SuperCharge"), prefix: GetHarmonyMethod(GetMethod<NewMovement_SuperCharge>("Prefix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("Respawn"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Respawn>("Postfix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("Start"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Transpiler"))); harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), transpiler: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate>("Transpiler"))); harmonyTweaks.Patch(GetMethod<NewMovement>("ForceAntiHP"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_ForceAntiHP>("Transpiler"))); } // ADDME harmonyTweaks.Patch(GetMethod<Revolver>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Revolver_Shoot>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Shotgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Transpiler")), prefix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Postfix"))); harmonyTweaks.Patch(GetMethod<Shotgun>("ShootSinks"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_ShootSinks>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Nailgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_Shoot>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Nailgun>("SuperSaw"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_SuperSaw>("Transpiler"))); if (ConfigManager.hardDamagePercent.normalizedValue != 1) harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Prefix")), postfix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Postfix"))); harmonyTweaks.Patch(GetMethod<HealthBar>("Start"), postfix: GetHarmonyMethod(GetMethod<HealthBar_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<HealthBar>("Update"), transpiler: GetHarmonyMethod(GetMethod<HealthBar_Update>("Transpiler"))); foreach (HealthBarTracker hb in HealthBarTracker.instances) { if (hb != null) hb.SetSliderRange(); } harmonyTweaks.Patch(GetMethod<Harpoon>("Start"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Start>("Postfix"))); if(ConfigManager.screwDriverHomeToggle.value) harmonyTweaks.Patch(GetMethod<Harpoon>("Punched"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Punched>("Postfix"))); if(ConfigManager.screwDriverSplitToggle.value) harmonyTweaks.Patch(GetMethod<Harpoon>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<Harpoon_OnTriggerEnter_Patch>("Prefix"))); } private static void PatchAllMemes() { if (ConfigManager.enrageSfxToggle.value) harmonyTweaks.Patch(GetMethod<EnrageEffect>("Start"), postfix: GetHarmonyMethod(GetMethod<EnrageEffect_Start>("Postfix"))); if(ConfigManager.funnyDruidKnightSFXToggle.value) { harmonyTweaks.Patch(GetMethod<Mandalore>("FullBurst"), postfix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Postfix")), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<Mandalore>("FullerBurst"), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullerBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Explode"), prefix: GetHarmonyMethod(GetMethod<Drone_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Drone_Explode>("Postfix"))); } if (ConfigManager.fleshObamiumToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Prefix"))); if (ConfigManager.obamapticonToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Prefix"))); } public static bool methodsPatched = false; public static void ScenePatchCheck() { if(methodsPatched && !ultrapainDifficulty) { harmonyTweaks.UnpatchSelf(); methodsPatched = false; } else if(!methodsPatched && ultrapainDifficulty) { PatchAll(); } } public static void PatchAll() { harmonyTweaks.UnpatchSelf(); methodsPatched = false; if (!ultrapainDifficulty) return; if(realUltrapainDifficulty && ConfigManager.discordRichPresenceToggle.value) harmonyTweaks.Patch(GetMethod<DiscordController>("SendActivity"), prefix: GetHarmonyMethod(GetMethod<DiscordController_SendActivity_Patch>("Prefix"))); if (realUltrapainDifficulty && ConfigManager.steamRichPresenceToggle.value) harmonyTweaks.Patch(GetMethod<SteamFriends>("SetRichPresence"), prefix: GetHarmonyMethod(GetMethod<SteamFriends_SetRichPresence_Patch>("Prefix"))); PatchAllEnemies(); PatchAllPlayers(); PatchAllMemes(); methodsPatched = true; } public static string workingPath; public static string workingDir; public static AssetBundle bundle; public static AudioClip druidKnightFullAutoAud; public static AudioClip druidKnightFullerAutoAud; public static AudioClip druidKnightDeathAud; public static AudioClip enrageAudioCustom; public static GameObject fleshObamium; public static GameObject obamapticon; public void Awake() { instance = this; workingPath = Assembly.GetExecutingAssembly().Location; workingDir = Path.GetDirectoryName(workingPath); Logger.LogInfo($"Working path: {workingPath}, Working dir: {workingDir}"); try { bundle = AssetBundle.LoadFromFile(Path.Combine(workingDir, "ultrapain")); druidKnightFullAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullauto.wav"); druidKnightFullerAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullerauto.wav"); druidKnightDeathAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/death.wav"); enrageAudioCustom = bundle.LoadAsset<AudioClip>("assets/ultrapain/sfx/enraged.wav"); fleshObamium = bundle.LoadAsset<GameObject>("assets/ultrapain/fleshprison/fleshobamium.prefab"); obamapticon = bundle.LoadAsset<GameObject>("assets/ultrapain/panopticon/obamapticon.prefab"); } catch (Exception e) { Logger.LogError($"Could not load the asset bundle:\n{e}"); } // DEBUG /*string logPath = Path.Combine(Environment.CurrentDirectory, "log.txt"); Logger.LogInfo($"Saving to {logPath}"); List<string> assetPaths = new List<string>() { "fonts.bundle", "videos.bundle", "shaders.bundle", "particles.bundle", "materials.bundle", "animations.bundle", "prefabs.bundle", "physicsmaterials.bundle", "models.bundle", "textures.bundle", }; //using (FileStream log = File.Open(logPath, FileMode.OpenOrCreate, FileAccess.Write)) //{ foreach(string assetPath in assetPaths) { Logger.LogInfo($"Attempting to load {assetPath}"); AssetBundle bundle = AssetBundle.LoadFromFile(Path.Combine(bundlePath, assetPath)); bundles.Add(bundle); //foreach (string name in bundle.GetAllAssetNames()) //{ // string line = $"[{bundle.name}][{name}]\n"; // log.Write(Encoding.ASCII.GetBytes(line), 0, line.Length); //} bundle.LoadAllAssets(); } //} */ // Plugin startup logic Logger.LogInfo($"Plugin {PluginInfo.PLUGIN_GUID} is loaded!"); harmonyTweaks = new Harmony(PLUGIN_GUID + "_tweaks"); harmonyBase = new Harmony(PLUGIN_GUID + "_base"); harmonyBase.Patch(GetMethod<DifficultySelectButton>("SetDifficulty"), postfix: GetHarmonyMethod(GetMethod<DifficultySelectPatch>("Postfix"))); harmonyBase.Patch(GetMethod<DifficultyTitle>("Check"), postfix: GetHarmonyMethod(GetMethod<DifficultyTitle_Check_Patch>("Postfix"))); harmonyBase.Patch(typeof(PrefsManager).GetConstructor(new Type[0]), postfix: GetHarmonyMethod(GetMethod<PrefsManager_Ctor>("Postfix"))); harmonyBase.Patch(GetMethod<PrefsManager>("EnsureValid"), prefix: GetHarmonyMethod(GetMethod<PrefsManager_EnsureValid>("Prefix"))); harmonyBase.Patch(GetMethod<Grenade>("Explode"), prefix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Prefix")), postfix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Postfix"))); LoadPrefabs(); ConfigManager.Initialize(); SceneManager.activeSceneChanged += OnSceneChange; } } public static class Tools { private static Transform _target; private static Transform target { get { if(_target == null) _target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); return _target; } } public static Vector3 PredictPlayerPosition(float speedMod, Collider enemyCol = null) { Vector3 projectedPlayerPos; if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f) { return target.position; } RaycastHit raycastHit; if (enemyCol != null && Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == enemyCol) { projectedPlayerPos = target.position; } else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { projectedPlayerPos = raycastHit.point; } else { projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod; projectedPlayerPos = new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z); } return projectedPlayerPos; } } // Asset destroyer tracker /*[HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object) })] public class TempClass1 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object), typeof(float) })] public class TempClass2 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object) })] public class TempClass3 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object), typeof(bool) })] public class TempClass4 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } }*/ }
Ultrapain/Plugin.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static ConfigPanel leviathanPanel;\n public static ConfigPanel somethingWickedPanel;\n public static ConfigPanel panopticonPanel;\n public static ConfigPanel idolPanel;\n // GLOBAL ENEMY CONFIG\n public static BoolField friendlyFireDamageOverrideToggle;\n public static FloatSliderField friendlyFireDamageOverrideExplosion;\n public static FloatSliderField friendlyFireDamageOverrideProjectile;\n public static FloatSliderField friendlyFireDamageOverrideFire;\n public static FloatSliderField friendlyFireDamageOverrideMelee;", "score": 0.8622463345527649 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static ConfigPanel streetCleanerPanel;\n public static ConfigPanel swordsMachinePanel;\n public static ConfigPanel virtuePanel;\n public static ConfigPanel ferrymanPanel;\n public static ConfigPanel turretPanel;\n public static ConfigPanel fleshPrisonPanel;\n public static ConfigPanel minosPrimePanel;\n public static ConfigPanel v2FirstPanel;\n public static ConfigPanel v2SecondPanel;\n public static ConfigPanel sisyInstPanel;", "score": 0.8577820062637329 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static ConfigPanel cerberusPanel;\n public static ConfigPanel dronePanel;\n public static ConfigPanel filthPanel;\n public static ConfigPanel hideousMassPanel;\n public static ConfigPanel maliciousFacePanel;\n public static ConfigPanel mindflayerPanel;\n public static ConfigPanel schismPanel;\n public static ConfigPanel soliderPanel;\n public static ConfigPanel stalkerPanel;\n public static ConfigPanel strayPanel;", "score": 0.8510428667068481 }, { "filename": "Ultrapain/Patches/Virtue.cs", "retrieved_chunk": " }\n }\n class VirtueFlag : MonoBehaviour\n {\n public AudioSource lighningBoltSFX;\n public GameObject ligtningBoltAud;\n public Transform windupObj;\n private EnemyIdentifier eid;\n public Drone virtue;\n public void Awake()", "score": 0.8415250778198242 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " }\n // ROOT PANEL\n public static BoolField enemyTweakToggle;\n private static ConfigPanel enemyPanel;\n public static BoolField playerTweakToggle;\n private static ConfigPanel playerPanel;\n public static BoolField discordRichPresenceToggle;\n public static BoolField steamRichPresenceToggle;\n public static StringField pluginName;\n public static StringMultilineField pluginInfo;", "score": 0.8347936868667603 } ]
csharp
GameObject turretFinalFlash;
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ExpressionTree; using FindClosestString; using SyslogLogging; using Watson.ORM; namespace RosettaStone.Core.Services { public class VendorMetadataService { #region Public-Members #endregion #region Private-Members private LoggingModule _Logging = null; private WatsonORM _ORM = null; #endregion #region Constructors-and-Factories public VendorMetadataService(LoggingModule logging, WatsonORM orm) { _Logging = logging ?? throw new ArgumentNullException(nameof(logging)); _ORM = orm ?? throw new ArgumentNullException(nameof(orm)); } #endregion #region Public-Methods public List<VendorMetadata> All() { Expr expr = new Expr( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.Id)), OperatorEnum.GreaterThan, 0); expr.PrependAnd( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.IsAssigned)), OperatorEnum.Equals, 1); return _ORM.SelectMany<VendorMetadata>(expr); } public VendorMetadata GetByKey(string key) { if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key)); key = key.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.Key)), OperatorEnum.Equals, key); expr.PrependAnd( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.IsAssigned)), OperatorEnum.Equals, 1); return _ORM.SelectFirst<VendorMetadata>(expr); } public bool ExistsByKey(string key) { if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key)); key = key.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.Key)), OperatorEnum.Equals, key); expr.PrependAnd( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.IsAssigned)), OperatorEnum.Equals, 1); return _ORM.Exists<VendorMetadata>(expr); } public VendorMetadata GetByGuid(string guid) { if (String.IsNullOrEmpty(guid)) throw new ArgumentNullException(nameof(guid)); guid = guid.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.GUID)), OperatorEnum.Equals, guid); expr.PrependAnd( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.IsAssigned)), OperatorEnum.Equals, 1); return _ORM.SelectFirst<VendorMetadata>(expr); } public bool ExistsByGuid(string guid) { if (String.IsNullOrEmpty(guid)) throw new ArgumentNullException(nameof(guid)); guid = guid.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.GUID)), OperatorEnum.Equals, guid); expr.PrependAnd( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.IsAssigned)), OperatorEnum.Equals, 1); return _ORM.Exists<VendorMetadata>(expr); } public List<
VendorMetadata> Search(Expr expr, int startIndex = 0, int maxResults = 1000) {
if (expr == null) throw new ArgumentNullException(nameof(expr)); if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex)); if (maxResults > 1000) throw new ArgumentOutOfRangeException(nameof(maxResults)); return _ORM.SelectMany<VendorMetadata>(startIndex, maxResults, expr); } public VendorMetadata Add(VendorMetadata vm) { if (vm == null) throw new ArgumentNullException(nameof(vm)); if (ExistsByGuid(vm.GUID)) throw new ArgumentException("Object with GUID '" + vm.GUID + "' already exists."); if (ExistsByKey(vm.Key)) throw new ArgumentException("Object with key '" + vm.Key + "' already exists."); vm.Key = vm.Key.ToUpper(); vm.GUID = vm.GUID.ToUpper(); return _ORM.Insert<VendorMetadata>(vm); } public VendorMetadata Update(VendorMetadata vm) { if (vm == null) throw new ArgumentNullException(nameof(vm)); vm.Key = vm.Key.ToUpper(); vm.GUID = vm.GUID.ToUpper(); return _ORM.Update<VendorMetadata>(vm); } public void DeleteByGuid(string guid) { if (String.IsNullOrEmpty(guid)) throw new ArgumentNullException(nameof(guid)); guid = guid.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.GUID)), OperatorEnum.Equals, guid ); _ORM.DeleteMany<VendorMetadata>(expr); } public void DeleteByKey(string key) { if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key)); key = key.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.Key)), OperatorEnum.Equals, key ); _ORM.DeleteMany<VendorMetadata>(expr); } public VendorMetadata FindClosestMatch(string key) { if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key)); key = key.ToUpper(); List<VendorMetadata> all = All(); List<string> keys = all.Where(x => x.IsAssigned).Select(x => x.Key).ToList(); (string, int) result = ClosestString.UsingLevenshtein(key, keys); VendorMetadata vendor = GetByKey(result.Item1); vendor.EditDistance = result.Item2; return vendor; } public List<VendorMetadata> FindClosestMatches(string key, int maxResults = 10) { if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key)); if (maxResults < 1 || maxResults > 10) throw new ArgumentOutOfRangeException(nameof(maxResults)); key = key.ToUpper(); List<VendorMetadata> all = All(); List<string> keys = all.Where(x => x.IsAssigned).Select(x => x.Key).ToList(); List<(string, int)> result = ClosestStrings.UsingLevenshtein(key, keys, maxResults); List<VendorMetadata> ret = new List<VendorMetadata>(); foreach ((string, int) item in result) { VendorMetadata vendor = GetByKey(item.Item1); vendor.EditDistance = item.Item2; ret.Add(vendor); } return ret; } #endregion #region Private-Methods #endregion } }
src/RosettaStone.Core/Services/VendorMetadataService.cs
jchristn-RosettaStone-898982c
[ { "filename": "src/RosettaStone.Core/Services/CodecMetadataService.cs", "retrieved_chunk": " vendorGuid = vendorGuid.ToUpper();\n Expr expr = new Expr(\n _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.VendorGUID)),\n OperatorEnum.Equals,\n vendorGuid\n );\n _ORM.DeleteMany<CodecMetadata>(expr);\n }\n public CodecMetadata FindClosestMatch(string key)\n {", "score": 0.8869261145591736 }, { "filename": "src/RosettaStone.Core/Services/CodecMetadataService.cs", "retrieved_chunk": " OperatorEnum.Equals,\n key);\n expr.PrependAnd(\n _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.IsAssigned)),\n OperatorEnum.Equals,\n 1);\n return _ORM.SelectFirst<CodecMetadata>(expr);\n }\n public bool ExistsByKey(string key)\n {", "score": 0.8711757063865662 }, { "filename": "src/RosettaStone.Core/Services/CodecMetadataService.cs", "retrieved_chunk": " Expr expr = new Expr(\n _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.Key)),\n OperatorEnum.Equals,\n key\n );\n _ORM.DeleteMany<CodecMetadata>(expr);\n }\n public void DeleteByVendorGuid(string vendorGuid)\n {\n if (String.IsNullOrEmpty(vendorGuid)) throw new ArgumentNullException(nameof(vendorGuid));", "score": 0.8545903563499451 }, { "filename": "src/RosettaStone.Core/Services/CodecMetadataService.cs", "retrieved_chunk": " Expr expr = new Expr(\n _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.Id)),\n OperatorEnum.GreaterThan,\n 0);\n expr.PrependAnd(\n _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.IsAssigned)),\n OperatorEnum.Equals,\n 1);\n return _ORM.SelectMany<CodecMetadata>(expr);\n }", "score": 0.8383933305740356 }, { "filename": "src/RosettaStone.Core/Services/CodecMetadataService.cs", "retrieved_chunk": " expr.PrependAnd(\n _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.IsAssigned)),\n OperatorEnum.Equals,\n 1);\n return _ORM.SelectFirst<CodecMetadata>(expr);\n }\n public bool ExistsByGuid(string guid)\n {\n if (String.IsNullOrEmpty(guid)) throw new ArgumentNullException(nameof(guid));\n guid = guid.ToUpper();", "score": 0.831608772277832 } ]
csharp
VendorMetadata> Search(Expr expr, int startIndex = 0, int maxResults = 1000) {
/* * Copyright (C) Antony Vitillo (aka Skarredghost), Perpetual eMotion 2023. * Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT). */ using RoslynCSharp; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using UnityEngine; using vrroom.Dynaimic.Ai; using vrroom.Dynaimic.GenerativeLogic; namespace vrroom.CubicMusic.CubesMgmt { /// <summary> /// Main class of the CubicMusic system. It manages the creation and destruction of the cubes and the logic attached to them /// </summary> [DefaultExecutionOrder(-1)] public class CubesManager : MonoBehaviour, ICreatesLogicFromPrompt { /// <summary> /// The prompt template to generate Unity scripts that can be added to the cubes at runtime without requiring /// the setup of public properties. Scripts should work out of the bo /// </summary> static readonly AiPromptTemplate s_promptTemplateForUnityScripts = new AiPromptTemplate() { PrePrompt = @"Generate a Unity C# script with internally initialized properties that does the following to the gameobject: ", PostPrompt = @"The script should work out of the box without requiring any external configuration. Here are the requirements: - The script can NOT include public properties. - The properties should be initialized internally within the script, in the start method. - If the property is a prefab, initialize it with a primitive, in the start method. - The properties should not be modifiable from external sources. - The script should include any necessary logic or code that utilizes these properties. - IF and only if the query is about the microphone, you can use vrroom.CubicMusic.Audio.AudioManager.Instance.MicrophoneAnalyzer.CurrentVolume property, range from 0 to 1. - IF and only if the query is about the music, you can use vrroom.CubicMusic.Audio.AudioManager.Instance.BackgroundMusicAnalyzer.CurrentVolume, range from 0 to 1. - IF and only if the gameobject has to interact the hand, the hand can be found as a trigger collider on the Hand layer. Ignore this if the hand is not involved in the query. Please generate the Unity script meeting these specifications." }; /// <summary> /// The prefab to use for the cubes to generate. If null, a default cube will be used /// </summary> [SerializeField] public GameObject CubePrefab; /// <summary> /// The assemblies that the generated scripts will reference /// </summary> [SerializeField] private AssemblyReferenceAsset[] m_referenceAssemblies; /// <summary> /// The element that performs the queries to the AI cloud /// </summary> private AiQueryPerformer m_aiQueryPerformer; /// <summary> /// The element that creates the logic from the AI prompts /// </summary> private
GenerativeLogicManager m_generativeLogicManager;
/// <summary> /// The list of cube groups managed by this object. /// Every group contains a list of cubes to which logic can be added at runtime /// </summary> private List<ObjectsGroupLogicHandler> m_managedCubeGroups; /// <inheritdoc /> public AiPromptTemplate PromptTemplate => s_promptTemplateForUnityScripts; /// <summary> /// Get the element that performs the queries to the AI cloud /// </summary> public AiQueryPerformer AiQueryPerformer => m_aiQueryPerformer; /// <summary> /// Singleton instance /// </summary> public static CubesManager Instance; /// <summary> /// Awake /// </summary> private void Awake() { //destroy this object if another instance already exists if(Instance != null && Instance != this) { Destroy(this); return; } //else we are the singleton instance else { Instance = this; //initialize a few things m_managedCubeGroups = new List<ObjectsGroupLogicHandler>(1); m_managedCubeGroups.Add(new ObjectsGroupLogicHandler()); //creates the first group m_aiQueryPerformer = new OpenAiQueryPerformer(); m_generativeLogicManager = new GenerativeLogicManager(m_aiQueryPerformer, new AiGenerationParameters(), m_referenceAssemblies); Debug.Log("[Cubes Manager] Initialized"); } } /// <summary> /// Adds a cube at the specified position, rotation and scale to the current managed group /// </summary> /// <param name="position">Position</param> /// <param name="rotation">Rotation</param> /// <param name="scale">Local scale</param> public void AddCubeToCurrentGroup(Vector3 position, Quaternion rotation, Vector3 scale) { GameObject cube = GenerateCube(); cube.transform.position = position; cube.transform.rotation = rotation; cube.transform.localScale = scale; m_managedCubeGroups[0].AddObjectToCurrentGroup(cube); Debug.Log($"[Cubes Manager] New cube added to the group. Number of cubes is now {m_managedCubeGroups[0].Count}"); } /// <inheritdoc /> public async Task GenerateLogicForGroupFromAudio(AudioClip audioPrompt, CancellationToken cancellationToken = default) { Debug.Log($"[Cubes Manager] Requested logic from audio prompt"); var script = await m_generativeLogicManager.GenerateLogicFromAudio(audioPrompt, s_promptTemplateForUnityScripts, cancellationToken); Debug.Log($"[Cubes Manager] Script generated from audio is called {script.FullName}"); AttachScriptToGroup(script); } /// <inheritdoc /> public async Task GenerateLogicForGroupFromText(string prompt, CancellationToken cancellationToken = default) { Debug.Log($"[Cubes Manager] Requested logic from text prompt"); ScriptType script = null; int tries = 0; do { script = await m_generativeLogicManager.GenerateLogicFromText(prompt, s_promptTemplateForUnityScripts, cancellationToken); if (script != null) //in case of error, the script is null { Debug.Log($"[Cubes Manager] Script generated from text is called {script.FullName}"); AttachScriptToGroup(script); } } while (script == null && ++tries < 3); //if a script fails, try again a few times } /// <summary> /// Generates a cube /// </summary> /// <returns>Generated cube</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] private GameObject GenerateCube() { if (CubePrefab == null) { return GameObject.CreatePrimitive(PrimitiveType.Cube); } else { return Object.Instantiate(CubePrefab); } } /// <summary> /// Attaches the specified script to the current group. /// After this, a new group is created and becomes the current group /// </summary> /// <param name="script">Script that has been generated</param> private void AttachScriptToGroup(ScriptType script) { m_managedCubeGroups[0].AttachLogicToGroupElements(script); m_managedCubeGroups.Insert(0, new ObjectsGroupLogicHandler()); } } }
CubicMusic/Assets/_CubicMusic/Runtime/CubesManagement/Scripts/CubesManager.cs
Perpetual-eMotion-DynaimicApps-46c94e0
[ { "filename": "CubicMusic/Assets/_CubicMusic/Runtime/CubesManagement/Scripts/EmotionalCubesGenerator.cs", "retrieved_chunk": " PostPrompt = @\"\"\" .Please generate the prompts only that are coherent with this mood. Write No examples, no explanations.\"\n };\n /// <summary>\n /// The element that performs the queries to the AI cloud\n /// </summary>\n private AiQueryPerformer m_aiQueryPerformer;\n /// <summary>\n /// Ai completion parameters\n /// </summary>\n private AiGenerationParameters m_aiParameters;", "score": 0.9250468015670776 }, { "filename": "CubicMusic/Assets/_DynaimicLogic/Runtime/GenerativeLogic/GenerativeLogicManager.cs", "retrieved_chunk": " /// The element that performs the queries to the AI cloud\n /// </summary>\n private AiQueryPerformer m_aiQueryPerformer;\n /// <summary>\n /// Parameters for the completion queries. We use always the same parameters for all the queries\n /// </summary>\n private AiGenerationParameters m_aiParameters;\n /// <summary>\n /// Runtime domain where the generated scripts will be loaded\n /// </summary>", "score": 0.9215472936630249 }, { "filename": "CubicMusic/Assets/_CubicMusic/Runtime/UI/Scripts/UserQueryCreationCanvas.cs", "retrieved_chunk": " /// </summary>\n [SerializeField]\n private MonoBehaviour m_logicFromQueriesGeneratorBehaviour;\n /// <summary>\n /// Element to be notified of the queries so that can generate logic\n /// </summary>\n private ICreatesLogicFromPrompt m_logicFromPromptCreator;\n /// <summary>\n /// Cancellation token\n /// </summary>", "score": 0.9032858610153198 }, { "filename": "CubicMusic/Assets/_DynaimicLogic/Runtime/GenerativeLogic/GenerativeLogicManager.cs", "retrieved_chunk": " private ScriptDomain m_scriptsDomain;\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"aiQueryPerformer\">Element that performs the queries to the AI backend</param>\n /// <param name=\"aiParameters\">Parameters for the completion queries. We use the same for all queries for simplicity</param>\n /// <param name=\"referenceAssets\">The assemblies that are the references of the scripts being generated</param>\n public GenerativeLogicManager(AiQueryPerformer aiQueryPerformer, AiGenerationParameters aiParameters, AssemblyReferenceAsset[] referenceAssets)\n {\n //create the runtime domain where the scripts will be loaded and add the references", "score": 0.8888916969299316 }, { "filename": "CubicMusic/Assets/_CubicMusic/Runtime/UI/Scripts/AiStatusCanvas.cs", "retrieved_chunk": " private TMP_Text m_promptResponseText;\n /// <summary>\n /// The coroutine that shows the progress of the AI operations\n /// </summary>\n private Coroutine m_progressCoroutine = default;\n /// <summary>\n /// On Enable\n /// </summary>\n private void OnEnable()\n {", "score": 0.8857779502868652 } ]
csharp
GenerativeLogicManager m_generativeLogicManager;
using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UIElements; using UnityEditor.UIElements; using UnityEditor.Experimental.GraphView; using UnityEditor; using UnityEngine.Windows; using System; namespace QuestSystem.QuestEditor { public class QuestGraphSaveUtility { private QuestGraphView _targetGraphView; private List<Edge> Edges => _targetGraphView.edges.ToList(); private List<NodeQuestGraph> node => _targetGraphView.nodes.ToList().Cast<NodeQuestGraph>().ToList(); private List<NodeQuest> _cacheNodes = new List<NodeQuest>(); public static QuestGraphSaveUtility GetInstance(QuestGraphView targetGraphView) { return new QuestGraphSaveUtility { _targetGraphView = targetGraphView, }; } private void creteNodeQuestAssets(Quest Q, ref List<NodeQuest> NodesInGraph) { int j = 0; CheckFolders(Q); string path = QuestConstants.MISIONS_FOLDER + $"/{Q.misionName}/Nodes"; string tempPath = QuestConstants.MISIONS_FOLDER + $"/{Q.misionName}/Temp"; //Move all nodes OUT to temp if (AssetDatabase.IsValidFolder(path)) { AssetDatabase.CreateFolder(QuestConstants.MISIONS_FOLDER + $"{Q.misionName}", "Temp"); var debug = AssetDatabase.MoveAsset(path, tempPath); } Debug.Log("GUID: " + AssetDatabase.CreateFolder(QuestConstants.MISIONS_FOLDER + $"/{Q.misionName}", "Nodes")); //Order by position List<NodeQuestGraph> nodeList = node.Where(node => !node.entryPoint).ToList(); foreach (var nodequest in nodeList) { //Visual part string nodeSaveName = Q.misionName + "_Node" + j; NodeQuest saveNode; //Si existe en temps bool alredyExists = false; if (alredyExists = !string.IsNullOrEmpty(AssetDatabase.AssetPathToGUID(tempPath + "/" + nodeSaveName + ".asset"))) { saveNode = AssetDatabase.LoadAssetAtPath<NodeQuest>(tempPath + "/" + nodeSaveName + ".asset"); } else { saveNode = ScriptableObject.CreateInstance<NodeQuest>(); } saveNode.GUID = nodequest.GUID; saveNode.position = nodequest.GetPosition().position; //Quest Part saveNode.isFinal = nodequest.isFinal; saveNode.extraText = nodequest.extraText; saveNode.nodeObjectives = createObjectivesFromGraph(nodequest.questObjectives); if(!alredyExists) AssetDatabase.CreateAsset(saveNode, $"{QuestConstants.MISIONS_FOLDER}/{Q.misionName}/Nodes/{nodeSaveName}.asset"); else { AssetDatabase.MoveAsset(tempPath + "/" + nodeSaveName + ".asset", path + "/" + nodeSaveName + ".asset"); } EditorUtility.SetDirty(saveNode); AssetDatabase.SaveAssets(); NodesInGraph.Add(saveNode); j++; } AssetDatabase.DeleteAsset(tempPath); } public void CheckFolders(Quest Q) { if (!AssetDatabase.IsValidFolder(QuestConstants.RESOURCES_PATH)) { AssetDatabase.CreateFolder(QuestConstants.PARENT_PATH, QuestConstants.RESOURCES_NAME); } if (!AssetDatabase.IsValidFolder(QuestConstants.MISIONS_FOLDER)) { AssetDatabase.CreateFolder(QuestConstants.RESOURCES_PATH, QuestConstants.MISIONS_NAME); } if (!AssetDatabase.IsValidFolder(QuestConstants.MISIONS_FOLDER + $"/{Q.misionName}")) { AssetDatabase.CreateFolder(QuestConstants.MISIONS_FOLDER, $"{Q.misionName}"); } } private void saveConections(Quest Q, List<
NodeQuest> nodesInGraph) {
var connectedPorts = Edges.Where(x => x.input.node != null).ToArray(); Q.ResetNodeLinksGraph(); foreach (NodeQuest currentNode in nodesInGraph) { currentNode.nextNode.Clear(); } for (int i = 0; i < connectedPorts.Length; i++) { var outputNode = connectedPorts[i].output.node as NodeQuestGraph; var inputNode = connectedPorts[i].input.node as NodeQuestGraph; Q.nodeLinkData.Add(new Quest.NodeLinksGraph { baseNodeGUID = outputNode.GUID, portName = connectedPorts[i].output.portName, targetNodeGUID = inputNode.GUID }); //Add to next node list NodeQuest baseNode = nodesInGraph.Find(n => n.GUID == outputNode.GUID); NodeQuest targetNode = nodesInGraph.Find(n => n.GUID == inputNode.GUID); if (targetNode != null && baseNode != null) baseNode.nextNode.Add(targetNode); } } public void SaveGraph(Quest Q) { if (!Edges.Any()) return; List<NodeQuest> NodesInGraph = new List<NodeQuest>(); // Nodes creteNodeQuestAssets(Q, ref NodesInGraph); // Conections saveConections(Q, NodesInGraph); //Last Quest parameters var startNode = node.Find(node => node.entryPoint); //Find the first node Graph Q.startDay = startNode.startDay; Q.limitDay = startNode.limitDay; Q.isMain = startNode.isMain; //Questionable var firstMisionNode = Edges.Find(x => x.output.portName == "Next"); var firstMisionNode2 = firstMisionNode.input.node as NodeQuestGraph; string GUIDfirst = firstMisionNode2.GUID; Q.firtsNode = NodesInGraph.Find(n => n.GUID == GUIDfirst); EditorUtility.SetDirty(Q); } public void LoadGraph(Quest Q) { if (Q == null) { EditorUtility.DisplayDialog("Error!!", "Quest aprece como null, revisa el scriptable object", "OK"); return; } NodeQuest[] getNodes = Resources.LoadAll<NodeQuest>($"{QuestConstants.MISIONS_NAME}/{ Q.misionName}/Nodes"); _cacheNodes = new List<NodeQuest>(getNodes); clearGraph(Q); LoadNodes(Q); ConectNodes(Q); } private void clearGraph(Quest Q) { node.Find(x => x.entryPoint).GUID = Q.nodeLinkData[0].baseNodeGUID; foreach (var node in node) { if (node.entryPoint) { var aux = node.mainContainer.Children().ToList(); var aux2 = aux[2].Children().ToList(); // C TextField misionName = aux2[0] as TextField; Toggle isMain = aux2[1] as Toggle; IntegerField startDay = aux2[2] as IntegerField; IntegerField limitDay = aux2[3] as IntegerField; misionName.value = Q.misionName; isMain.value = Q.isMain; startDay.value = Q.startDay; limitDay.value = Q.limitDay; // node.limitDay = Q.limitDay; node.startDay = Q.startDay; node.isMain = Q.isMain; node.misionName = Q.misionName; continue; } //Remove edges Edges.Where(x => x.input.node == node).ToList().ForEach(edge => _targetGraphView.RemoveElement(edge)); //Remove Node _targetGraphView.RemoveElement(node); } } private void LoadNodes(Quest Q) { foreach (var node in _cacheNodes) { var tempNode = _targetGraphView.CreateNodeQuest(node.name, Vector2.zero, node.extraText, node.isFinal); //Load node variables tempNode.GUID = node.GUID; tempNode.extraText = node.extraText; tempNode.isFinal = node.isFinal; tempNode.RefreshPorts(); if (node.nodeObjectives != null) { foreach (QuestObjective qObjective in node.nodeObjectives) { //CreateObjectives QuestObjectiveGraph objtemp = new QuestObjectiveGraph(qObjective.keyName, qObjective.maxItems, qObjective.actualItems, qObjective.description, qObjective.hiddenObjective, qObjective.autoExitOnCompleted); var deleteButton = new Button(clickEvent: () => _targetGraphView.removeQuestObjective(tempNode, objtemp)) { text = "x" }; objtemp.Add(deleteButton); var newBox = new Box(); objtemp.Add(newBox); objtemp.actualItems = qObjective.actualItems; objtemp.description = qObjective.description; objtemp.maxItems = qObjective.maxItems; objtemp.keyName = qObjective.keyName; objtemp.hiddenObjective = qObjective.hiddenObjective; objtemp.autoExitOnCompleted = qObjective.autoExitOnCompleted; tempNode.objectivesRef.Add(objtemp); tempNode.questObjectives.Add(objtemp); } } _targetGraphView.AddElement(tempNode); var nodePorts = Q.nodeLinkData.Where(x => x.baseNodeGUID == node.GUID).ToList(); nodePorts.ForEach(x => _targetGraphView.AddNextNodePort(tempNode)); } } private void ConectNodes(Quest Q) { List<NodeQuestGraph> nodeListCopy = new List<NodeQuestGraph>(node); for (int i = 0; i < nodeListCopy.Count; i++) { var conections = Q.nodeLinkData.Where(x => x.baseNodeGUID == nodeListCopy[i].GUID).ToList(); for (int j = 0; j < conections.Count(); j++) { string targetNodeGUID = conections[j].targetNodeGUID; var targetNode = nodeListCopy.Find(x => x.GUID == targetNodeGUID); LinkNodes(nodeListCopy[i].outputContainer[j].Q<Port>(), (Port)targetNode.inputContainer[0]); targetNode.SetPosition(new Rect(_cacheNodes.First(x => x.GUID == targetNodeGUID).position, new Vector2(150, 200))); } } } private void LinkNodes(Port outpor, Port inport) { var tempEdge = new Edge { output = outpor, input = inport }; tempEdge.input.Connect(tempEdge); tempEdge.output.Connect(tempEdge); _targetGraphView.Add(tempEdge); } public QuestObjective[] createObjectivesFromGraph(List<QuestObjectiveGraph> qog) { List<QuestObjective> Listaux = new List<QuestObjective>(); foreach (QuestObjectiveGraph obj in qog) { QuestObjective aux = new QuestObjective { keyName = obj.keyName, maxItems = obj.maxItems, actualItems = obj.actualItems, description = obj.description, hiddenObjective = obj.hiddenObjective, autoExitOnCompleted = obj.autoExitOnCompleted }; Listaux.Add(aux); } return Listaux.ToArray(); } } }
Editor/GraphEditor/QuestGraphSaveUtility.cs
lluispalerm-QuestSystem-cd836cc
[ { "filename": "Runtime/QuestManager.cs", "retrieved_chunk": " if (misionLog == null)\n {\n // crear\n misionLog = ScriptableObject.CreateInstance<QuestLog>();\n#if UNITY_EDITOR\n AssetDatabase.CreateAsset(misionLog, QuestConstants.RESOURCES_PATH + \"/\" + QuestConstants.QUEST_LOG_NAME + \".asset\");\n#endif\n }\n QuestLogSaveData aux = QuestSaveSystem.Load(QuestConstants.SAVE_FILE_PATH) as QuestLogSaveData;\n if (aux == null) Debug.Log(\"No file to load in \" + aux);", "score": 0.7750852108001709 }, { "filename": "Editor/GraphEditor/QuestGraphEditor.cs", "retrieved_chunk": " NodeQuestGraph entryNode = _questGraph.GetEntryPointNode();\n newQuest.misionName = entryNode.misionName;\n newQuest.isMain = entryNode.isMain;\n newQuest.startDay = entryNode.startDay;\n newQuest.limitDay = entryNode.limitDay;\n questForGraph = newQuest;\n var saveUtility = QuestGraphSaveUtility.GetInstance(_questGraph);\n saveUtility.CheckFolders(questForGraph);\n AssetDatabase.CreateAsset(newQuest, $\"{QuestConstants.MISIONS_FOLDER}/{newQuest.misionName}/{newQuest.misionName}.asset\");\n //saveUtility.LoadGraph(questForGraph);", "score": 0.7686747312545776 }, { "filename": "Runtime/QuestLog.cs", "retrieved_chunk": " foreach (QuestSaveData qs in qls.failedQuestSave)\n {\n Quest q = Resources.Load(QuestConstants.MISIONS_NAME + \"/\" + qs.name + \"/\" + qs.name) as Quest;\n failedQuest.Add(q);\n }\n }\n public void RemoveQuest(Quest q)\n {\n if (IsCurrent(q))\n curentQuests.Remove(q);", "score": 0.7204978466033936 }, { "filename": "Runtime/Quest.cs", "retrieved_chunk": " nodeActual = null;\n NodeQuest[] getNodes = Resources.LoadAll<NodeQuest>($\"{QuestConstants.MISIONS_NAME}/{ this.misionName}/Nodes\");\n foreach (NodeQuest n in getNodes)\n {\n for (int i = 0; i < n.nodeObjectives.Length; i++)\n {\n n.nodeObjectives[i].isCompleted = false;\n n.nodeObjectives[i].actualItems = 0;\n }\n#if UNITY_EDITOR", "score": 0.717403769493103 }, { "filename": "Runtime/QuestOnObjectWorld.cs", "retrieved_chunk": " {\n string path = $\"{QuestConstants.MISIONS_NAME}/{objectsForQuestTable[i].quest.misionName}/{QuestConstants.NODES_FOLDER_NAME}\";\n NodeQuest[] nodesFromQuest = Resources.LoadAll<NodeQuest>(path);\n if (nodesFromQuest != null && nodesFromQuest.Length > 0)\n {\n ActivationRowNode[] tableNodes = new ActivationRowNode[nodesFromQuest.Length]; \n for (int j = 0; j < tableNodes.Length; j++)\n {\n tableNodes[j].node = nodesFromQuest[j];\n }", "score": 0.7108650207519531 } ]
csharp
NodeQuest> nodesInGraph) {
using Moadian.API; using Moadian.Dto; using Moadian.Services; using Newtonsoft.Json.Linq; namespace Moadian { public class Moadian { private
TokenModel token;
protected readonly string publicKey; protected readonly string privateKey; protected readonly string orgKeyId; protected readonly string username; protected readonly string baseURL; protected readonly HttpClientService httpClient; public Moadian(string publicKey, string privateKey, string orgKeyId, string username, string baseURL = "https://tp.tax.gov.ir") { this.PublicKey = publicKey; this.PrivateKey = privateKey; this.OrgKeyId = orgKeyId; this.Username = username; this.BaseURL = baseURL; var signatureService = new SignatureService(PrivateKey); var encryptionService = new EncryptionService(publicKey, orgKeyId); this.httpClient = new HttpClientService(signatureService, encryptionService, baseURL); } public string PublicKey { get; } public string PrivateKey { get; } public string OrgKeyId { get; } public string Username { get; } public string BaseURL { get; } public Moadian SetToken(TokenModel token) { this.token = token; return this; } public async Task<object> SendInvoice(Packet packet) { if (this.token == null) { throw new ArgumentException("Set token before sending invoice!"); } var headers = new Dictionary<string, string> { { "Authorization", "Bearer " + this.token.Token }, { "requestTraceId", Guid.NewGuid().ToString() }, { "timestamp", DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString() }, }; var path = "req/api/self-tsp/async/normal-enqueue"; var response = await httpClient.SendPackets(path, new List<Packet>() { packet }, headers, true, true); return response; } public async Task<TokenModel> GetToken() { var api = new Api(this.Username, httpClient); var token = await api.GetToken(); return token; } public string GenerateTaxId(DateTime invoiceCreatedAt, int internalInvoiceId) { var invoiceIdService = new InvoiceIdService(this.Username); return invoiceIdService.GenerateInvoiceId(invoiceCreatedAt, internalInvoiceId); } public async Task<dynamic> InquiryByReferenceNumber(string referenceNumber) { var api = new Api(this.Username, httpClient); api.SetToken(this.token); var response = await api.InquiryByReferenceNumber(referenceNumber); return response; } public async Task<dynamic> GetEconomicCodeInformation(string taxID) { var api = new Api(this.Username, httpClient); api.SetToken(this.token); var response = await api.GetEconomicCodeInformation(taxID); return response; } public object GetFiscalInfo() { var api = new Api(this.username, httpClient); api.SetToken(this.token); return api.GetFiscalInfo(); } } }
Moadian.cs
Torabi-srh-Moadian-482c806
[ { "filename": "Dto/TokenModel.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Moadian.Dto\n{\n public class TokenModel\n {\n public TokenModel(string token, int expiresAt)", "score": 0.8432927131652832 }, { "filename": "Dto/InvoiceBodyDto.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Moadian.Dto\n{\n public class InvoiceBodyDto : PrimitiveDto\n {\n // service stuff ID", "score": 0.8277842402458191 }, { "filename": "Dto/InvoicePaymentDto.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Moadian.Dto\n{\n public class InvoicePaymentDto : PrimitiveDto\n {\n private string? iinn;", "score": 0.8270689249038696 }, { "filename": "Services/SimpleNormalizer.cs", "retrieved_chunk": "using Moadian.Constants;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Moadian.Services\n{\n public static class SimpleNormalizer\n {", "score": 0.8200399875640869 }, { "filename": "Services/Normalizer.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Moadian.Services\n{\n public static class Normalizer\n {\n public static string NormalizeArray(Dictionary<string, object> data)", "score": 0.8123325109481812 } ]
csharp
TokenModel token;
using Microsoft.EntityFrameworkCore; using Ryan.EntityFrameworkCore.Builder; using Ryan.Models; using System.Collections.Generic; namespace Ryan.EntityFrameworkCore.ModelBuilders { public class MEntityModelBuilder : EntityModelBuilder<M> { public override void Build<TImplementation>(ModelBuilder modelBuilder, string tableName) { modelBuilder.Entity<TImplementation>(b => { b.ToTable(tableName).HasKey(x => x.Id).IsClustered(false); b.Property(x => x.Id).ValueGeneratedOnAdd(); b.Property(x => x.Year).IsRequired(); b.Property(x => x.Name).IsRequired().HasMaxLength(50); }); } public override string GetTableName(Dictionary<string, string> value) { return $"M_{value["Year"]}"; } protected override void
EntityConfiguration() {
Apply(x => x.Year); } } }
test/Ryan.EntityFrameworkCore.Shard.Tests/EntityFrameworkCore/ModelBuilders/MEntityModelBuilder.cs
c-y-r-Ryan.EntityFrameworkCore.Shard-f15124c
[ { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityModelBuilder.cs", "retrieved_chunk": " /// <inheritdoc/>\n public virtual IEnumerable<EntityExpressionVisitor> GetExpressionVisitors()\n {\n return Visitors.Select(x => x());\n }\n /// <inheritdoc/>\n public abstract string GetTableName(Dictionary<string, string> value);\n /// <summary>\n /// 构建 <typeparamref name=\"TImplementation\"/> 类型 Model\n /// </summary>", "score": 0.8324901461601257 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityImplementationDictionaryGenerator.cs", "retrieved_chunk": " /// </summary>\n public IMemoryCache MemoryCache { get; }\n /// <inheritdoc/>\n public EntityImplementationDictionaryGenerator()\n {\n MemoryCache = new InternalMemoryCache();\n }\n /// <inheritdoc/>\n public virtual EntityImplementationDictionary Create(Type entityType)\n {", "score": 0.8105542659759521 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityImplementation.cs", "retrieved_chunk": " /// <summary>\n /// 创建实体实现\n /// </summary>\n public EntityImplementation(Type entityType, Type implementationType, string tableName)\n {\n EntityType = entityType;\n ImplementationType = implementationType;\n TableName = tableName;\n }\n }", "score": 0.7971760034561157 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Expressions/EntityExpressionVisitor`.cs", "retrieved_chunk": " /// <inheritdoc/>\n public override void Visit(object entity)\n {\n var func = LambdaCache<TValue>.GetFunc(LambdaExpression);\n AddExpressionValue(func(entity));\n }\n /// <inheritdoc/>\n protected override bool VisitBinaryMemberEqualConstant(MemberExpression memberExpression, ConstantExpression constantExpression)\n {\n if (memberExpression.Member != MemberExpression.Member)", "score": 0.7842105627059937 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityImplementationDictionaryGenerator.cs", "retrieved_chunk": " return (MemoryCache.GetOrCreate(entityType, (entry) =>\n {\n return entry.SetSize(1).SetValue(\n new EntityImplementationDictionary(entityType)\n ).Value;\n }) as EntityImplementationDictionary)!;\n }\n }\n}", "score": 0.7822287082672119 } ]
csharp
EntityConfiguration() {
using Microsoft.Extensions.DependencyInjection; using Nebula.Caching.InMemory.Extensions.InMemoryExtensions; using Nebula.Caching.InMemory.Extensions.InterceptorExtensions; using Nebula.Caching.InMemory.Extensions.ManagerExtensions; using Nebula.Caching.InMemory.Settings; using Nebula.Caching.InMemory.UtilsExtensions; namespace Nebula.Caching.InMemory.Extensions { public static class Extensions { public static IServiceCollection AddInMemoryChache(this IServiceCollection services,
InMemoryConfigurations configs = null) {
return services .AddInMemoryInterceptor() .AddInMemoryExtensions(configs) .AddManagerExtensions() .AddUtilsExtensions(); } } }
src/Nebula.Caching.InMemory/Extensions/Extensions.cs
Nebula-Software-Systems-Nebula.Caching-1f3bb62
[ { "filename": "src/Nebula.Caching.InMemory/Extensions/InMemoryExtensions/InMemoryExtensions.cs", "retrieved_chunk": "using Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.DependencyInjection;\nusing Nebula.Caching.Common.Constants;\nusing Nebula.Caching.InMemory.Settings;\nnamespace Nebula.Caching.InMemory.Extensions.InMemoryExtensions\n{\n public static class InMemoryExtensions\n {\n public static IServiceCollection AddInMemoryExtensions(this IServiceCollection services, InMemoryConfigurations inMemoryConfigs)\n {", "score": 0.964521050453186 }, { "filename": "src/Nebula.Caching.InMemory/Extensions/InterceptorExtensions/InterceptorExtensions.cs", "retrieved_chunk": "using AspectCore.Configuration;\nusing AspectCore.Extensions.DependencyInjection;\nusing Microsoft.Extensions.DependencyInjection;\nusing Nebula.Caching.InMemory.Interceptors;\nnamespace Nebula.Caching.InMemory.Extensions.InterceptorExtensions\n{\n public static class InterceptorExtensions\n {\n public static IServiceCollection AddInMemoryInterceptor(this IServiceCollection services)\n {", "score": 0.9274042844772339 }, { "filename": "src/Nebula.Caching.InMemory/UtilsExtensions/UtilsExtensions.cs", "retrieved_chunk": "using Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.DependencyInjection;\nusing Nebula.Caching.Common.Compression;\nusing Nebula.Caching.Common.Utils;\nusing Nebula.Caching.InMemory.KeyManager;\nusing Nebula.Caching.InMemory.Settings;\nnamespace Nebula.Caching.InMemory.UtilsExtensions\n{\n public static class UtilsExtensions\n {", "score": 0.8957587480545044 }, { "filename": "src/Nebula.Caching.InMemory/CacheManager/InMemoryCacheManager.cs", "retrieved_chunk": "using System.Text;\nusing Microsoft.Extensions.Caching.Memory;\nusing Nebula.Caching.Common.CacheManager;\nusing Nebula.Caching.Common.Compression;\nnamespace Nebula.Caching.InMemory.CacheManager\n{\n public class InMemoryCacheManager : ICacheManager\n {\n private readonly IMemoryCache _memoryCache;\n private readonly GZipCompression _gzipCompression;", "score": 0.8951008915901184 }, { "filename": "src/Nebula.Caching.InMemory/Extensions/ManagerExtensions/ManagerExtensions.cs", "retrieved_chunk": "using Microsoft.Extensions.Caching.Memory;\nusing Microsoft.Extensions.DependencyInjection;\nusing Nebula.Caching.Common.CacheManager;\nusing Nebula.Caching.Common.Compression;\nusing Nebula.Caching.Common.KeyManager;\nusing Nebula.Caching.InMemory.CacheManager;\nusing Nebula.Caching.InMemory.KeyManager;\nnamespace Nebula.Caching.InMemory.Extensions.ManagerExtensions\n{\n public static class ManagerExtensions", "score": 0.8716811537742615 } ]
csharp
InMemoryConfigurations configs = null) {
using System; using System.Data.Common; using System.Reflection; using System.Text.RegularExpressions; using Gum.InnerThoughts; using Gum.Utilities; namespace Gum { /// <summary> /// These are the directives used to parse the current line instruction. /// </summary> internal enum TokenChar { None = 0, Situation = '=', BeginCondition = '(', EndCondition = ')', OnceBlock = '-', MultipleBlock = '+', BeginAction = '[', EndAction = ']', ChoiceBlock = '>', Flow = '@', Negative = '!', Debug = '%' } internal static partial class Tokens { public const string Comments = "//"; } public partial class Parser { private static readonly Regex _indentation = new Regex(@"^(\t| |[-+] )*", RegexOptions.Compiled); private const char _separatorChar = ' '; private readonly string[] _lines; /// <summary> /// Each parser will consist into a single script. /// The owner shall be assigned once this gets instantiated in the engine. /// </summary> private readonly CharacterScript _script; /// <summary> /// The current block of dialog that currently belong to <see cref="CharacterScript.CurrentSituation"/>. /// </summary> private int _currentBlock = 0; private Block Block => _script.CurrentSituation.Blocks[_currentBlock]; /// <summary> /// Current line without any comments, used for diagnostics. /// </summary> private string _currentLine = string.Empty; /// <summary> /// Keep tack of the latest index of each line. /// </summary> private int _lastIndentationIndex = 0; /// <summary> /// If applicable, tracks the first token of the last line. /// This is used to tweak our own indentation rules. /// </summary> private TokenChar? _lastLineToken = null; private int _indentationIndex = 0; /// <summary> /// The last directive '@random' to randomize the following choices. /// </summary> private bool _random = false; /// <summary> /// Whether the last line processed was an action. /// </summary> private bool _wasPreviousAction = false; private bool ConsumeIsRandom() { bool random = _random; _random = false; return random; } /// <summary> /// The last directive '@' to play an amount of times. /// </summary> private int _playUntil = -1; private int ConsumePlayUntil() { int playUntil = _playUntil; _playUntil = -1; return playUntil; } // // Post-analysis variables. // /// <summary> /// This is for validating all the goto destination statements. /// </summary> private readonly List<(Block Block, string Location, int Line)> _gotoDestinations = new(); internal static
CharacterScript? Parse(string file) {
string[] lines = File.ReadAllLines(file); Parser parser = new(name: Path.GetFileNameWithoutExtension(file), lines); return parser.Start(); } internal Parser(string name, string[] lines) { _script = new(name); _lines = lines; } internal CharacterScript? Start() { int index = 0; foreach (string rawLine in _lines) { index++; ReadOnlySpan<char> lineNoComments = rawLine.AsSpan(); // First, start by ripping all the comments in this line. int comment = lineNoComments.IndexOf(Tokens.Comments); if (comment != -1) { lineNoComments = lineNoComments.Slice(start: 0, length: comment); lineNoComments = lineNoComments.TrimEnd(); } ReadOnlySpan<char> lineNoIndent = lineNoComments.TrimStart(); if (lineNoIndent.IsEmpty) continue; _currentLine = lineNoComments.ToString(); // TODO: I think I can be fancy and use ReadOnlySpan here instead. // However, I couldn't really find a smart way to list the group matches with a ValueMatch yet. MatchCollection result = _indentation.Matches(_currentLine); // Count the indentation based on the regex captures result. _lastIndentationIndex = _indentationIndex; _indentationIndex = result[0].Groups[1].Captures.Count; // For science! int column = lineNoComments.Length - lineNoIndent.Length; if (lineNoIndent.IsEmpty) continue; if (!ProcessLine(lineNoIndent, index, column)) { return null; } // Track whatever was the last token used. if (Enum.IsDefined(typeof(TokenChar), (int)lineNoIndent[0])) { _lastLineToken = (TokenChar)lineNoIndent[0]; } else { _lastLineToken = null; } if (_script.HasCurrentSituation is false) { OutputHelpers.WriteError($"Expected a situation (=) to be declared before line {index}."); return null; } } if (!ResolveAllGoto()) { return null; } _ = Trim(); return _script; } /// <summary> /// Check whether the first character of a line has a token defined. /// </summary> private bool Defines(ReadOnlySpan<char> line, TokenChar token, string? stringAfterToken = null) { ReadOnlySpan<char> word = GetNextWord(line, out int end).TrimStart(); while (end != -1 && !word.IsEmpty) { if (word[0] == (char)token) { if (stringAfterToken is null) { return true; } else if (word.Slice(1).StartsWith(stringAfterToken)) { return true; } } if (!Enum.IsDefined(typeof(TokenChar), (int)word[0])) { return false; } if (end == line.Length) { return false; } line = line.Slice(end); word = GetNextWord(line, out end).TrimStart(); } return false; } /// <summary> /// Check whether the first character of a line has a token defined. /// </summary> private bool Defines(ReadOnlySpan<char> line, TokenChar[] tokens) { HashSet<char> tokensChar = tokens.Select(t => (char)t).ToHashSet(); ReadOnlySpan<char> word = GetNextWord(line, out int end).TrimStart(); while (end != -1 && !word.IsEmpty) { if (tokensChar.Contains(word[0])) { return true; } if (Enum.IsDefined(typeof(TokenChar), (int)word[0])) { return false; } if (end >= line.Length) { return false; } line = line.Slice(end); } return false; } /// <summary> /// Read the next line, without any comments. /// </summary> /// <returns>Whether it was successful and no error occurred.</returns> private bool ProcessLine(ReadOnlySpan<char> line, int index, int column, int depth = 0, int joinLevel = 0, bool hasCreatedBlock = false) { if (line.IsEmpty) return true; bool isNestedBlock = false; // If this is not a situation declaration ('=') but a situation has not been declared yet! if (line[0] != (char)TokenChar.Situation && _script.HasCurrentSituation is false) { OutputHelpers.WriteError($"Expected a situation (=) to be declared before line {index}."); return false; } else if (depth == 0 && _script.HasCurrentSituation) { // This fixes the lack of indentation of choice dialogs. This is so we can // properly join scenarios such as: // // >> Something... // > Or else! // > No? // // Okay. bool isChoice = Defines(line, TokenChar.ChoiceBlock); if (_indentationIndex == _lastIndentationIndex && _lastLineToken == TokenChar.ChoiceBlock && !isChoice) { _lastIndentationIndex += 1; } // We are on a valid situation, check whether we need to join dialogs. // Indentation changed: // < from here // ^ to here if (_indentationIndex < _lastIndentationIndex) { joinLevel = _lastIndentationIndex - _indentationIndex; bool createJoinBlock = true; // If the last line was actually a flow (@) and this is a join, // we'll likely disregard the last join. // // @1 Hi! // Bye. // // Join. <- this will apply a join. // // @1 Hi! // Bye. <- this will apply a join. // // (something) // @1 Hi! // // Bye. <- this will apply a join on (something). if (_lastLineToken == TokenChar.Flow && _script.CurrentSituation.PeekLastBlockParent().Conditional) { joinLevel += 1; } if (Defines(line, TokenChar.BeginCondition)) { createJoinBlock = false; Block lastBlock = _script.CurrentSituation.PeekLastBlock(); Block parent = _script.CurrentSituation.PeekBlockAt(joinLevel); // This might backfire when it's actually deeper into the condition, but okay. if (lastBlock.Requirements.Count == 0 && parent.IsChoice) { // Consider this scenario: // (Condition) // Block! // >> Option A or B? // > A // > B <- parent was choice, so disregard one join...? // Something from B. <- last block was here // (...) <- joinLevel is 2. // Branch joinLevel -= 1; } } else if (Defines(line, new TokenChar[] { TokenChar.Situation, TokenChar.ChoiceBlock, TokenChar.MultipleBlock, TokenChar.OnceBlock })) { if (line.Length > 1 && line[1] == (char)TokenChar.ChoiceBlock) { // Actually a -> } else { // > Hell yeah! // (LookForFire) // Yes...? // > Why would I? <- this needs to pop if (_script.CurrentSituation.PeekLastBlock().Conditional) { joinLevel -= 1; // This is a bit awkward, but I added this in cases which: // - Option a // (Something) < parent of this is non linear, so extra pop is needed // Hello // - Option b if (_script.CurrentSituation.PeekLastBlockParent().NonLinearNode) { _script.CurrentSituation.PopLastBlock(); createJoinBlock = false; } } if (line[0] != (char)TokenChar.MultipleBlock && line[0] != (char)TokenChar.OnceBlock) { _script.CurrentSituation.PopLastBlock(); // We might need to do this check out of this switch case? if (_script.CurrentSituation.PeekLastBlock().IsChoice && _script.CurrentSituation.PeekLastEdgeKind() != EdgeKind.Choice) { _script.CurrentSituation.PopLastBlock(); joinLevel -= 1; } createJoinBlock = false; } } } // Depending where we were, we may need to "join" different branches. if (createJoinBlock) { Block? result = _script.CurrentSituation.AddBlock(ConsumePlayUntil(), joinLevel, isNested: false); if (result is null) { OutputHelpers.WriteError($"Unable to join line {index}. Was the indentation correct?"); return false; } _currentBlock = result.Id; hasCreatedBlock = true; } } else if (_indentationIndex > _lastIndentationIndex) { // May be used if we end up creating a new block. // (first indent obviously won't count) isNestedBlock = _indentationIndex != 1; // Since the last block was a choice, we will need to create another block to continue it. // AS LONG AS the next block is not another choice! if (_script.CurrentSituation.PeekLastBlock().IsChoice && !(line.Length > 1 && line[1] == (char)TokenChar.ChoiceBlock)) { Block? result = _script.CurrentSituation.AddBlock(ConsumePlayUntil(), joinLevel: 0, isNested: true); if (result is null) { OutputHelpers.WriteError($"Unable to nest line {index}. Was the indentation correct?"); return false; } _currentBlock = result.Id; isNestedBlock = false; hasCreatedBlock = true; } } bool isChoiceTitle = isChoice && Defines(line, TokenChar.ChoiceBlock, $"{(char)TokenChar.ChoiceBlock}"); if (isChoiceTitle && !isNestedBlock) { // If this declares another dialog, e.g.: // >> Option? // > Yes // > No! // >> Here comes another... // > Okay. // > Go away! // We need to make sure that the second title declares a new choice block. We do that by popping // the last option and the title. // The popping might have not come up before because they share the same indentation, so that's why we help them a little // bit here. if (_script.CurrentSituation.PeekLastBlock().IsChoice) { _script.CurrentSituation.PopLastBlock(); _script.CurrentSituation.PopLastBlock(); } } } if (Enum.IsDefined(typeof(TokenChar), (int)line[0])) { TokenChar nextDirective = (TokenChar)line[0]; // Eat this next token! line = line.Slice(1); column += 1; _wasPreviousAction = false; switch (nextDirective) { // = case TokenChar.Situation: if (_indentationIndex >= 1) { OutputHelpers.WriteError($"We do not expect an indentation prior to a situation declaration on line {index}."); OutputHelpers.ProposeFix(index, before: _currentLine, after: $"{TokenChar.Situation}{line}"); return false; } if (!_script.AddNewSituation(line)) { OutputHelpers.WriteError($"Situation of name '{line}' has been declared twice on line {index}."); OutputHelpers.ProposeFix(index, before: _currentLine, after: $"{_currentLine} 2"); return false; } return true; // @ case TokenChar.Flow: ReadOnlySpan<char> command = GetNextWord(line, out int end); if (command.Length == 0) { OutputHelpers.WriteError($"Empty flow (@) found on line {index}."); return false; } // List of supported directives ('@'): // @random // @order // @{number} // ...that's all! if (command.StartsWith("random")) { if (hasCreatedBlock) { _ = _script.CurrentSituation.SwitchRelationshipTo(EdgeKind.Random); } else { _random = true; } } else if (command.StartsWith("order")) { // No-op? This is already the default? } else if (TryReadInteger(command) is int number) { if (hasCreatedBlock) { _ = Block.PlayUntil = number; } else { if (Defines(line.Slice(end), TokenChar.BeginCondition, Tokens.Else)) { OutputHelpers.WriteError($"Flow directive '{(char)TokenChar.Flow}' is not supported on else blocks on line {index}."); ReadOnlySpan<char> newLine = _currentLine.AsSpan().Slice(0, _currentLine.IndexOf('(')); OutputHelpers.ProposeFixOnLineBelow( index, _currentLine, newLine: Regex.Replace(_currentLine, " @[0-9]", ""), newLineBelow: string.Concat(" ", newLine)); return false; } Block? result = _script.CurrentSituation.AddBlock(number, joinLevel, isNestedBlock, EdgeKind.Next); if (result is null) { OutputHelpers.WriteError($"Unable to join line {index}. Was the indentation correct?"); return false; } _currentBlock = result.Id; // Ignore any other join or nested operations, since the block has been dealed with. joinLevel = 0; } } else { // Failed reading the command :( TryGuessFlowDirectiveError(command, index); return false; } if (end == -1) { return true; } else { column += end; line = line.Slice(end).TrimStart(); } break; // ( case TokenChar.BeginCondition: if (!hasCreatedBlock) { int playUntil = ConsumePlayUntil(); EdgeKind relationshipKind = EdgeKind.Next; if (line.StartsWith(Tokens.Else)) { relationshipKind = EdgeKind.IfElse; } Block? result = _script.CurrentSituation.AddBlock( playUntil, joinLevel, isNestedBlock, relationshipKind); if (result is null) { OutputHelpers.WriteError($"Unable to create condition on line {index}."); return false; } _currentBlock = result.Id; } return ParseConditions(line, index, column); // [ case TokenChar.BeginAction: // Check for the end of the condition block ']' int endAction = MemoryExtensions.IndexOf(line, (char)TokenChar.EndAction); if (endAction == -1) { OutputHelpers.WriteError($"Missing matching '{(char)TokenChar.EndAction}' on line {index}."); OutputHelpers.ProposeFix( index, before: _currentLine, after: _currentLine.TrimEnd() + (char)TokenChar.EndAction); return false; } _wasPreviousAction = true; line = line.Slice(0, endAction); return ParseAction(line, index, column); // - case TokenChar.OnceBlock: // Check whether this is actually a '->' if (!line.IsEmpty && line[0] == (char)TokenChar.ChoiceBlock) { line = line.Slice(1); column += 1; return ParseGoto(line, index, column, isNestedBlock); } _playUntil = 1; return ParseOption(line, index, column, joinLevel, isNestedBlock); // + case TokenChar.MultipleBlock: _playUntil = -1; return ParseOption(line, index, column, joinLevel, isNestedBlock); // > case TokenChar.ChoiceBlock: return ParseChoice(line, index, column, joinLevel, isNestedBlock); default: return true; } } else { return ParseLine(line, index, column, isNestedBlock); } if (!line.IsEmpty) { return ProcessLine(line, index, column, depth + 1, joinLevel, hasCreatedBlock); } return true; } /// <summary> /// This parses choices of the dialog. It expects the following line format: /// > Choice is happening /// ^ begin of span ^ end of span /// >> Choice is happening /// ^ begin of span ^ end of span /// + > Choice is happening /// ^ begin of span ^ end of span /// </summary> private bool ParseChoice(ReadOnlySpan<char> line, int lineIndex, int columnIndex, int joinLevel, bool nested) { line = line.TrimStart().TrimEnd(); if (line.IsEmpty) { OutputHelpers.WriteError($"Invalid empty choice '{(char)TokenChar.ChoiceBlock}' on line {lineIndex}."); OutputHelpers.ProposeFixAtColumn( lineIndex, columnIndex, arrowLength: 1, content: _currentLine, issue: "Expected any form of text."); return false; } Block parent = _script.CurrentSituation.PeekBlockAt(joinLevel); if (!parent.IsChoice && line[0] != (char)TokenChar.ChoiceBlock) { ReadOnlySpan<char> newLine = _currentLine.AsSpan().Slice(0, columnIndex); OutputHelpers.WriteError($"Expected a title prior to a choice block '{(char)TokenChar.ChoiceBlock}' on line {lineIndex}."); OutputHelpers.ProposeFixOnLineAbove( lineIndex, currentLine: _currentLine, newLine: string.Concat(newLine, "> Do your choice")); return false; } if (line[0] == (char)TokenChar.ChoiceBlock) { // This is actually the title! So trim the first character. line = line.Slice(1).TrimStart(); } if (Enum.IsDefined(typeof(TokenChar), (int)line[0])) { OutputHelpers.WriteWarning($"Special tokens after a '>' will be ignored! Use a '\\' if this was what you meant. See line {lineIndex}."); OutputHelpers.ProposeFix( lineIndex, before: _currentLine, after: _currentLine.TrimEnd().Replace($"{line[0]}", $"\\{line[0]}")); } Block? result = _script.CurrentSituation.AddBlock(ConsumePlayUntil(), joinLevel, nested, EdgeKind.Choice); if (result is null) { OutputHelpers.WriteError($"Unable to create condition on line {lineIndex}. This may happen if you declare an else ('...') without a prior condition, for example."); return false; } _currentBlock = result.Id; AddLineToBlock(line); return true; } private bool ParseOption(ReadOnlySpan<char> line, int lineIndex, int columnIndex, int joinLevel, bool nested) { EdgeKind relationshipKind = EdgeKind.HighestScore; if (ConsumeIsRandom() || _script.CurrentSituation.PeekLastEdgeKind() == EdgeKind.Random) { relationshipKind = EdgeKind.Random; } // TODO: Check for requirements! Block? result = _script.CurrentSituation.AddBlock(ConsumePlayUntil(), joinLevel, nested, relationshipKind); if (result is null) { OutputHelpers.WriteError($"Unable to create option on line {lineIndex}."); return false; } _currentBlock = result.Id; line = line.TrimStart(); if (line.IsEmpty) { // OutputHelpers.WriteWarning($"Skipping first empty dialog option in line {lineIndex}."); return true; } if (line[0] == (char)TokenChar.BeginCondition) { // Do not create a new block for conditions. This is because an option is deeply tied // to its rules (it's their score, after all!) so we can't just get away with that. // We might do another syntax if we want to create a new block for some reason. return ParseConditions(line.Slice(1), lineIndex, columnIndex + 1); } else if (line[0] == (char)TokenChar.ChoiceBlock) { return ParseChoice(line.Slice(1), lineIndex, columnIndex + 1, joinLevel: 0, nested: false); } AddLineToBlock(line); return true; } private bool CheckAndCreateLinearBlock(int joinLevel, bool isNested) { // We only create a new block for a line when: // - this is actually the root (or first) node // - previous line was a choice (without a conditional). if (_script.CurrentSituation.Blocks.Count == 1 || (isNested && Block.IsChoice && !Block.Conditional)) { Block? result = _script.CurrentSituation.AddBlock( ConsumePlayUntil(), joinLevel, isNested: false, EdgeKind.Next); if (result is null) { return false; } _currentBlock = result.Id; } return true; } private bool ParseGoto(ReadOnlySpan<char> line, int lineIndex, int currentColumn, bool isNested) { CheckAndCreateLinearBlock(joinLevel: 0, isNested); // Check if we started specifying the relationship from the previous requirement. ReadOnlySpan<char> location = line.TrimStart().TrimEnd(); if (location.IsEmpty) { // We saw something like a (and) condition. This is not really valid for us. OutputHelpers.WriteError($"Expected a situation after '->'."); OutputHelpers.ProposeFixAtColumn( lineIndex, currentColumn, arrowLength: 1, content: _currentLine, issue: "Did you forget a destination here?"); return false; } bool isExit = false; if (MemoryExtensions.Equals(location, "exit!", StringComparison.OrdinalIgnoreCase)) { // If this is an 'exit!' keyword, finalize right away. isExit = true; } else { // Otherwise, keep track of this and add at the end. _gotoDestinations.Add((Block, location.ToString(), lineIndex)); } _script.CurrentSituation.MarkGotoOnBlock(_currentBlock, isExit); return true; } /// <summary> /// This reads and parses a condition into <see cref="_currentBlock"/>. /// Expected format is: /// (HasSomething is true) /// ^ begin of span ^ end of span /// /// </summary> /// <returns>Whether it succeeded parsing the line.</returns> private bool ParseConditions(ReadOnlySpan<char> line, int lineIndex, int currentColumn) { // Check for the end of the condition block ')' int endColumn = MemoryExtensions.IndexOf(line, (char)TokenChar.EndCondition); if (endColumn == -1) { OutputHelpers.WriteError($"Missing matching '{(char)TokenChar.EndCondition}' on line {lineIndex}."); OutputHelpers.ProposeFix( lineIndex, before: _currentLine, after: _currentLine.TrimEnd() + (char)TokenChar.EndCondition); return false; } Block.Conditional = true; line = line.Slice(0, endColumn).TrimEnd(); while (true) { ReadOnlySpan<char> previousLine = line; if (!ReadNextCriterion(ref line, lineIndex, currentColumn, out CriterionNode? node)) { return false; } currentColumn += previousLine.Length - line.Length; if (node is null) { return true; } Block.AddRequirement(node.Value); } } /// <summary> /// Fetches the immediate next word of a line. /// This disregards any indentation or white space prior to the word. /// </summary> /// <param name="end">The end of the parameter. If -1, this is an empty word.</param> private static ReadOnlySpan<char> GetNextWord(ReadOnlySpan<char> line, out int end) { ReadOnlySpan<char> trimmed = line.TrimStart(); int separatorIndex = trimmed.IndexOf(_separatorChar); ReadOnlySpan<char> result = separatorIndex == -1 ? trimmed : trimmed.Slice(0, separatorIndex); end = trimmed.IsEmpty ? -1 : result.Length + (line.Length - trimmed.Length); return result; } /// <summary> /// Fetches and removes the next word of <paramref name="line"/>. /// This disregards any indentation or white space prior to the word. /// </summary> /// <param name="end">The end of the parameter. If -1, this is an empty word.</param> private static ReadOnlySpan<char> PopNextWord(ref ReadOnlySpan<char> line, out int end) { ReadOnlySpan<char> result = GetNextWord(line, out end); if (end != -1) { line = line.Slice(end); } return result; } /// <summary> /// Expects to read an integer of a line such as: /// "28 (Something else)" -> valid /// "28something" -> invalid /// "28" -> valid /// </summary> private int? TryReadInteger(ReadOnlySpan<char> maybeInteger) { if (int.TryParse(maybeInteger, out int result)) { return result; } return null; } /// <summary> /// Try to guess why we failed parsing a '@' directive. /// </summary> private void TryGuessFlowDirectiveError(ReadOnlySpan<char> directive, int index) { OutputHelpers.WriteError($"Unable to recognize '@{directive}' directive on line {index}."); if (char.IsDigit(directive[0])) { char[] clean = Array.FindAll(directive.ToArray(), char.IsDigit); OutputHelpers.ProposeFix( index, before: _currentLine, after: _currentLine.Replace(directive.ToString(), new string(clean))); return; } int commonLength = directive.ToArray().Intersect("random").Count(); if (commonLength > 3) { OutputHelpers.ProposeFix( index, before: _currentLine, after: _currentLine.Replace(directive.ToString(), "random")); return; } OutputHelpers.Remark("We currently support '@{number}' and '@random' as valid directives. Please, reach out if this was not clear. 🙏"); } } }
src/Gum/Parser.cs
isadorasophia-gum-032cb2d
[ { "filename": "src/Gum/InnerThoughts/Situation.cs", "retrieved_chunk": " /// This points\n /// [ Node Id -> Parent ]\n /// If parent is empty, this is at the top.\n /// </summary>\n public readonly Dictionary<int, HashSet<int>> ParentOf = new();\n private readonly Stack<int> _lastBlocks = new();\n public Situation() { }\n public Situation(int id, string name)\n {\n Id = id;", "score": 0.8665410876274109 }, { "filename": "src/Gum/Parser_Actions.cs", "retrieved_chunk": " public const string Component = \"c:\";\n }\n public partial class Parser\n {\n /// <summary>\n /// This reads and parses an action into <see cref=\"_currentBlock\"/>.\n /// Expected format is:\n /// [SomeVariable = true]\n /// ^ begin of span ^ end of span\n /// ", "score": 0.8617733120918274 }, { "filename": "src/Gum/Parser_Requirements.cs", "retrieved_chunk": " }\n public partial class Parser\n {\n /// <summary>\n /// Read the next criterion.\n /// </summary>\n /// <param name=\"line\"></param>\n /// <param name=\"node\">\n /// The resulting node. Only valid if it was able to read a non-empty valid\n /// requirement syntax.", "score": 0.859599769115448 }, { "filename": "src/Gum/InnerThoughts/Situation.cs", "retrieved_chunk": " [JsonProperty]\n public readonly string Name = string.Empty;\n public int Root = 0;\n public readonly List<Block> Blocks = new();\n /// <summary>\n /// This points\n /// [ Node Id -> Edge ]\n /// </summary>\n public readonly Dictionary<int, Edge> Edges = new();\n /// <summary>", "score": 0.8565880656242371 }, { "filename": "src/Gum/Parser_Trimmer.cs", "retrieved_chunk": "using Gum.InnerThoughts;\nnamespace Gum\n{\n public partial class Parser\n {\n /// <summary>\n /// This will trim the graph: clean up empty edges and such.\n /// </summary>\n private bool Trim()\n {", "score": 0.8533288836479187 } ]
csharp
CharacterScript? Parse(string file) {
using Magic.IndexedDb.Models; using System; namespace IndexDb.Example.Pages { public partial class Index { private List<
Person> allPeople {
get; set; } = new List<Person>(); private IEnumerable<Person> WhereExample { get; set; } = Enumerable.Empty<Person>(); private double storageQuota { get; set; } private double storageUsage { get; set; } protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { try { var manager = await _MagicDb.GetDbManager(DbNames.Client); await manager.ClearTable<Person>(); var AllThePeeps = await manager.GetAll<Person>(); if (AllThePeeps.Count() < 1) { Person[] persons = new Person[] { new Person { Name = "Zack", TestInt = 9, _Age = 45, GUIY = Guid.NewGuid(), Secret = "I buried treasure behind my house"}, new Person { Name = "Luna", TestInt = 9, _Age = 35, GUIY = Guid.NewGuid(), Secret = "Jerry is my husband and I had an affair with Bob."}, new Person { Name = "Jerry", TestInt = 9, _Age = 35, GUIY = Guid.NewGuid(), Secret = "My wife is amazing"}, new Person { Name = "Jon", TestInt = 9, _Age = 37, GUIY = Guid.NewGuid(), Secret = "I black mail Luna for money because I know her secret"}, new Person { Name = "Jack", TestInt = 9, _Age = 37, GUIY = Guid.NewGuid(), Secret = "I have a drug problem"}, new Person { Name = "Cathy", TestInt = 9, _Age = 22, GUIY = Guid.NewGuid(), Secret = "I got away with reading Bobs diary."}, new Person { Name = "Bob", TestInt = 3 , _Age = 69, GUIY = Guid.NewGuid(), Secret = "I caught Cathy reading my diary, but I'm too shy to confront her." }, new Person { Name = "Alex", TestInt = 3 , _Age = 80, GUIY = Guid.NewGuid(), Secret = "I'm naked! But nobody can know!" } }; await manager.AddRange(persons); } //var StorageLimit = await manager.GetStorageEstimateAsync(); var storageInfo = await manager.GetStorageEstimateAsync(); storageQuota = storageInfo.quota; storageUsage = storageInfo.usage; var allPeopleDecrypted = await manager.GetAll<Person>(); foreach (Person person in allPeopleDecrypted) { person.SecretDecrypted = await manager.Decrypt(person.Secret); allPeople.Add(person); } WhereExample = await manager.Where<Person>(x => x.Name.StartsWith("c", StringComparison.OrdinalIgnoreCase) || x.Name.StartsWith("l", StringComparison.OrdinalIgnoreCase) || x.Name.StartsWith("j", StringComparison.OrdinalIgnoreCase) && x._Age > 35 ).OrderBy(x => x._Id).Skip(1).Execute(); /* * Still working on allowing nested */ //// Should return "Zack" //var NestedResult = await manager.Where<Person>(p => (p.Name == "Zack" || p.Name == "Luna") && (p._Age >= 35 && p._Age <= 45)).Execute(); //// should return "Luna", "Jerry" and "Jon" //var NonNestedResult = await manager.Where<Person>(p => p.TestInt == 9 && p._Age >= 35 && p._Age <= 45).Execute(); StateHasChanged(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } }
IndexDb.Example/Pages/Index.razor.cs
magiccodingman-Magic.IndexedDb-a279d6d
[ { "filename": "Magic.IndexedDb/Models/DbStore.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Magic.IndexedDb\n{\n public class DbStore\n {\n public string Name { get; set; }", "score": 0.8376728296279907 }, { "filename": "Magic.IndexedDb/Models/IndexFilterValue.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Magic.IndexedDb.Models\n{\n public class IndexFilterValue\n {\n public IndexFilterValue(string indexName, object filterValue)", "score": 0.8376047611236572 }, { "filename": "Magic.IndexedDb/Models/StoreSchema.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Magic.IndexedDb\n{\n public class StoreSchema\n {\n public string Name { get; set; }", "score": 0.8343994617462158 }, { "filename": "IndexDb.Example/Models/DbNames.cs", "retrieved_chunk": "namespace IndexDb.Example\n{\n public static class DbNames\n {\n public const string Client = \"client\";\n }\n}", "score": 0.8313562870025635 }, { "filename": "Magic.IndexedDb/Models/DbMigration.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Magic.IndexedDb\n{\n public class DbMigration\n {\n public string? FromVersion { get; set; }", "score": 0.8260608911514282 } ]
csharp
Person> allPeople {
using Microsoft.Bot.Builder; using Microsoft.Bot.Schema; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NVA.Enums; using NVA.Models; using NVA.Services; namespace NVA.Bots { public class Bot : ActivityHandler { // Seconds to wait before starting to do incremental updates. private const int UPDATE_INITIAL_DELAY_SECS = 7; private const string CONVERSATION_TYPE_CHANNEL = "channel"; private readonly ConversationManager _conversationManager; // Task source for piping incremental updates. private volatile TaskCompletionSource<string> _sentenceUpdate; public Bot(ConversationManager conversationManager) { _conversationManager = conversationManager; _sentenceUpdate = new TaskCompletionSource<string>(); } protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(turnContext.Activity.Text)) { return; } // is it a chat or a channel bool isChannel = turnContext.Activity.Conversation.ConversationType == CONVERSATION_TYPE_CHANNEL; if (!isChannel) { // Bot typing indicator. await turnContext.SendActivityAsync(new Activity { Type = ActivityTypes.Typing }, cancellationToken).ConfigureAwait(false); } // Intially we want to wait for a minimum time before sending an update, so combine sentence update event with delay task. var updateWaitTask = WaitSentenceUpdate(withDelay: true); // Start generating chat response. var generateTask = _conversationManager.GenerateResponse(turnContext, SentenceUpdateCallback, cancellationToken); string answerId = null; bool generateComplete = false; do { // Wait till either generation is complete or an incremental update arrives. var update = await Task.WhenAny(generateTask, updateWaitTask).Unwrap().ConfigureAwait(false); var updateMessage = MessageFactory.Text(update.Message); // refresh incremental update wait task updateWaitTask = WaitSentenceUpdate(); // Cache the value of task completion status. generateComplete = generateTask.IsCompleted; // If it's the first update there's no activity id generated yet. if (string.IsNullOrEmpty(answerId)) { var response = await turnContext.SendActivityAsync(updateMessage, cancellationToken).ConfigureAwait(false); answerId = response.Id; } // For subsequent updates use the same activity id. else { if (generateComplete && !isChannel) { // When generation is complete the message we've been updating is deleted, and then the entire content is send as a new message. // This raises a notification to the user when letter is complete, // and serves as a workaround to `UpdateActivity` not cancelling typing indicator. await Task.WhenAll(turnContext.DeleteActivityAsync(answerId, cancellationToken), turnContext.SendActivityAsync(updateMessage, cancellationToken)).ConfigureAwait(false); } else { // If generation is not complete use the same activity id and update the message. updateMessage.Id = answerId; await turnContext.UpdateActivityAsync(updateMessage, cancellationToken).ConfigureAwait(false); } } // refresh typing indicator if still generating or bot is busy if ((!generateComplete || update.Type == ConversationResponseType.Busy) && !isChannel) { // Typing indicator is reset when `SendActivity` is called, so it has to be resend. await turnContext.SendActivityAsync(new Activity { Type = ActivityTypes.Typing }, cancellationToken).ConfigureAwait(false); } } while (!generateComplete); } protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken) { var adaptiveCardJson = File.ReadAllText(@".\Cards\welcomeCard.json"); JObject json = JObject.Parse(adaptiveCardJson); var adaptiveCardAttachment = new Attachment() { ContentType = "application/vnd.microsoft.card.adaptive", Content = JsonConvert.DeserializeObject(json.ToString()), }; var response = MessageFactory.Attachment(adaptiveCardAttachment); await turnContext.SendActivityAsync(response, cancellationToken).ConfigureAwait(false); } private async Task<
ConversationResponse> WaitSentenceUpdate(bool withDelay = false) {
var task = _sentenceUpdate.Task; if (withDelay) { await Task.WhenAll(task, Task.Delay(UPDATE_INITIAL_DELAY_SECS)).ConfigureAwait(false); } else { await task.ConfigureAwait(false); } return new ConversationResponse(task.Result, ConversationResponseType.Chat); } private void SentenceUpdateCallback(string message) { _sentenceUpdate.TrySetResult(message); // Replace the incremental update task source with a new instance so that we can receive further updates via the event handler. _sentenceUpdate = new TaskCompletionSource<string>(); } } }
NonprofitVirtualAssistant/csharp/NonprofitVirtualAssistant/Bots/Bot.cs
microsoft-NonprofitVirtualAssistant-be69e9b
[ { "filename": "NonprofitVirtualAssistant/csharp/NonprofitVirtualAssistant/Services/ConversationManager.cs", "retrieved_chunk": " userConversation.Add(new MessagePair(question, new ChatMessage(ChatRole.Assistant, responseString)));\n // save changes to conversation history\n await _state.SaveChangesAsync(turnContext, cancellationToken: cancellationToken).ConfigureAwait(false);\n return new ConversationResponse(response.ToString(), ConversationResponseType.Chat);\n }\n catch (DisposableTokenException)\n {\n // if there is currently a bot response in processing for current conversation send back a wait message\n return new ConversationResponse(WAIT_MESSAGE, ConversationResponseType.Busy);\n }", "score": 0.7937031388282776 }, { "filename": "NonprofitVirtualAssistant/csharp/NonprofitVirtualAssistant/Services/OpenAIService.cs", "retrieved_chunk": " {\n var message = _client.Pipeline.CreateMessage(new RequestContext { CancellationToken = cancellationToken });\n message.Request.Method = RequestMethod.Post;\n message.Request.Uri = _moderationEndpoint;\n message.Request.Content = RequestContent.Create(new { input });\n await _client.Pipeline.SendAsync(message, cancellationToken);\n if (message.Response.IsError)\n {\n throw new RequestFailedException(message.Response.Status, $\"Moderation request returned error.\");\n }", "score": 0.7891911864280701 }, { "filename": "NonprofitVirtualAssistant/csharp/NonprofitVirtualAssistant/Services/OpenAIService.cs", "retrieved_chunk": " var json = message.Response.Content.ToObjectFromJson<ModerationResponse>(new JsonSerializerOptions\n {\n PropertyNamingPolicy = JsonNamingPolicy.CamelCase,\n });\n return json?.Results[0]?.Flagged ?? false;\n }\n public static int MaxInputLength { get; } = MAX_PROMPT_LENGTH - FewShotLearningMessages().Sum(m => m.Content.Length);\n // default completion options with system message appended\n public static ChatCompletionsOptions GetCompletionOptions()\n {", "score": 0.763451099395752 }, { "filename": "NonprofitVirtualAssistant/csharp/NonprofitVirtualAssistant/Services/OpenAIService.cs", "retrieved_chunk": " options.Retry.Delay = TimeSpan.FromSeconds(3);\n _client = new OpenAIClient(configuration.GetValue<string>(OPENAI_CONFIG_KEY), options);\n _moderationEndpoint = new RequestUriBuilder();\n _moderationEndpoint.Reset(new Uri(configuration.GetValue<string>(OPENAI_CONFIG_MODERATION_ENDPOINT)));\n }\n // generates completions for a given list of messages, streamed as an enumerable (usually one word at a time).\n public async IAsyncEnumerable<ChatMessage> GetCompletion(\n ChatCompletionsOptions completionsOptions, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n var completions = await _client.GetChatCompletionsStreamingAsync(GPT_MODEL_NAME, completionsOptions, cancellationToken).ConfigureAwait(false);", "score": 0.7615832090377808 }, { "filename": "NonprofitVirtualAssistant/csharp/NonprofitVirtualAssistant/Services/ConversationManager.cs", "retrieved_chunk": " {\n using var token = new DisposableToken(turnContext.Activity.Conversation.Id);\n var question = new ChatMessage(ChatRole.User, turnContext.Activity.Text);\n // limit the size of the user question to a reasonable length\n if (question.Content.Length > CHAR_LIMIT)\n {\n string retry = CHAR_LIMIT_WARNINGS[new Random().Next(CHAR_LIMIT_WARNINGS.Length)];\n return new ConversationResponse(retry, ConversationResponseType.CharLimit);\n }\n // check the new message vs moderation", "score": 0.7485728859901428 } ]
csharp
ConversationResponse> WaitSentenceUpdate(bool withDelay = false) {
using EcsDamageBubbles.Config; using Unity.Burst; using Unity.Collections; using Unity.Entities; using Unity.Mathematics; using Unity.Transforms; namespace EcsDamageBubbles { /// <summary> /// Replace DamageRequest tag with DamageBubble text /// </summary> public partial struct DamageBubbleSpawnSystem : ISystem { private NativeArray<float4> _colorConfig; [BurstCompile] public void OnCreate(ref SystemState state) { state.RequireForUpdate<BeginSimulationEntityCommandBufferSystem.Singleton>(); state.RequireForUpdate<DamageBubblesConfig>(); state.RequireForUpdate<DamageBubbleColorConfig>(); } public void OnDestroy(ref SystemState state) { _colorConfig.Dispose(); } [BurstCompile] public void OnUpdate(ref SystemState state) { if (_colorConfig == default) { var damageColorConfig = SystemAPI.GetSingletonBuffer<DamageBubbleColorConfig>(true); _colorConfig = new NativeArray<float4>(damageColorConfig.Length, Allocator.Persistent); for (var i = 0; i < _colorConfig.Length; i++) _colorConfig[i] = damageColorConfig[i].Color; } var config = SystemAPI.GetSingleton<DamageBubblesConfig>(); var elapsedTime = (float)SystemAPI.Time.ElapsedTime; var ecbSingleton = SystemAPI.GetSingleton<BeginSimulationEntityCommandBufferSystem.Singleton>(); new ApplyGlyphsJob { Ecb = ecbSingleton.CreateCommandBuffer(state.WorldUnmanaged).AsParallelWriter(), ElapsedTime = elapsedTime, ColorConfig = _colorConfig, GlyphEntity = config.GlyphPrefab, GlyphZOffset = config.GlyphZOffset, GlyphWidth = config.GlyphWidth }.ScheduleParallel(); } [BurstCompile] [WithNone(typeof(DamageBubble.
DamageBubble))] public partial struct ApplyGlyphsJob : IJobEntity {
public EntityCommandBuffer.ParallelWriter Ecb; [ReadOnly] public Entity GlyphEntity; [ReadOnly] public float ElapsedTime; [ReadOnly] public float GlyphZOffset; [ReadOnly] public float GlyphWidth; [ReadOnly] public NativeArray<float4> ColorConfig; public void Execute([ChunkIndexInQuery] int chunkIndex, Entity entity, in LocalTransform transform, in DamageBubbleRequest damageBubbleRequest) { var number = damageBubbleRequest.Value; var color = ColorConfig[damageBubbleRequest.ColorId]; var glyphTransform = transform; var offset = math.log10(number) / 2f * GlyphWidth; glyphTransform.Position.x += offset; // split to numbers // we iterate from rightmost digit to leftmost while (number > 0) { var digit = number % 10; number /= 10; var glyph = Ecb.Instantiate(chunkIndex, GlyphEntity); Ecb.SetComponent(chunkIndex, glyph, glyphTransform); glyphTransform.Position.x -= GlyphWidth; glyphTransform.Position.z -= GlyphZOffset; Ecb.AddComponent(chunkIndex, glyph, new DamageBubble.DamageBubble { SpawnTime = ElapsedTime, OriginalY = glyphTransform.Position.y }); Ecb.AddComponent(chunkIndex, glyph, new GlyphIdFloatOverride { Value = digit }); Ecb.SetComponent(chunkIndex, glyph, new GlyphColorOverride { Color = color }); } Ecb.DestroyEntity(chunkIndex, entity); } } } }
Assets/EcsDamageBubbles/Runtime/Scripts/DamageBubbleSpawnSystem.cs
nicloay-ecs-damage-bubbles-8ca1fd7
[ { "filename": "Assets/EcsDamageBubbles/Runtime/Scripts/Config/DamageBubblesConfigAuthoring.cs", "retrieved_chunk": " public float scaleOffset = 1f;\n public float glyphZOffset = 0.001f;\n public float glyphWidth = 0.07f;\n public Color[] damageColors;\n public class ConfigDataBaker : Baker<DamageBubblesConfigAuthoring>\n {\n public override void Bake(DamageBubblesConfigAuthoring authoring)\n {\n var entity = GetEntity(TransformUsageFlags.None);\n AddComponent(entity, new DamageBubblesConfig", "score": 0.8272050619125366 }, { "filename": "Assets/EcsDamageBubbles/Runtime/Scripts/Config/DamageBubblesConfig.cs", "retrieved_chunk": "using Unity.Entities;\nnamespace EcsDamageBubbles.Config\n{\n public struct DamageBubblesConfig : IComponentData\n {\n public Entity GlyphPrefab;\n public float VerticalOffset;\n public float MovementTime;\n public float ScaleOffset;\n public float GlyphZOffset;", "score": 0.8062053918838501 }, { "filename": "Assets/EcsDamageBubbles/Runtime/Scripts/Config/DamageBubblesConfigAuthoring.cs", "retrieved_chunk": " {\n GlyphPrefab = GetEntity(authoring.glyphPrefab, TransformUsageFlags.None),\n ScaleOffset = authoring.scaleOffset,\n VerticalOffset = authoring.verticalOffset,\n MovementTime = authoring.movementTime,\n GlyphZOffset = authoring.glyphZOffset,\n GlyphWidth = authoring.glyphWidth\n });\n var buffer = AddBuffer<DamageBubbleColorConfig>(entity);\n foreach (var managedColor in authoring.damageColors)", "score": 0.8008095026016235 }, { "filename": "Assets/EcsDamageBubbles/Runtime/Scripts/DamageBubble/DamageBubbleMovementSystem.cs", "retrieved_chunk": " [BurstCompile]\n public partial struct MoveJob : IJobEntity\n {\n public float ElapsedTime;\n public float DeltaTime;\n public EntityCommandBuffer.ParallelWriter ECBWriter;\n public float lifeTime;\n public float VerticalOffset;\n public float ScaleOffset;\n private void Execute(Entity entity, [ChunkIndexInQuery] int chunkIndex, ref LocalTransform transform,", "score": 0.7833276391029358 }, { "filename": "Assets/EcsDamageBubbles/Runtime/Scripts/DamageBubble/DamageBubble.cs", "retrieved_chunk": "using Unity.Entities;\nnamespace EcsDamageBubbles.DamageBubble\n{\n public struct DamageBubble : IComponentData\n {\n public float SpawnTime;\n public float OriginalY;\n }\n}", "score": 0.7747186422348022 } ]
csharp
DamageBubble))] public partial struct ApplyGlyphsJob : IJobEntity {
using EleCho.GoCqHttpSdk; using EleCho.GoCqHttpSdk.Message; using EleCho.GoCqHttpSdk.Post; using NodeBot.Classes; using NodeBot.Command; using NodeBot.Event; using NodeBot.Service; using System; using System.Collections.Generic; using System.Linq; using System.Reflection.Metadata; using System.Text; using System.Threading.Tasks; namespace NodeBot { public class NodeBot { public Dictionary<long, int> Permissions = new(); public int OpPermission = 5; public CqWsSession session; public event EventHandler<ConsoleInputEvent>? ConsoleInputEvent; public event EventHandler<
ReceiveMessageEvent>? ReceiveMessageEvent;
public List<ICommand> Commands = new List<ICommand>(); public List<IService> Services = new List<IService>(); public Queue<Task> ToDoQueue = new Queue<Task>(); public NodeBot(string ip) { session = new(new() { BaseUri = new Uri("ws://" + ip), UseApiEndPoint = true, UseEventEndPoint = true, }); session.PostPipeline.Use(async (context, next) => { if (ReceiveMessageEvent != null) { ReceiveMessageEvent(this, new(context)); } await next(); }); ConsoleInputEvent += (sender, e) => { ExecuteCommand(new ConsoleCommandSender(session, this), e.Text); }; ReceiveMessageEvent += (sender, e) => { if (e.Context is CqPrivateMessagePostContext cqPrivateMessage) { ExecuteCommand(new UserQQSender(session, this, cqPrivateMessage.UserId), cqPrivateMessage.Message); } if (e.Context is CqGroupMessagePostContext cqGroupMessage) { ExecuteCommand(new GroupQQSender(session ,this, cqGroupMessage.GroupId, cqGroupMessage.UserId), cqGroupMessage.Message); } }; } /// <summary> /// 保存权限数据 /// </summary> public void SavePermission() { if (!File.Exists("Permission.json")) { File.Create("Permission.json").Close(); } File.WriteAllText("Permission.json", Newtonsoft.Json.JsonConvert.SerializeObject(Permissions)); } /// <summary> /// 加载权限数据 /// </summary> public void LoadPermission() { if (File.Exists("Permission.json")) { string json = File.ReadAllText("Permission.json"); Permissions = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<long, int>>(json)!; } } public void RegisterCommand(ICommand command) { Commands.Add(command); } public void RegisterService(IService service) { Services.Add(service); } public void Start() { session.Start(); foreach (IService service in Services) { service.OnStart(this); } Task.Run(() => { while (true) { Thread.Sleep(1000); if (ToDoQueue.Count > 0) { Task task; lock (ToDoQueue) { task = ToDoQueue.Dequeue(); } task.Start(); } } }); } public void CallConsoleInputEvent(string text) { if (ConsoleInputEvent != null) { ConsoleInputEvent(this, new(text)); } } public void ExecuteCommand(ICommandSender sender, string commandLine) { ICommand? command = GetCommandByCommandLine(commandLine); if (command == null) { return; } if (sender is ConsoleCommandSender console) { if (command.IsConsoleCommand()) { command.Execute(sender, commandLine); } } } public void ExecuteCommand(IQQSender sender, CqMessage commandLine) { if (commandLine[0] is CqTextMsg cqTextMsg) { ICommand? command = GetCommandByCommandLine(cqTextMsg.Text); if (command == null) { return; } if (HasPermission(command, sender)) { if (sender is UserQQSender userQQSender && command.IsUserCommand()) { command.Execute(sender, commandLine); } if (sender is GroupQQSender groupQQSender && command.IsGroupCommand()) { command.Execute(sender, commandLine); } } else { sender.SendMessage("你没有权限"); } } } public ICommand? GetCommandByCommandLine(string command) { string[] tmp = command.Split(' '); foreach (string s in tmp) { if (s != string.Empty) { return FindCommand(s); } } return null; } public ICommand? FindCommand(string commandName) { foreach (ICommand command in Commands) { if (command.GetName().ToLower() == commandName.ToLower()) { return command; } } return null; } public bool HasPermission(ICommand command, long QQNumber) { int permission = 0; if (Permissions.ContainsKey(QQNumber)) { permission = Permissions[QQNumber]; } return permission >= command.GetDefaultPermission(); } public bool HasPermission(ICommand command, ICommandSender sender) { if (sender is IQQSender QQSender) { return HasPermission(command, QQSender.GetNumber()); } if (sender is ConsoleCommandSender) { return true; } return false; } public void RunTask(Task task) { lock (ToDoQueue) { ToDoQueue.Enqueue(task); } } public void RunAction(Action action) { Task task = new(action); RunTask(task); } public void SendGroupMessage(long GroupNumber, CqMessage msgs) { RunAction(() => { session.SendGroupMessage(GroupNumber, msgs); }); } public void SendPrivateMessage(long QQNumber, CqMessage msgs) { RunAction(() => { session.SendPrivateMessage(QQNumber, msgs); }); } public void SendMessage(long Number, CqMessage msgs, UserType type) { if(type == UserType.User) { SendPrivateMessage(Number, msgs); } else if(type == UserType.Group) { SendGroupMessage(Number, msgs); } } } }
NodeBot/NodeBot.cs
Blessing-Studio-NodeBot-ca9921f
[ { "filename": "NodeBot/Command/ConsoleCommandSender.cs", "retrieved_chunk": "{\n public class ConsoleCommandSender : ICommandSender\n {\n public CqWsSession Session;\n public NodeBot Bot;\n public ConsoleCommandSender(CqWsSession session, NodeBot bot)\n {\n Session = session;\n Bot = bot;\n }", "score": 0.8790608048439026 }, { "filename": "NodeBot/github/WebhookService.cs", "retrieved_chunk": " MessageType = messageType;\n }\n }\n public class WebhookService : IService\n {\n public static Thread ListenerThread = new(new ParameterizedThreadStart(Listening));\n public static event EventHandler<WebhookMessageEvent>? MessageEvent;\n public static WebhookService Instance { get; private set; } = new();\n public NodeBot? NodeBot { get; private set; }\n static WebhookService()", "score": 0.8784511685371399 }, { "filename": "NodeBot/github/WebhookService.cs", "retrieved_chunk": "using System.Threading.Tasks;\nnamespace NodeBot.github\n{\n public class WebhookMessageEvent : EventArgs\n {\n public string Message { get; set; }\n public string MessageType { get; set; }\n public WebhookMessageEvent(string message, string messageType)\n {\n Message = message;", "score": 0.8723756670951843 }, { "filename": "NodeBot/Classes/IQQSender.cs", "retrieved_chunk": " {\n Bot.SendGroupMessage(GroupNumber, msgs);\n }\n }\n public class UserQQSender : IQQSender\n {\n public long QQNumber;\n public CqWsSession Session;\n public NodeBot Bot;\n public UserQQSender(CqWsSession session,NodeBot bot, long QQNumber)", "score": 0.8533704280853271 }, { "filename": "NodeBot/BTD6/BTD6_RoundCheck.cs", "retrieved_chunk": "using System.Text;\nusing System.Threading.Tasks;\nnamespace NodeBot.BTD6\n{\n public class BTD6_RoundCheck : ICommand\n {\n public bool Execute(ICommandSender sender, string commandLine)\n {\n string msg = string.Empty;\n int round;", "score": 0.8443832993507385 } ]
csharp
ReceiveMessageEvent>? ReceiveMessageEvent;
using Serilog; using System.Diagnostics; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; namespace OGXbdmDumper { public class Connection : Stream { #region Properties private bool _disposed; private TcpClient _client; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static ReadOnlySpan<byte> NewLineBytes => new byte[] { (byte)'\r', (byte)'\n' }; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private const string NewLineString = "\r\n"; /// <summary> /// The binary reader for the session stream. /// </summary> public BinaryReader Reader { get; private set; } /// <summary> /// The binary writer for the session stream. /// </summary> public BinaryWriter Writer { get; private set; } /// <summary> /// Returns true if the session thinks it's connected based on the most recent operation. /// </summary> public bool IsConnected => _client.Connected; /// <summary> /// The time in milliseconds to wait while sending data before throwing a TimeoutException. /// </summary> public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; } /// <summary> /// The time in milliseconds to wait while receiving data before throwing a TimeoutException. /// </summary> public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; } #endregion #region Construction /// <summary> /// Initializes the session. /// </summary> public Connection() { // initialize defaults Reader = new BinaryReader(this); Writer = new BinaryWriter(this); ResetTcp(); } #endregion #region Methods /// <summary> /// Resets the internal TCP client state. /// </summary> private void ResetTcp() { // preserve previous settings or specify new defaults int sendTimeout = _client?.SendTimeout ?? 10000; int receiveTimeout = _client?.ReceiveTimeout ?? 10000; int sendBufferSize = _client?.SendBufferSize ?? 1024 * 1024 * 2; int receiveBufferSize = _client?.ReceiveBufferSize ?? 1024 * 1024 * 2; try { // attempt to disconnect _client?.Client?.Disconnect(false); _client?.Close(); _client?.Dispose(); } catch { /* do nothing */ } // initialize defaults _client = new TcpClient(AddressFamily.InterNetwork) { NoDelay = true, SendTimeout = sendTimeout, ReceiveTimeout = receiveTimeout, SendBufferSize = sendBufferSize, ReceiveBufferSize = receiveBufferSize }; } /// <summary> /// Connects to the specified host and port. /// </summary> /// <param name="host">The host to connect to.</param> /// <param name="port">The port the host is listening on for the connection.</param> /// <param name="timeout">The time to wait in milliseconds for a connection to complete.</param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <exception cref="TimeoutException"></exception> /// <exception cref="SocketException"></exception> /// <exception cref="ObjectDisposedException"></exception> /// <exception cref="InvalidDataException"></exception> /// <exception cref="Exception"></exception> public
ConnectionInfo Connect(string host, int port, int timeout = 500) {
// argument checks if (host == null) throw new ArgumentNullException(nameof(host)); if (port <= 0 || port > ushort.MaxValue) throw new ArgumentOutOfRangeException(nameof(port)); if (timeout < 0) throw new ArgumentOutOfRangeException(nameof(timeout)); if (_disposed) throw new ObjectDisposedException(nameof(Connection)); Log.Information("Connecting to {0}.", host + ":" + port); if (!_client.ConnectAsync(host, port).Wait(timeout)) { throw new TimeoutException("Failed to connect within the specified timeout period."); } Log.Information("Connected via {0}.", _client.Client.LocalEndPoint); // "201- connected\r\n" var response = ReceiveStatusResponse(); if (!response.Success) throw new Exception(response.Full); // check connection quality var endpoint = _client.Client.RemoteEndPoint as IPEndPoint; var ping = new Ping().Send(endpoint.Address); if (ping.RoundtripTime > 1) { Log.Warning("Elevated network latency of {0}ms detected. Please have wired connectivity to your Xbox for fastest results.", ping.RoundtripTime); } return new ConnectionInfo(endpoint); } /// <summary> /// Closes the connection. /// </summary> public void Disconnect() { if (_disposed) throw new ObjectDisposedException(nameof(Connection)); Log.Information("Disconnecting."); // avoid port exhaustion by attempting to gracefully inform the xbox we're leaving TrySendCommandText("bye"); ResetTcp(); } /// <summary> /// Waits for a single line of text to be available before receiving it. /// </summary> /// <param name="timeout">The optional receive timeout in milliseconds, overriding the session timeout.</param> /// <returns></returns> /// <exception cref="TimeoutException"></exception> /// <exception cref="ObjectDisposedException"></exception> /// <exception cref="SocketException"></exception> public string ReceiveLine(int? timeout = null) { if (_disposed) throw new ObjectDisposedException(nameof(Connection)); Stopwatch timer = Stopwatch.StartNew(); Span<byte> buffer = stackalloc byte[1024]; while ((timeout ?? ReceiveTimeout) == 0 || timer.ElapsedMilliseconds < (timeout ?? ReceiveTimeout)) { Wait(); // new line can't possibly exist if (_client.Available < NewLineBytes.Length) continue; // peek into the receive buffer for a new line int bytesRead = _client.Client.Receive(buffer, SocketFlags.Peek); int newLineIndex = buffer.Slice(0, bytesRead).IndexOf(NewLineBytes); // new line doesn't exist yet if (newLineIndex == -1) continue; // receive the line _client.Client.Receive(buffer.Slice(0, newLineIndex + NewLineBytes.Length)); string line = Encoding.ASCII.GetString(buffer.Slice(0, newLineIndex).ToArray()); Log.Verbose("Received line {0}.", line); return line; } throw new TimeoutException(); } /// <summary> /// Receives multiple lines of text discarding the '.' delimiter at the end. /// </summary> /// <param name="timeout">The optional receive timeout in milliseconds, overriding the session timeout.</param> /// <returns></returns> /// <exception cref="TimeoutException"></exception> public List<string> ReceiveMultilineResponse(int? timeout = null) { if (_disposed) throw new ObjectDisposedException(nameof(Connection)); Log.Verbose("Receiving multiline response."); List<string> lines = new List<string>(); string line; while ((line = ReceiveLine(timeout)) != ".") { lines.Add(line); } return lines; } /// <summary> /// Clears the specified amount of data from the receive buffer. /// </summary> /// <param name="size"></param> /// <exception cref="TimeoutException"></exception> /// <exception cref="ObjectDisposedException"></exception> /// <exception cref="SocketException"></exception> public void ClearReceiveBuffer(int size) { if (_disposed) throw new ObjectDisposedException(nameof(Connection)); if (size <= 0) return; Log.Verbose("Clearing {0} bytes from the receive buffer.", size); Span<byte> buffer = stackalloc byte[1024 * 80]; while (size > 0) { size -= _client.Client.Receive(buffer.Slice(0, Math.Min(buffer.Length, size))); } } /// <summary> /// Clears all existing data from the receive buffer. /// </summary> public void ClearReceiveBuffer() { ClearReceiveBuffer(_client.Available); } /// <summary> /// Sends a command to the xbox without waiting for a response. /// </summary> /// <param name="command">Command to be sent</param> /// <param name="args">Arguments</param> /// <exception cref="TimeoutException"></exception> /// <exception cref="IOException"></exception> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="SocketException"></exception> /// <exception cref="ObjectDisposedException"></exception> /// <exception cref="FormatException"></exception> public void SendCommandText(string command, params object[] args) { if (_disposed) throw new ObjectDisposedException(nameof(Connection)); // attempt to clean up the stream a bit; it's up to the caller to ensure this isn't ran while data is still being received ClearReceiveBuffer(_client.Available); string commandText = string.Format(command, args); Log.Verbose("Sending command {0}.", commandText); _client.Client.Send(Encoding.ASCII.GetBytes(commandText + NewLineString)); } /// <summary> /// Attempts to send a command to the Xbox without waiting for a response. /// </summary> /// <param name="command">Command to be sent</param> /// <param name="args">Arguments</param> /// <returns>Returns true if successful.</returns> public bool TrySendCommandText(string command, params object[] args) { try { SendCommandText(command, args); return true; } catch (Exception e) { Log.Warning(e, "Command failure ignored."); return false; } } /// <summary> /// Sends a command to the xbox and returns the status response. /// Leaves error-handling up to the caller. /// </summary> /// <param name="command">Command to be sent</param> /// <param name="args">Arguments</param> /// <returns>Status response</returns> /// <exception cref="TimeoutException"></exception> /// <exception cref="InvalidDataException"></exception> /// <exception cref="SocketException"></exception> /// <exception cref="IOException"></exception> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ObjectDisposedException"></exception> /// <exception cref="FormatException"></exception> public CommandResponse SendCommand(string command, params object[] args) { if (_disposed) throw new ObjectDisposedException(nameof(Connection)); SendCommandText(command, args); return ReceiveStatusResponse(); } /// <summary> /// Sends a command to the xbox and returns the status response. /// An error response is rethrown as an exception. /// </summary> /// <param name="command">The command to be sent.</param> /// <param name="args">The formatted command arguments.</param> /// <returns>The status response.</returns> /// <exception cref="ObjectDisposedException"></exception> /// <exception cref="TimeoutException"></exception> /// <exception cref="InvalidDataException"></exception> /// <exception cref="SocketException"></exception> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="IOException"></exception> /// <exception cref="FormatException"></exception> /// <exception cref="Exception">Throws varous other types when the command response indicates failure.</exception> public CommandResponse SendCommandStrict(string command, params object[] args) { if (_disposed) throw new ObjectDisposedException(nameof(Connection)); CommandResponse response = SendCommand(command, args); if (response.Success) return response; throw response.Code switch { // TODO: other error codes 402 => new FileNotFoundException(response.Full), // file not found 407 => new NotSupportedException(response.Full), // command not found 410 => new IOException(response.Full), // file already exists 411 => new IOException(response.Full), // directory not empty 412 => new IOException(response.Full), // bad filename 413 => new IOException(response.Full), // file cannot be created 414 => new UnauthorizedAccessException(response.Full), // access denied 423 => new ArgumentException(response.Full), // argument invalid _ => new Exception(response.Full), }; } /// <summary> /// Receives a command for a status response to be received from the xbox. /// </summary> /// <param name="timeout">The optional receive timeout in milliseconds, overriding the XbdmSession Timeout.</param> /// <returns></returns> /// <exception cref="TimeoutException"></exception> /// <exception cref="InvalidDataException"></exception> /// <exception cref="ObjectDisposedException"></exception> /// <exception cref="SocketException"></exception> public CommandResponse ReceiveStatusResponse(int? timeout = null) { if (_disposed) throw new ObjectDisposedException(nameof(Connection)); string response = ReceiveLine(timeout); try { return new CommandResponse(response, Convert.ToInt32(response.Remove(3)), response.Remove(0, 5)); } catch { throw new InvalidDataException("Invalid response."); } } /// <summary> /// Sleeps for the specified number of milliseconds unless the NoSleep session option is enabled, in which case it does nothing. /// </summary> public void Wait(int milliseconds = 1) { if (_disposed) throw new ObjectDisposedException(nameof(Connection)); if (milliseconds < 0) return; } #endregion #region Utilities /// <summary> /// Extracts key/value pairs from an Xbox response line. /// Values returned are either strings or UInt32's. /// Keys with a null value are considered flags. /// </summary> /// <param name="line"></param> /// <returns></returns> public static Dictionary<string, object> ParseKvpResponse(string line) { Dictionary<string, object> values = new Dictionary<string, object>(); // remove any whitespace surrounding equals signs line = Regex.Replace(line, @"\s*([=+])\s*", "$1"); // split by whitespace and commas, ignoring instances inside double quotes // ([^\s]+".*?[^\\]")|([^\s,]+) foreach (Match item in Regex.Matches(line, @"([^\s]+"".*?[^\\]"")|([^\s,]+)")) { // attempt to parse key value pair Match kvp = Regex.Match(item.Value, @"([^=]+)=(.+)"); if (kvp.Success) { string name = kvp.Groups[1].Value; string value = kvp.Groups[2].Value; if (value.StartsWith("\"")) { // string values[name] = value.Trim('"'); } else if (value.StartsWith("0x")) { // hexidecimal integer values[name] = Convert.ToUInt32(value, 16); } else if (uint.TryParse(value, out uint uintValue)) { // decimal integer values[name] = uintValue; } else { throw new InvalidCastException(line); } } else { // otherwise it must be a flag values[item.Value] = null; } } return values; } #endregion #region Stream Implementation public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public override int Read(byte[] buffer, int offset, int count) { // argument checks if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count)); if (_disposed) throw new ObjectDisposedException(nameof(Connection)); // ensure it blocks for the full amount requested int bytesRead = 0; while (bytesRead < count) { bytesRead += _client.Client.Receive(buffer, offset + bytesRead, count - bytesRead, SocketFlags.None); } return bytesRead; } public override void Write(byte[] buffer, int offset, int count) { // argument checks if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count)); if (_disposed) throw new ObjectDisposedException(nameof(Connection)); int bytesWritten = _client.Client.Send(buffer, offset, count, SocketFlags.None); // ensure all bytes are written if (bytesWritten != count) throw new Exception(string.Format("Partial write of {0} out of {1} bytes total.", bytesWritten, count)); } /// <summary> /// Does nothing. /// </summary> public override void Flush() { } /// <summary> /// Not supported. /// </summary> /// <param name="offset"></param> /// <param name="origin"></param> /// <returns></returns> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// Not supported. /// </summary> /// <param name="value"></param> public override void SetLength(long value) { throw new NotSupportedException(); } #endregion #region IDisposable Implementation protected override void Dispose(bool disposing) { if (!_disposed) { // TODO: free unmanaged resources (unmanaged objects) and override finalizer Disconnect(); if (disposing) { // TODO: dispose managed state (managed objects) } // TODO: set large fields to null _disposed = true; } } // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources ~Connection() { // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method Dispose(disposing: false); } public new void Dispose() { // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method Dispose(disposing: true); GC.SuppressFinalize(this); } #endregion } }
src/OGXbdmDumper/Connection.cs
Ernegien-OGXbdmDumper-07a1e82
[ { "filename": "src/OGXbdmDumper/XboxMemoryStream.cs", "retrieved_chunk": " default: throw new InvalidOperationException(\"Invalid SeekOrigin.\");\n }\n }\n /// <summary>\n /// TODO: description\n /// </summary>\n /// <param name=\"buffer\"></param>\n /// <param name=\"offset\"></param>\n /// <param name=\"count\"></param>\n /// <returns></returns>", "score": 0.6427358984947205 }, { "filename": "src/OGXbdmDumper/CommandResponse.cs", "retrieved_chunk": " /// <summary>\n /// TODO: description\n /// </summary>\n public bool Success => (Code & 200) == 200;\n /// <summary>\n /// TODO: description\n /// </summary>\n /// <param name=\"full\"></param>\n /// <param name=\"code\"></param>\n /// <param name=\"message\"></param>", "score": 0.6398274898529053 }, { "filename": "src/OGXbdmDumper/Extensions.cs", "retrieved_chunk": " /// <summary>\n /// Writes a value to a stream.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"stream\"></param>\n /// <param name=\"value\"></param>\n /// <returns>Returns the number of bytes written.</returns>\n public static int Write<T>(this Stream stream, T value)\n {\n if (value == null) throw new ArgumentNullException(nameof(value));", "score": 0.6238082051277161 }, { "filename": "src/OGXbdmDumper/Extensions.cs", "retrieved_chunk": " }\n return (int)(stream.Position - origStreamPosition);\n }\n #endregion\n #region Hex Conversion\n /// <summary>\n /// TODO: description\n /// </summary>\n /// <param name=\"value\"></param>\n /// <param name=\"padWidth\"></param>", "score": 0.6170833110809326 }, { "filename": "src/OGXbdmDumper/KernelExports.cs", "retrieved_chunk": " public long MmFreeContiguousMemory { get; }\n #endregion\n /// <summary>\n /// Index signifies ordinal number.\n /// </summary>\n /// <param name=\"kernelBase\"></param>\n /// <param name=\"functions\"></param>\n public KernelExports(long kernelBase, ExportFunction[] functions)\n {\n _kernelBase = kernelBase;", "score": 0.6129775047302246 } ]
csharp
ConnectionInfo Connect(string host, int port, int timeout = 500) {
using FayElf.Plugins.WeChat.OfficialAccount.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using XiaoFeng; using XiaoFeng.Http; /**************************************************************** * Copyright © (2022) www.fayelf.com All Rights Reserved. * * Author : jacky * * QQ : 7092734 * * Email : [email protected] * * Site : www.fayelf.com * * Create Time : 2022-03-18 08:56:16 * * Version : v 1.0.0 * * CLR Version : 4.0.30319.42000 * *****************************************************************/ namespace FayElf.Plugins.WeChat.OfficialAccount { /// <summary> /// 模板消息操作类 /// </summary> public class Template { #region 构造器 /// <summary> /// 无参构造器 /// </summary> public Template() { this.Config = Config.Current; } /// <summary> /// 设置配置 /// </summary> /// <param name="config">配置</param> public Template(Config config) { this.Config = config; } #endregion #region 属性 /// <summary> /// 配置 /// </summary> public Config Config { get; set; } #endregion #region 方法 #region 设置所属行业 /// <summary> /// 设置所属行业 /// </summary> /// <param name="industry1">公众号模板消息所属行业编号</param> /// <param name="industry2">公众号模板消息所属行业编号</param> /// <returns></returns> public BaseResult SetIndustry(Industry industry1,Industry industry2) { var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method= HttpMethod.Post, Address=$"https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token={token.AccessToken}", BodyData = $@"{{""industry_id1"":""{(int)industry1}"",""industry_id2"":""{(int)industry2}""}}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return response.Html.JsonToObject<BaseResult>(); } else { return new BaseResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); } #endregion #region 获取设置的行业信息 /* * { "primary_industry":{"first_class":"运输与仓储","second_class":"快递"}, "secondary_industry":{"first_class":"IT科技","second_class":"互联网|电子商务"} } */ /// <summary> /// 获取设置的行业信息 /// </summary> /// <returns></returns> public IndustryModelResult GetIndustry() { var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Get, Address = $"https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token={token.AccessToken}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return response.Html.JsonToObject<IndustryModelResult>(); } else { return new IndustryModelResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); } #endregion #region 获得模板ID /// <summary> /// 获得模板ID /// </summary> /// <param name="templateId">模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式</param> /// <returns></returns> public
IndustryTemplateResult AddTemplate(string templateId) {
var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Post, Address = $"https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token={token.AccessToken}", BodyData = $@"{{""template_id_short"":""{templateId}""}}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return response.Html.JsonToObject<IndustryTemplateResult>(); } else { return new IndustryTemplateResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); } #endregion #region 获取模板列表 /// <summary> /// 获取模板列表 /// </summary> /// <returns></returns> public IndustryTemplateListResult GetAllPrivateTemplate() { var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Get, Address = $"https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token={token.AccessToken}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return response.Html.JsonToObject<IndustryTemplateListResult>(); } else { return new IndustryTemplateListResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); } #endregion #region 删除模板 /// <summary> /// 删除模板 /// </summary> /// <param name="templateId">公众帐号下模板消息ID</param> /// <returns></returns> public Boolean DeletePrivateTemplate(string templateId) { var config = this.Config.GetConfig(WeChatType.Applets); var result = Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Post, Address = $"https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token={token.AccessToken}", BodyData = $@"{{""template_id"":""{templateId}""}}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return response.Html.JsonToObject<BaseResult>(); } else { return new BaseResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); return result.ErrCode == 0; } #endregion #region 发送模板消息 /// <summary> /// 发送模板消息 /// </summary> /// <param name="data">发送数据</param> /// <returns></returns> public IndustryTemplateSendDataResult Send(IndustryTemplateSendData data) { var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Post, Address = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={token.AccessToken}", BodyData = data.ToJson() }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return response.Html.JsonToObject<IndustryTemplateSendDataResult>(); } else { return new IndustryTemplateSendDataResult { ErrCode = 500, ErrMsg = "请求出错." }; } }); } #endregion #endregion } }
OfficialAccount/Template.cs
zhuovi-FayElf.Plugins.WeChat-5725d1e
[ { "filename": "OfficialAccount/Subscribe.cs", "retrieved_chunk": " #endregion\n #region 删除模板\n /// <summary>\n /// 删除模板\n /// </summary>\n /// <param name=\"priTmplId\">要删除的模板id</param>\n /// <returns></returns>\n public BaseResult DeleteTemplate(string priTmplId)\n {\n var config = this.Config.GetConfig(WeChatType.Applets);", "score": 0.8618950247764587 }, { "filename": "OfficialAccount/Model/IndustryTemplateResult.cs", "retrieved_chunk": " }\n #endregion\n #region 属性\n /// <summary>\n /// 模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式\n /// </summary>\n [Description(\"模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式\")]\n [JsonElement(\"template_id_short\")]\n public string TemplateIdShort { get; set; }\n #endregion", "score": 0.8561059236526489 }, { "filename": "OfficialAccount/Subscribe.cs", "retrieved_chunk": " };\n }\n });\n }\n #endregion\n #region 获取模板中的关键词\n /// <summary>\n /// 获取模板中的关键词\n /// </summary>\n /// <param name=\"tid\">模板标题 id,可通过接口获取</param>", "score": 0.8485723733901978 }, { "filename": "OfficialAccount/Subscribe.cs", "retrieved_chunk": " };\n }\n });\n }\n #endregion\n #region 获取类目下的公共模板\n /// <summary>\n /// 获取类目下的公共模板\n /// </summary>\n /// <param name=\"ids\">类目 id,多个用逗号隔开</param>", "score": 0.8286527991294861 }, { "filename": "OfficialAccount/Subscribe.cs", "retrieved_chunk": " }\n });\n }\n #endregion\n #region 获取公众号类目\n /// <summary>\n /// 获取公众号类目\n /// </summary>\n /// <returns></returns>\n public TemplateCategoryResult GetCategory()", "score": 0.8285491466522217 } ]
csharp
IndustryTemplateResult AddTemplate(string templateId) {
using HarmonyLib; using System.ComponentModel; using UnityEngine; namespace Ultrapain.Patches { class ZombieProjectile_ShootProjectile_Patch { static void Postfix(
ZombieProjectiles __instance, ref GameObject ___currentProjectile, Animator ___anim, EnemyIdentifier ___eid) {
/*Projectile proj = ___currentProjectile.GetComponent<Projectile>(); proj.target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); proj.speed *= speedMultiplier; proj.turningSpeedMultiplier = turningSpeedMultiplier; proj.damage = damage;*/ bool horizontal = ___anim.GetCurrentAnimatorClipInfo(0)[0].clip.name == "ShootHorizontal"; void AddProperties(GameObject obj) { Projectile component = obj.GetComponent<Projectile>(); component.safeEnemyType = EnemyType.Schism; component.speed *= 1.25f; component.speed *= ___eid.totalSpeedModifier; component.damage *= ___eid.totalDamageModifier; } if (horizontal) { float degreePerIteration = ConfigManager.schismSpreadAttackAngle.value / ConfigManager.schismSpreadAttackCount.value; float currentDegree = degreePerIteration; for (int i = 0; i < ConfigManager.schismSpreadAttackCount.value; i++) { GameObject downProj = GameObject.Instantiate(___currentProjectile); downProj.transform.position += -downProj.transform.up; downProj.transform.Rotate(new Vector3(-currentDegree, 0, 0), Space.Self); GameObject upProj = GameObject.Instantiate(___currentProjectile); upProj.transform.position += upProj.transform.up; upProj.transform.Rotate(new Vector3(currentDegree, 0, 0), Space.Self); currentDegree += degreePerIteration; AddProperties(downProj); AddProperties(upProj); } } else { float degreePerIteration = ConfigManager.schismSpreadAttackAngle.value / ConfigManager.schismSpreadAttackCount.value; float currentDegree = degreePerIteration; for (int i = 0; i < ConfigManager.schismSpreadAttackCount.value; i++) { GameObject leftProj = GameObject.Instantiate(___currentProjectile); leftProj.transform.position += -leftProj.transform.right; leftProj.transform.Rotate(new Vector3(0, -currentDegree, 0), Space.Self); GameObject rightProj = GameObject.Instantiate(___currentProjectile); rightProj.transform.position += rightProj.transform.right; rightProj.transform.Rotate(new Vector3(0, currentDegree, 0), Space.Self); currentDegree += degreePerIteration; AddProperties(leftProj); AddProperties(rightProj); } } } } /*[HarmonyPatch(typeof(ZombieProjectiles), "Start")] class ZombieProjectile_Start_Patch { static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid) { if (___eid.enemyType != EnemyType.Schism) return; __instance.projectile = Plugin.homingProjectile; __instance.decProjectile = Plugin.decorativeProjectile2; } }*/ }
Ultrapain/Patches/Schism.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Solider.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class Solider_Start_Patch\n {\n static void Postfix(ZombieProjectiles __instance, ref GameObject ___decProjectile, ref GameObject ___projectile, ref EnemyIdentifier ___eid, ref Animator ___anim)\n {\n if (___eid.enemyType != EnemyType.Soldier)\n return;", "score": 0.9270342588424683 }, { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": "using HarmonyLib;\nusing System.Reflection;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class Mindflayer_Start_Patch\n {\n static void Postfix(Mindflayer __instance, ref EnemyIdentifier ___eid)\n {\n __instance.gameObject.AddComponent<MindflayerPatch>();", "score": 0.8945823311805725 }, { "filename": "Ultrapain/Patches/Filth.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class SwingCheck2_CheckCollision_Patch2\n {\n static bool Prefix(SwingCheck2 __instance, Collider __0, EnemyIdentifier ___eid)\n {\n if (__0.gameObject.tag != \"Player\")\n return true;", "score": 0.8706307411193848 }, { "filename": "Ultrapain/Patches/Virtue.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class Virtue_Start_Patch\n {\n static void Postfix(Drone __instance, ref EnemyIdentifier ___eid)\n {\n VirtueFlag flag = __instance.gameObject.AddComponent<VirtueFlag>();\n flag.virtue = __instance;", "score": 0.8681419491767883 }, { "filename": "Ultrapain/Patches/StreetCleaner.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class StreetCleaner_Start_Patch\n {\n static void Postfix(Streetcleaner __instance, ref EnemyIdentifier ___eid)\n {\n ___eid.weakPoint = null;\n }", "score": 0.8558046817779541 } ]
csharp
ZombieProjectiles __instance, ref GameObject ___currentProjectile, Animator ___anim, EnemyIdentifier ___eid) {
using HarmonyLib; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using UnityEngine; namespace Ultrapain.Patches { public class OrbitalStrikeFlag : MonoBehaviour { public CoinChainList chainList; public bool isOrbitalRay = false; public bool exploded = false; public float activasionDistance; } public class Coin_Start { static void Postfix(Coin __instance) { __instance.gameObject.AddComponent<OrbitalStrikeFlag>(); } } public class CoinChainList : MonoBehaviour { public List<Coin> chainList = new List<Coin>(); public bool isOrbitalStrike = false; public float activasionDistance; } class Punch_BlastCheck { [
HarmonyBefore(new string[] {
"tempy.fastpunch" })] static bool Prefix(Punch __instance) { __instance.blastWave = GameObject.Instantiate(Plugin.explosionWaveKnuckleblaster, new Vector3(1000000, 1000000, 1000000), Quaternion.identity); __instance.blastWave.AddComponent<OrbitalStrikeFlag>(); return true; } [HarmonyBefore(new string[] { "tempy.fastpunch" })] static void Postfix(Punch __instance) { GameObject.Destroy(__instance.blastWave); __instance.blastWave = Plugin.explosionWaveKnuckleblaster; } } class Explosion_Collide { static bool Prefix(Explosion __instance, Collider __0, List<Collider> ___hitColliders) { if (___hitColliders.Contains(__0)/* || __instance.transform.parent.GetComponent<OrbitalStrikeFlag>() == null*/) return true; Coin coin = __0.GetComponent<Coin>(); if (coin != null) { OrbitalStrikeFlag flag = coin.GetComponent<OrbitalStrikeFlag>(); if(flag == null) { coin.gameObject.AddComponent<OrbitalStrikeFlag>(); Debug.Log("Added orbital strike flag"); } } return true; } } class Coin_DelayedReflectRevolver { static void Postfix(Coin __instance, GameObject ___altBeam) { CoinChainList flag = null; OrbitalStrikeFlag orbitalBeamFlag = null; if (___altBeam != null) { orbitalBeamFlag = ___altBeam.GetComponent<OrbitalStrikeFlag>(); if (orbitalBeamFlag == null) { orbitalBeamFlag = ___altBeam.AddComponent<OrbitalStrikeFlag>(); GameObject obj = new GameObject(); obj.AddComponent<RemoveOnTime>().time = 5f; flag = obj.AddComponent<CoinChainList>(); orbitalBeamFlag.chainList = flag; } else flag = orbitalBeamFlag.chainList; } else { if (__instance.ccc == null) { GameObject obj = new GameObject(); __instance.ccc = obj.AddComponent<CoinChainCache>(); obj.AddComponent<RemoveOnTime>().time = 5f; } flag = __instance.ccc.gameObject.GetComponent<CoinChainList>(); if(flag == null) flag = __instance.ccc.gameObject.AddComponent<CoinChainList>(); } if (flag == null) return; if (!flag.isOrbitalStrike && flag.chainList.Count != 0 && __instance.GetComponent<OrbitalStrikeFlag>() != null) { Coin lastCoin = flag.chainList.LastOrDefault(); float distance = Vector3.Distance(__instance.transform.position, lastCoin.transform.position); if (distance >= ConfigManager.orbStrikeMinDistance.value) { flag.isOrbitalStrike = true; flag.activasionDistance = distance; if (orbitalBeamFlag != null) { orbitalBeamFlag.isOrbitalRay = true; orbitalBeamFlag.activasionDistance = distance; } Debug.Log("Coin valid for orbital strike"); } } if (flag.chainList.Count == 0 || flag.chainList.LastOrDefault() != __instance) flag.chainList.Add(__instance); } } class Coin_ReflectRevolver { public static bool coinIsShooting = false; public static Coin shootingCoin = null; public static GameObject shootingAltBeam; public static float lastCoinTime = 0; static bool Prefix(Coin __instance, GameObject ___altBeam) { coinIsShooting = true; shootingCoin = __instance; lastCoinTime = Time.time; shootingAltBeam = ___altBeam; return true; } static void Postfix(Coin __instance) { coinIsShooting = false; } } class RevolverBeam_Start { static bool Prefix(RevolverBeam __instance) { OrbitalStrikeFlag flag = __instance.GetComponent<OrbitalStrikeFlag>(); if (flag != null && flag.isOrbitalRay) { RevolverBeam_ExecuteHits.orbitalBeam = __instance; RevolverBeam_ExecuteHits.orbitalBeamFlag = flag; } return true; } } class RevolverBeam_ExecuteHits { public static bool isOrbitalRay = false; public static RevolverBeam orbitalBeam = null; public static OrbitalStrikeFlag orbitalBeamFlag = null; static bool Prefix(RevolverBeam __instance) { OrbitalStrikeFlag flag = __instance.GetComponent<OrbitalStrikeFlag>(); if (flag != null && flag.isOrbitalRay) { isOrbitalRay = true; orbitalBeam = __instance; orbitalBeamFlag = flag; } return true; } static void Postfix() { isOrbitalRay = false; } } class OrbitalExplosionInfo : MonoBehaviour { public bool active = true; public string id; public int points; } class Grenade_Explode { class StateInfo { public bool state = false; public string id; public int points; public GameObject templateExplosion; } static bool Prefix(Grenade __instance, ref float __3, out StateInfo __state, bool __1, bool __2) { __state = new StateInfo(); if((Coin_ReflectRevolver.coinIsShooting && Coin_ReflectRevolver.shootingCoin != null) || (Time.time - Coin_ReflectRevolver.lastCoinTime <= 0.1f)) { CoinChainList list = null; if (Coin_ReflectRevolver.shootingAltBeam != null) { OrbitalStrikeFlag orbitalFlag = Coin_ReflectRevolver.shootingAltBeam.GetComponent<OrbitalStrikeFlag>(); if (orbitalFlag != null) list = orbitalFlag.chainList; } else if (Coin_ReflectRevolver.shootingCoin != null && Coin_ReflectRevolver.shootingCoin.ccc != null) list = Coin_ReflectRevolver.shootingCoin.ccc.GetComponent<CoinChainList>(); if (list != null && list.isOrbitalStrike) { if (__1) { __state.templateExplosion = GameObject.Instantiate(__instance.harmlessExplosion, new Vector3(1000000, 1000000, 1000000), Quaternion.identity); __instance.harmlessExplosion = __state.templateExplosion; } else if (__2) { __state.templateExplosion = GameObject.Instantiate(__instance.superExplosion, new Vector3(1000000, 1000000, 1000000), Quaternion.identity); __instance.superExplosion = __state.templateExplosion; } else { __state.templateExplosion = GameObject.Instantiate(__instance.explosion, new Vector3(1000000, 1000000, 1000000), Quaternion.identity); __instance.explosion = __state.templateExplosion; } OrbitalExplosionInfo info = __state.templateExplosion.AddComponent<OrbitalExplosionInfo>(); info.id = ""; __state.state = true; float damageMulti = 1f; float sizeMulti = 1f; // REVOLVER NORMAL if (Coin_ReflectRevolver.shootingAltBeam == null) { if (ConfigManager.orbStrikeRevolverGrenade.value) { damageMulti += ConfigManager.orbStrikeRevolverGrenadeExtraDamage.value; sizeMulti += ConfigManager.orbStrikeRevolverGrenadeExtraSize.value; info.id = ConfigManager.orbStrikeRevolverStyleText.guid; info.points = ConfigManager.orbStrikeRevolverStylePoint.value; } } else if (Coin_ReflectRevolver.shootingAltBeam.TryGetComponent(out RevolverBeam beam)) { if (beam.beamType == BeamType.Revolver) { // REVOLVER CHARGED (NORMAL + ALT. IF DISTINCTION IS NEEDED, USE beam.strongAlt FOR ALT) if (beam.ultraRicocheter) { if (ConfigManager.orbStrikeRevolverChargedGrenade.value) { damageMulti += ConfigManager.orbStrikeRevolverChargedGrenadeExtraDamage.value; sizeMulti += ConfigManager.orbStrikeRevolverChargedGrenadeExtraSize.value; info.id = ConfigManager.orbStrikeRevolverChargedStyleText.guid; info.points = ConfigManager.orbStrikeRevolverChargedStylePoint.value; } } // REVOLVER ALT else { if (ConfigManager.orbStrikeRevolverGrenade.value) { damageMulti += ConfigManager.orbStrikeRevolverGrenadeExtraDamage.value; sizeMulti += ConfigManager.orbStrikeRevolverGrenadeExtraSize.value; info.id = ConfigManager.orbStrikeRevolverStyleText.guid; info.points = ConfigManager.orbStrikeRevolverStylePoint.value; } } } // ELECTRIC RAILCANNON else if (beam.beamType == BeamType.Railgun && beam.hitAmount > 500) { if (ConfigManager.orbStrikeElectricCannonGrenade.value) { damageMulti += ConfigManager.orbStrikeElectricCannonExplosionDamage.value; sizeMulti += ConfigManager.orbStrikeElectricCannonExplosionSize.value; info.id = ConfigManager.orbStrikeElectricCannonStyleText.guid; info.points = ConfigManager.orbStrikeElectricCannonStylePoint.value; } } // MALICIOUS RAILCANNON else if (beam.beamType == BeamType.Railgun) { if (ConfigManager.orbStrikeMaliciousCannonGrenade.value) { damageMulti += ConfigManager.orbStrikeMaliciousCannonGrenadeExtraDamage.value; sizeMulti += ConfigManager.orbStrikeMaliciousCannonGrenadeExtraSize.value; info.id = ConfigManager.orbStrikeMaliciousCannonStyleText.guid; info.points = ConfigManager.orbStrikeMaliciousCannonStylePoint.value; } } else __state.state = false; } else __state.state = false; if(sizeMulti != 1 || damageMulti != 1) foreach(Explosion exp in __state.templateExplosion.GetComponentsInChildren<Explosion>()) { exp.maxSize *= sizeMulti; exp.speed *= sizeMulti; exp.damage = (int)(exp.damage * damageMulti); } Debug.Log("Applied orbital strike bonus"); } } return true; } static void Postfix(Grenade __instance, StateInfo __state) { if (__state.templateExplosion != null) GameObject.Destroy(__state.templateExplosion); if (!__state.state) return; } } class Cannonball_Explode { static bool Prefix(Cannonball __instance, GameObject ___interruptionExplosion, ref GameObject ___breakEffect) { if ((Coin_ReflectRevolver.coinIsShooting && Coin_ReflectRevolver.shootingCoin != null) || (Time.time - Coin_ReflectRevolver.lastCoinTime <= 0.1f)) { CoinChainList list = null; if (Coin_ReflectRevolver.shootingAltBeam != null) { OrbitalStrikeFlag orbitalFlag = Coin_ReflectRevolver.shootingAltBeam.GetComponent<OrbitalStrikeFlag>(); if (orbitalFlag != null) list = orbitalFlag.chainList; } else if (Coin_ReflectRevolver.shootingCoin != null && Coin_ReflectRevolver.shootingCoin.ccc != null) list = Coin_ReflectRevolver.shootingCoin.ccc.GetComponent<CoinChainList>(); if (list != null && list.isOrbitalStrike && ___interruptionExplosion != null) { float damageMulti = 1f; float sizeMulti = 1f; GameObject explosion = GameObject.Instantiate<GameObject>(___interruptionExplosion, __instance.transform.position, Quaternion.identity); OrbitalExplosionInfo info = explosion.AddComponent<OrbitalExplosionInfo>(); info.id = ""; // REVOLVER NORMAL if (Coin_ReflectRevolver.shootingAltBeam == null) { if (ConfigManager.orbStrikeRevolverGrenade.value) { damageMulti += ConfigManager.orbStrikeRevolverGrenadeExtraDamage.value; sizeMulti += ConfigManager.orbStrikeRevolverGrenadeExtraSize.value; info.id = ConfigManager.orbStrikeRevolverStyleText.guid; info.points = ConfigManager.orbStrikeRevolverStylePoint.value; } } else if (Coin_ReflectRevolver.shootingAltBeam.TryGetComponent(out RevolverBeam beam)) { if (beam.beamType == BeamType.Revolver) { // REVOLVER CHARGED (NORMAL + ALT. IF DISTINCTION IS NEEDED, USE beam.strongAlt FOR ALT) if (beam.ultraRicocheter) { if (ConfigManager.orbStrikeRevolverChargedGrenade.value) { damageMulti += ConfigManager.orbStrikeRevolverChargedGrenadeExtraDamage.value; sizeMulti += ConfigManager.orbStrikeRevolverChargedGrenadeExtraSize.value; info.id = ConfigManager.orbStrikeRevolverChargedStyleText.guid; info.points = ConfigManager.orbStrikeRevolverChargedStylePoint.value; } } // REVOLVER ALT else { if (ConfigManager.orbStrikeRevolverGrenade.value) { damageMulti += ConfigManager.orbStrikeRevolverGrenadeExtraDamage.value; sizeMulti += ConfigManager.orbStrikeRevolverGrenadeExtraSize.value; info.id = ConfigManager.orbStrikeRevolverStyleText.guid; info.points = ConfigManager.orbStrikeRevolverStylePoint.value; } } } // ELECTRIC RAILCANNON else if (beam.beamType == BeamType.Railgun && beam.hitAmount > 500) { if (ConfigManager.orbStrikeElectricCannonGrenade.value) { damageMulti += ConfigManager.orbStrikeElectricCannonExplosionDamage.value; sizeMulti += ConfigManager.orbStrikeElectricCannonExplosionSize.value; info.id = ConfigManager.orbStrikeElectricCannonStyleText.guid; info.points = ConfigManager.orbStrikeElectricCannonStylePoint.value; } } // MALICIOUS RAILCANNON else if (beam.beamType == BeamType.Railgun) { if (ConfigManager.orbStrikeMaliciousCannonGrenade.value) { damageMulti += ConfigManager.orbStrikeMaliciousCannonGrenadeExtraDamage.value; sizeMulti += ConfigManager.orbStrikeMaliciousCannonGrenadeExtraSize.value; info.id = ConfigManager.orbStrikeMaliciousCannonStyleText.guid; info.points = ConfigManager.orbStrikeMaliciousCannonStylePoint.value; } } } if (sizeMulti != 1 || damageMulti != 1) foreach (Explosion exp in explosion.GetComponentsInChildren<Explosion>()) { exp.maxSize *= sizeMulti; exp.speed *= sizeMulti; exp.damage = (int)(exp.damage * damageMulti); } if (MonoSingleton<PrefsManager>.Instance.GetBoolLocal("simpleExplosions", false)) { ___breakEffect = null; } __instance.Break(); return false; } } return true; } } class Explosion_CollideOrbital { static bool Prefix(Explosion __instance, Collider __0) { OrbitalExplosionInfo flag = __instance.transform.parent.GetComponent<OrbitalExplosionInfo>(); if (flag == null || !flag.active) return true; if ( __0.gameObject.tag != "Player" && (__0.gameObject.layer == 10 || __0.gameObject.layer == 11) && __instance.canHit != AffectedSubjects.PlayerOnly) { EnemyIdentifierIdentifier componentInParent = __0.GetComponentInParent<EnemyIdentifierIdentifier>(); if (componentInParent != null && componentInParent.eid != null && !componentInParent.eid.blessed/* && !componentInParent.eid.dead*/) { flag.active = false; if(flag.id != "") StyleHUD.Instance.AddPoints(flag.points, flag.id); } } return true; } } class EnemyIdentifier_DeliverDamage { static Coin lastExplosiveCoin = null; class StateInfo { public bool canPostStyle = false; public OrbitalExplosionInfo info = null; } static bool Prefix(EnemyIdentifier __instance, out StateInfo __state, Vector3 __2, ref float __3) { //if (Coin_ReflectRevolver.shootingCoin == lastExplosiveCoin) // return true; __state = new StateInfo(); bool causeExplosion = false; if (__instance.dead) return true; if ((Coin_ReflectRevolver.coinIsShooting && Coin_ReflectRevolver.shootingCoin != null)/* || (Time.time - Coin_ReflectRevolver.lastCoinTime <= 0.1f)*/) { CoinChainList list = null; if (Coin_ReflectRevolver.shootingAltBeam != null) { OrbitalStrikeFlag orbitalFlag = Coin_ReflectRevolver.shootingAltBeam.GetComponent<OrbitalStrikeFlag>(); if (orbitalFlag != null) list = orbitalFlag.chainList; } else if (Coin_ReflectRevolver.shootingCoin != null && Coin_ReflectRevolver.shootingCoin.ccc != null) list = Coin_ReflectRevolver.shootingCoin.ccc.GetComponent<CoinChainList>(); if (list != null && list.isOrbitalStrike) { causeExplosion = true; } } else if (RevolverBeam_ExecuteHits.isOrbitalRay && RevolverBeam_ExecuteHits.orbitalBeam != null) { if (RevolverBeam_ExecuteHits.orbitalBeamFlag != null && !RevolverBeam_ExecuteHits.orbitalBeamFlag.exploded) { causeExplosion = true; } } if(causeExplosion) { __state.canPostStyle = true; // REVOLVER NORMAL if (Coin_ReflectRevolver.shootingAltBeam == null) { if(ConfigManager.orbStrikeRevolverExplosion.value) { GameObject explosion = GameObject.Instantiate(Plugin.explosion, /*__instance.gameObject.transform.position*/__2, Quaternion.identity); foreach (Explosion exp in explosion.GetComponentsInChildren<Explosion>()) { exp.enemy = false; exp.hitterWeapon = ""; exp.maxSize *= ConfigManager.orbStrikeRevolverExplosionSize.value; exp.speed *= ConfigManager.orbStrikeRevolverExplosionSize.value; exp.damage = (int)(exp.damage * ConfigManager.orbStrikeRevolverExplosionDamage.value); } OrbitalExplosionInfo info = explosion.AddComponent<OrbitalExplosionInfo>(); info.id = ConfigManager.orbStrikeRevolverStyleText.guid; info.points = ConfigManager.orbStrikeRevolverStylePoint.value; __state.info = info; } } else if (Coin_ReflectRevolver.shootingAltBeam.TryGetComponent(out RevolverBeam beam)) { if (beam.beamType == BeamType.Revolver) { // REVOLVER CHARGED (NORMAL + ALT. IF DISTINCTION IS NEEDED, USE beam.strongAlt FOR ALT) if (beam.ultraRicocheter) { if(ConfigManager.orbStrikeRevolverChargedInsignia.value) { GameObject insignia = GameObject.Instantiate(Plugin.virtueInsignia, /*__instance.transform.position*/__2, Quaternion.identity); // This is required for ff override to detect this insignia as non ff attack insignia.gameObject.name = "PlayerSpawned"; float horizontalSize = ConfigManager.orbStrikeRevolverChargedInsigniaSize.value; insignia.transform.localScale = new Vector3(horizontalSize, insignia.transform.localScale.y, horizontalSize); VirtueInsignia comp = insignia.GetComponent<VirtueInsignia>(); comp.windUpSpeedMultiplier = ConfigManager.orbStrikeRevolverChargedInsigniaDelayBoost.value; comp.damage = ConfigManager.orbStrikeRevolverChargedInsigniaDamage.value; comp.predictive = false; comp.hadParent = false; comp.noTracking = true; StyleHUD.Instance.AddPoints(ConfigManager.orbStrikeRevolverChargedStylePoint.value, ConfigManager.orbStrikeRevolverChargedStyleText.guid); __state.canPostStyle = false; } } // REVOLVER ALT else { if (ConfigManager.orbStrikeRevolverExplosion.value) { GameObject explosion = GameObject.Instantiate(Plugin.explosion, /*__instance.gameObject.transform.position*/__2, Quaternion.identity); foreach (Explosion exp in explosion.GetComponentsInChildren<Explosion>()) { exp.enemy = false; exp.hitterWeapon = ""; exp.maxSize *= ConfigManager.orbStrikeRevolverExplosionSize.value; exp.speed *= ConfigManager.orbStrikeRevolverExplosionSize.value; exp.damage = (int)(exp.damage * ConfigManager.orbStrikeRevolverExplosionDamage.value); } OrbitalExplosionInfo info = explosion.AddComponent<OrbitalExplosionInfo>(); info.id = ConfigManager.orbStrikeRevolverStyleText.guid; info.points = ConfigManager.orbStrikeRevolverStylePoint.value; __state.info = info; } } } // ELECTRIC RAILCANNON else if (beam.beamType == BeamType.Railgun && beam.hitAmount > 500) { if(ConfigManager.orbStrikeElectricCannonExplosion.value) { GameObject lighning = GameObject.Instantiate(Plugin.lightningStrikeExplosive, /*__instance.gameObject.transform.position*/ __2, Quaternion.identity); foreach (Explosion exp in lighning.GetComponentsInChildren<Explosion>()) { exp.enemy = false; exp.hitterWeapon = ""; if (exp.damage == 0) exp.maxSize /= 2; exp.maxSize *= ConfigManager.orbStrikeElectricCannonExplosionSize.value; exp.speed *= ConfigManager.orbStrikeElectricCannonExplosionSize.value; exp.damage = (int)(exp.damage * ConfigManager.orbStrikeElectricCannonExplosionDamage.value); exp.canHit = AffectedSubjects.All; } OrbitalExplosionInfo info = lighning.AddComponent<OrbitalExplosionInfo>(); info.id = ConfigManager.orbStrikeElectricCannonStyleText.guid; info.points = ConfigManager.orbStrikeElectricCannonStylePoint.value; __state.info = info; } } // MALICIOUS RAILCANNON else if (beam.beamType == BeamType.Railgun) { // UNUSED causeExplosion = false; } // MALICIOUS BEAM else if (beam.beamType == BeamType.MaliciousFace) { GameObject explosion = GameObject.Instantiate(Plugin.sisyphiusPrimeExplosion, /*__instance.gameObject.transform.position*/__2, Quaternion.identity); foreach (Explosion exp in explosion.GetComponentsInChildren<Explosion>()) { exp.enemy = false; exp.hitterWeapon = ""; exp.maxSize *= ConfigManager.maliciousChargebackExplosionSizeMultiplier.value; exp.speed *= ConfigManager.maliciousChargebackExplosionSizeMultiplier.value; exp.damage = (int)(exp.damage * ConfigManager.maliciousChargebackExplosionDamageMultiplier.value); } OrbitalExplosionInfo info = explosion.AddComponent<OrbitalExplosionInfo>(); info.id = ConfigManager.maliciousChargebackStyleText.guid; info.points = ConfigManager.maliciousChargebackStylePoint.value; __state.info = info; } // SENTRY BEAM else if (beam.beamType == BeamType.Enemy) { StyleHUD.Instance.AddPoints(ConfigManager.sentryChargebackStylePoint.value, ConfigManager.sentryChargebackStyleText.formattedString); if (ConfigManager.sentryChargebackExtraBeamCount.value > 0) { List<Tuple<EnemyIdentifier, float>> enemies = UnityUtils.GetClosestEnemies(__2, ConfigManager.sentryChargebackExtraBeamCount.value, UnityUtils.doNotCollideWithPlayerValidator); foreach (Tuple<EnemyIdentifier, float> enemy in enemies) { RevolverBeam newBeam = GameObject.Instantiate(beam, beam.transform.position, Quaternion.identity); newBeam.hitEids.Add(__instance); newBeam.transform.LookAt(enemy.Item1.transform); GameObject.Destroy(newBeam.GetComponent<OrbitalStrikeFlag>()); } } RevolverBeam_ExecuteHits.isOrbitalRay = false; } } if (causeExplosion && RevolverBeam_ExecuteHits.orbitalBeamFlag != null) RevolverBeam_ExecuteHits.orbitalBeamFlag.exploded = true; Debug.Log("Applied orbital strike explosion"); } return true; } static void Postfix(EnemyIdentifier __instance, StateInfo __state) { if(__state.canPostStyle && __instance.dead && __state.info != null) { __state.info.active = false; if (__state.info.id != "") StyleHUD.Instance.AddPoints(__state.info.points, __state.info.id); } } } class RevolverBeam_HitSomething { static bool Prefix(RevolverBeam __instance, out GameObject __state) { __state = null; if (RevolverBeam_ExecuteHits.orbitalBeam == null) return true; if (__instance.beamType != BeamType.Railgun) return true; if (__instance.hitAmount != 1) return true; if (RevolverBeam_ExecuteHits.orbitalBeam.GetInstanceID() == __instance.GetInstanceID()) { if (!RevolverBeam_ExecuteHits.orbitalBeamFlag.exploded && ConfigManager.orbStrikeMaliciousCannonExplosion.value) { Debug.Log("MALICIOUS EXPLOSION EXTRA SIZE"); GameObject tempExp = GameObject.Instantiate(__instance.hitParticle, new Vector3(1000000, 1000000, 1000000), Quaternion.identity); foreach (Explosion exp in tempExp.GetComponentsInChildren<Explosion>()) { exp.maxSize *= ConfigManager.orbStrikeMaliciousCannonExplosionSizeMultiplier.value; exp.speed *= ConfigManager.orbStrikeMaliciousCannonExplosionSizeMultiplier.value; exp.damage = (int)(exp.damage * ConfigManager.orbStrikeMaliciousCannonExplosionDamageMultiplier.value); } __instance.hitParticle = tempExp; OrbitalExplosionInfo info = tempExp.AddComponent<OrbitalExplosionInfo>(); info.id = ConfigManager.orbStrikeMaliciousCannonStyleText.guid; info.points = ConfigManager.orbStrikeMaliciousCannonStylePoint.value; RevolverBeam_ExecuteHits.orbitalBeamFlag.exploded = true; } Debug.Log("Already exploded"); } else Debug.Log("Not the same instance"); return true; } static void Postfix(RevolverBeam __instance, GameObject __state) { if (__state != null) GameObject.Destroy(__state); } } }
Ultrapain/Patches/OrbitalStrike.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/V2Common.cs", "retrieved_chunk": " return true;\n }\n }\n class V2CommonRevolverBulletSharp : MonoBehaviour\n {\n public int reflectionCount = 2;\n public float autoAimAngle = 30f;\n public Projectile proj;\n public float speed = 350f;\n public bool hasTargetPoint = false;", "score": 0.8501448631286621 }, { "filename": "Ultrapain/Patches/Cerberus.cs", "retrieved_chunk": "using UnityEngine;\nnamespace Ultrapain.Patches\n{\n class CerberusFlag : MonoBehaviour\n {\n public int extraDashesRemaining = ConfigManager.cerberusTotalDashCount.value - 1;\n public Transform head;\n public float lastParryTime;\n private EnemyIdentifier eid;\n private void Awake()", "score": 0.8292462825775146 }, { "filename": "Ultrapain/Patches/Parry.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class GrenadeParriedFlag : MonoBehaviour\n {\n public int parryCount = 1;\n public bool registeredStyle = false;\n public bool bigExplosionOverride = false;\n public GameObject temporaryExplosion;", "score": 0.8251359462738037 }, { "filename": "Ultrapain/Patches/CommonComponents.cs", "retrieved_chunk": " public Quaternion targetRotation;\n private void Awake()\n {\n transform.rotation = targetRotation;\n }\n }\n public class CommonActivator : MonoBehaviour\n {\n public int originalId;\n public Renderer rend;", "score": 0.8202614784240723 }, { "filename": "Ultrapain/Patches/Virtue.cs", "retrieved_chunk": " }\n }\n class VirtueFlag : MonoBehaviour\n {\n public AudioSource lighningBoltSFX;\n public GameObject ligtningBoltAud;\n public Transform windupObj;\n private EnemyIdentifier eid;\n public Drone virtue;\n public void Awake()", "score": 0.8169779777526855 } ]
csharp
HarmonyBefore(new string[] {
using LibreDteDotNet.RestRequest.Interfaces; namespace LibreDteDotNet.RestRequest.Infraestructure { public class RestRequest { public ILibro Libro { get; } public IContribuyente Contribuyente { get; } public IFolioCaf FolioCaf { get; } public IBoleta Boleta { get; } public IDTE DocumentoTributario { get; } public RestRequest( ILibro libroService, IContribuyente contribuyenteService,
IFolioCaf folioCafService, IBoleta boletaService, IDTE dTEService ) {
Libro = libroService; Contribuyente = contribuyenteService; FolioCaf = folioCafService; Boleta = boletaService; DocumentoTributario = dTEService; } } }
LibreDteDotNet.RestRequest/Infraestructure/RestRequest.cs
sergiokml-LibreDteDotNet.RestRequest-6843109
[ { "filename": "LibreDteDotNet.RestRequest/Interfaces/IBoleta.cs", "retrieved_chunk": "namespace LibreDteDotNet.RestRequest.Interfaces\n{\n public interface IBoleta\n {\n Task<IBoleta> SetCookieCertificado();\n Task<string> GetConsumoByFecha(\n string anoIni,\n string mesIni,\n string anoFin,\n string mesFin,", "score": 0.8311077356338501 }, { "filename": "LibreDteDotNet.RestRequest/Interfaces/IFolioCaf.cs", "retrieved_chunk": " string rut,\n string dv,\n string cant,\n string cantmax,\n TipoDoc tipodoc\n );\n Task<XDocument> Descargar();\n Task<IFolioCaf> SetCookieCertificado();\n Task<Dictionary<string, string>> GetRangoMax(string rut, string dv, TipoDoc tipodoc);\n Task<IFolioCaf> Confirmar();", "score": 0.8237462043762207 }, { "filename": "LibreDteDotNet.RestRequest/Extensions/DTEExtension.cs", "retrieved_chunk": " public static async Task<string> Enviar(\n this Task<IDTE> folioService,\n string rutCompany,\n string DvCompany\n )\n {\n IDTE instance = await folioService;\n return await instance.Enviar(rutCompany, DvCompany);\n }\n }", "score": 0.8224714994430542 }, { "filename": "LibreDteDotNet.RestRequest/Extensions/BoletaExtension.cs", "retrieved_chunk": "using LibreDteDotNet.RestRequest.Interfaces;\nnamespace LibreDteDotNet.RestRequest.Extensions\n{\n public static class BoletaExtension\n {\n public static IBoleta Conectar(this IBoleta folioService)\n {\n IBoleta instance = folioService;\n return instance.SetCookieCertificado().Result;\n }", "score": 0.8147174119949341 }, { "filename": "LibreDteDotNet.RestRequest/Extensions/ContribuyenteExtension.cs", "retrieved_chunk": "using LibreDteDotNet.RestRequest.Interfaces;\nnamespace LibreDteDotNet.RestRequest.Extensions\n{\n public static class ContribuyenteExtension\n {\n public static IContribuyente Conectar(this IContribuyente folioService)\n {\n IContribuyente instance = folioService;\n return instance.SetCookieCertificado().Result;\n }", "score": 0.8121170997619629 } ]
csharp
IFolioCaf folioCafService, IBoleta boletaService, IDTE dTEService ) {
using Discord; using HarmonyLib; using System.Text.RegularExpressions; namespace Ultrapain.Patches { class DiscordController_SendActivity_Patch { static bool Prefix(
DiscordController __instance, ref Activity ___cachedActivity) {
if (___cachedActivity.State != null && ___cachedActivity.State == "DIFFICULTY: UKMD") { Regex rich = new Regex(@"<[^>]*>"); string text = $"DIFFICULTY: {ConfigManager.pluginName.value}"; if (rich.IsMatch(text)) { ___cachedActivity.State = rich.Replace(text, string.Empty); } else { ___cachedActivity.State = text; } } return true; } } }
Ultrapain/Patches/DiscordController.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/SteamFriends.cs", "retrieved_chunk": "using HarmonyLib;\nusing Steamworks;\nusing System.Text.RegularExpressions;\nnamespace Ultrapain.Patches\n{\n class SteamFriends_SetRichPresence_Patch\n {\n static bool Prefix(string __0, ref string __1)\n {\n if (__1.ToLower() != \"ukmd\")", "score": 0.867112398147583 }, { "filename": "Ultrapain/Patches/Idol.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class Idol_Death_Patch\n {\n static void Postfix(Idol __instance)\n {", "score": 0.8638989329338074 }, { "filename": "Ultrapain/Patches/FleshPrison.cs", "retrieved_chunk": "using HarmonyLib;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing UnityEngine;\nusing UnityEngine.UI;\nnamespace Ultrapain.Patches\n{\n class FleshObamium_Start\n {\n static bool Prefix(FleshPrison __instance)", "score": 0.8623285293579102 }, { "filename": "Ultrapain/Patches/StreetCleaner.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class StreetCleaner_Start_Patch\n {\n static void Postfix(Streetcleaner __instance, ref EnemyIdentifier ___eid)\n {\n ___eid.weakPoint = null;\n }", "score": 0.8367517590522766 }, { "filename": "Ultrapain/Patches/EnrageEffect.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class EnrageEffect_Start\n {\n static void Postfix(EnrageEffect __instance)", "score": 0.83548504114151 } ]
csharp
DiscordController __instance, ref Activity ___cachedActivity) {
using System; using NAK.AASEmulator.Runtime; using UnityEditor; using UnityEngine; using static NAK.AASEmulator.Editor.EditorExtensions; using static NAK.AASEmulator.Runtime.AASEmulatorRuntime; namespace NAK.AASEmulator.Editor { [CustomEditor(typeof(AASEmulatorRuntime))] public class AASEmulatorRuntimeEditor : UnityEditor.Editor { #region Variables private GUIStyle _boldFoldoutStyle; private
AASEmulatorRuntime _targetScript;
#endregion #region Unity / GUI Methods private void OnEnable() { OnRequestRepaint -= Repaint; OnRequestRepaint += Repaint; _boldFoldoutStyle = new GUIStyle(EditorStyles.foldout) { fontStyle = FontStyle.Bold }; // Initialize on select _targetScript = (AASEmulatorRuntime)target; if (!_targetScript.IsInitialized()) _targetScript.Initialize(); } private void OnDisable() => OnRequestRepaint -= Repaint; public override void OnInspectorGUI() { if (_targetScript == null) return; Draw_ScriptWarning(); Draw_AvatarInfo(); Draw_LipSync(); Draw_BuiltInGestures(); Draw_BuiltInLocomotion(); Draw_BuiltInEmotes(); Draw_AdditionalParameters(); } #endregion Unity / GUI Methods #region Drawing Methods private void Draw_ScriptWarning() { if (_targetScript.isInitializedExternally) return; EditorGUILayout.HelpBox("Warning: Do not upload this script with your avatar!\nThis script is prevented from saving to scenes & prefabs.", MessageType.Warning); EditorGUILayout.HelpBox("This script will automatically be added if you enable AASEmulator from the Tools menu (Tools > Enable AAS Emulator).", MessageType.Info); } private void Draw_AvatarInfo() { EditorGUILayout.Space(); _targetScript.avatarInfoFoldout = EditorGUILayout.Foldout(_targetScript.avatarInfoFoldout, "Avatar Info", true, _boldFoldoutStyle); if (_targetScript.avatarInfoFoldout) { EditorGUI.indentLevel++; // Add label to show if an emote is currently playing or not string emoteStatus = _targetScript.IsEmotePlaying ? "Playing an Emote - Tracking Disabled" : "Not Playing an Emote - Tracking Enabled"; EditorGUILayout.LabelField("Emote Status:", emoteStatus); // Add label to show the eye movement status string eyeMovementStatus = _targetScript.UseEyeMovement ? "Enabled - Eye Look On" : "Disabled - Eye Look Off"; EditorGUILayout.LabelField("Eye Movement:", eyeMovementStatus); // Add label to show the blink blendshapes status string blinkBlendshapesStatus = _targetScript.UseBlinkBlendshapes ? "Enabled - Eye Blink On" : "Disabled - Eye Blink Off"; EditorGUILayout.LabelField("Blink Blendshapes:", blinkBlendshapesStatus); // Add label to show the lipsync status string lipsyncStatus = _targetScript.UseLipsync ? "Enabled - Lipsync On" : "Disabled - Lipsync Off"; EditorGUILayout.LabelField("Lipsync:", lipsyncStatus); EditorGUI.indentLevel--; } } private void Draw_LipSync() { EditorGUILayout.Space(); string foldoutLabel = $"Lip Sync / {_targetScript.VisemeMode.ToString().Replace('_', ' ')}"; _targetScript.lipSyncFoldout = EditorGUILayout.Foldout(_targetScript.lipSyncFoldout, foldoutLabel, true, _boldFoldoutStyle); if (_targetScript.lipSyncFoldout) { EditorGUI.indentLevel++; switch (_targetScript.VisemeMode) { case VisemeModeIndex.Visemes: int newVisemeIndex = (int)_targetScript.VisemeIdx; newVisemeIndex = EditorGUILayout.Popup("Viseme Index", newVisemeIndex, Enum.GetNames(typeof(VisemeIndex))); HandlePopupScroll(ref newVisemeIndex, 0, Enum.GetNames(typeof(VisemeIndex)).Length - 1); _targetScript.VisemeIdx = (VisemeIndex)newVisemeIndex; _targetScript.Viseme = EditorGUILayout.IntSlider("Viseme", _targetScript.Viseme, 0, 14); break; case VisemeModeIndex.Single_Blendshape: case VisemeModeIndex.Jaw_Bone: _targetScript.VisemeLoudness = EditorGUILayout.Slider("Viseme Loudness", _targetScript.VisemeLoudness, 0f, 1f); break; } EditorGUI.indentLevel--; } } private void Draw_BuiltInGestures() { EditorGUILayout.Space(); _targetScript.builtInGesturesFoldout = EditorGUILayout.Foldout(_targetScript.builtInGesturesFoldout, "Built-in inputs / Hand Gestures", true, _boldFoldoutStyle); if (_targetScript.builtInGesturesFoldout) { EditorGUI.indentLevel++; int newLeftGestureIndex = EditorGUILayout.Popup("Gesture Left Index", (int)_targetScript.GestureLeftIdx, Enum.GetNames(typeof(GestureIndex))); HandlePopupScroll(ref newLeftGestureIndex, 0, Enum.GetNames(typeof(GestureIndex)).Length - 1); if ((GestureIndex)newLeftGestureIndex != _targetScript.GestureLeftIdx) { _targetScript.GestureLeftIdx = (GestureIndex)newLeftGestureIndex; } float newLeftGestureValue = EditorGUILayout.Slider("Gesture Left", _targetScript.GestureLeft, -1, 6); if (!Mathf.Approximately(newLeftGestureValue, _targetScript.GestureLeft)) { _targetScript.GestureLeft = newLeftGestureValue; } int newRightGestureIndex = EditorGUILayout.Popup("Gesture Right Index", (int)_targetScript.GestureRightIdx, Enum.GetNames(typeof(GestureIndex))); HandlePopupScroll(ref newRightGestureIndex, 0, Enum.GetNames(typeof(GestureIndex)).Length - 1); if ((GestureIndex)newRightGestureIndex != _targetScript.GestureRightIdx) { _targetScript.GestureRightIdx = (GestureIndex)newRightGestureIndex; } float newRightGestureValue = EditorGUILayout.Slider("Gesture Right", _targetScript.GestureRight, -1, 6); if (!Mathf.Approximately(newRightGestureValue, _targetScript.GestureRight)) { _targetScript.GestureRight = newRightGestureValue; } EditorGUI.indentLevel--; } } private void Draw_BuiltInLocomotion() { EditorGUILayout.Space(); _targetScript.builtInLocomotionFoldout = EditorGUILayout.Foldout(_targetScript.builtInLocomotionFoldout, "Built-in inputs / Locomotion", true, _boldFoldoutStyle); if (_targetScript.builtInLocomotionFoldout) { EditorGUI.indentLevel++; // Custom joystick GUI _targetScript.joystickFoldout = EditorGUILayout.Foldout(_targetScript.joystickFoldout, "Joystick", true, _boldFoldoutStyle); if (_targetScript.joystickFoldout) { EditorGUILayout.BeginHorizontal(); Rect joystickRect = GUILayoutUtility.GetRect(100, 100, GUILayout.MaxWidth(100), GUILayout.MaxHeight(100)); Vector2 newMovementValue = Joystick2DField(joystickRect, _targetScript.Movement, true); if (newMovementValue != _targetScript.Movement) _targetScript.Movement = newMovementValue; EditorGUILayout.BeginVertical(); GUILayout.FlexibleSpace(); EditorGUILayout.HelpBox("Double Click to Reset", MessageType.Info); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); } // Movement field Vector2 newMovementValue2 = EditorGUILayout.Vector2Field("Movement", _targetScript.Movement); if (newMovementValue2 != _targetScript.Movement) _targetScript.Movement = newMovementValue2; _targetScript.Crouching = EditorGUILayout.Toggle("Crouching", _targetScript.Crouching); _targetScript.Prone = EditorGUILayout.Toggle("Prone", _targetScript.Prone); _targetScript.Flying = EditorGUILayout.Toggle("Flying", _targetScript.Flying); _targetScript.Sitting = EditorGUILayout.Toggle("Sitting", _targetScript.Sitting); _targetScript.Grounded = EditorGUILayout.Toggle("Grounded", _targetScript.Grounded); EditorGUI.indentLevel--; } } private void Draw_BuiltInEmotes() { EditorGUILayout.Space(); _targetScript.builtInEmotesFoldout = EditorGUILayout.Foldout(_targetScript.builtInEmotesFoldout, "Built-in inputs / Emotes", true, _boldFoldoutStyle); if (_targetScript.builtInEmotesFoldout) { EditorGUI.indentLevel++; EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Emote", GUILayout.Width(60)); for (int i = 0; i <= 8; i++) { bool emote = EditorGUILayout.Toggle(_targetScript.Emote == i, GUILayout.Width(30)); if (emote) _targetScript.Emote = i; } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Toggle", GUILayout.Width(60)); for (int i = 0; i <= 8; i++) { bool toggle = EditorGUILayout.Toggle(_targetScript.Toggle == i, GUILayout.Width(30)); if (toggle) _targetScript.Toggle = i; } EditorGUILayout.EndHorizontal(); _targetScript.CancelEmote = EditorGUILayout.Toggle("Cancel Emote", _targetScript.CancelEmote); EditorGUI.indentLevel--; } } private void Draw_AdditionalParameters() { EditorGUILayout.Space(); if (_targetScript.AnimatorManager == null) return; _targetScript.floatsFoldout = EditorGUILayout.Foldout(_targetScript.floatsFoldout, "Additional inputs / Floats", true, _boldFoldoutStyle); if (_targetScript.floatsFoldout) { EditorGUI.indentLevel++; foreach (var floatParam in _targetScript.AnimatorManager.FloatParameters) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(floatParam.name, GUILayout.MaxWidth(150)); EditorGUILayout.LabelField(floatParam.isLocal ? "Local" : "Synced", GUILayout.MaxWidth(75)); EditorGUI.BeginDisabledGroup(floatParam.isControlledByCurve); float newFloatValue = EditorGUILayout.FloatField(floatParam.value); EditorGUI.EndDisabledGroup(); if (floatParam.value != newFloatValue) _targetScript.AnimatorManager.SetParameter(floatParam.name, newFloatValue); EditorGUILayout.EndHorizontal(); } EditorGUI.indentLevel--; } _targetScript.intsFoldout = EditorGUILayout.Foldout(_targetScript.intsFoldout, "Additional inputs / Ints", true, _boldFoldoutStyle); if (_targetScript.intsFoldout) { EditorGUI.indentLevel++; foreach (var intParam in _targetScript.AnimatorManager.IntParameters) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(intParam.name, GUILayout.MaxWidth(150)); EditorGUILayout.LabelField(intParam.isLocal ? "Local" : "Synced", GUILayout.MaxWidth(75)); EditorGUI.BeginDisabledGroup(intParam.isControlledByCurve); int newIntValue = EditorGUILayout.IntField(intParam.value); EditorGUI.EndDisabledGroup(); if (intParam.value != newIntValue) _targetScript.AnimatorManager.SetParameter(intParam.name, newIntValue); EditorGUILayout.EndHorizontal(); } EditorGUI.indentLevel--; } _targetScript.boolsFoldout = EditorGUILayout.Foldout(_targetScript.boolsFoldout, "Additional inputs / Bools", true, _boldFoldoutStyle); if (_targetScript.boolsFoldout) { EditorGUI.indentLevel++; foreach (var boolParam in _targetScript.AnimatorManager.BoolParameters) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(boolParam.name, GUILayout.MaxWidth(150)); EditorGUILayout.LabelField(boolParam.isLocal ? "Local" : "Synced", GUILayout.MaxWidth(75)); EditorGUI.BeginDisabledGroup(boolParam.isControlledByCurve); bool newBoolValue = EditorGUILayout.Toggle(boolParam.value); EditorGUI.EndDisabledGroup(); if (boolParam.value != newBoolValue) _targetScript.AnimatorManager.SetParameter(boolParam.name, newBoolValue); EditorGUILayout.EndHorizontal(); } EditorGUI.indentLevel--; } } #endregion Drawing Methods } }
Editor/AASEmulatorRuntimeEditor.cs
NotAKidOnSteam-AASEmulator-aacd289
[ { "filename": "Editor/AASMenuEditor.cs", "retrieved_chunk": "using NAK.AASEmulator.Runtime;\nusing UnityEditor;\nusing UnityEngine;\nusing static ABI.CCK.Scripts.CVRAdvancedSettingsEntry;\nusing static NAK.AASEmulator.Runtime.AASEmulatorRuntime;\nusing static NAK.AASEmulator.Runtime.AASMenu;\nnamespace NAK.AASEmulator.Editor\n{\n [CustomEditor(typeof(AASMenu))]\n public class AASMenuEditor : UnityEditor.Editor", "score": 0.8946102857589722 }, { "filename": "Editor/AASEmulatorSupport.cs", "retrieved_chunk": "using System.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nnamespace NAK.AASEmulator.Support\n{\n [InitializeOnLoad]\n public static class AASEmulatorSupport\n {\n static AASEmulatorSupport()", "score": 0.8390090465545654 }, { "filename": "Runtime/Scripts/AASMenu.cs", "retrieved_chunk": "using ABI.CCK.Scripts;\nusing NAK.AASEmulator.Runtime.SubSystems;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing static ABI.CCK.Scripts.CVRAdvancedSettingsEntry;\nnamespace NAK.AASEmulator.Runtime\n{\n [AddComponentMenu(\"\")]\n public class AASMenu : EditorOnlyMonoBehaviour\n {", "score": 0.8215702176094055 }, { "filename": "Runtime/Scripts/AASEmulatorRuntime.cs", "retrieved_chunk": "using ABI.CCK.Components;\nusing NAK.AASEmulator.Runtime.SubSystems;\nusing System;\nusing UnityEngine;\nnamespace NAK.AASEmulator.Runtime\n{\n [AddComponentMenu(\"\")]\n [HelpURL(\"https://github.com/NotAKidOnSteam/AASEmulator\")]\n public class AASEmulatorRuntime : EditorOnlyMonoBehaviour\n {", "score": 0.8147669434547424 }, { "filename": "Runtime/Scripts/AASEmulator.cs", "retrieved_chunk": "using ABI.CCK.Components;\nusing System.Collections.Generic;\nusing System.Linq;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nnamespace NAK.AASEmulator.Runtime\n{\n public class AASEmulator : MonoBehaviour\n {\n #region Support Delegates", "score": 0.7827510833740234 } ]
csharp
AASEmulatorRuntime _targetScript;
using LassoProcessManager.Models.Rules; using Newtonsoft.Json; using ProcessManager.Models.Configs; using System.Reflection; namespace ProcessManager.Providers { public class ConfigProvider : IConfigProvider { private const string ConfigFileName = "Config.json"; private
ManagerConfig managerConfig;
private ILogProvider LogProvider { get; set; } public ConfigProvider(ILogProvider logProvider) => this.LogProvider = logProvider; public ManagerConfig GetManagerConfig() { if (managerConfig != null) return managerConfig; string configPath = GetConfigFilePath(); try { managerConfig = JsonConvert.DeserializeObject<ManagerConfig>(File.ReadAllText(GetConfigFilePath())); return managerConfig; } catch { LogProvider.Log($"Failed to load config at '{configPath}'."); } return null; } public List<BaseRule> GetRules() { List<BaseRule> rules = new List<BaseRule>(); rules.AddRange(managerConfig.ProcessRules); rules.AddRange(managerConfig.FolderRules); return rules; } public Dictionary<string, LassoProfile> GetLassoProfiles() { Dictionary<string, LassoProfile> lassoProfiles = new Dictionary<string, LassoProfile>(); // Load lasso profiles foreach (var profile in managerConfig.Profiles) { if (!lassoProfiles.ContainsKey(profile.Name)) { lassoProfiles.Add(profile.Name, profile); } } return lassoProfiles; } private string GetConfigFilePath() => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName); } }
ProcessManager/Providers/ConfigProvider.cs
kenshinakh1-LassoProcessManager-bcc481f
[ { "filename": "ProcessManager/Providers/IConfigProvider.cs", "retrieved_chunk": "using LassoProcessManager.Models.Rules;\nusing ProcessManager.Models.Configs;\nnamespace ProcessManager.Providers\n{\n public interface IConfigProvider\n {\n /// <summary>\n /// Read the config files.\n /// </summary>\n /// <returns></returns>", "score": 0.8651750087738037 }, { "filename": "ProcessManager/Program.cs", "retrieved_chunk": "using ProcessManager.Managers;\nusing ProcessManager.Providers;\nusing System.Diagnostics;\nusing System.Management;\nnamespace ProcessManager\n{\n internal class Program\n {\n static void Main(string[] args)\n {", "score": 0.8576633930206299 }, { "filename": "ProcessManager/Managers/LassoManager.cs", "retrieved_chunk": "using LassoProcessManager.Models.Rules;\nusing ProcessManager.Models.Configs;\nusing ProcessManager.Providers;\nusing System.Diagnostics;\nusing System.Management;\nnamespace ProcessManager.Managers\n{\n public class LassoManager : ILassoManager\n {\n private Dictionary<string, LassoProfile> lassoProfiles;", "score": 0.8536763191223145 }, { "filename": "ProcessManager/Models/Configs/ManagerConfig.cs", "retrieved_chunk": "using LassoProcessManager.Models.Rules;\nnamespace ProcessManager.Models.Configs\n{\n public class ManagerConfig\n {\n /// <summary>\n /// Indicates to auto apply default profile for processes when no profiles are assigned.\n /// </summary>\n public bool AutoApplyDefaultProfile { get; set; }\n /// <summary>", "score": 0.8120049834251404 }, { "filename": "ProcessManager/Models/Rules/FolderRule.cs", "retrieved_chunk": "using System.Diagnostics;\nnamespace LassoProcessManager.Models.Rules\n{\n public class FolderRule : BaseRule\n {\n public string FolderPath { get; set; }\n public override bool IsMatchForRule(Process process)\n {\n try\n {", "score": 0.8084928393363953 } ]
csharp
ManagerConfig managerConfig;
using System.Diagnostics; namespace HikariEditor { internal class LaTeX { async public static Task<bool> Compile(MainWindow mainWindow, FileItem fileItem,
Editor editor) {
bool tex_compile_error = false; try { using (Process process = new()) { process.StartInfo.UseShellExecute = false; process.StartInfo.FileName = "C:\\texlive\\2022\\bin\\win32\\ptex2pdf.exe"; process.StartInfo.CreateNoWindow = true; process.StartInfo.Arguments = $"-l -ot -interaction=nonstopmode -halt-on-error -kanji=utf8 -output-directory=\"{fileItem.Dirname}\" \"{fileItem.Path}\""; process.StartInfo.RedirectStandardOutput = true; process.Start(); string stdout = process.StandardOutput.ReadToEnd(); await process.WaitForExitAsync(); //Debug.WriteLine(stdout); if (process.ExitCode == 0) { mainWindow.StatusBar.Text = $"{fileItem.Name} のコンパイルに成功しました。"; LogPage.AddLog(mainWindow, $"{fileItem.Name} のコンパイルに成功しました。"); } else { mainWindow.StatusBar.Text = $"{fileItem.Name} のコンパイルに失敗しました。"; LogPage.AddLog(mainWindow, $"{fileItem.Name} のコンパイルに失敗しました。"); Error.Dialog("LaTeX コンパイルエラー", stdout, mainWindow.Content.XamlRoot); tex_compile_error = true; } editor.Counter++; editor.DelayResetStatusBar(1000); } if (!tex_compile_error) { FileItem pdfFileItem = new(fileItem.Dirname, $"{fileItem.WithoutName}.pdf"); PDFPageInfo pdfPageInfo = new() { mainWindow = mainWindow, fileItem = pdfFileItem }; mainWindow.previewFrame.Navigate(typeof(PDF), pdfPageInfo); } } catch (Exception e) { Debug.WriteLine(e.Message); } return !tex_compile_error; } } }
HikariEditor/LaTeX.cs
Himeyama-HikariEditor-c37f978
[ { "filename": "HikariEditor/Preview/PDFPageInfo.cs", "retrieved_chunk": "namespace HikariEditor\n{\n internal class PDFPageInfo\n {\n public MainWindow? mainWindow;\n public FileItem? fileItem;\n }\n}", "score": 0.8519883751869202 }, { "filename": "HikariEditor/Explorer/NewFile.xaml.cs", "retrieved_chunk": "using Microsoft.UI.Xaml.Controls;\nnamespace HikariEditor\n{\n public sealed partial class NewFile : Page\n {\n public NewFile()\n {\n this.InitializeComponent();\n }\n }", "score": 0.8244933485984802 }, { "filename": "HikariEditor/Search.xaml.cs", "retrieved_chunk": "using Microsoft.UI.Xaml.Controls;\nnamespace HikariEditor\n{\n public sealed partial class Search : Page\n {\n public Search()\n {\n this.InitializeComponent();\n }\n }", "score": 0.8173226714134216 }, { "filename": "HikariEditor/Text.cs", "retrieved_chunk": "using System;\nusing System.Text;\nnamespace HikariEditor\n{\n public class Text\n {\n public string text { get; set; }\n public Text(string text)\n {\n this.text = text;", "score": 0.8120934367179871 }, { "filename": "HikariEditor/Preview/PDF.xaml.cs", "retrieved_chunk": "using Microsoft.UI.Xaml.Controls;\nusing Microsoft.UI.Xaml.Navigation;\nnamespace HikariEditor\n{\n public sealed partial class PDF : Page\n {\n MainWindow? mainWindow;\n FileItem? fileItem;\n protected override void OnNavigatedTo(NavigationEventArgs e)\n {", "score": 0.8097474575042725 } ]
csharp
Editor editor) {
using Microsoft.Azure.Cosmos; using System.Net; namespace CloudDistributedLock { public class CosmosLockClient { private readonly CloudDistributedLockProviderOptions options; private readonly Container container; public CosmosLockClient(CloudDistributedLockProviderOptions options) { this.options = options; this.container = options.CosmosClient!.GetContainer(options.DatabaseName, options.ContainerName); } public async Task<ItemResponse<
LockRecord>?> TryAquireLockAsync(string name) {
try { /* This will successfully insert the document if no other process is currently holding a lock. * The collection is set with a TTL so that the record will be deleted automatically, * releasing the lock in the event that it is not released by the holder. * */ var safeLockName = GenerateSafeLockName(name); var now = DateTimeOffset.UtcNow; var lockRecord = new LockRecord { id = safeLockName, name = name, providerName = options.ProviderName, lockObtainedAt = now, lockLastRenewedAt = now, _ttl = options.TTL }; return await container.CreateItemAsync(lockRecord, new PartitionKey(lockRecord.id)); } catch (CosmosException ex) { if (ex.StatusCode == HttpStatusCode.Conflict) { // lock already held by someone else return null; } throw; } } public async Task<ItemResponse<LockRecord>?> RenewLockAsync(ItemResponse<LockRecord> item) { try { var lockRecord = item.Resource; lockRecord.lockLastRenewedAt = DateTimeOffset.UtcNow; return await container.UpsertItemAsync(lockRecord, new PartitionKey(lockRecord.id), new ItemRequestOptions { IfMatchEtag = item.ETag }); } catch (CosmosException ex) { if (ex.StatusCode == HttpStatusCode.PreconditionFailed) { // someone else already acquired a new lock, which means our lock was already released return null; } throw; } } public async Task ReleaseLockAsync(ItemResponse<LockRecord> item) { try { var lockRecord = item.Resource; _ = await container.DeleteItemAsync<LockRecord>(lockRecord.id, new PartitionKey(lockRecord.id), new ItemRequestOptions { IfMatchEtag = item.ETag }); } catch (CosmosException ex) { if (ex.StatusCode == HttpStatusCode.PreconditionFailed) { // someone else already acquired a new lock, which means our lock was already released } } } private static string GenerateSafeLockName(string lockName) { //'/', '\\', '?', '#' are invalid return lockName.Replace('/', '_').Replace('\\', '_').Replace('?', '_').Replace('#', '_'); } } }
CloudDistributedLock/CosmosLockClient.cs
briandunnington-CloudDistributedLock-04f72e6
[ { "filename": "CloudDistributedLock/CloudDistributedLockProvider.cs", "retrieved_chunk": " private readonly CosmosLockClient cosmosLockClient;\n public CloudDistributedLockProvider(CloudDistributedLockProviderOptions options)\n {\n this.options = options;\n this.cosmosLockClient = new CosmosLockClient(options);\n }\n public async Task<CloudDistributedLock> AcquireLockAsync(string name, TimeSpan? timeout = null)\n {\n using var cancellationTokenSource = timeout.HasValue ? new CancellationTokenSource(timeout.Value) : new CancellationTokenSource();\n return await ContinuallyTryAquireLockAsync(name, cancellationTokenSource.Token);", "score": 0.8991674780845642 }, { "filename": "CloudDistributedLock/CloudDistributedLock.cs", "retrieved_chunk": " private Timer? timer;\n private bool isDisposed;\n public static CloudDistributedLock CreateUnacquiredLock()\n {\n return new CloudDistributedLock();\n }\n public static CloudDistributedLock CreateAcquiredLock(CosmosLockClient cosmosLockClient, ItemResponse<LockRecord> item)\n {\n return new CloudDistributedLock(cosmosLockClient, item);\n }", "score": 0.8707258105278015 }, { "filename": "CloudDistributedLock/ServiceCollectionExtensions.cs", "retrieved_chunk": " }\n public static IServiceCollection AddCloudDistributedLock(this IServiceCollection services, CosmosClient cosmosClient, string databaseName, int ttl, Action<CloudDistributedLockProviderOptions>? configureOptions = null)\n {\n return services.AddCloudDistributedLock(CloudDistributedLockProviderFactory.DefaultName, cosmosClient, databaseName, ttl, configureOptions);\n }\n public static IServiceCollection AddCloudDistributedLock(this IServiceCollection services, string name, string cosmosEndpoint, string cosmosKey, string databaseName, int ttl, Action<CloudDistributedLockProviderOptions>? configureOptions = null)\n {\n var cosmosClient = new CosmosClient(cosmosEndpoint, cosmosKey);\n return services.AddCloudDistributedLock(name, cosmosClient, databaseName, ttl, configureOptions);\n }", "score": 0.8412549495697021 }, { "filename": "CloudDistributedLock/ServiceCollectionExtensions.cs", "retrieved_chunk": "using Microsoft.Azure.Cosmos;\nusing Microsoft.Extensions.DependencyInjection;\nnamespace CloudDistributedLock\n{\n public static class ServiceCollectionExtensions\n {\n public static IServiceCollection AddCloudDistributedLock(this IServiceCollection services, string cosmosEndpoint, string cosmosKey, string databaseName, int ttl, Action<CloudDistributedLockProviderOptions>? configureOptions = null)\n {\n var cosmosClient = new CosmosClient(cosmosEndpoint, cosmosKey);\n return services.AddCloudDistributedLock(CloudDistributedLockProviderFactory.DefaultName, cosmosClient, databaseName, ttl, configureOptions);", "score": 0.8363544940948486 }, { "filename": "CloudDistributedLock/CloudDistributedLockProviderFactory.cs", "retrieved_chunk": " {\n internal const string DefaultName = \"__DEFAULT\";\n private readonly ConcurrentDictionary<string, ICloudDistributedLockProvider> clients = new();\n public CloudDistributedLockProviderFactory(IOptionsMonitor<CloudDistributedLockProviderOptions> optionsMonitor)\n {\n this.OptionsMonitor = optionsMonitor;\n }\n protected IOptionsMonitor<CloudDistributedLockProviderOptions> OptionsMonitor { get; }\n public ICloudDistributedLockProvider GetLockProvider(string name)\n {", "score": 0.8362737894058228 } ]
csharp
LockRecord>?> TryAquireLockAsync(string name) {
using NowPlaying.Utils; using System.Collections.Generic; using System.Threading; namespace NowPlaying.Models { public class GameCacheJob { public readonly GameCacheEntry entry; public readonly
RoboStats stats;
public readonly CancellationTokenSource tokenSource; public readonly CancellationToken token; public PartialFileResumeOpts pfrOpts; public long? partialFileResumeThresh; public int interPacketGap; public bool cancelledOnDiskFull; public bool cancelledOnMaxFill; public bool cancelledOnError; public List<string> errorLog; public GameCacheJob(GameCacheEntry entry, RoboStats stats=null, int interPacketGap = 0, PartialFileResumeOpts pfrOpts = null) { this.entry = entry; this.tokenSource = new CancellationTokenSource(); this.token = tokenSource.Token; this.stats = stats; this.pfrOpts = pfrOpts; this.interPacketGap = interPacketGap; this.cancelledOnDiskFull = false; this.cancelledOnMaxFill = false; this.cancelledOnError = false; this.errorLog = null; bool partialFileResume = pfrOpts?.Mode == EnDisThresh.Enabled || pfrOpts?.Mode == EnDisThresh.Threshold && pfrOpts?.FileSizeThreshold <= 0; stats?.Reset(entry.InstallFiles, entry.InstallSize, partialFileResume); } public override string ToString() { return $"{entry} {stats} Ipg:{interPacketGap} PfrOpts:[{pfrOpts}] OnDiskFull:{cancelledOnDiskFull} OnError:{cancelledOnError} ErrorLog:{errorLog}"; } } }
source/Models/GameCacheJob.cs
gittromney-Playnite-NowPlaying-23eec41
[ { "filename": "source/ViewModels/GameViewModel.cs", "retrieved_chunk": "using NowPlaying.Models;\nusing NowPlaying.Utils;\nusing Playnite.SDK.Models;\nusing System.Linq;\nnamespace NowPlaying.ViewModels\n{\n public class GameViewModel : ViewModelBase\n {\n public readonly Game game;\n public string Title => game.Name;", "score": 0.9121233224868774 }, { "filename": "source/ViewModels/GameCacheViewModel.cs", "retrieved_chunk": "using NowPlaying.Utils;\nusing NowPlaying.Models;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nnamespace NowPlaying.ViewModels\n{\n public class GameCacheViewModel : ObservableObject\n {\n private readonly NowPlaying plugin;", "score": 0.9011733531951904 }, { "filename": "source/ViewModels/TopPanelViewModel.cs", "retrieved_chunk": "using NowPlaying.Utils;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nnamespace NowPlaying.ViewModels\n{\n public class TopPanelViewModel : ViewModelBase\n {\n public enum Mode { Processing, Enable, Uninstall, Install, SlowInstall };\n private readonly NowPlaying plugin;", "score": 0.8959150910377502 }, { "filename": "source/ViewModels/GameCacheManagerViewModel.cs", "retrieved_chunk": "using static NowPlaying.Models.GameCacheManager;\nusing Playnite.SDK;\nnamespace NowPlaying.ViewModels\n{\n public class GameCacheManagerViewModel : ViewModelBase\n {\n public readonly NowPlaying plugin;\n public readonly ILogger logger;\n private readonly string pluginUserDataPath;\n private readonly string cacheRootsJsonPath;", "score": 0.8931413292884827 }, { "filename": "source/ViewModels/CacheRootViewModel.cs", "retrieved_chunk": "using NowPlaying.Utils;\nusing NowPlaying.Models;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nnamespace NowPlaying.ViewModels\n{\n public class CacheRootViewModel : ObservableObject\n {\n public readonly GameCacheManagerViewModel manager;", "score": 0.8861907124519348 } ]
csharp
RoboStats stats;
using LibreDteDotNet.RestRequest.Interfaces; namespace LibreDteDotNet.RestRequest.Infraestructure { public class RestRequest { public ILibro Libro { get; } public IContribuyente Contribuyente { get; } public IFolioCaf FolioCaf { get; } public IBoleta Boleta { get; } public IDTE DocumentoTributario { get; } public RestRequest( ILibro libroService, IContribuyente contribuyenteService, IFolioCaf folioCafService,
IBoleta boletaService, IDTE dTEService ) {
Libro = libroService; Contribuyente = contribuyenteService; FolioCaf = folioCafService; Boleta = boletaService; DocumentoTributario = dTEService; } } }
LibreDteDotNet.RestRequest/Infraestructure/RestRequest.cs
sergiokml-LibreDteDotNet.RestRequest-6843109
[ { "filename": "LibreDteDotNet.RestRequest/Interfaces/IBoleta.cs", "retrieved_chunk": "namespace LibreDteDotNet.RestRequest.Interfaces\n{\n public interface IBoleta\n {\n Task<IBoleta> SetCookieCertificado();\n Task<string> GetConsumoByFecha(\n string anoIni,\n string mesIni,\n string anoFin,\n string mesFin,", "score": 0.8311764001846313 }, { "filename": "LibreDteDotNet.RestRequest/Interfaces/IFolioCaf.cs", "retrieved_chunk": " string rut,\n string dv,\n string cant,\n string cantmax,\n TipoDoc tipodoc\n );\n Task<XDocument> Descargar();\n Task<IFolioCaf> SetCookieCertificado();\n Task<Dictionary<string, string>> GetRangoMax(string rut, string dv, TipoDoc tipodoc);\n Task<IFolioCaf> Confirmar();", "score": 0.8257002830505371 }, { "filename": "LibreDteDotNet.RestRequest/Extensions/DTEExtension.cs", "retrieved_chunk": " public static async Task<string> Enviar(\n this Task<IDTE> folioService,\n string rutCompany,\n string DvCompany\n )\n {\n IDTE instance = await folioService;\n return await instance.Enviar(rutCompany, DvCompany);\n }\n }", "score": 0.8244161009788513 }, { "filename": "LibreDteDotNet.RestRequest/Extensions/BoletaExtension.cs", "retrieved_chunk": "using LibreDteDotNet.RestRequest.Interfaces;\nnamespace LibreDteDotNet.RestRequest.Extensions\n{\n public static class BoletaExtension\n {\n public static IBoleta Conectar(this IBoleta folioService)\n {\n IBoleta instance = folioService;\n return instance.SetCookieCertificado().Result;\n }", "score": 0.8126325607299805 }, { "filename": "LibreDteDotNet.RestRequest/Extensions/ContribuyenteExtension.cs", "retrieved_chunk": "using LibreDteDotNet.RestRequest.Interfaces;\nnamespace LibreDteDotNet.RestRequest.Extensions\n{\n public static class ContribuyenteExtension\n {\n public static IContribuyente Conectar(this IContribuyente folioService)\n {\n IContribuyente instance = folioService;\n return instance.SetCookieCertificado().Result;\n }", "score": 0.8124073147773743 } ]
csharp
IBoleta boletaService, IDTE dTEService ) {
using BenchmarkDotNet.Attributes; using HybridRedisCache; using Microsoft.Extensions.Caching.Memory; using StackExchange.Redis; using System; using System.Linq; using System.Text.Json; using System.Threading.Tasks; namespace RedisCache.Benchmark { //[MemoryDiagnoser] [Orderer(BenchmarkDotNet.Order.SummaryOrderPolicy.FastestToSlowest)] public class BenchmarkManager { IMemoryCache _memCache;
ICacheService _redisCache;
EasyHybridCache _easyHybridCache; HybridCache _hybridCache; const int redisPort = 6379; const string redisIP = "127.0.0.1"; // "172.23.44.11" "127.0.0.1" const string KeyPrefix = "test_"; const string ReadKeyPrefix = "test_x"; const int ExpireDurationSecond = 3600; static SampleModel[] _data; static Lazy<SampleModel> _singleModel = new Lazy<SampleModel>(() => _data[0], true); static Lazy<SampleModel> _singleWorseModel = new Lazy<SampleModel>(() => _data[1], true); [Params(1, 10, 100)] public int RepeatCount { get; set; } [GlobalSetup] public void GlobalSetup() { // Write your initialization code here var connection = ConnectionMultiplexer.Connect($"{redisIP}:{redisPort}"); _redisCache = new CacheService(connection); _memCache = new MemoryCache(new MemoryCacheOptions()); _easyHybridCache = new EasyHybridCache(redisIP, redisPort); _data ??= Enumerable.Range(0, 10000).Select(_ => SampleModel.Factory()).ToArray(); _hybridCache = new HybridCache(new HybridCachingOptions() { InstanceName = nameof(BenchmarkManager), DefaultDistributedExpirationTime = TimeSpan.FromDays(1), DefaultLocalExpirationTime = TimeSpan.FromMinutes(10), RedisCacheConnectString = $"{redisIP}:{redisPort}", ThrowIfDistributedCacheError = false }); } [Benchmark(Baseline = true)] public void Add_InMemory() { // write cache for (var i = 0; i < RepeatCount; i++) _memCache.Set(KeyPrefix + i, JsonSerializer.Serialize(_data[i]), DateTimeOffset.Now.AddSeconds(ExpireDurationSecond)); } [Benchmark] public async Task Add_InMemory_Async() { // write cache for (var i = 0; i < RepeatCount; i++) await _memCache.GetOrCreateAsync(KeyPrefix + i, _ => Task.FromResult(JsonSerializer.Serialize(_data[i]))); } [Benchmark] public void Add_Redis() { // write cache for (var i = 0; i < RepeatCount; i++) _redisCache.AddOrUpdate(KeyPrefix + i, _data[i], DateTimeOffset.Now.AddSeconds(ExpireDurationSecond)); } [Benchmark] public async Task Add_Redis_Async() { // write cache for (var i = 0; i < RepeatCount; i++) await _redisCache.AddOrUpdateAsync(KeyPrefix + i, _data[i], DateTimeOffset.Now.AddSeconds(ExpireDurationSecond)); } [Benchmark] public void Add_Redis_With_FireAndForget() { // write cache for (var i = 0; i < RepeatCount; i++) _redisCache.AddOrUpdate(KeyPrefix + i, _data[i], DateTimeOffset.Now.AddSeconds(ExpireDurationSecond), true); } [Benchmark] public async Task Add_Redis_With_FireAndForget_Async() { // write cache for (var i = 0; i < RepeatCount; i++) await _redisCache.AddOrUpdateAsync(KeyPrefix + i, _data[i], DateTimeOffset.Now.AddSeconds(ExpireDurationSecond), true); } [Benchmark] public void Add_EasyCache_Hybrid() { // write cache for (var i = 0; i < RepeatCount; i++) _easyHybridCache.Set(KeyPrefix + i, _data[i], TimeSpan.FromSeconds(ExpireDurationSecond)); } [Benchmark] public async Task Add_EasyCache_Hybrid_Async() { // write cache for (var i = 0; i < RepeatCount; i++) await _easyHybridCache.SetAsync(KeyPrefix + i, _data[i], TimeSpan.FromSeconds(ExpireDurationSecond)); } [Benchmark] public void Add_HybridRedisCache() { // write cache for (var i = 0; i < RepeatCount; i++) _hybridCache.Set(KeyPrefix + i, _data[i], TimeSpan.FromSeconds(ExpireDurationSecond), fireAndForget: true); } [Benchmark] public async Task Add_HybridRedisCache_Async() { // write cache for (var i = 0; i < RepeatCount; i++) await _hybridCache.SetAsync(KeyPrefix + i, _data[i], TimeSpan.FromSeconds(ExpireDurationSecond), fireAndForget: true); } [Benchmark] public void Get_InMemory() { // write single cache _memCache.Set(ReadKeyPrefix, _singleModel.Value, DateTimeOffset.Now.AddSeconds(ExpireDurationSecond)); // read cache for (var i = 0; i < RepeatCount; i++) if (_memCache.TryGetValue(ReadKeyPrefix, out string value)) ThrowIfIsNotMatch(JsonSerializer.Deserialize<SampleModel>(value), _singleModel.Value); } [Benchmark] public async Task Get_InMemory_Async() { // write single cache _memCache.Set(ReadKeyPrefix, JsonSerializer.Serialize(_singleModel.Value), DateTimeOffset.Now.AddSeconds(ExpireDurationSecond)); // read cache for (var i = 0; i < RepeatCount; i++) { // don't generate correct data when couldn't find, because its already wrote! var value = await _memCache.GetOrCreateAsync(ReadKeyPrefix, _ => Task.FromResult(JsonSerializer.Serialize(_singleWorseModel.Value))); ThrowIfIsNotMatch(JsonSerializer.Deserialize<SampleModel>(value), _singleModel.Value); } } [Benchmark] public void Get_Redis() { // write single cache _redisCache.AddOrUpdate(ReadKeyPrefix, _singleModel.Value, DateTimeOffset.Now.AddSeconds(ExpireDurationSecond)); // read cache for (var i = 0; i < RepeatCount; i++) if (_redisCache.TryGetValue(ReadKeyPrefix, out SampleModel value)) ThrowIfIsNotMatch(value, _singleModel.Value); } [Benchmark] public async Task Get_Redis_Async() { // write single cache await _redisCache.AddOrUpdateAsync(ReadKeyPrefix, _singleModel.Value, DateTimeOffset.Now.AddSeconds(ExpireDurationSecond)); // read cache for (var i = 0; i < RepeatCount; i++) { // don't generate correct data when couldn't find, because its already wrote! var value = await _redisCache.GetAsync(ReadKeyPrefix, () => Task.FromResult(_singleWorseModel.Value), ExpireDurationSecond); ThrowIfIsNotMatch(value, _singleModel.Value); } } [Benchmark] public void Get_EasyCache_Hybrid() { // write single cache _easyHybridCache.Set(ReadKeyPrefix, _singleModel.Value, TimeSpan.FromSeconds(ExpireDurationSecond)); // read cache for (var i = 0; i < RepeatCount; i++) { // don't generate correct data when couldn't find, because its already wrote! var value = _easyHybridCache.Get<SampleModel>(ReadKeyPrefix); if (value == null) throw new ArgumentNullException(nameof(value)); } } [Benchmark] public async Task Get_EasyCache_Hybrid_Async() { // write single cache await _easyHybridCache.SetAsync(ReadKeyPrefix, _singleModel.Value, TimeSpan.FromSeconds(ExpireDurationSecond)); // read cache for (var i = 0; i < RepeatCount; i++) { // don't generate correct data when couldn't find, because its already wrote! var value = await _easyHybridCache.GetAsync<SampleModel>(ReadKeyPrefix); if (value == null) throw new ArgumentNullException(nameof(value)); } } [Benchmark] public void Get_HybridRedisCache() { // write single cache _hybridCache.Set(ReadKeyPrefix, _singleModel.Value, TimeSpan.FromSeconds(ExpireDurationSecond), fireAndForget: true); // read cache for (var i = 0; i < RepeatCount; i++) { // don't generate correct data when couldn't find, because its already wrote! var value = _easyHybridCache.Get<SampleModel>(ReadKeyPrefix); if (value == null) throw new ArgumentNullException(nameof(value)); } } [Benchmark] public async Task Get_HybridRedisCache_Async() { // write single cache await _hybridCache.SetAsync(ReadKeyPrefix, _singleModel.Value, TimeSpan.FromSeconds(ExpireDurationSecond), fireAndForget: true); // read cache for (var i = 0; i < RepeatCount; i++) { // don't generate correct data when couldn't find, because its already wrote! var value = await _hybridCache.GetAsync<SampleModel>(ReadKeyPrefix); if (value == null) throw new ArgumentNullException(nameof(value)); } } private void ThrowIfIsNotMatch(SampleModel a, SampleModel b) { if (a?.Id != b?.Id) throw new ArrayTypeMismatchException($"value.Id({a?.Id} not equal with _data[i].Id({b?.Id}"); } } }
src/RedisCache.Benchmark/BenchmarkManager.cs
bezzad-RedisCache.NetDemo-655b311
[ { "filename": "src/RedisCache.Benchmark/EasyHybridCache.cs", "retrieved_chunk": "using EasyCaching.Core;\nusing EasyCaching.Core.Configurations;\nusing Microsoft.Extensions.DependencyInjection;\nusing System;\nusing System.Threading.Tasks;\nnamespace RedisCache.Benchmark\n{\n public class EasyHybridCache\n {\n private readonly IHybridCachingProvider _provider;", "score": 0.8335704803466797 }, { "filename": "src/RedisCache/CacheService.cs", "retrieved_chunk": "using StackExchange.Redis;\nusing System;\nusing System.Text.Json;\nusing System.Threading.Tasks;\nnamespace RedisCache\n{\n public class CacheService : ICacheService\n {\n private IDatabase _db;\n public CacheService(IConnectionMultiplexer connection)", "score": 0.821420431137085 }, { "filename": "src/RedisCache.Benchmark/Program.cs", "retrieved_chunk": " static BenchmarkManager Manager = new() { RepeatCount = 1000 };\n private static async Task Main()\n {\n Console.Title = \"Redis vs. Mem cache benchmark\";\n#if !DEBUG\n BenchmarkDotNet.Running.BenchmarkRunner.Run<BenchmarkManager>();\n#else\n var timesOfExecutions = new Dictionary<string, double>();\n var sw = new System.Diagnostics.Stopwatch();\n Manager.GlobalSetup();", "score": 0.757049560546875 }, { "filename": "src/RedisCache.Benchmark/Program.cs", "retrieved_chunk": "// See https://aka.ms/new-console-template for more information\nusing BenchmarkDotNet.Attributes;\nusing RedisCache.Benchmark;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Threading.Tasks;\npublic class Program\n{", "score": 0.7496482133865356 }, { "filename": "src/RedisCache.Demo/Controllers/WeatherForecastController.cs", "retrieved_chunk": "using Microsoft.AspNetCore.Mvc;\nusing RedisCache;\nnamespace RedisCacheDemo.Controllers\n{\n [ApiController]\n [Route(\"[controller]\")]\n public class WeatherForecastController : ControllerBase\n {\n private static readonly string[] Summaries = new[]\n {", "score": 0.7476508617401123 } ]
csharp
ICacheService _redisCache;
using Gum.InnerThoughts; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; using System.Text.RegularExpressions; namespace Gum.Tests { [TestClass] public class Bungee { private
CharacterScript? Read(string input) {
string[] lines = Regex.Split(input, @"\r?\n|\r"); Parser parser = new("Test", lines); return parser.Start(); } [TestMethod] public void TestSerialization() { const string path = "./resources"; CharacterScript[] results = Reader.Parse(path, lastModified: null, out string errors); Assert.IsTrue(string.IsNullOrEmpty(errors)); Assert.AreEqual(1, results.Length); IEnumerable<Situation> situations = results[0].FetchAllSituations(); Assert.AreEqual(3, situations.Count()); } [TestMethod] public void TestDeserialization() { const string path = "./resources"; CharacterScript[] results = Reader.Parse(path, lastModified: null, out string errors); Assert.IsTrue(string.IsNullOrEmpty(errors)); Assert.AreEqual(1, results.Length); CharacterScript script = results[0]; string json = JsonConvert.SerializeObject(script, Reader.Settings); CharacterScript? deserializedScript = JsonConvert.DeserializeObject<CharacterScript>(json); Assert.IsNotNull(deserializedScript); IEnumerable<Situation> situations = deserializedScript.FetchAllSituations(); Assert.AreEqual(3, situations.Count()); } [TestMethod] public void TestSingleSentence() { const string situationText = @" =Encounter I just have one sentence."; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(target.Owner, 0); CollectionAssert.AreEqual(new int[] { 1 }, target.Blocks); } [TestMethod] public void TestSingleCondition() { const string situationText = @" =Encounter (!HasSeenThis) Wow! Have you seen this?"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Block block = situation.Blocks[1]; Assert.AreEqual(1, block.Requirements.Count); Assert.AreEqual(CriterionNodeKind.And, block.Requirements[0].Kind); Assert.AreEqual(CriterionKind.Different, block.Requirements[0].Criterion.Kind); Assert.AreEqual(true, block.Requirements[0].Criterion.BoolValue); } [TestMethod] public void TestSingleSentenceWithSpeaker() { const string situationText = @" =Encounter speaker.happy: I just have one sentence."; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(target.Owner, 0); CollectionAssert.AreEqual(new int[] { 1 }, target.Blocks); } [TestMethod] public void TestSimpleIf() { const string situationText = @" =Encounter (LikeFishes) Wow, I love fishes! (...) Ugh, I hate fishes."; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 2 }, target.Blocks); } [TestMethod] public void TestOrderChoice() { const string situationText = @" =Encounter @order - Hello + Bye! -> exit!"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.HighestScore, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 2 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 3 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 3 }, target.Blocks); } [TestMethod] public void TestChoicesWithRules() { const string situationText = @" =Encounter - (HasIceCream) This seems a pretty good ice cream. - (!HasIceCream) What do you have there?? - (WithoutCoins and HasIceCream) Maybe you want to sell that ice cream of yours?"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.HighestScore, target.Kind); Assert.AreEqual(target.Owner, 0); CollectionAssert.AreEqual(new int[] { 1, 2, 3 }, target.Blocks); Block block = situation.Blocks[1]; Assert.AreEqual(1, block.Requirements.Count); Assert.AreEqual(1, block.Lines.Count); block = situation.Blocks[2]; Assert.AreEqual(1, block.Requirements.Count); Assert.AreEqual(1, block.Lines.Count); block = situation.Blocks[3]; Assert.AreEqual(2, block.Requirements.Count); Assert.AreEqual(1, block.Lines.Count); } [TestMethod] public void TestLineAfterChoice() { const string situationText = @" =Dinner (Socks >= 5) Do you hate socks! >> Hate socks? > Hell yeah! -> exit! > Why would I? -> exit! Okay, bye!"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 7 }, target.Blocks); target = situation.Edges[1]; // Uhhh this block 7 shouldn't really be here, but I am okay with // this compromise. Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Choice, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 3, 5 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4 }, target.Blocks); target = situation.Edges[5]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(5, target.Owner); CollectionAssert.AreEqual(new int[] { 6 }, target.Blocks); } [TestMethod] public void TestOptionsWithChoices() { const string situationText = @" =Choice + >> Settle down for a while? > Rest my eyes... [c:SaveCheckpointInteraction] > Keep going. + >> Do you want it all to be all right? > Just for a while. [c:SaveCheckpointInteraction] > Not now."; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.HighestScore, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 6 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Choice, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 3, 5 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4 }, target.Blocks); target = situation.Edges[6]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(6, target.Owner); CollectionAssert.AreEqual(new int[] { 7 }, target.Blocks); target = situation.Edges[7]; Assert.AreEqual(EdgeKind.Choice, target.Kind); Assert.AreEqual(7, target.Owner); CollectionAssert.AreEqual(new int[] { 8, 10 }, target.Blocks); target = situation.Edges[8]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(8, target.Owner); CollectionAssert.AreEqual(new int[] { 9 }, target.Blocks); } [TestMethod] public void TestLineAfterChoiceWithoutLeaves() { const string situationText = @" =Dinner (Socks >= 5) Do you hate socks! >> Hate socks? > Hell yeah! Okay. > Why would I? Yeah?? Okay, bye!"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 7 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Choice, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 3, 5 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4 }, target.Blocks); target = situation.Edges[4]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 7 }, target.Blocks); target = situation.Edges[5]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(5, target.Owner); CollectionAssert.AreEqual(new int[] { 6 }, target.Blocks); target = situation.Edges[6]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(6, target.Owner); CollectionAssert.AreEqual(new int[] { 7 }, target.Blocks); } [TestMethod] public void TestChoiceWithAction() { const string situationText = @" =Dinner >> Hate socks? > Hell yeah! [FireOnSocks=true] > Why would I? [c:GoAwayInteraction]"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Choice, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2, 4 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 3 }, target.Blocks); target = situation.Edges[4]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 5 }, target.Blocks); } [TestMethod] public void TestChoiceWithNestedBlock() { const string situationText = @" =Dinner >> Hate socks? > Hell yeah! (LookForFire) Yes...? > Why would I? No!"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Choice, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2, 4 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 3 }, target.Blocks); target = situation.Edges[4]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 5 }, target.Blocks); } [TestMethod] public void TestElseAfterChoice() { const string situationText = @" =Dinner (Socks >= 5) Do you hate socks! >> Hate socks? > Hell yeah! -> DestroyAll > Why would I? -> Sorry (...Socks > 1 and Socks < 5) thief: What about socks that you hate? Everything!!!! (...) - thief: Actually, some shoes are okay. Ew. - thief: Can you not look at me? What if I do. + Happy birthday! I bought you socks. = DestroyAll = Sorry"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 7, 8 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Choice, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 3, 5 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4 }, target.Blocks); target = situation.Edges[5]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(5, target.Owner); CollectionAssert.AreEqual(new int[] { 6 }, target.Blocks); target = situation.Edges[8]; Assert.AreEqual(EdgeKind.HighestScore, target.Kind); Assert.AreEqual(8, target.Owner); CollectionAssert.AreEqual(new int[] { 9, 10, 11 }, target.Blocks); } [TestMethod] public void TestChoices() { const string situationText = @" =Chitchat - You are amazing. FOR A COOKER. - I'm sorry. I was rude there. I needed to come up with stuff. I actually did enjoy your food. + ... - The dead fly was on purpose, right?"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.HighestScore, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 2, 3, 4 }, target.Blocks); } [TestMethod] public void TestChoicesWithCondition() { const string situationText = @" =Choices - (!Eaten) I am FULL. - (!Eaten) I am soooooo stuffed. - (Hungry) DUDE I am hungry. [Eat=true] =Bye"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.HighestScore, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 2, 3 }, target.Blocks); } [TestMethod] public void TestNestedCondition1() { const string situationText = @" =Encounter @1 (!SawMe) Do you see anything? Of course not. [Variable=true] -> exit! (...) Okay you see me. I'm sorry. thief: For what? thief: I am simply existing here. -> Bye @1 (LookedAtLeft) -> Hey!? (!GotSword) (!Scared) What do you want? (...) @1 Please, stop. thief: Or what? -> Bye (...) -> Bye =Bye =Hey!?"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Assert.AreEqual(situation.Root, 0); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 4, 11 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2, 3 }, target.Blocks); target = situation.Edges[4]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 5 }, target.Blocks); target = situation.Edges[6]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(6, target.Owner); CollectionAssert.AreEqual(new int[] { 7, 8 }, target.Blocks); target = situation.Edges[8]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(8, target.Owner); CollectionAssert.AreEqual(new int[] { 9 }, target.Blocks); target = situation.Edges[11]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(11, target.Owner); CollectionAssert.AreEqual(new int[] { 6, 10 }, target.Blocks); } [TestMethod] public void TestNestedCondition2() { const string situationText = @" =Welcome @1 1! 2 (Three) 4 5 -> Bye (...) 6 7 [Condition=true] [c:Interaction] -> exit! (!Eight) 9 10 {i:Variable}! -> Bye (...!Eleven) (Twelve) @random + 13 + 14 (...) @random + 15 ... 16 + 17 -> exit! -> Bye =Bye"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Assert.AreEqual(situation.Name, "Welcome"); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 16 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2, 3 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4 }, target.Blocks); target = situation.Edges[6]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(6, target.Owner); CollectionAssert.AreEqual(new int[] { 8, 11 }, target.Blocks); target = situation.Edges[7]; Assert.AreEqual(target.Kind, EdgeKind.IfElse); Assert.AreEqual(target.Owner, 7); CollectionAssert.AreEqual(new int[] { 5, 6 }, target.Blocks); target = situation.Edges[8]; Assert.AreEqual(EdgeKind.Random, target.Kind); Assert.AreEqual(8, target.Owner); CollectionAssert.AreEqual(new int[] { 9, 10 }, target.Blocks); target = situation.Edges[9]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(9, target.Owner); CollectionAssert.AreEqual(new int[] { 14 }, target.Blocks); target = situation.Edges[10]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(10, target.Owner); CollectionAssert.AreEqual(new int[] { 14 }, target.Blocks); target = situation.Edges[11]; Assert.AreEqual(EdgeKind.Random, target.Kind); Assert.AreEqual(11, target.Owner); CollectionAssert.AreEqual(new int[] { 12, 13 }, target.Blocks); target = situation.Edges[12]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(12, target.Owner); CollectionAssert.AreEqual(new int[] { 14 }, target.Blocks); target = situation.Edges[13]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(13, target.Owner); CollectionAssert.AreEqual(new int[] { 14 }, target.Blocks); target = situation.Edges[16]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(16, target.Owner); CollectionAssert.AreEqual(new int[] { 7, 15 }, target.Blocks); } [TestMethod] public void TestNestedCondition3() { const string situationText = @" =Encounter @1 (!SawMe) Do you see anything? Of course not. [Variable=true] (...) Okay you see me. I'm sorry. thief: For what? thief: I am simply existing here. Bye. =Bye"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 4 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2, 3 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 4 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4 }, target.Blocks); } [TestMethod] public void TestNestedCondition4() { const string situationText = @" =Encounter @1 (!SawMe) Do you see anything? Of course not. [Variable=true] (...) Okay you see me. I'm sorry. thief: For what? thief: I am simply existing here. I guess? Bye. =Bye"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 5 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2, 3 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 4 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4 }, target.Blocks); target = situation.Edges[4]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 5 }, target.Blocks); } [TestMethod] public void TestNestedCondition5() { const string situationText = @" =Encounter @1 Hello. I do talk a lot. \(you might have noticed?\) SO. As I was saying- thief: What? Nevermind. (Defeated) WOW!! You did it! -> exit! // this will think that it's joining with the one above ^ @1 Can you go now? (!CanMove) thief: I would. If I wasn't STUCK. Wow wow wow! Hold on! What do you mean STUCK? thief: Stuck! Okay. (...) thief.happy: Yes. So go! Maybe I will! Okay. Okay. [Left=true] -> exit! @1 (Left and StillHere) thief.happy: Uhhhhhhhhhhhh -> exit! -> Random =Random"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 2, 3, 6, 8 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4, 5 }, target.Blocks); target = situation.Edges[4]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 6 }, target.Blocks); } [TestMethod] public void TestNestedCondition6() { const string situationText = @" =Encounter @1 (Defeated) Okay. I am here now. Right? [c:DoSomething] (...) Oh my. Congratulations. (WonInThePast) I don't care though. (...) I am super jealous. I hope you like the taste of victory. -> Random =Random"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 7 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2, 3 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 7 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4, 5 }, target.Blocks); target = situation.Edges[4]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 6 }, target.Blocks); target = situation.Edges[5]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(5, target.Owner); CollectionAssert.AreEqual(new int[] { 6 }, target.Blocks); target = situation.Edges[6]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(6, target.Owner); CollectionAssert.AreEqual(new int[] { 7 }, target.Blocks); } [TestMethod] public void TestNestedCondition7() { const string situationText = @" =Encounter (Meet and PreviouslySaidBye) @1 Hi! But only once. -> exit! (DatesTogether >= 1) I guess this is really like meeting again...? (...!StillHasJob) (ChocolateAmount == 0) @1 Out of chocolates? Again...? (...ChocolateAmount >= 1) - I mean, chocolates are great! - Until they aren't. (...) @1 I am embarassed. Bye. =Random"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 4, 10 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2, 3 }, target.Blocks); target = situation.Edges[4]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 5, 7 }, target.Blocks); target = situation.Edges[5]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(5, target.Owner); CollectionAssert.AreEqual(new int[] { 6 }, target.Blocks); target = situation.Edges[7]; Assert.AreEqual(EdgeKind.HighestScore, target.Kind); Assert.AreEqual(7, target.Owner); CollectionAssert.AreEqual(new int[] { 8, 9 }, target.Blocks); target = situation.Edges[10]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(10, target.Owner); CollectionAssert.AreEqual(new int[] { 11 }, target.Blocks); } [TestMethod] public void TestNestedCondition8() { const string situationText = @" =Encounter (!Meet and !Greet) @order - I will go now. + Hello!? -> exit!"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; // This edge currently has an extra edge to 4. // This technically doesn't make sense because 1 will always be chosen. // I *think* we could do some fancy inference around leaves? But for now, // I will leave it like this. Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 4 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.HighestScore, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2, 3 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 4 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4 }, target.Blocks); } [TestMethod] public void TestNestedCondition9() { const string situationText = @" =MapThree - mushroom: ... He says hi. - (!UnlockedBoatTravel) You seem more lost than usual. (TalkedWithBoatman) You met the boatman, haven't you? He must know a way to get where you want. (...) You can try searching for the boatman. He knows his way around here. I was told he is somewhere in the glimmering forest. - I used to be very upset about the farmlands. I did not like it here. The smell. The endlessness. The overbearing wall. I came to accept it, eventually. And it became easier. -> Choice =Choice"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.HighestScore, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 2, 5 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 6 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 3, 4 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 6 }, target.Blocks); target = situation.Edges[4]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 6 }, target.Blocks); target = situation.Edges[5]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(5, target.Owner); CollectionAssert.AreEqual(new int[] { 6 }, target.Blocks); } [TestMethod] public void TestLinearOneBlocks() { const string situationText = @" =CreateVillage @1 -> ChooseName @1 Seriously? You are not living in a place called {VillageName}. Choose an actual name now: -> exit! @1 (HasChosenSameName) Okay, I guess {VillageName} is what YOU really want. Move to {VilageName}? >> Ready? > Yes. -> ChooseName > No. -> ChooseName =ChooseName"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 2, 3, 5 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4 }, target.Blocks); target = situation.Edges[4]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 5 }, target.Blocks); target = situation.Edges[5]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(5, target.Owner); CollectionAssert.AreEqual(new int[] { 6 }, target.Blocks); target = situation.Edges[6]; Assert.AreEqual(EdgeKind.Choice, target.Kind); Assert.AreEqual(6, target.Owner); CollectionAssert.AreEqual(new int[] { 7, 9 }, target.Blocks); target = situation.Edges[7]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(7, target.Owner); CollectionAssert.AreEqual(new int[] { 8 }, target.Blocks); target = situation.Edges[9]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(9, target.Owner); CollectionAssert.AreEqual(new int[] { 10 }, target.Blocks); } [TestMethod] public void TestConditionWithOneJoin() { const string situationText = @" =Encounter (Something) @1 Hello! (...Something2) @1 Hello once? Bye! =ChooseName"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Assert.AreEqual(6, situation.Root); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 3 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2 }, target.Blocks); Assert.AreEqual(1, situation.Blocks[2].PlayUntil); // @1 target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 5 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4 }, target.Blocks); Assert.AreEqual(1, situation.Blocks[4].PlayUntil); // @1 target = situation.Edges[4]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 5 }, target.Blocks); target = situation.Edges[6]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(6, target.Owner); CollectionAssert.AreEqual(new int[] { 0, 5 }, target.Blocks); } [TestMethod] public void TestConditionWithTwoLinesJoin() { const string situationText = @" =Encounter (Something) @1 Hello! ok... (...Something2) @1 Hello once? Bye! =ChooseName"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Assert.AreEqual(6, situation.Root); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 3 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2 }, target.Blocks); Assert.AreEqual(1, situation.Blocks[2].PlayUntil); // @1 target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 5 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4 }, target.Blocks); Assert.AreEqual(1, situation.Blocks[4].PlayUntil); // @1 target = situation.Edges[4]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 5 }, target.Blocks); target = situation.Edges[6]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(6, target.Owner); CollectionAssert.AreEqual(new int[] { 0, 5 }, target.Blocks); } [TestMethod] public void TestConditionWithOneIfElseJoin() { const string situationText = @" =Encounter @1 (Something) Hello! (...Something2) Hello once? Bye! =ChooseName"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Assert.AreEqual(0, situation.Root); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 5 }, target.Blocks); Assert.AreEqual(1, situation.Blocks[1].PlayUntil); // @1 target = situation.Edges[1]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2, 3, 4 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 5 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 5 }, target.Blocks); target = situation.Edges[4]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 5 }, target.Blocks); } [TestMethod] public void TestConditionWithQuestion() { const string situationText = @" =Encounter (TriedPickName > 3) >> Do you really think a name will stop you from running away? > Yes. -> ChooseName > No. -> Encounter =ChooseName"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Assert.AreEqual(0, situation.Root); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Choice, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 3, 5 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4 }, target.Blocks); target = situation.Edges[5]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(5, target.Owner); CollectionAssert.AreEqual(new int[] { 6 }, target.Blocks); } [TestMethod] public void TestChoiceInsideIf() { const string situationText = @" =Encounter (SupposedlyHaveAJob) Especially since you don't even have a job. >> No job... > All my paperwork is set, sir. > I am very tired and I just want to go home. Okay."; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Assert.AreEqual(0, situation.Root); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 5 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Choice, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 3, 4 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 5 }, target.Blocks); target = situation.Edges[4]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 5 }, target.Blocks); } [TestMethod] public void TestChoiceOutsideIf() { const string situationText = @" =Encounter (SupposedlyHaveAJob) Especially since you don't even have a job. >> No job... > All my paperwork is set, sir. > I am very tired and I just want to go home. Okay."; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Assert.AreEqual(0, situation.Root); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1, 2 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 3 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Choice, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4, 5 }, target.Blocks); target = situation.Edges[4]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 6 }, target.Blocks); target = situation.Edges[5]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(5, target.Owner); CollectionAssert.AreEqual(new int[] { 6 }, target.Blocks); } [TestMethod] public void TestNestedChoice() { const string situationText = @" =Encounter >> No job... > All my paperwork is set, sir. >> Oh really? > It was a lie! > Yes... > I am very tired and I just want to go home. Okay."; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Choice, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2, 6 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 3 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Choice, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4, 5 }, target.Blocks); target = situation.Edges[4]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 7 }, target.Blocks); target = situation.Edges[5]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(5, target.Owner); CollectionAssert.AreEqual(new int[] { 7 }, target.Blocks); target = situation.Edges[6]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(6, target.Owner); CollectionAssert.AreEqual(new int[] { 7 }, target.Blocks); } [TestMethod] public void TestNestedChoice2() { const string situationText = @" =Encounter >> No job... > All my paperwork is set, sir. >> Oh really? > It was a lie! Yeah? > Yes... No! > I am very tired and I just want to go home. Okay."; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Choice, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2, 8 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 3 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Choice, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4, 6 }, target.Blocks); target = situation.Edges[4]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 5 }, target.Blocks); target = situation.Edges[5]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(5, target.Owner); CollectionAssert.AreEqual(new int[] { 9 }, target.Blocks); target = situation.Edges[6]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(6, target.Owner); CollectionAssert.AreEqual(new int[] { 7 }, target.Blocks); target = situation.Edges[7]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(7, target.Owner); CollectionAssert.AreEqual(new int[] { 9 }, target.Blocks); target = situation.Edges[8]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(8, target.Owner); CollectionAssert.AreEqual(new int[] { 9 }, target.Blocks); } [TestMethod] public void TestOrderAfterIf() { const string situationText = @" =Sold (AmountSold > 0) Here is a total of {AmountSold}C. [AmountSold = 0] + Have a wonderful day! + Bye, bye! + I hope you had fun! + See you around! + Thanks for passing by! "; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.HighestScore, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 3, 4, 5, 6, 7 }, target.Blocks); } [TestMethod] public void TestImmediateEffects() { const string situationText = @" =Encounter Hi! [c:SomeInteraction] Now, I will say bye. So bye!"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2 }, target.Blocks); } [TestMethod] public void TestChoicesWithIfElse() { const string situationText = @" =Encounter @1 (Day == 1) Hi! Hope you are okay. (Cooked >= 1) Anything new? >> I guess. > A soma: You could say so. Or... Not! > B soma: You could say so. But actually. No, nevermind. \(At least that's what I keep telling myself\) > C soma: You could say so. Maybe? I guess? I never thought too much about it. [Happy += 5] Or yes? (...) No. -> exit!"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2, 3 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 3 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4, 13 }, target.Blocks); target = situation.Edges[4]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 5 }, target.Blocks); target = situation.Edges[5]; Assert.AreEqual(EdgeKind.Choice, target.Kind); Assert.AreEqual(5, target.Owner); CollectionAssert.AreEqual(new int[] { 6, 8, 10 }, target.Blocks); target = situation.Edges[6]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(6, target.Owner); CollectionAssert.AreEqual(new int[] { 7 }, target.Blocks); target = situation.Edges[7]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(7, target.Owner); CollectionAssert.AreEqual(new int[] { 14 }, target.Blocks); target = situation.Edges[8]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(8, target.Owner); CollectionAssert.AreEqual(new int[] { 9 }, target.Blocks); target = situation.Edges[9]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(9, target.Owner); CollectionAssert.AreEqual(new int[] { 14 }, target.Blocks); target = situation.Edges[10]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(10, target.Owner); CollectionAssert.AreEqual(new int[] { 11 }, target.Blocks); target = situation.Edges[11]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(11, target.Owner); CollectionAssert.AreEqual(new int[] { 12 }, target.Blocks); target = situation.Edges[12]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(12, target.Owner); CollectionAssert.AreEqual(new int[] { 14 }, target.Blocks); target = situation.Edges[13]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(13, target.Owner); CollectionAssert.AreEqual(new int[] { 14 }, target.Blocks); } [TestMethod] public void TestChoicesWithIfElse2() { const string situationText = @" =Encounter @1 (Day == 1) Hi! Hope you are okay. (Cooked >= 1) Anything new? >> I guess. > A soma: You could say so. Or... Not! > B soma: You could say so. But actually. No, nevermind. \(At least that's what I keep telling myself\) > C soma: You could say so. Maybe? I guess? I never thought too much about it. [Happy += 5] (...) No. -> exit!"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2, 3 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 3 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.IfElse, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4, 12 }, target.Blocks); target = situation.Edges[4]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(4, target.Owner); CollectionAssert.AreEqual(new int[] { 5 }, target.Blocks); target = situation.Edges[5]; Assert.AreEqual(EdgeKind.Choice, target.Kind); Assert.AreEqual(5, target.Owner); CollectionAssert.AreEqual(new int[] { 6, 8, 10 }, target.Blocks); target = situation.Edges[6]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(6, target.Owner); CollectionAssert.AreEqual(new int[] { 7 }, target.Blocks); target = situation.Edges[7]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(7, target.Owner); CollectionAssert.AreEqual(new int[] { 13 }, target.Blocks); target = situation.Edges[8]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(8, target.Owner); CollectionAssert.AreEqual(new int[] { 9 }, target.Blocks); target = situation.Edges[9]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(9, target.Owner); CollectionAssert.AreEqual(new int[] { 13 }, target.Blocks); target = situation.Edges[10]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(10, target.Owner); CollectionAssert.AreEqual(new int[] { 11 }, target.Blocks); target = situation.Edges[11]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(11, target.Owner); CollectionAssert.AreEqual(new int[] { 13 }, target.Blocks); target = situation.Edges[12]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(12, target.Owner); CollectionAssert.AreEqual(new int[] { 13 }, target.Blocks); } [TestMethod] public void TestChoicesWithIfElse3() { const string situationText = @" =Encounter @1 A B >> Bla bla! > He. thief: No? Okay. > Ha! thief: Yes. Exactly! [AccumulatedCharm += 2] Do not do it. > No. thief: Stop! Okay. -> exit!"; CharacterScript? script = Read(situationText); Assert.IsTrue(script != null); Situation? situation = script.FetchSituation(id: 0); Assert.IsTrue(situation != null); Edge target = situation.Edges[0]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(0, target.Owner); CollectionAssert.AreEqual(new int[] { 1 }, target.Blocks); target = situation.Edges[1]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(1, target.Owner); CollectionAssert.AreEqual(new int[] { 2 }, target.Blocks); target = situation.Edges[2]; Assert.AreEqual(EdgeKind.Choice, target.Kind); Assert.AreEqual(2, target.Owner); CollectionAssert.AreEqual(new int[] { 3, 5, 8 }, target.Blocks); target = situation.Edges[3]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(3, target.Owner); CollectionAssert.AreEqual(new int[] { 4 }, target.Blocks); target = situation.Edges[5]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(5, target.Owner); CollectionAssert.AreEqual(new int[] { 6 }, target.Blocks); target = situation.Edges[6]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(6, target.Owner); CollectionAssert.AreEqual(new int[] { 7 }, target.Blocks); target = situation.Edges[8]; Assert.AreEqual(EdgeKind.Next, target.Kind); Assert.AreEqual(8, target.Owner); CollectionAssert.AreEqual(new int[] { 9 }, target.Blocks); } } }
src/Gum.Tests/Bungee.cs
isadorasophia-gum-032cb2d
[ { "filename": "src/Gum/InnerThoughts/Situation.cs", "retrieved_chunk": "using Gum.Utilities;\nusing Newtonsoft.Json;\nusing System.Diagnostics;\nnamespace Gum.InnerThoughts\n{\n [DebuggerDisplay(\"{Name}\")]\n public class Situation\n {\n [JsonProperty]\n public readonly int Id = 0;", "score": 0.8734558820724487 }, { "filename": "src/Gum/InnerThoughts/Block.cs", "retrieved_chunk": "using System;\nusing System.Diagnostics;\nusing System.Text;\nnamespace Gum.InnerThoughts\n{\n [DebuggerDisplay(\"{DebuggerDisplay(),nq}\")]\n public class Block\n {\n public readonly int Id = 0;\n /// <summary>", "score": 0.8275327682495117 }, { "filename": "src/Gum/InnerThoughts/DialogAction.cs", "retrieved_chunk": "using System.Diagnostics;\nusing System.Text;\nusing Gum.Blackboards;\nusing Gum.Utilities;\nnamespace Gum.InnerThoughts\n{\n [DebuggerDisplay(\"{DebuggerDisplay(),nq}\")]\n public class DialogAction\n {\n public readonly Fact Fact = new();", "score": 0.8046315312385559 }, { "filename": "src/Gum/Parser_Requirements.cs", "retrieved_chunk": "using System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing Gum.InnerThoughts;\nusing Gum.Utilities;\nnamespace Gum\n{\n internal static partial class Tokens\n {\n public const string And = \"and\";\n public const string And2 = \"&&\";", "score": 0.7955950498580933 }, { "filename": "src/Gum/InnerThoughts/CharacterScript.cs", "retrieved_chunk": "using Newtonsoft.Json;\nnamespace Gum.InnerThoughts\n{\n public class CharacterScript\n {\n /// <summary>\n /// List of tasks or events that the <see cref=\"Situations\"/> may do.\n /// </summary>\n [JsonProperty]\n private readonly SortedList<int, Situation> _situations = new();", "score": 0.7947077751159668 } ]
csharp
CharacterScript? Read(string input) {
using static QuizGenerator.Core.StringUtils; using Word = Microsoft.Office.Interop.Word; using System.Diagnostics; using Microsoft.Office.Interop.Word; namespace QuizGenerator.Core { public class RandomizedQuizGenerator { private ILogger logger; private Word.Application wordApp; public RandomizedQuizGenerator(ILogger logger) { this.logger = logger; } public void GenerateQuiz(string inputFilePath, string outputFolderPath) { this.logger.Log("Quiz generation started."); this.logger.LogNewLine(); if (KillAllProcesses("WINWORD")) Console.WriteLine("MS Word (WINWORD.EXE) is still running -> process terminated."); // Start MS Word and open the input file this.wordApp = new Word.Application(); this.wordApp.Visible = false; // Show / hide MS Word app window this.wordApp.ScreenUpdating = false; // Enable / disable screen updates after each change var inputDoc = this.wordApp.Documents.Open(inputFilePath); try { // Parse the input MS Word document this.logger.Log("Parsing the input document: " + inputFilePath); QuizParser quizParser = new QuizParser(this.logger); QuizDocument quiz = quizParser.Parse(inputDoc); this.logger.Log("Input document parsed successfully."); // Display the quiz content (question groups + questions + answers) quizParser.LogQuiz(quiz); // Generate the randomized quiz variants this.logger.LogNewLine(); this.logger.Log("Generating quizes..."); this.logger.Log($" (output path = {outputFolderPath})"); GenerateRandomizedQuizVariants(quiz, inputFilePath, outputFolderPath); this.logger.LogNewLine(); this.logger.Log("Quiz generation completed."); this.logger.LogNewLine(); } catch (Exception ex) { this.logger.LogException(ex); } finally { inputDoc.Close(); this.wordApp.Quit(); } } private void GenerateRandomizedQuizVariants(
QuizDocument quiz, string inputFilePath, string outputFolderPath) {
// Initialize the output folder (create it and ensure it is empty) this.logger.Log($"Initializing output folder: {outputFolderPath}"); if (Directory.Exists(outputFolderPath)) { Directory.Delete(outputFolderPath, true); } Directory.CreateDirectory(outputFolderPath); // Prepare the answer sheet for all variants List<List<char>> quizAnswerSheet = new List<List<char>>(); // Generate the requested randomized quiz variants, one by one for (int quizVariant = 1; quizVariant <= quiz.VariantsToGenerate; quizVariant++) { this.logger.LogNewLine(); this.logger.Log($"Generating randomized quiz: variant #{quizVariant} out of {quiz.VariantsToGenerate} ..."); string outputFilePath = outputFolderPath + Path.DirectorySeparatorChar + "quiz" + quizVariant.ToString("000") + ".docx"; RandomizedQuiz randQuiz = RandomizedQuiz.GenerateFromQuizData(quiz); WriteRandomizedQuizToFile( randQuiz, quizVariant, inputFilePath, outputFilePath, quiz.LangCode); List<char> answers = ExtractAnswersAsLetters(randQuiz, quiz.LangCode); quizAnswerSheet.Add(answers); this.logger.Log($"Randomized quiz: variant #{quizVariant} out of {quiz.VariantsToGenerate} generated successfully."); } WriteAnswerSheetToHTMLFile(quizAnswerSheet, outputFolderPath); } private void WriteRandomizedQuizToFile(RandomizedQuiz randQuiz, int quizVariant, string inputFilePath, string outputFilePath, string langCode) { File.Copy(inputFilePath, outputFilePath, true); // Open the output file in MS Word var outputDoc = this.wordApp.Documents.Open(outputFilePath); try { // Select all content in outputDoc and delete the seletion this.wordApp.Selection.WholeStory(); this.wordApp.Selection.Delete(); // Write the randomized quiz as MS Word document this.logger.Log($"Creating randomized quiz document: " + outputFilePath); WriteRandomizedQuizToWordDoc(randQuiz, quizVariant, langCode, outputDoc); } catch (Exception ex) { this.logger.LogException(ex); } finally { outputDoc.Save(); outputDoc.Close(); } } private void WriteRandomizedQuizToWordDoc(RandomizedQuiz quiz, int quizVariant, string langCode, Word.Document outputDoc) { // Print the quiz header in the output MS Word document string quizHeaderText = TruncateString(quiz.HeaderContent.Text); this.logger.Log($"Quiz header: {quizHeaderText}", 1); AppendRange(outputDoc, quiz.HeaderContent); // Replace all occurences of "# # #" with the variant number (page headers + body) string variantFormatted = quizVariant.ToString("000"); foreach (Word.Section section in outputDoc.Sections) { foreach (Word.HeaderFooter headerFooter in section.Headers) { ReplaceTextInRange(headerFooter.Range, "# # #", variantFormatted); } } ReplaceTextInRange(outputDoc.Content, "# # #", variantFormatted); int questionNumber = 0; this.logger.Log($"Question groups = {quiz.QuestionGroups.Count}", 1); for (int groupIndex = 0; groupIndex < quiz.QuestionGroups.Count; groupIndex++) { this.logger.Log($"[Question Group #{groupIndex + 1}]", 1); QuizQuestionGroup group = quiz.QuestionGroups[groupIndex]; string groupHeaderText = TruncateString(group.HeaderContent?.Text); this.logger.Log($"Group header: {groupHeaderText}", 2); if (!group.SkipHeader) { AppendRange(outputDoc, group.HeaderContent); } this.logger.Log($"Questions = {group.Questions.Count}", 2); for (int questionIndex = 0; questionIndex < group.Questions.Count; questionIndex++) { this.logger.Log($"[Question #{questionIndex + 1}]", 2); QuizQuestion question = group.Questions[questionIndex]; string questionContent = TruncateString(question.HeaderContent?.Text); this.logger.Log($"Question content: {questionContent}", 3); questionNumber++; AppendText(outputDoc, $"{questionNumber}. "); AppendRange(outputDoc, question.HeaderContent); this.logger.Log($"Answers = {question.Answers.Count}", 3); char letter = GetStartLetter(langCode); foreach (var answer in question.Answers) { string prefix = answer.IsCorrect ? "Correct answer" : "Wrong answer"; string answerText = TruncateString(answer.Content.Text); this.logger.Log($"{prefix}: {letter}) {answerText}", 4); AppendText(outputDoc, $"{letter}) "); AppendRange(outputDoc, answer.Content); letter++; } string questionFooterText = TruncateString(question.FooterContent?.Text); if (questionFooterText == "") questionFooterText = "(empty)"; this.logger.Log($"Question footer: {questionFooterText}", 3); AppendRange(outputDoc, question.FooterContent); } } string quizFooterText = TruncateString(quiz.FooterContent?.Text); this.logger.Log($"Quiz footer: {quizFooterText}", 1); AppendRange(outputDoc, quiz.FooterContent); } private void ReplaceTextInRange(Word.Range range, string srcText, string replaceText) { Word.Find find = range.Find; find.Text = srcText; find.Replacement.Text = replaceText; find.Forward = true; find.Wrap = Word.WdFindWrap.wdFindContinue; object replaceAll = Word.WdReplace.wdReplaceAll; find.Execute(Replace: ref replaceAll); } public void AppendRange(Word.Document targetDocument, Word.Range sourceRange) { if (sourceRange != null) { // Get the range at the end of the target document Word.Range targetRange = targetDocument.Content; object wdColapseEnd = Word.WdCollapseDirection.wdCollapseEnd; targetRange.Collapse(ref wdColapseEnd); // Insert the source range of formatted text to the target range targetRange.FormattedText = sourceRange.FormattedText; } } public void AppendText(Word.Document targetDocument, string text) { // Get the range at the end of the target document Word.Range targetRange = targetDocument.Content; object wdColapseEnd = Word.WdCollapseDirection.wdCollapseEnd; targetRange.Collapse(ref wdColapseEnd); // Insert the source range of formatted text to the target range targetRange.Text = text; } private List<char> ExtractAnswersAsLetters(RandomizedQuiz randQuiz, string langCode) { char startLetter = GetStartLetter(langCode); List<char> answers = new List<char>(); foreach (var question in randQuiz.AllQuestions) { int correctAnswerIndex = FindCorrectAnswerIndex(question.Answers); char answer = (char)(startLetter + correctAnswerIndex); answers.Add(answer); } return answers; } private static char GetStartLetter(string langCode) { char startLetter; if (langCode == "EN") startLetter = 'a'; // Latin letter 'a' else if (langCode == "BG") startLetter = 'а'; // Cyrillyc letter 'а' else throw new Exception("Unsupported language: " + langCode); return startLetter; } private int FindCorrectAnswerIndex(List<QuestionAnswer> answers) { for (int index = 0; index < answers.Count; index++) { if (answers[index].IsCorrect) return index; } // No correct answer found in the list of answers return -1; } private void WriteAnswerSheetToHTMLFile( List<List<char>> quizAnswerSheet, string outputFilePath) { string outputFileName = outputFilePath + Path.DirectorySeparatorChar + "answers.html"; this.logger.LogNewLine(); this.logger.Log($"Writing answers sheet: {outputFileName}"); for (int quizIndex = 0; quizIndex < quizAnswerSheet.Count; quizIndex++) { List<char> answers = quizAnswerSheet[quizIndex]; string answersAsString = $"Variant #{quizIndex + 1}: {string.Join(" ", answers)}"; this.logger.Log(answersAsString, 1); } List<string> html = new List<string>(); html.Add("<table border='1'>"); html.Add(" <tr>"); html.Add(" <td>Var</td>"); for (int questionIndex = 0; questionIndex < quizAnswerSheet[0].Count; questionIndex++) { html.Add($" <td>{questionIndex + 1}</td>"); } html.Add(" </tr>"); for (int quizIndex = 0; quizIndex < quizAnswerSheet.Count; quizIndex++) { html.Add(" <tr>"); html.Add($" <td>{(quizIndex + 1).ToString("000")}</td>"); foreach (var answer in quizAnswerSheet[quizIndex]) { html.Add($" <td>{answer}</td>"); } html.Add(" </tr>"); } html.Add("</table>"); File.WriteAllLines(outputFileName, html); } public bool KillAllProcesses(string processName) { Process[] processes = Process.GetProcessesByName(processName); int killedProcessesCount = 0; foreach (Process process in processes) { try { process.Kill(); killedProcessesCount++; this.logger.Log($"Process {processName} ({process.Id}) stopped."); } catch { this.logger.LogError($"Process {processName} ({process.Id}) is running, but cannot be stopped!"); } } return (killedProcessesCount > 0); } } }
QuizGenerator.Core/QuizGenerator.cs
SoftUni-SoftUni-Quiz-Generator-b071448
[ { "filename": "QuizGenerator.UI/FormQuizGenerator.cs", "retrieved_chunk": "\t\t\tstring outputFolder = Path.Combine(startupFolder, @\"../../../../output\");\n\t\t\tthis.textBoxOutputFolder.Text = Path.GetFullPath(outputFolder);\n\t\t\tthis.ActiveControl = this.buttonGenerate;\n\t\t}\n\t\tprivate void buttonGenerate_Click(object sender, EventArgs e)\n\t\t{\n\t\t\tstring inputFilePath = this.textBoxInputFile.Text;\n\t\t\tstring outputFolderPath = this.textBoxOutputFolder.Text;\n\t\t\tRandomizedQuizGenerator quizGenerator = new RandomizedQuizGenerator(this);\n\t\t\tquizGenerator.GenerateQuiz(inputFilePath, outputFolderPath);", "score": 0.7978305816650391 }, { "filename": "QuizGenerator.UI/FormQuizGenerator.cs", "retrieved_chunk": "\t\tpublic void LogException(Exception ex)\n\t\t{\n\t\t\tthis.LogError(ex.Message);\n\t\t\tthis.LogError(ex.StackTrace, \"Exception\", 1);\n\t\t}\n\t\tprivate void FormQuizGenerator_Load(object sender, EventArgs e)\n\t\t{\n\t\t\tstring startupFolder = Application.StartupPath;\n\t\t\tstring inputFolder = Path.Combine(startupFolder, @\"../../../../input\");\n\t\t\tthis.textBoxInputFile.Text = Path.GetFullPath(inputFolder + @\"/questions.docx\");", "score": 0.7695351839065552 }, { "filename": "QuizGenerator.Core/QuizParser.cs", "retrieved_chunk": "\t\tprivate const string QuestionTag = \"~~~ Question ~~~\";\n\t\tprivate const string CorrectAnswerTag = \"Correct.\";\n\t\tprivate const string WrongAnswerTag = \"Wrong.\";\n\t\tprivate ILogger logger;\n\t\tpublic QuizParser(ILogger logger)\n\t\t{ \n\t\t\tthis.logger = logger;\n\t\t}\n\t\tpublic QuizDocument Parse(Word.Document doc)\n\t\t{", "score": 0.7191043496131897 }, { "filename": "QuizGenerator.UI/FormQuizGenerator.Designer.cs", "retrieved_chunk": "\t\t\tText = \"SoftUni Quiz Generator\";\n\t\t\tLoad += FormQuizGenerator_Load;\n\t\t\tResumeLayout(false);\n\t\t\tPerformLayout();\n\t\t}\n\t\t#endregion\n\t\tprivate Label labelInputFile;\n\t\tprivate TextBox textBoxInputFile;\n\t\tprivate Button buttonChooseInputFile;\n\t\tprivate Label labelOutputFolder;", "score": 0.6989418268203735 }, { "filename": "QuizGenerator.UI/Program.cs", "retrieved_chunk": "\t\t\tApplicationConfiguration.Initialize();\n\t\t\tApplication.Run(new FormQuizGenerator());\n\t\t}\n\t}\n}", "score": 0.674227774143219 } ]
csharp
QuizDocument quiz, string inputFilePath, string outputFolderPath) {
using EF012.CodeFirstMigration.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; namespace EF012.CodeFirstMigration.Data { public class AppDbContext : DbContext { public DbSet<Course> Courses { get; set; } public DbSet<Instructor> Instructors { get; set; } public DbSet<Office> Offices { get; set; } public DbSet<Section> Sections { get; set; } public DbSet<Schedule> Schedules { get; set; } public DbSet<Student> Students { get; set; } public DbSet<
Enrollment> Enrollments {
get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); var config = new ConfigurationBuilder().AddJsonFile("appsettings.json") .Build(); var connectionString = config.GetSection("constr").Value; optionsBuilder.UseSqlServer(connectionString); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // modelBuilder.ApplyConfiguration(new CourseConfiguration()); // not best practice modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly); } } }
EF012.CodeFirstMigration/Data/AppDbContext.cs
metigator-EF012-054d65d
[ { "filename": "EF012.CodeFirstMigration/Entities/Section.cs", "retrieved_chunk": "namespace EF012.CodeFirstMigration.Entities\n{\n public class Section\n {\n public int Id { get; set; }\n public string SectionName { get; set; }\n public int CourseId { get; set; }\n public Course Course { get; set; }\n public int? InstructorId { get; set; }\n public Instructor? Instructor { get; set; }", "score": 0.8434339165687561 }, { "filename": "EF012.CodeFirstMigration/Entities/Instructor.cs", "retrieved_chunk": "namespace EF012.CodeFirstMigration.Entities\n{\n public class Instructor\n {\n public int Id { get; set; }\n public string? FName { get; set; }\n public string? LName { get; set; }\n public int? OfficeId { get; set; }\n public Office? Office { get; set; }\n public ICollection<Section> Sections { get; set; } = new List<Section>();", "score": 0.8410859704017639 }, { "filename": "EF012.CodeFirstMigration/Entities/Section.cs", "retrieved_chunk": " public int ScheduleId { get; set; }\n public Schedule Schedule { get; set; }\n public TimeSlot TimeSlot { get; set; }\n public ICollection<Student> Students { get; set; } = new List<Student>();\n }\n public class TimeSlot\n {\n public TimeSpan StartTime { get; set; }\n public TimeSpan EndTime { get; set; }\n public override string ToString()", "score": 0.838599681854248 }, { "filename": "EF012.CodeFirstMigration/Entities/Schedule.cs", "retrieved_chunk": "using EF012.CodeFirstMigration.Enums;\nnamespace EF012.CodeFirstMigration.Entities\n{\n public class Schedule\n {\n public int Id { get; set; }\n public ScheduleEnum Title { get; set; }\n public bool SUN { get; set; }\n public bool MON { get; set; }\n public bool TUE { get; set; }", "score": 0.8203827142715454 }, { "filename": "EF012.CodeFirstMigration/Entities/Course.cs", "retrieved_chunk": "namespace EF012.CodeFirstMigration.Entities\n{\n public class Course\n {\n public int Id { get; set; }\n public string? CourseName { get; set; }\n public decimal Price { get; set; }\n public ICollection<Section> Sections { get; set; } = new List<Section>();\n }\n}", "score": 0.818918764591217 } ]
csharp
Enrollment> Enrollments {
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System; using System.Collections.Generic; using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Textures; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Containers; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Framework.Logging; using osu.Framework.Screens; using osu.Game.Audio; using osu.Game.Screens; using osu.Game.Graphics.Sprites; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Gengo.UI.Translation; using osu.Game.Rulesets.Gengo.Anki; using osu.Game.Rulesets.Gengo.Cards; using osuTK; using osuTK.Graphics; namespace osu.Game.Rulesets.Gengo.Objects.Drawables { public partial class DrawableGengoHitObject : DrawableHitObject<GengoHitObject>, IKeyBindingHandler<GengoAction> { private const double time_preempt = 600; private const double time_fadein = 400; public override bool HandlePositionalInput => true; public DrawableGengoHitObject(GengoHitObject hitObject) : base(hitObject) { Size = new Vector2(80); Origin = Anchor.Centre; Position = hitObject.Position; } [Resolved] protected TranslationContainer translationContainer { get; set; } [Resolved] protected AnkiAPI anki { get; set; } private
Card assignedCard;
private Card baitCard; private Box cardDesign; private OsuSpriteText cardText; [BackgroundDependencyLoader] private void load(TextureStore textures) { assignedCard = anki.FetchRandomCard(); baitCard = anki.FetchRandomCard(); translationContainer.AddCard(assignedCard, baitCard); AddInternal(new CircularContainer { AutoSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, Masking = true, CornerRadius = 15f, Children = new Drawable[] { cardDesign = new Box { RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, Colour = Color4.Black, }, cardText = new OsuSpriteText { Text = assignedCard.foreignText, Anchor = Anchor.Centre, Origin = Anchor.Centre, Colour = Color4.Red, Font = new FontUsage(size: 35f), Margin = new MarginPadding(8f), } } }); } public override IEnumerable<HitSampleInfo> GetSamples() => new[] { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }; protected void ApplyResult(HitResult result) { void resultApplication(JudgementResult r) => r.Type = result; ApplyResult(resultApplication); } GengoAction pressedAction; /// <summary> /// Checks whether or not the pressed button/action for the current HitObject was correct for (matching to) the assigned card. /// </summary> bool CorrectActionCheck() { if (pressedAction == GengoAction.LeftButton) return translationContainer.leftWordText.Text == assignedCard.translatedText; else if (pressedAction == GengoAction.RightButton) return translationContainer.rightWordText.Text == assignedCard.translatedText; return false; } protected override void CheckForResult(bool userTriggered, double timeOffset) { if (!userTriggered) { if (!HitObject.HitWindows.CanBeHit(timeOffset)) { translationContainer.RemoveCard(); ApplyResult(r => r.Type = r.Judgement.MinResult); } return; } var result = HitObject.HitWindows.ResultFor(timeOffset); if (result == HitResult.None) return; if (!CorrectActionCheck()) { translationContainer.RemoveCard(); ApplyResult(HitResult.Miss); return; } translationContainer.RemoveCard(); ApplyResult(r => r.Type = result); } protected override double InitialLifetimeOffset => time_preempt; protected override void UpdateHitStateTransforms(ArmedState state) { switch (state) { case ArmedState.Hit: cardText.FadeColour(Color4.White, 200, Easing.OutQuint); cardDesign.FadeColour(Color4.YellowGreen, 200, Easing.OutQuint); this.ScaleTo(2, 500, Easing.OutQuint).Expire(); break; default: this.ScaleTo(0.8f, 200, Easing.OutQuint); cardText.FadeColour(Color4.Black, 200, Easing.OutQuint); cardDesign.FadeColour(Color4.Red, 200, Easing.OutQuint); this.FadeOut(500, Easing.InQuint).Expire(); break; } } public bool OnPressed(KeyBindingPressEvent<GengoAction> e) { if (e.Action != GengoAction.LeftButton && e.Action != GengoAction.RightButton) return false; pressedAction = e.Action; return UpdateResult(true); } public void OnReleased(KeyBindingReleaseEvent<GengoAction> e) { } } }
osu.Game.Rulesets.Gengo/Objects/Drawables/DrawableGengoHitObject.cs
0xdeadbeer-gengo-dd4f78d
[ { "filename": "osu.Game.Rulesets.Gengo/Anki/Anki.cs", "retrieved_chunk": " protected GengoRulesetConfigManager config { get; set; }\n [Resolved]\n protected IBeatmap beatmap { get; set; }\n [Resolved] \n protected IDialogOverlay dialogOverlay { get; set; }\n private Random hitObjectRandom;\n /// <summary>\n /// Function checks whether it's possible to send valid requests to the Anki API with current configurations\n /// </summary>\n bool CheckSettings() {", "score": 0.8719557523727417 }, { "filename": "osu.Game.Rulesets.Gengo/UI/Cursor/GengoCursorContainer.cs", "retrieved_chunk": " private Bindable<bool> autoCursorScale;\n [Resolved(canBeNull: true)]\n private GameplayState state { get; set; }\n [Resolved]\n private OsuConfigManager config { get; set; }\n protected override Drawable CreateCursor() => new GengoCursor();\n [BackgroundDependencyLoader]\n private void load(TextureStore textures) {\n }\n protected override void LoadComplete()", "score": 0.8711891174316406 }, { "filename": "osu.Game.Rulesets.Gengo/Objects/GengoHitObject.cs", "retrieved_chunk": " public override Judgement CreateJudgement() => new Judgement();\n public Vector2 Position { get; set; }\n public float X => Position.X;\n public float Y => Position.Y;\n }\n}", "score": 0.8701298832893372 }, { "filename": "osu.Game.Rulesets.Gengo/Anki/Anki.cs", "retrieved_chunk": " /// Class for connecting to the anki API. \n /// </summary>\n public partial class AnkiAPI : Component {\n public string URL { get; set; } \n public string ankiDeck{ get; set; }\n public string foreignWordField { get; set; } \n public string translatedWordField { get; set; }\n private List<Card> dueCards = new List<Card>();\n private HttpClient httpClient;\n [Resolved]", "score": 0.8697501420974731 }, { "filename": "osu.Game.Rulesets.Gengo/UI/GengoPlayfieldAdjustmentContainer.cs", "retrieved_chunk": " }\n /// <summary>\n /// A <see cref=\"Container\"/> which scales its content relative to a target width.\n /// </summary>\n private partial class ScalingContainer : Container\n {\n internal bool PlayfieldShift { get; set; }\n protected override void Update()\n {\n base.Update();", "score": 0.8340479135513306 } ]
csharp
Card assignedCard;
using HarmonyLib; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Text; using UnityEngine; using UnityEngine.UI; using UnityEngine.UIElements; namespace Ultrapain.Patches { class Panopticon_Start { static void Postfix(FleshPrison __instance) { if (__instance.altVersion) __instance.onFirstHeal = new UltrakillEvent(); } } class Obamapticon_Start { static bool Prefix(FleshPrison __instance) { if (!__instance.altVersion) return true; if (__instance.eid == null) __instance.eid = __instance.GetComponent<EnemyIdentifier>(); __instance.eid.overrideFullName = ConfigManager.obamapticonName.value; return true; } static void Postfix(FleshPrison __instance) { if (!__instance.altVersion) return; GameObject obamapticon = GameObject.Instantiate(Plugin.obamapticon, __instance.transform); obamapticon.transform.parent = __instance.transform.Find("FleshPrison2/Armature/FP2_Root/Head_Root"); obamapticon.transform.localScale = new Vector3(15.4f, 15.4f, 15.4f); obamapticon.transform.localPosition = Vector3.zero; obamapticon.transform.localRotation = Quaternion.identity; obamapticon.layer = 24; __instance.transform.Find("FleshPrison2/FleshPrison2_Head").GetComponent<SkinnedMeshRenderer>().enabled = false; if (__instance.bossHealth != null) { __instance.bossHealth.bossName = ConfigManager.obamapticonName.value; if (__instance.bossHealth.bossBar != null) { BossHealthBarTemplate temp = __instance.bossHealth.bossBar.GetComponent<BossHealthBarTemplate>(); temp.bossNameText.text = ConfigManager.obamapticonName.value; foreach (Text t in temp.textInstances) t.text = ConfigManager.obamapticonName.value; } } } } class Panopticon_SpawnInsignia { static bool Prefix(FleshPrison __instance, ref bool ___inAction, Statue ___stat, float ___maxHealth, int ___difficulty, ref float ___fleshDroneCooldown, EnemyIdentifier ___eid) { if (!__instance.altVersion) return true; ___inAction = false; GameObject gameObject = GameObject.Instantiate<GameObject>(__instance.insignia, MonoSingleton<PlayerTracker>.Instance.GetPlayer().position, Quaternion.identity); Vector3 playerVelocity = MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(); playerVelocity.y = 0f; if (playerVelocity.magnitude > 0f) { gameObject.transform.LookAt(MonoSingleton<PlayerTracker>.Instance.GetPlayer().position + playerVelocity); } else { gameObject.transform.Rotate(Vector3.up * UnityEngine.Random.Range(0f, 360f), Space.Self); } gameObject.transform.Rotate(Vector3.right * 90f, Space.Self); VirtueInsignia virtueInsignia; if (gameObject.TryGetComponent<VirtueInsignia>(out virtueInsignia)) { virtueInsignia.predictive = true; virtueInsignia.noTracking = true; virtueInsignia.otherParent = __instance.transform; if (___stat.health > ___maxHealth / 2f) { virtueInsignia.charges = 2; } else { virtueInsignia.charges = 3; } if (___difficulty == 3) { virtueInsignia.charges++; } virtueInsignia.windUpSpeedMultiplier = 0.5f; virtueInsignia.windUpSpeedMultiplier *= ___eid.totalSpeedModifier; virtueInsignia.damage = Mathf.RoundToInt((float)virtueInsignia.damage * ___eid.totalDamageModifier); virtueInsignia.target = MonoSingleton<PlayerTracker>.Instance.GetPlayer(); virtueInsignia.predictiveVersion = null; Light light = gameObject.AddComponent<Light>(); light.range = 30f; light.intensity = 50f; } if (___difficulty >= 2) { gameObject.transform.localScale = new Vector3(8f, 2f, 8f); } else if (___difficulty == 1) { gameObject.transform.localScale = new Vector3(7f, 2f, 7f); } else { gameObject.transform.localScale = new Vector3(5f, 2f, 5f); } GoreZone componentInParent = __instance.GetComponentInParent<GoreZone>(); if (componentInParent) { gameObject.transform.SetParent(componentInParent.transform, true); } else { gameObject.transform.SetParent(__instance.transform, true); } // CUSTOM CODE HERE GameObject xInsignia = GameObject.Instantiate(gameObject, gameObject.transform.position, gameObject.transform.rotation, gameObject.transform.parent); GameObject zInsignia = GameObject.Instantiate(gameObject, gameObject.transform.position, gameObject.transform.rotation, gameObject.transform.parent); xInsignia.transform.Rotate(xInsignia.transform.right, 90f, Space.World); zInsignia.transform.Rotate(zInsignia.transform.forward, 90f, Space.World); Quaternion xRot = xInsignia.transform.rotation; Quaternion yRot = gameObject.transform.rotation; Quaternion zRot = zInsignia.transform.rotation; RotateOnSpawn xInsigniaRotation = xInsignia.AddComponent<RotateOnSpawn>(); RotateOnSpawn zInsigniaRotation = zInsignia.AddComponent<RotateOnSpawn>(); RotateOnSpawn yInsigniaRotation = gameObject.AddComponent<RotateOnSpawn>(); xInsignia.transform.rotation = xInsigniaRotation.targetRotation = xRot; gameObject.transform.rotation = yInsigniaRotation.targetRotation = yRot; zInsignia.transform.rotation = zInsigniaRotation.targetRotation = zRot; xInsignia.transform.localScale = new Vector3(xInsignia.transform.localScale.x * ConfigManager.panopticonAxisBeamSizeMulti.value, xInsignia.transform.localScale.y, xInsignia.transform.localScale.z * ConfigManager.panopticonAxisBeamSizeMulti.value); zInsignia.transform.localScale = new Vector3(zInsignia.transform.localScale.x * ConfigManager.panopticonAxisBeamSizeMulti.value, zInsignia.transform.localScale.y, zInsignia.transform.localScale.z * ConfigManager.panopticonAxisBeamSizeMulti.value); if (___fleshDroneCooldown < 1f) { ___fleshDroneCooldown = 1f; } return false; } } class Panopticon_HomingProjectileAttack { static void Postfix(FleshPrison __instance, EnemyIdentifier ___eid) { if (!__instance.altVersion) return; GameObject obj = new GameObject(); obj.transform.position = __instance.transform.position + Vector3.up; FleshPrisonRotatingInsignia flag = obj.AddComponent<FleshPrisonRotatingInsignia>(); flag.prison = __instance; flag.damageMod = ___eid.totalDamageModifier; flag.speedMod = ___eid.totalSpeedModifier; } } class Panopticon_SpawnBlackHole { static void Postfix(FleshPrison __instance, EnemyIdentifier ___eid) { if (!__instance.altVersion) return; Vector3 vector = MonoSingleton<PlayerTracker>.Instance.PredictPlayerPosition(0.5f / ___eid.totalSpeedModifier); GameObject gameObject = GameObject.Instantiate(Plugin.sisyphusDestroyExplosion, vector, Quaternion.identity); GoreZone gz = __instance.GetComponentInParent<GoreZone>(); gameObject.transform.SetParent(gz == null ? __instance.transform : gz.transform); LineRenderer componentInChildren = gameObject.GetComponentInChildren<LineRenderer>(); if (componentInChildren) { componentInChildren.SetPosition(0, vector); componentInChildren.SetPosition(1, __instance.transform.position); } foreach (Explosion explosion in gameObject.GetComponentsInChildren<Explosion>()) { explosion.speed *= ___eid.totalSpeedModifier; explosion.damage = Mathf.RoundToInt((float)explosion.damage * ___eid.totalDamageModifier); explosion.maxSize *= ___eid.totalDamageModifier; } } } class Panopticon_SpawnFleshDrones { struct StateInfo { public GameObject template; public bool changedToEye; } static bool Prefix(
FleshPrison __instance, int ___difficulty, int ___currentDrone, out StateInfo __state) {
__state = new StateInfo(); if (!__instance.altVersion) return true; if (___currentDrone % 2 == 0) { __state.template = __instance.skullDrone; __state.changedToEye = true; __instance.skullDrone = __instance.fleshDrone; } else { __state.template = __instance.fleshDrone; __state.changedToEye = false; __instance.fleshDrone = __instance.skullDrone; } return true; } static void Postfix(FleshPrison __instance, StateInfo __state) { if (!__instance.altVersion) return; if (__state.changedToEye) __instance.skullDrone = __state.template; else __instance.fleshDrone = __state.template; } } class Panopticon_BlueProjectile { public static void BlueProjectileSpawn(FleshPrison instance) { if (!instance.altVersion || !ConfigManager.panopticonBlueProjToggle.value) return; int count = ConfigManager.panopticonBlueProjCount.value; float deltaAngle = 360f / (count + 1); float currentAngle = deltaAngle; for (int i = 0; i < count; i++) { GameObject proj = GameObject.Instantiate(Plugin.homingProjectile, instance.rotationBone.position + instance.rotationBone.up * 16f, instance.rotationBone.rotation); proj.transform.position += proj.transform.forward * 5f; proj.transform.RotateAround(instance.transform.position, Vector3.up, currentAngle); currentAngle += deltaAngle; Projectile comp = proj.GetComponent<Projectile>(); comp.safeEnemyType = EnemyType.FleshPanopticon; comp.target = instance.target; comp.damage = ConfigManager.panopticonBlueProjDamage.value * instance.eid.totalDamageModifier; comp.turningSpeedMultiplier *= ConfigManager.panopticonBlueProjTurnSpeed.value; comp.speed = ConfigManager.panopticonBlueProjInitialSpeed.value; } } static MethodInfo m_Panopticon_BlueProjectile_BlueProjectileSpawn = typeof(Panopticon_BlueProjectile).GetMethod("BlueProjectileSpawn", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); static MethodInfo m_GameObject_GetComponent_Projectile = typeof(GameObject).GetMethod("GetComponent", new Type[0]).MakeGenericMethod(new Type[1] { typeof(Projectile) }); static IEnumerable Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Callvirt && code[i].OperandIs(m_GameObject_GetComponent_Projectile)) { i += 2; // Push instance reference code.Insert(i, new CodeInstruction(OpCodes.Ldarg_0)); i += 1; // Call the method code.Insert(i, new CodeInstruction(OpCodes.Call, m_Panopticon_BlueProjectile_BlueProjectileSpawn)); break; } } return code.AsEnumerable(); } } }
Ultrapain/Patches/Panopticon.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/OrbitalStrike.cs", "retrieved_chunk": " {\n public bool state = false;\n public string id;\n public int points;\n public GameObject templateExplosion;\n }\n static bool Prefix(Grenade __instance, ref float __3, out StateInfo __state,\n bool __1, bool __2)\n {\n __state = new StateInfo();", "score": 0.8780690431594849 }, { "filename": "Ultrapain/Patches/OrbitalStrike.cs", "retrieved_chunk": " class EnemyIdentifier_DeliverDamage\n {\n static Coin lastExplosiveCoin = null;\n class StateInfo\n {\n public bool canPostStyle = false;\n public OrbitalExplosionInfo info = null;\n }\n static bool Prefix(EnemyIdentifier __instance, out StateInfo __state, Vector3 __2, ref float __3)\n {", "score": 0.8744754791259766 }, { "filename": "Ultrapain/Patches/DruidKnight.cs", "retrieved_chunk": " public static float offset = 0.205f;\n class StateInfo\n {\n public GameObject oldProj;\n public GameObject tempProj;\n }\n static bool Prefix(Mandalore __instance, out StateInfo __state)\n {\n __state = new StateInfo() { oldProj = __instance.fullAutoProjectile };\n GameObject obj = new GameObject();", "score": 0.8598510026931763 }, { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": " //___eid.SpeedBuff();\n }\n }\n class Mindflayer_ShootProjectiles_Patch\n {\n public static float maxProjDistance = 5;\n public static float initialProjectileDistance = -1f;\n public static float distancePerProjShot = 0.2f;\n static bool Prefix(Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___enraged)\n {", "score": 0.8361532092094421 }, { "filename": "Ultrapain/Patches/V2Second.cs", "retrieved_chunk": " void PrepareAltFire()\n {\n }\n void AltFire()\n {\n }\n }\n class V2SecondUpdate\n {\n static bool Prefix(V2 __instance, ref int ___currentWeapon, ref Transform ___overrideTarget, ref Rigidbody ___overrideTargetRb, ref float ___shootCooldown,", "score": 0.8326119780540466 } ]
csharp
FleshPrison __instance, int ___difficulty, int ___currentDrone, out StateInfo __state) {
using BepInEx; using UnityEngine; using UnityEngine.SceneManagement; using System; using HarmonyLib; using System.IO; using Ultrapain.Patches; using System.Linq; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Reflection; using Steamworks; using Unity.Audio; using System.Text; using System.Collections.Generic; using UnityEngine.AddressableAssets; using UnityEngine.AddressableAssets.ResourceLocators; using UnityEngine.ResourceManagement.ResourceLocations; using UnityEngine.UIElements; using PluginConfig.API; namespace Ultrapain { [BepInPlugin(PLUGIN_GUID, PLUGIN_NAME, PLUGIN_VERSION)] [BepInDependency("com.eternalUnion.pluginConfigurator", "1.6.0")] public class Plugin : BaseUnityPlugin { public const string PLUGIN_GUID = "com.eternalUnion.ultraPain"; public const string PLUGIN_NAME = "Ultra Pain"; public const string PLUGIN_VERSION = "1.1.0"; public static Plugin instance; private static bool addressableInit = false; public static T LoadObject<T>(string path) { if (!addressableInit) { Addressables.InitializeAsync().WaitForCompletion(); addressableInit = true; } return Addressables.LoadAssetAsync<T>(path).WaitForCompletion(); } public static Vector3 PredictPlayerPosition(Collider safeCollider, float speedMod) { Transform target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f) return target.position; RaycastHit raycastHit; if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == safeCollider) return target.position; else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { return raycastHit.point; } else { Vector3 projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod; return new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z); } } public static GameObject projectileSpread; public static GameObject homingProjectile; public static GameObject hideousMassProjectile; public static
GameObject decorativeProjectile2;
public static GameObject shotgunGrenade; public static GameObject beam; public static GameObject turretBeam; public static GameObject lightningStrikeExplosiveSetup; public static GameObject lightningStrikeExplosive; public static GameObject lighningStrikeWindup; public static GameObject explosion; public static GameObject bigExplosion; public static GameObject sandExplosion; public static GameObject virtueInsignia; public static GameObject rocket; public static GameObject revolverBullet; public static GameObject maliciousCannonBeam; public static GameObject lightningBoltSFX; public static GameObject revolverBeam; public static GameObject blastwave; public static GameObject cannonBall; public static GameObject shockwave; public static GameObject sisyphiusExplosion; public static GameObject sisyphiusPrimeExplosion; public static GameObject explosionWaveKnuckleblaster; public static GameObject chargeEffect; public static GameObject maliciousFaceProjectile; public static GameObject hideousMassSpear; public static GameObject coin; public static GameObject sisyphusDestroyExplosion; //public static GameObject idol; public static GameObject ferryman; public static GameObject minosPrime; //public static GameObject maliciousFace; public static GameObject somethingWicked; public static Turret turret; public static GameObject turretFinalFlash; public static GameObject enrageEffect; public static GameObject v2flashUnparryable; public static GameObject ricochetSfx; public static GameObject parryableFlash; public static AudioClip cannonBallChargeAudio; public static Material gabrielFakeMat; public static Sprite blueRevolverSprite; public static Sprite greenRevolverSprite; public static Sprite redRevolverSprite; public static Sprite blueShotgunSprite; public static Sprite greenShotgunSprite; public static Sprite blueNailgunSprite; public static Sprite greenNailgunSprite; public static Sprite blueSawLauncherSprite; public static Sprite greenSawLauncherSprite; public static GameObject rocketLauncherAlt; public static GameObject maliciousRailcannon; // Variables public static float SoliderShootAnimationStart = 1.2f; public static float SoliderGrenadeForce = 10000f; public static float SwordsMachineKnockdownTimeNormalized = 0.8f; public static float SwordsMachineCoreSpeed = 80f; public static float MinGrenadeParryVelocity = 40f; public static GameObject _lighningBoltSFX; public static GameObject lighningBoltSFX { get { if (_lighningBoltSFX == null) _lighningBoltSFX = ferryman.gameObject.transform.Find("LightningBoltChimes").gameObject; return _lighningBoltSFX; } } private static bool loadedPrefabs = false; public void LoadPrefabs() { if (loadedPrefabs) return; loadedPrefabs = true; // Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab projectileSpread = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab homingProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab decorativeProjectile2 = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab"); // Assets/Prefabs/Attacks and Projectiles/Grenade.prefab shotgunGrenade = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Grenade.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab turretBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab beam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab lightningStrikeExplosiveSetup = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab"); // Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab lighningStrikeWindup = LoadObject<GameObject>("Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab"); //[bundle-0][assets/prefabs/enemies/idol.prefab] //idol = LoadObject<GameObject>("assets/prefabs/enemies/idol.prefab"); // Assets/Prefabs/Enemies/Ferryman.prefab ferryman = LoadObject<GameObject>("Assets/Prefabs/Enemies/Ferryman.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab explosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab bigExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab sandExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab"); // Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab virtueInsignia = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab hideousMassProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab"); // Assets/Particles/Enemies/RageEffect.prefab enrageEffect = LoadObject<GameObject>("Assets/Particles/Enemies/RageEffect.prefab"); // Assets/Particles/Flashes/V2FlashUnparriable.prefab v2flashUnparryable = LoadObject<GameObject>("Assets/Particles/Flashes/V2FlashUnparriable.prefab"); // Assets/Prefabs/Attacks and Projectiles/Rocket.prefab rocket = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Rocket.prefab"); // Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab revolverBullet = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab maliciousCannonBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab revolverBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab blastwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab"); // Assets/Prefabs/Enemies/MinosPrime.prefab minosPrime = LoadObject<GameObject>("Assets/Prefabs/Enemies/MinosPrime.prefab"); // Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab cannonBall = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab"); // get from Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab cannonBallChargeAudio = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab").transform.Find("RocketLauncher/Armature/Body_Bone/HologramDisplay").GetComponent<AudioSource>().clip; // Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab shockwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab sisyphiusExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab sisyphiusPrimeExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab explosionWaveKnuckleblaster = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab - [bundle-0][assets/prefabs/explosionlightning variant.prefab] lightningStrikeExplosive = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab"); // Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab rocketLauncherAlt = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab"); // Assets/Prefabs/Weapons/Railcannon Malicious.prefab maliciousRailcannon = LoadObject<GameObject>("Assets/Prefabs/Weapons/Railcannon Malicious.prefab"); //Assets/Particles/SoundBubbles/Ricochet.prefab ricochetSfx = LoadObject<GameObject>("Assets/Particles/SoundBubbles/Ricochet.prefab"); //Assets/Particles/Flashes/Flash.prefab parryableFlash = LoadObject<GameObject>("Assets/Particles/Flashes/Flash.prefab"); //Assets/Prefabs/Attacks and Projectiles/Spear.prefab hideousMassSpear = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Spear.prefab"); //Assets/Prefabs/Enemies/Wicked.prefab somethingWicked = LoadObject<GameObject>("Assets/Prefabs/Enemies/Wicked.prefab"); //Assets/Textures/UI/SingleRevolver.png blueRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/SingleRevolver.png"); //Assets/Textures/UI/RevolverSpecial.png greenRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSpecial.png"); //Assets/Textures/UI/RevolverSharp.png redRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSharp.png"); //Assets/Textures/UI/Shotgun.png blueShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun.png"); //Assets/Textures/UI/Shotgun1.png greenShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun1.png"); //Assets/Textures/UI/Nailgun2.png blueNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Nailgun2.png"); //Assets/Textures/UI/NailgunOverheat.png greenNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/NailgunOverheat.png"); //Assets/Textures/UI/SawbladeLauncher.png blueSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncher.png"); //Assets/Textures/UI/SawbladeLauncherOverheat.png greenSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncherOverheat.png"); //Assets/Prefabs/Attacks and Projectiles/Coin.prefab coin = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Coin.prefab"); //Assets/Materials/GabrielFake.mat gabrielFakeMat = LoadObject<Material>("Assets/Materials/GabrielFake.mat"); //Assets/Prefabs/Enemies/Turret.prefab turret = LoadObject<GameObject>("Assets/Prefabs/Enemies/Turret.prefab").GetComponent<Turret>(); //Assets/Particles/Flashes/GunFlashDistant.prefab turretFinalFlash = LoadObject<GameObject>("Assets/Particles/Flashes/GunFlashDistant.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab sisyphusDestroyExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab"); //Assets/Prefabs/Effects/Charge Effect.prefab chargeEffect = LoadObject<GameObject>("Assets/Prefabs/Effects/Charge Effect.prefab"); //Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab maliciousFaceProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab"); } public static bool ultrapainDifficulty = false; public static bool realUltrapainDifficulty = false; public static GameObject currentDifficultyButton; public static GameObject currentDifficultyPanel; public static Text currentDifficultyInfoText; public void OnSceneChange(Scene before, Scene after) { StyleIDs.RegisterIDs(); ScenePatchCheck(); string mainMenuSceneName = "b3e7f2f8052488a45b35549efb98d902"; string bootSequenceSceneName = "4f8ecffaa98c2614f89922daf31fa22d"; string currentSceneName = SceneManager.GetActiveScene().name; if (currentSceneName == mainMenuSceneName) { LoadPrefabs(); //Canvas/Difficulty Select (1)/Violent Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Difficulty Select (1)"); GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect); currentDifficultyButton = ultrapainButton; ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value; ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5; RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>(); ultrapainTrans.anchoredPosition = new Vector2(20f, -104f); //Canvas/Difficulty Select (1)/Violent Info GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect); currentDifficultyPanel = info; currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>(); currentDifficultyInfoText.text = ConfigManager.pluginInfo.value; Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>(); currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--"; currentDifficultyHeaderText.resizeTextForBestFit = true; currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap; currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate; info.SetActive(false); EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>(); evt.triggers.Clear(); /*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(false));*/ EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit }; trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false)); evt.triggers.Add(trigger1); evt.triggers.Add(trigger2); foreach(EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>()) { if (trigger.gameObject == ultrapainButton) continue; EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false)); trigger.triggers.Add(closeTrigger); } } else if(currentSceneName == bootSequenceSceneName) { LoadPrefabs(); //Canvas/Difficulty Select (1)/Violent Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Intro/Difficulty Select"); GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect); currentDifficultyButton = ultrapainButton; ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value; ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5; RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>(); ultrapainTrans.anchoredPosition = new Vector2(20f, -104f); //Canvas/Difficulty Select (1)/Violent Info GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect); currentDifficultyPanel = info; currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>(); currentDifficultyInfoText.text = ConfigManager.pluginInfo.value; Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>(); currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--"; currentDifficultyHeaderText.resizeTextForBestFit = true; currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap; currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate; info.SetActive(false); EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>(); evt.triggers.Clear(); /*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(false));*/ EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit }; trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false)); evt.triggers.Add(trigger1); evt.triggers.Add(trigger2); foreach (EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>()) { if (trigger.gameObject == ultrapainButton) continue; EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false)); trigger.triggers.Add(closeTrigger); } } // LOAD CUSTOM PREFABS HERE TO AVOID MID GAME LAG MinosPrimeCharge.CreateDecoy(); GameObject shockwaveSisyphus = SisyphusInstructionist_Start.shockwave; } public static class StyleIDs { private static bool registered = false; public static void RegisterIDs() { registered = false; if (MonoSingleton<StyleHUD>.Instance == null) return; MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.grenadeBoostStyleText.guid, ConfigManager.grenadeBoostStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.rocketBoostStyleText.guid, ConfigManager.rocketBoostStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverStyleText.guid, ConfigManager.orbStrikeRevolverStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverChargedStyleText.guid, ConfigManager.orbStrikeRevolverChargedStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeElectricCannonStyleText.guid, ConfigManager.orbStrikeElectricCannonStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeMaliciousCannonStyleText.guid, ConfigManager.orbStrikeMaliciousCannonStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.maliciousChargebackStyleText.guid, ConfigManager.maliciousChargebackStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.sentryChargebackStyleText.guid, ConfigManager.sentryChargebackStyleText.formattedString); registered = true; Debug.Log("Registered all style ids"); } private static FieldInfo idNameDict = typeof(StyleHUD).GetField("idNameDict", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); public static void UpdateID(string id, string newName) { if (!registered || StyleHUD.Instance == null) return; (idNameDict.GetValue(StyleHUD.Instance) as Dictionary<string, string>)[id] = newName; } } public static Harmony harmonyTweaks; public static Harmony harmonyBase; private static MethodInfo GetMethod<T>(string name) { return typeof(T).GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } private static Dictionary<MethodInfo, HarmonyMethod> methodCache = new Dictionary<MethodInfo, HarmonyMethod>(); private static HarmonyMethod GetHarmonyMethod(MethodInfo method) { if (methodCache.TryGetValue(method, out HarmonyMethod harmonyMethod)) return harmonyMethod; else { harmonyMethod = new HarmonyMethod(method); methodCache.Add(method, harmonyMethod); return harmonyMethod; } } private static void PatchAllEnemies() { if (!ConfigManager.enemyTweakToggle.value) return; if (ConfigManager.friendlyFireDamageOverrideToggle.value) { harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<PhysicalShockwave>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<VirtueInsignia>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_FF>("Prefix"))); harmonyTweaks.Patch(GetMethod<Flammable>("Burn"), prefix: GetHarmonyMethod(GetMethod<Flammable_Burn_FF>("Prefix"))); harmonyTweaks.Patch(GetMethod<FireZone>("OnTriggerStay"), prefix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Postfix"))); } harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("UpdateModifiers"), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_UpdateModifiers>("Postfix"))); harmonyTweaks.Patch(GetMethod<StatueBoss>("Start"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Start_Patch>("Postfix"))); if (ConfigManager.cerberusDashToggle.value) harmonyTweaks.Patch(GetMethod<StatueBoss>("StopDash"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopDash_Patch>("Postfix"))); if(ConfigManager.cerberusParryable.value) { harmonyTweaks.Patch(GetMethod<StatueBoss>("StopTracking"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopTracking_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<StatueBoss>("Stomp"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Stomp_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Statue>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Statue_GetHurt_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Drone_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Drone>("Shoot"), prefix: GetHarmonyMethod(GetMethod<Drone_Shoot_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("PlaySound"), prefix: GetHarmonyMethod(GetMethod<Drone_PlaySound_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Update"), postfix: GetHarmonyMethod(GetMethod<Drone_Update>("Postfix"))); if(ConfigManager.droneHomeToggle.value) { harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Drone_Death_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Drone_GetHurt_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Ferryman>("Start"), postfix: GetHarmonyMethod(GetMethod<FerrymanStart>("Postfix"))); if(ConfigManager.ferrymanComboToggle.value) harmonyTweaks.Patch(GetMethod<Ferryman>("StopMoving"), postfix: GetHarmonyMethod(GetMethod<FerrymanStopMoving>("Postfix"))); if(ConfigManager.filthExplodeToggle.value) harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch2>("Prefix"))); if(ConfigManager.fleshPrisonSpinAttackToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<FleshPrisonShoot>("Postfix"))); if (ConfigManager.hideousMassInsigniaToggle.value) { harmonyTweaks.Patch(GetMethod<Projectile>("Explode"), postfix: GetHarmonyMethod(GetMethod<Projectile_Explode_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Mass>("ShootExplosive"), postfix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Postfix")), prefix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Prefix"))); } harmonyTweaks.Patch(GetMethod<SpiderBody>("Start"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<SpiderBody>("ChargeBeam"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ChargeBeam>("Postfix"))); harmonyTweaks.Patch(GetMethod<SpiderBody>("BeamChargeEnd"), prefix: GetHarmonyMethod(GetMethod<MaliciousFace_BeamChargeEnd>("Prefix"))); if (ConfigManager.maliciousFaceHomingProjectileToggle.value) { harmonyTweaks.Patch(GetMethod<SpiderBody>("ShootProj"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ShootProj_Patch>("Postfix"))); } if (ConfigManager.maliciousFaceRadianceOnEnrage.value) harmonyTweaks.Patch(GetMethod<SpiderBody>("Enrage"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Enrage_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Mindflayer>("Start"), postfix: GetHarmonyMethod(GetMethod<Mindflayer_Start_Patch>("Postfix"))); if (ConfigManager.mindflayerShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<Mindflayer>("ShootProjectiles"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_ShootProjectiles_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_MF>("Prefix"))); } if (ConfigManager.mindflayerTeleportComboToggle.value) { harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Mindflayer>("MeleeTeleport"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_MeleeTeleport_Patch>("Prefix"))); //harmonyTweaks.Patch(GetMethod<SwingCheck2>("DamageStop"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_DamageStop_Patch>("Postfix"))); } if (ConfigManager.minosPrimeRandomTeleportToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("Postfix"))); if (ConfigManager.minosPrimeTeleportTrail.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("Teleport"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("TeleportPostfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Start"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Dropkick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Dropkick>("Prefix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Combo"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Combo>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("StopAction"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_StopAction>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Ascend"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Ascend>("Prefix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Death"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Death>("Prefix"))); if (ConfigManager.minosPrimeCrushAttackToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("RiderKick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_RiderKick>("Prefix"))); if (ConfigManager.minosPrimeComboExplosiveEndToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_ProjectileCharge>("Prefix"))); if (ConfigManager.schismSpreadAttackToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ShootProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ShootProjectile_Patch>("Postfix"))); if (ConfigManager.soliderShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<Solider_Start_Patch>("Postfix"))); } if(ConfigManager.soliderCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_SpawnProjectile_Patch>("Postfix"))); if (ConfigManager.soliderShootGrenadeToggle.value || ConfigManager.soliderShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_ThrowProjectile_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Stalker>("SandExplode"), prefix: GetHarmonyMethod(GetMethod<Stalker_SandExplode_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SandificationZone>("Enter"), postfix: GetHarmonyMethod(GetMethod<SandificationZone_Enter_Patch>("Postfix"))); if (ConfigManager.strayCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Swing>("Postfix"))); if (ConfigManager.strayShootToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_Start_Patch1>("Postfix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ThrowProjectile_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<SwingEnd>("Prefix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("DamageEnd"), prefix: GetHarmonyMethod(GetMethod<DamageEnd>("Prefix"))); } if(ConfigManager.streetCleanerCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<Streetcleaner>("Start"), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Start_Patch>("Postfix"))); if(ConfigManager.streetCleanerPredictiveDodgeToggle.value) harmonyTweaks.Patch(GetMethod<BulletCheck>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<BulletCheck_OnTriggerEnter_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("Start"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Start>("Postfix"))); if (ConfigManager.swordsMachineNoLightKnockbackToggle.value || ConfigManager.swordsMachineSecondPhaseMode.value != ConfigManager.SwordsMachineSecondPhase.None) { harmonyTweaks.Patch(GetMethod<SwordsMachine>("Knockdown"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Knockdown_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("Down"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Prefix"))); //harmonyTweaks.Patch(GetMethod<SwordsMachine>("SetSpeed"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_SetSpeed_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("EndFirstPhase"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Prefix"))); } if (ConfigManager.swordsMachineExplosiveSwordToggle.value) { harmonyTweaks.Patch(GetMethod<ThrownSword>("Start"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<ThrownSword>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_OnTriggerEnter_Patch>("Postfix"))); } harmonyTweaks.Patch(GetMethod<Turret>("Start"), postfix: GetHarmonyMethod(GetMethod<TurretStart>("Postfix"))); if(ConfigManager.turretBurstFireToggle.value) { harmonyTweaks.Patch(GetMethod<Turret>("Shoot"), prefix: GetHarmonyMethod(GetMethod<TurretShoot>("Prefix"))); harmonyTweaks.Patch(GetMethod<Turret>("StartAiming"), postfix: GetHarmonyMethod(GetMethod<TurretAim>("Postfix"))); } harmonyTweaks.Patch(GetMethod<Explosion>("Start"), postfix: GetHarmonyMethod(GetMethod<V2CommonExplosion>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2FirstStart>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2FirstUpdate>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2FirstShootWeapon>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2SecondStart>("Postfix"))); //if(ConfigManager.v2SecondStartEnraged.value) // harmonyTweaks.Patch(GetMethod<BossHealthBar>("OnEnable"), postfix: GetHarmonyMethod(GetMethod<V2SecondEnrage>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2SecondUpdate>("Prefix"))); //harmonyTweaks.Patch(GetMethod<V2>("AltShootWeapon"), postfix: GetHarmonyMethod(GetMethod<V2AltShootWeapon>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("SwitchWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondSwitchWeapon>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Prefix")), postfix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Postfix"))); if(ConfigManager.v2SecondFastCoinToggle.value) harmonyTweaks.Patch(GetMethod<V2>("ThrowCoins"), prefix: GetHarmonyMethod(GetMethod<V2SecondFastCoin>("Prefix"))); harmonyTweaks.Patch(GetMethod<Cannonball>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<V2RocketLauncher>("CannonBallTriggerPrefix"))); if (ConfigManager.v2FirstSharpshooterToggle.value || ConfigManager.v2SecondSharpshooterToggle.value) { harmonyTweaks.Patch(GetMethod<EnemyRevolver>("PrepareAltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverPrepareAltFire>("Prefix"))); harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverBullet>("Prefix"))); harmonyTweaks.Patch(GetMethod<EnemyRevolver>("AltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverAltShoot>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Virtue_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Drone>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Virtue_SpawnInsignia_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Virtue_Death_Patch>("Prefix"))); if (ConfigManager.sisyInstJumpShockwave.value) { harmonyTweaks.Patch(GetMethod<Sisyphus>("Start"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Sisyphus>("Update"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Update>("Postfix"))); } if(ConfigManager.sisyInstBoulderShockwave.value) harmonyTweaks.Patch(GetMethod<Sisyphus>("SetupExplosion"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_SetupExplosion>("Postfix"))); if(ConfigManager.sisyInstStrongerExplosion.value) harmonyTweaks.Patch(GetMethod<Sisyphus>("StompExplosion"), prefix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_StompExplosion>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("Awake"), postfix: GetHarmonyMethod(GetMethod<LeviathanTail_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("BigSplash"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_BigSplash>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_SwingEnd>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("Start"), postfix: GetHarmonyMethod(GetMethod<Leviathan_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurst"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurstStart"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurstStart>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<Leviathan_FixedUpdate>("Prefix"))); if (ConfigManager.somethingWickedSpear.value) { harmonyTweaks.Patch(GetMethod<Wicked>("Start"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_GetHit>("Postfix"))); } if(ConfigManager.somethingWickedSpawnOn43.value) { harmonyTweaks.Patch(GetMethod<ObjectActivator>("Activate"), prefix: GetHarmonyMethod(GetMethod<ObjectActivator_Activate>("Prefix"))); harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<JokeWicked_GetHit>("Postfix"))); } if (ConfigManager.panopticonFullPhase.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Panopticon_Start>("Postfix"))); if (ConfigManager.panopticonAxisBeam.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnInsignia>("Prefix"))); if (ConfigManager.panopticonSpinAttackToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<Panopticon_HomingProjectileAttack>("Postfix"))); if (ConfigManager.panopticonBlackholeProj.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnBlackHole"), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnBlackHole>("Postfix"))); if (ConfigManager.panopticonBalanceEyes.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnFleshDrones"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Postfix"))); if (ConfigManager.panopticonBlueProjToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Update"), transpiler: GetHarmonyMethod(GetMethod<Panopticon_BlueProjectile>("Transpiler"))); if (ConfigManager.idolExplosionToggle.value) harmonyTweaks.Patch(GetMethod<Idol>("Death"), postfix: GetHarmonyMethod(GetMethod<Idol_Death_Patch>("Postfix"))); // ADDME /* harmonyTweaks.Patch(GetMethod<GabrielSecond>("Start"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("BasicCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_BasicCombo>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("FastCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_FastCombo>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("CombineSwords"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_CombineSwords>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("ThrowCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_ThrowCombo>("Postfix"))); */ } private static void PatchAllPlayers() { if (!ConfigManager.playerTweakToggle.value) return; harmonyTweaks.Patch(GetMethod<Punch>("CheckForProjectile"), prefix: GetHarmonyMethod(GetMethod<Punch_CheckForProjectile_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch1>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Collision"), prefix: GetHarmonyMethod(GetMethod<Grenade_Collision_Patch>("Prefix"))); if (ConfigManager.rocketBoostToggle.value) harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_Patch>("Prefix"))); if (ConfigManager.rocketGrabbingToggle.value) harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate_Patch>("Prefix"))); if (ConfigManager.orbStrikeToggle.value) { harmonyTweaks.Patch(GetMethod<Coin>("Start"), postfix: GetHarmonyMethod(GetMethod<Coin_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Punch>("BlastCheck"), prefix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Postfix"))); harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide>("Prefix"))); harmonyTweaks.Patch(GetMethod<Coin>("DelayedReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_DelayedReflectRevolver>("Postfix"))); harmonyTweaks.Patch(GetMethod<Coin>("ReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Postfix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Prefix")), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Postfix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("ExecuteHits"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Prefix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("HitSomething"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Prefix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("Start"), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_Start>("Prefix"))); harmonyTweaks.Patch(GetMethod<Cannonball>("Explode"), prefix: GetHarmonyMethod(GetMethod<Cannonball_Explode>("Prefix"))); harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_CollideOrbital>("Prefix"))); } if(ConfigManager.chargedRevRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<Revolver>("Update"), prefix: GetHarmonyMethod(GetMethod<Revolver_Update>("Prefix"))); if(ConfigManager.coinRegSpeedMulti.value != 1 || ConfigManager.sharpshooterRegSpeedMulti.value != 1 || ConfigManager.railcannonRegSpeedMulti.value != 1 || ConfigManager.rocketFreezeRegSpeedMulti.value != 1 || ConfigManager.rocketCannonballRegSpeedMulti.value != 1 || ConfigManager.nailgunAmmoRegSpeedMulti.value != 1 || ConfigManager.sawAmmoRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<WeaponCharges>("Charge"), prefix: GetHarmonyMethod(GetMethod<WeaponCharges_Charge>("Prefix"))); if(ConfigManager.nailgunHeatsinkRegSpeedMulti.value != 1 || ConfigManager.sawHeatsinkRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<Nailgun>("Update"), prefix: GetHarmonyMethod(GetMethod<NailGun_Update>("Prefix"))); if(ConfigManager.staminaRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<NewMovement>("Update"), prefix: GetHarmonyMethod(GetMethod<NewMovement_Update>("Prefix"))); if(ConfigManager.playerHpDeltaToggle.value || ConfigManager.maxPlayerHp.value != 100 || ConfigManager.playerHpSupercharge.value != 200 || ConfigManager.whiplashHardDamageCap.value != 50 || ConfigManager.whiplashHardDamageSpeed.value != 1) { harmonyTweaks.Patch(GetMethod<NewMovement>("GetHealth"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHealth>("Prefix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("SuperCharge"), prefix: GetHarmonyMethod(GetMethod<NewMovement_SuperCharge>("Prefix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("Respawn"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Respawn>("Postfix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("Start"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Transpiler"))); harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), transpiler: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate>("Transpiler"))); harmonyTweaks.Patch(GetMethod<NewMovement>("ForceAntiHP"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_ForceAntiHP>("Transpiler"))); } // ADDME harmonyTweaks.Patch(GetMethod<Revolver>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Revolver_Shoot>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Shotgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Transpiler")), prefix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Postfix"))); harmonyTweaks.Patch(GetMethod<Shotgun>("ShootSinks"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_ShootSinks>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Nailgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_Shoot>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Nailgun>("SuperSaw"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_SuperSaw>("Transpiler"))); if (ConfigManager.hardDamagePercent.normalizedValue != 1) harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Prefix")), postfix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Postfix"))); harmonyTweaks.Patch(GetMethod<HealthBar>("Start"), postfix: GetHarmonyMethod(GetMethod<HealthBar_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<HealthBar>("Update"), transpiler: GetHarmonyMethod(GetMethod<HealthBar_Update>("Transpiler"))); foreach (HealthBarTracker hb in HealthBarTracker.instances) { if (hb != null) hb.SetSliderRange(); } harmonyTweaks.Patch(GetMethod<Harpoon>("Start"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Start>("Postfix"))); if(ConfigManager.screwDriverHomeToggle.value) harmonyTweaks.Patch(GetMethod<Harpoon>("Punched"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Punched>("Postfix"))); if(ConfigManager.screwDriverSplitToggle.value) harmonyTweaks.Patch(GetMethod<Harpoon>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<Harpoon_OnTriggerEnter_Patch>("Prefix"))); } private static void PatchAllMemes() { if (ConfigManager.enrageSfxToggle.value) harmonyTweaks.Patch(GetMethod<EnrageEffect>("Start"), postfix: GetHarmonyMethod(GetMethod<EnrageEffect_Start>("Postfix"))); if(ConfigManager.funnyDruidKnightSFXToggle.value) { harmonyTweaks.Patch(GetMethod<Mandalore>("FullBurst"), postfix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Postfix")), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<Mandalore>("FullerBurst"), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullerBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Explode"), prefix: GetHarmonyMethod(GetMethod<Drone_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Drone_Explode>("Postfix"))); } if (ConfigManager.fleshObamiumToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Prefix"))); if (ConfigManager.obamapticonToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Prefix"))); } public static bool methodsPatched = false; public static void ScenePatchCheck() { if(methodsPatched && !ultrapainDifficulty) { harmonyTweaks.UnpatchSelf(); methodsPatched = false; } else if(!methodsPatched && ultrapainDifficulty) { PatchAll(); } } public static void PatchAll() { harmonyTweaks.UnpatchSelf(); methodsPatched = false; if (!ultrapainDifficulty) return; if(realUltrapainDifficulty && ConfigManager.discordRichPresenceToggle.value) harmonyTweaks.Patch(GetMethod<DiscordController>("SendActivity"), prefix: GetHarmonyMethod(GetMethod<DiscordController_SendActivity_Patch>("Prefix"))); if (realUltrapainDifficulty && ConfigManager.steamRichPresenceToggle.value) harmonyTweaks.Patch(GetMethod<SteamFriends>("SetRichPresence"), prefix: GetHarmonyMethod(GetMethod<SteamFriends_SetRichPresence_Patch>("Prefix"))); PatchAllEnemies(); PatchAllPlayers(); PatchAllMemes(); methodsPatched = true; } public static string workingPath; public static string workingDir; public static AssetBundle bundle; public static AudioClip druidKnightFullAutoAud; public static AudioClip druidKnightFullerAutoAud; public static AudioClip druidKnightDeathAud; public static AudioClip enrageAudioCustom; public static GameObject fleshObamium; public static GameObject obamapticon; public void Awake() { instance = this; workingPath = Assembly.GetExecutingAssembly().Location; workingDir = Path.GetDirectoryName(workingPath); Logger.LogInfo($"Working path: {workingPath}, Working dir: {workingDir}"); try { bundle = AssetBundle.LoadFromFile(Path.Combine(workingDir, "ultrapain")); druidKnightFullAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullauto.wav"); druidKnightFullerAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullerauto.wav"); druidKnightDeathAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/death.wav"); enrageAudioCustom = bundle.LoadAsset<AudioClip>("assets/ultrapain/sfx/enraged.wav"); fleshObamium = bundle.LoadAsset<GameObject>("assets/ultrapain/fleshprison/fleshobamium.prefab"); obamapticon = bundle.LoadAsset<GameObject>("assets/ultrapain/panopticon/obamapticon.prefab"); } catch (Exception e) { Logger.LogError($"Could not load the asset bundle:\n{e}"); } // DEBUG /*string logPath = Path.Combine(Environment.CurrentDirectory, "log.txt"); Logger.LogInfo($"Saving to {logPath}"); List<string> assetPaths = new List<string>() { "fonts.bundle", "videos.bundle", "shaders.bundle", "particles.bundle", "materials.bundle", "animations.bundle", "prefabs.bundle", "physicsmaterials.bundle", "models.bundle", "textures.bundle", }; //using (FileStream log = File.Open(logPath, FileMode.OpenOrCreate, FileAccess.Write)) //{ foreach(string assetPath in assetPaths) { Logger.LogInfo($"Attempting to load {assetPath}"); AssetBundle bundle = AssetBundle.LoadFromFile(Path.Combine(bundlePath, assetPath)); bundles.Add(bundle); //foreach (string name in bundle.GetAllAssetNames()) //{ // string line = $"[{bundle.name}][{name}]\n"; // log.Write(Encoding.ASCII.GetBytes(line), 0, line.Length); //} bundle.LoadAllAssets(); } //} */ // Plugin startup logic Logger.LogInfo($"Plugin {PluginInfo.PLUGIN_GUID} is loaded!"); harmonyTweaks = new Harmony(PLUGIN_GUID + "_tweaks"); harmonyBase = new Harmony(PLUGIN_GUID + "_base"); harmonyBase.Patch(GetMethod<DifficultySelectButton>("SetDifficulty"), postfix: GetHarmonyMethod(GetMethod<DifficultySelectPatch>("Postfix"))); harmonyBase.Patch(GetMethod<DifficultyTitle>("Check"), postfix: GetHarmonyMethod(GetMethod<DifficultyTitle_Check_Patch>("Postfix"))); harmonyBase.Patch(typeof(PrefsManager).GetConstructor(new Type[0]), postfix: GetHarmonyMethod(GetMethod<PrefsManager_Ctor>("Postfix"))); harmonyBase.Patch(GetMethod<PrefsManager>("EnsureValid"), prefix: GetHarmonyMethod(GetMethod<PrefsManager_EnsureValid>("Prefix"))); harmonyBase.Patch(GetMethod<Grenade>("Explode"), prefix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Prefix")), postfix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Postfix"))); LoadPrefabs(); ConfigManager.Initialize(); SceneManager.activeSceneChanged += OnSceneChange; } } public static class Tools { private static Transform _target; private static Transform target { get { if(_target == null) _target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); return _target; } } public static Vector3 PredictPlayerPosition(float speedMod, Collider enemyCol = null) { Vector3 projectedPlayerPos; if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f) { return target.position; } RaycastHit raycastHit; if (enemyCol != null && Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == enemyCol) { projectedPlayerPos = target.position; } else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { projectedPlayerPos = raycastHit.point; } else { projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod; projectedPlayerPos = new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z); } return projectedPlayerPos; } } // Asset destroyer tracker /*[HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object) })] public class TempClass1 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object), typeof(float) })] public class TempClass2 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object) })] public class TempClass3 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object), typeof(bool) })] public class TempClass4 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } }*/ }
Ultrapain/Plugin.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Leviathan.cs", "retrieved_chunk": " {\n proj = GameObject.Instantiate(Plugin.hideousMassProjectile, ___shootPoint.position, ___shootPoint.rotation);\n comp = proj.GetComponent<Projectile>();\n comp.target = MonoSingleton<PlayerTracker>.Instance.GetTarget();\n comp.safeEnemyType = EnemyType.Leviathan;\n // values from p2 flesh prison\n comp.turnSpeed *= 4f;\n comp.turningSpeedMultiplier *= 4f;\n comp.predictiveHomingMultiplier = 1.25f;\n }", "score": 0.8300449848175049 }, { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": " if (___eid.drillers.Count > 0)\n return false;\n Vector3 targetPosition = MonoSingleton<PlayerTracker>.Instance.PredictPlayerPosition(0.9f) + deltaPosition;\n float distance = Vector3.Distance(__instance.transform.position, targetPosition);\n Ray targetRay = new Ray(__instance.transform.position, targetPosition - __instance.transform.position);\n RaycastHit hit;\n if (Physics.Raycast(targetRay, out hit, distance, ___environmentMask, QueryTriggerInteraction.Ignore))\n {\n targetPosition = targetRay.GetPoint(Mathf.Max(0.0f, hit.distance - 1.0f));\n }", "score": 0.8253244161605835 }, { "filename": "Ultrapain/Patches/V2Second.cs", "retrieved_chunk": " Vector3 predictedPosition = MonoSingleton<PlayerTracker>.Instance.PredictPlayerPosition(1.0f);\n float velocity = Mathf.Clamp(distance, Mathf.Max(magnitude - 5.0f, 0), magnitude + 5);\n rocket.transform.LookAt(predictedPosition);\n rocket.GetComponent<Grenade>().rocketSpeed = velocity;\n rb.maxAngularVelocity = velocity;\n rb.velocity = Vector3.zero;\n rb.AddRelativeForce(Vector3.forward * magnitude * rb.mass, ForceMode.VelocityChange);\n // rb.velocity = rocket.transform.forward * velocity;\n */\n // NEW PREDICTION", "score": 0.8234094381332397 }, { "filename": "Ultrapain/Patches/V2Second.cs", "retrieved_chunk": " }\n else\n {*/\n Debug.Log($\"{debugTag} Targeted player with random spread\");\n targetPosition = playerTarget.transform.position + UnityEngine.Random.onUnitSphere * 2f;\n //}\n }\n GameObject beam = Instantiate(Plugin.maliciousCannonBeam, v2trans.position, Quaternion.identity);\n beam.transform.position = new Vector3(beam.transform.position.x, v2trans.GetComponent<Collider>().bounds.center.y, beam.transform.position.z);\n beam.transform.LookAt(targetPosition);", "score": 0.8182072639465332 }, { "filename": "Ultrapain/Patches/Leviathan.cs", "retrieved_chunk": " }\n else */if (Physics.Raycast(player.transform.position, targetShootPoint - player.transform.position, out raycastHit, Vector3.Distance(targetShootPoint, player.transform.position), LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide))\n {\n targetShootPoint = raycastHit.point;\n }\n Invoke(\"Shoot\", ConfigManager.leviathanChargeDelay.value / comp.lcon.eid.totalSpeedModifier);\n }\n private Vector3 RandomVector(float min, float max)\n {\n return new Vector3(UnityEngine.Random.Range(min, max), UnityEngine.Random.Range(min, max), UnityEngine.Random.Range(min, max));", "score": 0.8179801106452942 } ]
csharp
GameObject decorativeProjectile2;
/* Copyright (c) 2023 Xavier Arpa López Thomas Peter ('Kingdox') Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using UnityEngine; using Kingdox.UniFlux.Core; namespace Kingdox.UniFlux.Benchmark { public class Benchmark_UniFlux : MonoFlux { [SerializeField] private
Marker _m_store_string_add = new Marker() {
K = "store<string,Action> ADD" }; [SerializeField] private Marker _m_store_int_add = new Marker() { K = "store<int,Action> ADD" }; [SerializeField] private Marker _m_store_byte_add = new Marker() { K = "store<byte,Action> ADD" }; [SerializeField] private Marker _m_store_bool_add = new Marker() { K = "store<bool,Action> ADD" }; [SerializeField] private Marker _m_store_string_remove = new Marker() { K = "store<string,Action> REMOVE" }; [SerializeField] private Marker _m_store_int_remove = new Marker() { K = "store<int,Action> REMOVE" }; [SerializeField] private Marker _m_store_byte_remove = new Marker() { K = "store<byte,Action> REMOVE" }; [SerializeField] private Marker _m_store_bool_remove = new Marker() { K = "store<bool,Action> REMOVE" }; [SerializeField] private Marker _m_dispatch_string = new Marker() { K = $"dispatch<string>" }; [SerializeField] private Marker _m_dispatch_int = new Marker() { K = $"dispatch<int>" }; [SerializeField] private Marker _m_dispatch_byte = new Marker() { K = $"dispatch<byte>" }; [SerializeField] private Marker _m_dispatch_bool = new Marker() { K = $"dispatch<bool>" }; private const byte __m_store = 52; private const byte __m_dispatch = 250; private Rect rect_area; private readonly Lazy<GUIStyle> _style = new Lazy<GUIStyle>(() => new GUIStyle("label") { fontSize = 28, alignment = TextAnchor.MiddleLeft, padding = new RectOffset(10, 0, 0, 0) }); [SerializeField] private int _iterations = default; [SerializeField] private List<string> _Results = default; public bool draw=true; public bool isUpdated = false; public bool isUpdated_store = false; public bool isUpdated_dispatch = false; protected override void OnFlux(in bool condition) { StoreTest_Add(); StoreTest_Remove(); } public void Start() { DispatchTest(); } private void Update() { if(!isUpdated) return; if(isUpdated_store) StoreTest_Add(); if(isUpdated_store) StoreTest_Remove(); if(isUpdated_dispatch) DispatchTest(); } private void StoreTest_Add() { // Store String if(_m_store_string_add.Execute) { _m_store_string_add.iteration=_iterations; _m_store_string_add.Begin(); for (int i = 0; i < _iterations; i++) { "Store".Store(Example_OnFlux, true); } _m_store_string_add.End(); } // Store Int if(_m_store_int_add.Execute) { _m_store_int_add.iteration=_iterations; _m_store_int_add.Begin(); for (int i = 0; i < _iterations; i++) { 42.Store(Example_OnFlux, true); } _m_store_int_add.End(); } // Store Byte if(_m_store_byte_add.Execute) { _m_store_byte_add.iteration=_iterations; _m_store_byte_add.Begin(); for (int i = 0; i < _iterations; i++) { Flux.Store(__m_store, Example_OnFlux, true); } _m_store_byte_add.End(); } // Store Bool if(_m_store_bool_add.Execute) { _m_store_bool_add.iteration=_iterations; _m_store_bool_add.Begin(); for (int i = 0; i < _iterations; i++) { Flux.Store(true, Example_OnFlux, true); } _m_store_bool_add.End(); } } private void StoreTest_Remove() { // Store String if(_m_store_string_remove.Execute) { _m_store_string_remove.iteration=_iterations; _m_store_string_remove.Begin(); for (int i = 0; i < _iterations; i++) { "Store".Store(Example_OnFlux, false); } _m_store_string_remove.End(); } // Store Int if(_m_store_int_remove.Execute) { _m_store_int_remove.iteration=_iterations; _m_store_int_remove.Begin(); for (int i = 0; i < _iterations; i++) { 42.Store(Example_OnFlux, false); } _m_store_int_remove.End(); } // Store Byte if(_m_store_byte_remove.Execute) { _m_store_byte_remove.iteration=_iterations; _m_store_byte_remove.Begin(); for (int i = 0; i < _iterations; i++) { Flux.Store(__m_store, Example_OnFlux, false); } _m_store_byte_remove.End(); } // Store Bool if(_m_store_bool_remove.Execute) { _m_store_bool_remove.iteration=_iterations; _m_store_bool_remove.Begin(); for (int i = 0; i < _iterations; i++) { Flux.Store(true, Example_OnFlux, false); } _m_store_bool_remove.End(); } } private void DispatchTest() { // Dispatch String if(_m_dispatch_string.Execute) { _m_dispatch_string.iteration=_iterations; _m_dispatch_string.Begin(); for (int i = 0; i < _iterations; i++) "UniFlux.Dispatch".Dispatch(); _m_dispatch_string.End(); } // Dispatch Int if(_m_dispatch_int.Execute) { _m_dispatch_int.iteration=_iterations; _m_dispatch_int.Begin(); for (int i = 0; i < _iterations; i++) 0.Dispatch(); _m_dispatch_int.End(); } // Dispatch Byte if(_m_dispatch_byte.Execute) { _m_dispatch_byte.iteration=_iterations; _m_dispatch_byte.Begin(); for (int i = 0; i < _iterations; i++) Flux.Dispatch(__m_dispatch); _m_dispatch_byte.End(); } // Dispatch Boolean if(_m_dispatch_bool.Execute) { _m_dispatch_bool.iteration=_iterations; _m_dispatch_bool.Begin(); for (int i = 0; i < _iterations; i++) Flux.Dispatch(true); _m_dispatch_bool.End(); } } [Flux("UniFlux.Dispatch")] private void Example_Dispatch_String(){} [Flux("UniFlux.Dispatch")] private void Example_Dispatch_String2(){} [Flux(0)] private void Example_Dispatch_Int(){} [Flux(__m_dispatch)] private void Example_Dispatch_Byte(){} [Flux(false)] private void Example_Dispatch_Boolean_2(){} [Flux(false)] private void Example_Dispatch_Boolean_3(){} [Flux(false)] private void Example_Dispatch_Boolean_4(){} [Flux(false)] private void Example_Dispatch_Boolean_5(){} [Flux(false)] private void Example_Dispatch_Boolean_6(){} [Flux(true)] private void Example_Dispatch_Boolean(){} private void Example_OnFlux(){} private void OnGUI() { if(!draw)return; _Results.Clear(); _Results.Add(_m_store_string_add.Visual); _Results.Add(_m_store_int_add.Visual); _Results.Add(_m_store_byte_add.Visual); _Results.Add(_m_store_bool_add.Visual); _Results.Add(_m_store_string_remove.Visual); _Results.Add(_m_store_int_remove.Visual); _Results.Add(_m_store_byte_remove.Visual); _Results.Add(_m_store_bool_remove.Visual); _Results.Add(_m_dispatch_string.Visual); _Results.Add(_m_dispatch_int.Visual); _Results.Add(_m_dispatch_byte.Visual); _Results.Add(_m_dispatch_bool.Visual); var height = (float) Screen.height / 2; for (int i = 0; i < _Results.Count; i++) { rect_area = new Rect(0, _style.Value.lineHeight * i, Screen.width, height); GUI.Label(rect_area, _Results[i], _style.Value); } } } }
Benchmark/General/Benchmark_UniFlux.cs
xavierarpa-UniFlux-a2d46de
[ { "filename": "Benchmark/Nest/Benchmark_Nest_UniFlux.cs", "retrieved_chunk": "using System;\nusing UnityEngine;\nnamespace Kingdox.UniFlux.Benchmark\n{\n public sealed class Benchmark_Nest_UniFlux : MonoFlux\n {\n [SerializeField] private Marker _mark_fluxAttribute = new Marker()\n {\n K = \"NestedModel Flux Attribute\"\n };", "score": 0.8869154453277588 }, { "filename": "Editor/MonoFluxEditor.cs", "retrieved_chunk": "using System.Reflection;\nusing System;\nusing System.Linq;\nusing System.Collections.Generic;\nnamespace Kingdox.UniFlux.Editor\n{\n [CustomEditor(typeof(MonoFlux), true)]\n public partial class MonoFluxEditor : UnityEditor.Editor\n {\n private MethodInfo[] methods_subscribeAttrb;", "score": 0.8734123706817627 }, { "filename": "Tests/EditMode/EditMode_Test_1.cs", "retrieved_chunk": "using System.Collections.Generic;\nusing NUnit.Framework;\nusing UnityEngine;\nusing UnityEngine.TestTools;\nusing Kingdox.UniFlux;\nusing Kingdox.UniFlux.Core;\nnamespace Kingdox.UniFlux.Tests\n{\n public class EditMode_Test_1\n {", "score": 0.8264302015304565 }, { "filename": "Runtime/MonoFluxExtension.cs", "retrieved_chunk": "using System.Linq;\nusing System.Reflection;\nnamespace Kingdox.UniFlux\n{\n ///<summary>\n /// static class that ensure to handle the FluxAttribute\n ///</summary>\n internal static class MonoFluxExtension\n {\n internal static readonly BindingFlags m_bindingflag_all = (BindingFlags)(-1);", "score": 0.802901029586792 }, { "filename": "Benchmark/Tool/Mark.cs", "retrieved_chunk": "using UnityEngine;\nusing UnityEngine.Profiling;\nnamespace Kingdox.UniFlux.Benchmark\n{\n [Serializable]\n public class Marker\n {\n [SerializeField] public bool Execute=true;\n [HideInInspector] public int iteration = 1;\n\t\t[HideInInspector] public readonly Stopwatch sw = new Stopwatch();", "score": 0.7917363047599792 } ]
csharp
Marker _m_store_string_add = new Marker() {
/* * Copyright (C) Antony Vitillo (aka Skarredghost), Perpetual eMotion 2023. * Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT). */ using System; using System.Threading; using System.Threading.Tasks; using UnityEngine; using vrroom.Dynaimic.GenerativeLogic; namespace vrroom.CubicMusic.CubesMgmt { /// <summary> /// Interface for objects that generate logic from an AI prompt /// </summary> public interface ICreatesLogicFromPrompt { /// <summary> /// Template used to give more context to every prompt to make the instructions clearer to the AI /// </summary>
AiPromptTemplate PromptTemplate {
get; } /// <summary> /// Generate logic for a group of objects from a text prompt /// </summary> /// <param name="prompt">The text prompt of the behaviour to implement</param> /// <param name="cancellationToken">Cancellation token</param> Task GenerateLogicForGroupFromText(string prompt, CancellationToken cancellationToken = default); /// <summary> /// Generate logic for a group of objects from a text prompt /// </summary> /// <param name="audioPrompt">The audio prompt of the behaviour to implement</param> /// <param name="cancellationToken">Cancellation token</param> Task GenerateLogicForGroupFromAudio(AudioClip audioPrompt, CancellationToken cancellationToken = default); } }
CubicMusic/Assets/_CubicMusic/Runtime/CubesManagement/Scripts/ICreatesLogicFromPrompt.cs
Perpetual-eMotion-DynaimicApps-46c94e0
[ { "filename": "CubicMusic/Assets/_DynaimicLogic/Runtime/AiQuerys/AiQueryPerformer.cs", "retrieved_chunk": " /// <summary>\n /// Base class for elements that can perform queries to AI cloud solutions (e.g. OpenAI APIs)\n /// </summary>\n public abstract class AiQueryPerformer\n {\n /// <summary>\n /// Event that is triggered when a textual prompt query is sent to the AI cloud solution.\n /// The parameter is the prompt that was sent\n /// </summary>\n public Action<string> OnPromptSent;", "score": 0.9258115291595459 }, { "filename": "CubicMusic/Assets/_DynaimicLogic/Runtime/GenerativeLogic/GenerativeLogicManager.cs", "retrieved_chunk": " /// (E.g. the pre-prompt may say \"Generate a Unity script that does this:\"\n /// so that the prompt asked by the user can only include the logic that \n /// the user wants)\n /// </summary>\n public class AiPromptTemplate\n {\n /// <summary>\n /// Sentence to be added before the prompt\n /// </summary>\n public string PrePrompt { get; set; } = string.Empty;", "score": 0.9117578268051147 }, { "filename": "CubicMusic/Assets/_CubicMusic/Runtime/UI/Scripts/AiStatusCanvas.cs", "retrieved_chunk": "{\n /// <summary>\n /// UI that displays the status of the AI operations\n /// </summary>\n public class AiStatusCanvas : MonoBehaviour\n {\n /// <summary>\n /// Text that shows the status of the AI operations\n /// </summary>\n [SerializeField]", "score": 0.9112048149108887 }, { "filename": "CubicMusic/Assets/_DynaimicLogic/Runtime/GenerativeLogic/GenerativeLogicManager.cs", "retrieved_chunk": " /// <summary>\n /// Maximum number of tokens to use for the completion\n /// </summary>\n public int MaxTokens { get; set; } = 2048;\n }\n /// <summary>\n /// Represents a template for a prompt to the AI.\n /// It lets specify some conditions to be applied around the\n /// prompt that has been specified by the user, so that to\n /// add some context that the AI system should use.", "score": 0.9022014737129211 }, { "filename": "CubicMusic/Assets/_DynaimicLogic/Runtime/GenerativeLogic/GenerativeLogicManager.cs", "retrieved_chunk": " /// <summary>\n /// Sentence to be added after the prompt\n /// </summary>\n public string PostPrompt { get; set; } = string.Empty;\n /// <summary>\n /// Generates the full prompt to be sent to the AI cloud solution\n /// </summary>\n /// <param name=\"prompt\">Prompt specified by the user</param>\n /// <returns>Compound prompt, ready to be read by the AI</returns>\n public string GenerateFullPrompt(string prompt)", "score": 0.9011901617050171 } ]
csharp
AiPromptTemplate PromptTemplate {
using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using System.Text; using ULTRAKILL.Cheats; using UnityEngine; namespace Ultrapain.Patches { class Leviathan_Flag : MonoBehaviour { private
LeviathanHead comp;
private Animator anim; //private Collider col; private LayerMask envMask = new LayerMask() { value = 1 << 8 | 1 << 24 }; public float playerRocketRideTracker = 0; private GameObject currentProjectileEffect; private AudioSource currentProjectileAud; private Transform shootPoint; public float currentProjectileSize = 0; public float beamChargeRate = 12f / 1f; public int beamRemaining = 0; public int projectilesRemaining = 0; public float projectileDelayRemaining = 0f; private static FieldInfo ___inAction = typeof(LeviathanHead).GetField("inAction", BindingFlags.NonPublic | BindingFlags.Instance); private void Awake() { comp = GetComponent<LeviathanHead>(); anim = GetComponent<Animator>(); //col = GetComponent<Collider>(); } public bool beamAttack = false; public bool projectileAttack = false; public bool charging = false; private void Update() { if (currentProjectileEffect != null && (charging || currentProjectileSize < 11.9f)) { currentProjectileSize += beamChargeRate * Time.deltaTime; currentProjectileEffect.transform.localScale = Vector3.one * currentProjectileSize; currentProjectileAud.pitch = currentProjectileSize / 2; } } public void ChargeBeam(Transform shootPoint) { if (currentProjectileEffect != null) return; this.shootPoint = shootPoint; charging = true; currentProjectileSize = 0; currentProjectileEffect = GameObject.Instantiate(Plugin.chargeEffect, shootPoint); currentProjectileAud = currentProjectileEffect.GetComponent<AudioSource>(); currentProjectileEffect.transform.localPosition = new Vector3(0, 0, 6); currentProjectileEffect.transform.localScale = Vector3.zero; beamRemaining = ConfigManager.leviathanChargeCount.value; beamChargeRate = 11.9f / ConfigManager.leviathanChargeDelay.value; Invoke("PrepareForFire", ConfigManager.leviathanChargeDelay.value / comp.lcon.eid.totalSpeedModifier); } private Grenade FindTargetGrenade() { List<Grenade> list = GrenadeList.Instance.grenadeList; Grenade targetGrenade = null; Vector3 playerPos = PlayerTracker.Instance.GetTarget().position; foreach (Grenade grn in list) { if (Vector3.Distance(grn.transform.position, playerPos) <= 10f) { targetGrenade = grn; break; } } return targetGrenade; } private Grenade targetGrenade = null; public void PrepareForFire() { charging = false; // OLD PREDICTION //targetShootPoint = NewMovement.Instance.playerCollider.bounds.center; //if (Physics.Raycast(NewMovement.Instance.transform.position, Vector3.down, out RaycastHit hit, float.MaxValue, envMask)) // targetShootPoint = hit.point; // Malicious face beam prediction GameObject player = MonoSingleton<PlayerTracker>.Instance.GetPlayer().gameObject; Vector3 a = new Vector3(MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().x, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().y / (float)(MonoSingleton<NewMovement>.Instance.ridingRocket ? 1 : 2), MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().z); targetShootPoint = (MonoSingleton<NewMovement>.Instance.ridingRocket ? MonoSingleton<NewMovement>.Instance.ridingRocket.transform.position : player.transform.position) + a / (1f / ConfigManager.leviathanChargeDelay.value) / comp.lcon.eid.totalSpeedModifier; RaycastHit raycastHit; // I guess this was in case player is approaching the malface, but it is very unlikely with leviathan /*if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude > 0f && col.Raycast(new Ray(player.transform.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity()), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.5f / comp.lcon.eid.totalSpeedModifier)) { targetShootPoint = player.transform.position; } else */if (Physics.Raycast(player.transform.position, targetShootPoint - player.transform.position, out raycastHit, Vector3.Distance(targetShootPoint, player.transform.position), LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { targetShootPoint = raycastHit.point; } Invoke("Shoot", ConfigManager.leviathanChargeDelay.value / comp.lcon.eid.totalSpeedModifier); } private Vector3 RandomVector(float min, float max) { return new Vector3(UnityEngine.Random.Range(min, max), UnityEngine.Random.Range(min, max), UnityEngine.Random.Range(min, max)); } public Vector3 targetShootPoint; private void Shoot() { Debug.Log("Attempting to shoot projectile for leviathan"); GameObject proj = GameObject.Instantiate(Plugin.maliciousFaceProjectile, shootPoint.transform.position, Quaternion.identity); if (targetGrenade == null) targetGrenade = FindTargetGrenade(); if (targetGrenade != null) { //NewMovement.Instance.playerCollider.bounds.center //proj.transform.rotation = Quaternion.LookRotation(targetGrenade.transform.position - shootPoint.transform.position); proj.transform.rotation = Quaternion.LookRotation(targetGrenade.transform.position - shootPoint.transform.position); } else { proj.transform.rotation = Quaternion.LookRotation(targetShootPoint - proj.transform.position); //proj.transform.rotation = Quaternion.LookRotation(NewMovement.Instance.playerCollider.bounds.center - proj.transform.position); //proj.transform.eulerAngles += RandomVector(-5f, 5f); } proj.transform.localScale = new Vector3(2f, 1f, 2f); if (proj.TryGetComponent(out RevolverBeam projComp)) { GameObject expClone = GameObject.Instantiate(projComp.hitParticle, new Vector3(1000000, 1000000, 1000000), Quaternion.identity); foreach (Explosion exp in expClone.GetComponentsInChildren<Explosion>()) { exp.maxSize *= ConfigManager.leviathanChargeSizeMulti.value; exp.speed *= ConfigManager.leviathanChargeSizeMulti.value; exp.damage = (int)(exp.damage * ConfigManager.leviathanChargeDamageMulti.value * comp.lcon.eid.totalDamageModifier); exp.toIgnore.Add(EnemyType.Leviathan); } projComp.damage *= 2 * comp.lcon.eid.totalDamageModifier; projComp.hitParticle = expClone; } beamRemaining -= 1; if (beamRemaining <= 0) { Destroy(currentProjectileEffect); currentProjectileSize = 0; beamAttack = false; if (projectilesRemaining <= 0) { comp.lookAtPlayer = false; anim.SetBool("ProjectileBurst", false); ___inAction.SetValue(comp, false); targetGrenade = null; } else { comp.lookAtPlayer = true; projectileAttack = true; } } else { targetShootPoint = NewMovement.Instance.playerCollider.bounds.center; if (Physics.Raycast(NewMovement.Instance.transform.position, Vector3.down, out RaycastHit hit, float.MaxValue, envMask)) targetShootPoint = hit.point; comp.lookAtPlayer = true; Invoke("PrepareForFire", ConfigManager.leviathanChargeDelay.value / comp.lcon.eid.totalSpeedModifier); } } private void SwitchToSecondPhase() { comp.lcon.phaseChangeHealth = comp.lcon.stat.health; } } class LeviathanTail_Flag : MonoBehaviour { public int swingCount = 0; private Animator ___anim; private void Awake() { ___anim = GetComponent<Animator>(); } public static float crossfadeDuration = 0.05f; private void SwingAgain() { ___anim.CrossFade("TailWhip", crossfadeDuration, 0, LeviathanTail_SwingEnd.targetStartNormalized); } } class Leviathan_Start { static void Postfix(LeviathanHead __instance) { Leviathan_Flag flag = __instance.gameObject.AddComponent<Leviathan_Flag>(); if(ConfigManager.leviathanSecondPhaseBegin.value) flag.Invoke("SwitchToSecondPhase", 2f / __instance.lcon.eid.totalSpeedModifier); } } class Leviathan_FixedUpdate { public static float projectileForward = 10f; static bool Roll(float chancePercent) { return UnityEngine.Random.Range(0, 99.9f) <= chancePercent; } static bool Prefix(LeviathanHead __instance, LeviathanController ___lcon, ref bool ___projectileBursting, float ___projectileBurstCooldown, Transform ___shootPoint, ref bool ___trackerIgnoreLimits, Animator ___anim, ref int ___previousAttack) { if (!__instance.active) { return false; } Leviathan_Flag flag = __instance.GetComponent<Leviathan_Flag>(); if (flag == null) return true; if (___projectileBursting && flag.projectileAttack) { if (flag.projectileDelayRemaining > 0f) { flag.projectileDelayRemaining = Mathf.MoveTowards(flag.projectileDelayRemaining, 0f, Time.deltaTime * __instance.lcon.eid.totalSpeedModifier); } else { flag.projectilesRemaining -= 1; flag.projectileDelayRemaining = (1f / ConfigManager.leviathanProjectileDensity.value) / __instance.lcon.eid.totalSpeedModifier; GameObject proj = null; Projectile comp = null; if (Roll(ConfigManager.leviathanProjectileYellowChance.value) && ConfigManager.leviathanProjectileMixToggle.value) { proj = GameObject.Instantiate(Plugin.hideousMassProjectile, ___shootPoint.position, ___shootPoint.rotation); comp = proj.GetComponent<Projectile>(); comp.target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); comp.safeEnemyType = EnemyType.Leviathan; // values from p2 flesh prison comp.turnSpeed *= 4f; comp.turningSpeedMultiplier *= 4f; comp.predictiveHomingMultiplier = 1.25f; } else if (Roll(ConfigManager.leviathanProjectileBlueChance.value) && ConfigManager.leviathanProjectileMixToggle.value) { proj = GameObject.Instantiate(Plugin.homingProjectile, ___shootPoint.position, ___shootPoint.rotation); comp = proj.GetComponent<Projectile>(); comp.target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); comp.safeEnemyType = EnemyType.Leviathan; // values from mindflayer comp.turningSpeedMultiplier = 0.5f; comp.speed = 20f; comp.speed *= ___lcon.eid.totalSpeedModifier; comp.damage *= ___lcon.eid.totalDamageModifier; } else { proj = GameObject.Instantiate<GameObject>(MonoSingleton<DefaultReferenceManager>.Instance.projectile, ___shootPoint.position, ___shootPoint.rotation); comp = proj.GetComponent<Projectile>(); comp.safeEnemyType = EnemyType.Leviathan; comp.speed *= 2f; comp.enemyDamageMultiplier = 0.5f; } comp.speed *= __instance.lcon.eid.totalSpeedModifier; comp.damage *= __instance.lcon.eid.totalDamageModifier; comp.safeEnemyType = EnemyType.Leviathan; comp.enemyDamageMultiplier = ConfigManager.leviathanProjectileFriendlyFireDamageMultiplier.normalizedValue; proj.transform.localScale *= 2f; proj.transform.position += proj.transform.forward * projectileForward; } } if (___projectileBursting) { if (flag.projectilesRemaining <= 0 || BlindEnemies.Blind) { flag.projectileAttack = false; if (!flag.beamAttack) { ___projectileBursting = false; ___trackerIgnoreLimits = false; ___anim.SetBool("ProjectileBurst", false); } } else { if (NewMovement.Instance.ridingRocket != null && ConfigManager.leviathanChargeAttack.value && ConfigManager.leviathanChargeHauntRocketRiding.value) { flag.playerRocketRideTracker += Time.deltaTime; if (flag.playerRocketRideTracker >= 1 && !flag.beamAttack) { flag.projectileAttack = false; flag.beamAttack = true; __instance.lookAtPlayer = true; flag.ChargeBeam(___shootPoint); flag.beamRemaining = 1; return false; } } else { flag.playerRocketRideTracker = 0; } } } return false; } } class Leviathan_ProjectileBurst { static bool Prefix(LeviathanHead __instance, Animator ___anim, ref int ___projectilesLeftInBurst, ref float ___projectileBurstCooldown, ref bool ___inAction) { if (!__instance.active) { return false; } Leviathan_Flag flag = __instance.GetComponent<Leviathan_Flag>(); if (flag == null) return true; if (flag.beamAttack || flag.projectileAttack) return false; flag.beamAttack = false; if (ConfigManager.leviathanChargeAttack.value) { if (NewMovement.Instance.ridingRocket != null && ConfigManager.leviathanChargeHauntRocketRiding.value) { flag.beamAttack = true; } else if (UnityEngine.Random.Range(0, 99.9f) <= ConfigManager.leviathanChargeChance.value && ConfigManager.leviathanChargeAttack.value) { flag.beamAttack = true; } } flag.projectileAttack = true; return true; /*if (!beamAttack) { flag.projectileAttack = true; return true; }*/ /*if(flag.beamAttack) { Debug.Log("Attempting to prepare beam for leviathan"); ___anim.SetBool("ProjectileBurst", true); //___projectilesLeftInBurst = 1; //___projectileBurstCooldown = 100f; ___inAction = true; return true; }*/ } } class Leviathan_ProjectileBurstStart { static bool Prefix(LeviathanHead __instance, Transform ___shootPoint) { Leviathan_Flag flag = __instance.GetComponent<Leviathan_Flag>(); if (flag == null) return true; if (flag.projectileAttack) { if(flag.projectilesRemaining <= 0) { flag.projectilesRemaining = ConfigManager.leviathanProjectileCount.value; flag.projectileDelayRemaining = 0; } } if (flag.beamAttack) { if (!flag.charging) { Debug.Log("Attempting to charge beam for leviathan"); __instance.lookAtPlayer = true; flag.ChargeBeam(___shootPoint); } } return true; } } class LeviathanTail_Start { static void Postfix(LeviathanTail __instance) { __instance.gameObject.AddComponent<LeviathanTail_Flag>(); } } // This is the tail attack animation begin // fires at n=3.138 // l=5.3333 // 0.336 // 0.88 class LeviathanTail_BigSplash { static bool Prefix(LeviathanTail __instance) { LeviathanTail_Flag flag = __instance.gameObject.GetComponent<LeviathanTail_Flag>(); if (flag == null) return true; flag.swingCount = ConfigManager.leviathanTailComboCount.value; return true; } } class LeviathanTail_SwingEnd { public static float targetEndNormalized = 0.7344f; public static float targetStartNormalized = 0.41f; static bool Prefix(LeviathanTail __instance, Animator ___anim) { LeviathanTail_Flag flag = __instance.gameObject.GetComponent<LeviathanTail_Flag>(); if (flag == null) return true; flag.swingCount -= 1; if (flag.swingCount == 0) return true; flag.Invoke("SwingAgain", Mathf.Max(0f, 5.3333f * (0.88f - targetEndNormalized) * (1f / ___anim.speed))); return false; } } }
Ultrapain/Patches/Leviathan.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/FleshPrison.cs", "retrieved_chunk": "using HarmonyLib;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing UnityEngine;\nusing UnityEngine.UI;\nnamespace Ultrapain.Patches\n{\n class FleshObamium_Start\n {\n static bool Prefix(FleshPrison __instance)", "score": 0.8993266820907593 }, { "filename": "Ultrapain/Patches/V2First.cs", "retrieved_chunk": "using HarmonyLib;\nusing System;\nusing System.Linq;\nusing System.Reflection;\nusing ULTRAKILL.Cheats;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class V2FirstFlag : MonoBehaviour\n {", "score": 0.8957884311676025 }, { "filename": "Ultrapain/Patches/SomethingWicked.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nnamespace Ultrapain.Patches\n{\n class SomethingWickedFlag : MonoBehaviour\n {\n public GameObject spear;", "score": 0.8917091488838196 }, { "filename": "Ultrapain/Patches/GlobalEnemyTweaks.cs", "retrieved_chunk": "using HarmonyLib;\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing UnityEngine;\nusing static Ultrapain.ConfigManager;\nnamespace Ultrapain.Patches\n{\n // EID\n class EnemyIdentifier_UpdateModifiers", "score": 0.8808000087738037 }, { "filename": "Ultrapain/Patches/Ferryman.cs", "retrieved_chunk": "using HarmonyLib;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing UnityEngine;\nusing UnityEngine.AI;\nnamespace Ultrapain.Patches\n{\n class FerrymanFlag : MonoBehaviour\n {", "score": 0.8763103485107422 } ]
csharp
LeviathanHead comp;
using HarmonyLib; using System.Security.Cryptography; using UnityEngine; namespace Ultrapain.Patches { class SwordsMachineFlag : MonoBehaviour { public SwordsMachine sm; public Animator anim; public EnemyIdentifier eid; public bool speedingUp = false; private void ResetAnimSpeed() { if(anim.GetCurrentAnimatorStateInfo(0).IsName("Knockdown")) { Invoke("ResetAnimSpeed", 0.01f); return; } Debug.Log("Resetting speed"); speedingUp = false; sm.SendMessage("SetSpeed"); } private void Awake() { anim = GetComponent<Animator>(); eid = GetComponent<EnemyIdentifier>(); } public float speed = 1f; private void Update() { if (speedingUp) { if (anim == null) { anim = sm.GetComponent<Animator>(); if (anim == null) { Destroy(this); return; } } anim.speed = speed; } } } class SwordsMachine_Start { static void Postfix(SwordsMachine __instance) { SwordsMachineFlag flag = __instance.gameObject.AddComponent<SwordsMachineFlag>(); flag.sm = __instance; } } class SwordsMachine_Knockdown_Patch { static bool Prefix(SwordsMachine __instance, bool __0) { __instance.Enrage(); if (!__0) __instance.SwordCatch(); return false; } } class SwordsMachine_Down_Patch { static bool Prefix(SwordsMachine __instance) { if (ConfigManager.swordsMachineSecondPhaseMode.value == ConfigManager.SwordsMachineSecondPhase.Skip && __instance.secondPhasePosTarget == null) return false; return true; } static void Postfix(SwordsMachine __instance, Animator ___anim, EnemyIdentifier ___eid) { if (ConfigManager.swordsMachineSecondPhaseMode.value != ConfigManager.SwordsMachineSecondPhase.SpeedUp || __instance.secondPhasePosTarget != null) return; SwordsMachineFlag flag = __instance.GetComponent<SwordsMachineFlag>(); if (flag == null) { flag = __instance.gameObject.AddComponent<SwordsMachineFlag>(); flag.sm = __instance; } flag.speedingUp = true; flag.speed = (1f * ___eid.totalSpeedModifier) * ConfigManager.swordsMachineSecondPhaseSpeed.value; ___anim.speed = flag.speed; AnimatorClipInfo clipInfo = ___anim.GetCurrentAnimatorClipInfo(0)[0]; flag.Invoke("ResetAnimSpeed", clipInfo.clip.length / flag.speed); } } class SwordsMachine_EndFirstPhase_Patch { static bool Prefix(SwordsMachine __instance) { if (ConfigManager.swordsMachineSecondPhaseMode.value == ConfigManager.SwordsMachineSecondPhase.Skip && __instance.secondPhasePosTarget == null) return false; return true; } static void Postfix(SwordsMachine __instance, Animator ___anim, EnemyIdentifier ___eid) { if (ConfigManager.swordsMachineSecondPhaseMode.value != ConfigManager.SwordsMachineSecondPhase.SpeedUp || __instance.secondPhasePosTarget != null) return; SwordsMachineFlag flag = __instance.GetComponent<SwordsMachineFlag>(); if (flag == null) { flag = __instance.gameObject.AddComponent<SwordsMachineFlag>(); flag.sm = __instance; } flag.speedingUp = true; flag.speed = (1f * ___eid.totalSpeedModifier) * ConfigManager.swordsMachineSecondPhaseSpeed.value; ___anim.speed = flag.speed; AnimatorClipInfo clipInfo = ___anim.GetCurrentAnimatorClipInfo(0)[0]; flag.Invoke("ResetAnimSpeed", clipInfo.clip.length / flag.speed); } } /*class SwordsMachine_SetSpeed_Patch { static bool Prefix(SwordsMachine __instance, ref Animator ___anim) { if (___anim == null) ___anim = __instance.GetComponent<Animator>(); SwordsMachineFlag flag = __instance.GetComponent<SwordsMachineFlag>(); if (flag == null || !flag.speedingUp) return true; return false; } }*/ /*[HarmonyPatch(typeof(SwordsMachine))] [HarmonyPatch("Down")] class SwordsMachine_Down_Patch { static void Postfix(SwordsMachine __instance, ref Animator ___anim, ref Machine ___mach) { ___anim.Play("Knockdown", 0, Plugin.SwordsMachineKnockdownTimeNormalized); __instance.CancelInvoke("CheckLoop"); ___mach.health = ___mach.symbiote.health; __instance.downed = false; } } [HarmonyPatch(typeof(SwordsMachine))] [HarmonyPatch("CheckLoop")] class SwordsMachine_CheckLoop_Patch { static bool Prefix(SwordsMachine __instance) { return false; } }*/ /*[HarmonyPatch(typeof(SwordsMachine))] [HarmonyPatch("ShootGun")] class SwordsMachine_ShootGun_Patch { static bool Prefix(SwordsMachine __instance) { if(UnityEngine.Random.RandomRangeInt(0, 2) == 1) { GameObject grn = GameObject.Instantiate(Plugin.shotgunGrenade.gameObject, __instance.transform.position, __instance.transform.rotation); grn.transform.position += grn.transform.forward * 0.5f + grn.transform.up * 0.5f; Grenade grnComp = grn.GetComponent<Grenade>(); grnComp.enemy = true; grnComp.CanCollideWithPlayer(true); Vector3 playerPosition = MonoSingleton<PlayerTracker>.Instance.gameObject.transform.position; float distanceFromPlayer = Vector3.Distance(playerPosition, grn.transform.position); Vector3 predictedPosition = MonoSingleton<PlayerTracker>.Instance.PredictPlayerPosition(distanceFromPlayer / 40); grn.transform.LookAt(predictedPosition); grn.GetComponent<Rigidbody>().maxAngularVelocity = 40; grn.GetComponent<Rigidbody>().velocity = grn.transform.forward * 40; return false; } return true; } }*/ class ThrownSword_Start_Patch { static void Postfix(ThrownSword __instance) { __instance.gameObject.AddComponent<ThrownSwordCollisionDetector>(); } } class ThrownSword_OnTriggerEnter_Patch { static void Postfix(ThrownSword __instance, Collider __0) { if (__0.gameObject.tag == "Player") { GameObject explosionObj = GameObject.Instantiate(Plugin.shotgunGrenade.gameObject.GetComponent<Grenade>().explosion, __0.gameObject.transform.position, __0.gameObject.transform.rotation); foreach (Explosion explosion in explosionObj.GetComponentsInChildren<Explosion>()) { explosion.enemy = true; } } } } class ThrownSwordCollisionDetector : MonoBehaviour { public bool exploded = false; public void OnCollisionEnter(
Collision other) {
if (exploded) return; if (other.gameObject.layer != 24) { Debug.Log($"Hit layer {other.gameObject.layer}"); return; } exploded = true; GameObject explosionObj = GameObject.Instantiate(Plugin.shotgunGrenade.gameObject.GetComponent<Grenade>().explosion, transform.position, transform.rotation); foreach (Explosion explosion in explosionObj.GetComponentsInChildren<Explosion>()) { explosion.enemy = true; explosion.damage = ConfigManager.swordsMachineExplosiveSwordDamage.value; explosion.maxSize *= ConfigManager.swordsMachineExplosiveSwordSize.value; explosion.speed *= ConfigManager.swordsMachineExplosiveSwordSize.value; } gameObject.GetComponent<ThrownSword>().Invoke("Return", 0.1f); } } }
Ultrapain/Patches/SwordsMachine.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/OrbitalStrike.cs", "retrieved_chunk": " }\n class OrbitalExplosionInfo : MonoBehaviour\n {\n public bool active = true;\n public string id;\n public int points;\n }\n class Grenade_Explode\n {\n class StateInfo", "score": 0.8823793530464172 }, { "filename": "Ultrapain/Patches/V2Common.cs", "retrieved_chunk": " return true;\n }\n }\n class V2CommonRevolverBulletSharp : MonoBehaviour\n {\n public int reflectionCount = 2;\n public float autoAimAngle = 30f;\n public Projectile proj;\n public float speed = 350f;\n public bool hasTargetPoint = false;", "score": 0.8819856643676758 }, { "filename": "Ultrapain/Patches/CommonComponents.cs", "retrieved_chunk": " public Quaternion targetRotation;\n private void Awake()\n {\n transform.rotation = targetRotation;\n }\n }\n public class CommonActivator : MonoBehaviour\n {\n public int originalId;\n public Renderer rend;", "score": 0.863060474395752 }, { "filename": "Ultrapain/Patches/OrbitalStrike.cs", "retrieved_chunk": " {\n public CoinChainList chainList;\n public bool isOrbitalRay = false;\n public bool exploded = false;\n public float activasionDistance;\n }\n public class Coin_Start\n {\n static void Postfix(Coin __instance)\n {", "score": 0.8627991080284119 }, { "filename": "Ultrapain/Patches/Drone.cs", "retrieved_chunk": " }\n }\n class DroneFlag : MonoBehaviour\n {\n public enum Firemode : int\n {\n Projectile = 0,\n Explosive,\n TurretBeam\n }", "score": 0.8532902002334595 } ]
csharp
Collision other) {
using Tokenizer; namespace Parser.SymbolTableUtil { /// <summary> /// Represents type of an <see cref="ISymbol"/>. /// </summary> public class SymbolType { /// <summary> /// Gets name of the type. /// </summary> public string Name { get; } /// <summary> /// Gets keyword associated with this type. /// </summary> public
TokenType TokenType {
get; } /// <summary> /// Initializes new instance of the <see cref="SymbolType"/> class. /// </summary> /// <param name="name">Name of the type.</param> /// <param name="type">A <see cref="Tokenizer.TokenType"/> representing keyword associated with this type.</param> public SymbolType(string name, TokenType type) { Name = name; TokenType = type; } public override string ToString() { return Name; } } }
Parser/SymbolTableUtil/SymbolType.cs
amirsina-mashayekh-TSLang-Compiler-3a68caf
[ { "filename": "Parser/SymbolTableUtil/Function.cs", "retrieved_chunk": " /// </summary>\n public string Identifier { get; }\n /// <summary>\n /// Gets return type of the function.\n /// </summary>\n public SymbolType Type { get; }\n /// <summary>\n /// Gets list of the function parameters.\n /// </summary>\n public ReadOnlyCollection<Variable> Parameters { get; }", "score": 0.9447404146194458 }, { "filename": "Parser/SymbolTableUtil/ISymbol.cs", "retrieved_chunk": "namespace Parser.SymbolTableUtil\n{\n /// <summary>\n /// Represents a symbol which has a name and type.\n /// </summary>\n internal interface ISymbol\n {\n /// <summary>\n /// Gets name of the symbol.\n /// </summary>", "score": 0.9314488768577576 }, { "filename": "Parser/SymbolTableUtil/ISymbol.cs", "retrieved_chunk": " public string Identifier { get; }\n /// <summary>\n /// Gets type of the symbol.\n /// </summary>\n public SymbolType Type { get; }\n }\n}", "score": 0.9235770106315613 }, { "filename": "Tokenizer/TokenType.cs", "retrieved_chunk": " /// Gets the name of the current <see cref=\"TokenType\"/>.\n /// </summary>\n public string Name { get; }\n /// <summary>\n /// Gets the regex object to match tokens with the current <see cref=\"TokenType\"/>.\n /// </summary>\n public Regex Pattern { get; }\n /// <summary>\n /// Saves hash code of the current <see cref=\"TokenType\"/>. \n /// </summary>", "score": 0.9234719276428223 }, { "filename": "Parser/TSLangParser.cs", "retrieved_chunk": " /// Symbol table for current scope.\n /// </summary>\n private SymbolTable currentSymTab;\n /// <summary>\n /// Gets whether an error occured while parsing the code.\n /// </summary>\n public bool HasError { get; private set; }\n /// <summary>\n /// Last token which caused syntax error.\n /// </summary>", "score": 0.9214137196540833 } ]
csharp
TokenType TokenType {
using HarmonyLib; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.ConstrainedExecution; using UnityEngine; namespace Ultrapain.Patches { class Drone_Start_Patch { static void Postfix(Drone __instance, ref EnemyIdentifier ___eid) { if (___eid.enemyType != EnemyType.Drone) return; __instance.gameObject.AddComponent<DroneFlag>(); } } class Drone_PlaySound_Patch { static FieldInfo antennaFlashField = typeof(Turret).GetField("antennaFlash", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); static ParticleSystem antennaFlash; public static Color defaultLineColor = new Color(1f, 0.44f, 0.74f); static bool Prefix(Drone __instance, EnemyIdentifier ___eid, AudioClip __0) { if (___eid.enemyType != EnemyType.Drone) return true; if(__0 == __instance.windUpSound) { DroneFlag flag = __instance.GetComponent<DroneFlag>(); if (flag == null) return true; List<Tuple<DroneFlag.Firemode, float>> chances = new List<Tuple<DroneFlag.Firemode, float>>(); if (ConfigManager.droneProjectileToggle.value) chances.Add(new Tuple<DroneFlag.Firemode, float>(DroneFlag.Firemode.Projectile, ConfigManager.droneProjectileChance.value)); if (ConfigManager.droneExplosionBeamToggle.value) chances.Add(new Tuple<DroneFlag.Firemode, float>(DroneFlag.Firemode.Explosive, ConfigManager.droneExplosionBeamChance.value)); if (ConfigManager.droneSentryBeamToggle.value) chances.Add(new Tuple<DroneFlag.Firemode, float>(DroneFlag.Firemode.TurretBeam, ConfigManager.droneSentryBeamChance.value)); if (chances.Count == 0 || chances.Sum(item => item.Item2) <= 0) flag.currentMode = DroneFlag.Firemode.Projectile; else flag.currentMode = UnityUtils.GetRandomFloatWeightedItem(chances, item => item.Item2).Item1; if (flag.currentMode == DroneFlag.Firemode.Projectile) { flag.attackDelay = ConfigManager.droneProjectileDelay.value; return true; } else if (flag.currentMode == DroneFlag.Firemode.Explosive) { flag.attackDelay = ConfigManager.droneExplosionBeamDelay.value; GameObject chargeEffect = GameObject.Instantiate(Plugin.chargeEffect, __instance.transform); chargeEffect.transform.localPosition = new Vector3(0, 0, 0.8f); chargeEffect.transform.localScale = Vector3.zero; float duration = ConfigManager.droneExplosionBeamDelay.value / ___eid.totalSpeedModifier; RemoveOnTime remover = chargeEffect.AddComponent<RemoveOnTime>(); remover.time = duration; CommonLinearScaler scaler = chargeEffect.AddComponent<CommonLinearScaler>(); scaler.targetTransform = scaler.transform; scaler.scaleSpeed = 1f / duration; CommonAudioPitchScaler pitchScaler = chargeEffect.AddComponent<CommonAudioPitchScaler>(); pitchScaler.targetAud = chargeEffect.GetComponent<AudioSource>(); pitchScaler.scaleSpeed = 1f / duration; return false; } else if (flag.currentMode == DroneFlag.Firemode.TurretBeam) { flag.attackDelay = ConfigManager.droneSentryBeamDelay.value; if(ConfigManager.droneDrawSentryBeamLine.value) { flag.lr.enabled = true; flag.SetLineColor(ConfigManager.droneSentryBeamLineNormalColor.value); flag.Invoke("LineRendererColorToWarning", Mathf.Max(0.01f, (flag.attackDelay / ___eid.totalSpeedModifier) - ConfigManager.droneSentryBeamLineIndicatorDelay.value)); } if (flag.particleSystem == null) { if (antennaFlash == null) antennaFlash = (ParticleSystem)antennaFlashField.GetValue(Plugin.turret); flag.particleSystem = GameObject.Instantiate(antennaFlash, __instance.transform); flag.particleSystem.transform.localPosition = new Vector3(0, 0, 2); } flag.particleSystem.Play(); GameObject flash = GameObject.Instantiate(Plugin.turretFinalFlash, __instance.transform); GameObject.Destroy(flash.transform.Find("MuzzleFlash/muzzleflash").gameObject); return false; } } return true; } } class Drone_Shoot_Patch { static bool Prefix(Drone __instance, ref EnemyIdentifier ___eid) { DroneFlag flag = __instance.GetComponent<DroneFlag>(); if(flag == null || __instance.crashing) return true; DroneFlag.Firemode mode = flag.currentMode; if (mode == DroneFlag.Firemode.Projectile) return true; if (mode == DroneFlag.Firemode.Explosive) { GameObject beam = GameObject.Instantiate(Plugin.beam.gameObject, __instance.transform.position + __instance.transform.forward, __instance.transform.rotation); RevolverBeam revBeam = beam.GetComponent<RevolverBeam>(); revBeam.hitParticle = Plugin.shotgunGrenade.gameObject.GetComponent<Grenade>().explosion; revBeam.damage /= 2; revBeam.damage *= ___eid.totalDamageModifier; return false; } if(mode == DroneFlag.Firemode.TurretBeam) { GameObject turretBeam = GameObject.Instantiate(Plugin.turretBeam.gameObject, __instance.transform.position + __instance.transform.forward * 2f, __instance.transform.rotation); if (turretBeam.TryGetComponent<RevolverBeam>(out RevolverBeam revBeam)) { revBeam.damage = ConfigManager.droneSentryBeamDamage.value; revBeam.damage *= ___eid.totalDamageModifier; revBeam.alternateStartPoint = __instance.transform.position + __instance.transform.forward; revBeam.ignoreEnemyType = EnemyType.Drone; } flag.lr.enabled = false; return false; } Debug.LogError($"Drone fire mode in impossible state. Current value: {mode} : {(int)mode}"); return true; } } class Drone_Update { static void Postfix(Drone __instance, EnemyIdentifier ___eid, ref float ___attackCooldown, int ___difficulty) { if (___eid.enemyType != EnemyType.Drone) return; DroneFlag flag = __instance.GetComponent<DroneFlag>(); if (flag == null || flag.attackDelay < 0) return; float attackSpeedDecay = (float)(___difficulty / 2); if (___difficulty == 1) { attackSpeedDecay = 0.75f; } else if (___difficulty == 0) { attackSpeedDecay = 0.5f; } attackSpeedDecay *= ___eid.totalSpeedModifier; float delay = flag.attackDelay / ___eid.totalSpeedModifier; __instance.CancelInvoke("Shoot"); __instance.Invoke("Shoot", delay); ___attackCooldown = UnityEngine.Random.Range(2f, 4f) + (flag.attackDelay - 0.75f) * attackSpeedDecay; flag.attackDelay = -1; } } class DroneFlag : MonoBehaviour { public enum Firemode : int { Projectile = 0, Explosive, TurretBeam } public ParticleSystem particleSystem; public LineRenderer lr; public Firemode currentMode = Firemode.Projectile; private static Firemode[] allModes = Enum.GetValues(typeof(Firemode)) as Firemode[]; static FieldInfo turretAimLine = typeof(Turret).GetField("aimLine", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); static Material whiteMat; public void Awake() { lr = gameObject.AddComponent<LineRenderer>(); lr.enabled = false; lr.receiveShadows = false; lr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; lr.startWidth = lr.endWidth = lr.widthMultiplier = 0.025f; if (whiteMat == null) whiteMat = ((LineRenderer)turretAimLine.GetValue(Plugin.turret)).material; lr.material = whiteMat; } public void SetLineColor(Color c) { Gradient gradient = new Gradient(); GradientColorKey[] array = new GradientColorKey[1]; array[0].color = c; GradientAlphaKey[] array2 = new GradientAlphaKey[1]; array2[0].alpha = 1f; gradient.SetKeys(array, array2); lr.colorGradient = gradient; } public void LineRendererColorToWarning() { SetLineColor(ConfigManager.droneSentryBeamLineWarningColor.value); } public float attackDelay = -1; public bool homingTowardsPlayer = false; Transform target; Rigidbody rb; private void Update() { if(homingTowardsPlayer) { if(target == null) target = PlayerTracker.Instance.GetTarget(); if (rb == null) rb = GetComponent<Rigidbody>(); Quaternion to = Quaternion.LookRotation(target.position/* + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity()*/ - transform.position); transform.rotation = Quaternion.RotateTowards(transform.rotation, to, Time.deltaTime * ConfigManager.droneHomeTurnSpeed.value); rb.velocity = transform.forward * rb.velocity.magnitude; } if(lr.enabled) { lr.SetPosition(0, transform.position); lr.SetPosition(1, transform.position + transform.forward * 1000); } } } class Drone_Death_Patch { static bool Prefix(Drone __instance, EnemyIdentifier ___eid) { if (___eid.enemyType != EnemyType.Drone || __instance.crashing) return true; DroneFlag flag = __instance.GetComponent<DroneFlag>(); if (flag == null) return true; if (___eid.hitter == "heavypunch" || ___eid.hitter == "punch") return true; flag.homingTowardsPlayer = true; return true; } } class Drone_GetHurt_Patch { static bool Prefix(Drone __instance,
EnemyIdentifier ___eid, bool ___parried) {
if((___eid.hitter == "shotgunzone" || ___eid.hitter == "punch") && !___parried) { DroneFlag flag = __instance.GetComponent<DroneFlag>(); if (flag == null) return true; flag.homingTowardsPlayer = false; } return true; } } }
Ultrapain/Patches/Drone.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/MaliciousFace.cs", "retrieved_chunk": " flag.charging = false;\n }\n return true;\n }\n }\n class MaliciousFace_ShootProj_Patch\n {\n /*static bool Prefix(SpiderBody __instance, ref GameObject ___proj, out bool __state)\n {\n __state = false;", "score": 0.8889244198799133 }, { "filename": "Ultrapain/Patches/Cerberus.cs", "retrieved_chunk": " {\n CerberusFlag flag = __instance.GetComponent<CerberusFlag>();\n if (flag == null)\n return;\n flag.MakeParryable();\n }\n }\n class Statue_GetHurt_Patch\n {\n static bool Prefix(Statue __instance, EnemyIdentifier ___eid)", "score": 0.8707969784736633 }, { "filename": "Ultrapain/Patches/Screwdriver.cs", "retrieved_chunk": " if (!__instance.drill)\n return;\n DrillFlag flag = __instance.gameObject.AddComponent<DrillFlag>();\n flag.drill = __instance;\n }\n }\n class Harpoon_Punched\n {\n static void Postfix(Harpoon __instance, EnemyIdentifierIdentifier ___target)\n {", "score": 0.8696409463882446 }, { "filename": "Ultrapain/Patches/DruidKnight.cs", "retrieved_chunk": " aud.time = offset;\n aud.Play();\n return true;\n }\n }\n class Drone_Explode\n {\n static bool Prefix(bool ___exploded, out bool __state)\n {\n __state = ___exploded;", "score": 0.8660922646522522 }, { "filename": "Ultrapain/Patches/PlayerStatTweaks.cs", "retrieved_chunk": " }\n }\n return code.AsEnumerable();\n }\n }\n class NewMovement_GetHealth\n {\n static bool Prefix(NewMovement __instance, int __0, bool __1, ref AudioSource ___greenHpAud, Canvas ___fullHud)\n {\n if (__instance.dead || __instance.exploded)", "score": 0.8648124933242798 } ]
csharp
EnemyIdentifier ___eid, bool ___parried) {
#nullable enable using System.Collections.Generic; using Mochineko.Relent.Result; namespace Mochineko.RelentStateMachine { internal sealed class TransitionMap<TEvent, TContext> : ITransitionMap<TEvent, TContext> { private readonly IState<TEvent, TContext> initialState; private readonly IReadOnlyList<IState<TEvent, TContext>> states; private readonly IReadOnlyDictionary< IState<TEvent, TContext>, IReadOnlyDictionary<TEvent, IState<TEvent, TContext>>> transitionMap; private readonly IReadOnlyDictionary<TEvent, IState<TEvent, TContext>> anyTransitionMap; public TransitionMap( IState<TEvent, TContext> initialState, IReadOnlyList<IState<TEvent, TContext>> states, IReadOnlyDictionary< IState<TEvent, TContext>, IReadOnlyDictionary<TEvent, IState<TEvent, TContext>>> transitionMap, IReadOnlyDictionary<TEvent, IState<TEvent, TContext>> anyTransitionMap) { this.initialState = initialState; this.states = states; this.transitionMap = transitionMap; this.anyTransitionMap = anyTransitionMap; }
IState<TEvent, TContext> ITransitionMap<TEvent, TContext>.InitialState => initialState;
IResult<IState<TEvent, TContext>> ITransitionMap<TEvent, TContext>.AllowedToTransit( IState<TEvent, TContext> currentState, TEvent @event) { if (transitionMap.TryGetValue(currentState, out var candidates)) { if (candidates.TryGetValue(@event, out var nextState)) { return Results.Succeed(nextState); } } if (anyTransitionMap.TryGetValue(@event, out var nextStateFromAny)) { return Results.Succeed(nextStateFromAny); } return Results.Fail<IState<TEvent, TContext>>( $"Not found transition from {currentState.GetType()} with event {@event}."); } public void Dispose() { foreach (var state in states) { state.Dispose(); } } } }
Assets/Mochineko/RelentStateMachine/TransitionMap.cs
mochi-neko-RelentStateMachine-64762eb
[ { "filename": "Assets/Mochineko/RelentStateMachine/TransitionMapBuilder.cs", "retrieved_chunk": " private readonly Dictionary<IState<TEvent, TContext>, Dictionary<TEvent, IState<TEvent, TContext>>>\n transitionMap = new();\n private readonly Dictionary<TEvent, IState<TEvent, TContext>>\n anyTransitionMap = new();\n private bool disposed = false;\n public static TransitionMapBuilder<TEvent, TContext> Create<TInitialState>()\n where TInitialState : IState<TEvent, TContext>, new()\n {\n var initialState = new TInitialState();\n return new TransitionMapBuilder<TEvent, TContext>(initialState);", "score": 0.9085675477981567 }, { "filename": "Assets/Mochineko/RelentStateMachine/TransitionMapBuilder.cs", "retrieved_chunk": " BuildReadonlyTransitionMap(),\n anyTransitionMap);\n // Cannot reuse builder after build.\n this.Dispose();\n return result;\n }\n private IReadOnlyDictionary<\n IState<TEvent, TContext>,\n IReadOnlyDictionary<TEvent, IState<TEvent, TContext>>>\n BuildReadonlyTransitionMap()", "score": 0.8895466327667236 }, { "filename": "Assets/Mochineko/RelentStateMachine/TransitionMapBuilder.cs", "retrieved_chunk": "#nullable enable\nusing System;\nusing System.Collections.Generic;\nnamespace Mochineko.RelentStateMachine\n{\n public sealed class TransitionMapBuilder<TEvent, TContext>\n : ITransitionMapBuilder<TEvent, TContext>\n {\n private readonly IState<TEvent, TContext> initialState;\n private readonly List<IState<TEvent, TContext>> states = new();", "score": 0.8669813275337219 }, { "filename": "Assets/Mochineko/RelentStateMachine/TransitionMapBuilder.cs", "retrieved_chunk": " {\n var result = new Dictionary<\n IState<TEvent, TContext>,\n IReadOnlyDictionary<TEvent, IState<TEvent, TContext>>>();\n foreach (var (key, value) in transitionMap)\n {\n result.Add(key, value);\n }\n return result;\n }", "score": 0.8605518341064453 }, { "filename": "Assets/Mochineko/RelentStateMachine/TransitionMapBuilder.cs", "retrieved_chunk": " }\n else\n {\n transitions.Add(@event, toState);\n }\n }\n else\n {\n var newTransitions = new Dictionary<TEvent, IState<TEvent, TContext>>();\n newTransitions.Add(@event, toState);", "score": 0.8594169020652771 } ]
csharp
IState<TEvent, TContext> ITransitionMap<TEvent, TContext>.InitialState => initialState;
using Microsoft.Extensions.Logging; using Microsoft.SemanticKernel; using SKernel.Factory.Config; using System.Collections.Generic; namespace SKernel.Factory { public class SemanticSkillsImporter : ISkillsImporter { private readonly string[] _folders; private readonly ILogger<SemanticSkillsImporter> _logger; public SemanticSkillsImporter(
SkillOptions skillOptions, ILoggerFactory logger) {
_folders = skillOptions.SemanticSkillsFolders; _logger = logger.CreateLogger<SemanticSkillsImporter>(); } public void ImportSkills(IKernel kernel, IList<string> skills) { foreach (var folder in _folders) kernel.RegisterSemanticSkills(folder, skills, _logger); } } }
src/SKernel/Factory/SemanticSkillsImporter.cs
geffzhang-ai-search-aspnet-qdrant-chatgpt-378d2be
[ { "filename": "src/SKernel/Factory/NativeSkillsImporter.cs", "retrieved_chunk": "using Microsoft.SemanticKernel;\nusing SKernel.Factory.Config;\nusing System;\nusing System.Collections.Generic;\nnamespace SKernel.Factory\n{\n public class NativeSkillsImporter : ISkillsImporter\n {\n private readonly IList<Type> _skills;\n private readonly IServiceProvider _provider;", "score": 0.8913152813911438 }, { "filename": "src/SKernel/Factory/ISkillsImporter.cs", "retrieved_chunk": "using Microsoft.SemanticKernel;\nusing System.Collections.Generic;\nnamespace SKernel.Factory\n{\n public interface ISkillsImporter\n {\n void ImportSkills(IKernel kernel, IList<string> skills);\n }\n}", "score": 0.8686093091964722 }, { "filename": "src/SKernel/Factory/Config/SkillOptions.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nnamespace SKernel.Factory.Config\n{\n public class SkillOptions\n {\n public string[] SemanticSkillsFolders { get; init; } = { \"./skills\" };\n public IList<Type> NativeSkillTypes { get; init; } = new List<Type>();\n }\n}", "score": 0.8664041757583618 }, { "filename": "src/SKernel/Factory/SemanticKernelFactory.cs", "retrieved_chunk": " private readonly NativeSkillsImporter _native;\n private readonly SemanticSkillsImporter _semantic;\n private readonly SKConfig _config;\n private readonly IMemoryStore _memoryStore;\n private readonly ILogger _logger;\n public SemanticKernelFactory(NativeSkillsImporter native, SemanticSkillsImporter semantic, SKConfig config,\n IMemoryStore memoryStore, ILoggerFactory logger)\n {\n _native = native;\n _semantic = semantic;", "score": 0.8370230793952942 }, { "filename": "src/SKernel.Contracts/Services/ISkillsService.cs", "retrieved_chunk": "namespace SKernel.Contract.Services\n{\n public interface ISkillsService\n {\n Task<IResult> GetSkillsAsync();\n Task<IResult> GetSkillFunctionAsync(string skill, string function);\n }\n}", "score": 0.8314321637153625 } ]
csharp
SkillOptions skillOptions, ILoggerFactory logger) {
using GraphNotifications.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Graph; namespace GraphNotifications.Services { public class GraphNotificationService : IGraphNotificationService { private readonly ILogger _logger; private readonly string _notificationUrl; private readonly IGraphClientService _graphClientService; private readonly ICertificateService _certificateService; public GraphNotificationService(IGraphClientService graphClientService,
ICertificateService certificateService, IOptions<AppSettings> settings, ILogger<GraphNotificationService> logger) {
_graphClientService = graphClientService; _certificateService = certificateService ?? throw new ArgumentException(nameof(certificateService)); _logger = logger; _notificationUrl = settings.Value.NotificationUrl ?? throw new ArgumentException(nameof(settings.Value.NotificationUrl)); } public async Task<Subscription> AddSubscriptionAsync(string userAccessToken, SubscriptionDefinition subscriptionDefinition) { // Create the subscription request var subscription = new Subscription { ChangeType = string.Join(',', subscriptionDefinition.ChangeTypes), //"created", NotificationUrl = _notificationUrl, Resource = subscriptionDefinition.Resource, // "me/mailfolders/inbox/messages", ClientState = Guid.NewGuid().ToString(), IncludeResourceData = subscriptionDefinition.ResourceData, ExpirationDateTime = subscriptionDefinition.ExpirationTime }; if (subscriptionDefinition.ResourceData) { // Get the encryption certificate (public key) var encryptionCertificate = await _certificateService.GetEncryptionCertificate(); subscription.EncryptionCertificateId = encryptionCertificate.Subject; // To get resource data, we must provide a public key that // Microsoft Graph will use to encrypt their key // See https://docs.microsoft.com/graph/webhooks-with-resource-data#creating-a-subscription subscription.AddPublicEncryptionCertificate(encryptionCertificate); } _logger.LogInformation("Getting GraphService with accesstoken for Graph onbehalf of user"); var graphUserClient = _graphClientService.GetUserGraphClient(userAccessToken); _logger.LogInformation("Create graph subscription"); return await graphUserClient.Subscriptions.Request().AddAsync(subscription); } public async Task<Subscription> RenewSubscriptionAsync(string userAccessToken, string subscriptionId, DateTimeOffset expirationTime) { var subscription = new Subscription { ExpirationDateTime = expirationTime }; _logger.LogInformation("Getting GraphService with accesstoken for Graph onbehalf of user"); var graphUserClient = _graphClientService.GetUserGraphClient(userAccessToken); _logger.LogInformation($"Renew graph subscription: {subscriptionId}"); return await graphUserClient.Subscriptions[subscriptionId].Request().UpdateAsync(subscription); } public async Task<Subscription> GetSubscriptionAsync(string userAccessToken, string subscriptionId) { _logger.LogInformation("Getting GraphService with accesstoken for Graph onbehalf of user"); var graphUserClient = _graphClientService.GetUserGraphClient(userAccessToken); _logger.LogInformation($"Get graph subscription: {subscriptionId}"); return await graphUserClient.Subscriptions[subscriptionId].Request().GetAsync(); } } }
Services/GraphNotificationService.cs
microsoft-GraphNotificationBroker-b1564aa
[ { "filename": "Services/GraphClientService.cs", "retrieved_chunk": " {\n private readonly AppSettings _settings;\n private readonly ILogger _logger;\n public GraphClientService(IOptions<AppSettings> options, ILogger<GraphClientService> logger)\n {\n _settings = options.Value;\n _logger = logger;\n }\n public GraphServiceClient GetUserGraphClient(string userAssertion)\n {", "score": 0.9063469171524048 }, { "filename": "Functions/GraphNotificationsHub.cs", "retrieved_chunk": " private readonly ICertificateService _certificateService;\n private readonly ICacheService _cacheService;\n private readonly ILogger _logger;\n private readonly AppSettings _settings;\n private const string MicrosoftGraphChangeTrackingSpId = \"0bf30f3b-4a52-48df-9a82-234910c4a086\";\n public GraphNotificationsHub(\n ITokenValidationService tokenValidationService,\n IGraphNotificationService graphNotificationService,\n ICacheService cacheService,\n ICertificateService certificateService,", "score": 0.869377851486206 }, { "filename": "Services/CacheService.cs", "retrieved_chunk": " /// <summary>\n /// Implements connection to Redis\n /// </summary> \n public class CacheService : ICacheService\n {\n private readonly ILogger<CacheService> _logger;\n private readonly IRedisFactory _redisFactory;\n private static readonly Encoding encoding = Encoding.UTF8;\n public CacheService(IRedisFactory redisFactory, ILogger<CacheService> logger)\n {", "score": 0.8553327322006226 }, { "filename": "Services/CertificateService.cs", "retrieved_chunk": "namespace GraphNotifications.Services\n{\n /// <summary>\n /// Implements methods to retrieve certificates from Azure Key Vault\n /// </summary>\n public class CertificateService : ICertificateService\n {\n private readonly AppSettings _settings;\n private readonly ILogger _logger;\n private readonly Uri _keyVaultUrl;", "score": 0.8477409482002258 }, { "filename": "Functions/GraphNotificationsHub.cs", "retrieved_chunk": " ILogger<GraphNotificationsHub> logger,\n IOptions<AppSettings> options)\n {\n _tokenValidationService = tokenValidationService;\n _graphNotificationService = graphNotificationService;\n _certificateService = certificateService ?? throw new ArgumentException(nameof(certificateService));\n _cacheService = cacheService ?? throw new ArgumentException(nameof(cacheService));\n _logger = logger;\n _settings = options.Value;\n }", "score": 0.8334029912948608 } ]
csharp
ICertificateService certificateService, IOptions<AppSettings> settings, ILogger<GraphNotificationService> logger) {
namespace CloudDistributedLock { public interface ICloudDistributedLockProvider { Task<CloudDistributedLock> TryAquireLockAsync(string name); Task<
CloudDistributedLock> AcquireLockAsync(string name, TimeSpan? timeout = default);
} public class CloudDistributedLockProvider : ICloudDistributedLockProvider { private readonly CloudDistributedLockProviderOptions options; private readonly CosmosLockClient cosmosLockClient; public CloudDistributedLockProvider(CloudDistributedLockProviderOptions options) { this.options = options; this.cosmosLockClient = new CosmosLockClient(options); } public async Task<CloudDistributedLock> AcquireLockAsync(string name, TimeSpan? timeout = null) { using var cancellationTokenSource = timeout.HasValue ? new CancellationTokenSource(timeout.Value) : new CancellationTokenSource(); return await ContinuallyTryAquireLockAsync(name, cancellationTokenSource.Token); } public async Task<CloudDistributedLock> TryAquireLockAsync(string name) { var item = await cosmosLockClient.TryAquireLockAsync(name); if (item != null) { return CloudDistributedLock.CreateAcquiredLock(cosmosLockClient, item); } else { return CloudDistributedLock.CreateUnacquiredLock(); } } private async Task<CloudDistributedLock> ContinuallyTryAquireLockAsync(string name, CancellationToken cancellationToken) { CloudDistributedLock? @lock; do { @lock = await TryAquireLockAsync(name); if ([email protected] && !cancellationToken.IsCancellationRequested) { await Task.Delay(options.RetryInterval); } } while ([email protected] && !cancellationToken.IsCancellationRequested); return @lock; } } }
CloudDistributedLock/CloudDistributedLockProvider.cs
briandunnington-CloudDistributedLock-04f72e6
[ { "filename": "ExampleApp/Functions.cs", "retrieved_chunk": " private readonly ICloudDistributedLockProviderFactory lockProviderFactory;\n public Functions(ICloudDistributedLockProviderFactory lockProviderFactory)\n {\n this.lockProviderFactory = lockProviderFactory;\n }\n [Function(\"TryLock\")]\n public async Task<HttpResponseData> TryLock([HttpTrigger(AuthorizationLevel.Anonymous, \"get\")] HttpRequestData req)\n {\n var response = req.CreateResponse();\n var lockProvider = lockProviderFactory.GetLockProvider();", "score": 0.8726595044136047 }, { "filename": "CloudDistributedLock/CloudDistributedLockProviderFactory.cs", "retrieved_chunk": "using Microsoft.Extensions.Options;\nusing System.Collections.Concurrent;\nnamespace CloudDistributedLock\n{\n public interface ICloudDistributedLockProviderFactory\n {\n ICloudDistributedLockProvider GetLockProvider();\n ICloudDistributedLockProvider GetLockProvider(string name);\n }\n public class CloudDistributedLockProviderFactory : ICloudDistributedLockProviderFactory", "score": 0.8664299249649048 }, { "filename": "CloudDistributedLock/CloudDistributedLockProviderFactory.cs", "retrieved_chunk": " {\n internal const string DefaultName = \"__DEFAULT\";\n private readonly ConcurrentDictionary<string, ICloudDistributedLockProvider> clients = new();\n public CloudDistributedLockProviderFactory(IOptionsMonitor<CloudDistributedLockProviderOptions> optionsMonitor)\n {\n this.OptionsMonitor = optionsMonitor;\n }\n protected IOptionsMonitor<CloudDistributedLockProviderOptions> OptionsMonitor { get; }\n public ICloudDistributedLockProvider GetLockProvider(string name)\n {", "score": 0.8389444947242737 }, { "filename": "CloudDistributedLock/CloudDistributedLock.cs", "retrieved_chunk": " private Timer? timer;\n private bool isDisposed;\n public static CloudDistributedLock CreateUnacquiredLock()\n {\n return new CloudDistributedLock();\n }\n public static CloudDistributedLock CreateAcquiredLock(CosmosLockClient cosmosLockClient, ItemResponse<LockRecord> item)\n {\n return new CloudDistributedLock(cosmosLockClient, item);\n }", "score": 0.8327982425689697 }, { "filename": "CloudDistributedLock/CloudDistributedLockProviderFactory.cs", "retrieved_chunk": " return clients.GetOrAdd(name, n => CreateClient(n));\n }\n public ICloudDistributedLockProvider GetLockProvider()\n {\n return GetLockProvider(DefaultName);\n }\n protected ICloudDistributedLockProvider CreateClient(string name)\n {\n var options = OptionsMonitor.Get(name);\n ArgumentNullException.ThrowIfNull(options.ProviderName);", "score": 0.8217089176177979 } ]
csharp
CloudDistributedLock> AcquireLockAsync(string name, TimeSpan? timeout = default);
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChatGPTInterface { public class EmbeddingResponse { [JsonProperty("object")] public string ObjectType { get; set; } [JsonProperty("data")] public EmbeddingData[] Data { get; set; } [JsonProperty("model")] public string Model { get; set; } [JsonProperty("usage")] public
EmbeddingUsage Usage {
get; set; } } }
ChatGPTInterface/EmbeddingResponse.cs
TaxAIExamples-semantic-search-using-chatgpt-a90ef71
[ { "filename": "ChatGPTInterface/CompletionResponse.cs", "retrieved_chunk": " [JsonProperty(\"id\")]\n public string Id { get; set; }\n [JsonProperty(\"object\")]\n public string ObjectType { get; set; }\n [JsonProperty(\"created\")]\n public int Created { get; set; }\n [JsonProperty(\"choices\")]\n public CompletionChoices[] Choices { get; set; }\n [JsonProperty(\"usage\")]\n public CompletionUsage Usage { get; set; }", "score": 0.9193329811096191 }, { "filename": "ChatGPTInterface/EmbeddingData.cs", "retrieved_chunk": " [JsonProperty(\"object\")]\n public string EmbeddingObject { get; set; }\n [JsonProperty(\"index\")]\n public int Index { get; set; }\n [JsonProperty(\"embedding\")]\n public double[] Embedding { get; set; }\n }\n}", "score": 0.9186287522315979 }, { "filename": "ChatGPTInterface/CompletionChoices.cs", "retrieved_chunk": " [JsonProperty(\"text\")]\n public string Text { get; set; }\n [JsonProperty(\"index\")]\n public int Index { get; set; }\n [JsonProperty(\"logprobs\")]\n public int? LogProbs { get; set; }\n [JsonProperty(\"finish_reason\")]\n public string FinishReason { get; set; }\n }\n}", "score": 0.8860979080200195 }, { "filename": "ChatGPTInterface/KnowledgeRecord.cs", "retrieved_chunk": " public int Id { get; set; }\n public string Title { get; set; }\n public string Content{ get; set; }\n public int Tokens { get; set; }\n public List<KnowledgeVectorItem> KnowledgeVector { get; set; }\n }\n}", "score": 0.8426898717880249 }, { "filename": "ChatGPTInterface/CompletionUsage.cs", "retrieved_chunk": " [JsonProperty(\"prompt_tokens\")]\n public int Tokens { get; set; }\n [JsonProperty(\"completion_tokens\")]\n public int CompletionTokens { get; set; }\n [JsonProperty(\"total_tokens\")]\n public int TotalTokens { get; set; }\n }\n}", "score": 0.8301886320114136 } ]
csharp
EmbeddingUsage Usage {
/* * Copyright (C) Antony Vitillo (aka Skarredghost), Perpetual eMotion 2023. * Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT). */ using System; using System.Collections; using System.Collections.Generic; using System.Threading; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; using vrroom.CubicMusic.Audio; using vrroom.CubicMusic.CubesMgmt; namespace vrroom.CubicMusic.UI { /// <summary> /// Managest the UI for the user to create an AI query and receive the responses /// </summary> public class UserQueryCreationCanvas : MonoBehaviour { /// <summary> /// Toggle to enable/disable the recording of the microphone /// </summary> [SerializeField] private Toggle m_recordingToggle; /// <summary> /// Button to send the prompt to the AI cloud /// </summary> [SerializeField] private Button m_sendPromptButton; /// <summary> /// Input field with the textual query /// </summary> [SerializeField] private TMP_InputField m_textQueryInputField; /// <summary> /// The object responsible to generate the logic from the prompts. /// Must implement <see cref="ICreatesLogicFromPrompt"/> /// If it is null, defaults to <see cref="CubesManager"/> /// </summary> [SerializeField] private MonoBehaviour m_logicFromQueriesGeneratorBehaviour; /// <summary> /// Element to be notified of the queries so that can generate logic /// </summary> private
ICreatesLogicFromPrompt m_logicFromPromptCreator;
/// <summary> /// Cancellation token /// </summary> private CancellationTokenSource m_cancellationTokenSource; /// <summary> /// Awake /// </summary> private void Awake() { m_cancellationTokenSource = new CancellationTokenSource(); if(m_logicFromQueriesGeneratorBehaviour == null) m_logicFromPromptCreator = CubesManager.Instance; else m_logicFromPromptCreator = m_logicFromQueriesGeneratorBehaviour as ICreatesLogicFromPrompt; } /// <summary> /// On Enable /// </summary> private void OnEnable() { m_recordingToggle.onValueChanged.AddListener(OnRecordingToggleValueChanged); m_sendPromptButton.onClick.AddListener(OnSendPromptButtonClicked); } /// <summary> /// On Application Quit /// </summary> private void OnApplicationQuit() { //cancel all pending tasks m_cancellationTokenSource.Cancel(); } /// <summary> /// On Disable /// </summary> private void OnDisable() { m_recordingToggle.onValueChanged.RemoveListener(OnRecordingToggleValueChanged); m_sendPromptButton.onClick.RemoveListener(OnSendPromptButtonClicked); } /// <summary> /// Callback called when the recording toggle value changes /// </summary> /// <param name="value">The new value of the toggle</param> private async void OnRecordingToggleValueChanged(bool value) { //if the toggle is on, start recording if (value) AudioManager.Instance.MicrophoneManager.StartRecording(false, 30); //if the toggle is off, stop recording and generate the logic else { var userAudioClip = AudioManager.Instance.MicrophoneManager.EndRecording(); await m_logicFromPromptCreator.GenerateLogicForGroupFromAudio(userAudioClip); } } /// <summary> /// Callback called when the send prompt button is clicked /// </summary> private async void OnSendPromptButtonClicked() { await m_logicFromPromptCreator.GenerateLogicForGroupFromText(m_textQueryInputField.text); } #if UNITY_EDITOR /// <summary> /// On Validate /// </summary> private void OnValidate() { //check that the assignment of the logic from queries generator is correct if (m_logicFromQueriesGeneratorBehaviour != null && m_logicFromQueriesGeneratorBehaviour.GetComponent<ICreatesLogicFromPrompt>() == null) { Debug.LogError("[User Queries UI] The logic from queries generator must implement ICreatesLogicFromPrompt"); m_logicFromQueriesGeneratorBehaviour = null; } } #endif } }
CubicMusic/Assets/_CubicMusic/Runtime/UI/Scripts/UserQueryCreationCanvas.cs
Perpetual-eMotion-DynaimicApps-46c94e0
[ { "filename": "CubicMusic/Assets/_CubicMusic/Runtime/CubesManagement/Scripts/CubesManager.cs", "retrieved_chunk": " /// </summary>\n private AiQueryPerformer m_aiQueryPerformer;\n /// <summary>\n /// The element that creates the logic from the AI prompts\n /// </summary>\n private GenerativeLogicManager m_generativeLogicManager;\n /// <summary>\n /// The list of cube groups managed by this object.\n /// Every group contains a list of cubes to which logic can be added at runtime\n /// </summary>", "score": 0.8848136067390442 }, { "filename": "CubicMusic/Assets/_CubicMusic/Runtime/CubesManagement/Scripts/CubesGenerator.cs", "retrieved_chunk": " /// Generates the cubes in the scene to which the AI logic can be added at runtime\n /// </summary>\n public class CubesGenerator : MonoBehaviour\n {\n /// <summary>\n /// Action to be used to add a cube to the scene\n /// </summary>\n [SerializeField]\n private InputActionReference m_addCubeAction;\n /// <summary>", "score": 0.8691974878311157 }, { "filename": "CubicMusic/Assets/_CubicMusic/Runtime/CubesManagement/Scripts/EmotionalCubesGenerator.cs", "retrieved_chunk": " PostPrompt = @\"\"\" .Please generate the prompts only that are coherent with this mood. Write No examples, no explanations.\"\n };\n /// <summary>\n /// The element that performs the queries to the AI cloud\n /// </summary>\n private AiQueryPerformer m_aiQueryPerformer;\n /// <summary>\n /// Ai completion parameters\n /// </summary>\n private AiGenerationParameters m_aiParameters;", "score": 0.8657869100570679 }, { "filename": "CubicMusic/Assets/_CubicMusic/Runtime/CubesManagement/Scripts/CubesManager.cs", "retrieved_chunk": " private List<ObjectsGroupLogicHandler> m_managedCubeGroups;\n /// <inheritdoc />\n public AiPromptTemplate PromptTemplate => s_promptTemplateForUnityScripts;\n /// <summary>\n /// Get the element that performs the queries to the AI cloud\n /// </summary>\n public AiQueryPerformer AiQueryPerformer => m_aiQueryPerformer;\n /// <summary>\n /// Singleton instance\n /// </summary>", "score": 0.8630944490432739 }, { "filename": "CubicMusic/Assets/_CubicMusic/Runtime/Input/Scripts/FlyMovement.cs", "retrieved_chunk": " /// </summary>\n [SerializeField]\n private InputActionReference m_upDownMovementAction;\n /// <summary>\n /// Action for activating/deactivating the current movement\n /// </summary>\n [SerializeField]\n private InputActionReference m_flyActivationAction;\n /// <summary>\n /// True if the movement is activated when the <see cref=\"m_flyActivationAction\"/> is on, false otherwise", "score": 0.8554163575172424 } ]
csharp
ICreatesLogicFromPrompt m_logicFromPromptCreator;
// Licensed under the MIT License. See LICENSE in the project root for license information. using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using UnityEngine; using UnityEngine.Scripting; using Utilities.WebRequestRest; namespace BlockadeLabs.Skyboxes { public sealed class SkyboxEndpoint : BlockadeLabsBaseEndpoint { [Preserve] private class SkyboxInfoRequest { [Preserve] [JsonConstructor] public SkyboxInfoRequest([JsonProperty("request")] SkyboxInfo skyboxInfo) { SkyboxInfo = skyboxInfo; } [Preserve] [JsonProperty("request")] public SkyboxInfo SkyboxInfo { get; } } [Preserve] private class SkyboxOperation { [Preserve] [JsonConstructor] public SkyboxOperation( [JsonProperty("success")] string success, [JsonProperty("error")] string error) { Success = success; Error = error; } [Preserve] [JsonProperty("success")] public string Success { get; } [Preserve] [JsonProperty("Error")] public string Error { get; } } public SkyboxEndpoint(BlockadeLabsClient client) : base(client) { } protected override string Root => string.Empty; /// <summary> /// Returns the list of predefined styles that can influence the overall aesthetic of your skybox generation. /// </summary> /// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param> /// <returns>A list of <see cref="SkyboxStyle"/>s.</returns> public async Task<IReadOnlyList<SkyboxStyle>> GetSkyboxStylesAsync(CancellationToken cancellationToken = default) { var response = await Rest.GetAsync(GetUrl("skybox/styles"), parameters: new RestParameters(client.DefaultRequestHeaders), cancellationToken); response.Validate(); return JsonConvert.DeserializeObject<IReadOnlyList<SkyboxStyle>>(response.Body, client.JsonSerializationOptions); } /// <summary> /// Generate a skybox image. /// </summary> /// <param name="skyboxRequest"><see cref="SkyboxRequest"/>.</param> /// <param name="pollingInterval">Optional, polling interval in seconds.</param> /// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param> /// <returns><see cref="SkyboxInfo"/>.</returns> public async Task<SkyboxInfo> GenerateSkyboxAsync(
SkyboxRequest skyboxRequest, int? pollingInterval = null, CancellationToken cancellationToken = default) {
var formData = new WWWForm(); formData.AddField("prompt", skyboxRequest.Prompt); if (!string.IsNullOrWhiteSpace(skyboxRequest.NegativeText)) { formData.AddField("negative_text", skyboxRequest.NegativeText); } if (skyboxRequest.Seed.HasValue) { formData.AddField("seed", skyboxRequest.Seed.Value); } if (skyboxRequest.SkyboxStyleId.HasValue) { formData.AddField("skybox_style_id", skyboxRequest.SkyboxStyleId.Value); } if (skyboxRequest.RemixImagineId.HasValue) { formData.AddField("remix_imagine_id", skyboxRequest.RemixImagineId.Value); } if (skyboxRequest.Depth) { formData.AddField("return_depth", skyboxRequest.Depth.ToString()); } if (skyboxRequest.ControlImage != null) { if (!string.IsNullOrWhiteSpace(skyboxRequest.ControlModel)) { formData.AddField("control_model", skyboxRequest.ControlModel); } using var imageData = new MemoryStream(); await skyboxRequest.ControlImage.CopyToAsync(imageData, cancellationToken); formData.AddBinaryData("control_image", imageData.ToArray(), skyboxRequest.ControlImageFileName); skyboxRequest.Dispose(); } var response = await Rest.PostAsync(GetUrl("skybox"), formData, parameters: new RestParameters(client.DefaultRequestHeaders), cancellationToken); response.Validate(); var skyboxInfo = JsonConvert.DeserializeObject<SkyboxInfo>(response.Body, client.JsonSerializationOptions); while (!cancellationToken.IsCancellationRequested) { await Task.Delay(pollingInterval ?? 3 * 1000, CancellationToken.None) .ConfigureAwait(true); // Configure await to make sure we're still in Unity context skyboxInfo = await GetSkyboxInfoAsync(skyboxInfo, CancellationToken.None); if (skyboxInfo.Status is Status.Pending or Status.Processing or Status.Dispatched) { continue; } break; } if (cancellationToken.IsCancellationRequested) { var cancelResult = await CancelSkyboxGenerationAsync(skyboxInfo, CancellationToken.None); if (!cancelResult) { throw new Exception($"Failed to cancel generation for {skyboxInfo.Id}"); } } cancellationToken.ThrowIfCancellationRequested(); if (skyboxInfo.Status != Status.Complete) { throw new Exception($"Failed to generate skybox! {skyboxInfo.Id} -> {skyboxInfo.Status}\nError: {skyboxInfo.ErrorMessage}\n{skyboxInfo}"); } await skyboxInfo.LoadTexturesAsync(cancellationToken); return skyboxInfo; } /// <summary> /// Returns the skybox metadata for the given skybox id. /// </summary> /// <param name="id">Skybox Id.</param> /// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param> /// <returns><see cref="SkyboxInfo"/>.</returns> public async Task<SkyboxInfo> GetSkyboxInfoAsync(int id, CancellationToken cancellationToken = default) { var response = await Rest.GetAsync(GetUrl($"imagine/requests/{id}"), parameters: new RestParameters(client.DefaultRequestHeaders), cancellationToken); response.Validate(); return JsonConvert.DeserializeObject<SkyboxInfoRequest>(response.Body, client.JsonSerializationOptions).SkyboxInfo; } /// <summary> /// Deletes a skybox by id. /// </summary> /// <param name="id">The id of the skybox.</param> /// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param> /// <returns>True, if skybox was successfully deleted.</returns> public async Task<bool> DeleteSkyboxAsync(int id, CancellationToken cancellationToken = default) { var response = await Rest.DeleteAsync(GetUrl($"imagine/deleteImagine/{id}"), new RestParameters(client.DefaultRequestHeaders), cancellationToken); response.Validate(); var skyboxOp = JsonConvert.DeserializeObject<SkyboxOperation>(response.Body, client.JsonSerializationOptions); const string successStatus = "Item deleted successfully"; if (skyboxOp is not { Success: successStatus }) { throw new Exception($"Failed to cancel generation for skybox {id}!\n{skyboxOp?.Error}"); } return skyboxOp.Success.Equals(successStatus); } /// <summary> /// Gets the previously generated skyboxes. /// </summary> /// <param name="parameters">Optional, <see cref="SkyboxHistoryParameters"/>.</param> /// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param> /// <returns><see cref="SkyboxHistory"/>.</returns> public async Task<SkyboxHistory> GetSkyboxHistoryAsync(SkyboxHistoryParameters parameters = null, CancellationToken cancellationToken = default) { var historyRequest = parameters ?? new SkyboxHistoryParameters(); var response = await Rest.GetAsync(GetUrl($"imagine/myRequests{historyRequest}"), parameters: new RestParameters(client.DefaultRequestHeaders), cancellationToken); response.Validate(); return JsonConvert.DeserializeObject<SkyboxHistory>(response.Body, client.JsonSerializationOptions); } /// <summary> /// Cancels a pending skybox generation request by id. /// </summary> /// <param name="id">The id of the skybox.</param> /// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param> /// <returns>True, if generation was cancelled.</returns> public async Task<bool> CancelSkyboxGenerationAsync(int id, CancellationToken cancellationToken = default) { var response = await Rest.DeleteAsync(GetUrl($"imagine/requests/{id}"), new RestParameters(client.DefaultRequestHeaders), cancellationToken); response.Validate(); var skyboxOp = JsonConvert.DeserializeObject<SkyboxOperation>(response.Body, client.JsonSerializationOptions); if (skyboxOp is not { Success: "true" }) { throw new Exception($"Failed to cancel generation for skybox {id}!\n{skyboxOp?.Error}"); } return skyboxOp.Success.Equals("true"); } /// <summary> /// Cancels ALL pending skybox generation requests. /// </summary> /// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param> public async Task<bool> CancelAllPendingSkyboxGenerationsAsync(CancellationToken cancellationToken = default) { var response = await Rest.DeleteAsync(GetUrl("imagine/requests/pending"), new RestParameters(client.DefaultRequestHeaders), cancellationToken); response.Validate(); var skyboxOp = JsonConvert.DeserializeObject<SkyboxOperation>(response.Body, client.JsonSerializationOptions); if (skyboxOp is not { Success: "true" }) { if (skyboxOp != null && skyboxOp.Error.Contains("You don't have any pending")) { return false; } throw new Exception($"Failed to cancel all pending skybox generations!\n{skyboxOp?.Error}"); } return skyboxOp.Success.Equals("true"); } } }
BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/Skyboxes/SkyboxEndpoint.cs
RageAgainstThePixel-com.rest.blockadelabs-aa2142f
[ { "filename": "BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/Skyboxes/SkyboxInfo.cs", "retrieved_chunk": " [JsonProperty(\"error_message\")]\n public string ErrorMessage { get; set; }\n public override string ToString() => JsonConvert.SerializeObject(this, Formatting.Indented);\n public static implicit operator int(SkyboxInfo skyboxInfo) => skyboxInfo.Id;\n /// <summary>\n /// Loads the textures for this skybox.\n /// </summary>\n /// <param name=\"cancellationToken\">Optional, <see cref=\"CancellationToken\"/>.</param>\n public async Task LoadTexturesAsync(CancellationToken cancellationToken = default)\n {", "score": 0.7765930891036987 }, { "filename": "BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/BlockadeLabsAuthentication.cs", "retrieved_chunk": " /// </summary>\n /// <param name=\"apiKey\">The API key, required to access the API endpoint.</param>\n public BlockadeLabsAuthentication(string apiKey) => Info = new BlockadeLabsAuthInfo(apiKey);\n /// <summary>\n /// Instantiates a new Authentication object with the given <paramref name=\"authInfo\"/>, which may be <see langword=\"null\"/>.\n /// </summary>\n /// <param name=\"authInfo\"></param>\n public BlockadeLabsAuthentication(BlockadeLabsAuthInfo authInfo) => Info = authInfo;\n /// <inheritdoc />\n public override BlockadeLabsAuthInfo Info { get; }", "score": 0.7494311332702637 }, { "filename": "BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/Skyboxes/SkyboxRequest.cs", "retrieved_chunk": " /// </param>\n /// <param name=\"controlImage\">\n /// <see cref=\"Stream\"/> data of control image for request.\n /// </param>\n /// <param name=\"controlImageFileName\">\n /// File name of <see cref=\"controlImage\"/>.\n /// </param>\n /// <param name=\"controlModel\">\n /// Model used for the <see cref=\"ControlImage\"/>.\n /// Currently the only option is: \"scribble\".", "score": 0.733674168586731 }, { "filename": "BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/Skyboxes/SkyboxRequest.cs", "retrieved_chunk": " /// </param>\n /// <param name=\"remixImagineId\">\n /// ID of a previously generated skybox.\n /// </param>\n /// <param name=\"depth\">\n /// Return depth map image.\n /// </param>\n public SkyboxRequest(\n string prompt,\n string negativeText = null,", "score": 0.7278350591659546 }, { "filename": "BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/Skyboxes/SkyboxRequest.cs", "retrieved_chunk": " /// </param>\n /// <param name=\"remixImagineId\">\n /// ID of a previously generated skybox.\n /// </param>\n /// <param name=\"depth\">\n /// Return depth map image.\n /// </param>\n public SkyboxRequest(\n string prompt,\n Texture2D controlImage,", "score": 0.7171511054039001 } ]
csharp
SkyboxRequest skyboxRequest, int? pollingInterval = null, CancellationToken cancellationToken = default) {
using ChatGPTConnection; using ChatUI.Core; using ChatUI.MVVM.Model; using System; using System.Linq; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows; namespace ChatUI.MVVM.ViewModel { internal class MainViewModel : ObservableObject { public ObservableCollection<
MessageModel> Messages {
get; set; } private MainWindow MainWindow { get; set; } public RelayCommand SendCommand { get; set; } private string _message = ""; public string Message { get { return _message; } set { _message = value; OnPropertyChanged(); } } private string CatIconPath => Path.Combine(MainWindow.DllDirectory, "Icons/cat.jpeg"); public MainViewModel() { Messages = new ObservableCollection<MessageModel>(); //ビュー(?)を取得 var window = Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x is MainWindow); MainWindow = (MainWindow)window; //キーを押したらメッセージが追加されるコマンド SendCommand = new RelayCommand(o => { if (Message == "") return; //自分のメッセージを追加 AddMyMessages(Message); //ChatGPTにメッセージをおくり、返信をメッセージに追加 SendToChatGPT(Message); //メッセージボックスを空にする Message = ""; }); //Test_Message(); } private void AddMyMessages(string message) { Messages.Add(new MessageModel { Username = "You", UsernameColor = "White", Time = DateTime.Now, MainMessage = message, IsMyMessage = true }); ScrollToBottom(); } //TODO: 多責務になっているので分割したい private async void SendToChatGPT(string message) { //LoadingSpinnerを表示 AddLoadingSpinner(); //APIキーをセッティングファイルから取得 Settings settings = Settings.LoadSettings(); if (settings == null || settings.APIKey == "") { MessageBox.Show("API key not found. Please set from the options."); return; } string apiKey = settings.APIKey; string systemMessage = settings.SystemMessage; //ChatGPTにメッセージを送る ChatGPTConnector connector = new ChatGPTConnector(apiKey, systemMessage); var response = await connector.RequestAsync(message); //LoadingSpinnerを削除 DeleteLoadingSpinner(); if (!response.isSuccess) { AddChatGPTMessage("API request failed. API key may be wrong.", null); return; } //返信をチャット欄に追加 string conversationText = response.GetConversation(); string fullText = response.GetMessage(); AddChatGPTMessage(conversationText, fullText); //イベントを実行 MainWindow.OnResponseReceived(new ChatGPTResponseEventArgs(response)); } private void AddChatGPTMessage(string mainMessage, string subMessage) { Messages.Add(new MessageModel { Username = "ChatGPT", UsernameColor = "#738CBA", ImageSource = CatIconPath, Time = DateTime.Now, MainMessage = mainMessage, SubMessage = subMessage, UseSubMessage = MainWindow.IsDebagMode, IsMyMessage = false }); ScrollToBottom(); } private void ScrollToBottom() { int lastIndex = MainWindow.ChatView.Items.Count - 1; var item = MainWindow.ChatView.Items[lastIndex]; MainWindow.ChatView.ScrollIntoView(item); } private void AddLoadingSpinner() { Messages.Add(new MessageModel { IsLoadingSpinner = true }); ScrollToBottom(); } private void DeleteLoadingSpinner() { for (int i = 0; i < Messages.Count; i++) { var item = Messages[i]; if (item.IsLoadingSpinner) { Messages.Remove(item); } } } } }
ChatUI/MVVM/ViewModel/MainViewModel.cs
4kk11-ChatGPTforRhino-382323e
[ { "filename": "ChatUI/MainWindow.xaml.cs", "retrieved_chunk": "using ChatUI.MVVM.ViewModel;\nusing System.ComponentModel;\nusing System.Runtime.CompilerServices;\nusing ChatGPTConnection;\nnamespace ChatUI\n{\n\tpublic partial class MainWindow : Window\n\t{\n\t\tpublic static string DllDirectory\n\t\t{", "score": 0.9024028182029724 }, { "filename": "ChatUI/Core/ObservableObject.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace ChatUI.Core\n{\n\tinternal class ObservableObject : INotifyPropertyChanged", "score": 0.8927032351493835 }, { "filename": "ChatUI/Core/RelayCommand.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Windows.Input;\nnamespace ChatUI.Core\n{\n\tclass RelayCommand : ICommand\n\t{", "score": 0.8750547170639038 }, { "filename": "ChatGPTforRhino/RhinoCommand.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Rhino;\nnamespace ChatGPTforRhino\n{\n\tpublic class RhinoCommands\n\t{", "score": 0.8681732416152954 }, { "filename": "ChatUI/App.xaml.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Configuration;\nusing System.Data;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nnamespace ChatUI\n{\n\t/// <summary>", "score": 0.851677417755127 } ]
csharp
MessageModel> Messages {
using System; using System.Collections.Generic; using System.Data.Common; using System.Linq; using System.Reflection; using DapperExtensions.Sql; using LogDashboard.Authorization; using LogDashboard.Extensions; using LogDashboard.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; namespace LogDashboard { public class LogDashboardCookieOptions { public TimeSpan Expire { get; set; } public string TokenKey { get; set; } public string TimestampKey { get; set; } public Func<
LogdashboardAccountAuthorizeFilter, string> Secure {
get; set; } public LogDashboardCookieOptions() { Expire = TimeSpan.FromDays(1); TokenKey = "LogDashboard.CookieKey"; TimestampKey = "LogDashboard.Timestamp"; Secure = (filter) => $"{filter.UserName}&&{filter.Password}"; } } }
src/LogDashboard.Authorization/LogDashboardCookieOptions.cs
Bryan-Cyf-LogDashboard.Authorization-14d4540
[ { "filename": "src/LogDashboard.Authorization/Models/LoginInput.cs", "retrieved_chunk": "using System;\nnamespace LogDashboard.Models\n{\n public class LoginInput\n {\n public string Name { get; set; }\n public string Password { get; set; }\n }\n}", "score": 0.9028995037078857 }, { "filename": "src/LogDashboard.Authorization/Authorization/LogdashboardAccountAuthorizeFilter.cs", "retrieved_chunk": " public class LogdashboardAccountAuthorizeFilter : ILogDashboardAuthorizationFilter\n {\n public string UserName { get; set; }\n public string Password { get; set; }\n public LogDashboardCookieOptions CookieOptions { get; set; }\n public LogdashboardAccountAuthorizeFilter(string userName, string password)\n {\n UserName = userName;\n Password = password;\n CookieOptions = new LogDashboardCookieOptions();", "score": 0.8939885497093201 }, { "filename": "src/LogDashboard.Authorization/Extensions/DateTimeExtensions.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nnamespace LogDashboard.Extensions\n{\n internal static class DateTimeExtensions\n {\n public static double ToUnixTimestamp(this DateTime target)\n {\n DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);", "score": 0.832510232925415 }, { "filename": "src/LogDashboard.Authorization/Authorization/LogdashboardAccountAuthorizeFilter.cs", "retrieved_chunk": " }\n public LogdashboardAccountAuthorizeFilter(string userName, string password, Action<LogDashboardCookieOptions> cookieConfig)\n {\n UserName = userName;\n Password = password;\n CookieOptions = new LogDashboardCookieOptions();\n cookieConfig.Invoke(CookieOptions);\n }\n public bool Authorization(LogDashboardContext context)\n {", "score": 0.827635645866394 }, { "filename": "src/LogDashboard.Authorization/EmbeddedFiles/LogDashboardAuthorizationEmbeddedFiles.cs", "retrieved_chunk": " };\n private static readonly Assembly Assembly;\n static LogDashboardAuthorizationEmbeddedFiles()\n {\n Assembly = Assembly.GetExecutingAssembly();\n }\n public static async Task IncludeEmbeddedFile(HttpContext context, string path)\n {\n context.Response.OnStarting(() =>\n {", "score": 0.8023525476455688 } ]
csharp
LogdashboardAccountAuthorizeFilter, string> Secure {
using HarmonyLib; using UnityEngine; namespace Ultrapain.Patches { class TurretFlag : MonoBehaviour { public int shootCountRemaining = ConfigManager.turretBurstFireCount.value; } class TurretStart { static void Postfix(Turret __instance) { __instance.gameObject.AddComponent<TurretFlag>(); } } class TurretShoot { static bool Prefix(Turret __instance, ref
EnemyIdentifier ___eid, ref RevolverBeam ___beam, ref Transform ___shootPoint, ref float ___aimTime, ref float ___maxAimTime, ref float ___nextBeepTime, ref float ___flashTime) {
TurretFlag flag = __instance.GetComponent<TurretFlag>(); if (flag == null) return true; if (flag.shootCountRemaining > 0) { RevolverBeam revolverBeam = GameObject.Instantiate<RevolverBeam>(___beam, new Vector3(__instance.transform.position.x, ___shootPoint.transform.position.y, __instance.transform.position.z), ___shootPoint.transform.rotation); revolverBeam.alternateStartPoint = ___shootPoint.transform.position; RevolverBeam revolverBeam2; if (___eid.totalDamageModifier != 1f && revolverBeam.TryGetComponent<RevolverBeam>(out revolverBeam2)) { revolverBeam2.damage *= ___eid.totalDamageModifier; } ___nextBeepTime = 0; ___flashTime = 0; ___aimTime = ___maxAimTime - ConfigManager.turretBurstFireDelay.value; if (___aimTime < 0) ___aimTime = 0; flag.shootCountRemaining -= 1; return false; } else flag.shootCountRemaining = ConfigManager.turretBurstFireCount.value; return true; } } class TurretAim { static void Postfix(Turret __instance) { TurretFlag flag = __instance.GetComponent<TurretFlag>(); if (flag == null) return; flag.shootCountRemaining = ConfigManager.turretBurstFireCount.value; } } }
Ultrapain/Patches/Turret.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": " componentInChildren.sourceWeapon = __instance.gameObject;\n counter.shotsLeft -= 1;\n __instance.Invoke(\"ShootProjectiles\", ConfigManager.mindflayerShootDelay.value / ___eid.totalSpeedModifier);\n return false;\n }\n }\n class EnemyIdentifier_DeliverDamage_MF\n {\n static bool Prefix(EnemyIdentifier __instance, ref float __3, GameObject __6)\n {", "score": 0.8595107793807983 }, { "filename": "Ultrapain/Patches/Stray.cs", "retrieved_chunk": " public static int projectileDamage = 10;\n public static int explosionDamage = 20;\n public static float coreSpeed = 110f;\n static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid, ref Animator ___anim, ref GameObject ___currentProjectile\n , ref NavMeshAgent ___nma, ref Zombie ___zmb)\n {\n if (___eid.enemyType != EnemyType.Stray)\n return;\n StrayFlag flag = __instance.gameObject.GetComponent<StrayFlag>();\n if (flag == null)", "score": 0.8569234013557434 }, { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": " //___eid.SpeedBuff();\n }\n }\n class Mindflayer_ShootProjectiles_Patch\n {\n public static float maxProjDistance = 5;\n public static float initialProjectileDistance = -1f;\n public static float distancePerProjShot = 0.2f;\n static bool Prefix(Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___enraged)\n {", "score": 0.8566128015518188 }, { "filename": "Ultrapain/Patches/Leviathan.cs", "retrieved_chunk": " }\n return false;\n }\n }\n class Leviathan_ProjectileBurst\n {\n static bool Prefix(LeviathanHead __instance, Animator ___anim,\n ref int ___projectilesLeftInBurst, ref float ___projectileBurstCooldown, ref bool ___inAction)\n {\n if (!__instance.active)", "score": 0.8548524379730225 }, { "filename": "Ultrapain/Patches/V2Second.cs", "retrieved_chunk": " void PrepareAltFire()\n {\n }\n void AltFire()\n {\n }\n }\n class V2SecondUpdate\n {\n static bool Prefix(V2 __instance, ref int ___currentWeapon, ref Transform ___overrideTarget, ref Rigidbody ___overrideTargetRb, ref float ___shootCooldown,", "score": 0.8547950387001038 } ]
csharp
EnemyIdentifier ___eid, ref RevolverBeam ___beam, ref Transform ___shootPoint, ref float ___aimTime, ref float ___maxAimTime, ref float ___nextBeepTime, ref float ___flashTime) {
using HarmonyLib; using UnityEngine; namespace Ultrapain.Patches { public class HideousMassProjectile : MonoBehaviour { public float damageBuf = 1f; public float speedBuf = 1f; } public class Projectile_Explode_Patch { static void Postfix(Projectile __instance) { HideousMassProjectile flag = __instance.gameObject.GetComponent<HideousMassProjectile>(); if (flag == null) return; GameObject createInsignia(float size, int damage) { GameObject insignia = GameObject.Instantiate(Plugin.virtueInsignia, __instance.transform.position, Quaternion.identity); insignia.transform.localScale = new Vector3(size, 1f, size); VirtueInsignia comp = insignia.GetComponent<VirtueInsignia>(); comp.windUpSpeedMultiplier = ConfigManager.hideousMassInsigniaSpeed.value * flag.speedBuf; comp.damage = (int)(damage * flag.damageBuf); comp.predictive = false; comp.hadParent = false; comp.noTracking = true; return insignia; } if (ConfigManager.hideousMassInsigniaXtoggle.value) { GameObject insignia = createInsignia(ConfigManager.hideousMassInsigniaXsize.value, ConfigManager.hideousMassInsigniaXdamage.value); insignia.transform.Rotate(new Vector3(0, 0, 90f)); } if (ConfigManager.hideousMassInsigniaYtoggle.value) { GameObject insignia = createInsignia(ConfigManager.hideousMassInsigniaYsize.value, ConfigManager.hideousMassInsigniaYdamage.value); } if (ConfigManager.hideousMassInsigniaZtoggle.value) { GameObject insignia = createInsignia(ConfigManager.hideousMassInsigniaZsize.value, ConfigManager.hideousMassInsigniaZdamage.value); insignia.transform.Rotate(new Vector3(90f, 0, 0)); } } } public class HideousMassHoming { static bool Prefix(
Mass __instance, EnemyIdentifier ___eid) {
__instance.explosiveProjectile = GameObject.Instantiate(Plugin.hideousMassProjectile); HideousMassProjectile flag = __instance.explosiveProjectile.AddComponent<HideousMassProjectile>(); flag.damageBuf = ___eid.totalDamageModifier; flag.speedBuf = ___eid.totalSpeedModifier; return true; } static void Postfix(Mass __instance) { GameObject.Destroy(__instance.explosiveProjectile); __instance.explosiveProjectile = Plugin.hideousMassProjectile; } } }
Ultrapain/Patches/HideousMass.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/SisyphusInstructionist.cs", "retrieved_chunk": " esi.enraged = true;\n }\n GameObject effect = GameObject.Instantiate(Plugin.enrageEffect, __instance.transform);\n effect.transform.localScale = Vector3.one * 0.2f;\n }\n }*/\n public class SisyphusInstructionist_Start\n {\n public static GameObject _shockwave;\n public static GameObject shockwave", "score": 0.7995604872703552 }, { "filename": "Ultrapain/Patches/MinosPrime.cs", "retrieved_chunk": " __instance.Teleport(vector + Vector3.up * 25f, __instance.transform.position);\n __instance.SendMessage(\"DropAttack\");\n return false;\n }\n }\n // End of PREPARE THYSELF\n class MinosPrime_ProjectileCharge\n {\n static bool Prefix(MinosPrime __instance, Animator ___anim)\n {", "score": 0.7868196964263916 }, { "filename": "Ultrapain/Patches/Panopticon.cs", "retrieved_chunk": " foreach (Text t in temp.textInstances)\n t.text = ConfigManager.obamapticonName.value;\n }\n }\n }\n }\n class Panopticon_SpawnInsignia\n {\n static bool Prefix(FleshPrison __instance, ref bool ___inAction, Statue ___stat, float ___maxHealth, int ___difficulty,\n ref float ___fleshDroneCooldown, EnemyIdentifier ___eid)", "score": 0.7846660614013672 }, { "filename": "Ultrapain/Patches/Panopticon.cs", "retrieved_chunk": " if (___fleshDroneCooldown < 1f)\n {\n ___fleshDroneCooldown = 1f;\n }\n return false;\n }\n }\n class Panopticon_HomingProjectileAttack\n {\n static void Postfix(FleshPrison __instance, EnemyIdentifier ___eid)", "score": 0.7802025079727173 }, { "filename": "Ultrapain/Patches/FleshPrison.cs", "retrieved_chunk": " flag.prison = __instance;\n flag.damageMod = ___eid.totalDamageModifier;\n flag.speedMod = ___eid.totalSpeedModifier;\n }\n }\n /*[HarmonyPatch(typeof(FleshPrison), \"SpawnInsignia\")]\n class FleshPrisonInsignia\n {\n static bool Prefix(FleshPrison __instance, ref bool ___inAction, ref float ___fleshDroneCooldown, EnemyIdentifier ___eid,\n Statue ___stat, float ___maxHealth)", "score": 0.778684675693512 } ]
csharp
Mass __instance, EnemyIdentifier ___eid) {
using Microsoft.Extensions.Logging; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Memory; using SKernel.Factory.Config; using System.Collections.Generic; using System.Linq; namespace SKernel.Factory { public class SemanticKernelFactory { private readonly NativeSkillsImporter _native; private readonly SemanticSkillsImporter _semantic; private readonly
SKConfig _config;
private readonly IMemoryStore _memoryStore; private readonly ILogger _logger; public SemanticKernelFactory(NativeSkillsImporter native, SemanticSkillsImporter semantic, SKConfig config, IMemoryStore memoryStore, ILoggerFactory logger) { _native = native; _semantic = semantic; _config = config; _memoryStore = memoryStore; _logger = logger.CreateLogger<SemanticKernelFactory>(); } public IKernel Create(ApiKey key, IList<string>? skills = null) { var selected = (skills ?? new List<string>()) .Select(_ => _.ToLower()).ToList(); var kernel = new KernelBuilder() .WithOpenAI(_config, key) .WithLogger(_logger) .Build() .RegistryCoreSkills(selected) .Register(_native, selected) .Register(_semantic, selected); kernel.UseMemory("embedding", _memoryStore); return kernel; } } }
src/SKernel/Factory/SemanticKernelFactory.cs
geffzhang-ai-search-aspnet-qdrant-chatgpt-378d2be
[ { "filename": "src/SKernel/Factory/NativeSkillsImporter.cs", "retrieved_chunk": "using Microsoft.SemanticKernel;\nusing SKernel.Factory.Config;\nusing System;\nusing System.Collections.Generic;\nnamespace SKernel.Factory\n{\n public class NativeSkillsImporter : ISkillsImporter\n {\n private readonly IList<Type> _skills;\n private readonly IServiceProvider _provider;", "score": 0.9170376062393188 }, { "filename": "src/SKernel/Factory/SemanticSkillsImporter.cs", "retrieved_chunk": "using Microsoft.Extensions.Logging;\nusing Microsoft.SemanticKernel;\nusing SKernel.Factory.Config;\nusing System.Collections.Generic;\nnamespace SKernel.Factory\n{\n public class SemanticSkillsImporter : ISkillsImporter\n {\n private readonly string[] _folders;\n private readonly ILogger<SemanticSkillsImporter> _logger;", "score": 0.8914299011230469 }, { "filename": "src/SKernel/Factory/Config/SkillOptions.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nnamespace SKernel.Factory.Config\n{\n public class SkillOptions\n {\n public string[] SemanticSkillsFolders { get; init; } = { \"./skills\" };\n public IList<Type> NativeSkillTypes { get; init; } = new List<Type>();\n }\n}", "score": 0.8688356876373291 }, { "filename": "src/SKernel/Factory/ISkillsImporter.cs", "retrieved_chunk": "using Microsoft.SemanticKernel;\nusing System.Collections.Generic;\nnamespace SKernel.Factory\n{\n public interface ISkillsImporter\n {\n void ImportSkills(IKernel kernel, IList<string> skills);\n }\n}", "score": 0.8430125117301941 }, { "filename": "src/SKernel/Factory/Config/SKConfig.cs", "retrieved_chunk": "namespace SKernel.Factory.Config\n{\n public class SKConfig\n {\n public string[] Skills { get; set; } = { \"./skills\" };\n public LanguageModel Models { get; set; } = new();\n public SemanticMemory Memory { get; set; } = new();\n public class LanguageModel\n {\n public string Text { get; set; } = \"text-davinci-003\";", "score": 0.8275648951530457 } ]
csharp
SKConfig _config;
using System.Text.Json; namespace WAGIapp.AI { internal class Master { private static Master singleton; public static Master Singleton { get { if (singleton == null) { Console.WriteLine("Create master"); singleton = new Master(); Console.WriteLine("Master created"); } return singleton; } } public
LongTermMemory Memory;
public ActionList Actions; public ScriptFile scriptFile; public bool Done = true; private string nextMemoryPrompt = ""; private string lastCommandOuput = ""; public List<string> Notes; private List<ChatMessage> LastMessages = new List<ChatMessage>(); private List<ChatMessage> LastCommand = new List<ChatMessage>(); public string FormatedNotes { get { string output = ""; for (int i = 0; i < Notes.Count; i++) { output += (i + 1) + ". " + Notes[i] + "\n"; } return output; } } public Master() { Notes = new List<string>(); Memory = new LongTermMemory(1024); Actions = new ActionList(10); scriptFile = new ScriptFile(); singleton = this; } public async Task Tick() { Console.WriteLine("master tick -master"); if (Done) return; if (Memory.memories.Count == 0) { await Memory.MakeMemory(Settings.Goal); Console.WriteLine("master start memory done"); } var masterInput = await GetMasterInput(); string responseString; MasterResponse response; var action = Actions.AddAction("Thinking", LogAction.ThinkIcon); while (true) { try { responseString = await OpenAI.GetChatCompletion(ChatModel.ChatGPT, masterInput); response = Utils.GetObjectFromJson<MasterResponse>(responseString) ?? new(); break; } catch (Exception) { Console.WriteLine("Master failed - trying again"); } } nextMemoryPrompt = response.thoughts; lastCommandOuput = await Commands.TryToRun(this, response.command); LastMessages.Add(new ChatMessage(ChatRole.Assistant, responseString)); LastCommand.Add(new ChatMessage(ChatRole.System, "Command output:\n" + lastCommandOuput)); if (LastMessages.Count >= 10) LastMessages.RemoveAt(0); if (LastCommand.Count >= 10) LastCommand.RemoveAt(0); action.Text = response.thoughts; masterInput.Add(LastMessages.Last()); masterInput.Add(LastCommand.Last()); Console.WriteLine(JsonSerializer.Serialize(masterInput, new JsonSerializerOptions() { WriteIndented = true })); Console.WriteLine(scriptFile.GetText()); Console.WriteLine("------------------------------------------------------------------------"); Actions.AddAction("Memory", LogAction.MemoryIcon); await Memory.MakeMemory(responseString); } public async Task<List<ChatMessage>> GetMasterInput() { List<ChatMessage> messages = new List<ChatMessage>(); messages.Add(Texts.MasterStartText); messages.Add(new ChatMessage(ChatRole.System, "Memories:\n" + await Memory.GetMemories(nextMemoryPrompt))); messages.Add(new ChatMessage(ChatRole.System, "Notes:\n" + FormatedNotes)); messages.Add(new ChatMessage(ChatRole.System, "Commands:\n" + Commands.GetCommands())); messages.Add(new ChatMessage(ChatRole.System, "Main Goal:\n" + Settings.Goal)); messages.Add(new ChatMessage(ChatRole.System, "Script file:\n" + scriptFile.GetText() + "\nEnd of script file")); messages.Add(Texts.MasterStartText); messages.Add(Texts.MasterOutputFormat); for (int i = 0; i < LastMessages.Count; i++) { messages.Add(LastMessages[i]); messages.Add(LastCommand[i]); } return messages; } } class MasterResponse { public string thoughts { get; set; } = ""; public string command { get; set; } = ""; } }
WAGIapp/AI/Master.cs
Woltvint-WAGI-d808927
[ { "filename": "WAGIapp/AI/AICommands/GoalReachedCommand.cs", "retrieved_chunk": " public override string Description => \"Command that you must call when you reach the main goal\";\n public override string Format => \"goal-reached\";\n public override async Task<string> Execute(Master caller, string[] args)\n {\n caller.Done = true;\n return \"done.\";\n }\n }\n}", "score": 0.8189883232116699 }, { "filename": "WAGIapp/AI/LongTermMemory.cs", "retrieved_chunk": " {\n Console.WriteLine(\"Add memory failed\");\n }\n MemoryChanged = true;\n }\n public async Task<string> GetMemories(string input)\n {\n string memoryInput = \"\";\n memoryInput += \"Available tags:\\n\";\n foreach (string tag in tags)", "score": 0.7890055179595947 }, { "filename": "WAGIapp/AI/AICommands/NoActionCommand.cs", "retrieved_chunk": " public override string Name => \"no-action\";\n public override string Description => \"does nothing\";\n public override string Format => \"no-action\";\n public override async Task<string> Execute(Master caller, string[] args)\n {\n return \"command did nothing\";\n }\n }\n}", "score": 0.7867208123207092 }, { "filename": "WAGIapp/AI/AICommands/Command.cs", "retrieved_chunk": "namespace WAGIapp.AI.AICommands\n{\n internal abstract class Command\n {\n public abstract string Name { get; }\n public abstract string Description { get; }\n public abstract string Format { get; }\n public abstract Task<string> Execute(Master caller, string[] args);\n }\n}", "score": 0.7784795761108398 }, { "filename": "WAGIapp/Program.cs", "retrieved_chunk": " {\n case 0:\n var a = Master.Singleton.Actions.AddAction(\"Thinking\", LogAction.ThinkIcon);\n await Task.Delay(4000);\n a.Text = \"testing text is cool and all but does the transition finally work of what? im quite tired of waiting for it to start working .. i would love to get to other things and stop obsesing about this.\";\n break;\n case 1:\n Master.Singleton.Actions.AddAction(\"Creating a memory\", LogAction.MemoryIcon);\n break;\n case 2:", "score": 0.7705152034759521 } ]
csharp
LongTermMemory Memory;
using System.Text; using System.Net; using Microsoft.Extensions.Caching.Memory; using Serilog; using Serilog.Events; using Iced.Intel; using static Iced.Intel.AssemblerRegisters; namespace OGXbdmDumper { public class Xbox : IDisposable { #region Properties private bool _disposed; private const int _cacheDuration = 1; // in minutes private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(_cacheDuration) }); private bool? _hasFastGetmem; public ScratchBuffer StaticScratch; public bool HasFastGetmem { get { if (_hasFastGetmem == null) { try { long testAddress = 0x10000; if (IsValidAddress(testAddress)) { Session.SendCommandStrict("getmem2 addr={0} length=1", testAddress.ToHexString()); Session.ClearReceiveBuffer(); _hasFastGetmem = true; Log.Information("Fast getmem support detected."); } else _hasFastGetmem = false; } catch { _hasFastGetmem = false; } } return _hasFastGetmem.Value; } } /// <summary> /// Determines whether precautions (usually at the expense of performance) should be taken to prevent crashing the xbox. /// </summary> public bool SafeMode { get; set; } = true; public bool IsConnected => Session.IsConnected; public int SendTimeout { get => Session.SendTimeout; set => Session.SendTimeout = value; } public int ReceiveTimeout { get => Session.ReceiveTimeout; set => Session.ReceiveTimeout = value; } public
Connection Session {
get; private set; } = new Connection(); public ConnectionInfo? ConnectionInfo { get; protected set; } /// <summary> /// The Xbox memory stream. /// </summary> public XboxMemoryStream Memory { get; private set; } public Kernel Kernel { get; private set; } public List<Module> Modules => GetModules(); public List<Thread> Threads => GetThreads(); public Version Version => GetVersion(); #endregion #region Connection public void Connect(string host, int port = 731) { _cache.Clear(); ConnectionInfo = Session.Connect(host, port); // init subsystems Memory = new XboxMemoryStream(this); Kernel = new Kernel(this); StaticScratch = new ScratchBuffer(this); Log.Information("Loaded Modules:"); foreach (var module in Modules) { Log.Information("\t{0} ({1})", module.Name, module.TimeStamp); } Log.Information("Xbdm Version {0}", Version); Log.Information("Kernel Version {0}", Kernel.Version); // enable remote code execution and use the remainder reloc section as scratch PatchXbdm(this); } public void Disconnect() { Session.Disconnect(); ConnectionInfo = null; _cache.Clear(); } public List<ConnectionInfo> Discover(int timeout = 500) { return ConnectionInfo.DiscoverXbdm(731, timeout); } public void Connect(IPEndPoint endpoint) { Connect(endpoint.Address.ToString(), endpoint.Port); } public void Connect(int timeout = 500) { Connect(Discover(timeout).First().Endpoint); } #endregion #region Memory public bool IsValidAddress(long address) { try { Session.SendCommandStrict("getmem addr={0} length=1", address.ToHexString()); return "??" != Session.ReceiveMultilineResponse()[0]; } catch { return false; } } public void ReadMemory(long address, Span<byte> buffer) { if (HasFastGetmem && !SafeMode) { Session.SendCommandStrict("getmem2 addr={0} length={1}", address.ToHexString(), buffer.Length); Session.Read(buffer); if (Log.IsEnabled(LogEventLevel.Verbose)) { Log.Verbose(buffer.ToHexString()); } } else if (!SafeMode) { // custom getmem2 Session.SendCommandStrict("funccall type=1 addr={0} length={1}", address, buffer.Length); Session.ReadExactly(buffer); if (Log.IsEnabled(LogEventLevel.Verbose)) { Log.Verbose(buffer.ToHexString()); } } else { Session.SendCommandStrict("getmem addr={0} length={1}", address.ToHexString(), buffer.Length); int bytesRead = 0; string hexString; while ((hexString = Session.ReceiveLine()) != ".") { Span<byte> slice = buffer.Slice(bytesRead, hexString.Length / 2); slice.FromHexString(hexString); bytesRead += slice.Length; } } } public void ReadMemory(long address, byte[] buffer, int offset, int count) { ReadMemory(address, buffer.AsSpan(offset, count)); } public void ReadMemory(long address, int count, Stream destination) { // argument checks if (address < 0) throw new ArgumentOutOfRangeException(nameof(address)); if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count)); if (destination == null) throw new ArgumentNullException(nameof(destination)); Span<byte> buffer = stackalloc byte[1024 * 80]; while (count > 0) { int bytesToRead = Math.Min(buffer.Length, count); Span<byte> slice = buffer.Slice(0, bytesToRead); ReadMemory(address, slice); destination.Write(slice); count -= bytesToRead; address += (uint)bytesToRead; } } public void WriteMemory(long address, ReadOnlySpan<byte> buffer) { const int maxBytesPerLine = 240; int totalWritten = 0; while (totalWritten < buffer.Length) { ReadOnlySpan<byte> slice = buffer.Slice(totalWritten, Math.Min(maxBytesPerLine, buffer.Length - totalWritten)); Session.SendCommandStrict("setmem addr={0} data={1}", (address + totalWritten).ToHexString(), slice.ToHexString()); totalWritten += slice.Length; } } public void WriteMemory(long address, byte[] buffer, int offset, int count) { WriteMemory(address, buffer.AsSpan(offset, count)); } public void WriteMemory(long address, int count, Stream source) { // argument checks if (address < 0) throw new ArgumentOutOfRangeException(nameof(address)); if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count)); if (source == null) throw new ArgumentNullException(nameof(source)); Span<byte> buffer = stackalloc byte[1024 * 80]; while (count > 0) { int bytesRead = source.Read(buffer.Slice(0, Math.Min(buffer.Length, count))); WriteMemory(address, buffer.Slice(0, bytesRead)); count -= bytesRead; address += bytesRead; } } #endregion #region Process public List<Thread> GetThreads() { List<Thread> threads = new List<Thread>(); Session.SendCommandStrict("threads"); foreach (var threadId in Session.ReceiveMultilineResponse()) { Session.SendCommandStrict("threadinfo thread={0}", threadId); var info = Connection.ParseKvpResponse(string.Join(Environment.NewLine, Session.ReceiveMultilineResponse())); threads.Add(new Thread { Id = Convert.ToInt32(threadId), Suspend = (int)(uint)info["suspend"], // initially -1 in earlier xbdm versions, 0 in later ones Priority = (int)(uint)info["priority"], TlsBase = (uint)info["tlsbase"], // optional depending on xbdm version Start = info.ContainsKey("start") ? (uint)info["start"] : 0, Base = info.ContainsKey("base") ? (uint)info["base"] : 0, Limit = info.ContainsKey("limit") ? (uint)info["limit"] : 0, CreationTime = DateTime.FromFileTime( (info.ContainsKey("createhi") ? (((long)(uint)info["createhi"]) << 32) : 0) | (info.ContainsKey("createlo") ? (uint)info["createlo"] : 0)) }); } return threads; } public List<Module> GetModules() { List<Module> modules = new List<Module>(); Session.SendCommandStrict("modules"); foreach (var moduleResponse in Session.ReceiveMultilineResponse()) { var moduleInfo = Connection.ParseKvpResponse(moduleResponse); Module module = new Module { Name = (string)moduleInfo["name"], BaseAddress = (uint)moduleInfo["base"], Size = (int)(uint)moduleInfo["size"], Checksum = (uint)moduleInfo["check"], TimeStamp = DateTimeOffset.FromUnixTimeSeconds((uint)moduleInfo["timestamp"]).DateTime, Sections = new List<ModuleSection>(), HasTls = moduleInfo.ContainsKey("tls"), IsXbe = moduleInfo.ContainsKey("xbe") }; Session.SendCommandStrict("modsections name=\"{0}\"", module.Name); foreach (var sectionResponse in Session.ReceiveMultilineResponse()) { var sectionInfo = Connection.ParseKvpResponse(sectionResponse); module.Sections.Add(new ModuleSection { Name = (string)sectionInfo["name"], Base = (uint)sectionInfo["base"], Size = (int)(uint)sectionInfo["size"], Flags = (uint)sectionInfo["flags"] }); } modules.Add(module); } return modules; } public Version GetVersion() { var version = _cache.Get<Version>(nameof(GetVersion)); if (version == null) { try { // peek inside VS_VERSIONINFO struct var versionAddress = GetModules().FirstOrDefault(m => m.Name.Equals("xbdm.dll")).GetSection(".rsrc").Base + 0x98; // call getmem directly to avoid dependency loops with ReadMemory checking the version Span<byte> buffer = stackalloc byte[sizeof(ushort) * 4]; Session.SendCommandStrict("getmem addr={0} length={1}", versionAddress.ToHexString(), buffer.Length); buffer.FromHexString(Session.ReceiveMultilineResponse().First()); version = new Version( BitConverter.ToUInt16(buffer.Slice(2, sizeof(ushort))), BitConverter.ToUInt16(buffer.Slice(0, sizeof(ushort))), BitConverter.ToUInt16(buffer.Slice(6, sizeof(ushort))), BitConverter.ToUInt16(buffer.Slice(4, sizeof(ushort))) ); // cache the result _cache.Set(nameof(GetVersion), version); } catch { version = new Version("0.0.0.0"); } } return version; } public void Stop() { Log.Information("Suspending xbox execution."); Session.SendCommand("stop"); } public void Go() { Log.Information("Resuming xbox execution."); Session.SendCommand("go"); } /// <summary> /// Calls an Xbox function. /// </summary> /// <param name="address">The function address.</param> /// <param name="args">The function arguments.</param> /// <returns>Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.</returns> public uint Call(long address, params object[] args) { // TODO: call context (~4039+ which requires qwordparam) // injected script pushes arguments in reverse order for simplicity, this corrects that var reversedArgs = args.Reverse().ToArray(); StringBuilder command = new StringBuilder(); command.AppendFormat("funccall type=0 addr={0} ", address); for (int i = 0; i < reversedArgs.Length; i++) { command.AppendFormat("arg{0}={1} ", i, Convert.ToUInt32(reversedArgs[i])); } var returnValues = Connection.ParseKvpResponse(Session.SendCommandStrict(command.ToString()).Message); return (uint)returnValues["eax"]; } /// <summary> /// Original Xbox Debug Monitor runtime patches. /// Prevents crashdumps from being written to the HDD and enables remote code execution. /// </summary> /// <param name="target"></param> private void PatchXbdm(Xbox target) { // the spin routine to be patched in after the signature patterns // spin: // jmp spin // int 3 var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC }; // prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+) if (target.Signatures.ContainsKey("ReadWriteOneSector")) { Log.Information("Disabling crashdump functionality."); target.WriteMemory(target.Signatures["ReadWriteOneSector"] + 9, spinBytes); } else if (target.Signatures.ContainsKey("WriteSMBusByte")) { // this will prevent the LED state from changing upon crash Log.Information("Disabling crashdump functionality."); target.WriteMemory(target.Signatures["WriteSMBusByte"] + 9, spinBytes); } Log.Information("Patching xbdm memory to enable remote code execution."); uint argThreadStringAddress = StaticScratch.Alloc("thread\0"); uint argTypeStringAddress = StaticScratch.Alloc("type\0"); uint argAddrStringAddress = StaticScratch.Alloc("addr\0"); uint argLengthStringAddress = StaticScratch.Alloc("length\0"); uint argFormatStringAddress = StaticScratch.Alloc("arg%01d\0"); uint returnFormatAddress = StaticScratch.Alloc("eax=0x%X\0"); var asm = new Assembler(32); #region HrSendGetMemory2Data uint getmem2CallbackAddress = 0; if (!HasFastGetmem) { // labels var label1 = asm.CreateLabel(); var label2 = asm.CreateLabel(); var label3 = asm.CreateLabel(); asm.push(ebx); asm.mov(ebx, __dword_ptr[esp + 8]); // pdmcc asm.mov(eax, __dword_ptr[ebx + 0x14]); // size asm.test(eax, eax); asm.mov(edx, __dword_ptr[ebx + 0x10]); asm.ja(label1); //asm.push(__dword_ptr[ebx + 8]); //asm.call((uint)target.Signatures["DmFreePool"]); //asm.and(__dword_ptr[ebx + 8], 0); asm.mov(eax, 0x82DB0104); asm.jmp(label3); asm.Label(ref label1); asm.mov(ecx, __dword_ptr[ebx + 0xC]); // buffer size asm.cmp(eax, ecx); asm.jb(label2); asm.mov(eax, ecx); asm.Label(ref label2); asm.push(ebp); asm.push(esi); asm.mov(esi, __dword_ptr[edx + 0x14]); // address asm.push(edi); asm.mov(edi, __dword_ptr[ebx + 8]); asm.mov(ecx, eax); asm.mov(ebp, ecx); asm.shr(ecx, 2); asm.rep.movsd(); asm.mov(ecx, ebp); asm.and(ecx, 3); asm.rep.movsb(); asm.sub(__dword_ptr[ebx + 0x14], eax); asm.pop(edi); asm.mov(__dword_ptr[ebx + 4], eax); asm.add(__dword_ptr[edx + 0x14], eax); asm.pop(esi); asm.mov(eax, 0x2DB0000); asm.pop(ebp); asm.Label(ref label3); asm.pop(ebx); asm.ret(0xC); getmem2CallbackAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address)); } #endregion #region HrFunctionCall // 3424+ as it depends on sprintf within xbdm, earlier versions can possibly call against the kernel but their exports are different asm = new Assembler(32); // labels var binaryResponseLabel = asm.CreateLabel(); var getmem2Label = asm.CreateLabel(); var errorLabel = asm.CreateLabel(); var successLabel = asm.CreateLabel(); // prolog asm.push(ebp); asm.mov(ebp, esp); asm.sub(esp, 0x10); // carve out arbitrary space for local temp variables asm.pushad(); // disable write protection globally, otherwise checked kernel calls may fail when writing to the default scratch space asm.mov(eax, cr0); asm.and(eax, 0xFFFEFFFF); asm.mov(cr0, eax); // arguments var commandPtr = ebp + 0x8; var responseAddress = ebp + 0xC; var pdmcc = ebp + 0x14; // local variables var temp = ebp - 0x4; var callAddress = ebp - 0x8; var argName = ebp - 0x10; // check for thread id asm.lea(eax, temp); asm.push(eax); asm.push(argThreadStringAddress); // 'thread', 0 asm.push(__dword_ptr[commandPtr]); asm.call((uint)target.Signatures["FGetDwParam"]); asm.test(eax, eax); var customCommandLabel = asm.CreateLabel(); asm.je(customCommandLabel); // call original code if thread id exists asm.push(__dword_ptr[temp]); asm.call((uint)target.Signatures["DmSetupFunctionCall"]); var doneLabel = asm.CreateLabel(); asm.jmp(doneLabel); // thread argument doesn't exist, must be a custom command asm.Label(ref customCommandLabel); // determine custom function type asm.lea(eax, temp); asm.push(eax); asm.push(argTypeStringAddress); // 'type', 0 asm.push(__dword_ptr[commandPtr]); asm.call((uint)target.Signatures["FGetDwParam"]); asm.test(eax, eax); asm.je(errorLabel); #region Custom Call (type 0) asm.cmp(__dword_ptr[temp], 0); asm.jne(getmem2Label); // get the call address asm.lea(eax, __dword_ptr[callAddress]); asm.push(eax); asm.push(argAddrStringAddress); // 'addr', 0 asm.push(__dword_ptr[commandPtr]); asm.call((uint)target.Signatures["FGetDwParam"]); asm.test(eax, eax); asm.je(errorLabel); // push arguments (leave it up to caller to reverse argument order and supply the correct amount) asm.xor(edi, edi); var nextArgLabel = asm.CreateLabel(); var noMoreArgsLabel = asm.CreateLabel(); asm.Label(ref nextArgLabel); { // get argument name asm.push(edi); // argument index asm.push(argFormatStringAddress); // format string address asm.lea(eax, __dword_ptr[argName]); // argument name address asm.push(eax); asm.call((uint)target.Signatures["sprintf"]); asm.add(esp, 0xC); // check if it's included in the command asm.lea(eax, __[temp]); // argument value address asm.push(eax); asm.lea(eax, __[argName]); // argument name address asm.push(eax); asm.push(__dword_ptr[commandPtr]); // command asm.call((uint)target.Signatures["FGetDwParam"]); asm.test(eax, eax); asm.je(noMoreArgsLabel); // push it on the stack asm.push(__dword_ptr[temp]); asm.inc(edi); // move on to the next argument asm.jmp(nextArgLabel); } asm.Label(ref noMoreArgsLabel); // perform the call asm.call(__dword_ptr[callAddress]); // print response message asm.push(eax); // integer return value asm.push(returnFormatAddress); // format string address asm.push(__dword_ptr[responseAddress]); // response address asm.call((uint)target.Signatures["sprintf"]); asm.add(esp, 0xC); asm.jmp(successLabel); #endregion #region Fast Getmem (type 1) asm.Label(ref getmem2Label); asm.cmp(__dword_ptr[temp], 1); asm.jne(errorLabel); if (!HasFastGetmem) { // TODO: figure out why DmAllocatePool crashes, for now, allocate static scratch space (prevents multi-session!) StaticScratch.Align16(); uint getmem2BufferSize = 512; uint getmem2buffer = StaticScratch.Alloc(new byte[getmem2BufferSize]); // get length and size args asm.mov(esi, __dword_ptr[pdmcc]); asm.push(__dword_ptr[responseAddress]); asm.mov(edi, __dword_ptr[esi + 0x10]); asm.lea(eax, __dword_ptr[pdmcc]); asm.push(eax); asm.push(argAddrStringAddress); asm.push(__dword_ptr[commandPtr]); asm.call((uint)target.Signatures["FGetNamedDwParam"]); asm.test(eax, eax); asm.jz(errorLabel); asm.push(__dword_ptr[responseAddress]); asm.lea(eax, __dword_ptr[responseAddress]); asm.push(eax); asm.push(argLengthStringAddress); asm.push(__dword_ptr[commandPtr]); asm.call((uint)target.Signatures["FGetNamedDwParam"]); asm.test(eax, eax); asm.jz(errorLabel); asm.mov(eax, __dword_ptr[pdmcc]); // address asm.and(__dword_ptr[edi + 0x10], 0); asm.mov(__dword_ptr[edi + 0x14], eax); //asm.mov(eax, 0x2000); // TODO: increase pool size? //asm.push(eax); //asm.call((uint)target.Signatures["DmAllocatePool"]); // TODO: crashes in here, possible IRQ issues? asm.mov(__dword_ptr[esi + 0xC], getmem2BufferSize); // buffer size asm.mov(__dword_ptr[esi + 8], getmem2buffer); // buffer address asm.mov(eax, __dword_ptr[responseAddress]); asm.mov(__dword_ptr[esi + 0x14], eax); asm.mov(__dword_ptr[esi], getmem2CallbackAddress); asm.jmp(binaryResponseLabel); } #endregion #region Return Codes // if we're here, must be an unknown custom type asm.jmp(errorLabel); // generic success epilog asm.Label(ref successLabel); asm.popad(); asm.leave(); asm.mov(eax, 0x2DB0000); asm.ret(0x10); // successful binary response follows epilog asm.Label(ref binaryResponseLabel); asm.popad(); asm.leave(); asm.mov(eax, 0x2DB0003); asm.ret(0x10); // generic failure epilog asm.Label(ref errorLabel); asm.popad(); asm.leave(); asm.mov(eax, 0x82DB0000); asm.ret(0x10); // original epilog asm.Label(ref doneLabel); asm.popad(); asm.leave(); asm.ret(0x10); #endregion // inject RPC handler and hook uint caveAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address)); Log.Information("HrFuncCall address {0}", caveAddress.ToHexString()); asm.Hook(target, target.Signatures["HrFunctionCall"], caveAddress); #endregion } public string GetDisassembly(long address, int length, bool tabPrefix = true, bool showBytes = false) { // read code from xbox memory byte[] code = Memory.ReadBytes(address, length); // disassemble valid instructions var decoder = Iced.Intel.Decoder.Create(32, code); decoder.IP = (ulong)address; var instructions = new List<Instruction>(); while (decoder.IP < decoder.IP + (uint)code.Length) { var insn = decoder.Decode(); if (insn.IsInvalid) break; instructions.Add(insn); } // formatting options var formatter = new MasmFormatter(); formatter.Options.FirstOperandCharIndex = 8; formatter.Options.SpaceAfterOperandSeparator = true; // convert to string var output = new StringOutput(); var disassembly = new StringBuilder(); bool firstInstruction = true; foreach (var instr in instructions) { // skip newline for the first instruction if (firstInstruction) { firstInstruction = false; } else disassembly.AppendLine(); // optionally indent if (tabPrefix) { disassembly.Append('\t'); } // output address disassembly.Append(instr.IP.ToString("X8")); disassembly.Append(' '); // optionally output instruction bytes if (showBytes) { for (int i = 0; i < instr.Length; i++) disassembly.Append(code[(int)(instr.IP - (ulong)address) + i].ToString("X2")); int missingBytes = 10 - instr.Length; for (int i = 0; i < missingBytes; i++) disassembly.Append(" "); disassembly.Append(' '); } // output the decoded instruction formatter.Format(instr, output); disassembly.Append(output.ToStringAndReset()); } return disassembly.ToString(); } public Dictionary<string, long> Signatures { get { var signatures = _cache.Get<Dictionary<string, long>>(nameof(Signatures)); if (signatures == null) { var resolver = new SignatureResolver { // NOTE: ensure patterns don't overlap with any hooks! that way we don't have to cache any states; simplicity at the expense of slightly less perf on connect // universal pattern new SodmaSignature("ReadWriteOneSector") { // mov ebp, esp new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }), // mov dx, 1F6h new OdmPattern(0x3, new byte[] { 0x66, 0xBA, 0xF6, 0x01 }), // mov al, 0A0h new OdmPattern(0x7, new byte[] { 0xB0, 0xA0 }) }, // universal pattern new SodmaSignature("WriteSMBusByte") { // mov al, 20h new OdmPattern(0x3, new byte[] { 0xB0, 0x20 }), // mov dx, 0C004h new OdmPattern(0x5, new byte[] { 0x66, 0xBA, 0x04, 0xC0 }), }, // universal pattern new SodmaSignature("FGetDwParam") { // jz short 0x2C new OdmPattern(0x15, new byte[] { 0x74, 0x2C }), // push 20h new OdmPattern(0x17, new byte[] { 0x6A, 0x20 }), // mov [ecx], eax new OdmPattern(0x33, new byte[] { 0x89, 0x01 }) }, // universal pattern new SodmaSignature("FGetNamedDwParam") { // mov ebp, esp new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }), // jnz short 0x17 new OdmPattern(0x13, new byte[] { 0x75, 0x17 }), // retn 10h new OdmPattern(0x30, new byte[] { 0xC2, 0x10, 0x00 }) }, // universal pattern new SodmaSignature("DmSetupFunctionCall") { // test ax, 280h new OdmPattern(0x45, new byte[] { 0x66, 0xA9, 0x80, 0x02 }), // push 63666D64h new OdmPattern(0x54, new byte[] { 0x68, 0x64, 0x6D, 0x66, 0x63 }) }, // early revisions new SodmaSignature("HrFunctionCall") { // mov eax, 80004005h new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }), // mov ebx, 10008h new OdmPattern(0x46, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 }) }, // later revisions new SodmaSignature("HrFunctionCall") { // mov eax, 80004005h new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }), // mov ebx, 10008h new OdmPattern(0x45, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 }) }, // xbdm 3424+ contains this (3223 does not, who knows what inbetween does) whereas some early kernel versions do not? or have different kernel export tables for alpha/dvt3/dvt4/dvt6 etc. new SodmaSignature("sprintf") { // mov esi, [ebp+arg_0] new OdmPattern(0x7, new byte[] { 0x8B, 0x75, 0x08 }), // mov [ebp+var_1C], 7FFFFFFFh new OdmPattern(0x16, new byte[] { 0xC7, 0x45, 0xE4, 0xFF, 0xFF, 0xFF, 0x7F }) }, // early revisions new SodmaSignature("DmAllocatePool") { // push ebp new OdmPattern(0x0, new byte[] { 0x55 }), // mov ebp, esp new OdmPattern(0x0, new byte[] { 0x8B, 0xEC }), // push 'enoN' new OdmPattern(0x3, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }) }, // later revisions new SodmaSignature("DmAllocatePool") { // push 'enoN' new OdmPattern(0x0, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }), // retn 4 new OdmPattern(0xE, new byte[] { 0xC2, 0x04, 0x00 }) }, // universal pattern new SodmaSignature("DmFreePool") { // cmp eax, 0B0000000h new OdmPattern(0xF, new byte[] { 0x3D, 0x00, 0x00, 0x00, 0xB0 }) } }; // read xbdm .text section var xbdmTextSegment = GetModules().FirstOrDefault(m => m.Name.Equals("xbdm.dll")).GetSection(".text"); byte[] data = new byte[xbdmTextSegment.Size]; ReadMemory(xbdmTextSegment.Base, data); // scan for signatures signatures = resolver.Resolve(data, xbdmTextSegment.Base); // cache the result indefinitely _cache.Set(nameof(Signatures), signatures); } return signatures; } } #endregion #region File public char[] GetDrives() { return Session.SendCommandStrict("drivelist").Message.ToCharArray(); } public List<XboxFileInformation> GetDirectoryList(string path) { var list = new List<XboxFileInformation>(); Session.SendCommandStrict("dirlist name=\"{0}\"", path); foreach (string file in Session.ReceiveMultilineResponse()) { var fileInfo = file.ParseXboxResponseLine(); var info = new XboxFileInformation(); info.FullName = Path.Combine(path, (string)fileInfo["name"]); info.Size = ((long)fileInfo["sizehi"] << 32) | (long)fileInfo["sizelo"]; info.CreationTime = DateTime.FromFileTimeUtc(((long)fileInfo["createhi"] << 32) | (long)fileInfo["createlo"]); info.ChangeTime = DateTime.FromFileTimeUtc(((long)fileInfo["changehi"] << 32) | (long)fileInfo["changelo"]); info.Attributes |= file.Contains("directory") ? FileAttributes.Directory : FileAttributes.Normal; info.Attributes |= file.Contains("readonly") ? FileAttributes.ReadOnly : 0; info.Attributes |= file.Contains("hidden") ? FileAttributes.Hidden : 0; list.Add(info); } return list; } public void GetFile(string localPath, string remotePath) { Session.SendCommandStrict("getfile name=\"{0}\"", remotePath); using var lfs = File.Create(localPath); Session.CopyToCount(lfs, Session.Reader.ReadInt32()); } #endregion #region IDisposable protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { // TODO: dispose managed state (managed objects) } // TODO: free unmanaged resources (unmanaged objects) and override finalizer Session?.Dispose(); // TODO: set large fields to null _disposed = true; } } ~Xbox() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
src/OGXbdmDumper/Xbox.cs
Ernegien-OGXbdmDumper-07a1e82
[ { "filename": "src/OGXbdmDumper/Connection.cs", "retrieved_chunk": " /// <summary>\n /// The time in milliseconds to wait while sending data before throwing a TimeoutException.\n /// </summary>\n public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n /// <summary>\n /// The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n /// </summary>\n public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n #endregion\n #region Construction", "score": 0.9375977516174316 }, { "filename": "src/OGXbdmDumper/Connection.cs", "retrieved_chunk": " /// </summary>\n public BinaryReader Reader { get; private set; }\n /// <summary>\n /// The binary writer for the session stream.\n /// </summary>\n public BinaryWriter Writer { get; private set; }\n /// <summary>\n /// Returns true if the session thinks it's connected based on the most recent operation.\n /// </summary>\n public bool IsConnected => _client.Connected;", "score": 0.9030228853225708 }, { "filename": "src/OGXbdmDumper/Connection.cs", "retrieved_chunk": " #endregion\n #region Methods\n /// <summary>\n /// Resets the internal TCP client state.\n /// </summary>\n private void ResetTcp()\n {\n // preserve previous settings or specify new defaults\n int sendTimeout = _client?.SendTimeout ?? 10000;\n int receiveTimeout = _client?.ReceiveTimeout ?? 10000;", "score": 0.8839331269264221 }, { "filename": "src/OGXbdmDumper/XboxMemoryStream.cs", "retrieved_chunk": " /// </summary>\n public override bool CanWrite => true;\n /// <summary>\n /// TODO: description\n /// </summary>\n public override bool CanTimeout => true;\n /// <summary>\n /// TODO: description\n /// </summary>\n public override int ReadTimeout => _xbox.ReceiveTimeout;", "score": 0.8784859776496887 }, { "filename": "src/OGXbdmDumper/ConnectionInfo.cs", "retrieved_chunk": " public IPEndPoint Endpoint { get; set; }\n public string? Name { get; set; }\n public ConnectionInfo(IPEndPoint endpoint, string? name = null)\n {\n Endpoint = endpoint;\n Name = name;\n }\n public static List<ConnectionInfo> DiscoverXbdm(int port, int timeout = 500)\n {\n Log.Information(\"Performing Xbox debug monitor network discovery broadcast on UDP port {Port}.\", port);", "score": 0.8736122846603394 } ]
csharp
Connection Session {
using Microsoft.EntityFrameworkCore; using System.Collections.Generic; namespace Ryan.EntityFrameworkCore.Proxy { /// <summary> /// 上下文实体代理 /// </summary> public class DbContextEntityProxy { /// <summary> /// 上下文 /// </summary> public DbContext Context { get; } /// <summary> /// 实体代理 /// </summary> public List<
EntityProxy> EntityProxies {
get; } /// <summary> /// 创建上下文实体代理 /// </summary> public DbContextEntityProxy(DbContext context) { Context = context; EntityProxies = new List<EntityProxy>(); } } }
src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Proxy/DbContextEntityProxy.cs
c-y-r-Ryan.EntityFrameworkCore.Shard-f15124c
[ { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Proxy/EntityProxy.cs", "retrieved_chunk": " /// <summary>\n /// 上下文\n /// </summary>\n public DbContext DbContext { get; }\n /// <summary>\n /// 创建实体代理\n /// </summary>\n public EntityProxy(object entity, object implementation, EntityProxyType type, DbContext dbContext)\n {\n Entity = entity;", "score": 0.9460949897766113 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityModelBuilderGenerator.cs", "retrieved_chunk": " {\n /// <summary>\n /// 容器\n /// </summary>\n public IServiceProvider ServiceProvider { get; }\n /// <summary>\n /// 内存缓存\n /// </summary>\n public IMemoryCache MemoryCache { get; }\n /// <summary>", "score": 0.9176434874534607 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityModelBuilderAccessor.cs", "retrieved_chunk": " /// <summary>\n /// 实体类型\n /// </summary>\n public Type EntityType { get; }\n /// <summary>\n /// 实体实现字典\n /// </summary>\n public EntityImplementationDictionary Dictionary { get; }\n /// <summary>\n /// 实体模型构建", "score": 0.9168215394020081 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Proxy/EntityProxy.cs", "retrieved_chunk": " /// </summary>\n public object Entity { get; }\n /// <summary>\n /// 实现\n /// </summary>\n public object Implementation { get; }\n /// <summary>\n /// 代理类型\n /// </summary>\n public EntityProxyType Type { get; }", "score": 0.9118214845657349 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/ShardDbContext.cs", "retrieved_chunk": " /// 分表实体\n /// </summary>\n private List<Type> ShardEntityTypes { get; set; } = new List<Type>();\n /// <summary>\n /// 分表依赖\n /// </summary>\n public IShardDependency Dependencies { get; }\n /// <summary>\n /// 创建分表上下文\n /// </summary>", "score": 0.9071975350379944 } ]
csharp
EntityProxy> EntityProxies {
using BepInEx; using UnityEngine; using UnityEngine.SceneManagement; using System; using HarmonyLib; using System.IO; using Ultrapain.Patches; using System.Linq; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Reflection; using Steamworks; using Unity.Audio; using System.Text; using System.Collections.Generic; using UnityEngine.AddressableAssets; using UnityEngine.AddressableAssets.ResourceLocators; using UnityEngine.ResourceManagement.ResourceLocations; using UnityEngine.UIElements; using PluginConfig.API; namespace Ultrapain { [BepInPlugin(PLUGIN_GUID, PLUGIN_NAME, PLUGIN_VERSION)] [BepInDependency("com.eternalUnion.pluginConfigurator", "1.6.0")] public class Plugin : BaseUnityPlugin { public const string PLUGIN_GUID = "com.eternalUnion.ultraPain"; public const string PLUGIN_NAME = "Ultra Pain"; public const string PLUGIN_VERSION = "1.1.0"; public static Plugin instance; private static bool addressableInit = false; public static T LoadObject<T>(string path) { if (!addressableInit) { Addressables.InitializeAsync().WaitForCompletion(); addressableInit = true; } return Addressables.LoadAssetAsync<T>(path).WaitForCompletion(); } public static Vector3 PredictPlayerPosition(Collider safeCollider, float speedMod) { Transform target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f) return target.position; RaycastHit raycastHit; if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == safeCollider) return target.position; else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { return raycastHit.point; } else { Vector3 projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod; return new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z); } } public static GameObject projectileSpread; public static GameObject homingProjectile; public static GameObject hideousMassProjectile; public static GameObject decorativeProjectile2; public static GameObject shotgunGrenade; public static GameObject beam; public static GameObject turretBeam; public static GameObject lightningStrikeExplosiveSetup; public static GameObject lightningStrikeExplosive; public static GameObject lighningStrikeWindup; public static GameObject explosion; public static GameObject bigExplosion; public static GameObject sandExplosion; public static GameObject virtueInsignia; public static GameObject rocket; public static GameObject revolverBullet; public static GameObject maliciousCannonBeam; public static GameObject lightningBoltSFX; public static GameObject revolverBeam; public static GameObject blastwave; public static GameObject cannonBall; public static
GameObject shockwave;
public static GameObject sisyphiusExplosion; public static GameObject sisyphiusPrimeExplosion; public static GameObject explosionWaveKnuckleblaster; public static GameObject chargeEffect; public static GameObject maliciousFaceProjectile; public static GameObject hideousMassSpear; public static GameObject coin; public static GameObject sisyphusDestroyExplosion; //public static GameObject idol; public static GameObject ferryman; public static GameObject minosPrime; //public static GameObject maliciousFace; public static GameObject somethingWicked; public static Turret turret; public static GameObject turretFinalFlash; public static GameObject enrageEffect; public static GameObject v2flashUnparryable; public static GameObject ricochetSfx; public static GameObject parryableFlash; public static AudioClip cannonBallChargeAudio; public static Material gabrielFakeMat; public static Sprite blueRevolverSprite; public static Sprite greenRevolverSprite; public static Sprite redRevolverSprite; public static Sprite blueShotgunSprite; public static Sprite greenShotgunSprite; public static Sprite blueNailgunSprite; public static Sprite greenNailgunSprite; public static Sprite blueSawLauncherSprite; public static Sprite greenSawLauncherSprite; public static GameObject rocketLauncherAlt; public static GameObject maliciousRailcannon; // Variables public static float SoliderShootAnimationStart = 1.2f; public static float SoliderGrenadeForce = 10000f; public static float SwordsMachineKnockdownTimeNormalized = 0.8f; public static float SwordsMachineCoreSpeed = 80f; public static float MinGrenadeParryVelocity = 40f; public static GameObject _lighningBoltSFX; public static GameObject lighningBoltSFX { get { if (_lighningBoltSFX == null) _lighningBoltSFX = ferryman.gameObject.transform.Find("LightningBoltChimes").gameObject; return _lighningBoltSFX; } } private static bool loadedPrefabs = false; public void LoadPrefabs() { if (loadedPrefabs) return; loadedPrefabs = true; // Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab projectileSpread = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab homingProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab decorativeProjectile2 = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab"); // Assets/Prefabs/Attacks and Projectiles/Grenade.prefab shotgunGrenade = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Grenade.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab turretBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab beam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab lightningStrikeExplosiveSetup = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab"); // Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab lighningStrikeWindup = LoadObject<GameObject>("Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab"); //[bundle-0][assets/prefabs/enemies/idol.prefab] //idol = LoadObject<GameObject>("assets/prefabs/enemies/idol.prefab"); // Assets/Prefabs/Enemies/Ferryman.prefab ferryman = LoadObject<GameObject>("Assets/Prefabs/Enemies/Ferryman.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab explosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab bigExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab sandExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab"); // Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab virtueInsignia = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab hideousMassProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab"); // Assets/Particles/Enemies/RageEffect.prefab enrageEffect = LoadObject<GameObject>("Assets/Particles/Enemies/RageEffect.prefab"); // Assets/Particles/Flashes/V2FlashUnparriable.prefab v2flashUnparryable = LoadObject<GameObject>("Assets/Particles/Flashes/V2FlashUnparriable.prefab"); // Assets/Prefabs/Attacks and Projectiles/Rocket.prefab rocket = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Rocket.prefab"); // Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab revolverBullet = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab maliciousCannonBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab revolverBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab blastwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab"); // Assets/Prefabs/Enemies/MinosPrime.prefab minosPrime = LoadObject<GameObject>("Assets/Prefabs/Enemies/MinosPrime.prefab"); // Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab cannonBall = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab"); // get from Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab cannonBallChargeAudio = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab").transform.Find("RocketLauncher/Armature/Body_Bone/HologramDisplay").GetComponent<AudioSource>().clip; // Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab shockwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab sisyphiusExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab sisyphiusPrimeExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab explosionWaveKnuckleblaster = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab - [bundle-0][assets/prefabs/explosionlightning variant.prefab] lightningStrikeExplosive = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab"); // Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab rocketLauncherAlt = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab"); // Assets/Prefabs/Weapons/Railcannon Malicious.prefab maliciousRailcannon = LoadObject<GameObject>("Assets/Prefabs/Weapons/Railcannon Malicious.prefab"); //Assets/Particles/SoundBubbles/Ricochet.prefab ricochetSfx = LoadObject<GameObject>("Assets/Particles/SoundBubbles/Ricochet.prefab"); //Assets/Particles/Flashes/Flash.prefab parryableFlash = LoadObject<GameObject>("Assets/Particles/Flashes/Flash.prefab"); //Assets/Prefabs/Attacks and Projectiles/Spear.prefab hideousMassSpear = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Spear.prefab"); //Assets/Prefabs/Enemies/Wicked.prefab somethingWicked = LoadObject<GameObject>("Assets/Prefabs/Enemies/Wicked.prefab"); //Assets/Textures/UI/SingleRevolver.png blueRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/SingleRevolver.png"); //Assets/Textures/UI/RevolverSpecial.png greenRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSpecial.png"); //Assets/Textures/UI/RevolverSharp.png redRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSharp.png"); //Assets/Textures/UI/Shotgun.png blueShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun.png"); //Assets/Textures/UI/Shotgun1.png greenShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun1.png"); //Assets/Textures/UI/Nailgun2.png blueNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Nailgun2.png"); //Assets/Textures/UI/NailgunOverheat.png greenNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/NailgunOverheat.png"); //Assets/Textures/UI/SawbladeLauncher.png blueSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncher.png"); //Assets/Textures/UI/SawbladeLauncherOverheat.png greenSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncherOverheat.png"); //Assets/Prefabs/Attacks and Projectiles/Coin.prefab coin = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Coin.prefab"); //Assets/Materials/GabrielFake.mat gabrielFakeMat = LoadObject<Material>("Assets/Materials/GabrielFake.mat"); //Assets/Prefabs/Enemies/Turret.prefab turret = LoadObject<GameObject>("Assets/Prefabs/Enemies/Turret.prefab").GetComponent<Turret>(); //Assets/Particles/Flashes/GunFlashDistant.prefab turretFinalFlash = LoadObject<GameObject>("Assets/Particles/Flashes/GunFlashDistant.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab sisyphusDestroyExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab"); //Assets/Prefabs/Effects/Charge Effect.prefab chargeEffect = LoadObject<GameObject>("Assets/Prefabs/Effects/Charge Effect.prefab"); //Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab maliciousFaceProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab"); } public static bool ultrapainDifficulty = false; public static bool realUltrapainDifficulty = false; public static GameObject currentDifficultyButton; public static GameObject currentDifficultyPanel; public static Text currentDifficultyInfoText; public void OnSceneChange(Scene before, Scene after) { StyleIDs.RegisterIDs(); ScenePatchCheck(); string mainMenuSceneName = "b3e7f2f8052488a45b35549efb98d902"; string bootSequenceSceneName = "4f8ecffaa98c2614f89922daf31fa22d"; string currentSceneName = SceneManager.GetActiveScene().name; if (currentSceneName == mainMenuSceneName) { LoadPrefabs(); //Canvas/Difficulty Select (1)/Violent Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Difficulty Select (1)"); GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect); currentDifficultyButton = ultrapainButton; ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value; ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5; RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>(); ultrapainTrans.anchoredPosition = new Vector2(20f, -104f); //Canvas/Difficulty Select (1)/Violent Info GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect); currentDifficultyPanel = info; currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>(); currentDifficultyInfoText.text = ConfigManager.pluginInfo.value; Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>(); currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--"; currentDifficultyHeaderText.resizeTextForBestFit = true; currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap; currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate; info.SetActive(false); EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>(); evt.triggers.Clear(); /*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(false));*/ EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit }; trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false)); evt.triggers.Add(trigger1); evt.triggers.Add(trigger2); foreach(EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>()) { if (trigger.gameObject == ultrapainButton) continue; EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false)); trigger.triggers.Add(closeTrigger); } } else if(currentSceneName == bootSequenceSceneName) { LoadPrefabs(); //Canvas/Difficulty Select (1)/Violent Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Intro/Difficulty Select"); GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect); currentDifficultyButton = ultrapainButton; ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value; ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5; RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>(); ultrapainTrans.anchoredPosition = new Vector2(20f, -104f); //Canvas/Difficulty Select (1)/Violent Info GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect); currentDifficultyPanel = info; currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>(); currentDifficultyInfoText.text = ConfigManager.pluginInfo.value; Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>(); currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--"; currentDifficultyHeaderText.resizeTextForBestFit = true; currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap; currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate; info.SetActive(false); EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>(); evt.triggers.Clear(); /*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(false));*/ EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit }; trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false)); evt.triggers.Add(trigger1); evt.triggers.Add(trigger2); foreach (EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>()) { if (trigger.gameObject == ultrapainButton) continue; EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false)); trigger.triggers.Add(closeTrigger); } } // LOAD CUSTOM PREFABS HERE TO AVOID MID GAME LAG MinosPrimeCharge.CreateDecoy(); GameObject shockwaveSisyphus = SisyphusInstructionist_Start.shockwave; } public static class StyleIDs { private static bool registered = false; public static void RegisterIDs() { registered = false; if (MonoSingleton<StyleHUD>.Instance == null) return; MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.grenadeBoostStyleText.guid, ConfigManager.grenadeBoostStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.rocketBoostStyleText.guid, ConfigManager.rocketBoostStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverStyleText.guid, ConfigManager.orbStrikeRevolverStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverChargedStyleText.guid, ConfigManager.orbStrikeRevolverChargedStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeElectricCannonStyleText.guid, ConfigManager.orbStrikeElectricCannonStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeMaliciousCannonStyleText.guid, ConfigManager.orbStrikeMaliciousCannonStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.maliciousChargebackStyleText.guid, ConfigManager.maliciousChargebackStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.sentryChargebackStyleText.guid, ConfigManager.sentryChargebackStyleText.formattedString); registered = true; Debug.Log("Registered all style ids"); } private static FieldInfo idNameDict = typeof(StyleHUD).GetField("idNameDict", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); public static void UpdateID(string id, string newName) { if (!registered || StyleHUD.Instance == null) return; (idNameDict.GetValue(StyleHUD.Instance) as Dictionary<string, string>)[id] = newName; } } public static Harmony harmonyTweaks; public static Harmony harmonyBase; private static MethodInfo GetMethod<T>(string name) { return typeof(T).GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } private static Dictionary<MethodInfo, HarmonyMethod> methodCache = new Dictionary<MethodInfo, HarmonyMethod>(); private static HarmonyMethod GetHarmonyMethod(MethodInfo method) { if (methodCache.TryGetValue(method, out HarmonyMethod harmonyMethod)) return harmonyMethod; else { harmonyMethod = new HarmonyMethod(method); methodCache.Add(method, harmonyMethod); return harmonyMethod; } } private static void PatchAllEnemies() { if (!ConfigManager.enemyTweakToggle.value) return; if (ConfigManager.friendlyFireDamageOverrideToggle.value) { harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<PhysicalShockwave>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<VirtueInsignia>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_FF>("Prefix"))); harmonyTweaks.Patch(GetMethod<Flammable>("Burn"), prefix: GetHarmonyMethod(GetMethod<Flammable_Burn_FF>("Prefix"))); harmonyTweaks.Patch(GetMethod<FireZone>("OnTriggerStay"), prefix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Postfix"))); } harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("UpdateModifiers"), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_UpdateModifiers>("Postfix"))); harmonyTweaks.Patch(GetMethod<StatueBoss>("Start"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Start_Patch>("Postfix"))); if (ConfigManager.cerberusDashToggle.value) harmonyTweaks.Patch(GetMethod<StatueBoss>("StopDash"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopDash_Patch>("Postfix"))); if(ConfigManager.cerberusParryable.value) { harmonyTweaks.Patch(GetMethod<StatueBoss>("StopTracking"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopTracking_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<StatueBoss>("Stomp"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Stomp_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Statue>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Statue_GetHurt_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Drone_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Drone>("Shoot"), prefix: GetHarmonyMethod(GetMethod<Drone_Shoot_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("PlaySound"), prefix: GetHarmonyMethod(GetMethod<Drone_PlaySound_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Update"), postfix: GetHarmonyMethod(GetMethod<Drone_Update>("Postfix"))); if(ConfigManager.droneHomeToggle.value) { harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Drone_Death_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Drone_GetHurt_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Ferryman>("Start"), postfix: GetHarmonyMethod(GetMethod<FerrymanStart>("Postfix"))); if(ConfigManager.ferrymanComboToggle.value) harmonyTweaks.Patch(GetMethod<Ferryman>("StopMoving"), postfix: GetHarmonyMethod(GetMethod<FerrymanStopMoving>("Postfix"))); if(ConfigManager.filthExplodeToggle.value) harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch2>("Prefix"))); if(ConfigManager.fleshPrisonSpinAttackToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<FleshPrisonShoot>("Postfix"))); if (ConfigManager.hideousMassInsigniaToggle.value) { harmonyTweaks.Patch(GetMethod<Projectile>("Explode"), postfix: GetHarmonyMethod(GetMethod<Projectile_Explode_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Mass>("ShootExplosive"), postfix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Postfix")), prefix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Prefix"))); } harmonyTweaks.Patch(GetMethod<SpiderBody>("Start"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<SpiderBody>("ChargeBeam"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ChargeBeam>("Postfix"))); harmonyTweaks.Patch(GetMethod<SpiderBody>("BeamChargeEnd"), prefix: GetHarmonyMethod(GetMethod<MaliciousFace_BeamChargeEnd>("Prefix"))); if (ConfigManager.maliciousFaceHomingProjectileToggle.value) { harmonyTweaks.Patch(GetMethod<SpiderBody>("ShootProj"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ShootProj_Patch>("Postfix"))); } if (ConfigManager.maliciousFaceRadianceOnEnrage.value) harmonyTweaks.Patch(GetMethod<SpiderBody>("Enrage"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Enrage_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Mindflayer>("Start"), postfix: GetHarmonyMethod(GetMethod<Mindflayer_Start_Patch>("Postfix"))); if (ConfigManager.mindflayerShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<Mindflayer>("ShootProjectiles"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_ShootProjectiles_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_MF>("Prefix"))); } if (ConfigManager.mindflayerTeleportComboToggle.value) { harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Mindflayer>("MeleeTeleport"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_MeleeTeleport_Patch>("Prefix"))); //harmonyTweaks.Patch(GetMethod<SwingCheck2>("DamageStop"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_DamageStop_Patch>("Postfix"))); } if (ConfigManager.minosPrimeRandomTeleportToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("Postfix"))); if (ConfigManager.minosPrimeTeleportTrail.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("Teleport"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("TeleportPostfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Start"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Dropkick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Dropkick>("Prefix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Combo"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Combo>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("StopAction"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_StopAction>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Ascend"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Ascend>("Prefix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Death"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Death>("Prefix"))); if (ConfigManager.minosPrimeCrushAttackToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("RiderKick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_RiderKick>("Prefix"))); if (ConfigManager.minosPrimeComboExplosiveEndToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_ProjectileCharge>("Prefix"))); if (ConfigManager.schismSpreadAttackToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ShootProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ShootProjectile_Patch>("Postfix"))); if (ConfigManager.soliderShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<Solider_Start_Patch>("Postfix"))); } if(ConfigManager.soliderCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_SpawnProjectile_Patch>("Postfix"))); if (ConfigManager.soliderShootGrenadeToggle.value || ConfigManager.soliderShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_ThrowProjectile_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Stalker>("SandExplode"), prefix: GetHarmonyMethod(GetMethod<Stalker_SandExplode_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SandificationZone>("Enter"), postfix: GetHarmonyMethod(GetMethod<SandificationZone_Enter_Patch>("Postfix"))); if (ConfigManager.strayCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Swing>("Postfix"))); if (ConfigManager.strayShootToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_Start_Patch1>("Postfix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ThrowProjectile_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<SwingEnd>("Prefix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("DamageEnd"), prefix: GetHarmonyMethod(GetMethod<DamageEnd>("Prefix"))); } if(ConfigManager.streetCleanerCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<Streetcleaner>("Start"), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Start_Patch>("Postfix"))); if(ConfigManager.streetCleanerPredictiveDodgeToggle.value) harmonyTweaks.Patch(GetMethod<BulletCheck>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<BulletCheck_OnTriggerEnter_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("Start"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Start>("Postfix"))); if (ConfigManager.swordsMachineNoLightKnockbackToggle.value || ConfigManager.swordsMachineSecondPhaseMode.value != ConfigManager.SwordsMachineSecondPhase.None) { harmonyTweaks.Patch(GetMethod<SwordsMachine>("Knockdown"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Knockdown_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("Down"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Prefix"))); //harmonyTweaks.Patch(GetMethod<SwordsMachine>("SetSpeed"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_SetSpeed_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("EndFirstPhase"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Prefix"))); } if (ConfigManager.swordsMachineExplosiveSwordToggle.value) { harmonyTweaks.Patch(GetMethod<ThrownSword>("Start"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<ThrownSword>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_OnTriggerEnter_Patch>("Postfix"))); } harmonyTweaks.Patch(GetMethod<Turret>("Start"), postfix: GetHarmonyMethod(GetMethod<TurretStart>("Postfix"))); if(ConfigManager.turretBurstFireToggle.value) { harmonyTweaks.Patch(GetMethod<Turret>("Shoot"), prefix: GetHarmonyMethod(GetMethod<TurretShoot>("Prefix"))); harmonyTweaks.Patch(GetMethod<Turret>("StartAiming"), postfix: GetHarmonyMethod(GetMethod<TurretAim>("Postfix"))); } harmonyTweaks.Patch(GetMethod<Explosion>("Start"), postfix: GetHarmonyMethod(GetMethod<V2CommonExplosion>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2FirstStart>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2FirstUpdate>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2FirstShootWeapon>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2SecondStart>("Postfix"))); //if(ConfigManager.v2SecondStartEnraged.value) // harmonyTweaks.Patch(GetMethod<BossHealthBar>("OnEnable"), postfix: GetHarmonyMethod(GetMethod<V2SecondEnrage>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2SecondUpdate>("Prefix"))); //harmonyTweaks.Patch(GetMethod<V2>("AltShootWeapon"), postfix: GetHarmonyMethod(GetMethod<V2AltShootWeapon>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("SwitchWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondSwitchWeapon>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Prefix")), postfix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Postfix"))); if(ConfigManager.v2SecondFastCoinToggle.value) harmonyTweaks.Patch(GetMethod<V2>("ThrowCoins"), prefix: GetHarmonyMethod(GetMethod<V2SecondFastCoin>("Prefix"))); harmonyTweaks.Patch(GetMethod<Cannonball>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<V2RocketLauncher>("CannonBallTriggerPrefix"))); if (ConfigManager.v2FirstSharpshooterToggle.value || ConfigManager.v2SecondSharpshooterToggle.value) { harmonyTweaks.Patch(GetMethod<EnemyRevolver>("PrepareAltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverPrepareAltFire>("Prefix"))); harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverBullet>("Prefix"))); harmonyTweaks.Patch(GetMethod<EnemyRevolver>("AltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverAltShoot>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Virtue_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Drone>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Virtue_SpawnInsignia_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Virtue_Death_Patch>("Prefix"))); if (ConfigManager.sisyInstJumpShockwave.value) { harmonyTweaks.Patch(GetMethod<Sisyphus>("Start"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Sisyphus>("Update"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Update>("Postfix"))); } if(ConfigManager.sisyInstBoulderShockwave.value) harmonyTweaks.Patch(GetMethod<Sisyphus>("SetupExplosion"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_SetupExplosion>("Postfix"))); if(ConfigManager.sisyInstStrongerExplosion.value) harmonyTweaks.Patch(GetMethod<Sisyphus>("StompExplosion"), prefix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_StompExplosion>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("Awake"), postfix: GetHarmonyMethod(GetMethod<LeviathanTail_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("BigSplash"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_BigSplash>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_SwingEnd>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("Start"), postfix: GetHarmonyMethod(GetMethod<Leviathan_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurst"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurstStart"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurstStart>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<Leviathan_FixedUpdate>("Prefix"))); if (ConfigManager.somethingWickedSpear.value) { harmonyTweaks.Patch(GetMethod<Wicked>("Start"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_GetHit>("Postfix"))); } if(ConfigManager.somethingWickedSpawnOn43.value) { harmonyTweaks.Patch(GetMethod<ObjectActivator>("Activate"), prefix: GetHarmonyMethod(GetMethod<ObjectActivator_Activate>("Prefix"))); harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<JokeWicked_GetHit>("Postfix"))); } if (ConfigManager.panopticonFullPhase.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Panopticon_Start>("Postfix"))); if (ConfigManager.panopticonAxisBeam.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnInsignia>("Prefix"))); if (ConfigManager.panopticonSpinAttackToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<Panopticon_HomingProjectileAttack>("Postfix"))); if (ConfigManager.panopticonBlackholeProj.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnBlackHole"), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnBlackHole>("Postfix"))); if (ConfigManager.panopticonBalanceEyes.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnFleshDrones"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Postfix"))); if (ConfigManager.panopticonBlueProjToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Update"), transpiler: GetHarmonyMethod(GetMethod<Panopticon_BlueProjectile>("Transpiler"))); if (ConfigManager.idolExplosionToggle.value) harmonyTweaks.Patch(GetMethod<Idol>("Death"), postfix: GetHarmonyMethod(GetMethod<Idol_Death_Patch>("Postfix"))); // ADDME /* harmonyTweaks.Patch(GetMethod<GabrielSecond>("Start"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("BasicCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_BasicCombo>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("FastCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_FastCombo>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("CombineSwords"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_CombineSwords>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("ThrowCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_ThrowCombo>("Postfix"))); */ } private static void PatchAllPlayers() { if (!ConfigManager.playerTweakToggle.value) return; harmonyTweaks.Patch(GetMethod<Punch>("CheckForProjectile"), prefix: GetHarmonyMethod(GetMethod<Punch_CheckForProjectile_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch1>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Collision"), prefix: GetHarmonyMethod(GetMethod<Grenade_Collision_Patch>("Prefix"))); if (ConfigManager.rocketBoostToggle.value) harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_Patch>("Prefix"))); if (ConfigManager.rocketGrabbingToggle.value) harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate_Patch>("Prefix"))); if (ConfigManager.orbStrikeToggle.value) { harmonyTweaks.Patch(GetMethod<Coin>("Start"), postfix: GetHarmonyMethod(GetMethod<Coin_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Punch>("BlastCheck"), prefix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Postfix"))); harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide>("Prefix"))); harmonyTweaks.Patch(GetMethod<Coin>("DelayedReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_DelayedReflectRevolver>("Postfix"))); harmonyTweaks.Patch(GetMethod<Coin>("ReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Postfix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Prefix")), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Postfix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("ExecuteHits"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Prefix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("HitSomething"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Prefix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("Start"), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_Start>("Prefix"))); harmonyTweaks.Patch(GetMethod<Cannonball>("Explode"), prefix: GetHarmonyMethod(GetMethod<Cannonball_Explode>("Prefix"))); harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_CollideOrbital>("Prefix"))); } if(ConfigManager.chargedRevRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<Revolver>("Update"), prefix: GetHarmonyMethod(GetMethod<Revolver_Update>("Prefix"))); if(ConfigManager.coinRegSpeedMulti.value != 1 || ConfigManager.sharpshooterRegSpeedMulti.value != 1 || ConfigManager.railcannonRegSpeedMulti.value != 1 || ConfigManager.rocketFreezeRegSpeedMulti.value != 1 || ConfigManager.rocketCannonballRegSpeedMulti.value != 1 || ConfigManager.nailgunAmmoRegSpeedMulti.value != 1 || ConfigManager.sawAmmoRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<WeaponCharges>("Charge"), prefix: GetHarmonyMethod(GetMethod<WeaponCharges_Charge>("Prefix"))); if(ConfigManager.nailgunHeatsinkRegSpeedMulti.value != 1 || ConfigManager.sawHeatsinkRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<Nailgun>("Update"), prefix: GetHarmonyMethod(GetMethod<NailGun_Update>("Prefix"))); if(ConfigManager.staminaRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<NewMovement>("Update"), prefix: GetHarmonyMethod(GetMethod<NewMovement_Update>("Prefix"))); if(ConfigManager.playerHpDeltaToggle.value || ConfigManager.maxPlayerHp.value != 100 || ConfigManager.playerHpSupercharge.value != 200 || ConfigManager.whiplashHardDamageCap.value != 50 || ConfigManager.whiplashHardDamageSpeed.value != 1) { harmonyTweaks.Patch(GetMethod<NewMovement>("GetHealth"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHealth>("Prefix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("SuperCharge"), prefix: GetHarmonyMethod(GetMethod<NewMovement_SuperCharge>("Prefix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("Respawn"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Respawn>("Postfix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("Start"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Transpiler"))); harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), transpiler: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate>("Transpiler"))); harmonyTweaks.Patch(GetMethod<NewMovement>("ForceAntiHP"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_ForceAntiHP>("Transpiler"))); } // ADDME harmonyTweaks.Patch(GetMethod<Revolver>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Revolver_Shoot>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Shotgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Transpiler")), prefix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Postfix"))); harmonyTweaks.Patch(GetMethod<Shotgun>("ShootSinks"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_ShootSinks>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Nailgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_Shoot>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Nailgun>("SuperSaw"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_SuperSaw>("Transpiler"))); if (ConfigManager.hardDamagePercent.normalizedValue != 1) harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Prefix")), postfix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Postfix"))); harmonyTweaks.Patch(GetMethod<HealthBar>("Start"), postfix: GetHarmonyMethod(GetMethod<HealthBar_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<HealthBar>("Update"), transpiler: GetHarmonyMethod(GetMethod<HealthBar_Update>("Transpiler"))); foreach (HealthBarTracker hb in HealthBarTracker.instances) { if (hb != null) hb.SetSliderRange(); } harmonyTweaks.Patch(GetMethod<Harpoon>("Start"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Start>("Postfix"))); if(ConfigManager.screwDriverHomeToggle.value) harmonyTweaks.Patch(GetMethod<Harpoon>("Punched"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Punched>("Postfix"))); if(ConfigManager.screwDriverSplitToggle.value) harmonyTweaks.Patch(GetMethod<Harpoon>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<Harpoon_OnTriggerEnter_Patch>("Prefix"))); } private static void PatchAllMemes() { if (ConfigManager.enrageSfxToggle.value) harmonyTweaks.Patch(GetMethod<EnrageEffect>("Start"), postfix: GetHarmonyMethod(GetMethod<EnrageEffect_Start>("Postfix"))); if(ConfigManager.funnyDruidKnightSFXToggle.value) { harmonyTweaks.Patch(GetMethod<Mandalore>("FullBurst"), postfix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Postfix")), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<Mandalore>("FullerBurst"), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullerBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Explode"), prefix: GetHarmonyMethod(GetMethod<Drone_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Drone_Explode>("Postfix"))); } if (ConfigManager.fleshObamiumToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Prefix"))); if (ConfigManager.obamapticonToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Prefix"))); } public static bool methodsPatched = false; public static void ScenePatchCheck() { if(methodsPatched && !ultrapainDifficulty) { harmonyTweaks.UnpatchSelf(); methodsPatched = false; } else if(!methodsPatched && ultrapainDifficulty) { PatchAll(); } } public static void PatchAll() { harmonyTweaks.UnpatchSelf(); methodsPatched = false; if (!ultrapainDifficulty) return; if(realUltrapainDifficulty && ConfigManager.discordRichPresenceToggle.value) harmonyTweaks.Patch(GetMethod<DiscordController>("SendActivity"), prefix: GetHarmonyMethod(GetMethod<DiscordController_SendActivity_Patch>("Prefix"))); if (realUltrapainDifficulty && ConfigManager.steamRichPresenceToggle.value) harmonyTweaks.Patch(GetMethod<SteamFriends>("SetRichPresence"), prefix: GetHarmonyMethod(GetMethod<SteamFriends_SetRichPresence_Patch>("Prefix"))); PatchAllEnemies(); PatchAllPlayers(); PatchAllMemes(); methodsPatched = true; } public static string workingPath; public static string workingDir; public static AssetBundle bundle; public static AudioClip druidKnightFullAutoAud; public static AudioClip druidKnightFullerAutoAud; public static AudioClip druidKnightDeathAud; public static AudioClip enrageAudioCustom; public static GameObject fleshObamium; public static GameObject obamapticon; public void Awake() { instance = this; workingPath = Assembly.GetExecutingAssembly().Location; workingDir = Path.GetDirectoryName(workingPath); Logger.LogInfo($"Working path: {workingPath}, Working dir: {workingDir}"); try { bundle = AssetBundle.LoadFromFile(Path.Combine(workingDir, "ultrapain")); druidKnightFullAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullauto.wav"); druidKnightFullerAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullerauto.wav"); druidKnightDeathAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/death.wav"); enrageAudioCustom = bundle.LoadAsset<AudioClip>("assets/ultrapain/sfx/enraged.wav"); fleshObamium = bundle.LoadAsset<GameObject>("assets/ultrapain/fleshprison/fleshobamium.prefab"); obamapticon = bundle.LoadAsset<GameObject>("assets/ultrapain/panopticon/obamapticon.prefab"); } catch (Exception e) { Logger.LogError($"Could not load the asset bundle:\n{e}"); } // DEBUG /*string logPath = Path.Combine(Environment.CurrentDirectory, "log.txt"); Logger.LogInfo($"Saving to {logPath}"); List<string> assetPaths = new List<string>() { "fonts.bundle", "videos.bundle", "shaders.bundle", "particles.bundle", "materials.bundle", "animations.bundle", "prefabs.bundle", "physicsmaterials.bundle", "models.bundle", "textures.bundle", }; //using (FileStream log = File.Open(logPath, FileMode.OpenOrCreate, FileAccess.Write)) //{ foreach(string assetPath in assetPaths) { Logger.LogInfo($"Attempting to load {assetPath}"); AssetBundle bundle = AssetBundle.LoadFromFile(Path.Combine(bundlePath, assetPath)); bundles.Add(bundle); //foreach (string name in bundle.GetAllAssetNames()) //{ // string line = $"[{bundle.name}][{name}]\n"; // log.Write(Encoding.ASCII.GetBytes(line), 0, line.Length); //} bundle.LoadAllAssets(); } //} */ // Plugin startup logic Logger.LogInfo($"Plugin {PluginInfo.PLUGIN_GUID} is loaded!"); harmonyTweaks = new Harmony(PLUGIN_GUID + "_tweaks"); harmonyBase = new Harmony(PLUGIN_GUID + "_base"); harmonyBase.Patch(GetMethod<DifficultySelectButton>("SetDifficulty"), postfix: GetHarmonyMethod(GetMethod<DifficultySelectPatch>("Postfix"))); harmonyBase.Patch(GetMethod<DifficultyTitle>("Check"), postfix: GetHarmonyMethod(GetMethod<DifficultyTitle_Check_Patch>("Postfix"))); harmonyBase.Patch(typeof(PrefsManager).GetConstructor(new Type[0]), postfix: GetHarmonyMethod(GetMethod<PrefsManager_Ctor>("Postfix"))); harmonyBase.Patch(GetMethod<PrefsManager>("EnsureValid"), prefix: GetHarmonyMethod(GetMethod<PrefsManager_EnsureValid>("Prefix"))); harmonyBase.Patch(GetMethod<Grenade>("Explode"), prefix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Prefix")), postfix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Postfix"))); LoadPrefabs(); ConfigManager.Initialize(); SceneManager.activeSceneChanged += OnSceneChange; } } public static class Tools { private static Transform _target; private static Transform target { get { if(_target == null) _target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); return _target; } } public static Vector3 PredictPlayerPosition(float speedMod, Collider enemyCol = null) { Vector3 projectedPlayerPos; if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f) { return target.position; } RaycastHit raycastHit; if (enemyCol != null && Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == enemyCol) { projectedPlayerPos = target.position; } else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { projectedPlayerPos = raycastHit.point; } else { projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod; projectedPlayerPos = new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z); } return projectedPlayerPos; } } // Asset destroyer tracker /*[HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object) })] public class TempClass1 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object), typeof(float) })] public class TempClass2 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object) })] public class TempClass3 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object), typeof(bool) })] public class TempClass4 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } }*/ }
Ultrapain/Plugin.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static ConfigPanel cerberusPanel;\n public static ConfigPanel dronePanel;\n public static ConfigPanel filthPanel;\n public static ConfigPanel hideousMassPanel;\n public static ConfigPanel maliciousFacePanel;\n public static ConfigPanel mindflayerPanel;\n public static ConfigPanel schismPanel;\n public static ConfigPanel soliderPanel;\n public static ConfigPanel stalkerPanel;\n public static ConfigPanel strayPanel;", "score": 0.8707334995269775 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static ConfigPanel streetCleanerPanel;\n public static ConfigPanel swordsMachinePanel;\n public static ConfigPanel virtuePanel;\n public static ConfigPanel ferrymanPanel;\n public static ConfigPanel turretPanel;\n public static ConfigPanel fleshPrisonPanel;\n public static ConfigPanel minosPrimePanel;\n public static ConfigPanel v2FirstPanel;\n public static ConfigPanel v2SecondPanel;\n public static ConfigPanel sisyInstPanel;", "score": 0.8585186004638672 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static ConfigPanel leviathanPanel;\n public static ConfigPanel somethingWickedPanel;\n public static ConfigPanel panopticonPanel;\n public static ConfigPanel idolPanel;\n // GLOBAL ENEMY CONFIG\n public static BoolField friendlyFireDamageOverrideToggle;\n public static FloatSliderField friendlyFireDamageOverrideExplosion;\n public static FloatSliderField friendlyFireDamageOverrideProjectile;\n public static FloatSliderField friendlyFireDamageOverrideFire;\n public static FloatSliderField friendlyFireDamageOverrideMelee;", "score": 0.8323115706443787 }, { "filename": "Ultrapain/Patches/Virtue.cs", "retrieved_chunk": " }\n }\n class VirtueFlag : MonoBehaviour\n {\n public AudioSource lighningBoltSFX;\n public GameObject ligtningBoltAud;\n public Transform windupObj;\n private EnemyIdentifier eid;\n public Drone virtue;\n public void Awake()", "score": 0.8280853033065796 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " }\n // ROOT PANEL\n public static BoolField enemyTweakToggle;\n private static ConfigPanel enemyPanel;\n public static BoolField playerTweakToggle;\n private static ConfigPanel playerPanel;\n public static BoolField discordRichPresenceToggle;\n public static BoolField steamRichPresenceToggle;\n public static StringField pluginName;\n public static StringMultilineField pluginInfo;", "score": 0.8254075646400452 } ]
csharp
GameObject shockwave;
namespace CloudDistributedLock { public interface ICloudDistributedLockProvider { Task<CloudDistributedLock> TryAquireLockAsync(string name); Task<CloudDistributedLock> AcquireLockAsync(string name, TimeSpan? timeout = default); } public class CloudDistributedLockProvider : ICloudDistributedLockProvider { private readonly CloudDistributedLockProviderOptions options; private readonly CosmosLockClient cosmosLockClient; public CloudDistributedLockProvider(CloudDistributedLockProviderOptions options) { this.options = options; this.cosmosLockClient = new CosmosLockClient(options); } public async Task<
CloudDistributedLock> AcquireLockAsync(string name, TimeSpan? timeout = null) {
using var cancellationTokenSource = timeout.HasValue ? new CancellationTokenSource(timeout.Value) : new CancellationTokenSource(); return await ContinuallyTryAquireLockAsync(name, cancellationTokenSource.Token); } public async Task<CloudDistributedLock> TryAquireLockAsync(string name) { var item = await cosmosLockClient.TryAquireLockAsync(name); if (item != null) { return CloudDistributedLock.CreateAcquiredLock(cosmosLockClient, item); } else { return CloudDistributedLock.CreateUnacquiredLock(); } } private async Task<CloudDistributedLock> ContinuallyTryAquireLockAsync(string name, CancellationToken cancellationToken) { CloudDistributedLock? @lock; do { @lock = await TryAquireLockAsync(name); if ([email protected] && !cancellationToken.IsCancellationRequested) { await Task.Delay(options.RetryInterval); } } while ([email protected] && !cancellationToken.IsCancellationRequested); return @lock; } } }
CloudDistributedLock/CloudDistributedLockProvider.cs
briandunnington-CloudDistributedLock-04f72e6
[ { "filename": "CloudDistributedLock/CloudDistributedLock.cs", "retrieved_chunk": " private Timer? timer;\n private bool isDisposed;\n public static CloudDistributedLock CreateUnacquiredLock()\n {\n return new CloudDistributedLock();\n }\n public static CloudDistributedLock CreateAcquiredLock(CosmosLockClient cosmosLockClient, ItemResponse<LockRecord> item)\n {\n return new CloudDistributedLock(cosmosLockClient, item);\n }", "score": 0.9094010591506958 }, { "filename": "CloudDistributedLock/CosmosLockClient.cs", "retrieved_chunk": "using Microsoft.Azure.Cosmos;\nusing System.Net;\nnamespace CloudDistributedLock\n{\n public class CosmosLockClient\n {\n private readonly CloudDistributedLockProviderOptions options;\n private readonly Container container;\n public CosmosLockClient(CloudDistributedLockProviderOptions options)\n {", "score": 0.8857043385505676 }, { "filename": "CloudDistributedLock/CloudDistributedLockProviderFactory.cs", "retrieved_chunk": " {\n internal const string DefaultName = \"__DEFAULT\";\n private readonly ConcurrentDictionary<string, ICloudDistributedLockProvider> clients = new();\n public CloudDistributedLockProviderFactory(IOptionsMonitor<CloudDistributedLockProviderOptions> optionsMonitor)\n {\n this.OptionsMonitor = optionsMonitor;\n }\n protected IOptionsMonitor<CloudDistributedLockProviderOptions> OptionsMonitor { get; }\n public ICloudDistributedLockProvider GetLockProvider(string name)\n {", "score": 0.8841341733932495 }, { "filename": "CloudDistributedLock/ServiceCollectionExtensions.cs", "retrieved_chunk": " }\n public static IServiceCollection AddCloudDistributedLock(this IServiceCollection services, CosmosClient cosmosClient, string databaseName, int ttl, Action<CloudDistributedLockProviderOptions>? configureOptions = null)\n {\n return services.AddCloudDistributedLock(CloudDistributedLockProviderFactory.DefaultName, cosmosClient, databaseName, ttl, configureOptions);\n }\n public static IServiceCollection AddCloudDistributedLock(this IServiceCollection services, string name, string cosmosEndpoint, string cosmosKey, string databaseName, int ttl, Action<CloudDistributedLockProviderOptions>? configureOptions = null)\n {\n var cosmosClient = new CosmosClient(cosmosEndpoint, cosmosKey);\n return services.AddCloudDistributedLock(name, cosmosClient, databaseName, ttl, configureOptions);\n }", "score": 0.8785760402679443 }, { "filename": "CloudDistributedLock/ServiceCollectionExtensions.cs", "retrieved_chunk": "using Microsoft.Azure.Cosmos;\nusing Microsoft.Extensions.DependencyInjection;\nnamespace CloudDistributedLock\n{\n public static class ServiceCollectionExtensions\n {\n public static IServiceCollection AddCloudDistributedLock(this IServiceCollection services, string cosmosEndpoint, string cosmosKey, string databaseName, int ttl, Action<CloudDistributedLockProviderOptions>? configureOptions = null)\n {\n var cosmosClient = new CosmosClient(cosmosEndpoint, cosmosKey);\n return services.AddCloudDistributedLock(CloudDistributedLockProviderFactory.DefaultName, cosmosClient, databaseName, ttl, configureOptions);", "score": 0.8710383176803589 } ]
csharp
CloudDistributedLock> AcquireLockAsync(string name, TimeSpan? timeout = null) {
using System; using SQLServerCoverage.Gateway; using SQLServerCoverage.Objects; using SQLServerCoverage.Source; namespace SQLServerCoverage.Trace { class TraceControllerBuilder { public TraceController GetTraceController(
DatabaseGateway gateway, string databaseName, TraceControllerType type) {
switch(type) { case TraceControllerType.Azure: return new AzureTraceController(gateway, databaseName); case TraceControllerType.Sql: return new SqlTraceController(gateway, databaseName); case TraceControllerType.SqlLocalDb: return new SqlLocalDbTraceController(gateway, databaseName); } var source = new DatabaseSourceGateway(gateway); if (LooksLikeLocalDb(gateway.DataSource)) { return new SqlLocalDbTraceController(gateway, databaseName); } var isAzure = source.IsAzure(); if(!isAzure) return new SqlTraceController(gateway, databaseName); var version = source.GetVersion(); if(version < SqlServerVersion.Sql120) throw new Exception("SQL Azure is only supported from Version 12"); return new AzureTraceController(gateway, databaseName); } private bool LooksLikeLocalDb(string dataSource) { dataSource = dataSource.ToLowerInvariant(); return dataSource.Contains("(localdb)") || dataSource.StartsWith("np:\\\\.\\pipe\\localdb"); } } public enum TraceControllerType { Default, Sql, Azure, Exp, SqlLocalDb } }
src/SQLServerCoverageLib/Trace/TraceControllerBuilder.cs
sayantandey-SQLServerCoverage-aea57e3
[ { "filename": "src/SQLServerCoverageLib/Trace/SqlLocalDbTraceController.cs", "retrieved_chunk": "using SQLServerCoverage.Gateway;\nusing System.IO;\nnamespace SQLServerCoverage.Trace\n{\n class SqlLocalDbTraceController : SqlTraceController\n {\n public SqlLocalDbTraceController(DatabaseGateway gateway, string databaseName) : base(gateway, databaseName)\n {\n }\n protected override void Create()", "score": 0.9138333201408386 }, { "filename": "src/SQLServerCoverageLib/Trace/TraceController.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing SQLServerCoverage.Gateway;\nnamespace SQLServerCoverage.Trace\n{\n abstract class TraceController\n {\n protected readonly string DatabaseId;\n protected readonly DatabaseGateway Gateway;\n protected string FileName;", "score": 0.8887421488761902 }, { "filename": "src/SQLServerCoverageLib/Trace/SqlTraceController.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Data;\nusing System.IO;\nusing SQLServerCoverage.Gateway;\nnamespace SQLServerCoverage.Trace\n{\n class SqlTraceController : TraceController\n {\n protected const string CreateTrace = @\"CREATE EVENT SESSION [{0}] ON SERVER ", "score": 0.869743824005127 }, { "filename": "src/SQLServerCoverageLib/Trace/AzureTraceController.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Data;\nusing System.Threading;\nusing SQLServerCoverage.Gateway;\nnamespace SQLServerCoverage.Trace\n{\n internal class AzureTraceController : TraceController\n {\n private const string CreateTrace = @\"CREATE EVENT SESSION [{0}] ON DATABASE ", "score": 0.8608485460281372 }, { "filename": "src/SQLServerCoverageLib/Gateway/SourceGateway.cs", "retrieved_chunk": "using System.Collections.Generic;\nusing SQLServerCoverage.Objects;\nnamespace SQLServerCoverage.Source\n{\n public interface SourceGateway\n {\n SqlServerVersion GetVersion();\n IEnumerable<Batch> GetBatches(List<string> objectFilter);\n string GetWarnings();\n }", "score": 0.8593389391899109 } ]
csharp
DatabaseGateway gateway, string databaseName, TraceControllerType type) {
using HarmonyLib; using UnityEngine; namespace Ultrapain.Patches { class Virtue_Start_Patch { static void Postfix(Drone __instance, ref EnemyIdentifier ___eid) { VirtueFlag flag = __instance.gameObject.AddComponent<VirtueFlag>(); flag.virtue = __instance; } } class Virtue_Death_Patch { static bool Prefix(Drone __instance, ref EnemyIdentifier ___eid) { if(___eid.enemyType != EnemyType.Virtue) return true; __instance.GetComponent<VirtueFlag>().DestroyProjectiles(); return true; } } class VirtueFlag : MonoBehaviour { public AudioSource lighningBoltSFX; public
GameObject ligtningBoltAud;
public Transform windupObj; private EnemyIdentifier eid; public Drone virtue; public void Awake() { eid = GetComponent<EnemyIdentifier>(); ligtningBoltAud = Instantiate(Plugin.lighningBoltSFX, transform); lighningBoltSFX = ligtningBoltAud.GetComponent<AudioSource>(); } public void SpawnLightningBolt() { LightningStrikeExplosive lightningStrikeExplosive = Instantiate(Plugin.lightningStrikeExplosiveSetup.gameObject, windupObj.transform.position, Quaternion.identity).GetComponent<LightningStrikeExplosive>(); lightningStrikeExplosive.safeForPlayer = false; lightningStrikeExplosive.damageMultiplier = eid.totalDamageModifier * ((virtue.enraged)? ConfigManager.virtueEnragedLightningDamage.value : ConfigManager.virtueNormalLightningDamage.value); if(windupObj != null) Destroy(windupObj.gameObject); } public void DestroyProjectiles() { CancelInvoke("SpawnLightningBolt"); if (windupObj != null) Destroy(windupObj.gameObject); } } class Virtue_SpawnInsignia_Patch { static bool Prefix(Drone __instance, ref EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target, ref int ___usedAttacks) { if (___eid.enemyType != EnemyType.Virtue) return true; GameObject createInsignia(Drone __instance, ref EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target, int damage, float lastMultiplier) { GameObject gameObject = GameObject.Instantiate<GameObject>(__instance.projectile, ___target.transform.position, Quaternion.identity); VirtueInsignia component = gameObject.GetComponent<VirtueInsignia>(); component.target = MonoSingleton<PlayerTracker>.Instance.GetPlayer(); component.parentDrone = __instance; component.hadParent = true; component.damage = damage; component.explosionLength *= lastMultiplier; __instance.chargeParticle.Stop(false, ParticleSystemStopBehavior.StopEmittingAndClear); if (__instance.enraged) { component.predictive = true; } /*if (___difficulty == 1) { component.windUpSpeedMultiplier = 0.875f; } else if (___difficulty == 0) { component.windUpSpeedMultiplier = 0.75f; }*/ if (MonoSingleton<PlayerTracker>.Instance.playerType == PlayerType.Platformer) { gameObject.transform.localScale *= 0.75f; component.windUpSpeedMultiplier *= 0.875f; } component.windUpSpeedMultiplier *= ___eid.totalSpeedModifier; component.damage = Mathf.RoundToInt((float)component.damage * ___eid.totalDamageModifier); return gameObject; } if (__instance.enraged && !ConfigManager.virtueTweakEnragedAttackToggle.value) return true; if (!__instance.enraged && !ConfigManager.virtueTweakNormalAttackToggle.value) return true; bool insignia = (__instance.enraged) ? ConfigManager.virtueEnragedAttackType.value == ConfigManager.VirtueAttackType.Insignia : ConfigManager.virtueNormalAttackType.value == ConfigManager.VirtueAttackType.Insignia; if (insignia) { bool xAxis = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaXtoggle.value : ConfigManager.virtueNormalInsigniaXtoggle.value; bool yAxis = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaYtoggle.value : ConfigManager.virtueNormalInsigniaYtoggle.value; bool zAxis = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaZtoggle.value : ConfigManager.virtueNormalInsigniaZtoggle.value; if (xAxis) { GameObject obj = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target, (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaXdamage.value : ConfigManager.virtueNormalInsigniaXdamage.value, (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaLastMulti.value : ConfigManager.virtueNormalInsigniaLastMulti.value); float size = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaXsize.value : ConfigManager.virtueNormalInsigniaXsize.value; obj.transform.localScale = new Vector3(size, obj.transform.localScale.y, size); obj.transform.Rotate(new Vector3(90f, 0, 0)); } if (yAxis) { GameObject obj = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target, (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaYdamage.value : ConfigManager.virtueNormalInsigniaYdamage.value, (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaLastMulti.value : ConfigManager.virtueNormalInsigniaLastMulti.value); float size = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaYsize.value : ConfigManager.virtueNormalInsigniaYsize.value; obj.transform.localScale = new Vector3(size, obj.transform.localScale.y, size); } if (zAxis) { GameObject obj = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target, (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaZdamage.value : ConfigManager.virtueNormalInsigniaZdamage.value, (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaLastMulti.value : ConfigManager.virtueNormalInsigniaLastMulti.value); float size = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaZsize.value : ConfigManager.virtueNormalInsigniaZsize.value; obj.transform.localScale = new Vector3(size, obj.transform.localScale.y, size); obj.transform.Rotate(new Vector3(0, 0, 90f)); } } else { Vector3 predictedPos; if (___difficulty <= 1) predictedPos = MonoSingleton<PlayerTracker>.Instance.GetPlayer().position; else { Vector3 vector = new Vector3(MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().x, 0f, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().z); predictedPos = MonoSingleton<PlayerTracker>.Instance.GetPlayer().position + vector.normalized * Mathf.Min(vector.magnitude, 5.0f); } GameObject currentWindup = GameObject.Instantiate<GameObject>(Plugin.lighningStrikeWindup.gameObject, predictedPos, Quaternion.identity); foreach (Follow follow in currentWindup.GetComponents<Follow>()) { if (follow.speed != 0f) { if (___difficulty >= 2) { follow.speed *= (float)___difficulty; } else if (___difficulty == 1) { follow.speed /= 2f; } else { follow.enabled = false; } follow.speed *= ___eid.totalSpeedModifier; } } VirtueFlag flag = __instance.GetComponent<VirtueFlag>(); flag.lighningBoltSFX.Play(); flag.windupObj = currentWindup.transform; flag.Invoke("SpawnLightningBolt", (__instance.enraged)? ConfigManager.virtueEnragedLightningDelay.value : ConfigManager.virtueNormalLightningDelay.value); } ___usedAttacks += 1; if(___usedAttacks == 3) { __instance.Invoke("Enrage", 3f / ___eid.totalSpeedModifier); } return false; } /*static void Postfix(Drone __instance, ref EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target, bool __state) { if (!__state) return; GameObject createInsignia(Drone __instance, ref EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target) { GameObject gameObject = GameObject.Instantiate<GameObject>(__instance.projectile, ___target.transform.position, Quaternion.identity); VirtueInsignia component = gameObject.GetComponent<VirtueInsignia>(); component.target = MonoSingleton<PlayerTracker>.Instance.GetPlayer(); component.parentDrone = __instance; component.hadParent = true; __instance.chargeParticle.Stop(false, ParticleSystemStopBehavior.StopEmittingAndClear); if (__instance.enraged) { component.predictive = true; } if (___difficulty == 1) { component.windUpSpeedMultiplier = 0.875f; } else if (___difficulty == 0) { component.windUpSpeedMultiplier = 0.75f; } if (MonoSingleton<PlayerTracker>.Instance.playerType == PlayerType.Platformer) { gameObject.transform.localScale *= 0.75f; component.windUpSpeedMultiplier *= 0.875f; } component.windUpSpeedMultiplier *= ___eid.totalSpeedModifier; component.damage = Mathf.RoundToInt((float)component.damage * ___eid.totalDamageModifier); return gameObject; } GameObject xAxisInsignia = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target); xAxisInsignia.transform.Rotate(new Vector3(90, 0, 0)); xAxisInsignia.transform.localScale = new Vector3(xAxisInsignia.transform.localScale.x * horizontalInsigniaScale, xAxisInsignia.transform.localScale.y, xAxisInsignia.transform.localScale.z * horizontalInsigniaScale); GameObject zAxisInsignia = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target); zAxisInsignia.transform.Rotate(new Vector3(0, 0, 90)); zAxisInsignia.transform.localScale = new Vector3(zAxisInsignia.transform.localScale.x * horizontalInsigniaScale, zAxisInsignia.transform.localScale.y, zAxisInsignia.transform.localScale.z * horizontalInsigniaScale); }*/ } }
Ultrapain/Patches/Virtue.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/SomethingWicked.cs", "retrieved_chunk": " SomethingWickedFlag flag = __instance.GetComponent<SomethingWickedFlag>();\n if (flag == null)\n return;\n if (flag.spear != null)\n GameObject.Destroy(flag.spear);\n }\n }\n class JokeWicked : MonoBehaviour\n {\n void OnDestroy()", "score": 0.8400949239730835 }, { "filename": "Ultrapain/Patches/SisyphusInstructionist.cs", "retrieved_chunk": " esi.enraged = true;\n }\n GameObject effect = GameObject.Instantiate(Plugin.enrageEffect, __instance.transform);\n effect.transform.localScale = Vector3.one * 0.2f;\n }\n }*/\n public class SisyphusInstructionist_Start\n {\n public static GameObject _shockwave;\n public static GameObject shockwave", "score": 0.8279926180839539 }, { "filename": "Ultrapain/Patches/Stray.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nusing UnityEngine.AI;\nnamespace Ultrapain.Patches\n{\n public class StrayFlag : MonoBehaviour\n {\n //public int extraShotsRemaining = 6;\n private Animator anim;\n private EnemyIdentifier eid;", "score": 0.8224848508834839 }, { "filename": "Ultrapain/Patches/OrbitalStrike.cs", "retrieved_chunk": " __instance.gameObject.AddComponent<OrbitalStrikeFlag>();\n }\n }\n public class CoinChainList : MonoBehaviour\n {\n public List<Coin> chainList = new List<Coin>();\n public bool isOrbitalStrike = false;\n public float activasionDistance;\n }\n class Punch_BlastCheck", "score": 0.8176218271255493 }, { "filename": "Ultrapain/Patches/MinosPrime.cs", "retrieved_chunk": " }\n class MinosPrimeFlag : MonoBehaviour\n {\n void Start()\n {\n }\n public void ComboExplosion()\n {\n GameObject explosion = Instantiate(Plugin.lightningStrikeExplosive, transform.position, Quaternion.identity);\n foreach(Explosion e in explosion.GetComponentsInChildren<Explosion>())", "score": 0.8145200610160828 } ]
csharp
GameObject ligtningBoltAud;
using Microsoft.VisualStudio.Shell; using System.ComponentModel; namespace VSIntelliSenseTweaks { public class GeneralSettings : DialogPage { public const string PageName = "General"; private bool includeDebugSuffix = false; private bool disableSoftSelection = false; private bool boostEnumMemberScore = true; [Category(
VSIntelliSenseTweaksPackage.PackageDisplayName)] [DisplayName(nameof(IncludeDebugSuffix))] [Description("Adds a suffix with debug information to the entries in the completion list.")] public bool IncludeDebugSuffix {
get { return includeDebugSuffix; } set { includeDebugSuffix = value; } } [Category(VSIntelliSenseTweaksPackage.PackageDisplayName)] [DisplayName(nameof(DisableSoftSelection))] [Description("Disables initial soft-selection in the completion-list when completion was triggered manually (usually by ctrl + space).")] public bool DisableSoftSelection { get { return disableSoftSelection; } set { disableSoftSelection = value; } } [Category(VSIntelliSenseTweaksPackage.PackageDisplayName)] [DisplayName(nameof(BoostEnumMemberScore))] [Description("Boosts the score of enum members when the enum type was preselected by roslyn.")] public bool BoostEnumMemberScore { get { return boostEnumMemberScore; } set { boostEnumMemberScore = value; } } } }
VSIntelliSenseTweaks/GeneralSettings.cs
cfognom-VSIntelliSenseTweaks-4099741
[ { "filename": "VSIntelliSenseTweaks/CompletionItemManager.cs", "retrieved_chunk": " WordScorer scorer = new WordScorer(256);\n CompletionFilterManager filterManager;\n bool hasFilterManager;\n bool includeDebugSuffix;\n bool disableSoftSelection;\n bool boostEnumMemberScore;\n public CompletionItemManager(GeneralSettings settings)\n {\n this.includeDebugSuffix = settings.IncludeDebugSuffix;\n this.disableSoftSelection = settings.DisableSoftSelection;", "score": 0.8469458818435669 }, { "filename": "VSIntelliSenseTweaks/VSIntelliSenseTweaksPackage.cs", "retrieved_chunk": " /// register itself and its components with the shell. These attributes tell the pkgdef creation\n /// utility what data to put into .pkgdef file.\n /// </para>\n /// <para>\n /// To get loaded into VS, the package must be referred by &lt;Asset Type=\"Microsoft.VisualStudio.VsPackage\" ...&gt; in .vsixmanifest file.\n /// </para>\n /// </remarks>\n [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]\n [Guid(VSIntelliSenseTweaksPackage.PackageGuidString)]\n [ProvideOptionPage(pageType: typeof(GeneralSettings), categoryName: PackageDisplayName, pageName: GeneralSettings.PageName, 0, 0, true)]", "score": 0.8198015689849854 }, { "filename": "VSIntelliSenseTweaks/CompletionItemManager.cs", "retrieved_chunk": " BitField64 activeBlacklist;\n BitField64 activeWhitelist;\n /// <summary>\n /// True when there is an active whitelist to perform checks against.\n /// </summary>\n public bool HasActiveWhitelist => activeWhitelist != default;\n enum CompletionFilterKind\n {\n Null, Blacklist, Whitelist\n }", "score": 0.8183571100234985 }, { "filename": "VSIntelliSenseTweaks/VSIntelliSenseTweaksPackage.cs", "retrieved_chunk": " public sealed class VSIntelliSenseTweaksPackage : AsyncPackage\n {\n /// <summary>\n /// VSIntelliSenseTweaksPackage GUID string.\n /// </summary>\n public const string PackageGuidString = \"8e0ec3d8-0561-477a-ade4-77d8826fc290\";\n public const string PackageDisplayName = \"IntelliSense Tweaks\";\n #region Package Members\n /// <summary>\n /// Initialization of the package; this method is called right after the package is sited, so this is the place", "score": 0.8082318902015686 }, { "filename": "VSIntelliSenseTweaks/CompletionItemManager.cs", "retrieved_chunk": " }\n }\n activeBlacklist = ~selection & blacklist;\n activeWhitelist = selection & whitelist;\n }\n public BitField64 CreateFilterMask(ImmutableArray<CompletionFilter> completionFilters)\n {\n BitField64 mask = default;\n for (int i = 0; i < completionFilters.Length; i++)\n {", "score": 0.7938287258148193 } ]
csharp
VSIntelliSenseTweaksPackage.PackageDisplayName)] [DisplayName(nameof(IncludeDebugSuffix))] [Description("Adds a suffix with debug information to the entries in the completion list.")] public bool IncludeDebugSuffix {
using Magic.IndexedDb; using Magic.IndexedDb.SchemaAnnotations; namespace IndexDb.Example { [MagicTable("Person", DbNames.Client)] public class Person { [MagicPrimaryKey("id")] public int _Id { get; set; } [MagicIndex] public string Name { get; set; } [MagicIndex("Age")] public int _Age { get; set; } [
MagicIndex] public int TestInt {
get; set; } [MagicUniqueIndex("guid")] public Guid GUIY { get; set; } = Guid.NewGuid(); [MagicEncrypt] public string Secret { get; set; } [MagicNotMapped] public string DoNotMapTest { get; set; } [MagicNotMapped] public string SecretDecrypted { get; set; } private bool testPrivate { get; set; } = false; public bool GetTest() { return true; } } }
IndexDb.Example/Models/Person.cs
magiccodingman-Magic.IndexedDb-a279d6d
[ { "filename": "Magic.IndexedDb/Models/StoredMagicQuery.cs", "retrieved_chunk": " public string? Name { get; set; }\n public int IntValue { get; set; } = 0;\n public string? StringValue { get; set; }\n }\n}", "score": 0.8557212948799133 }, { "filename": "Magic.IndexedDb/Models/StoreSchema.cs", "retrieved_chunk": " public string PrimaryKey { get; set; }\n public bool PrimaryKeyAuto { get; set; }\n public List<string> UniqueIndexes { get; set; } = new List<string>();\n public List<string> Indexes { get; set; } = new List<string>();\n }\n}", "score": 0.850806474685669 }, { "filename": "Magic.IndexedDb/Models/StoreRecord.cs", "retrieved_chunk": "namespace Magic.IndexedDb\n{ \n public class StoreRecord<T>\n {\n public string? DbName { get; set; }\n public string? StoreName { get; set; }\n public T? Record { get; set; }\n }\n}", "score": 0.84213787317276 }, { "filename": "Magic.IndexedDb/Models/IndexFilterValue.cs", "retrieved_chunk": " {\n IndexName = indexName;\n FilterValue = filterValue;\n }\n public string IndexName { get; set; }\n public object FilterValue { get; set; }\n }\n}", "score": 0.8366426229476929 }, { "filename": "IndexDb.Example/Pages/Index.razor.cs", "retrieved_chunk": "using Magic.IndexedDb.Models;\nusing System;\nnamespace IndexDb.Example.Pages\n{\n public partial class Index\n {\n private List<Person> allPeople { get; set; } = new List<Person>();\n private IEnumerable<Person> WhereExample { get; set; } = Enumerable.Empty<Person>();\n private double storageQuota { get; set; }\n private double storageUsage { get; set; }", "score": 0.8344128131866455 } ]
csharp
MagicIndex] public int TestInt {
using BepInEx; using UnityEngine; using UnityEngine.SceneManagement; using System; using HarmonyLib; using System.IO; using Ultrapain.Patches; using System.Linq; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Reflection; using Steamworks; using Unity.Audio; using System.Text; using System.Collections.Generic; using UnityEngine.AddressableAssets; using UnityEngine.AddressableAssets.ResourceLocators; using UnityEngine.ResourceManagement.ResourceLocations; using UnityEngine.UIElements; using PluginConfig.API; namespace Ultrapain { [BepInPlugin(PLUGIN_GUID, PLUGIN_NAME, PLUGIN_VERSION)] [BepInDependency("com.eternalUnion.pluginConfigurator", "1.6.0")] public class Plugin : BaseUnityPlugin { public const string PLUGIN_GUID = "com.eternalUnion.ultraPain"; public const string PLUGIN_NAME = "Ultra Pain"; public const string PLUGIN_VERSION = "1.1.0"; public static Plugin instance; private static bool addressableInit = false; public static T LoadObject<T>(string path) { if (!addressableInit) { Addressables.InitializeAsync().WaitForCompletion(); addressableInit = true; } return Addressables.LoadAssetAsync<T>(path).WaitForCompletion(); } public static Vector3 PredictPlayerPosition(Collider safeCollider, float speedMod) { Transform target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f) return target.position; RaycastHit raycastHit; if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == safeCollider) return target.position; else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { return raycastHit.point; } else { Vector3 projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod; return new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z); } } public static GameObject projectileSpread; public static GameObject homingProjectile; public static GameObject hideousMassProjectile; public static GameObject decorativeProjectile2; public static GameObject shotgunGrenade; public static GameObject beam; public static GameObject turretBeam; public static GameObject lightningStrikeExplosiveSetup; public static GameObject lightningStrikeExplosive; public static GameObject lighningStrikeWindup; public static GameObject explosion; public static GameObject bigExplosion; public static GameObject sandExplosion; public static GameObject virtueInsignia; public static GameObject rocket; public static GameObject revolverBullet; public static GameObject maliciousCannonBeam; public static GameObject lightningBoltSFX; public static GameObject revolverBeam; public static GameObject blastwave; public static GameObject cannonBall; public static GameObject shockwave; public static GameObject sisyphiusExplosion; public static GameObject sisyphiusPrimeExplosion; public static GameObject explosionWaveKnuckleblaster; public static GameObject chargeEffect; public static GameObject maliciousFaceProjectile; public static GameObject hideousMassSpear; public static GameObject coin; public static GameObject sisyphusDestroyExplosion; //public static GameObject idol; public static GameObject ferryman; public static GameObject minosPrime; //public static GameObject maliciousFace; public static GameObject somethingWicked; public static Turret turret; public static GameObject turretFinalFlash; public static GameObject enrageEffect; public static GameObject v2flashUnparryable; public static GameObject ricochetSfx; public static GameObject parryableFlash; public static AudioClip cannonBallChargeAudio; public static Material gabrielFakeMat; public static Sprite blueRevolverSprite; public static Sprite greenRevolverSprite; public static Sprite redRevolverSprite; public static Sprite blueShotgunSprite; public static Sprite greenShotgunSprite; public static Sprite blueNailgunSprite; public static Sprite greenNailgunSprite; public static Sprite blueSawLauncherSprite; public static Sprite greenSawLauncherSprite; public static GameObject rocketLauncherAlt; public static
GameObject maliciousRailcannon;
// Variables public static float SoliderShootAnimationStart = 1.2f; public static float SoliderGrenadeForce = 10000f; public static float SwordsMachineKnockdownTimeNormalized = 0.8f; public static float SwordsMachineCoreSpeed = 80f; public static float MinGrenadeParryVelocity = 40f; public static GameObject _lighningBoltSFX; public static GameObject lighningBoltSFX { get { if (_lighningBoltSFX == null) _lighningBoltSFX = ferryman.gameObject.transform.Find("LightningBoltChimes").gameObject; return _lighningBoltSFX; } } private static bool loadedPrefabs = false; public void LoadPrefabs() { if (loadedPrefabs) return; loadedPrefabs = true; // Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab projectileSpread = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab homingProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab decorativeProjectile2 = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab"); // Assets/Prefabs/Attacks and Projectiles/Grenade.prefab shotgunGrenade = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Grenade.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab turretBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab beam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab lightningStrikeExplosiveSetup = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab"); // Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab lighningStrikeWindup = LoadObject<GameObject>("Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab"); //[bundle-0][assets/prefabs/enemies/idol.prefab] //idol = LoadObject<GameObject>("assets/prefabs/enemies/idol.prefab"); // Assets/Prefabs/Enemies/Ferryman.prefab ferryman = LoadObject<GameObject>("Assets/Prefabs/Enemies/Ferryman.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab explosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab bigExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab sandExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab"); // Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab virtueInsignia = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab hideousMassProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab"); // Assets/Particles/Enemies/RageEffect.prefab enrageEffect = LoadObject<GameObject>("Assets/Particles/Enemies/RageEffect.prefab"); // Assets/Particles/Flashes/V2FlashUnparriable.prefab v2flashUnparryable = LoadObject<GameObject>("Assets/Particles/Flashes/V2FlashUnparriable.prefab"); // Assets/Prefabs/Attacks and Projectiles/Rocket.prefab rocket = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Rocket.prefab"); // Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab revolverBullet = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab maliciousCannonBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab revolverBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab blastwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab"); // Assets/Prefabs/Enemies/MinosPrime.prefab minosPrime = LoadObject<GameObject>("Assets/Prefabs/Enemies/MinosPrime.prefab"); // Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab cannonBall = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab"); // get from Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab cannonBallChargeAudio = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab").transform.Find("RocketLauncher/Armature/Body_Bone/HologramDisplay").GetComponent<AudioSource>().clip; // Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab shockwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab sisyphiusExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab sisyphiusPrimeExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab explosionWaveKnuckleblaster = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab - [bundle-0][assets/prefabs/explosionlightning variant.prefab] lightningStrikeExplosive = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab"); // Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab rocketLauncherAlt = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab"); // Assets/Prefabs/Weapons/Railcannon Malicious.prefab maliciousRailcannon = LoadObject<GameObject>("Assets/Prefabs/Weapons/Railcannon Malicious.prefab"); //Assets/Particles/SoundBubbles/Ricochet.prefab ricochetSfx = LoadObject<GameObject>("Assets/Particles/SoundBubbles/Ricochet.prefab"); //Assets/Particles/Flashes/Flash.prefab parryableFlash = LoadObject<GameObject>("Assets/Particles/Flashes/Flash.prefab"); //Assets/Prefabs/Attacks and Projectiles/Spear.prefab hideousMassSpear = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Spear.prefab"); //Assets/Prefabs/Enemies/Wicked.prefab somethingWicked = LoadObject<GameObject>("Assets/Prefabs/Enemies/Wicked.prefab"); //Assets/Textures/UI/SingleRevolver.png blueRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/SingleRevolver.png"); //Assets/Textures/UI/RevolverSpecial.png greenRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSpecial.png"); //Assets/Textures/UI/RevolverSharp.png redRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSharp.png"); //Assets/Textures/UI/Shotgun.png blueShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun.png"); //Assets/Textures/UI/Shotgun1.png greenShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun1.png"); //Assets/Textures/UI/Nailgun2.png blueNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Nailgun2.png"); //Assets/Textures/UI/NailgunOverheat.png greenNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/NailgunOverheat.png"); //Assets/Textures/UI/SawbladeLauncher.png blueSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncher.png"); //Assets/Textures/UI/SawbladeLauncherOverheat.png greenSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncherOverheat.png"); //Assets/Prefabs/Attacks and Projectiles/Coin.prefab coin = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Coin.prefab"); //Assets/Materials/GabrielFake.mat gabrielFakeMat = LoadObject<Material>("Assets/Materials/GabrielFake.mat"); //Assets/Prefabs/Enemies/Turret.prefab turret = LoadObject<GameObject>("Assets/Prefabs/Enemies/Turret.prefab").GetComponent<Turret>(); //Assets/Particles/Flashes/GunFlashDistant.prefab turretFinalFlash = LoadObject<GameObject>("Assets/Particles/Flashes/GunFlashDistant.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab sisyphusDestroyExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab"); //Assets/Prefabs/Effects/Charge Effect.prefab chargeEffect = LoadObject<GameObject>("Assets/Prefabs/Effects/Charge Effect.prefab"); //Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab maliciousFaceProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab"); } public static bool ultrapainDifficulty = false; public static bool realUltrapainDifficulty = false; public static GameObject currentDifficultyButton; public static GameObject currentDifficultyPanel; public static Text currentDifficultyInfoText; public void OnSceneChange(Scene before, Scene after) { StyleIDs.RegisterIDs(); ScenePatchCheck(); string mainMenuSceneName = "b3e7f2f8052488a45b35549efb98d902"; string bootSequenceSceneName = "4f8ecffaa98c2614f89922daf31fa22d"; string currentSceneName = SceneManager.GetActiveScene().name; if (currentSceneName == mainMenuSceneName) { LoadPrefabs(); //Canvas/Difficulty Select (1)/Violent Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Difficulty Select (1)"); GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect); currentDifficultyButton = ultrapainButton; ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value; ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5; RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>(); ultrapainTrans.anchoredPosition = new Vector2(20f, -104f); //Canvas/Difficulty Select (1)/Violent Info GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect); currentDifficultyPanel = info; currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>(); currentDifficultyInfoText.text = ConfigManager.pluginInfo.value; Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>(); currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--"; currentDifficultyHeaderText.resizeTextForBestFit = true; currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap; currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate; info.SetActive(false); EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>(); evt.triggers.Clear(); /*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(false));*/ EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit }; trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false)); evt.triggers.Add(trigger1); evt.triggers.Add(trigger2); foreach(EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>()) { if (trigger.gameObject == ultrapainButton) continue; EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false)); trigger.triggers.Add(closeTrigger); } } else if(currentSceneName == bootSequenceSceneName) { LoadPrefabs(); //Canvas/Difficulty Select (1)/Violent Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Intro/Difficulty Select"); GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect); currentDifficultyButton = ultrapainButton; ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value; ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5; RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>(); ultrapainTrans.anchoredPosition = new Vector2(20f, -104f); //Canvas/Difficulty Select (1)/Violent Info GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect); currentDifficultyPanel = info; currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>(); currentDifficultyInfoText.text = ConfigManager.pluginInfo.value; Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>(); currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--"; currentDifficultyHeaderText.resizeTextForBestFit = true; currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap; currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate; info.SetActive(false); EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>(); evt.triggers.Clear(); /*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(false));*/ EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit }; trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false)); evt.triggers.Add(trigger1); evt.triggers.Add(trigger2); foreach (EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>()) { if (trigger.gameObject == ultrapainButton) continue; EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false)); trigger.triggers.Add(closeTrigger); } } // LOAD CUSTOM PREFABS HERE TO AVOID MID GAME LAG MinosPrimeCharge.CreateDecoy(); GameObject shockwaveSisyphus = SisyphusInstructionist_Start.shockwave; } public static class StyleIDs { private static bool registered = false; public static void RegisterIDs() { registered = false; if (MonoSingleton<StyleHUD>.Instance == null) return; MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.grenadeBoostStyleText.guid, ConfigManager.grenadeBoostStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.rocketBoostStyleText.guid, ConfigManager.rocketBoostStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverStyleText.guid, ConfigManager.orbStrikeRevolverStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverChargedStyleText.guid, ConfigManager.orbStrikeRevolverChargedStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeElectricCannonStyleText.guid, ConfigManager.orbStrikeElectricCannonStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeMaliciousCannonStyleText.guid, ConfigManager.orbStrikeMaliciousCannonStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.maliciousChargebackStyleText.guid, ConfigManager.maliciousChargebackStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.sentryChargebackStyleText.guid, ConfigManager.sentryChargebackStyleText.formattedString); registered = true; Debug.Log("Registered all style ids"); } private static FieldInfo idNameDict = typeof(StyleHUD).GetField("idNameDict", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); public static void UpdateID(string id, string newName) { if (!registered || StyleHUD.Instance == null) return; (idNameDict.GetValue(StyleHUD.Instance) as Dictionary<string, string>)[id] = newName; } } public static Harmony harmonyTweaks; public static Harmony harmonyBase; private static MethodInfo GetMethod<T>(string name) { return typeof(T).GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } private static Dictionary<MethodInfo, HarmonyMethod> methodCache = new Dictionary<MethodInfo, HarmonyMethod>(); private static HarmonyMethod GetHarmonyMethod(MethodInfo method) { if (methodCache.TryGetValue(method, out HarmonyMethod harmonyMethod)) return harmonyMethod; else { harmonyMethod = new HarmonyMethod(method); methodCache.Add(method, harmonyMethod); return harmonyMethod; } } private static void PatchAllEnemies() { if (!ConfigManager.enemyTweakToggle.value) return; if (ConfigManager.friendlyFireDamageOverrideToggle.value) { harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<PhysicalShockwave>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<VirtueInsignia>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_FF>("Prefix"))); harmonyTweaks.Patch(GetMethod<Flammable>("Burn"), prefix: GetHarmonyMethod(GetMethod<Flammable_Burn_FF>("Prefix"))); harmonyTweaks.Patch(GetMethod<FireZone>("OnTriggerStay"), prefix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Postfix"))); } harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("UpdateModifiers"), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_UpdateModifiers>("Postfix"))); harmonyTweaks.Patch(GetMethod<StatueBoss>("Start"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Start_Patch>("Postfix"))); if (ConfigManager.cerberusDashToggle.value) harmonyTweaks.Patch(GetMethod<StatueBoss>("StopDash"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopDash_Patch>("Postfix"))); if(ConfigManager.cerberusParryable.value) { harmonyTweaks.Patch(GetMethod<StatueBoss>("StopTracking"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopTracking_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<StatueBoss>("Stomp"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Stomp_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Statue>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Statue_GetHurt_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Drone_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Drone>("Shoot"), prefix: GetHarmonyMethod(GetMethod<Drone_Shoot_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("PlaySound"), prefix: GetHarmonyMethod(GetMethod<Drone_PlaySound_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Update"), postfix: GetHarmonyMethod(GetMethod<Drone_Update>("Postfix"))); if(ConfigManager.droneHomeToggle.value) { harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Drone_Death_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Drone_GetHurt_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Ferryman>("Start"), postfix: GetHarmonyMethod(GetMethod<FerrymanStart>("Postfix"))); if(ConfigManager.ferrymanComboToggle.value) harmonyTweaks.Patch(GetMethod<Ferryman>("StopMoving"), postfix: GetHarmonyMethod(GetMethod<FerrymanStopMoving>("Postfix"))); if(ConfigManager.filthExplodeToggle.value) harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch2>("Prefix"))); if(ConfigManager.fleshPrisonSpinAttackToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<FleshPrisonShoot>("Postfix"))); if (ConfigManager.hideousMassInsigniaToggle.value) { harmonyTweaks.Patch(GetMethod<Projectile>("Explode"), postfix: GetHarmonyMethod(GetMethod<Projectile_Explode_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Mass>("ShootExplosive"), postfix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Postfix")), prefix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Prefix"))); } harmonyTweaks.Patch(GetMethod<SpiderBody>("Start"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<SpiderBody>("ChargeBeam"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ChargeBeam>("Postfix"))); harmonyTweaks.Patch(GetMethod<SpiderBody>("BeamChargeEnd"), prefix: GetHarmonyMethod(GetMethod<MaliciousFace_BeamChargeEnd>("Prefix"))); if (ConfigManager.maliciousFaceHomingProjectileToggle.value) { harmonyTweaks.Patch(GetMethod<SpiderBody>("ShootProj"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ShootProj_Patch>("Postfix"))); } if (ConfigManager.maliciousFaceRadianceOnEnrage.value) harmonyTweaks.Patch(GetMethod<SpiderBody>("Enrage"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Enrage_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Mindflayer>("Start"), postfix: GetHarmonyMethod(GetMethod<Mindflayer_Start_Patch>("Postfix"))); if (ConfigManager.mindflayerShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<Mindflayer>("ShootProjectiles"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_ShootProjectiles_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_MF>("Prefix"))); } if (ConfigManager.mindflayerTeleportComboToggle.value) { harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Mindflayer>("MeleeTeleport"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_MeleeTeleport_Patch>("Prefix"))); //harmonyTweaks.Patch(GetMethod<SwingCheck2>("DamageStop"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_DamageStop_Patch>("Postfix"))); } if (ConfigManager.minosPrimeRandomTeleportToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("Postfix"))); if (ConfigManager.minosPrimeTeleportTrail.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("Teleport"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("TeleportPostfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Start"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Dropkick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Dropkick>("Prefix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Combo"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Combo>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("StopAction"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_StopAction>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Ascend"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Ascend>("Prefix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Death"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Death>("Prefix"))); if (ConfigManager.minosPrimeCrushAttackToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("RiderKick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_RiderKick>("Prefix"))); if (ConfigManager.minosPrimeComboExplosiveEndToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_ProjectileCharge>("Prefix"))); if (ConfigManager.schismSpreadAttackToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ShootProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ShootProjectile_Patch>("Postfix"))); if (ConfigManager.soliderShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<Solider_Start_Patch>("Postfix"))); } if(ConfigManager.soliderCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_SpawnProjectile_Patch>("Postfix"))); if (ConfigManager.soliderShootGrenadeToggle.value || ConfigManager.soliderShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_ThrowProjectile_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Stalker>("SandExplode"), prefix: GetHarmonyMethod(GetMethod<Stalker_SandExplode_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SandificationZone>("Enter"), postfix: GetHarmonyMethod(GetMethod<SandificationZone_Enter_Patch>("Postfix"))); if (ConfigManager.strayCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Swing>("Postfix"))); if (ConfigManager.strayShootToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_Start_Patch1>("Postfix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ThrowProjectile_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<SwingEnd>("Prefix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("DamageEnd"), prefix: GetHarmonyMethod(GetMethod<DamageEnd>("Prefix"))); } if(ConfigManager.streetCleanerCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<Streetcleaner>("Start"), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Start_Patch>("Postfix"))); if(ConfigManager.streetCleanerPredictiveDodgeToggle.value) harmonyTweaks.Patch(GetMethod<BulletCheck>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<BulletCheck_OnTriggerEnter_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("Start"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Start>("Postfix"))); if (ConfigManager.swordsMachineNoLightKnockbackToggle.value || ConfigManager.swordsMachineSecondPhaseMode.value != ConfigManager.SwordsMachineSecondPhase.None) { harmonyTweaks.Patch(GetMethod<SwordsMachine>("Knockdown"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Knockdown_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("Down"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Prefix"))); //harmonyTweaks.Patch(GetMethod<SwordsMachine>("SetSpeed"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_SetSpeed_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("EndFirstPhase"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Prefix"))); } if (ConfigManager.swordsMachineExplosiveSwordToggle.value) { harmonyTweaks.Patch(GetMethod<ThrownSword>("Start"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<ThrownSword>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_OnTriggerEnter_Patch>("Postfix"))); } harmonyTweaks.Patch(GetMethod<Turret>("Start"), postfix: GetHarmonyMethod(GetMethod<TurretStart>("Postfix"))); if(ConfigManager.turretBurstFireToggle.value) { harmonyTweaks.Patch(GetMethod<Turret>("Shoot"), prefix: GetHarmonyMethod(GetMethod<TurretShoot>("Prefix"))); harmonyTweaks.Patch(GetMethod<Turret>("StartAiming"), postfix: GetHarmonyMethod(GetMethod<TurretAim>("Postfix"))); } harmonyTweaks.Patch(GetMethod<Explosion>("Start"), postfix: GetHarmonyMethod(GetMethod<V2CommonExplosion>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2FirstStart>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2FirstUpdate>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2FirstShootWeapon>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2SecondStart>("Postfix"))); //if(ConfigManager.v2SecondStartEnraged.value) // harmonyTweaks.Patch(GetMethod<BossHealthBar>("OnEnable"), postfix: GetHarmonyMethod(GetMethod<V2SecondEnrage>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2SecondUpdate>("Prefix"))); //harmonyTweaks.Patch(GetMethod<V2>("AltShootWeapon"), postfix: GetHarmonyMethod(GetMethod<V2AltShootWeapon>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("SwitchWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondSwitchWeapon>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Prefix")), postfix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Postfix"))); if(ConfigManager.v2SecondFastCoinToggle.value) harmonyTweaks.Patch(GetMethod<V2>("ThrowCoins"), prefix: GetHarmonyMethod(GetMethod<V2SecondFastCoin>("Prefix"))); harmonyTweaks.Patch(GetMethod<Cannonball>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<V2RocketLauncher>("CannonBallTriggerPrefix"))); if (ConfigManager.v2FirstSharpshooterToggle.value || ConfigManager.v2SecondSharpshooterToggle.value) { harmonyTweaks.Patch(GetMethod<EnemyRevolver>("PrepareAltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverPrepareAltFire>("Prefix"))); harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverBullet>("Prefix"))); harmonyTweaks.Patch(GetMethod<EnemyRevolver>("AltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverAltShoot>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Virtue_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Drone>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Virtue_SpawnInsignia_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Virtue_Death_Patch>("Prefix"))); if (ConfigManager.sisyInstJumpShockwave.value) { harmonyTweaks.Patch(GetMethod<Sisyphus>("Start"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Sisyphus>("Update"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Update>("Postfix"))); } if(ConfigManager.sisyInstBoulderShockwave.value) harmonyTweaks.Patch(GetMethod<Sisyphus>("SetupExplosion"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_SetupExplosion>("Postfix"))); if(ConfigManager.sisyInstStrongerExplosion.value) harmonyTweaks.Patch(GetMethod<Sisyphus>("StompExplosion"), prefix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_StompExplosion>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("Awake"), postfix: GetHarmonyMethod(GetMethod<LeviathanTail_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("BigSplash"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_BigSplash>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_SwingEnd>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("Start"), postfix: GetHarmonyMethod(GetMethod<Leviathan_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurst"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurstStart"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurstStart>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<Leviathan_FixedUpdate>("Prefix"))); if (ConfigManager.somethingWickedSpear.value) { harmonyTweaks.Patch(GetMethod<Wicked>("Start"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_GetHit>("Postfix"))); } if(ConfigManager.somethingWickedSpawnOn43.value) { harmonyTweaks.Patch(GetMethod<ObjectActivator>("Activate"), prefix: GetHarmonyMethod(GetMethod<ObjectActivator_Activate>("Prefix"))); harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<JokeWicked_GetHit>("Postfix"))); } if (ConfigManager.panopticonFullPhase.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Panopticon_Start>("Postfix"))); if (ConfigManager.panopticonAxisBeam.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnInsignia>("Prefix"))); if (ConfigManager.panopticonSpinAttackToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<Panopticon_HomingProjectileAttack>("Postfix"))); if (ConfigManager.panopticonBlackholeProj.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnBlackHole"), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnBlackHole>("Postfix"))); if (ConfigManager.panopticonBalanceEyes.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnFleshDrones"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Postfix"))); if (ConfigManager.panopticonBlueProjToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Update"), transpiler: GetHarmonyMethod(GetMethod<Panopticon_BlueProjectile>("Transpiler"))); if (ConfigManager.idolExplosionToggle.value) harmonyTweaks.Patch(GetMethod<Idol>("Death"), postfix: GetHarmonyMethod(GetMethod<Idol_Death_Patch>("Postfix"))); // ADDME /* harmonyTweaks.Patch(GetMethod<GabrielSecond>("Start"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("BasicCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_BasicCombo>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("FastCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_FastCombo>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("CombineSwords"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_CombineSwords>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("ThrowCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_ThrowCombo>("Postfix"))); */ } private static void PatchAllPlayers() { if (!ConfigManager.playerTweakToggle.value) return; harmonyTweaks.Patch(GetMethod<Punch>("CheckForProjectile"), prefix: GetHarmonyMethod(GetMethod<Punch_CheckForProjectile_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch1>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Collision"), prefix: GetHarmonyMethod(GetMethod<Grenade_Collision_Patch>("Prefix"))); if (ConfigManager.rocketBoostToggle.value) harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_Patch>("Prefix"))); if (ConfigManager.rocketGrabbingToggle.value) harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate_Patch>("Prefix"))); if (ConfigManager.orbStrikeToggle.value) { harmonyTweaks.Patch(GetMethod<Coin>("Start"), postfix: GetHarmonyMethod(GetMethod<Coin_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Punch>("BlastCheck"), prefix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Postfix"))); harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide>("Prefix"))); harmonyTweaks.Patch(GetMethod<Coin>("DelayedReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_DelayedReflectRevolver>("Postfix"))); harmonyTweaks.Patch(GetMethod<Coin>("ReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Postfix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Prefix")), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Postfix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("ExecuteHits"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Prefix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("HitSomething"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Prefix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("Start"), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_Start>("Prefix"))); harmonyTweaks.Patch(GetMethod<Cannonball>("Explode"), prefix: GetHarmonyMethod(GetMethod<Cannonball_Explode>("Prefix"))); harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_CollideOrbital>("Prefix"))); } if(ConfigManager.chargedRevRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<Revolver>("Update"), prefix: GetHarmonyMethod(GetMethod<Revolver_Update>("Prefix"))); if(ConfigManager.coinRegSpeedMulti.value != 1 || ConfigManager.sharpshooterRegSpeedMulti.value != 1 || ConfigManager.railcannonRegSpeedMulti.value != 1 || ConfigManager.rocketFreezeRegSpeedMulti.value != 1 || ConfigManager.rocketCannonballRegSpeedMulti.value != 1 || ConfigManager.nailgunAmmoRegSpeedMulti.value != 1 || ConfigManager.sawAmmoRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<WeaponCharges>("Charge"), prefix: GetHarmonyMethod(GetMethod<WeaponCharges_Charge>("Prefix"))); if(ConfigManager.nailgunHeatsinkRegSpeedMulti.value != 1 || ConfigManager.sawHeatsinkRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<Nailgun>("Update"), prefix: GetHarmonyMethod(GetMethod<NailGun_Update>("Prefix"))); if(ConfigManager.staminaRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<NewMovement>("Update"), prefix: GetHarmonyMethod(GetMethod<NewMovement_Update>("Prefix"))); if(ConfigManager.playerHpDeltaToggle.value || ConfigManager.maxPlayerHp.value != 100 || ConfigManager.playerHpSupercharge.value != 200 || ConfigManager.whiplashHardDamageCap.value != 50 || ConfigManager.whiplashHardDamageSpeed.value != 1) { harmonyTweaks.Patch(GetMethod<NewMovement>("GetHealth"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHealth>("Prefix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("SuperCharge"), prefix: GetHarmonyMethod(GetMethod<NewMovement_SuperCharge>("Prefix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("Respawn"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Respawn>("Postfix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("Start"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Transpiler"))); harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), transpiler: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate>("Transpiler"))); harmonyTweaks.Patch(GetMethod<NewMovement>("ForceAntiHP"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_ForceAntiHP>("Transpiler"))); } // ADDME harmonyTweaks.Patch(GetMethod<Revolver>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Revolver_Shoot>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Shotgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Transpiler")), prefix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Postfix"))); harmonyTweaks.Patch(GetMethod<Shotgun>("ShootSinks"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_ShootSinks>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Nailgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_Shoot>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Nailgun>("SuperSaw"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_SuperSaw>("Transpiler"))); if (ConfigManager.hardDamagePercent.normalizedValue != 1) harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Prefix")), postfix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Postfix"))); harmonyTweaks.Patch(GetMethod<HealthBar>("Start"), postfix: GetHarmonyMethod(GetMethod<HealthBar_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<HealthBar>("Update"), transpiler: GetHarmonyMethod(GetMethod<HealthBar_Update>("Transpiler"))); foreach (HealthBarTracker hb in HealthBarTracker.instances) { if (hb != null) hb.SetSliderRange(); } harmonyTweaks.Patch(GetMethod<Harpoon>("Start"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Start>("Postfix"))); if(ConfigManager.screwDriverHomeToggle.value) harmonyTweaks.Patch(GetMethod<Harpoon>("Punched"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Punched>("Postfix"))); if(ConfigManager.screwDriverSplitToggle.value) harmonyTweaks.Patch(GetMethod<Harpoon>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<Harpoon_OnTriggerEnter_Patch>("Prefix"))); } private static void PatchAllMemes() { if (ConfigManager.enrageSfxToggle.value) harmonyTweaks.Patch(GetMethod<EnrageEffect>("Start"), postfix: GetHarmonyMethod(GetMethod<EnrageEffect_Start>("Postfix"))); if(ConfigManager.funnyDruidKnightSFXToggle.value) { harmonyTweaks.Patch(GetMethod<Mandalore>("FullBurst"), postfix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Postfix")), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<Mandalore>("FullerBurst"), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullerBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Explode"), prefix: GetHarmonyMethod(GetMethod<Drone_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Drone_Explode>("Postfix"))); } if (ConfigManager.fleshObamiumToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Prefix"))); if (ConfigManager.obamapticonToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Prefix"))); } public static bool methodsPatched = false; public static void ScenePatchCheck() { if(methodsPatched && !ultrapainDifficulty) { harmonyTweaks.UnpatchSelf(); methodsPatched = false; } else if(!methodsPatched && ultrapainDifficulty) { PatchAll(); } } public static void PatchAll() { harmonyTweaks.UnpatchSelf(); methodsPatched = false; if (!ultrapainDifficulty) return; if(realUltrapainDifficulty && ConfigManager.discordRichPresenceToggle.value) harmonyTweaks.Patch(GetMethod<DiscordController>("SendActivity"), prefix: GetHarmonyMethod(GetMethod<DiscordController_SendActivity_Patch>("Prefix"))); if (realUltrapainDifficulty && ConfigManager.steamRichPresenceToggle.value) harmonyTweaks.Patch(GetMethod<SteamFriends>("SetRichPresence"), prefix: GetHarmonyMethod(GetMethod<SteamFriends_SetRichPresence_Patch>("Prefix"))); PatchAllEnemies(); PatchAllPlayers(); PatchAllMemes(); methodsPatched = true; } public static string workingPath; public static string workingDir; public static AssetBundle bundle; public static AudioClip druidKnightFullAutoAud; public static AudioClip druidKnightFullerAutoAud; public static AudioClip druidKnightDeathAud; public static AudioClip enrageAudioCustom; public static GameObject fleshObamium; public static GameObject obamapticon; public void Awake() { instance = this; workingPath = Assembly.GetExecutingAssembly().Location; workingDir = Path.GetDirectoryName(workingPath); Logger.LogInfo($"Working path: {workingPath}, Working dir: {workingDir}"); try { bundle = AssetBundle.LoadFromFile(Path.Combine(workingDir, "ultrapain")); druidKnightFullAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullauto.wav"); druidKnightFullerAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullerauto.wav"); druidKnightDeathAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/death.wav"); enrageAudioCustom = bundle.LoadAsset<AudioClip>("assets/ultrapain/sfx/enraged.wav"); fleshObamium = bundle.LoadAsset<GameObject>("assets/ultrapain/fleshprison/fleshobamium.prefab"); obamapticon = bundle.LoadAsset<GameObject>("assets/ultrapain/panopticon/obamapticon.prefab"); } catch (Exception e) { Logger.LogError($"Could not load the asset bundle:\n{e}"); } // DEBUG /*string logPath = Path.Combine(Environment.CurrentDirectory, "log.txt"); Logger.LogInfo($"Saving to {logPath}"); List<string> assetPaths = new List<string>() { "fonts.bundle", "videos.bundle", "shaders.bundle", "particles.bundle", "materials.bundle", "animations.bundle", "prefabs.bundle", "physicsmaterials.bundle", "models.bundle", "textures.bundle", }; //using (FileStream log = File.Open(logPath, FileMode.OpenOrCreate, FileAccess.Write)) //{ foreach(string assetPath in assetPaths) { Logger.LogInfo($"Attempting to load {assetPath}"); AssetBundle bundle = AssetBundle.LoadFromFile(Path.Combine(bundlePath, assetPath)); bundles.Add(bundle); //foreach (string name in bundle.GetAllAssetNames()) //{ // string line = $"[{bundle.name}][{name}]\n"; // log.Write(Encoding.ASCII.GetBytes(line), 0, line.Length); //} bundle.LoadAllAssets(); } //} */ // Plugin startup logic Logger.LogInfo($"Plugin {PluginInfo.PLUGIN_GUID} is loaded!"); harmonyTweaks = new Harmony(PLUGIN_GUID + "_tweaks"); harmonyBase = new Harmony(PLUGIN_GUID + "_base"); harmonyBase.Patch(GetMethod<DifficultySelectButton>("SetDifficulty"), postfix: GetHarmonyMethod(GetMethod<DifficultySelectPatch>("Postfix"))); harmonyBase.Patch(GetMethod<DifficultyTitle>("Check"), postfix: GetHarmonyMethod(GetMethod<DifficultyTitle_Check_Patch>("Postfix"))); harmonyBase.Patch(typeof(PrefsManager).GetConstructor(new Type[0]), postfix: GetHarmonyMethod(GetMethod<PrefsManager_Ctor>("Postfix"))); harmonyBase.Patch(GetMethod<PrefsManager>("EnsureValid"), prefix: GetHarmonyMethod(GetMethod<PrefsManager_EnsureValid>("Prefix"))); harmonyBase.Patch(GetMethod<Grenade>("Explode"), prefix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Prefix")), postfix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Postfix"))); LoadPrefabs(); ConfigManager.Initialize(); SceneManager.activeSceneChanged += OnSceneChange; } } public static class Tools { private static Transform _target; private static Transform target { get { if(_target == null) _target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); return _target; } } public static Vector3 PredictPlayerPosition(float speedMod, Collider enemyCol = null) { Vector3 projectedPlayerPos; if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f) { return target.position; } RaycastHit raycastHit; if (enemyCol != null && Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == enemyCol) { projectedPlayerPos = target.position; } else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { projectedPlayerPos = raycastHit.point; } else { projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod; projectedPlayerPos = new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z); } return projectedPlayerPos; } } // Asset destroyer tracker /*[HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object) })] public class TempClass1 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object), typeof(float) })] public class TempClass2 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object) })] public class TempClass3 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object), typeof(bool) })] public class TempClass4 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } }*/ }
Ultrapain/Plugin.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static ConfigPanel streetCleanerPanel;\n public static ConfigPanel swordsMachinePanel;\n public static ConfigPanel virtuePanel;\n public static ConfigPanel ferrymanPanel;\n public static ConfigPanel turretPanel;\n public static ConfigPanel fleshPrisonPanel;\n public static ConfigPanel minosPrimePanel;\n public static ConfigPanel v2FirstPanel;\n public static ConfigPanel v2SecondPanel;\n public static ConfigPanel sisyInstPanel;", "score": 0.8406050205230713 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static ConfigPanel cerberusPanel;\n public static ConfigPanel dronePanel;\n public static ConfigPanel filthPanel;\n public static ConfigPanel hideousMassPanel;\n public static ConfigPanel maliciousFacePanel;\n public static ConfigPanel mindflayerPanel;\n public static ConfigPanel schismPanel;\n public static ConfigPanel soliderPanel;\n public static ConfigPanel stalkerPanel;\n public static ConfigPanel strayPanel;", "score": 0.8389273285865784 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static ConfigPanel leviathanPanel;\n public static ConfigPanel somethingWickedPanel;\n public static ConfigPanel panopticonPanel;\n public static ConfigPanel idolPanel;\n // GLOBAL ENEMY CONFIG\n public static BoolField friendlyFireDamageOverrideToggle;\n public static FloatSliderField friendlyFireDamageOverrideExplosion;\n public static FloatSliderField friendlyFireDamageOverrideProjectile;\n public static FloatSliderField friendlyFireDamageOverrideFire;\n public static FloatSliderField friendlyFireDamageOverrideMelee;", "score": 0.8384535312652588 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static FloatField shotgunGreenExplosionSpeed;\n public static IntField shotgunGreenExplosionDamage;\n public static IntField shotgunGreenExplosionPlayerDamage;\n // NAILGUN/SAW LAUNCHER\n public static FloatField nailgunBlueDamage;\n public static FloatField nailgunGreenDamage;\n public static FloatField nailgunGreenBurningDamage;\n public static FloatField sawBlueDamage;\n public static FloatField sawBlueHitAmount;\n public static FloatField sawGreenDamage;", "score": 0.8383481502532959 }, { "filename": "Ultrapain/Patches/V2Second.cs", "retrieved_chunk": " public class V2SecondFlag : MonoBehaviour\n {\n public V2RocketLauncher rocketLauncher;\n public V2MaliciousCannon maliciousCannon;\n public Collider v2collider;\n public Transform targetGrenade;\n }\n public class V2RocketLauncher : MonoBehaviour\n {\n public Transform shootPoint;", "score": 0.8269964456558228 } ]
csharp
GameObject maliciousRailcannon;
using objective.Core.Enums; using System; using System.Collections.Generic; using System.Windows; using System.Windows.Media; namespace objective.Models { public class ReportObjectModel { public Type Type { get; set; } public object Content { get; set; } public FontWeight FontWeight { get; set; } public double FontSize { get; set; } = 12; public string Rows { get; set; } public string Columns { get; set; } public double Width { get; set; } = 800; public double Height { get; set; } public Stretch Stretch { get; set; } public Thickness BorderThickness { get; set; } public Brush Background { get; set; } public Brush BorderBrush { get; set; } public double Top { get; set; } = 0; public double Left { get; set; } = 0; public List<ReportObjectModel> CellFields { get; set; } public
CellType CellType {
get; set; } public int RowSpan { get; set; } public int ColumnSpan { get; set; } public string Base64 { get; set; } } }
objective/objective/objective.Core/Models/ReportObjectModel.cs
jamesnet214-objective-0e60b6f
[ { "filename": "objective/objective/objective.Core/Models/ModeModel.cs", "retrieved_chunk": " public string Value { get; set; }\n public ModeModel(string display, string value)\n {\n Display = display;\n Value = value;\n }\n }\n}", "score": 0.8455756306648254 }, { "filename": "objective/objective/objective.Forms/Local/Models/ToolItems.cs", "retrieved_chunk": "namespace objective.Forms.Local.Models\n{\n public class ToolItem\n {\n public string Name { get; set; }\n public ToolItem(string name)\n {\n Name = name;\n }\n }", "score": 0.8147890567779541 }, { "filename": "objective/objective/objective.Forms/UI/Units/CellField.cs", "retrieved_chunk": " get { return (int)GetValue(ColumnSpanProperty); }\n set { SetValue(ColumnSpanProperty, value); }\n }\n public int RowSpan\n {\n get { return (int)GetValue(RowSpanProperty); }\n set { SetValue(RowSpanProperty, value); }\n }\n static CellField()\n {", "score": 0.8042864799499512 }, { "filename": "objective/objective/objective.Core/ReportObject.cs", "retrieved_chunk": " {\n base.OnPropertyChanged(e);\n }\n public abstract void SetLeft(double d);\n public abstract void SetTop(double d);\n public abstract void WidthSync(double d);\n\t\t\t\tpublic T FindParent<T>(DependencyObject child) where T : IReportCanvas\n {\n DependencyObject parent = VisualTreeHelper.GetParent(child);\n if (parent == null)", "score": 0.7876648902893066 }, { "filename": "objective/objective/objective.Forms/Local/Converters/CanvasTopChangeConverter.cs", "retrieved_chunk": " return value;\n }\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}", "score": 0.776502788066864 } ]
csharp
CellType CellType {
using Newtonsoft.Json; namespace DotNetDevBadgeWeb.Model { public class UserSummary { [JsonProperty("likes_given")] public int LikesGiven { get; set; } [JsonProperty("likes_received")] public int LikesReceived { get; set; } [JsonProperty("topics_entered")] public int TopicsEntered { get; set; } [JsonProperty("posts_read_count")] public int PostsReadCount { get; set; } [JsonProperty("days_visited")] public int DaysVisited { get; set; } [JsonProperty("topic_count")] public int TopicCount { get; set; } [JsonProperty("post_count")] public int PostCount { get; set; } [JsonProperty("time_read")] public int TimeRead { get; set; } [JsonProperty("recent_time_read")] public int RecentTimeRead { get; set; } [
JsonProperty("bookmark_count")] public int BookmarkCount {
get; set; } [JsonProperty("can_see_summary_stats")] public bool CanSeeSummaryStats { get; set; } [JsonProperty("solved_count")] public int SolvedCount { get; set; } } }
src/dotnetdev-badge/dotnetdev-badge.web/Model/UserSummary.cs
chanos-dev-dotnetdev-badge-5740a40
[ { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Model/User.cs", "retrieved_chunk": " public string Username { get; set; }\n [JsonProperty(\"name\")]\n public string Name { get; set; }\n [JsonProperty(\"avatar_template\")]\n public string AvatarTemplate { get; set; }\n [JsonProperty(\"flair_name\")]\n public object FlairName { get; set; }\n [JsonProperty(\"trust_level\")]\n public int TrustLevel { get; set; }\n [JsonProperty(\"admin\")]", "score": 0.8375316262245178 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Model/User.cs", "retrieved_chunk": "using DotNetDevBadgeWeb.Common;\nusing Newtonsoft.Json;\nnamespace DotNetDevBadgeWeb.Model\n{\n public class User\n {\n private const int AVATAR_SIZE = 128;\n [JsonProperty(\"id\")]\n public int Id { get; set; }\n [JsonProperty(\"username\")]", "score": 0.727586030960083 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Model/User.cs", "retrieved_chunk": " public bool? Admin { get; set; }\n [JsonProperty(\"moderator\")]\n public bool? Moderator { get; set; }\n public ELevel Level => TrustLevel switch\n {\n 3 => ELevel.Silver,\n 4 => ELevel.Gold,\n _ => ELevel.Bronze,\n };\n public string AvatarEndPoint => AvatarTemplate?.Replace(\"{size}\", AVATAR_SIZE.ToString()) ?? string.Empty;", "score": 0.7017636299133301 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Common/Palette.cs", "retrieved_chunk": " _ => \"CD7F32\",\n };\n }\n internal class ColorSet\n {\n internal string FontColor { get; private set; }\n internal string BackgroundColor { get; private set; }\n internal ColorSet(string fontColor, string backgroundColor)\n {\n FontColor = fontColor;", "score": 0.6782582998275757 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Interfaces/IProvider.cs", "retrieved_chunk": "using DotNetDevBadgeWeb.Model;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IProvider\n {\n Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n }\n}", "score": 0.676323413848877 } ]
csharp
JsonProperty("bookmark_count")] public int BookmarkCount {
using Moadian.Dto; using Moadian.Services; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace Moadian.API { public class Api { private TokenModel? token = null; private readonly string username; private readonly HttpClientService httpClient; public Api(string username, HttpClientService httpClient) { this.username = username; this.httpClient = httpClient; } public async Task<TokenModel> GetToken() { var getTokenDto = new GetTokenDto() { username = this.username }; var packet = new Packet(Constants.PacketType.GET_TOKEN, getTokenDto); packet.retry = false; packet.fiscalId = this.username; var headers = GetEssentialHeaders(); var response = await this.httpClient.SendPacket("req/api/self-tsp/sync/GET_TOKEN", packet, headers); return null; //var tokenData = response["result"]["data"]; //return new TokenModel(tokenData["token"], tokenData["expiresIn"]); } public async Task<dynamic> InquiryByReferenceNumberAsync(string referenceNumber) { var inquiryByReferenceNumberDto = new InquiryByReferenceNumberDto(); inquiryByReferenceNumberDto.SetReferenceNumber(referenceNumber); var packet = new Packet(Constants.PacketType.PACKET_TYPE_INQUIRY_BY_REFERENCE_NUMBER, inquiryByReferenceNumberDto); packet.retry = false; packet.fiscalId = this.username; var headers = GetEssentialHeaders(); headers["Authorization"] = "Bearer " + this.token?.Token; var path = "req/api/self-tsp/sync/" + Constants.PacketType.PACKET_TYPE_INQUIRY_BY_REFERENCE_NUMBER; return await this.httpClient.SendPacket(path, packet, headers); } public async Task<dynamic> GetEconomicCodeInformationAsync(string taxID) { RequireToken(); var packet = new Packet(Constants.PacketType.GET_ECONOMIC_CODE_INFORMATION, JsonConvert.SerializeObject(new { economicCode = taxID })); packet.retry = false; packet.fiscalId = this.username; var headers = GetEssentialHeaders(); headers["Authorization"] = "Bearer " + this.token?.Token; var path = "req/api/self-tsp/sync/" + Constants.PacketType.GET_ECONOMIC_CODE_INFORMATION; return await this.httpClient.SendPacket(path, packet, headers); } public async Task<dynamic> SendInvoicesAsync(List<object> invoiceDtos) { var packets = new List<Packet>(); foreach (var invoiceDto in invoiceDtos) { var packet = new Packet(Constants.PacketType.INVOICE_V01, invoiceDto); packet.uid = "AAA"; packets.Add(packet); } var headers = GetEssentialHeaders(); headers[Constants.TransferConstants.AUTHORIZATION_HEADER] = this.token?.Token; dynamic res = null; try { res = await this.httpClient.SendPackets("req/api/self-tsp/async/normal-enqueue", packets, headers, true, true); } catch (Exception e) { } return res?.GetBody().GetContents(); } public async Task<dynamic> GetFiscalInfoAsync() { RequireToken(); var packet = new Packet(Constants.PacketType.GET_FISCAL_INFORMATION, this.username); var headers = GetEssentialHeaders(); headers["Authorization"] = "Bearer " + this.token?.Token; return await this.httpClient.SendPacket("req/api/self-tsp/sync/GET_FISCAL_INFORMATION", packet, headers); } public Api SetToken(TokenModel? token) { this.token = token; return this; } public dynamic InquiryByReferenceNumber(string referenceNumber) { var inquiryByReferenceNumberDto = new InquiryByReferenceNumberDto(); inquiryByReferenceNumberDto.SetReferenceNumber(referenceNumber); var packet = new Packet(Constants.PacketType.PACKET_TYPE_INQUIRY_BY_REFERENCE_NUMBER, inquiryByReferenceNumberDto); packet.retry = false; packet.fiscalId = this.username; var headers = GetEssentialHeaders(); headers["Authorization"] = "Bearer " + this.token.Token; var path = "req/api/self-tsp/sync/" + Constants.PacketType.PACKET_TYPE_INQUIRY_BY_REFERENCE_NUMBER; return this.httpClient.SendPacket(path, packet, headers); } public dynamic GetEconomicCodeInformation(string taxId) { RequireToken(); var packet = new Packet(Constants.PacketType.GET_ECONOMIC_CODE_INFORMATION, JsonConvert.SerializeObject(new { EconomicCode = taxId })); packet.retry = false; packet.fiscalId = this.username; var headers = GetEssentialHeaders(); headers["Authorization"] = "Bearer " + this.token.Token; var path = "req/api/self-tsp/sync/" + Constants.PacketType.GET_ECONOMIC_CODE_INFORMATION; return this.httpClient.SendPacket(path, packet, headers); } public dynamic SendInvoices(List<
InvoiceDto> invoiceDtos) {
var packets = new List<Packet>(); foreach (var invoiceDto in invoiceDtos) { var packet = new Packet(Constants.PacketType.INVOICE_V01, invoiceDto); packet.uid = "AAA"; packets.Add(packet); } var headers = GetEssentialHeaders(); headers[Constants.TransferConstants.AUTHORIZATION_HEADER] = this.token.Token; dynamic res = null; try { res = this.httpClient.SendPackets( "req/api/self-tsp/async/normal-enqueue", packets, headers, true, true ); } catch (Exception e) { } return res?.GetBody()?.GetContents(); } public dynamic GetFiscalInfo() { RequireToken(); var packet = new Packet(Constants.PacketType.GET_FISCAL_INFORMATION, this.username); var headers = GetEssentialHeaders(); headers["Authorization"] = "Bearer " + this.token.Token; return this.httpClient.SendPacket("req/api/self-tsp/sync/GET_FISCAL_INFORMATION", packet, headers); } private Dictionary<string, string> GetEssentialHeaders() { return new Dictionary<string, string> { { Constants.TransferConstants.TIMESTAMP_HEADER, DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString() }, { Constants.TransferConstants.REQUEST_TRACE_ID_HEADER, Guid.NewGuid().ToString() } }; } private async void RequireToken() { if (this.token == null || this.token.IsExpired()) { this.token = await this.GetToken(); } } } }
API/API.cs
Torabi-srh-Moadian-482c806
[ { "filename": "Moadian.cs", "retrieved_chunk": " throw new ArgumentException(\"Set token before sending invoice!\");\n }\n var headers = new Dictionary<string, string>\n {\n { \"Authorization\", \"Bearer \" + this.token.Token },\n { \"requestTraceId\", Guid.NewGuid().ToString() },\n { \"timestamp\", DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString() },\n };\n var path = \"req/api/self-tsp/async/normal-enqueue\";\n var response = await httpClient.SendPackets(path, new List<Packet>() { packet }, headers, true, true);", "score": 0.8023724555969238 }, { "filename": "Moadian.cs", "retrieved_chunk": " var invoiceIdService = new InvoiceIdService(this.Username);\n return invoiceIdService.GenerateInvoiceId(invoiceCreatedAt, internalInvoiceId);\n }\n public async Task<dynamic> InquiryByReferenceNumber(string referenceNumber)\n {\n var api = new Api(this.Username, httpClient);\n api.SetToken(this.token);\n var response = await api.InquiryByReferenceNumber(referenceNumber);\n return response;\n }", "score": 0.7769482135772705 }, { "filename": "Services/HttpClientService.cs", "retrieved_chunk": " {\n BaseAddress = new Uri(baseUri)\n };\n client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/json\"));\n this.signatureService = signatureService;\n this.encryptionService = encryptionService;\n }\n public async Task<object?> SendPacket(string path, Packet packet, Dictionary<string, string> headers)\n {\n var cloneHeader = new Dictionary<string, string>(headers);", "score": 0.749563992023468 }, { "filename": "Moadian.cs", "retrieved_chunk": " public async Task<dynamic> GetEconomicCodeInformation(string taxID)\n {\n var api = new Api(this.Username, httpClient);\n api.SetToken(this.token);\n var response = await api.GetEconomicCodeInformation(taxID);\n return response;\n }\n public object GetFiscalInfo()\n {\n var api = new Api(this.username, httpClient);", "score": 0.7469037175178528 }, { "filename": "Services/HttpClientService.cs", "retrieved_chunk": " packet.data = (Encoding.UTF8.GetBytes(encryptionService.Encrypt(JsonConvert.SerializeObject(packet.data is string ? packet.data : ((PacketDataInterface)packet.data)?.ToArray()), hex2bin(aesHex), hex2bin(iv))));\n }\n return packets;\n }\n private async Task<HttpResponseMessage> Post(string path, string content, Dictionary<string, string> headers = null)\n {\n var request = new HttpRequestMessage(HttpMethod.Post, path);\n request.Content = new StringContent(content, Encoding.UTF8, \"application/json\");\n if (headers != null)\n {", "score": 0.7304648160934448 } ]
csharp
InvoiceDto> invoiceDtos) {
using JdeJabali.JXLDataTableExtractor.Configuration; using JdeJabali.JXLDataTableExtractor.DataExtraction; using JdeJabali.JXLDataTableExtractor.Exceptions; using JdeJabali.JXLDataTableExtractor.JXLExtractedData; using System; using System.Collections.Generic; using System.Data; using System.Linq; namespace JdeJabali.JXLDataTableExtractor { public class DataTableExtractor : IDataTableExtractorConfiguration, IDataTableExtractorWorkbookConfiguration, IDataTableExtractorSearchConfiguration, IDataTableExtractorWorksheetConfiguration { private bool _readAllWorksheets; private int _searchLimitRow; private int _searchLimitColumn; private readonly List<string> _workbooks = new List<string>(); private readonly List<int> _worksheetIndexes = new List<int>(); private readonly List<string> _worksheets = new List<string>(); private readonly List<HeaderToSearch> _headersToSearch = new List<HeaderToSearch>(); private HeaderToSearch _headerToSearch; private
DataReader _reader;
private DataTableExtractor() { } public static IDataTableExtractorConfiguration Configure() { return new DataTableExtractor(); } public IDataTableExtractorWorkbookConfiguration Workbook(string workbook) { if (string.IsNullOrEmpty(workbook)) { throw new ArgumentException($"{nameof(workbook)} cannot be null or empty."); } // You can't add more than one workbook anyway, so there is no need to check for duplicates. // This would imply that there is a configuration for each workbook. _workbooks.Add(workbook); return this; } public IDataTableExtractorWorkbookConfiguration Workbooks(string[] workbooks) { if (workbooks is null) { throw new ArgumentNullException($"{nameof(workbooks)} cannot be null."); } foreach (string workbook in workbooks) { if (_workbooks.Contains(workbook)) { throw new DuplicateWorkbookException("Cannot search for more than one workbook with the same name: " + $@"""{workbook}""."); } _workbooks.Add(workbook); } return this; } public IDataTableExtractorSearchConfiguration SearchLimits(int searchLimitRow, int searchLimitColumn) { _searchLimitRow = searchLimitRow; _searchLimitColumn = searchLimitColumn; return this; } public IDataTableExtractorSearchConfiguration Worksheet(int worksheetIndex) { if (worksheetIndex < 0) { throw new ArgumentException($"{nameof(worksheetIndex)} cannot be less than zero."); } if (_worksheetIndexes.Contains(worksheetIndex)) { throw new ArgumentException("Cannot search for more than one worksheet with the same name: " + $@"""{worksheetIndex}""."); } _worksheetIndexes.Add(worksheetIndex); return this; } public IDataTableExtractorSearchConfiguration Worksheets(int[] worksheetIndexes) { if (worksheetIndexes is null) { throw new ArgumentException($"{nameof(worksheetIndexes)} cannot be null or empty."); } _worksheetIndexes.AddRange(worksheetIndexes); return this; } public IDataTableExtractorSearchConfiguration Worksheet(string worksheet) { if (string.IsNullOrEmpty(worksheet)) { throw new ArgumentException($"{nameof(worksheet)} cannot be null or empty."); } if (_worksheets.Contains(worksheet)) { throw new ArgumentException("Cannot search for more than one worksheet with the same name: " + $@"""{worksheet}""."); } _worksheets.Add(worksheet); return this; } public IDataTableExtractorSearchConfiguration Worksheets(string[] worksheets) { if (worksheets is null) { throw new ArgumentException($"{nameof(worksheets)} cannot be null or empty."); } _worksheets.AddRange(worksheets); return this; } public IDataTableExtractorWorksheetConfiguration ReadOnlyTheIndicatedSheets() { _readAllWorksheets = false; if (_worksheetIndexes.Count == 0 && _worksheets.Count == 0) { throw new InvalidOperationException("No worksheets selected."); } return this; } public IDataTableExtractorWorksheetConfiguration ReadAllWorksheets() { _readAllWorksheets = true; return this; } IDataTableExtractorWorksheetConfiguration IDataTableColumnsToSearch.ColumnHeader(string columnHeader) { if (string.IsNullOrEmpty(columnHeader)) { throw new ArgumentException($"{nameof(columnHeader)} cannot be null or empty."); } if (_headersToSearch.FirstOrDefault(h => h.ColumnHeaderName == columnHeader) != null) { throw new DuplicateColumnException("Cannot search for more than one column header with the same name: " + $@"""{columnHeader}""."); } _headerToSearch = new HeaderToSearch() { ColumnHeaderName = columnHeader, }; _headersToSearch.Add(_headerToSearch); return this; } IDataTableExtractorWorksheetConfiguration IDataTableColumnsToSearch.ColumnIndex(int columnIndex) { if (columnIndex < 0) { throw new ArgumentException($"{nameof(columnIndex)} cannot be less than zero."); } if (_headersToSearch.FirstOrDefault(h => h.ColumnIndex == columnIndex) != null) { throw new DuplicateColumnException("Cannot search for more than one column with the same index: " + $@"""{columnIndex}""."); } _headerToSearch = new HeaderToSearch() { ColumnIndex = columnIndex, }; _headersToSearch.Add(_headerToSearch); return this; } IDataTableExtractorWorksheetConfiguration IDataTableColumnsToSearch.CustomColumnHeaderMatch(Func<string, bool> conditional) { if (conditional is null) { throw new ArgumentNullException("Conditional cannot be null."); } _headerToSearch = new HeaderToSearch() { ConditionalToReadColumnHeader = conditional, }; _headersToSearch.Add(_headerToSearch); return this; } IDataTableExtractorWorksheetConfiguration IDataTableExtractorColumnConfiguration.ConditionToExtractRow(Func<string, bool> conditional) { if (conditional is null) { throw new ArgumentNullException("Conditional cannot be null."); } if (_headerToSearch is null) { throw new InvalidOperationException(nameof(_headerToSearch)); } _headerToSearch.ConditionalToReadRow = conditional; return this; } public List<JXLWorkbookData> GetWorkbooksData() { _reader = new DataReader() { Workbooks = _workbooks, SearchLimitRow = _searchLimitRow, SearchLimitColumn = _searchLimitColumn, WorksheetIndexes = _worksheetIndexes, Worksheets = _worksheets, ReadAllWorksheets = _readAllWorksheets, HeadersToSearch = _headersToSearch, }; return _reader.GetWorkbooksData(); } public List<JXLExtractedRow> GetExtractedRows() { _reader = new DataReader() { Workbooks = _workbooks, SearchLimitRow = _searchLimitRow, SearchLimitColumn = _searchLimitColumn, WorksheetIndexes = _worksheetIndexes, Worksheets = _worksheets, ReadAllWorksheets = _readAllWorksheets, HeadersToSearch = _headersToSearch, }; return _reader.GetJXLExtractedRows(); } public DataTable GetDataTable() { _reader = new DataReader() { Workbooks = _workbooks, SearchLimitRow = _searchLimitRow, SearchLimitColumn = _searchLimitColumn, WorksheetIndexes = _worksheetIndexes, Worksheets = _worksheets, ReadAllWorksheets = _readAllWorksheets, HeadersToSearch = _headersToSearch, }; return _reader.GetDataTable(); } } }
JdeJabali.JXLDataTableExtractor/DataTableExtractor.cs
JdeJabali-JXLDataTableExtractor-90a12f4
[ { "filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs", "retrieved_chunk": " {\n public List<string> Workbooks { get; set; } = new List<string>();\n public int SearchLimitRow { get; set; }\n public int SearchLimitColumn { get; set; }\n public List<int> WorksheetIndexes { get; set; } = new List<int>();\n public List<string> Worksheets { get; set; } = new List<string>();\n public bool ReadAllWorksheets { get; set; }\n public List<HeaderToSearch> HeadersToSearch { get; set; } = new List<HeaderToSearch>();\n public DataTable GetDataTable()\n {", "score": 0.7961337566375732 }, { "filename": "JdeJabali.JXLDataTableExtractor/Configuration/IDataTableExtractorSearchConfiguration.cs", "retrieved_chunk": " /// <exception cref=\"ArgumentException\"/>\n IDataTableExtractorSearchConfiguration Worksheets(string[] worksheets);\n /// <summary>\n /// Read all the worksheets in the workbook(s) specified.\n /// </summary>\n /// <returns></returns>\n IDataTableExtractorWorksheetConfiguration ReadAllWorksheets();\n IDataTableExtractorWorksheetConfiguration ReadOnlyTheIndicatedSheets();\n }\n}", "score": 0.7189111113548279 }, { "filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs", "retrieved_chunk": " }\n return extractedRow;\n }\n private void GetHeadersCoordinates(ExcelWorksheet sheet)\n {\n AddHeaderCoordsFromWorksheetColumnConfigurations(sheet);\n AddHeaderCoordsFromWorksheetColumnIndexesConfigurations();\n AddHeaderCoordsFromCustomColumnHeaderMatch(sheet);\n }\n private void AddHeaderCoordsFromWorksheetColumnConfigurations(ExcelWorksheet sheet)", "score": 0.7181342840194702 }, { "filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs", "retrieved_chunk": " headerToSearch.HeaderCoord = new HeaderCoord\n {\n Row = 1,\n Column = headerToSearch.ColumnIndex.Value,\n };\n }\n }\n private void AddHeaderCoordsFromCustomColumnHeaderMatch(ExcelWorksheet sheet)\n {\n List<HeaderToSearch> headersToSearch = HeadersToSearch", "score": 0.7177284955978394 }, { "filename": "JdeJabali.JXLDataTableExtractor/JXLExtractedData/JXLWorkbookData.cs", "retrieved_chunk": "using System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLWorkbookData\n {\n public string WorkbookPath { get; set; } = string.Empty;\n public string WorkbookName { get; set; } = string.Empty;\n public List<JXLWorksheetData> WorksheetsData { get; set; } = new List<JXLWorksheetData>();\n }\n}", "score": 0.7176636457443237 } ]
csharp
DataReader _reader;
using VRC.SDK3.Data; using Koyashiro.GenericDataContainer.Internal; namespace Koyashiro.GenericDataContainer { public static class DataListExt { public static int Capacity<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); return dataList.Capacity; } public static int Count<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); return dataList.Count; } public static void Add<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); dataList.Add(token); } public static void AddRange<T>(this DataList<T> list, T[] collection) { foreach (var item in collection) { list.Add(item); } } public static void AddRange<T>(this DataList<T> list, DataList<T> collection) { var dataList = (DataList)(object)(list); var tokens = (DataList)(object)collection; dataList.AddRange(tokens); } public static void BinarySearch<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); dataList.BinarySearch(token); } public static void BinarySearch<T>(this DataList<T> list, int index, int count, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); dataList.BinarySearch(index, count, token); } public static void Clear<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); dataList.Clear(); } public static bool Contains<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.Contains(token); } public static
DataList<T> DeepClone<T>(this DataList<T> list) {
var dataList = (DataList)(object)(list); return (DataList<T>)(object)dataList.DeepClone(); } public static DataList<T> GetRange<T>(this DataList<T> list, int index, int count) { var dataList = (DataList)(object)(list); return (DataList<T>)(object)dataList.GetRange(index, count); } public static int IndexOf<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.IndexOf(token); } public static int IndexOf<T>(this DataList<T> list, T item, int index) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.IndexOf(token, index); } public static int IndexOf<T>(this DataList<T> list, T item, int index, int count) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.IndexOf(token, index, count); } public static void Insert<T>(this DataList<T> list, int index, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); dataList.Insert(index, token); } public static void InsertRange<T>(this DataList<T> list, int index, T[] collection) { for (var i = index; i < collection.Length; i++) { list.Insert(i, collection[i]); } } public static void InsertRange<T>(this DataList<T> list, int index, DataList<T> collection) { var dataList = (DataList)(object)(list); var tokens = (DataList)(object)collection; dataList.InsertRange(index, tokens); } public static int LastIndexOf<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.LastIndexOf(token); } public static int LastIndexOf<T>(this DataList<T> list, T item, int index) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.LastIndexOf(token, index); } public static int LastIndexOf<T>(this DataList<T> list, T item, int index, int count) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.LastIndexOf(token, index, count); } public static bool Remove<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.Remove(token); } public static bool RemoveAll<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.RemoveAll(token); } public static void RemoveAt<T>(this DataList<T> list, int index) { var dataList = (DataList)(object)(list); dataList.RemoveAt(index); } public static void RemoveRange<T>(this DataList<T> list, int index, int count) { var dataList = (DataList)(object)(list); dataList.RemoveRange(index, count); } public static void Reverse<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); dataList.Reverse(); } public static void Reverse<T>(this DataList<T> list, int index, int count) { var dataList = (DataList)(object)(list); dataList.Reverse(index, count); } public static void SetValue<T>(this DataList<T> list, int index, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); dataList.SetValue(index, token); } public static DataList<T> ShallowClone<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); return (DataList<T>)(object)dataList.ShallowClone(); } public static void Sort<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); dataList.Sort(); } public static void Sort<T>(this DataList<T> list, int index, int count) { var dataList = (DataList)(object)(list); dataList.Sort(index, count); } public static T[] ToArray<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); var length = dataList.Count; var array = new T[length]; for (var i = 0; i < length; i++) { var token = dataList[i]; switch (token.TokenType) { case TokenType.Reference: array[i] = (T)token.Reference; break; default: array[i] = (T)(object)token; break; } } return array; } public static object[] ToObjectArray<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); var length = dataList.Count; var array = new object[length]; for (var i = 0; i < length; i++) { var token = dataList[i]; switch (token.TokenType) { case TokenType.Reference: array[i] = (T)token.Reference; break; default: array[i] = (T)(object)token; break; } } return array; } public static void TrimExcess<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); dataList.TrimExcess(); } public static bool TryGetValue<T>(this DataList<T> list, int index, out T value) { var dataList = (DataList)(object)(list); if (!dataList.TryGetValue(index, out var token)) { value = default; return false; } switch (token.TokenType) { case TokenType.Reference: value = (T)token.Reference; break; default: value = (T)(object)token; break; } return true; } public static T GetValue<T>(this DataList<T> list, int index) { var dataList = (DataList)(object)(list); var token = dataList[index]; switch (token.TokenType) { case TokenType.Reference: return (T)token.Reference; default: return (T)(object)token; } } } }
Packages/net.koyashiro.genericdatacontainer/Runtime/DataListExt.cs
koyashiro-generic-data-container-1aef372
[ { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataList.cs", "retrieved_chunk": " {\n return (DataList<T>)(object)new DataList();\n }\n public static DataList<T> New(params T[] array)\n {\n var tokens = DataTokenUtil.NewDataTokens(array);\n return (DataList<T>)(object)new DataList(tokens);\n }\n }\n}", "score": 0.8687503933906555 }, { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataDictionaryExt.cs", "retrieved_chunk": " var dataDictionary = (DataDictionary)(object)(dictionary);\n dataDictionary.Clear();\n }\n public static bool ContainsKey<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TKey key)\n {\n var dataDictionary = (DataDictionary)(object)(dictionary);\n var keyToken = DataTokenUtil.NewDataToken(key);\n return dataDictionary.ContainsKey(keyToken);\n }\n public static bool ContainsValue<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TValue value)", "score": 0.8536534905433655 }, { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataDictionaryExt.cs", "retrieved_chunk": " return result;\n }\n public static void SetValue<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TKey key, TValue value)\n {\n var dataDictionary = (DataDictionary)(object)(dictionary);\n var keyToken = DataTokenUtil.NewDataToken(key);\n var keyValue = DataTokenUtil.NewDataToken(value);\n dataDictionary.SetValue(keyToken, keyValue);\n }\n public static DataDictionary<TKey, TValue> ShallowClone<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary)", "score": 0.8433005809783936 }, { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataDictionaryExt.cs", "retrieved_chunk": " {\n var dataDictionary = (DataDictionary)(object)(dictionary);\n var keyValue = DataTokenUtil.NewDataToken(value);\n return dataDictionary.ContainsValue(keyValue);\n }\n public static DataDictionary<TKey, TValue> DeepClohne<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary)\n {\n var dataDictionary = (DataDictionary)(object)(dictionary);\n return (DataDictionary<TKey, TValue>)(object)dataDictionary.DeepClone();\n }", "score": 0.8430764675140381 }, { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataDictionaryExt.cs", "retrieved_chunk": " }\n public static void Add<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TKey key, TValue value)\n {\n var dataDictionary = (DataDictionary)(object)(dictionary);\n var keyToken = DataTokenUtil.NewDataToken(key);\n var valueToken = DataTokenUtil.NewDataToken(value);\n dataDictionary.Add(keyToken, valueToken);\n }\n public static void Clear<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary)\n {", "score": 0.8430166244506836 } ]
csharp
DataList<T> DeepClone<T>(this DataList<T> list) {
using BepInEx; using BepInEx.Configuration; using Comfort.Common; using EFT; using LootingBots.Patch.Components; using LootingBots.Patch.Util; using LootingBots.Patch; using LootingBots.Brain; using DrakiaXYZ.BigBrain.Brains; using System.Collections.Generic; using HandbookClass = GClass2775; namespace LootingBots { [BepInPlugin(MOD_GUID, MOD_NAME, MOD_VERSION)] [BepInDependency("xyz.drakia.bigbrain", "0.1.4")] [BepInProcess("EscapeFromTarkov.exe")] public class LootingBots : BaseUnityPlugin { private const string MOD_GUID = "me.skwizzy.lootingbots"; private const string MOD_NAME = "LootingBots"; private const string MOD_VERSION = "1.1.2"; public const BotType SettingsDefaults = BotType.Scav | BotType.Pmc | BotType.Raider; // Loot Finder Settings public static ConfigEntry<BotType> CorpseLootingEnabled; public static ConfigEntry<BotType> ContainerLootingEnabled; public static ConfigEntry<BotType> LooseItemLootingEnabled; public static ConfigEntry<float> TimeToWaitBetweenLoot; public static ConfigEntry<float> DetectItemDistance; public static ConfigEntry<float> DetectContainerDistance; public static ConfigEntry<float> DetectCorpseDistance; public static ConfigEntry<bool> DebugLootNavigation; public static ConfigEntry<LogLevel> LootingLogLevels; public static Log LootLog; // Loot Settings public static ConfigEntry<bool> UseMarketPrices; public static ConfigEntry<bool> ValueFromMods; public static ConfigEntry<bool> CanStripAttachments; public static ConfigEntry<float> PMCLootThreshold; public static ConfigEntry<float> ScavLootThreshold; public static ConfigEntry<EquipmentType> PMCGearToEquip; public static ConfigEntry<EquipmentType> PMCGearToPickup; public static ConfigEntry<
EquipmentType> ScavGearToEquip;
public static ConfigEntry<EquipmentType> ScavGearToPickup; public static ConfigEntry<LogLevel> ItemAppraiserLogLevels; public static Log ItemAppraiserLog; public static ItemAppraiser ItemAppraiser = new ItemAppraiser(); public void LootFinderSettings() { CorpseLootingEnabled = Config.Bind( "Loot Finder", "Enable corpse looting", SettingsDefaults, new ConfigDescription( "Enables corpse looting for the selected bot types", null, new ConfigurationManagerAttributes { Order = 10 } ) ); DetectCorpseDistance = Config.Bind( "Loot Finder", "Detect corpse distance", 75f, new ConfigDescription( "Distance (in meters) a bot is able to detect a corpse", null, new ConfigurationManagerAttributes { Order = 9 } ) ); ContainerLootingEnabled = Config.Bind( "Loot Finder", "Enable container looting", SettingsDefaults, new ConfigDescription( "Enables container looting for the selected bot types", null, new ConfigurationManagerAttributes { Order = 8 } ) ); DetectContainerDistance = Config.Bind( "Loot Finder", "Detect container distance", 75f, new ConfigDescription( "Distance (in meters) a bot is able to detect a container", null, new ConfigurationManagerAttributes { Order = 7 } ) ); LooseItemLootingEnabled = Config.Bind( "Loot Finder", "Enable loose item looting", SettingsDefaults, new ConfigDescription( "Enables loose item looting for the selected bot types", null, new ConfigurationManagerAttributes { Order = 6 } ) ); DetectItemDistance = Config.Bind( "Loot Finder", "Detect item distance", 75f, new ConfigDescription( "Distance (in meters) a bot is able to detect an item", null, new ConfigurationManagerAttributes { Order = 5 } ) ); TimeToWaitBetweenLoot = Config.Bind( "Loot Finder", "Delay between looting", 15f, new ConfigDescription( "The amount of time the bot will wait after looting an container/item/corpse before trying to find the next nearest item/container/corpse", null, new ConfigurationManagerAttributes { Order = 2 } ) ); LootingLogLevels = Config.Bind( "Loot Finder", "Log Levels", LogLevel.Error | LogLevel.Info, new ConfigDescription( "Enable different levels of log messages to show in the logs", null, new ConfigurationManagerAttributes { Order = 1 } ) ); DebugLootNavigation = Config.Bind( "Loot Finder", "Debug: Show navigation points", false, new ConfigDescription( "Renders shperes where bots are trying to navigate when container looting. (Red): Container position. (Black): 'Optimized' container position. (Green): Calculated bot destination. (Blue): NavMesh corrected destination (where the bot will move).", null, new ConfigurationManagerAttributes { Order = 0 } ) ); } public void LootSettings() { UseMarketPrices = Config.Bind( "Loot Settings", "Use flea market prices", false, new ConfigDescription( "Bots will query more accurate ragfair prices to do item value checks. Will make a query to get ragfair prices when the client is first started", null, new ConfigurationManagerAttributes { Order = 10 } ) ); ValueFromMods = Config.Bind( "Loot Settings", "Calculate weapon value from attachments", true, new ConfigDescription( "Calculate weapon value by looking up each attachement. More accurate than just looking at the base weapon template but a slightly more expensive check", null, new ConfigurationManagerAttributes { Order = 9 } ) ); CanStripAttachments = Config.Bind( "Loot Settings", "Allow weapon attachment stripping", true, new ConfigDescription( "Allows bots to take the attachments off of a weapon if they are not able to pick the weapon up into their inventory", null, new ConfigurationManagerAttributes { Order = 8 } ) ); PMCLootThreshold = Config.Bind( "Loot Settings", "PMC: Loot value threshold", 12000f, new ConfigDescription( "PMC bots will only loot items that exceed the specified value in roubles", null, new ConfigurationManagerAttributes { Order = 6 } ) ); PMCGearToEquip = Config.Bind( "Loot Settings", "PMC: Allowed gear to equip", EquipmentType.All, new ConfigDescription( "The equipment a PMC bot is able to equip during raid", null, new ConfigurationManagerAttributes { Order = 5 } ) ); PMCGearToPickup = Config.Bind( "Loot Settings", "PMC: Allowed gear in bags", EquipmentType.All, new ConfigDescription( "The equipment a PMC bot is able to place in their backpack/rig", null, new ConfigurationManagerAttributes { Order = 4 } ) ); ScavLootThreshold = Config.Bind( "Loot Settings", "Scav: Loot value threshold", 5000f, new ConfigDescription( "All non-PMC bots will only loot items that exceed the specified value in roubles.", null, new ConfigurationManagerAttributes { Order = 3 } ) ); ScavGearToEquip = Config.Bind( "Loot Settings", "Scav: Allowed gear to equip", EquipmentType.All, new ConfigDescription( "The equipment a non-PMC bot is able to equip during raid", null, new ConfigurationManagerAttributes { Order = 2 } ) ); ScavGearToPickup = Config.Bind( "Loot Settings", "Scav: Allowed gear in bags", EquipmentType.All, new ConfigDescription( "The equipment a non-PMC bot is able to place in their backpack/rig", null, new ConfigurationManagerAttributes { Order = 1 } ) ); ItemAppraiserLogLevels = Config.Bind( "Loot Settings", "Log Levels", LogLevel.Error, new ConfigDescription( "Enables logs for the item apprasier that calcualtes the weapon values", null, new ConfigurationManagerAttributes { Order = 0 } ) ); } public void Awake() { LootFinderSettings(); LootSettings(); LootLog = new Log(Logger, LootingLogLevels); ItemAppraiserLog = new Log(Logger, ItemAppraiserLogLevels); new SettingsAndCachePatch().Enable(); new RemoveComponent().Enable(); BrainManager.RemoveLayer( "Utility peace", new List<string>() { "Assault", "ExUsec", "BossSanitar", "CursAssault", "PMC", "SectantWarrior" } ); BrainManager.AddCustomLayer( typeof(LootingLayer), new List<string>() { "Assault", "BossSanitar", "CursAssault", "BossKojaniy", "SectantPriest", "FollowerGluharScout", "FollowerGluharProtect", "FollowerGluharAssault", "BossGluhar", "Fl_Zraychiy", "TagillaFollower", "FollowerSanitar", "FollowerBully", "BirdEye", "BigPipe", "Knight", "BossZryachiy", "Tagilla", "Killa", "BossSanitar", "BossBully" }, 2 ); BrainManager.AddCustomLayer( typeof(LootingLayer), new List<string>() { "PMC", "ExUsec" }, 3 ); BrainManager.AddCustomLayer( typeof(LootingLayer), new List<string>() { "SectantWarrior" }, 13 ); } public void Update() { bool shoultInitAppraiser = (!UseMarketPrices.Value && ItemAppraiser.HandbookData == null) || (UseMarketPrices.Value && !ItemAppraiser.MarketInitialized); // Initialize the itemAppraiser when the BE instance comes online if ( Singleton<ClientApplication<ISession>>.Instance != null && Singleton<HandbookClass>.Instance != null && shoultInitAppraiser ) { LootLog.LogInfo($"Initializing item appraiser"); ItemAppraiser.Init(); } } } }
LootingBots/LootingBots.cs
Skwizzy-SPT-LootingBots-76279a3
[ { "filename": "LootingBots/components/ItemAppraiser.cs", "retrieved_chunk": " public class ItemAppraiser\n {\n public Log Log;\n public Dictionary<string, EFT.HandBook.HandbookData> HandbookData;\n public Dictionary<string, float> MarketData;\n public bool MarketInitialized = false;\n public void Init()\n {\n Log = LootingBots.ItemAppraiserLog;\n if (LootingBots.UseMarketPrices.Value)", "score": 0.8066837787628174 }, { "filename": "LootingBots/components/InventoryController.cs", "retrieved_chunk": " {\n public float NetLootValue;\n public int AvailableGridSpaces;\n public int TotalGridSpaces;\n public GearValue WeaponValues = new GearValue();\n public void AddNetValue(float itemPrice)\n {\n NetLootValue += itemPrice;\n }\n public void SubtractNetValue(float itemPrice)", "score": 0.783610999584198 }, { "filename": "LootingBots/utils/EquipmentTypes.cs", "retrieved_chunk": " public static class EquipmentTypeUtils\n {\n public static bool HasBackpack(this EquipmentType equipmentType)\n {\n return equipmentType.HasFlag(EquipmentType.Backpack);\n }\n public static bool HasTacticalRig(this EquipmentType equipmentType)\n {\n return equipmentType.HasFlag(EquipmentType.TacticalRig);\n }", "score": 0.783515989780426 }, { "filename": "LootingBots/logics/FindLootLogic.cs", "retrieved_chunk": " {\n private readonly LootingBrain _lootingBrain;\n private readonly BotLog _log;\n private float DetectCorpseDistance\n {\n get { return Mathf.Pow(LootingBots.DetectCorpseDistance.Value, 2); }\n }\n private float DetectContainerDistance\n {\n get { return Mathf.Pow(LootingBots.DetectContainerDistance.Value, 2); }", "score": 0.7646801471710205 }, { "filename": "LootingBots/utils/EquipmentTypes.cs", "retrieved_chunk": " public static bool HasArmoredRig(this EquipmentType equipmentType)\n {\n return equipmentType.HasFlag(EquipmentType.ArmoredRig);\n }\n public static bool HasArmorVest(this EquipmentType equipmentType)\n {\n return equipmentType.HasFlag(EquipmentType.ArmorVest);\n }\n public static bool HasGrenade(this EquipmentType equipmentType)\n {", "score": 0.7604314684867859 } ]
csharp
EquipmentType> ScavGearToEquip;
using System; using System.Collections.Generic; using System.Text; using UnityEngine; using UnityEngine.SceneManagement; namespace Ultrapain.Patches { class SomethingWickedFlag : MonoBehaviour { public GameObject spear; public
MassSpear spearComp;
public EnemyIdentifier eid; public Transform spearOrigin; public Rigidbody spearRb; public static float SpearTriggerDistance = 80f; public static LayerMask envMask = new LayerMask() { value = (1 << 8) | (1 << 24) }; void Awake() { if (eid == null) eid = GetComponent<EnemyIdentifier>(); if (spearOrigin == null) { GameObject obj = new GameObject(); obj.transform.parent = transform; obj.transform.position = GetComponent<Collider>().bounds.center; obj.SetActive(false); spearOrigin = obj.transform; } } void Update() { if(spear == null) { Vector3 playerCenter = NewMovement.Instance.playerCollider.bounds.center; float distanceFromPlayer = Vector3.Distance(spearOrigin.position, playerCenter); if (distanceFromPlayer < SpearTriggerDistance) { if(!Physics.Raycast(transform.position, playerCenter - transform.position, distanceFromPlayer, envMask)) { spear = GameObject.Instantiate(Plugin.hideousMassSpear, transform); spear.transform.position = spearOrigin.position; spear.transform.LookAt(playerCenter); spear.transform.position += spear.transform.forward * 5; spearComp = spear.GetComponent<MassSpear>(); spearRb = spearComp.GetComponent<Rigidbody>(); spearComp.originPoint = spearOrigin; spearComp.damageMultiplier = 0f; spearComp.speedMultiplier = 2; } } } else if(spearComp.beenStopped) { if (!spearComp.transform.parent || spearComp.transform.parent.tag != "Player") if(spearRb.isKinematic == true) GameObject.Destroy(spear); } } } class SomethingWicked_Start { static void Postfix(Wicked __instance) { SomethingWickedFlag flag = __instance.gameObject.AddComponent<SomethingWickedFlag>(); } } class SomethingWicked_GetHit { static void Postfix(Wicked __instance) { SomethingWickedFlag flag = __instance.GetComponent<SomethingWickedFlag>(); if (flag == null) return; if (flag.spear != null) GameObject.Destroy(flag.spear); } } class JokeWicked : MonoBehaviour { void OnDestroy() { MusicManager.Instance.ForceStartMusic(); } } class JokeWicked_GetHit { static void Postfix(Wicked __instance) { if (__instance.GetComponent<JokeWicked>() == null) return; GameObject.Destroy(__instance.gameObject); } } class ObjectActivator_Activate { static bool Prefix(ObjectActivator __instance) { if (SceneManager.GetActiveScene().name != "38748a67bc9e67a43956a92f87d1e742") return true; if(__instance.name == "Scream") { GameObject goreZone = new GameObject(); goreZone.AddComponent<GoreZone>(); Vector3 spawnPos = new Vector3(86.7637f, -39.9667f, 635.7572f); if (Physics.Raycast(spawnPos + Vector3.up, Vector3.down, out RaycastHit hit, 100f, new LayerMask() { value = (1 << 8) | (1 << 24) }, QueryTriggerInteraction.Ignore)) spawnPos = hit.point; GameObject wicked = GameObject.Instantiate(Plugin.somethingWicked, spawnPos, Quaternion.identity, goreZone.transform); ; wicked.AddComponent<JokeWicked>(); Wicked comp = wicked.GetComponent<Wicked>(); comp.patrolPoints = new Transform[] { __instance.transform }; wicked.AddComponent<JokeWicked>(); } else if(__instance.name == "Hint 1") { return false; } return true; } } }
Ultrapain/Patches/SomethingWicked.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Stray.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nusing UnityEngine.AI;\nnamespace Ultrapain.Patches\n{\n public class StrayFlag : MonoBehaviour\n {\n //public int extraShotsRemaining = 6;\n private Animator anim;\n private EnemyIdentifier eid;", "score": 0.8677114248275757 }, { "filename": "Ultrapain/Patches/SwordsMachine.cs", "retrieved_chunk": "using HarmonyLib;\nusing System.Security.Cryptography;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class SwordsMachineFlag : MonoBehaviour\n {\n public SwordsMachine sm;\n public Animator anim;\n public EnemyIdentifier eid;", "score": 0.8592872619628906 }, { "filename": "Ultrapain/Patches/Parry.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class GrenadeParriedFlag : MonoBehaviour\n {\n public int parryCount = 1;\n public bool registeredStyle = false;\n public bool bigExplosionOverride = false;\n public GameObject temporaryExplosion;", "score": 0.8556129336357117 }, { "filename": "Ultrapain/Patches/MaliciousFace.cs", "retrieved_chunk": "using HarmonyLib;\nusing System;\nusing System.ComponentModel;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class MaliciousFaceFlag : MonoBehaviour\n {\n public bool charging = false;\n }", "score": 0.8514493703842163 }, { "filename": "Ultrapain/Patches/HideousMass.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n public class HideousMassProjectile : MonoBehaviour\n {\n public float damageBuf = 1f;\n public float speedBuf = 1f;\n }\n public class Projectile_Explode_Patch ", "score": 0.8268824219703674 } ]
csharp
MassSpear spearComp;
using UnityEditor; using UnityEditor.Timeline; using UnityEngine; using UnityEngine.Timeline; namespace dev.kemomimi.TimelineExtension.AbstractValueControlTrack.Editor { internal static class AbstractIntValueControlTrackEditorUtility { internal static Color PrimaryColor = new(1f, 1f, 0.5f); } [CustomTimelineEditor(typeof(
AbstractIntValueControlTrack))] public class AbstractIntValueControlTrackCustomEditor : TrackEditor {
public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding) { track.name = "CustomTrack"; var options = base.GetTrackOptions(track, binding); options.trackColor = AbstractIntValueControlTrackEditorUtility.PrimaryColor; return options; } } [CustomTimelineEditor(typeof(AbstractIntValueControlClip))] public class AbstractIntValueControlCustomEditor : ClipEditor { public override ClipDrawOptions GetClipOptions(TimelineClip clip) { var clipOptions = base.GetClipOptions(clip); clipOptions.icons = null; clipOptions.highlightColor = AbstractIntValueControlTrackEditorUtility.PrimaryColor; return clipOptions; } } [CanEditMultipleObjects] [CustomEditor(typeof(AbstractIntValueControlClip))] public class AbstractIntValueControlClipEditor : UnityEditor.Editor { public override void OnInspectorGUI() { DrawDefaultInspector(); } } }
Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractIntValueControlTrackCustomEditor.cs
nmxi-Unity_AbstractTimelineExtention-b518049
[ { "filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractFloatValueControlTrackCustomEditor.cs", "retrieved_chunk": "using UnityEditor;\nusing UnityEditor.Timeline;\nusing UnityEngine;\nusing UnityEngine.Timeline;\nnamespace dev.kemomimi.TimelineExtension.AbstractValueControlTrack.Editor\n{\n internal static class AbstractFloatValueControlTrackEditorUtility\n {\n internal static Color PrimaryColor = new(1f, 0.5f, 0.5f);\n }", "score": 0.8960747718811035 }, { "filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractBoolValueControlTrackCustomEditor.cs", "retrieved_chunk": "using System.Collections.Generic;\nusing UnityEditor;\nusing UnityEditor.Timeline;\nusing UnityEngine;\nusing UnityEngine.Timeline;\nnamespace dev.kemomimi.TimelineExtension.AbstractValueControlTrack.Editor\n{\n internal static class AbstractBoolValueControlTrackEditorUtility\n {\n internal static Color PrimaryColor = new(0.5f, 1f, 0.5f);", "score": 0.878298282623291 }, { "filename": "Assets/TimelineExtension/Editor/CustomActivationTrackEditor/CustomActivationTrackCustomEditor.cs", "retrieved_chunk": "using UnityEditor.Timeline;\nusing UnityEngine;\nusing UnityEngine.Timeline;\nnamespace dev.kemomimi.TimelineExtension.CustomActivationTrack.Editor\n{\n internal static class CustomActivationTrackEditorUtility\n {\n internal static Color PrimaryColor = new(0.5f, 1f, 0.5f);\n }\n [CustomTimelineEditor(typeof(CustomActivationTrack))]", "score": 0.8766882419586182 }, { "filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractColorValueControlTrackCustomEditor.cs", "retrieved_chunk": "using System.Collections.Generic;\nusing UnityEditor;\nusing UnityEditor.Timeline;\nusing UnityEngine;\nusing UnityEngine.Timeline;\nnamespace dev.kemomimi.TimelineExtension.AbstractValueControlTrack.Editor\n{\n internal static class AbstractColorValueControlTrackEditorUtility\n {\n internal static Color PrimaryColor = new(0.5f, 0.5f, 1f);", "score": 0.8707756996154785 }, { "filename": "Assets/TimelineExtension/Scripts/AbstractValueControlTrack/Controller/EnvironmentAmbientColorController.cs", "retrieved_chunk": "using UnityEngine;\nnamespace dev.kemomimi.TimelineExtension.AbstractValueControlTrack.Controller\n{\n public class EnvironmentAmbientColorController : AbstractColorValueController\n {\n protected override void OnValueChanged(Color value)\n {\n RenderSettings.ambientSkyColor = value;\n }\n }", "score": 0.8640381097793579 } ]
csharp
AbstractIntValueControlTrack))] public class AbstractIntValueControlTrackCustomEditor : TrackEditor {
#nullable enable using System.Collections.Generic; namespace Mochineko.FacialExpressions.Blink { /// <summary> /// Composition of some <see cref="IEyelidMorpher"/>s. /// </summary> public sealed class CompositeEyelidMorpher : IEyelidMorpher { private readonly IReadOnlyList<IEyelidMorpher> morphers; /// <summary> /// Creates a new instance of <see cref="CompositeEyelidMorpher"/>. /// </summary> /// <param name="morphers">Composited morphers.</param> public CompositeEyelidMorpher(IReadOnlyList<IEyelidMorpher> morphers) { this.morphers = morphers; } void IEyelidMorpher.MorphInto(EyelidSample sample) { foreach (var morpher in morphers) { morpher.MorphInto(sample); } } float
IEyelidMorpher.GetWeightOf(Eyelid eyelid) {
return morphers[0].GetWeightOf(eyelid); } void IEyelidMorpher.Reset() { foreach (var morpher in morphers) { morpher.Reset(); } } } }
Assets/Mochineko/FacialExpressions/Blink/CompositeEyelidMorpher.cs
mochi-neko-facial-expressions-unity-ab0d020
[ { "filename": "Assets/Mochineko/FacialExpressions/Emotion/CompositeEmotionMorpher.cs", "retrieved_chunk": " this.morphers = morphers;\n }\n void IEmotionMorpher<TEmotion>.MorphInto(EmotionSample<TEmotion> sample)\n {\n foreach (var morpher in morphers)\n {\n morpher.MorphInto(sample);\n }\n }\n float IEmotionMorpher<TEmotion>.GetWeightOf(TEmotion emotion)", "score": 0.8744659423828125 }, { "filename": "Assets/Mochineko/FacialExpressions/LipSync/CompositeLipMorpher.cs", "retrieved_chunk": " foreach (var morpher in morphers)\n {\n morpher.MorphInto(sample);\n }\n }\n float ILipMorpher.GetWeightOf(Viseme viseme)\n {\n return morphers[0].GetWeightOf(viseme);\n }\n void ILipMorpher.Reset()", "score": 0.8562971353530884 }, { "filename": "Assets/Mochineko/FacialExpressions/Emotion/CompositeEmotionMorpher.cs", "retrieved_chunk": " {\n return morphers[0].GetWeightOf(emotion);\n }\n void IEmotionMorpher<TEmotion>.Reset()\n {\n foreach (var morpher in morphers)\n {\n morpher.Reset();\n }\n }", "score": 0.8176080584526062 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/AnimatorEyelidMorpher.cs", "retrieved_chunk": " {\n this.animator = animator;\n this.idMap = idMap;\n }\n public void MorphInto(EyelidSample sample)\n {\n if (idMap.TryGetValue(sample.eyelid, out var id))\n {\n animator.SetFloat(id, sample.weight);\n }", "score": 0.7777289152145386 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/SkinnedMeshEyelidMorpher.cs", "retrieved_chunk": " }\n else if (indexMap.TryGetValue(sample.eyelid, out var index))\n {\n skinnedMeshRenderer.SetBlendShapeWeight(index, sample.weight * 100f);\n }\n }\n public float GetWeightOf(Eyelid eyelid)\n {\n if (indexMap.TryGetValue(eyelid, out var index))\n {", "score": 0.7740490436553955 } ]
csharp
IEyelidMorpher.GetWeightOf(Eyelid eyelid) {
#nullable enable using System.Collections.Generic; namespace Mochineko.FacialExpressions.Blink { /// <summary> /// Composition of some <see cref="IEyelidMorpher"/>s. /// </summary> public sealed class CompositeEyelidMorpher : IEyelidMorpher { private readonly IReadOnlyList<
IEyelidMorpher> morphers;
/// <summary> /// Creates a new instance of <see cref="CompositeEyelidMorpher"/>. /// </summary> /// <param name="morphers">Composited morphers.</param> public CompositeEyelidMorpher(IReadOnlyList<IEyelidMorpher> morphers) { this.morphers = morphers; } void IEyelidMorpher.MorphInto(EyelidSample sample) { foreach (var morpher in morphers) { morpher.MorphInto(sample); } } float IEyelidMorpher.GetWeightOf(Eyelid eyelid) { return morphers[0].GetWeightOf(eyelid); } void IEyelidMorpher.Reset() { foreach (var morpher in morphers) { morpher.Reset(); } } } }
Assets/Mochineko/FacialExpressions/Blink/CompositeEyelidMorpher.cs
mochi-neko-facial-expressions-unity-ab0d020
[ { "filename": "Assets/Mochineko/FacialExpressions/LipSync/CompositeLipMorpher.cs", "retrieved_chunk": "#nullable enable\nusing System.Collections.Generic;\nnamespace Mochineko.FacialExpressions.LipSync\n{\n /// <summary>\n /// Composition of some <see cref=\"Mochineko.FacialExpressions.LipSync.ILipMorpher\"/>s.\n /// </summary>\n public sealed class CompositeLipMorpher : ILipMorpher\n {\n private readonly IReadOnlyList<ILipMorpher> morphers;", "score": 0.9140333533287048 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/AnimatorEyelidMorpher.cs", "retrieved_chunk": "#nullable enable\nusing System.Collections.Generic;\nusing UnityEngine;\nnamespace Mochineko.FacialExpressions.Blink\n{\n /// <summary>\n /// A simple implementation of <see cref=\"IEyelidMorpher\"/> for <see cref=\"Animator\"/>.\n /// </summary>\n public sealed class AnimatorEyelidMorpher : IEyelidMorpher\n {", "score": 0.9026280641555786 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/SkinnedMeshEyelidMorpher.cs", "retrieved_chunk": "#nullable enable\nusing System.Collections.Generic;\nusing UnityEngine;\nnamespace Mochineko.FacialExpressions.Blink\n{\n /// <summary>\n /// A simple implementation of <see cref=\"IEyelidMorpher\"/> for <see cref=\"skinnedMeshRenderer\"/>.\n /// </summary>\n public sealed class SkinnedMeshEyelidMorpher : IEyelidMorpher\n {", "score": 0.8962401151657104 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/SequentialEyelidAnimator.cs", "retrieved_chunk": " /// </summary>\n public sealed class SequentialEyelidAnimator : ISequentialEyelidAnimator\n {\n private readonly IEyelidMorpher morpher;\n /// <summary>\n /// Creates a new instance of <see cref=\"SequentialEyelidAnimator\"/>.\n /// </summary>\n /// <param name=\"morpher\">Target morpher.</param>\n public SequentialEyelidAnimator(IEyelidMorpher morpher)\n {", "score": 0.869436502456665 }, { "filename": "Assets/Mochineko/FacialExpressions/Emotion/CompositeEmotionMorpher.cs", "retrieved_chunk": "#nullable enable\nusing System;\nusing System.Collections.Generic;\nnamespace Mochineko.FacialExpressions.Emotion\n{\n /// <summary>\n /// Composition of some <see cref=\"Mochineko.FacialExpressions.Emotion.IEmotionMorpher{TEmotion}\"/>s.\n /// </summary>\n /// <typeparam name=\"TEmotion\"></typeparam>\n public sealed class CompositeEmotionMorpher<TEmotion>", "score": 0.8645771145820618 } ]
csharp
IEyelidMorpher> morphers;
using HarmonyLib; using UnityEngine; namespace Ultrapain.Patches { class GrenadeParriedFlag : MonoBehaviour { public int parryCount = 1; public bool registeredStyle = false; public bool bigExplosionOverride = false; public GameObject temporaryExplosion; public GameObject temporaryBigExplosion; public GameObject weapon; public enum GrenadeType { Core, Rocket, } public GrenadeType grenadeType; } class Punch_CheckForProjectile_Patch { static bool Prefix(
Punch __instance, Transform __0, ref bool __result, ref bool ___hitSomething, Animator ___anim) {
Grenade grn = __0.GetComponent<Grenade>(); if(grn != null) { if (grn.rocket && !ConfigManager.rocketBoostToggle.value) return true; if (!ConfigManager.grenadeBoostToggle.value) return true; MonoSingleton<TimeController>.Instance.ParryFlash(); ___hitSomething = true; grn.transform.LookAt(Camera.main.transform.position + Camera.main.transform.forward * 100.0f); Rigidbody rb = grn.GetComponent<Rigidbody>(); rb.velocity = Vector3.zero; rb.AddRelativeForce(Vector3.forward * Mathf.Max(Plugin.MinGrenadeParryVelocity, rb.velocity.magnitude), ForceMode.VelocityChange); rb.velocity = grn.transform.forward * Mathf.Max(Plugin.MinGrenadeParryVelocity, rb.velocity.magnitude); /*if (grn.rocket) MonoSingleton<StyleHUD>.Instance.AddPoints(100, Plugin.StyleIDs.rocketBoost, MonoSingleton<GunControl>.Instance.currentWeapon, null); else MonoSingleton<StyleHUD>.Instance.AddPoints(100, Plugin.StyleIDs.fistfulOfNades, MonoSingleton<GunControl>.Instance.currentWeapon, null); */ GrenadeParriedFlag flag = grn.GetComponent<GrenadeParriedFlag>(); if (flag != null) flag.parryCount += 1; else { flag = grn.gameObject.AddComponent<GrenadeParriedFlag>(); flag.grenadeType = (grn.rocket) ? GrenadeParriedFlag.GrenadeType.Rocket : GrenadeParriedFlag.GrenadeType.Core; flag.weapon = MonoSingleton<GunControl>.Instance.currentWeapon; } grn.rocketSpeed *= 1f + ConfigManager.rocketBoostSpeedMultiplierPerHit.value; ___anim.Play("Hook", 0, 0.065f); __result = true; return false; } return true; } } class Grenade_Explode_Patch1 { static bool Prefix(Grenade __instance, ref bool __2, ref bool __1, ref bool ___exploded) { GrenadeParriedFlag flag = __instance.GetComponent<GrenadeParriedFlag>(); if (flag == null) return true; if (__instance.rocket) { bool rocketParried = flag != null; bool rocketHitGround = __1; flag.temporaryBigExplosion = GameObject.Instantiate(__instance.superExplosion, new Vector3(1000000, 1000000, 1000000), Quaternion.identity); __instance.superExplosion = flag.temporaryBigExplosion; foreach (Explosion e in __instance.superExplosion.GetComponentsInChildren<Explosion>()) { e.speed *= 1f + ConfigManager.rocketBoostSizeMultiplierPerHit.value * flag.parryCount; e.damage *= (int)(1f + ConfigManager.rocketBoostDamageMultiplierPerHit.value * flag.parryCount); e.maxSize *= 1f + ConfigManager.rocketBoostSizeMultiplierPerHit.value * flag.parryCount; } flag.temporaryExplosion = GameObject.Instantiate(__instance.explosion, new Vector3(1000000, 1000000, 1000000), Quaternion.identity); __instance.explosion = flag.temporaryExplosion; if (rocketParried/* && rocketHitGround*/) { if(!rocketHitGround || ConfigManager.rocketBoostAlwaysExplodesToggle.value) __1 = false; foreach(Explosion e in (__2) ? flag.temporaryBigExplosion.GetComponentsInChildren<Explosion>() : flag.temporaryExplosion.GetComponentsInChildren<Explosion>()) { GrenadeParriedFlag fFlag = e.gameObject.AddComponent<GrenadeParriedFlag>(); fFlag.weapon = flag.weapon; fFlag.grenadeType = GrenadeParriedFlag.GrenadeType.Rocket; fFlag.parryCount = flag.parryCount; break; } } foreach (Explosion e in __instance.explosion.GetComponentsInChildren<Explosion>()) { e.speed *= 1f + ConfigManager.rocketBoostSizeMultiplierPerHit.value * flag.parryCount; e.damage *= (int)(1f + ConfigManager.rocketBoostDamageMultiplierPerHit.value * flag.parryCount); e.maxSize *= 1f + ConfigManager.rocketBoostSizeMultiplierPerHit.value * flag.parryCount; } } else { if (flag != null/* && flag.bigExplosionOverride*/) { __2 = true; GameObject explosion = GameObject.Instantiate(__instance.superExplosion); foreach(Explosion exp in explosion.GetComponentsInChildren<Explosion>()) { exp.damage = (int)(exp.damage * ConfigManager.grenadeBoostDamageMultiplier.value); exp.maxSize *= ConfigManager.grenadeBoostSizeMultiplier.value; exp.speed *= ConfigManager.grenadeBoostSizeMultiplier.value; } __instance.superExplosion = explosion; flag.temporaryBigExplosion = explosion; } } return true; } static void Postfix(Grenade __instance, ref bool ___exploded) { GrenadeParriedFlag flag = __instance.GetComponent<GrenadeParriedFlag>(); if (flag == null) return; if (__instance.rocket) { if (flag.temporaryExplosion != null) { GameObject.Destroy(flag.temporaryExplosion); flag.temporaryExplosion = null; } if (flag.temporaryBigExplosion != null) { GameObject.Destroy(flag.temporaryBigExplosion); flag.temporaryBigExplosion = null; } } else { if (flag.temporaryBigExplosion != null) { GameObject.Destroy(flag.temporaryBigExplosion); flag.temporaryBigExplosion = null; } } } } class Grenade_Collision_Patch { static float lastTime = 0; static bool Prefix(Grenade __instance, Collider __0) { GrenadeParriedFlag flag = __instance.GetComponent<GrenadeParriedFlag>(); if (flag == null) return true; //if (!Plugin.ultrapainDifficulty || !ConfigManager.playerTweakToggle.value || !ConfigManager.grenadeBoostToggle.value) // return true; if (__0.gameObject.layer != 14 && __0.gameObject.layer != 20) { EnemyIdentifierIdentifier enemyIdentifierIdentifier; if ((__0.gameObject.layer == 11 || __0.gameObject.layer == 10) && __0.TryGetComponent<EnemyIdentifierIdentifier>(out enemyIdentifierIdentifier) && enemyIdentifierIdentifier.eid) { if (enemyIdentifierIdentifier.eid.enemyType != EnemyType.MaliciousFace && flag.grenadeType == GrenadeParriedFlag.GrenadeType.Core && (Time.time - lastTime >= 0.25f || lastTime < 0)) { lastTime = Time.time; flag.bigExplosionOverride = true; MonoSingleton<StyleHUD>.Instance.AddPoints(ConfigManager.grenadeBoostStylePoints.value, ConfigManager.grenadeBoostStyleText.guid, MonoSingleton<GunControl>.Instance.currentWeapon, null); } } } return true; } } class Explosion_Collide_Patch { static float lastTime = 0; static bool Prefix(Explosion __instance, Collider __0) { GrenadeParriedFlag flag = __instance.gameObject.GetComponent<GrenadeParriedFlag>(); if (flag == null || flag.registeredStyle) return true; if (!flag.registeredStyle && __0.gameObject.tag != "Player" && (__0.gameObject.layer == 10 || __0.gameObject.layer == 11) && __instance.canHit != AffectedSubjects.PlayerOnly) { EnemyIdentifierIdentifier componentInParent = __0.GetComponentInParent<EnemyIdentifierIdentifier>(); if(flag.grenadeType == GrenadeParriedFlag.GrenadeType.Rocket && componentInParent != null && componentInParent.eid != null && !componentInParent.eid.blessed && !componentInParent.eid.dead && (Time.time - lastTime >= 0.25f || lastTime < 0)) { flag.registeredStyle = true; lastTime = Time.time; MonoSingleton<StyleHUD>.Instance.AddPoints(ConfigManager.rocketBoostStylePoints.value, ConfigManager.rocketBoostStyleText.guid, flag.weapon, null, flag.parryCount); } } return true; } } }
Ultrapain/Patches/Parry.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Leviathan.cs", "retrieved_chunk": " }\n return false;\n }\n }\n class Leviathan_ProjectileBurst\n {\n static bool Prefix(LeviathanHead __instance, Animator ___anim,\n ref int ___projectilesLeftInBurst, ref float ___projectileBurstCooldown, ref bool ___inAction)\n {\n if (!__instance.active)", "score": 0.8946120738983154 }, { "filename": "Ultrapain/Patches/MaliciousFace.cs", "retrieved_chunk": " flag.charging = false;\n }\n return true;\n }\n }\n class MaliciousFace_ShootProj_Patch\n {\n /*static bool Prefix(SpiderBody __instance, ref GameObject ___proj, out bool __state)\n {\n __state = false;", "score": 0.8938999176025391 }, { "filename": "Ultrapain/Patches/PlayerStatTweaks.cs", "retrieved_chunk": " }\n }\n return code.AsEnumerable();\n }\n }\n class NewMovement_GetHealth\n {\n static bool Prefix(NewMovement __instance, int __0, bool __1, ref AudioSource ___greenHpAud, Canvas ___fullHud)\n {\n if (__instance.dead || __instance.exploded)", "score": 0.8842964172363281 }, { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": " }\n else\n patch.swingComboLeft = 2;*/\n }\n }\n class Mindflayer_MeleeTeleport_Patch\n {\n public static Vector3 deltaPosition = new Vector3(0, -10, 0);\n static bool Prefix(Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___goingLeft, ref Animator ___anim, ref bool ___enraged)\n {", "score": 0.8783879280090332 }, { "filename": "Ultrapain/Patches/OrbitalStrike.cs", "retrieved_chunk": " {\n public bool state = false;\n public string id;\n public int points;\n public GameObject templateExplosion;\n }\n static bool Prefix(Grenade __instance, ref float __3, out StateInfo __state,\n bool __1, bool __2)\n {\n __state = new StateInfo();", "score": 0.87638258934021 } ]
csharp
Punch __instance, Transform __0, ref bool __result, ref bool ___hitSomething, Animator ___anim) {
using System; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Primitives; using ClockSnowFlake; namespace Microsoft.Extensions.DependencyInjection { public static class ServiceCollectionExtensions { public static IServiceCollection AddSnowFlakeId(this IServiceCollection services, IConfiguration configuration, Action<SnowFakeOptions> configure = null, string sectionName = null) { sectionName ??= SnowFakeOptions.SectionName; services.AddOptions<SnowFakeOptions>(); services.PostConfigure<SnowFakeOptions>(x => { configure?.Invoke(x); }); var options = configuration.GetSection(sectionName).Get<SnowFakeOptions>() ?? new SnowFakeOptions(); configure?.Invoke(options); SnowFakeOptionsConst.WorkId = options.WorkId; Console.WriteLine($"SnowWorkId:{SnowFakeOptionsConst.WorkId}"); return services; } public static IServiceCollection AddSnowFlakeId(this IServiceCollection services, Action<
SnowFakeOptions> configure) {
services.AddOptions<SnowFakeOptions>().Configure(configure); var options = new SnowFakeOptions(); configure.Invoke(options); SnowFakeOptionsConst.WorkId = options.WorkId; Console.WriteLine($"SnowWorkId:{SnowFakeOptionsConst.WorkId}"); return services; } public static void AddSnowFlakeId(this IConfiguration configuration, Action<SnowFakeOptions> configure = null, string sectionName = null) { sectionName ??= SnowFakeOptions.SectionName; var options = configuration.GetSection(sectionName).Get<SnowFakeOptions>() ?? new SnowFakeOptions(); configure?.Invoke(options); SnowFakeOptionsConst.WorkId = options.WorkId; Console.WriteLine($"SnowWorkId:{SnowFakeOptionsConst.WorkId}"); } } }
src/ClockSnowFlake/Extensions/ServiceCollectionExtensions.cs
Bryan-Cyf-ClockSnowFlake-7c4a524
[ { "filename": "test/ClockSnowFlake.Unitests/ClockSnowFlakeTest.cs", "retrieved_chunk": "using Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.DependencyInjection;\nusing Xunit;\nnamespace ClockSnowFlake.Unitests\n{\n public class ClockSnowFlakeTest\n {\n public ClockSnowFlakeTest()\n {\n IServiceCollection services = new ServiceCollection();", "score": 0.7179598808288574 }, { "filename": "src/ClockSnowFlake/Options/SnowFlakeOptions.cs", "retrieved_chunk": "using Microsoft.Extensions.Options;\nnamespace ClockSnowFlake\n{\n public class SnowFakeOptions\n {\n public const string SectionName = \"SnowFlakeId\";\n /// <summary>\n /// 工作节点ID,范围 0~128\n /// </summary>\n public int? WorkId { get; set; }", "score": 0.7031039595603943 }, { "filename": "src/ClockSnowFlake/Generator/ClockSnowFlakeIdGenerator.cs", "retrieved_chunk": "namespace ClockSnowFlake\n{\n /// <summary>\n /// 基于时钟序列的 雪花算法ID 生成器\n /// </summary>\n public class ClockSnowFlakeIdGenerator : ILongGenerator\n {\n public ClockSnowFlakeIdGenerator()\n {\n var workerId = SnowFakeOptionsConst.WorkId;", "score": 0.6976519823074341 }, { "filename": "test/ClockSnowFlake.Unitests/ClockSnowFlakeTest.cs", "retrieved_chunk": " //注意:工作机器ID不能重复\n services.AddSnowFlakeId(x => x.WorkId = 2);\n }\n [Fact]\n public void Id_Generate_Should_Be_Succeed()\n {\n var id = IdGener.GetLong();\n Assert.True(id > 0);\n }\n }", "score": 0.6831076741218567 }, { "filename": "src/ClockSnowFlake/Generator/ClockSnowFlakeIdGenerator.cs", "retrieved_chunk": " _id = new ClockSnowflakeId(workerId);\n }\n /// <summary>\n /// 基于时钟序列的雪花算法ID\n /// </summary>\n private readonly ClockSnowflakeId _id;\n /// <summary>\n /// 获取<see cref=\"ClockSnowFlakeIdGenerator\"/>类型的实例\n /// </summary>\n public static ClockSnowFlakeIdGenerator Current { get; set; } = new ClockSnowFlakeIdGenerator();", "score": 0.6689013838768005 } ]
csharp
SnowFakeOptions> configure) {
using System.Text.Json; namespace WAGIapp.AI { internal class Master { private static Master singleton; public static Master Singleton { get { if (singleton == null) { Console.WriteLine("Create master"); singleton = new Master(); Console.WriteLine("Master created"); } return singleton; } } public LongTermMemory Memory; public ActionList Actions; public ScriptFile scriptFile; public bool Done = true; private string nextMemoryPrompt = ""; private string lastCommandOuput = ""; public List<string> Notes; private List<ChatMessage> LastMessages = new List<ChatMessage>(); private List<ChatMessage> LastCommand = new List<ChatMessage>(); public string FormatedNotes { get { string output = ""; for (int i = 0; i < Notes.Count; i++) { output += (i + 1) + ". " + Notes[i] + "\n"; } return output; } } public Master() { Notes = new List<string>(); Memory = new LongTermMemory(1024); Actions = new ActionList(10); scriptFile = new ScriptFile(); singleton = this; } public async Task Tick() { Console.WriteLine("master tick -master"); if (Done) return; if (Memory.memories.Count == 0) { await Memory.MakeMemory(Settings.Goal); Console.WriteLine("master start memory done"); } var masterInput = await GetMasterInput(); string responseString; MasterResponse response; var action = Actions.AddAction("Thinking", LogAction.ThinkIcon); while (true) { try { responseString = await OpenAI.GetChatCompletion(ChatModel.ChatGPT, masterInput); response = Utils.GetObjectFromJson<MasterResponse>(responseString) ?? new(); break; } catch (Exception) { Console.WriteLine("Master failed - trying again"); } } nextMemoryPrompt = response.thoughts; lastCommandOuput = await Commands.TryToRun(this, response.command); LastMessages.Add(new ChatMessage(ChatRole.Assistant, responseString)); LastCommand.Add(new ChatMessage(ChatRole.System, "Command output:\n" + lastCommandOuput)); if (LastMessages.Count >= 10) LastMessages.RemoveAt(0); if (LastCommand.Count >= 10) LastCommand.RemoveAt(0); action.Text = response.thoughts; masterInput.Add(LastMessages.Last()); masterInput.Add(LastCommand.Last()); Console.WriteLine(JsonSerializer.Serialize(masterInput, new JsonSerializerOptions() { WriteIndented = true })); Console.WriteLine(scriptFile.GetText()); Console.WriteLine("------------------------------------------------------------------------"); Actions.AddAction("Memory", LogAction.MemoryIcon); await Memory.MakeMemory(responseString); } public async Task<List<
ChatMessage>> GetMasterInput() {
List<ChatMessage> messages = new List<ChatMessage>(); messages.Add(Texts.MasterStartText); messages.Add(new ChatMessage(ChatRole.System, "Memories:\n" + await Memory.GetMemories(nextMemoryPrompt))); messages.Add(new ChatMessage(ChatRole.System, "Notes:\n" + FormatedNotes)); messages.Add(new ChatMessage(ChatRole.System, "Commands:\n" + Commands.GetCommands())); messages.Add(new ChatMessage(ChatRole.System, "Main Goal:\n" + Settings.Goal)); messages.Add(new ChatMessage(ChatRole.System, "Script file:\n" + scriptFile.GetText() + "\nEnd of script file")); messages.Add(Texts.MasterStartText); messages.Add(Texts.MasterOutputFormat); for (int i = 0; i < LastMessages.Count; i++) { messages.Add(LastMessages[i]); messages.Add(LastCommand[i]); } return messages; } } class MasterResponse { public string thoughts { get; set; } = ""; public string command { get; set; } = ""; } }
WAGIapp/AI/Master.cs
Woltvint-WAGI-d808927
[ { "filename": "WAGIapp/AI/LongTermMemory.cs", "retrieved_chunk": " string tagString = \"Tags:\\n\";\n foreach (var tag in tags)\n tagString += tag + \" ,\";\n tagString.TrimEnd(',');\n tagString += \"\\n\";\n ChatMessage tagsListMessage = new ChatMessage(ChatRole.System, tagString);\n ChatMessage stateMessage = new ChatMessage(ChatRole.User, state);\n string mem = await OpenAI.GetChatCompletion(ChatModel.ChatGPT, new List<ChatMessage>() { tagsListMessage, Texts.ShortTermMemoryAddPrompt, stateMessage, Texts.ShortTermMemoryAddFormat });\n mem = Utils.ExtractJson(mem);\n try", "score": 0.8067560791969299 }, { "filename": "WAGIapp/AI/LongTermMemory.cs", "retrieved_chunk": " mem = await OpenAI.GetChatCompletion(ChatModel.ChatGPT, new List<ChatMessage>() { Texts.ShortTermMemoryGetPrompt, memoryState, Texts.ShortTermMemoryGetFormat });\n memoryTags = Utils.GetObjectFromJson<OutputMemoryTagsJson>(mem);\n break;\n }\n catch (Exception)\n {\n Console.WriteLine(\"Get memory failed - trying again\");\n }\n }\n HashSet<string> splitTags = Utils.CleanInput(memoryTags.tags.Split(\",\")).ToHashSet();", "score": 0.8046819567680359 }, { "filename": "WAGIapp/Program.cs", "retrieved_chunk": "Master.Singleton.Actions.AddAction(\"Creating a memory\", LogAction.MemoryIcon);\nMaster.Singleton.Actions.AddAction(\"Hello there\");\n*/\nTask.Run(async () =>\n{\n while (true)\n {\n await Task.Delay(10000);\n await Master.Singleton.Tick();\n /*switch (Random.Shared.Next(0,6))", "score": 0.7821102738380432 }, { "filename": "WAGIapp/AI/Texts.cs", "retrieved_chunk": "namespace WAGIapp.AI\n{\n public static class Texts\n {\n public static ChatMessage MasterStartText => new(ChatRole.System, Settings.Rules);\n public static ChatMessage MasterOutputFormat = new ChatMessage(\n ChatRole.System,\n \"only reply in this json format\" +\n \"Output format:\" +\n \"{\" +", "score": 0.7719190120697021 }, { "filename": "WAGIapp/AI/ActionList.cs", "retrieved_chunk": " MaxActions = maxActions;\n }\n public LogAction AddAction(string action, string icon = LogAction.InfoIcon)\n {\n LogAction a = new LogAction() { Title = action, Icon = icon };\n lock (dataLock)\n {\n Actions.Add(a);\n if (Actions.Count >= MaxActions)\n Actions.RemoveAt(0);", "score": 0.7683762311935425 } ]
csharp
ChatMessage>> GetMasterInput() {
using static QuizGenerator.Core.StringUtils; using Word = Microsoft.Office.Interop.Word; using System.Diagnostics; using Microsoft.Office.Interop.Word; namespace QuizGenerator.Core { public class RandomizedQuizGenerator { private ILogger logger; private Word.Application wordApp; public RandomizedQuizGenerator(ILogger logger) { this.logger = logger; } public void GenerateQuiz(string inputFilePath, string outputFolderPath) { this.logger.Log("Quiz generation started."); this.logger.LogNewLine(); if (KillAllProcesses("WINWORD")) Console.WriteLine("MS Word (WINWORD.EXE) is still running -> process terminated."); // Start MS Word and open the input file this.wordApp = new Word.Application(); this.wordApp.Visible = false; // Show / hide MS Word app window this.wordApp.ScreenUpdating = false; // Enable / disable screen updates after each change var inputDoc = this.wordApp.Documents.Open(inputFilePath); try { // Parse the input MS Word document this.logger.Log("Parsing the input document: " + inputFilePath); QuizParser quizParser = new QuizParser(this.logger); QuizDocument quiz = quizParser.Parse(inputDoc); this.logger.Log("Input document parsed successfully."); // Display the quiz content (question groups + questions + answers) quizParser.LogQuiz(quiz); // Generate the randomized quiz variants this.logger.LogNewLine(); this.logger.Log("Generating quizes..."); this.logger.Log($" (output path = {outputFolderPath})"); GenerateRandomizedQuizVariants(quiz, inputFilePath, outputFolderPath); this.logger.LogNewLine(); this.logger.Log("Quiz generation completed."); this.logger.LogNewLine(); } catch (Exception ex) { this.logger.LogException(ex); } finally { inputDoc.Close(); this.wordApp.Quit(); } } private void GenerateRandomizedQuizVariants( QuizDocument quiz, string inputFilePath, string outputFolderPath) { // Initialize the output folder (create it and ensure it is empty) this.logger.Log($"Initializing output folder: {outputFolderPath}"); if (Directory.Exists(outputFolderPath)) { Directory.Delete(outputFolderPath, true); } Directory.CreateDirectory(outputFolderPath); // Prepare the answer sheet for all variants List<List<char>> quizAnswerSheet = new List<List<char>>(); // Generate the requested randomized quiz variants, one by one for (int quizVariant = 1; quizVariant <= quiz.VariantsToGenerate; quizVariant++) { this.logger.LogNewLine(); this.logger.Log($"Generating randomized quiz: variant #{quizVariant} out of {quiz.VariantsToGenerate} ..."); string outputFilePath = outputFolderPath + Path.DirectorySeparatorChar + "quiz" + quizVariant.ToString("000") + ".docx"; RandomizedQuiz randQuiz = RandomizedQuiz.GenerateFromQuizData(quiz); WriteRandomizedQuizToFile( randQuiz, quizVariant, inputFilePath, outputFilePath, quiz.LangCode); List<char> answers = ExtractAnswersAsLetters(randQuiz, quiz.LangCode); quizAnswerSheet.Add(answers); this.logger.Log($"Randomized quiz: variant #{quizVariant} out of {quiz.VariantsToGenerate} generated successfully."); } WriteAnswerSheetToHTMLFile(quizAnswerSheet, outputFolderPath); } private void WriteRandomizedQuizToFile(
RandomizedQuiz randQuiz, int quizVariant, string inputFilePath, string outputFilePath, string langCode) {
File.Copy(inputFilePath, outputFilePath, true); // Open the output file in MS Word var outputDoc = this.wordApp.Documents.Open(outputFilePath); try { // Select all content in outputDoc and delete the seletion this.wordApp.Selection.WholeStory(); this.wordApp.Selection.Delete(); // Write the randomized quiz as MS Word document this.logger.Log($"Creating randomized quiz document: " + outputFilePath); WriteRandomizedQuizToWordDoc(randQuiz, quizVariant, langCode, outputDoc); } catch (Exception ex) { this.logger.LogException(ex); } finally { outputDoc.Save(); outputDoc.Close(); } } private void WriteRandomizedQuizToWordDoc(RandomizedQuiz quiz, int quizVariant, string langCode, Word.Document outputDoc) { // Print the quiz header in the output MS Word document string quizHeaderText = TruncateString(quiz.HeaderContent.Text); this.logger.Log($"Quiz header: {quizHeaderText}", 1); AppendRange(outputDoc, quiz.HeaderContent); // Replace all occurences of "# # #" with the variant number (page headers + body) string variantFormatted = quizVariant.ToString("000"); foreach (Word.Section section in outputDoc.Sections) { foreach (Word.HeaderFooter headerFooter in section.Headers) { ReplaceTextInRange(headerFooter.Range, "# # #", variantFormatted); } } ReplaceTextInRange(outputDoc.Content, "# # #", variantFormatted); int questionNumber = 0; this.logger.Log($"Question groups = {quiz.QuestionGroups.Count}", 1); for (int groupIndex = 0; groupIndex < quiz.QuestionGroups.Count; groupIndex++) { this.logger.Log($"[Question Group #{groupIndex + 1}]", 1); QuizQuestionGroup group = quiz.QuestionGroups[groupIndex]; string groupHeaderText = TruncateString(group.HeaderContent?.Text); this.logger.Log($"Group header: {groupHeaderText}", 2); if (!group.SkipHeader) { AppendRange(outputDoc, group.HeaderContent); } this.logger.Log($"Questions = {group.Questions.Count}", 2); for (int questionIndex = 0; questionIndex < group.Questions.Count; questionIndex++) { this.logger.Log($"[Question #{questionIndex + 1}]", 2); QuizQuestion question = group.Questions[questionIndex]; string questionContent = TruncateString(question.HeaderContent?.Text); this.logger.Log($"Question content: {questionContent}", 3); questionNumber++; AppendText(outputDoc, $"{questionNumber}. "); AppendRange(outputDoc, question.HeaderContent); this.logger.Log($"Answers = {question.Answers.Count}", 3); char letter = GetStartLetter(langCode); foreach (var answer in question.Answers) { string prefix = answer.IsCorrect ? "Correct answer" : "Wrong answer"; string answerText = TruncateString(answer.Content.Text); this.logger.Log($"{prefix}: {letter}) {answerText}", 4); AppendText(outputDoc, $"{letter}) "); AppendRange(outputDoc, answer.Content); letter++; } string questionFooterText = TruncateString(question.FooterContent?.Text); if (questionFooterText == "") questionFooterText = "(empty)"; this.logger.Log($"Question footer: {questionFooterText}", 3); AppendRange(outputDoc, question.FooterContent); } } string quizFooterText = TruncateString(quiz.FooterContent?.Text); this.logger.Log($"Quiz footer: {quizFooterText}", 1); AppendRange(outputDoc, quiz.FooterContent); } private void ReplaceTextInRange(Word.Range range, string srcText, string replaceText) { Word.Find find = range.Find; find.Text = srcText; find.Replacement.Text = replaceText; find.Forward = true; find.Wrap = Word.WdFindWrap.wdFindContinue; object replaceAll = Word.WdReplace.wdReplaceAll; find.Execute(Replace: ref replaceAll); } public void AppendRange(Word.Document targetDocument, Word.Range sourceRange) { if (sourceRange != null) { // Get the range at the end of the target document Word.Range targetRange = targetDocument.Content; object wdColapseEnd = Word.WdCollapseDirection.wdCollapseEnd; targetRange.Collapse(ref wdColapseEnd); // Insert the source range of formatted text to the target range targetRange.FormattedText = sourceRange.FormattedText; } } public void AppendText(Word.Document targetDocument, string text) { // Get the range at the end of the target document Word.Range targetRange = targetDocument.Content; object wdColapseEnd = Word.WdCollapseDirection.wdCollapseEnd; targetRange.Collapse(ref wdColapseEnd); // Insert the source range of formatted text to the target range targetRange.Text = text; } private List<char> ExtractAnswersAsLetters(RandomizedQuiz randQuiz, string langCode) { char startLetter = GetStartLetter(langCode); List<char> answers = new List<char>(); foreach (var question in randQuiz.AllQuestions) { int correctAnswerIndex = FindCorrectAnswerIndex(question.Answers); char answer = (char)(startLetter + correctAnswerIndex); answers.Add(answer); } return answers; } private static char GetStartLetter(string langCode) { char startLetter; if (langCode == "EN") startLetter = 'a'; // Latin letter 'a' else if (langCode == "BG") startLetter = 'а'; // Cyrillyc letter 'а' else throw new Exception("Unsupported language: " + langCode); return startLetter; } private int FindCorrectAnswerIndex(List<QuestionAnswer> answers) { for (int index = 0; index < answers.Count; index++) { if (answers[index].IsCorrect) return index; } // No correct answer found in the list of answers return -1; } private void WriteAnswerSheetToHTMLFile( List<List<char>> quizAnswerSheet, string outputFilePath) { string outputFileName = outputFilePath + Path.DirectorySeparatorChar + "answers.html"; this.logger.LogNewLine(); this.logger.Log($"Writing answers sheet: {outputFileName}"); for (int quizIndex = 0; quizIndex < quizAnswerSheet.Count; quizIndex++) { List<char> answers = quizAnswerSheet[quizIndex]; string answersAsString = $"Variant #{quizIndex + 1}: {string.Join(" ", answers)}"; this.logger.Log(answersAsString, 1); } List<string> html = new List<string>(); html.Add("<table border='1'>"); html.Add(" <tr>"); html.Add(" <td>Var</td>"); for (int questionIndex = 0; questionIndex < quizAnswerSheet[0].Count; questionIndex++) { html.Add($" <td>{questionIndex + 1}</td>"); } html.Add(" </tr>"); for (int quizIndex = 0; quizIndex < quizAnswerSheet.Count; quizIndex++) { html.Add(" <tr>"); html.Add($" <td>{(quizIndex + 1).ToString("000")}</td>"); foreach (var answer in quizAnswerSheet[quizIndex]) { html.Add($" <td>{answer}</td>"); } html.Add(" </tr>"); } html.Add("</table>"); File.WriteAllLines(outputFileName, html); } public bool KillAllProcesses(string processName) { Process[] processes = Process.GetProcessesByName(processName); int killedProcessesCount = 0; foreach (Process process in processes) { try { process.Kill(); killedProcessesCount++; this.logger.Log($"Process {processName} ({process.Id}) stopped."); } catch { this.logger.LogError($"Process {processName} ({process.Id}) is running, but cannot be stopped!"); } } return (killedProcessesCount > 0); } } }
QuizGenerator.Core/QuizGenerator.cs
SoftUni-SoftUni-Quiz-Generator-b071448
[ { "filename": "QuizGenerator.Core/RandomizedQuiz.cs", "retrieved_chunk": "\t\tpublic static RandomizedQuiz GenerateFromQuizData(QuizDocument quizData)\n\t\t{\n\t\t\t// Clone the quiz header, question groups and footer\n\t\t\tRandomizedQuiz randQuiz = new RandomizedQuiz();\n\t\t\trandQuiz.HeaderContent = quizData.HeaderContent;\n\t\t\trandQuiz.FooterContent = quizData.FooterContent;\n\t\t\trandQuiz.QuestionGroups = new List<QuizQuestionGroup>();\n\t\t\tint questionGroupIndex = 1;\n\t\t\tforeach (var questionGroupData in quizData.QuestionGroups)\n\t\t\t{", "score": 0.8111914992332458 }, { "filename": "QuizGenerator.UI/FormQuizGenerator.cs", "retrieved_chunk": "\t\t\tstring outputFolder = Path.Combine(startupFolder, @\"../../../../output\");\n\t\t\tthis.textBoxOutputFolder.Text = Path.GetFullPath(outputFolder);\n\t\t\tthis.ActiveControl = this.buttonGenerate;\n\t\t}\n\t\tprivate void buttonGenerate_Click(object sender, EventArgs e)\n\t\t{\n\t\t\tstring inputFilePath = this.textBoxInputFile.Text;\n\t\t\tstring outputFolderPath = this.textBoxOutputFolder.Text;\n\t\t\tRandomizedQuizGenerator quizGenerator = new RandomizedQuizGenerator(this);\n\t\t\tquizGenerator.GenerateQuiz(inputFilePath, outputFolderPath);", "score": 0.7822222709655762 }, { "filename": "QuizGenerator.Core/RandomizedQuiz.cs", "retrieved_chunk": "\t\t\t\t// Copy question groups from quiz data to randQuiz\n\t\t\t\tquestionGroupIndex++;\n\t\t\t\tvar randQuestionGroup = new QuizQuestionGroup();\n\t\t\t\trandQuiz.QuestionGroups.Add(randQuestionGroup);\n\t\t\t\trandQuestionGroup.HeaderContent = questionGroupData.HeaderContent;\n\t\t\t\trandQuestionGroup.SkipHeader = questionGroupData.SkipHeader;\n\t\t\t\trandQuestionGroup.Questions = new List<QuizQuestion>();\n\t\t\t\t// Check if QuestionsToGenerate is valid number\n\t\t\t\tif (questionGroupData.QuestionsToGenerate > questionGroupData.Questions.Count)\n\t\t\t\t{", "score": 0.7672474980354309 }, { "filename": "QuizGenerator.Core/QuizParser.cs", "retrieved_chunk": "\t\tpublic void LogQuiz(QuizDocument quiz)\n\t\t{\n\t\t\tthis.logger.LogNewLine();\n\t\t\tthis.logger.Log($\"Parsed quiz document (from the input MS Word file):\");\n\t\t\tthis.logger.Log($\" - LangCode: {quiz.LangCode}\");\n\t\t\tthis.logger.Log($\" - VariantsToGenerate: {quiz.VariantsToGenerate}\");\n\t\t\tthis.logger.Log($\" - TotalAvailableQuestions: {quiz.TotalAvailableQuestions}\");\n\t\t\tthis.logger.Log($\" - AnswersPerQuestion: {quiz.AnswersPerQuestion}\");\n\t\t\tstring quizHeaderText = TruncateString(quiz.HeaderContent.Text);\n\t\t\tthis.logger.Log($\"Quiz header: {quizHeaderText}\", 1);", "score": 0.7569459676742554 }, { "filename": "QuizGenerator.Core/QuizParser.cs", "retrieved_chunk": "\t\t\t{\n\t\t\t\tparagraph = doc.Paragraphs[paragraphIndex];\n\t\t\t\tvar text = paragraph.Range.Text.Trim();\n\t\t\t\tif (text.StartsWith(QuizStartTag))\n\t\t\t\t{\n\t\t\t\t\t// ~~~ Quiz: {\"VariantsToGenerate\":5, \"AnswersPerQuestion\":4, \"Lang\":\"BG\"} ~~~\n\t\t\t\t\tthis.logger.Log(\"Parsing: \" + text, 1);\n\t\t\t\t\tvar settings = ParseSettings(text, QuizStartTag);\n\t\t\t\t\tquiz.VariantsToGenerate = settings.VariantsToGenerate;\n\t\t\t\t\tquiz.AnswersPerQuestion = settings.AnswersPerQuestion;", "score": 0.7558296918869019 } ]
csharp
RandomizedQuiz randQuiz, int quizVariant, string inputFilePath, string outputFilePath, string langCode) {
using NowPlaying.Models; using NowPlaying.Views; using Playnite.SDK; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Windows; using System.Windows.Input; using System.Windows.Threading; namespace NowPlaying.ViewModels { public class AddGameCachesViewModel : ViewModelBase { private readonly NowPlaying plugin; private readonly Window popup; private readonly List<
CacheRootViewModel> cacheRoots;
private readonly List<GameViewModel> allEligibleGames; private string searchText; public string SearchText { get => searchText; set { if (searchText != value) { searchText = value; OnPropertyChanged(); if (string.IsNullOrWhiteSpace(searchText)) { EligibleGames = allEligibleGames; OnPropertyChanged(nameof(EligibleGames)); SelectNoGames(); } else { EligibleGames = allEligibleGames.Where(g => g.Title.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0).ToList(); OnPropertyChanged(nameof(EligibleGames)); SelectNoGames(); } } } } public class CustomInstallSizeSorter : IComparer { public int Compare(object x, object y) { long sizeX = ((GameViewModel)x).InstallSizeBytes; long sizeY = ((GameViewModel)y).InstallSizeBytes; return sizeX.CompareTo(sizeY); } } public CustomInstallSizeSorter CustomInstallSizeSort { get; private set; } public ICommand ClearSearchTextCommand { get; private set; } public ICommand SelectAllCommand { get; private set; } public ICommand SelectNoneCommand { get; private set; } public ICommand CloseCommand { get; private set; } public ICommand EnableSelectedGamesCommand { get; private set; } public List<string> CacheRoots => cacheRoots.Select(r => r.Directory).ToList(); public List<GameViewModel> EligibleGames { get; private set; } private List<GameViewModel> selectedGames; public List<GameViewModel> SelectedGames { get => selectedGames; set { selectedGames = value; OnPropertyChanged(); } } public string SelectedCacheRoot { get; set; } public string EligibleGamesVisibility => allEligibleGames.Count > 0 ? "Visible" : "Collapsed"; public string NoEligibleGamesVisibility => allEligibleGames.Count > 0 ? "Collapsed" : "Visible"; public AddGameCachesViewModel(NowPlaying plugin, Window popup) { this.plugin = plugin; this.popup = popup; this.CustomInstallSizeSort = new CustomInstallSizeSorter(); this.cacheRoots = plugin.cacheManager.CacheRoots.ToList(); this.SelectedGames = new List<GameViewModel>(); var eligibles = plugin.PlayniteApi.Database.Games.Where(g => plugin.IsGameNowPlayingEligible(g) != GameCachePlatform.InEligible); this.allEligibleGames = eligibles.Select(g => new GameViewModel(g)).ToList(); ClearSearchTextCommand = new RelayCommand(() => SearchText = string.Empty); SelectAllCommand = new RelayCommand(() => SelectAllGames()); SelectNoneCommand = new RelayCommand(() => SelectNoGames()); CloseCommand = new RelayCommand(() => CloseWindow()); EnableSelectedGamesCommand = new RelayCommand(() => EnableSelectedGamesAsync(), () => SelectedGames.Count > 0); SelectedCacheRoot = cacheRoots.First()?.Directory; OnPropertyChanged(nameof(SelectedCacheRoot)); EligibleGames = allEligibleGames; OnPropertyChanged(nameof(EligibleGames)); OnPropertyChanged(nameof(EligibleGamesVisibility)); OnPropertyChanged(nameof(NoEligibleGamesVisibility)); } public void SelectNoGames() { var view = popup.Content as AddGameCachesView; view?.EligibleGames_ClearSelected(); } public void SelectAllGames() { var view = popup.Content as AddGameCachesView; view?.EligibleGames_SelectAll(); } private async void EnableSelectedGamesAsync() { CloseWindow(); if (SelectedGames != null) { var cacheRoot = plugin.cacheManager.FindCacheRoot(SelectedCacheRoot); if (cacheRoot != null) { foreach (var game in SelectedGames) { if (!plugin.IsGameNowPlayingEnabled(game.game)) { if (await plugin.CheckIfGameInstallDirIsAccessibleAsync(game.Title, game.InstallDir)) { if (plugin.CheckAndConfirmOrAdjustInstallDirDepth(game.game)) { (new NowPlayingGameEnabler(plugin, game.game, cacheRoot.Directory)).Activate(); } } } } } } } public void CloseWindow() { if (popup.Dispatcher.CheckAccess()) { popup.Close(); } else { popup.Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadStart(popup.Close)); } } } }
source/ViewModels/AddGameCachesViewModel.cs
gittromney-Playnite-NowPlaying-23eec41
[ { "filename": "source/ViewModels/GameCacheManagerViewModel.cs", "retrieved_chunk": "using static NowPlaying.Models.GameCacheManager;\nusing Playnite.SDK;\nnamespace NowPlaying.ViewModels\n{\n public class GameCacheManagerViewModel : ViewModelBase\n {\n public readonly NowPlaying plugin;\n public readonly ILogger logger;\n private readonly string pluginUserDataPath;\n private readonly string cacheRootsJsonPath;", "score": 0.9331673383712769 }, { "filename": "source/ViewModels/GameViewModel.cs", "retrieved_chunk": "using NowPlaying.Models;\nusing NowPlaying.Utils;\nusing Playnite.SDK.Models;\nusing System.Linq;\nnamespace NowPlaying.ViewModels\n{\n public class GameViewModel : ViewModelBase\n {\n public readonly Game game;\n public string Title => game.Name;", "score": 0.8928940296173096 }, { "filename": "source/Models/GameCacheJob.cs", "retrieved_chunk": "using NowPlaying.Utils;\nusing System.Collections.Generic;\nusing System.Threading;\nnamespace NowPlaying.Models\n{\n public class GameCacheJob\n {\n public readonly GameCacheEntry entry;\n public readonly RoboStats stats;\n public readonly CancellationTokenSource tokenSource;", "score": 0.8893436789512634 }, { "filename": "source/ViewModels/TopPanelViewModel.cs", "retrieved_chunk": "using NowPlaying.Utils;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nnamespace NowPlaying.ViewModels\n{\n public class TopPanelViewModel : ViewModelBase\n {\n public enum Mode { Processing, Enable, Uninstall, Install, SlowInstall };\n private readonly NowPlaying plugin;", "score": 0.8869971632957458 }, { "filename": "source/ViewModels/NowPlayingSettingsViewModel.cs", "retrieved_chunk": "using Playnite.SDK;\nusing Playnite.SDK.Data;\nusing System.Collections.Generic;\nnamespace NowPlaying.ViewModels\n{\n public class NowPlayingSettingsViewModel : ObservableObject, ISettings\n {\n private readonly NowPlaying plugin;\n // . editable settings values.\n private NowPlayingSettings settings;", "score": 0.8866572380065918 } ]
csharp
CacheRootViewModel> cacheRoots;
using HarmonyLib; using System; using System.Collections.Generic; using System.Text; using UnityEngine; namespace Ultrapain.Patches { /*public class ObjectActivator : MonoBehaviour { public int originalInstanceID = 0; public MonoBehaviour activator; void Start() { if (gameObject.GetInstanceID() == originalInstanceID) return; activator?.Invoke("OnClone", 0f); } }*/ public class CommonLinearScaler : MonoBehaviour { public
Transform targetTransform;
public float scaleSpeed = 1f; void Update() { float deltaSize = Time.deltaTime * scaleSpeed; targetTransform.localScale = new Vector3(targetTransform.localScale.x + deltaSize, targetTransform.localScale.y + deltaSize, targetTransform.localScale.y + deltaSize); } } public class CommonAudioPitchScaler : MonoBehaviour { public AudioSource targetAud; public float scaleSpeed = 1f; void Update() { float deltaPitch = Time.deltaTime * scaleSpeed; targetAud.pitch += deltaPitch; } } public class RotateOnSpawn : MonoBehaviour { public Quaternion targetRotation; private void Awake() { transform.rotation = targetRotation; } } public class CommonActivator : MonoBehaviour { public int originalId; public Renderer rend; public Rigidbody rb; public bool kinematic; public bool colDetect; public Collider col; public AudioSource aud; public List<MonoBehaviour> comps = new List<MonoBehaviour>(); void Awake() { if (originalId == gameObject.GetInstanceID()) return; if (rend != null) rend.enabled = true; if (rb != null) { rb.isKinematic = kinematic; rb.detectCollisions = colDetect; } if (col != null) col.enabled = true; if (aud != null) aud.enabled = true; foreach (MonoBehaviour comp in comps) comp.enabled = true; foreach (Transform child in gameObject.transform) child.gameObject.SetActive(true); } } public class GrenadeExplosionOverride : MonoBehaviour { public bool harmlessMod = false; public float harmlessSize = 1f; public float harmlessSpeed = 1f; public float harmlessDamage = 1f; public int harmlessPlayerDamageOverride = -1; public bool normalMod = false; public float normalSize = 1f; public float normalSpeed = 1f; public float normalDamage = 1f; public int normalPlayerDamageOverride = -1; public bool superMod = false; public float superSize = 1f; public float superSpeed = 1f; public float superDamage = 1f; public int superPlayerDamageOverride = -1; struct StateInfo { public GameObject tempHarmless; public GameObject tempNormal; public GameObject tempSuper; public StateInfo() { tempHarmless = tempNormal = tempSuper = null; } } [HarmonyBefore] static bool Prefix(Grenade __instance, out StateInfo __state) { __state = new StateInfo(); GrenadeExplosionOverride flag = __instance.GetComponent<GrenadeExplosionOverride>(); if (flag == null) return true; if (flag.harmlessMod) { __state.tempHarmless = __instance.harmlessExplosion = GameObject.Instantiate(__instance.harmlessExplosion); foreach (Explosion exp in __instance.harmlessExplosion.GetComponentsInChildren<Explosion>()) { exp.damage = (int)(exp.damage * flag.harmlessDamage); exp.maxSize *= flag.harmlessSize; exp.speed *= flag.harmlessSize * flag.harmlessSpeed; exp.playerDamageOverride = flag.harmlessPlayerDamageOverride; } } if (flag.normalMod) { __state.tempNormal = __instance.explosion = GameObject.Instantiate(__instance.explosion); foreach (Explosion exp in __instance.explosion.GetComponentsInChildren<Explosion>()) { exp.damage = (int)(exp.damage * flag.normalDamage); exp.maxSize *= flag.normalSize; exp.speed *= flag.normalSize * flag.normalSpeed; exp.playerDamageOverride = flag.normalPlayerDamageOverride; } } if (flag.superMod) { __state.tempSuper = __instance.superExplosion = GameObject.Instantiate(__instance.superExplosion); foreach (Explosion exp in __instance.superExplosion.GetComponentsInChildren<Explosion>()) { exp.damage = (int)(exp.damage * flag.superDamage); exp.maxSize *= flag.superSize; exp.speed *= flag.superSize * flag.superSpeed; exp.playerDamageOverride = flag.superPlayerDamageOverride; } } return true; } static void Postfix(StateInfo __state) { if (__state.tempHarmless != null) GameObject.Destroy(__state.tempHarmless); if (__state.tempNormal != null) GameObject.Destroy(__state.tempNormal); if (__state.tempSuper != null) GameObject.Destroy(__state.tempSuper); } } }
Ultrapain/Patches/CommonComponents.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Stalker.cs", "retrieved_chunk": " }\n }\n __instance.gameObject.SetActive(false);\n Object.Destroy(__instance.gameObject);\n return false;\n }\n }\n public class SandificationZone_Enter_Patch\n {\n static void Postfix(SandificationZone __instance, Collider __0)", "score": 0.8521316051483154 }, { "filename": "Ultrapain/Patches/SisyphusInstructionist.cs", "retrieved_chunk": " esi.enraged = true;\n }\n GameObject effect = GameObject.Instantiate(Plugin.enrageEffect, __instance.transform);\n effect.transform.localScale = Vector3.one * 0.2f;\n }\n }*/\n public class SisyphusInstructionist_Start\n {\n public static GameObject _shockwave;\n public static GameObject shockwave", "score": 0.8470569849014282 }, { "filename": "Ultrapain/Patches/SwordsMachine.cs", "retrieved_chunk": " sm.SendMessage(\"SetSpeed\");\n }\n private void Awake()\n {\n anim = GetComponent<Animator>();\n eid = GetComponent<EnemyIdentifier>();\n }\n public float speed = 1f;\n private void Update()\n {", "score": 0.8130919337272644 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " protected override void OnCreateUI(RectTransform fieldUI)\n {\n currentUI = fieldUI;\n fieldUI.sizeDelta = new Vector2(fieldUI.sizeDelta.x, space);\n }\n }\n public static class ConfigManager\n {\n public static PluginConfigurator config = null;\n public static void AddMissingPresets()", "score": 0.8120753765106201 }, { "filename": "Ultrapain/Patches/Cerberus.cs", "retrieved_chunk": " }\n }\n class StatueBoss_Start_Patch\n {\n static void Postfix(StatueBoss __instance)\n {\n __instance.gameObject.AddComponent<CerberusFlag>();\n }\n }\n}", "score": 0.8094459772109985 } ]
csharp
Transform targetTransform;
using HarmonyLib; using UnityEngine; namespace Ultrapain.Patches { class Solider_Start_Patch { static void Postfix(ZombieProjectiles __instance, ref GameObject ___decProjectile, ref GameObject ___projectile, ref EnemyIdentifier ___eid, ref Animator ___anim) { if (___eid.enemyType != EnemyType.Soldier) return; /*___projectile = Plugin.soliderBullet; if (Plugin.decorativeProjectile2.gameObject != null) ___decProjectile = Plugin.decorativeProjectile2.gameObject;*/ __instance.gameObject.AddComponent<SoliderShootCounter>(); } } class Solider_SpawnProjectile_Patch { static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid, ref GameObject ___origWP) { if (___eid.enemyType != EnemyType.Soldier) return; ___eid.weakPoint = null; } } class SoliderGrenadeFlag : MonoBehaviour { public GameObject tempExplosion; } class Solider_ThrowProjectile_Patch { static void Postfix(ZombieProjectiles __instance, ref GameObject ___currentProjectile, ref EnemyIdentifier ___eid, ref GameObject ___player, ref Animator ___anim, ref float ___coolDown) { if (___eid.enemyType != EnemyType.Soldier) return; ___currentProjectile.GetComponent<ProjectileSpread>().spreadAmount = 10; ___currentProjectile.SetActive(true); SoliderShootCounter counter = __instance.gameObject.GetComponent<SoliderShootCounter>(); if (counter.remainingShots > 0) { counter.remainingShots -= 1; if (counter.remainingShots != 0) { ___anim.Play("Shoot", 0, Plugin.SoliderShootAnimationStart / 2f); ___anim.fireEvents = true; __instance.DamageStart(); ___coolDown = 0; } else { counter.remainingShots = ConfigManager.soliderShootCount.value; if (ConfigManager.soliderShootGrenadeToggle.value) { GameObject grenade = GameObject.Instantiate(Plugin.shotgunGrenade.gameObject, ___currentProjectile.transform.position, ___currentProjectile.transform.rotation); grenade.transform.Translate(Vector3.forward * 0.5f); Vector3 targetPos = Plugin.PredictPlayerPosition(__instance.GetComponent<Collider>(), ___eid.totalSpeedModifier); grenade.transform.LookAt(targetPos); Rigidbody rb = grenade.GetComponent<Rigidbody>(); //rb.maxAngularVelocity = 10000; //foreach (Rigidbody r in grenade.GetComponentsInChildren<Rigidbody>()) // r.maxAngularVelocity = 10000; rb.AddForce(grenade.transform.forward * Plugin.SoliderGrenadeForce); //rb.velocity = ___currentProjectile.transform.forward * Plugin.instance.SoliderGrenadeForce; rb.useGravity = false; grenade.GetComponent<Grenade>().enemy = true; grenade.GetComponent<Grenade>().CanCollideWithPlayer(true); grenade.AddComponent<SoliderGrenadeFlag>(); } } } //counter.remainingShots = ConfigManager.soliderShootCount.value; } } class Grenade_Explode_Patch { static bool Prefix(
Grenade __instance, out bool __state) {
__state = false; SoliderGrenadeFlag flag = __instance.GetComponent<SoliderGrenadeFlag>(); if (flag == null) return true; flag.tempExplosion = GameObject.Instantiate(__instance.explosion); __state = true; foreach(Explosion e in flag.tempExplosion.GetComponentsInChildren<Explosion>()) { e.damage = ConfigManager.soliderGrenadeDamage.value; e.maxSize *= ConfigManager.soliderGrenadeSize.value; e.speed *= ConfigManager.soliderGrenadeSize.value; } __instance.explosion = flag.tempExplosion; return true; } static void Postfix(Grenade __instance, bool __state) { if (!__state) return; SoliderGrenadeFlag flag = __instance.GetComponent<SoliderGrenadeFlag>(); GameObject.Destroy(flag.tempExplosion); } } class SoliderShootCounter : MonoBehaviour { public int remainingShots = ConfigManager.soliderShootCount.value; } }
Ultrapain/Patches/Solider.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Parry.cs", "retrieved_chunk": " GameObject.Destroy(flag.temporaryBigExplosion);\n flag.temporaryBigExplosion = null;\n }\n }\n }\n }\n class Grenade_Collision_Patch\n {\n static float lastTime = 0;\n static bool Prefix(Grenade __instance, Collider __0)", "score": 0.8950755596160889 }, { "filename": "Ultrapain/Patches/MaliciousFace.cs", "retrieved_chunk": " flag.charging = false;\n }\n return true;\n }\n }\n class MaliciousFace_ShootProj_Patch\n {\n /*static bool Prefix(SpiderBody __instance, ref GameObject ___proj, out bool __state)\n {\n __state = false;", "score": 0.8716609477996826 }, { "filename": "Ultrapain/Patches/Parry.cs", "retrieved_chunk": " exp.speed *= ConfigManager.grenadeBoostSizeMultiplier.value;\n }\n __instance.superExplosion = explosion;\n flag.temporaryBigExplosion = explosion;\n }\n }\n return true;\n }\n static void Postfix(Grenade __instance, ref bool ___exploded)\n {", "score": 0.8710786700248718 }, { "filename": "Ultrapain/Patches/DruidKnight.cs", "retrieved_chunk": " aud.time = offset;\n aud.Play();\n return true;\n }\n }\n class Drone_Explode\n {\n static bool Prefix(bool ___exploded, out bool __state)\n {\n __state = ___exploded;", "score": 0.861433207988739 }, { "filename": "Ultrapain/Patches/Screwdriver.cs", "retrieved_chunk": " {\n targetEids.Clear();\n }\n }\n }\n }\n class Harpoon_Start\n {\n static void Postfix(Harpoon __instance)\n {", "score": 0.8596837520599365 } ]
csharp
Grenade __instance, out bool __state) {
using Microsoft.AspNetCore.Identity; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Security.Cryptography; using System.Text; using UserManagement.Data.Models; namespace UserManagement.Api.Services { public class AuthService : IAuthService { private readonly UserManager<ApplicationUser> userManager; private readonly RoleManager<IdentityRole> roleManager; private readonly IConfiguration _configuration; public AuthService(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, IConfiguration configuration) { this.userManager = userManager; this.roleManager = roleManager; _configuration = configuration; } public async Task<(int, string)> Registeration(RegistrationModel model, string role) { var userExists = await userManager.FindByNameAsync(model.Username); if (userExists != null) return (0, "User already exists"); ApplicationUser user = new() { Email = model.Email, SecurityStamp = Guid.NewGuid().ToString(), UserName = model.Username, FirstName = model.FirstName, LastName = model.LastName, }; var createUserResult = await userManager.CreateAsync(user, model.Password); if (!createUserResult.Succeeded) return (0, "User creation failed! Please check user details and try again."); if (!await roleManager.RoleExistsAsync(role)) await roleManager.CreateAsync(new IdentityRole(role)); if (await roleManager.RoleExistsAsync(role)) await userManager.AddToRoleAsync(user, role); return (1, "User created successfully!"); } public async Task<
TokenViewModel> Login(LoginModel model) {
TokenViewModel _TokenViewModel = new(); var user = await userManager.FindByNameAsync(model.Username); if (user == null) { _TokenViewModel.StatusCode = 0; _TokenViewModel.StatusMessage = "Invalid username"; return _TokenViewModel; } if (!await userManager.CheckPasswordAsync(user, model.Password)) { _TokenViewModel.StatusCode = 0; _TokenViewModel.StatusMessage = "Invalid password"; return _TokenViewModel; } var userRoles = await userManager.GetRolesAsync(user); var authClaims = new List<Claim> { new Claim(ClaimTypes.Name, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; foreach (var userRole in userRoles) { authClaims.Add(new Claim(ClaimTypes.Role, userRole)); } _TokenViewModel.AccessToken = GenerateToken(authClaims); _TokenViewModel.RefreshToken = GenerateRefreshToken(); _TokenViewModel.StatusCode = 1; _TokenViewModel.StatusMessage = "Success"; var _RefreshTokenValidityInDays = Convert.ToInt64(_configuration["JWTKey:RefreshTokenValidityInDays"]); user.RefreshToken = _TokenViewModel.RefreshToken; user.RefreshTokenExpiryTime = DateTime.Now.AddDays(_RefreshTokenValidityInDays); await userManager.UpdateAsync(user); return _TokenViewModel; } public async Task<TokenViewModel> GetRefreshToken(GetRefreshTokenViewModel model) { TokenViewModel _TokenViewModel = new(); var principal = GetPrincipalFromExpiredToken(model.AccessToken); string username = principal.Identity.Name; var user = await userManager.FindByNameAsync(username); if (user == null || user.RefreshToken != model.RefreshToken || user.RefreshTokenExpiryTime <= DateTime.Now) { _TokenViewModel.StatusCode = 0; _TokenViewModel.StatusMessage = "Invalid access token or refresh token"; return _TokenViewModel; } var authClaims = new List<Claim> { new Claim(ClaimTypes.Name, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; var newAccessToken = GenerateToken(authClaims); var newRefreshToken = GenerateRefreshToken(); user.RefreshToken = newRefreshToken; await userManager.UpdateAsync(user); _TokenViewModel.StatusCode = 1; _TokenViewModel.StatusMessage = "Success"; _TokenViewModel.AccessToken = newAccessToken; _TokenViewModel.RefreshToken = newRefreshToken; return _TokenViewModel; } private string GenerateToken(IEnumerable<Claim> claims) { var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWTKey:Secret"])); var _TokenExpiryTimeInHour = Convert.ToInt64(_configuration["JWTKey:TokenExpiryTimeInHour"]); var tokenDescriptor = new SecurityTokenDescriptor { Issuer = _configuration["JWTKey:ValidIssuer"], Audience = _configuration["JWTKey:ValidAudience"], //Expires = DateTime.UtcNow.AddHours(_TokenExpiryTimeInHour), Expires = DateTime.UtcNow.AddMinutes(30), SigningCredentials = new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256), Subject = new ClaimsIdentity(claims) }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } private static string GenerateRefreshToken() { var randomNumber = new byte[64]; using var rng = RandomNumberGenerator.Create(); rng.GetBytes(randomNumber); return Convert.ToBase64String(randomNumber); } private ClaimsPrincipal GetPrincipalFromExpiredToken(string? token) { var tokenValidationParameters = new TokenValidationParameters { ValidateAudience = false, ValidateIssuer = false, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWTKey:Secret"])), ValidateLifetime = false }; var tokenHandler = new JwtSecurityTokenHandler(); var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken securityToken); if (securityToken is not JwtSecurityToken jwtSecurityToken || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) throw new SecurityTokenException("Invalid token"); return principal; } } }
UserManagement.Api/Services/AuthService.cs
shahedbd-API.RefreshTokens-c4d606e
[ { "filename": "UserManagement.Api/Services/IAuthService.cs", "retrieved_chunk": "using UserManagement.Data.Models;\nnamespace UserManagement.Api.Services\n{\n public interface IAuthService\n {\n Task<(int, string)> Registeration(RegistrationModel model, string role);\n Task<TokenViewModel> Login(LoginModel model);\n Task<TokenViewModel> GetRefreshToken(GetRefreshTokenViewModel model);\n }\n}", "score": 0.7854800224304199 }, { "filename": "UserManagement.Api/Controllers/RefreshTokensController.cs", "retrieved_chunk": " return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);\n }\n }\n [Authorize]\n [HttpPost]\n [Route(\"revoke/{username}\")]\n public async Task<IActionResult> Revoke(string username)\n {\n var user = await _userManager.FindByNameAsync(username);\n if (user == null) return BadRequest(\"Invalid user name\");", "score": 0.7722214460372925 }, { "filename": "UserManagement.Api/Controllers/RefreshTokensController.cs", "retrieved_chunk": " user.RefreshToken = null;\n await _userManager.UpdateAsync(user);\n return Ok(\"Success\");\n }\n [Authorize]\n [HttpPost]\n [Route(\"revoke-all\")]\n public async Task<IActionResult> RevokeAll()\n {\n var users = _userManager.Users.ToList();", "score": 0.7671352028846741 }, { "filename": "UserManagement.Api/Controllers/RefreshTokensController.cs", "retrieved_chunk": " foreach (var user in users)\n {\n user.RefreshToken = null;\n await _userManager.UpdateAsync(user);\n }\n return Ok(\"Success\");\n }\n }\n}", "score": 0.7608644962310791 }, { "filename": "UserManagement.Api/Controllers/AuthenticationController.cs", "retrieved_chunk": " {\n if (!ModelState.IsValid)\n return BadRequest(\"Invalid payload\");\n var (status, message) = await _authService.Registeration(model, UserRoles.Admin);\n if (status == 0)\n {\n return BadRequest(message);\n }\n return CreatedAtAction(nameof(Register), model);\n }", "score": 0.7550828456878662 } ]
csharp
TokenViewModel> Login(LoginModel model) {
using Newtonsoft.Json; namespace Gum.InnerThoughts { public class CharacterScript { /// <summary> /// List of tasks or events that the <see cref="Situations"/> may do. /// </summary> [JsonProperty] private readonly SortedList<int,
Situation> _situations = new();
private readonly Dictionary<string, int> _situationNames = new(); [JsonProperty] private int _nextId = 0; public readonly string Name; public CharacterScript(string name) { Name = name; } private Situation? _currentSituation; public Situation CurrentSituation => _currentSituation ?? throw new InvalidOperationException("☠️ Unable to fetch an active situation."); public bool HasCurrentSituation => _currentSituation != null; public bool AddNewSituation(ReadOnlySpan<char> name) { int id = _nextId++; string situationName = name.TrimStart().TrimEnd().ToString(); if (_situationNames.ContainsKey(situationName)) { return false; } _currentSituation = new Situation(id, situationName); _situations.Add(id, _currentSituation); _situationNames.Add(situationName, id); return true; } public Situation? FetchSituation(int id) { if (_situations.TryGetValue(id, out Situation? value)) { return value; } return null; } public int? FetchSituationId(string name) { if (_situationNames.TryGetValue(name, out int id)) { return id; } return null; } public string[] FetchAllNames() => _situationNames.Keys.ToArray(); public IEnumerable<Situation> FetchAllSituations() => _situations.Values; } }
src/Gum/InnerThoughts/CharacterScript.cs
isadorasophia-gum-032cb2d
[ { "filename": "src/Gum/InnerThoughts/Line.cs", "retrieved_chunk": "using System.Diagnostics;\nnamespace Gum.InnerThoughts\n{\n [DebuggerDisplay(\"{Text}\")]\n public readonly struct Line\n {\n /// <summary>\n /// This may be the speaker name or \"Owner\" for whoever owns this script.\n /// </summary>\n public readonly string? Speaker;", "score": 0.8333876132965088 }, { "filename": "src/Gum/Parser_Trimmer.cs", "retrieved_chunk": "using Gum.InnerThoughts;\nnamespace Gum\n{\n public partial class Parser\n {\n /// <summary>\n /// This will trim the graph: clean up empty edges and such.\n /// </summary>\n private bool Trim()\n {", "score": 0.8229867219924927 }, { "filename": "src/Gum/InnerThoughts/Situation.cs", "retrieved_chunk": "using Gum.Utilities;\nusing Newtonsoft.Json;\nusing System.Diagnostics;\nnamespace Gum.InnerThoughts\n{\n [DebuggerDisplay(\"{Name}\")]\n public class Situation\n {\n [JsonProperty]\n public readonly int Id = 0;", "score": 0.8130151033401489 }, { "filename": "src/Gum/InnerThoughts/EdgeKind.cs", "retrieved_chunk": "namespace Gum.InnerThoughts\n{\n public enum EdgeKind\n {\n /// <summary>\n /// This will pick in consecutive order, whatever matches first.\n /// </summary>\n Next = 1,\n /// <summary>\n /// This will pick random dialogs.", "score": 0.8077316880226135 }, { "filename": "src/Gum/Utilities/InnerThoughtsHelpers.cs", "retrieved_chunk": "using Gum.InnerThoughts;\nnamespace Gum.Utilities\n{\n internal static class InnerThoughtsHelpers\n {\n /// <summary>\n /// Returns whether the order in which the blocks are available within an edge\n /// is relevant or not when picking a new option.\n /// </summary>\n public static bool IsSequential(this EdgeKind kind)", "score": 0.803695797920227 } ]
csharp
Situation> _situations = new();
using FayElf.Plugins.WeChat.OfficialAccount.Model; using System; using System.Collections.Generic; using System.Linq; using XiaoFeng.Http; using System.Text; using System.Threading.Tasks; using XiaoFeng; /**************************************************************** * Copyright © (2022) www.fayelf.com All Rights Reserved. * * Author : jacky * * QQ : 7092734 * * Email : [email protected] * * Site : www.fayelf.com * * Create Time : 2022-03-16 15:18:40 * * Version : v 1.0.0 * * CLR Version : 4.0.30319.42000 * *****************************************************************/ namespace FayElf.Plugins.WeChat.OfficialAccount { /// <summary> /// 二维码 /// </summary> public class QRCode { #region 构造器 /// <summary> /// 无参构造器 /// </summary> public QRCode() { } #endregion #region 属性 #endregion #region 方法 /// <summary> /// 创建二维码 /// </summary> /// <param name="accessToken">网页授权接口调用凭证</param> /// <param name="qrcodeType">二维码类型</param> /// <param name="scene_id">开发者自行设定的参数</param> /// <param name="seconds">该二维码有效时间,以秒为单位。 最大不超过2592000(即30天),此字段如果不填,则默认有效期为60秒。</param> /// <returns></returns> public static QRCodeResult CreateParameterQRCode(string accessToken,
QrcodeType qrcodeType, int scene_id, int seconds = 60) {
var result = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Post, Address = $"https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={accessToken}", BodyData = $@"{{{(qrcodeType == QrcodeType.QR_STR_SCENE ? ($@"""expire_seconds"":{seconds},") : "")}""action_name"": ""{qrcodeType}"", ""action_info"": {{""scene"": {{""scene_id"": {scene_id}}}}}}}" }); if (result.StatusCode == System.Net.HttpStatusCode.OK) { return result.Html.JsonToObject<QRCodeResult>(); } else return new QRCodeResult { ErrCode = 500, ErrMsg = "请求出错." }; } #endregion #region 通过ticket 获取二维码 /// <summary> /// 通过ticket 获取二维码 /// </summary> /// <param name="ticket">二维码ticket</param> /// <returns>ticket正确情况下,http 返回码是200,是一张图片,可以直接展示或者下载。</returns> public static byte[] GetQrCode(string ticket) { return HttpHelper.GetHtml($"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={ticket}").Data; } #endregion } }
OfficialAccount/QRCode.cs
zhuovi-FayElf.Plugins.WeChat-5725d1e
[ { "filename": "Applets/Applets.cs", "retrieved_chunk": " #region 获取小程序二维码\n /// <summary>\n /// 获取小程序二维码\n /// </summary>\n /// <param name=\"path\">扫码进入的小程序页面路径,最大长度 128 字节,不能为空;对于小游戏,可以只传入 query 部分,来实现传参效果,如:传入 \"?foo=bar\",即可在 wx.getLaunchOptionsSync 接口中的 query 参数获取到 {foo:\"bar\"}。</param>\n /// <param name=\"width\">二维码的宽度,单位 px。最小 280px,最大 1280px;默认是430</param>\n /// <returns></returns>\n public QrCodeResult CreateQRCode(string path, int width)\n {\n var config = this.Config.GetConfig(WeChatType.Applets);", "score": 0.8671243786811829 }, { "filename": "OfficialAccount/OAuthAPI.cs", "retrieved_chunk": " }\n #endregion\n #region 检验授权凭证(access_token)是否有效\n /// <summary>\n /// 检验授权凭证(access_token)是否有效\n /// </summary>\n /// <param name=\"accessToken\">网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同</param>\n /// <param name=\"openId\">用户的唯一标识</param>\n /// <returns></returns>\n public static Boolean CheckAccessToken(string accessToken, string openId)", "score": 0.8473444581031799 }, { "filename": "OfficialAccount/OAuthAPI.cs", "retrieved_chunk": " }\n }\n #endregion\n #region 拉取用户信息(需scope为 snsapi_userinfo)\n /// <summary>\n /// 拉取用户信息(需scope为 snsapi_userinfo)\n /// </summary>\n /// <param name=\"accessToken\">网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同</param>\n /// <param name=\"openId\">用户的唯一标识</param>\n /// <param name=\"lang\">返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语</param>", "score": 0.8351080417633057 }, { "filename": "OfficialAccount/Subscribe.cs", "retrieved_chunk": " /// </summary>\n /// <param name=\"tid\">模板标题 id,可通过getPubTemplateTitleList接口获取,也可登录公众号后台查看获取</param>\n /// <param name=\"kidList\">开发者自行组合好的模板关键词列表,关键词顺序可以自由搭配(例如 [3,5,4] 或 [4,5,3]),最多支持5个,最少2个关键词组合</param>\n /// <param name=\"sceneDesc\">服务场景描述,15个字以内</param>\n /// <returns></returns>\n public AddTemplateResult AddTemplate(string tid, int kidList, string sceneDesc)\n {\n var config = this.Config.GetConfig(WeChatType.Applets);\n return Common.Execute(config.AppID, config.AppSecret, token =>\n {", "score": 0.8277480006217957 }, { "filename": "OfficialAccount/Model/QRCodeResult.cs", "retrieved_chunk": " [Description(\"获取的二维码ticket,凭借此ticket可以在有效时间内换取二维码。\")]\n [JsonElement(\"ticket\")]\n public string Ticket { get; set; }\n /// <summary>\n /// 二维码图片解析后的地址,开发者可根据该地址自行生成需要的二维码图片\n /// </summary>\n [Description(\"二维码图片解析后的地址,开发者可根据该地址自行生成需要的二维码图片\")]\n [JsonElement(\"url\")]\n public string Url { get; set; }\n /// <summary>", "score": 0.8176754713058472 } ]
csharp
QrcodeType qrcodeType, int scene_id, int seconds = 60) {
using UnityEngine; namespace Ultrapain.Patches { class CerberusFlag : MonoBehaviour { public int extraDashesRemaining = ConfigManager.cerberusTotalDashCount.value - 1; public
Transform head;
public float lastParryTime; private EnemyIdentifier eid; private void Awake() { eid = GetComponent<EnemyIdentifier>(); head = transform.Find("Armature/Control/Waist/Chest/Chest_001/Head"); if (head == null) head = UnityUtils.GetChildByTagRecursively(transform, "Head"); } public void MakeParryable() { lastParryTime = Time.time; GameObject flash = GameObject.Instantiate(Plugin.parryableFlash, head.transform.position, head.transform.rotation, head); flash.transform.LookAt(CameraController.Instance.transform); flash.transform.position += flash.transform.forward; flash.transform.Rotate(Vector3.up, 90, Space.Self); } } class StatueBoss_StopTracking_Patch { static void Postfix(StatueBoss __instance, Animator ___anim) { CerberusFlag flag = __instance.GetComponent<CerberusFlag>(); if (flag == null) return; if (___anim.GetCurrentAnimatorClipInfo(0)[0].clip.name != "Tackle") return; flag.MakeParryable(); } } class StatueBoss_Stomp_Patch { static void Postfix(StatueBoss __instance) { CerberusFlag flag = __instance.GetComponent<CerberusFlag>(); if (flag == null) return; flag.MakeParryable(); } } class Statue_GetHurt_Patch { static bool Prefix(Statue __instance, EnemyIdentifier ___eid) { CerberusFlag flag = __instance.GetComponent<CerberusFlag>(); if (flag == null) return true; if (___eid.hitter != "punch" && ___eid.hitter != "shotgunzone") return true; float deltaTime = Time.time - flag.lastParryTime; if (deltaTime > ConfigManager.cerberusParryableDuration.value / ___eid.totalSpeedModifier) return true; flag.lastParryTime = 0; ___eid.health -= ConfigManager.cerberusParryDamage.value; MonoSingleton<FistControl>.Instance.currentPunch.Parry(false, ___eid); return true; } } class StatueBoss_StopDash_Patch { public static void Postfix(StatueBoss __instance, ref int ___tackleChance) { CerberusFlag flag = __instance.GetComponent<CerberusFlag>(); if (flag == null) return; if (flag.extraDashesRemaining > 0) { flag.extraDashesRemaining -= 1; __instance.SendMessage("Tackle"); ___tackleChance -= 20; } else flag.extraDashesRemaining = ConfigManager.cerberusTotalDashCount.value - 1; } } class StatueBoss_Start_Patch { static void Postfix(StatueBoss __instance) { __instance.gameObject.AddComponent<CerberusFlag>(); } } }
Ultrapain/Patches/Cerberus.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Turret.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class TurretFlag : MonoBehaviour\n {\n public int shootCountRemaining = ConfigManager.turretBurstFireCount.value;\n }\n class TurretStart\n {", "score": 0.8699682950973511 }, { "filename": "Ultrapain/Patches/Stray.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nusing UnityEngine.AI;\nnamespace Ultrapain.Patches\n{\n public class StrayFlag : MonoBehaviour\n {\n //public int extraShotsRemaining = 6;\n private Animator anim;\n private EnemyIdentifier eid;", "score": 0.8356590867042542 }, { "filename": "Ultrapain/Patches/Parry.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class GrenadeParriedFlag : MonoBehaviour\n {\n public int parryCount = 1;\n public bool registeredStyle = false;\n public bool bigExplosionOverride = false;\n public GameObject temporaryExplosion;", "score": 0.825055718421936 }, { "filename": "Ultrapain/Patches/MaliciousFace.cs", "retrieved_chunk": "using HarmonyLib;\nusing System;\nusing System.ComponentModel;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class MaliciousFaceFlag : MonoBehaviour\n {\n public bool charging = false;\n }", "score": 0.8245181441307068 }, { "filename": "Ultrapain/Patches/SwordsMachine.cs", "retrieved_chunk": "using HarmonyLib;\nusing System.Security.Cryptography;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class SwordsMachineFlag : MonoBehaviour\n {\n public SwordsMachine sm;\n public Animator anim;\n public EnemyIdentifier eid;", "score": 0.8021724224090576 } ]
csharp
Transform head;
using DotNetLineBotSdk.Helpers; using DotNetLineBotSdk.Message; using DotNetLineBotSdk.MessageEvent; using GPTLinebot.Models; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using System.Text; namespace GPTLinebot.Controllers { [Route("api/[controller]")] [ApiController] public class Linebot2Controller : ControllerBase { private string channel_Access_Token = "line channel Access Token"; string model = "text-davinci-003"; int maxTokens = 500; double temperature = 0.5; string apiKey = "openai api key"; string endpoint = "https://api.openai.com/v1/completions"; string userPrompt = string.Empty; string historyPrompt = string.Empty; private readonly
UserHistoryPrompt _userHistoryPrompt;
public Linebot2Controller(UserHistoryPrompt userHistoryPrompt) { _userHistoryPrompt = userHistoryPrompt; } [HttpPost] public async Task<IActionResult> Post() { var replyEvent = new ReplyEvent(channel_Access_Token); try { //Get Post RawData (json format) var req = this.HttpContext.Request; using (var bodyReader = new StreamReader(stream: req.Body, encoding: Encoding.UTF8, detectEncodingFromByteOrderMarks: false, bufferSize: 1024, leaveOpen: true)) { var body = await bodyReader.ReadToEndAsync(); var lineReceMsg = ReceivedMessageConvert.ReceivedMessage(body); if (lineReceMsg != null && lineReceMsg.Events[0].Type == WebhookEventType.message.ToString()) { //get user msg var userMsg = lineReceMsg.Events[0].Message.Text; //History Prompt foreach (var item in _userHistoryPrompt.HistoryPrompt) { historyPrompt += " " + item; } //combine Prompt userPrompt = historyPrompt + " ME: " + userMsg+"/n AI:" ; var promptModel = new OpenAiRequestModel() { Prompt = userPrompt, Model = model, Max_tokens = maxTokens, Temperature = temperature }; //send to openai api var completionMsg = await GenerateText(promptModel); //keep question & ans _userHistoryPrompt.HistoryPrompt.Add(userMsg + completionMsg.Choices[0].Text); //send reply msg var txtMessage = new TextMessage(completionMsg.Choices[0].Text); await replyEvent.ReplyAsync(lineReceMsg.Events[0].ReplyToken, new List<IMessage>() { txtMessage }); } } } catch (Exception ex) { return Ok(); } return Ok(); } private async Task<Completion> GenerateText(OpenAiRequestModel model) { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey); var json = JsonConvert.SerializeObject(model); var data = new StringContent(json, Encoding.UTF8, "application/json"); var response = await client.PostAsync(endpoint, data); var responseContent = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<Completion>(responseContent); } } } }
GPTLinebot/Controllers/Linebot2Controller.cs
iangithub-ChatGPT101-8fe781a
[ { "filename": "GPTLinebot/Controllers/Linebot3Controller.cs", "retrieved_chunk": " [Route(\"api/[controller]\")]\n [ApiController]\n public class Linebot3Controller : ControllerBase\n {\n private string channel_Access_Token = \"line channel Access Token\";\n string apiKey = \"openai api key\";\n string endpoint = \"https://api.openai.com/v1/chat/completions\";\n string userPrompt = string.Empty;\n string historyPrompt = string.Empty;\n private readonly ChatGptRequestModel _chatGptRequestModel;", "score": 0.8957436084747314 }, { "filename": "GPTLinebot/Controllers/LinebotController.cs", "retrieved_chunk": " double temperature = 0.5; //介於 0~1,越接近0,模型回覆的內容變化越小,背答案的機器人\n string apiKey = \"openai api key\";\n string endpoint = \"https://api.openai.com/v1/completions\";\n [HttpPost]\n public async Task<IActionResult> Post()\n {\n var replyEvent = new ReplyEvent(channel_Access_Token);\n try\n {\n //Get Post RawData (json format)", "score": 0.7802764773368835 }, { "filename": "GPTLinebot/Models/ChatGptRequestModel.cs", "retrieved_chunk": " public int Max_tokens { get; set; }\n [JsonProperty(PropertyName = \"temperature\")]\n public double Temperature { get; set; }\n public ChatGptRequestModel()\n {\n Messages = new List<Message>();\n Model = \"gpt-3.5-turbo\";\n }\n }\n public class Completion", "score": 0.7661382555961609 }, { "filename": "GPTLinebot/Controllers/LinebotController.cs", "retrieved_chunk": " //get user msg\n var userMsg = $\"user:{lineReceMsg.Events[0].Message.Text} \\n ai:\";\n var promptModel = new OpenAiRequestModel() { Prompt = userMsg, Model = model, Max_tokens = maxTokens, Temperature = temperature };\n //send to openai api\n var completionMsg = await GenerateText(promptModel);\n //send reply msg\n var txtMessage = new TextMessage(completionMsg.Choices[0].Text);\n await replyEvent.ReplyAsync(lineReceMsg.Events[0].ReplyToken,\n new List<IMessage>() {\n txtMessage", "score": 0.7565692663192749 }, { "filename": "GPTLinebot/Models/Completion.cs", "retrieved_chunk": " [JsonProperty(PropertyName = \"prompt\")]\n public string Prompt { get; set; }\n [JsonProperty(PropertyName = \"model\")]\n public string Model { get; set; }\n [JsonProperty(PropertyName = \"max_tokens\")]\n public int Max_tokens { get; set; }\n [JsonProperty(PropertyName = \"temperature\")]\n public double Temperature { get; set; }\n }\n}", "score": 0.7562073469161987 } ]
csharp
UserHistoryPrompt _userHistoryPrompt;
using System; using System.Collections.Generic; using ECS.ComponentsAndTags; using UnityEngine; /// <summary> /// A struct to give better inputs on inspector /// </summary> [Serializable] public struct TeamSpawnTransformsData { public Team team; public Transform[] spawnTransforms; } /// <summary> /// This Manager basically holds team and unit data for entity generation /// </summary> public class DataManager : MonoBehaviour { [SerializeField] private TeamSpawnTransformsData[] teamsSpawnData; [SerializeField] private TeamData[] teamsData; public static Dictionary<Team, Vector3[]> TeamsSpawnPoints { get; private set; } public static Dictionary<
Team, List<TeamData>> TeamsData {
get; private set; } /// <summary> /// Clear static values on destroy /// </summary> private void OnDestroy() { TeamsSpawnPoints = null; TeamsData = null; } private void Awake() { Init(); } private void Init() { InitSpawnPoints(); InitTeams(); } /// <summary> /// Storing values on dictionary first to have a better usage /// </summary> private void InitTeams() { TeamsData = new Dictionary<Team, List<TeamData>>(); foreach (var teamData in teamsData) { if (!TeamsData.ContainsKey(teamData.Team)) { TeamsData.Add(teamData.Team, new List<TeamData>()); } TeamsData[teamData.Team].Add(teamData); } } /// <summary> /// Storing values on dictionary first to have a better usage /// </summary> private void InitSpawnPoints() { TeamsSpawnPoints = new Dictionary<Team, Vector3[]>(); foreach (var spawnData in teamsSpawnData) { var spawnPoints = new Vector3[9]; if (spawnData.spawnTransforms.Length != 9) { #if UNITY_EDITOR Debug.LogError("Team Spawn Transform Count Must Be 9"); #endif } for (int i = 0; i < 9; i++) { var spawnTransform = spawnData.spawnTransforms[i]; spawnPoints[i] = new Vector3(spawnTransform.position.x, 1f, spawnTransform.position.z); } TeamsSpawnPoints.Add(spawnData.team, spawnPoints); } } }
Assets/Scripts/DataManager.cs
aknkrstozkn-BattleSimulator-DOTS-48e9e68
[ { "filename": "Assets/Scripts/PrefabsToEntityConverter.cs", "retrieved_chunk": "\t[SerializeField] private TeamUnitPrefabData[] teamsUnitPrefab;\n\t[SerializeField] private GameObject unitHealthDisplayPrefab;\n\tpublic static Dictionary<Team, Entity> TeamsEntityDic { get; private set; }\n\tpublic static Entity UnitHealthDisplay { get; private set; }\n\tprivate void Awake()\n\t{\n\t\tTeamsEntityDic = new Dictionary<Team, Entity>();\n\t\tvar settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null);\n\t\tforeach (var teamUnitPrefab in teamsUnitPrefab)\n\t\t{", "score": 0.8525082468986511 }, { "filename": "Assets/Scripts/ScrollViewContentInitializer.cs", "retrieved_chunk": "using ECS.ComponentsAndTags;\nusing UnityEngine;\n/// <summary>\n/// This class generates TeamButtons for ScrollViews \n/// </summary>\npublic class ScrollViewContentInitializer : MonoBehaviour\n{\n [SerializeField] public Team team;\n [SerializeField] public TeamButton teamButtonPrefab;\n private void Start()", "score": 0.8320666551589966 }, { "filename": "Assets/Scripts/TeamData.cs", "retrieved_chunk": "\tpublic int slotIndex;\n\tpublic UnitData unitData;\n}\n/// <summary>\n/// This SO is the base data holder. it holds data of a team.\n/// </summary>\n[CreateAssetMenu(fileName = \"TeamData\", menuName = \"ScriptableObjects/TeamData\", order = 1)]\npublic class TeamData : ScriptableObject\n{\n\t[SerializeField] private string teamName;", "score": 0.8293043375015259 }, { "filename": "Assets/Scripts/PlatformController.cs", "retrieved_chunk": "using UnityEngine;\n/// <summary>\n/// To control starting platform of teams. Just for polish.\n/// </summary>\npublic class PlatformController : MonoBehaviour\n{\n\t[SerializeField] private GameObject[] teamsPlatforms;\n\tprivate void Awake()\n\t{\n\t\tSignUpEvents();", "score": 0.8227611780166626 }, { "filename": "Assets/Scripts/UIController.cs", "retrieved_chunk": "using UnityEngine;\n/// <summary>\n/// A Basic UI controller\n/// </summary>\npublic class UIController : MonoBehaviour\n{\n [SerializeField] private GameObject preGameUI;\n [SerializeField] private GameObject inGameUI;\n [SerializeField] private GameObject endGameUI;\n [SerializeField] private GameObject winText;", "score": 0.78798508644104 } ]
csharp
Team, List<TeamData>> TeamsData {
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace TreeifyTask { public class TaskNode : ITaskNode { private static Random rnd = new Random(); private readonly List<Task> taskObjects = new(); private readonly List<ITaskNode> childTasks = new(); private bool hasCustomAction; private Func<IProgressReporter, CancellationToken, Task> action = async (rep, tok) => await Task.Yield(); public event ProgressReportingEventHandler Reporting; private bool seriesRunnerIsBusy; private bool concurrentRunnerIsBusy; public TaskNode() { this.Id = rnd.Next() + string.Empty; this.Reporting += OnSelfReporting; } public TaskNode(string Id) : this() { this.Id = Id ?? rnd.Next() + string.Empty; } public TaskNode(string Id, Func<
IProgressReporter, CancellationToken, Task> cancellableProgressReportingAsyncFunction) : this(Id) {
this.SetAction(cancellableProgressReportingAsyncFunction); } #region Props public string Id { get; set; } public double ProgressValue { get; private set; } public object ProgressState { get; private set; } public TaskStatus TaskStatus { get; private set; } public ITaskNode Parent { get; set; } public IEnumerable<ITaskNode> ChildTasks => this.childTasks; #endregion Props public void AddChild(ITaskNode childTask) { childTask = childTask ?? throw new ArgumentNullException(nameof(childTask)); childTask.Parent = this; // Ensure this after setting its parent as this EnsureNoCycles(childTask); childTask.Reporting += OnChildReporting; childTasks.Add(childTask); } private class ActionReport { public ActionReport() { this.TaskStatus = TaskStatus.NotStarted; this.ProgressValue = 0; this.ProgressState = null; } public ActionReport(ITaskNode task) { this.Id = task.Id; this.TaskStatus = task.TaskStatus; this.ProgressState = task.ProgressState; this.ProgressValue = task.ProgressValue; } public string Id { get; set; } public TaskStatus TaskStatus { get; set; } public double ProgressValue { get; set; } public object ProgressState { get; set; } public override string ToString() { return $"Id={Id},({TaskStatus}, {ProgressValue}, {ProgressState})"; } } private ActionReport selfActionReport = new(); private void OnSelfReporting(object sender, ProgressReportingEventArgs eventArgs) { TaskStatus = selfActionReport.TaskStatus = eventArgs.TaskStatus; ProgressValue = selfActionReport.ProgressValue = eventArgs.ProgressValue; ProgressState = selfActionReport.ProgressState = eventArgs.ProgressState; } private void OnChildReporting(object sender, ProgressReportingEventArgs eventArgs) { // Child task that reports var cTask = sender as ITaskNode; var allReports = childTasks.Select(t => new ActionReport(t)); if (hasCustomAction) { allReports = allReports.Append(selfActionReport); } this.TaskStatus = allReports.Any(v => v.TaskStatus == TaskStatus.InDeterminate) ? TaskStatus.InDeterminate : TaskStatus.InProgress; this.TaskStatus = allReports.Any(v => v.TaskStatus == TaskStatus.Failed) ? TaskStatus.Failed : this.TaskStatus; if (this.TaskStatus == TaskStatus.Failed) { this.ProgressState = new AggregateException($"{Id}: One or more error occurred in child tasks.", childTasks.Where(v => v.TaskStatus == TaskStatus.Failed && v.ProgressState is Exception) .Select(c => c.ProgressState as Exception)); } this.ProgressValue = allReports.Select(t => t.ProgressValue).Average(); SafeRaiseReportingEvent(this, new ProgressReportingEventArgs { ProgressValue = this.ProgressValue, TaskStatus = this.TaskStatus, ChildTasksRunningInParallel = concurrentRunnerIsBusy, ProgressState = seriesRunnerIsBusy ? cTask.ProgressState : this.ProgressState }); } public async Task ExecuteConcurrently(CancellationToken cancellationToken, bool throwOnError) { if (concurrentRunnerIsBusy || seriesRunnerIsBusy) return; concurrentRunnerIsBusy = true; ResetChildrenProgressValues(); foreach (var child in childTasks) { taskObjects.Add(child.ExecuteConcurrently(cancellationToken, throwOnError)); } taskObjects.Add(ExceptionHandledAction(cancellationToken, throwOnError)); if (taskObjects.Any()) { await Task.WhenAll(taskObjects); } if (throwOnError && taskObjects.Any(t => t.IsFaulted)) { var exs = taskObjects.Where(t => t.IsFaulted).Select(t => t.Exception); throw new AggregateException($"Internal error occurred while executing task - {Id}.", exs); } concurrentRunnerIsBusy = false; if (TaskStatus != TaskStatus.Failed) { if (cancellationToken.IsCancellationRequested) Report(TaskStatus.Cancelled, 0); else Report(TaskStatus.Completed, 100); } } private async Task ExceptionHandledAction(CancellationToken cancellationToken, bool throwOnError) { try { await action(this, cancellationToken); } catch (OperationCanceledException) { // Don't throw this as an error as we have to come out of await. } catch (Exception ex) { this.Report(TaskStatus.Failed, this.ProgressValue, ex); if (throwOnError) { throw new AggregateException($"Internal error occurred while executing the action of task - {Id}.", ex); } } } public async Task ExecuteInSeries(CancellationToken cancellationToken, bool throwOnError) { if (seriesRunnerIsBusy || concurrentRunnerIsBusy) return; seriesRunnerIsBusy = true; ResetChildrenProgressValues(); try { foreach (var child in childTasks) { if (cancellationToken.IsCancellationRequested) break; await child.ExecuteInSeries(cancellationToken, throwOnError); } await ExceptionHandledAction(cancellationToken, throwOnError); } catch (Exception ex) { if (throwOnError) { throw new AggregateException($"Internal error occurred while executing task - {Id}.", ex); } } seriesRunnerIsBusy = false; if (TaskStatus != TaskStatus.Failed) { if (cancellationToken.IsCancellationRequested) Report(TaskStatus.Cancelled, 0); else Report(TaskStatus.Completed, 100); } } public IEnumerable<ITaskNode> ToFlatList() { return FlatList(this); } private void SafeRaiseReportingEvent(object sender, ProgressReportingEventArgs args) { this.Reporting?.Invoke(sender, args); } private void ResetChildrenProgressValues() { taskObjects.Clear(); foreach (var task in childTasks) { task.ResetStatus(); } } /// <summary> /// Throws <see cref="AsyncTasksCycleDetectedException"/> /// </summary> /// <param name="newTask"></param> private void EnsureNoCycles(ITaskNode newTask) { var thisNode = this as ITaskNode; HashSet<ITaskNode> hSet = new HashSet<ITaskNode>(); while (true) { if (thisNode.Parent is null) { break; } if (hSet.Contains(thisNode)) { throw new TaskNodeCycleDetectedException(thisNode, newTask); } hSet.Add(thisNode); thisNode = thisNode.Parent; } var existingTask = FlatList(thisNode).FirstOrDefault(t => t == newTask); if (existingTask != null) { throw new TaskNodeCycleDetectedException(newTask, existingTask.Parent); } } private IEnumerable<ITaskNode> FlatList(ITaskNode root) { yield return root; foreach (var ct in root.ChildTasks) { foreach (var item in FlatList(ct)) yield return item; } } public void RemoveChild(ITaskNode childTask) { childTask.Reporting -= OnChildReporting; childTasks.Remove(childTask); } public void Report(TaskStatus taskStatus, double progressValue, object progressState = null) { SafeRaiseReportingEvent(this, new ProgressReportingEventArgs { ChildTasksRunningInParallel = concurrentRunnerIsBusy, TaskStatus = taskStatus, ProgressValue = progressValue, ProgressState = progressState }); } public void SetAction(Func<IProgressReporter, CancellationToken, Task> cancellableProgressReportingAction) { cancellableProgressReportingAction = cancellableProgressReportingAction ?? throw new ArgumentNullException(nameof(cancellableProgressReportingAction)); hasCustomAction = true; action = cancellableProgressReportingAction; } public void ResetStatus() { this.TaskStatus = TaskStatus.NotStarted; this.ProgressState = null; this.ProgressValue = 0; } public override string ToString() { return $"Id={Id},({TaskStatus}, {ProgressValue}, {ProgressState})"; } } }
Source/TreeifyTask/TaskTree/TaskNode.cs
intuit-TreeifyTask-4b124d4
[ { "filename": "Source/TreeifyTask.BlazorSample/TaskDataModel/code.cs", "retrieved_chunk": " {\n }\n class AT\n {\n public AT(string id,\n CancellableAsyncActionDelegate action,\n params AT[] children)\n {\n Id = id;\n Action = action;", "score": 0.846162736415863 }, { "filename": "Source/TreeifyTask.WpfSample/MainWindow.xaml.cs", "retrieved_chunk": " e.Handled = true;\n }\n private async Task SimpleTimer(IProgressReporter progressReporter, CancellationToken token, CodeBehavior behaviors = null, string progressMessage = null)\n {\n behaviors ??= new CodeBehavior();\n progressMessage ??= \"In progress \";\n progressReporter.Report(TaskStatus.InProgress, 0, $\"{progressMessage}: 0%\");\n bool error = false;\n if (behaviors.ShouldThrowException)\n {", "score": 0.8380959033966064 }, { "filename": "Source/TreeifyTask.BlazorSample/Pages/Error.cshtml.cs", "retrieved_chunk": " [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]\n [IgnoreAntiforgeryToken]\n public class ErrorModel : PageModel\n {\n public string RequestId { get; set; }\n public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);\n private readonly ILogger<ErrorModel> _logger;\n public ErrorModel(ILogger<ErrorModel> logger)\n {\n _logger = logger;", "score": 0.830417811870575 }, { "filename": "Source/TreeifyTask/TaskTree/IProgressReporter.cs", "retrieved_chunk": "namespace TreeifyTask\n{\n public interface IProgressReporter\n {\n void Report(TaskStatus taskStatus, double progressValue, object progressState = default);\n event ProgressReportingEventHandler Reporting;\n }\n}", "score": 0.8229137063026428 }, { "filename": "Source/TreeifyTask/TaskTree/ITaskNode.cs", "retrieved_chunk": " object ProgressState { get; }\n ITaskNode Parent { get; set; }\n IEnumerable<ITaskNode> ChildTasks { get; }\n TaskStatus TaskStatus { get; }\n void SetAction(Func<IProgressReporter, CancellationToken, Task> cancellableProgressReportingAsyncFunction);\n Task ExecuteInSeries(CancellationToken cancellationToken, bool throwOnError);\n Task ExecuteConcurrently(CancellationToken cancellationToken, bool throwOnError);\n void AddChild(ITaskNode childTask);\n void RemoveChild(ITaskNode childTask);\n void ResetStatus();", "score": 0.8214448094367981 } ]
csharp
IProgressReporter, CancellationToken, Task> cancellableProgressReportingAsyncFunction) : this(Id) {
using EleCho.GoCqHttpSdk; using EleCho.GoCqHttpSdk.Message; using EleCho.GoCqHttpSdk.Post; using NodeBot.Classes; using NodeBot.Command; using NodeBot.Event; using NodeBot.Service; using System; using System.Collections.Generic; using System.Linq; using System.Reflection.Metadata; using System.Text; using System.Threading.Tasks; namespace NodeBot { public class NodeBot { public Dictionary<long, int> Permissions = new(); public int OpPermission = 5; public CqWsSession session; public event EventHandler<ConsoleInputEvent>? ConsoleInputEvent; public event EventHandler<ReceiveMessageEvent>? ReceiveMessageEvent; public List<ICommand> Commands = new List<ICommand>(); public List<IService> Services = new List<IService>(); public Queue<Task> ToDoQueue = new Queue<Task>(); public NodeBot(string ip) { session = new(new() { BaseUri = new Uri("ws://" + ip), UseApiEndPoint = true, UseEventEndPoint = true, }); session.PostPipeline.Use(async (context, next) => { if (ReceiveMessageEvent != null) { ReceiveMessageEvent(this, new(context)); } await next(); }); ConsoleInputEvent += (sender, e) => { ExecuteCommand(new ConsoleCommandSender(session, this), e.Text); }; ReceiveMessageEvent += (sender, e) => { if (e.Context is CqPrivateMessagePostContext cqPrivateMessage) { ExecuteCommand(new UserQQSender(session, this, cqPrivateMessage.UserId), cqPrivateMessage.Message); } if (e.Context is CqGroupMessagePostContext cqGroupMessage) { ExecuteCommand(new GroupQQSender(session ,this, cqGroupMessage.GroupId, cqGroupMessage.UserId), cqGroupMessage.Message); } }; } /// <summary> /// 保存权限数据 /// </summary> public void SavePermission() { if (!File.Exists("Permission.json")) { File.Create("Permission.json").Close(); } File.WriteAllText("Permission.json", Newtonsoft.Json.JsonConvert.SerializeObject(Permissions)); } /// <summary> /// 加载权限数据 /// </summary> public void LoadPermission() { if (File.Exists("Permission.json")) { string json = File.ReadAllText("Permission.json"); Permissions = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<long, int>>(json)!; } } public void RegisterCommand(ICommand command) { Commands.Add(command); } public void RegisterService(IService service) { Services.Add(service); } public void Start() { session.Start(); foreach (IService service in Services) { service.OnStart(this); } Task.Run(() => { while (true) { Thread.Sleep(1000); if (ToDoQueue.Count > 0) { Task task; lock (ToDoQueue) { task = ToDoQueue.Dequeue(); } task.Start(); } } }); } public void CallConsoleInputEvent(string text) { if (ConsoleInputEvent != null) { ConsoleInputEvent(this, new(text)); } } public void ExecuteCommand(ICommandSender sender, string commandLine) { ICommand? command = GetCommandByCommandLine(commandLine); if (command == null) { return; } if (sender is ConsoleCommandSender console) { if (command.IsConsoleCommand()) { command.Execute(sender, commandLine); } } } public void ExecuteCommand(IQQSender sender, CqMessage commandLine) { if (commandLine[0] is CqTextMsg cqTextMsg) { ICommand? command = GetCommandByCommandLine(cqTextMsg.Text); if (command == null) { return; } if (HasPermission(command, sender)) { if (sender is UserQQSender userQQSender && command.IsUserCommand()) { command.Execute(sender, commandLine); } if (sender is GroupQQSender groupQQSender && command.IsGroupCommand()) { command.Execute(sender, commandLine); } } else { sender.SendMessage("你没有权限"); } } } public ICommand? GetCommandByCommandLine(string command) { string[] tmp = command.Split(' '); foreach (string s in tmp) { if (s != string.Empty) { return FindCommand(s); } } return null; } public ICommand? FindCommand(string commandName) { foreach (ICommand command in Commands) { if (command.GetName().ToLower() == commandName.ToLower()) { return command; } } return null; } public bool HasPermission(ICommand command, long QQNumber) { int permission = 0; if (Permissions.ContainsKey(QQNumber)) { permission = Permissions[QQNumber]; } return permission >= command.GetDefaultPermission(); } public bool HasPermission(
ICommand command, ICommandSender sender) {
if (sender is IQQSender QQSender) { return HasPermission(command, QQSender.GetNumber()); } if (sender is ConsoleCommandSender) { return true; } return false; } public void RunTask(Task task) { lock (ToDoQueue) { ToDoQueue.Enqueue(task); } } public void RunAction(Action action) { Task task = new(action); RunTask(task); } public void SendGroupMessage(long GroupNumber, CqMessage msgs) { RunAction(() => { session.SendGroupMessage(GroupNumber, msgs); }); } public void SendPrivateMessage(long QQNumber, CqMessage msgs) { RunAction(() => { session.SendPrivateMessage(QQNumber, msgs); }); } public void SendMessage(long Number, CqMessage msgs, UserType type) { if(type == UserType.User) { SendPrivateMessage(Number, msgs); } else if(type == UserType.Group) { SendGroupMessage(Number, msgs); } } } }
NodeBot/NodeBot.cs
Blessing-Studio-NodeBot-ca9921f
[ { "filename": "NodeBot/Command/Op.cs", "retrieved_chunk": " catch { }\n }\n QQSender.GetNodeBot().SavePermission();\n return true;\n }\n public int GetDefaultPermission()\n {\n return 5;\n }\n public string GetName()", "score": 0.8208860158920288 }, { "filename": "NodeBot/Command/AtAll.cs", "retrieved_chunk": " {\n return false;\n }\n public bool IsGroupCommand()\n {\n return true;\n }\n public bool IsUserCommand()\n {\n return false;", "score": 0.8082797527313232 }, { "filename": "NodeBot/Classes/IQQSender.cs", "retrieved_chunk": " {\n this.Session = session;\n this.QQNumber = QQNumber;\n this.Bot = bot;\n }\n public long? GetGroupNumber()\n {\n return null;\n }\n public NodeBot GetNodeBot()", "score": 0.8056515455245972 }, { "filename": "NodeBot/github/GithubCommand.cs", "retrieved_chunk": " public class GithubCommand : ICommand\n {\n public GithubCommand()\n {\n }\n public bool Execute(ICommandSender sender, string commandLine)\n {\n return true;\n }\n public bool Execute(IQQSender QQSender, CqMessage msgs)", "score": 0.803813636302948 }, { "filename": "NodeBot/BTD6/BTD6_RoundCheck.cs", "retrieved_chunk": " return true;\n }\n public bool IsGroupCommand()\n {\n return true;\n }\n public bool IsUserCommand()\n {\n return true;\n }", "score": 0.8011114001274109 } ]
csharp
ICommand command, ICommandSender sender) {
using HarmonyLib; using System; using System.ComponentModel; using UnityEngine; namespace Ultrapain.Patches { class MaliciousFaceFlag : MonoBehaviour { public bool charging = false; } class MaliciousFace_Start_Patch { static void Postfix(SpiderBody __instance, ref GameObject ___proj, ref int ___maxBurst) { __instance.gameObject.AddComponent<MaliciousFaceFlag>(); if (ConfigManager.maliciousFaceHomingProjectileToggle.value) { ___proj = Plugin.homingProjectile; ___maxBurst = Math.Max(0, ConfigManager.maliciousFaceHomingProjectileCount.value - 1); } } } class MaliciousFace_ChargeBeam { static void Postfix(SpiderBody __instance) { if (__instance.TryGetComponent<MaliciousFaceFlag>(out MaliciousFaceFlag flag)) flag.charging = true; } } class MaliciousFace_BeamChargeEnd { static bool Prefix(SpiderBody __instance, float ___maxHealth, ref int ___beamsAmount) { if (__instance.TryGetComponent<MaliciousFaceFlag>(out MaliciousFaceFlag flag) && flag.charging) { if (__instance.health < ___maxHealth / 2) ___beamsAmount = ConfigManager.maliciousFaceBeamCountEnraged.value; else ___beamsAmount = ConfigManager.maliciousFaceBeamCountNormal.value; flag.charging = false; } return true; } } class MaliciousFace_ShootProj_Patch { /*static bool Prefix(SpiderBody __instance, ref GameObject ___proj, out bool __state) { __state = false; if (!Plugin.ultrapainDifficulty || !ConfigManager.enemyTweakToggle.value || !ConfigManager.maliciousFaceHomingProjectileToggle.value) return true; ___proj = Plugin.homingProjectile; __state = true; return true; }*/ static void Postfix(SpiderBody __instance, ref GameObject ___currentProj,
EnemyIdentifier ___eid/*, bool __state*/) {
/*if (!__state) return;*/ Projectile proj = ___currentProj.GetComponent<Projectile>(); proj.target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); proj.speed = ConfigManager.maliciousFaceHomingProjectileSpeed.value; proj.turningSpeedMultiplier = ConfigManager.maliciousFaceHomingProjectileTurnSpeed.value; proj.damage = ConfigManager.maliciousFaceHomingProjectileDamage.value; proj.safeEnemyType = EnemyType.MaliciousFace; proj.speed *= ___eid.totalSpeedModifier; proj.damage *= ___eid.totalDamageModifier; ___currentProj.SetActive(true); } } class MaliciousFace_Enrage_Patch { static void Postfix(SpiderBody __instance) { EnemyIdentifier comp = __instance.GetComponent<EnemyIdentifier>(); for(int i = 0; i < ConfigManager.maliciousFaceRadianceAmount.value; i++) comp.BuffAll(); comp.UpdateBuffs(false); //__instance.spark = new GameObject(); } } /*[HarmonyPatch(typeof(SpiderBody))] [HarmonyPatch("BeamChargeEnd")] class MaliciousFace_BeamChargeEnd_Patch { static void Postfix(SpiderBody __instance, ref bool ___parryable) { if (__instance.currentEnrageEffect == null) return; ___parryable = false; } }*/ /*[HarmonyPatch(typeof(HookArm))] [HarmonyPatch("FixedUpdate")] class HookArm_FixedUpdate_MaliciousFacePatch { static void Postfix(HookArm __instance, ref EnemyIdentifier ___caughtEid) { if (__instance.state == HookState.Caught && ___caughtEid.enemyType == EnemyType.MaliciousFace) { if (___caughtEid.GetComponent<SpiderBody>().currentEnrageEffect == null) return; //__instance.state = HookState.Pulling; ___caughtEid = null; __instance.StopThrow(); } } }*/ }
Ultrapain/Patches/MaliciousFace.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Schism.cs", "retrieved_chunk": " class ZombieProjectile_Start_Patch\n {\n static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid)\n {\n if (___eid.enemyType != EnemyType.Schism)\n return;\n __instance.projectile = Plugin.homingProjectile;\n __instance.decProjectile = Plugin.decorativeProjectile2;\n }\n }*/", "score": 0.856196403503418 }, { "filename": "Ultrapain/Patches/Solider.cs", "retrieved_chunk": " /*___projectile = Plugin.soliderBullet;\n if (Plugin.decorativeProjectile2.gameObject != null)\n ___decProjectile = Plugin.decorativeProjectile2.gameObject;*/\n __instance.gameObject.AddComponent<SoliderShootCounter>();\n }\n }\n class Solider_SpawnProjectile_Patch\n {\n static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid, ref GameObject ___origWP)\n {", "score": 0.832353949546814 }, { "filename": "Ultrapain/Patches/Stray.cs", "retrieved_chunk": " class Swing\n {\n static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid)\n {\n if (___eid.enemyType != EnemyType.Stray)\n return;\n ___eid.weakPoint = null;\n }\n }\n /*[HarmonyPatch(typeof(ZombieProjectiles), \"Swing\")]", "score": 0.8296530842781067 }, { "filename": "Ultrapain/Patches/HideousMass.cs", "retrieved_chunk": " flag.damageBuf = ___eid.totalDamageModifier;\n flag.speedBuf = ___eid.totalSpeedModifier;\n return true;\n }\n static void Postfix(Mass __instance)\n {\n GameObject.Destroy(__instance.explosiveProjectile);\n __instance.explosiveProjectile = Plugin.hideousMassProjectile;\n }\n }", "score": 0.8242509365081787 }, { "filename": "Ultrapain/Patches/Solider.cs", "retrieved_chunk": " {\n static void Postfix(ZombieProjectiles __instance, ref GameObject ___currentProjectile, ref EnemyIdentifier ___eid, ref GameObject ___player, ref Animator ___anim, ref float ___coolDown)\n {\n if (___eid.enemyType != EnemyType.Soldier)\n return;\n ___currentProjectile.GetComponent<ProjectileSpread>().spreadAmount = 10;\n ___currentProjectile.SetActive(true);\n SoliderShootCounter counter = __instance.gameObject.GetComponent<SoliderShootCounter>();\n if (counter.remainingShots > 0)\n {", "score": 0.8236972093582153 } ]
csharp
EnemyIdentifier ___eid/*, bool __state*/) {