This commit is contained in:
2025-08-26 18:33:49 +08:00
parent c3161287d3
commit a897c2e44c
12 changed files with 11864 additions and 80 deletions

100
Source/HarmonyPatch.md Normal file
View File

@@ -0,0 +1,100 @@
Patching
Concept
In order to provide your own code to Harmony, you need to define methods that run in the context of the original method. Harmony provides three types of methods that each offer different possibilities.
Types of patches
Two of them, the Prefix patch and the Postfix patch are easy to understand and you can write them as simple static methods.
Transpiler patches are not methods that are executed together with the original but instead are called in an earlier stage where the instructions of the original are fed into the transpiler so it can process and change them, to finally output the instructions that will build the new original.
A Finalizer patch is a static method that handles exceptions and can change them. It is the only patch type that is immune to exceptions thrown by the original method or by any applied patches. The other patch types are considered part of the original and may not get executed when an exception occurs.
Finally, there is the Reverse Patch. It is different from the previous types in that it patches your methods instead of foreign original methods. To use it, you define a stub that looks like the original in some way and patch the original onto your stub which you can easily call from your own code. You can even transpile the result during the process.
Patches need to be static
Patch methods need to be static because Harmony works with multiple users in different assemblies in mind. In order to guarantee the correct patching order, patches are always re-applied as soon as someone wants to change the original. Since it is hard to serialize data in a generic way across assemblies in .NET, Harmony only stores a method pointer to your patch methods so it can use and apply them at a later point again.
If you need custom state in your patches, it is recommended to use a static variable and store all your patch state in there. Keep in mind that Transpilers are only executed to generate the method so they don't "run" when the original is executed.
Commonly unsupported use cases
Harmony works only in the current AppDomain. Accessing other app domains requires xpc and serialization which is not supported.
Currently, support for generic types and methods is experimental and can give unexpected results. See Edge Cases for more information.
When a method is inlined and the code that tries to mark in for not inlining does not work, your patches are not called because there is no method to patch.
Patch Class
With manual patching, you can put your patches anywhere you like since you will refer to them yourself. Patching by annotations simplifies patching by assuming that you set up annotated classes and define your patch methods inside them.
Layout The class can be static or not, public or private, it doesn't matter. However, in order to make Harmony find it, it must have at least one [HarmonyPatch] attribute. Inside the class you define patches as static methods that either have special names like Prefix or Transpiler or use attributes to define their type. Usually they also include annotations that define their target (the original method you want to patch). It also common to have fields and other helper methods in the class.
Attribute Inheritance The attributes of the methods in the class inherit the attributes of the class.
Patch methods
Harmony identifies your patch methods and their helper methods by name. If you prefer to name your methods differently, you can use attributes to tell Harmony what your methods are.
[HarmonyPatch(...)]
class Patch
{
static void Prefix()
{
// this method uses the name "Prefix", no annotation necessary
}
[HarmonyPostfix]
static void MyOwnName()
{
// this method is a Postfix as defined by the attribute
}
}
If you prefer manual patching, you can use any method name or class structure you want. You are responsible to retrieve the MethodInfo for the different patch methods and supply them to the Patch() method by wrapping them into HarmonyMethod objects.
note Patch methods must be static but you can define them public or private. They cannot be dynamic methods but you can write static patch factory methods that return dynamic methods.
[HarmonyPatch(...)]
class Patch
{
// the return type of factory methods can be either MethodInfo or DynamicMethod
[HarmonyPrefix]
static MethodInfo PrefixFactory(MethodBase originalMethod)
{
// return an instance of MethodInfo or an instance of DynamicMethod
}
[HarmonyPostfix]
static MethodInfo PostfixFactory(MethodBase originalMethod)
{
// return an instance of MethodInfo or an instance of DynamicMethod
}
}
Method names
Manual patching knows four main patch types: Prefix, Postfix, Transpiler and Finalizer. If you use attributes for patching, you can also use the helper methods: Prepare, TargetMethod, TargetMethods and Cleanup as explained below.
Each of those names has a corresponding attribute starting with [Harmony...]. So instead of calling one of your methods "Prepare", you can call it anything and decorate it with a [HarmonyPrepare] attribute.
Patch method types
Both prefix and postfix have specific semantics that are unique to them. They do however share the ability to use a range of injected values as arguments.
Prefix
A prefix is a method that is executed before the original method. It is commonly used to:
access and edit the arguments of the original method
set the result of the original method
skip the original method
set custom state that can be recalled in the postfix
run a piece of code at the beginning that is guaranteed to be executed
Postfix
A postfix is a method that is executed after the original method. It is commonly used to:
read or change the result of the original method
access the arguments of the original method
read custom state from the prefix
Transpiler
This method defines the transpiler that modifies the code of the original method. Use this in the advanced case where you want to modify the original methods IL codes.
Finalizer
A finalizer is a method that executes after all postfixes. It wraps the original method, all prefixes, and postfixes in try/catch logic and is called either with null (no exception) or with an exception if one occurred. It is commonly used to:
run a piece of code at the end that is guaranteed to be executed
handle exceptions and suppress them
handle exceptions and alter them

View File

@@ -6,9 +6,6 @@
},
{
"path": "../../../../Data"
},
{
"path": "../../../../dll1.6"
}
],
"settings": {}

View File

@@ -0,0 +1,77 @@
using Verse;
using RimWorld;
using System.Collections.Generic;
namespace WulaFallenEmpire
{
public class CompUseEffect_AddDamageShieldCharges : CompUseEffect
{
public CompProperties_AddDamageShieldCharges Props => (CompProperties_AddDamageShieldCharges)props;
public override void DoEffect(Pawn user)
{
base.DoEffect(user);
// 获取或添加 Hediff_DamageShield
Hediff_DamageShield damageShield = user.health.hediffSet.GetFirstHediff<Hediff_DamageShield>();
if (damageShield == null)
{
// 如果没有 Hediff则添加一个
damageShield = (Hediff_DamageShield)HediffMaker.MakeHediff(Props.hediffDef, user);
user.health.AddHediff(damageShield);
damageShield.ShieldCharges = Props.chargesToAdd; // 设置初始层数
}
else
{
// 如果已有 Hediff则增加层数
damageShield.ShieldCharges += Props.chargesToAdd;
}
// 确保层数不超过最大值
if (damageShield.ShieldCharges > (int)damageShield.def.maxSeverity)
{
damageShield.ShieldCharges = (int)damageShield.def.maxSeverity;
}
// 发送消息
Messages.Message("WULA_MessageGainedDamageShieldCharges".Translate(user.LabelShort, Props.chargesToAdd), user, MessageTypeDefOf.PositiveEvent);
}
// 修正 CanBeUsedBy 方法签名
public override AcceptanceReport CanBeUsedBy(Pawn p)
{
// 确保只能对活着的 Pawn 使用
if (p.Dead)
{
return "WULA_CannotUseOnDeadPawn".Translate();
}
// 检查是否已达到最大层数
Hediff_DamageShield damageShield = p.health.hediffSet.GetFirstHediff<Hediff_DamageShield>();
if (damageShield != null && damageShield.ShieldCharges >= (int)damageShield.def.maxSeverity)
{
return "WULA_DamageShieldMaxChargesReached".Translate();
}
return true; // 可以使用
}
// 可以在这里添加 GetDescriptionPart() 来显示描述
public override string GetDescriptionPart()
{
return "WULA_DamageShieldChargesDescription".Translate(Props.chargesToAdd);
}
}
public class CompProperties_AddDamageShieldCharges : CompProperties_UseEffect
{
public HediffDef hediffDef;
public int chargesToAdd;
public CompProperties_AddDamageShieldCharges()
{
compClass = typeof(CompUseEffect_AddDamageShieldCharges);
}
}
}

View File

@@ -0,0 +1,40 @@
using HarmonyLib;
using Verse;
using System.Reflection;
using UnityEngine; // Add UnityEngine for MoteMaker and Color
namespace WulaFallenEmpire.HarmonyPatches
{
[HarmonyPatch(typeof(Pawn_HealthTracker), "PreApplyDamage")]
public static class DamageShieldPatch
{
// 使用 Harmony 的 AccessTools.Field 来获取私有的 pawn 字段
private static readonly FieldInfo PawnField = AccessTools.Field(typeof(Pawn_HealthTracker), "pawn");
public static bool Prefix(Pawn_HealthTracker __instance, ref DamageInfo dinfo, out bool absorbed)
{
// 获取 Pawn 实例
Pawn pawn = (Pawn)PawnField.GetValue(__instance);
// 查找 Pawn 身上是否有 Hediff_DamageShield
Hediff_DamageShield damageShield = pawn.health.hediffSet.GetFirstHediff<Hediff_DamageShield>();
if (damageShield != null && damageShield.ShieldCharges > 0)
{
// 如果有护盾层数,则消耗一层并抵挡伤害
damageShield.ShieldCharges--;
// MoteMaker.ThrowText(pawn.DrawPos, pawn.Map, "伤害被护盾抵挡!", Color.cyan, 1.2f); // 视觉反馈,明确指定 Verse.MoteMaker此行将被删除
// 设置 absorbed 为 true表示伤害被完全吸收
absorbed = true;
// 返回 false阻止原始方法执行即伤害不会被应用
return false;
}
// 如果没有护盾 Hediff 或者层数用尽,则正常处理伤害
absorbed = false;
return true; // 继续执行原始方法
}
}
}

View File

@@ -0,0 +1,73 @@
using Verse;
using System.Text;
using RimWorld;
using UnityEngine;
namespace WulaFallenEmpire
{
public class Hediff_DamageShield : HediffWithComps
{
// 伤害抵挡层数
// 直接将 severityInt 作为 ShieldCharges这样外部对 severity 的修改会直接影响 ShieldCharges
public int ShieldCharges
{
get => (int)severityInt;
set => severityInt = value;
}
public override string LabelInBrackets
{
get
{
if (ShieldCharges > 0)
{
return "层数: " + ShieldCharges;
}
return null;
}
}
public override string TipStringExtra
{
get
{
StringBuilder sb = new StringBuilder();
sb.Append(base.TipStringExtra);
if (ShieldCharges > 0)
{
sb.AppendLine(" - 每层抵挡一次伤害。当前层数: " + ShieldCharges);
}
else
{
sb.AppendLine(" - 没有可用的抵挡层数。");
}
return sb.ToString();
}
}
public override void ExposeData()
{
base.ExposeData();
// severityInt 会自动保存,所以不需要额外处理 ShieldCharges
}
public override void PostAdd(DamageInfo? dinfo)
{
base.PostAdd(dinfo);
// 初始层数由 XML 中的 initialSeverity 控制
// 如果需要一个固定的初始值,可以在这里设置
// 例如:如果 hediffDef.initialSeverity 设为 0这里可以强制给一个默认值
// 如果 initialSeverity 在 XML 中已经设置为 10这里就不需要额外处理
}
public override void Tick()
{
base.Tick();
// 如果层数归零,移除 Hediff
if (ShieldCharges <= 0)
{
pawn.health.RemoveHediff(this);
}
}
}
}

View File

@@ -182,6 +182,9 @@
<Compile Include="Verb\VerbProperties_WeaponStealBeam.cs" />
<Compile Include="Verb\Verb_ShootWeaponStealBeam.cs" />
<Compile Include="Verb\Verb_ShootMeltBeam.cs" />
<Compile Include="Hediff_DamageShield.cs" />
<Compile Include="HarmonyPatches\DamageShieldPatch.cs" />
<Compile Include="CompUseEffect_AddDamageShieldCharges.cs" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />