code:
using System.Text;
using Verse;
using RimWorld;
using Multiplayer.API;
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using HugsLib.Utils;
using System.Linq;
using HugsLib;

namespace rjw
{
	/// <summary>
	/// Comp for rjw hediff parts
	/// </summary>
	public class CompHediffBodyPart : HediffComp
	{
		public string Size => parent.CurStage?.label ?? "";
		public string RaceOwner = "Unknows species";		//base race when part created
		public string PreviousOwner = "Unknows";			//base race when part created
		public float SizeBase;								//base size/severity when part created, someday alter by operation
		public float SizeOwner = 0;							//modifier of 1st owner race body size
		public float EffSize;								//SizeBase x SizeOwner = current size | hediff.severity
		public string FluidType = "";						//cummies/milk - insectjelly/honey etc
		public float FluidAmmount;							//amount of Milk/Ejaculation/Wetness
		public float FluidModifier = 1f;					//
		public string Eggs;                                 //for ovi eggs, maybe
		public bool Transplanted = false;					//transplaned from someone else

		/// <summary>
		/// part size in labels
		/// </summary>

		//public override string CompLabelInBracketsExtra
		//{
		//	get
		//	{
		//		if (Size != "")
		//			return Size;

		//		return null;
		//	}
		//}

		/// <summary>
		/// save data
		/// </summary>
		public override void CompExposeData()
		{
			base.CompExposeData();
			Scribe_Values.Look(ref SizeBase, "SizeBase");
			Scribe_Values.Look(ref SizeOwner, "SizeOwner");
			Scribe_Values.Look(ref RaceOwner, "RaceOwner");
			Scribe_Values.Look(ref PreviousOwner, "PreviousOwner");
			Scribe_Values.Look(ref FluidType, "FluidType");
			Scribe_Values.Look(ref FluidAmmount, "FluidAmmount");
			Scribe_Values.Look(ref FluidModifier, "FluidModifier");
			Scribe_Values.Look(ref Eggs, "Eggs");
			Scribe_Values.Look(ref Transplanted, "Transplanted");
		}

		public override void CompPostPostAdd(DamageInfo? dinfo)
		{
			base.CompPostPostAdd(dinfo);
			try//error at world gen
			{
				Pawn.GetRJWPawnData().genitals = new List<Hediff>();
				Pawn.GetRJWPawnData().breasts = new List<Hediff>();
				Pawn.GetRJWPawnData().udders = new List<Hediff>();
				Pawn.GetRJWPawnData().anus = new List<Hediff>();
			}
			catch
			{
			}
		}
		public override void CompPostPostRemoved()
		{
			base.CompPostPostRemoved();
			try
			{
				Pawn.GetRJWPawnData().genitals = new List<Hediff>();
				Pawn.GetRJWPawnData().breasts = new List<Hediff>();
				Pawn.GetRJWPawnData().udders = new List<Hediff>();
				Pawn.GetRJWPawnData().anus = new List<Hediff>();
			}
			catch
			{
			}
		}

		/// <summary>
		/// show part info in healthab
		/// </summary>
		public override string CompTipStringExtra
		{
			get
			{
				if (SizeOwner == 0)
				{
					ModLog.Warning(" " + xxx.get_pawnname(Pawn) + " part " + parent.def.defName + " is broken, resetting");
					initComp();
					updatesize();
					updatepartposition();
				}
				// In theory the tip should be a condensed form and the longer form should be elsewhere, but where?
				return GetTipString(RJWSettings.ShowRjwParts == RJWSettings.ShowParts.Extended).Join("\n");
			}
		}

		IEnumerable<string> GetTipString(bool extended)
		{
			//ModLog.Message(" CompTipStringExtra " + xxx.get_pawnname(Pawn) + " " + parent.def.defName);
			// TODO: Part type should be a property in the extension.
			//StringBuilder defstringBuilder = new StringBuilder();
			if (parent.Part != null)
				if (parent.def.defName.ToLower().Contains("breasts"))
				{
					return GetBreastTip(extended);
				}
				else if (parent.def.defName.ToLower().Contains("penis"))
				{
					return GetPenisTip(extended);
				}
				else if (parent.def.defName.ToLower().Contains("anus") || parent.def.defName.ToLower().Contains("vagina"))
				{
					return GetOrificeTip(extended);
				}
				else if (parent.def.defName.ToLower().Contains("ovi"))
				{
					return GetEggTip(extended);
				}

			return Enumerable.Empty<string>();
		}

		IEnumerable<string> GetEggTip(bool extended)
		{
			if (Eggs != "")
			{
				yield return "RJW_hediff_eggs".Translate(Eggs);
			}
		}

		IEnumerable<string> GetPenisTip(bool extended)
		{
			if (PartSizeExtension.TryGetLength(parent, out float length))
			{
				yield return "RJW_hediff_length".Translate(length.ToString("F1"));
			}

			if (!extended)
			{
				yield break;
			}

			if (PartSizeExtension.TryGetGirth(parent, out float girth))
			{
				yield return "RJW_hediff_girth".Translate(girth.ToString("F1"));
			}

			if (PartSizeExtension.TryGetPenisWeight(parent, out float weight))
			{
				yield return "RJW_hediff_weight".Translate(weight.ToString("F1"));
			}

			foreach (var line in GetFluidTip())
			{
				yield return line;
			}

			if (PartProps.TryGetProps(parent, out List<string> propslist))
			{
				yield return "Properties: " + propslist.ToCommaList();
			}
		}

		IEnumerable<string> GetOrificeTip(bool extended)
		{
			if (!extended)
			{
				yield break;
			}
				//defstringBuilder.Append(this.Def.description);
				//defstringBuilder.AppendLine("Cum: " + FluidType);
				//defstringBuilder.AppendLine("Ejaculation: " + (FluidAmmount * FluidModifier).ToString("F2") + "ml");

			// TODO: Should be scaled bigger than penis size either in xml or here.
			if (PartSizeExtension.TryGetLength(parent, out float length))
			{
				yield return "RJW_hediff_maxLength".Translate(length.ToString("F1"));
			}

			if (PartSizeExtension.TryGetGirth(parent, out float girth))
			{
				yield return "RJW_hediff_maxGirth".Translate(girth.ToString("F1"));
			}

			foreach (var line in GetFluidTip())
			{
				yield return line;
			}

			if (PartProps.TryGetProps(parent, out List<string> propslist))
			{
				yield return "Properties: " + propslist.ToCommaList();
			}
		}

		IEnumerable<string> GetBreastTip(bool extended)
		{
			if (parent.Part.def == xxx.breastsDef)
			{
				foreach (var line in GetBraCupTip())
				{
					yield return line;
				}

				if (!extended)
				{
					yield break;
				}

				if (PartSizeExtension.TryGetCupSize(parent, out float size))
				{
					var cupSize = (int)size;

					if (cupSize > 0)
					{
						var bandSize = PartSizeExtension.GetBandSize(parent);
						yield return "RJW_hediff_braSize".Translate(
							bandSize,
							cupSize);

						if (PartSizeExtension.TryGetOverbustSize(parent, out float overbust))
						{
							var underbust = PartSizeExtension.GetUnderbustSize(parent);
							yield return "RJW_hediff_underbust".Translate(underbust.ToString("F1"));
							yield return "RJW_hediff_overbust".Translate(overbust.ToString("F1"));
						}

						if (PartSizeExtension.TryGetBreastWeight(parent, out float weight))
						{
							yield return "RJW_hediff_weight".Translate(weight.ToString("F1"));
						}
					}
					else
					{
						yield return "RJW_hediff_braSizeNone".Translate();
					}
				}
			}

			foreach (var line in GetFluidTip())
			{
				yield return line;
			}

			if (PartProps.TryGetProps(parent, out List<string> propslist))
			{
				yield return "Properties: " + propslist.ToCommaList();
			}
		}

		IEnumerable<string> GetBraCupTip()
		{
			if (PartSizeExtension.TryGetCupSize(parent, out float size))
			{
				var cupSize = (int)size;

				if (cupSize > 0)
				{
					yield return "RJW_hediff_braCup".Translate(
						PartStagesDef.GetCupSizeLabel(cupSize));
				}
			}
		}

		IEnumerable<string> GetFluidTip()
		{
			if (FluidAmmount != 0 && FluidType != "")
			{
				yield return "RJW_hediff_fluidTypeFluidAmount".Translate(
					FluidType,
					(FluidAmmount * FluidModifier).ToString("F1"));
			}
		}

		//TODO: someday part(SizeOwner) change operations
		public void updatesize(float value = 0)
		{
			if (value == 0) // refresh size
			{
				//Log.Message("CompHediffBodyPart::updatesize original owner part size ( " + SizeOwner + " )");
				//Log.Message("CompHediffBodyPart::updatesize current owner part size ( " + parent.pawn.BodySize + " )");
				value = (parent.pawn.RaceProps.baseBodySize - SizeOwner) / SizeOwner;
				value = SizeBase / (1 + value);

				if (!Transplanted) // update non transplanted part size (kids growth?)
					value /= parent.pawn.RaceProps.baseBodySize / parent.pawn.BodySize;
				//else
				//	value *= parent.pawn.RaceProps.baseBodySize / parent.pawn.BodySize;

				parent.Severity = value;
			}
			else // change size by %
			{
				if (value > 0)
					incsize(value);
				else
					decsize(value);
			}
		}

		//scale parts to bodysize
		public void incsize(float value = 0)
		{
			if (value < 0)
				return;
			else if(value == 0)
				return;
			else if(value != 0)
			{
				//Log.Message(xxx.get_pawnname(pawn) + " updatesize " + parent.def.defName);
				//Log.Message("CompHediffBodyPart::updatesize - increase");
				//Log.Message("CompHediffBodyPart::updatesize( " + SizeOwner + " )");
				//Log.Message("CompHediffBodyPart::updatesize( " + parent.pawn.BodySize + " )");
				//Log.Message("CompHediffBodyPart::updatesize - value");
				//Log.Message("CompHediffBodyPart::updatesize( " + value + " )");
				value = SizeBase * (1 + value);
			}
			parent.Severity = value;
		}

		public void decsize(float value = 0)
		{
			if (value > 0)
				return;
			else if(value == 0)
				return;
			else if (value != 0)
			{
				//Log.Message(xxx.get_pawnname(pawn) + " updatesize " + parent.def.defName);
				//Log.Message("CompHediffBodyPart::updatesize - decrease");
				//Log.Message("CompHediffBodyPart::updatesize( " + SizeOwner + " )");
				//Log.Message("CompHediffBodyPart::updatesize( " + parent.pawn.BodySize + " )");
				//Log.Message("CompHediffBodyPart::updatesize - value");
				//Log.Message("CompHediffBodyPart::updatesize( " + value + " )");
				value = SizeBase * (1 + value);
			}
			if (value <= 0) // aka dont remove 0 severity hediff
			{
				value = 0.01f;
			}
			parent.Severity = value;
		}

		[SyncMethod]
		public void updatepartposition()
		{
			var partBase = parent.def as HediffDef_PartBase;
			if (partBase != null)
			{
				//Log.Message("0 " + (parent.Part == null));
				//Log.Message("1 " +parent.Part);
				//Log.Message("2 " +parent.Part.def);
				//Log.Message("3 " +parent.Part.def.defName);
				//Log.Message("4 " +partBase);
				//Log.Message("5 " +partBase.DefaultBodyPart);
				//ModLog.Message("pawn " + xxx.get_pawnname(Pawn) + ", part: " + parent.def.defName);
				if (parent.Part == null)
				{
					var bp = parent.pawn.RaceProps.body.AllParts.Find(x => x.def.defName.Contains(partBase.DefaultBodyPart));
					if (bp != null)
					{
						ModLog.Warning(" " + xxx.get_pawnname(Pawn) + " part is null/wholebody? is in wrong BodyPart position, resetting to default: " + partBase.DefaultBodyPart);
						parent.Part = bp;
						Pawn.GetRJWPawnData().genitals = new List<Hediff>();
						Pawn.GetRJWPawnData().breasts = new List<Hediff>();
						Pawn.GetRJWPawnData().udders = new List<Hediff>();
						Pawn.GetRJWPawnData().anus = new List<Hediff>();
					}
					else
					{
						ModLog.Message(" " + xxx.get_pawnname(Pawn) + " default bodypart not found: " + partBase.DefaultBodyPart + " -skip.");
					}
				}
				else if (parent.Part != null && partBase.DefaultBodyPart != "" && parent.Part.def.defName != partBase.DefaultBodyPart)
				{
					//Log.Message("f");
					//Log.Message(partBase.DefaultBodyPartList.ToLineList());
					if (partBase.DefaultBodyPartList.Any() && partBase.DefaultBodyPartList.Contains(parent.Part.def.defName))
					{
						return;
					}
					var bp = parent.pawn.RaceProps.body.AllParts.Find(x => x.def.defName.Contains(partBase.DefaultBodyPart));
					if (bp != null)
					{
						ModLog.Warning(" " + xxx.get_pawnname(Pawn) + " part " + parent.def.defName + " is in wrong BodyPart position, resetting to default: " + partBase.DefaultBodyPart);
						parent.Part = bp;
						Pawn.GetRJWPawnData().genitals = new List<Hediff>();
						Pawn.GetRJWPawnData().breasts = new List<Hediff>();
						Pawn.GetRJWPawnData().udders = new List<Hediff>();
						Pawn.GetRJWPawnData().anus = new List<Hediff>();
					}
					else
					{
						ModLog.Message(" " + xxx.get_pawnname(Pawn) + " default bodypart not found: " + partBase.DefaultBodyPart + " -skip.");
					}
					//if (pawn.IsColonist)
					//{
					//	Log.Message(xxx.get_pawnname(pawn) + " has broken hediffs, removing " + this.ToString());
					//	Log.Message(Part.ToString());
					//	Log.Message(bp.def.defName);
					//	Log.Message(partBase.DefaultBodyPart.ToString());
					//}
				}
			}
		}

		/// <summary>
		/// fill comp data
		/// </summary>
		[SyncMethod]
		public void initComp(Pawn pawn = null, bool reroll = false)
		{
			if (pawn == null)
				pawn = parent.pawn;

			double u1 = 1.0 - Rand.Range(0.01f, 1); //uniform(0.01f, 1] random doubles
			double u2 = 1.0 - Rand.Range(0.01f, 1);
			double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) *
				Math.Sin(2.0 * Math.PI * u2);
			double value =
				(3 /*mostly prevents negatives*/ + .75 /*Normalizing factor*/ * randStdNormal) / 6; /*changes to percent */
			if (value <= 0)
			{
				value = 0.01f;
			}
			else if (value > 1)
			{
				value = 1;
			}
			bool trap = false;
			if (reroll == true)
				value = SizeBase;
			{
				if (parent.def.defName.ToLower().Contains("breast"))
				{
					//FluidType = "Milk";
					FluidAmmount = 0;

					if (pawn != null)
					{
						if (pawn.gender == Gender.Male && RJWSettings.MaleTrap)
							if (pawn.Faction != null && !xxx.is_animal(pawn)) //null faction throws error
							{
								//natives/spacer futa
								float chance = (int)pawn.Faction.def.techLevel < 5 ? RJWSettings.futa_natives_chance : RJWSettings.futa_spacers_chance;
								//nymph futa gender
								chance = xxx.is_nympho(pawn) ? RJWSettings.futa_nymph_chance : chance;

								if (Rand.Chance(chance))
								{
									//make trap
									trap = true;
								}
							}

						if (pawn.gender == Gender.Male && !trap && reroll == false)
							value = 0.01f;

					}
				}
				else if (parent.def.defName.ToLower().Contains("penis") || parent.def.defName.ToLower().Contains("Ovipositorf") || parent.def.defName.ToLower().Contains("Ovipositorm"))
				{
					FluidAmmount = (float)value * pawn.RaceProps.baseBodySize * pawn.RaceProps.baseBodySize * 10 * 2 * Rand.Range(0.75f, 1.25f);
				}
				else if (parent.def.defName.ToLower().Contains("vagina"))
				{
					FluidAmmount = (float)value * pawn.RaceProps.baseBodySize * pawn.RaceProps.baseBodySize * 10 * Rand.Range(0.75f, 1.25f);
				}
				else if (parent.def.defName.ToLower().Contains("anus"))
				{
					FluidAmmount = 0;
				}
				else if (parent.def.defName.ToLower().Contains("tentacle"))
				{
					value *= 2;
					FluidAmmount = (float)value * pawn.RaceProps.baseBodySize * pawn.RaceProps.baseBodySize * 10 * 2 * Rand.Range(0.75f, 1.25f);
				}
				if (parent.def.defName.ToLower().Contains("ovi"))
				{
					Eggs = pawn?.kindDef?.label ?? "";
				}

				FluidType = (parent.def as HediffDef_PartBase).FluidType;
				SizeBase = (float)value;
				SizeOwner = pawn?.RaceProps?.baseBodySize ?? 1.0f;
				RaceOwner = pawn?.kindDef?.race.LabelCap ?? "RJW_hediff_unknownSpecies".Translate();
				PreviousOwner = xxx.get_pawnname(pawn);
				EffSize = SizeOwner*SizeBase;
				FluidModifier = 1f;
			}
		}
	}
}


code:
using RimWorld;

namespace rjw
{
	public class CompRJWProperties_Hatcher : CompProperties_Hatcher
	{
		public CompRJWProperties_Hatcher()
		{
			this.compClass = typeof(CompRJWHatcher);
		}
	}
}

repo_name: ElToro/rjw

license: mit


code:
using System.Text;
using Verse;
using RimWorld;
using Multiplayer.API;
using System.Collections.Generic;

namespace rjw
{
	/// <summary>
	/// Comp for things
	/// </summary>
	public class CompThingBodyPart : ThingComp
	{
		/// <summary>
		/// Comp for rjw Thing parts.
		/// </summary>

		public string Size;										//eventually replace with below, maybe
		public float SizeBase;									//base size when part created, someday alter by operation
		public float SizeOwner = 0;								//modifier of 1st owner race body size
		public string RaceOwner = "Unknows species";			//race of 1st owner race
		public string PreviousOwner = "Unknown";				//erm
		public float EffSize;									//SizeBase x SizeOwner
		public string FluidType;								//cummies/milk - insectjelly/honey etc
		public float FluidAmmount;								//amount of Milk/Ejaculation/Wetness
		public float FluidModifier;								//
		public string Eggs;										//for ovi eggs, maybe

		/// <summary>
		/// Thing/part size in labels, init comp on select
		/// </summary>

		//public override string CompInspectStringExtra()
		//{
		//	if (Size != "")
		//		return Translator.Translate("Size") + ": " + Size;
		//	else
		//		return null;

		//	return base.CompInspectStringExtra();
		//}

		/// <summary>
		/// Thing/part size in label
		/// </summary>
		public override string TransformLabel(string label)
		{
			if (SizeOwner == 0)
				InitComp();

			if (Size != "")
				return label + " (" + Size + ")" + " (" + SizeOwner + ")";
			//this.parent.GetStatValue(StatDefOf.Nutrition);

			return label;
		}

		/// <summary>
		/// Thing/part description + comp description
		/// </summary>
		public override string GetDescriptionPart()
		{
			//ModLog.Message(" CompTipStringExtra " + xxx.get_pawnname(Pawn) + " " + parent.def.defName);
			StringBuilder stringBuilder = new StringBuilder();
			if (SizeOwner == 0)
				InitComp();
			stringBuilder.AppendLine("Previous owner: " + PreviousOwner);
			stringBuilder.AppendLine("Original owner race: " + RaceOwner);
			stringBuilder.AppendLine("Original owner race size: " + SizeOwner);
			if (parent.def.defName.ToLower().Contains("breasts"))
			{
				if (FluidType != "")
					stringBuilder.AppendLine("Producing: " + FluidType);
				if (FluidAmmount != 0)
				{
					stringBuilder.AppendLine("Amount: " + FluidAmmount.ToString("F2"));
				}
				if (Size != "")
					stringBuilder.AppendLine("Size: " + Size);
			}
			else if (parent.def.defName.ToLower().Contains("penis") || parent.def.defName.ToLower().Contains("vagina"))
			{
				if (FluidAmmount != 0)
				{
					if (FluidType != "")
						stringBuilder.AppendLine("Cum: " + FluidType);
					if (parent.def.defName.ToLower().Contains("penis"))
						stringBuilder.AppendLine("Ejaculation: " + FluidAmmount.ToString("F2") + "ml");
					if (parent.def.defName.ToLower().Contains("vagina"))
						stringBuilder.AppendLine("Wetness: " + FluidAmmount.ToString("F2"));
				}
				if (Size != "")
					stringBuilder.AppendLine("Size: " + Size);
			}
			else if (parent.def.defName.ToLower().Contains("anus"))
			{
				if (FluidType != "" && FluidAmmount != 0)
				{
					stringBuilder.AppendLine("Lube: " + FluidType);
					if (parent.def.defName.ToLower().Contains("anus"))
						stringBuilder.AppendLine("Wetness: " + FluidAmmount.ToString("F2"));
				}
				if (Size != "")
					stringBuilder.AppendLine("Size: " + Size);
			}
			else if (parent.def.defName.ToLower().Contains("ovi"))
			{
				if (Eggs != "")
					stringBuilder.AppendLine("Eggs: " + Eggs);
			}
			//TODO: someday add properties
			//if (PartProps.TryGetProps(parent, out List<string> propslist))
			//{
			//	yield return "Properties: " + propslist.ToCommaList();
			//	if (Eggs != "")
			//		stringBuilder.AppendLine("Properties: " + propslist.ToCommaList());
			//}

			return stringBuilder.ToString();
		}

		public override void PostExposeData()
		{
			base.PostExposeData();
			Scribe_Values.Look(ref Size, "Size");
			Scribe_Values.Look(ref SizeBase, "SizeBase");
			Scribe_Values.Look(ref SizeOwner, "SizeOwner");
			Scribe_Values.Look(ref RaceOwner, "RaceOwner");
			Scribe_Values.Look(ref PreviousOwner, "PreviousOwner");
			Scribe_Values.Look(ref FluidType, "FluidType");
			Scribe_Values.Look(ref FluidAmmount, "FluidAmmount");
			Scribe_Values.Look(ref FluidModifier, "FluidModifier");
			Scribe_Values.Look(ref Eggs, "Eggs");
		}

		/// <summary>
		/// fill comp data
		/// </summary>
		[SyncMethod]
		public void InitComp(Pawn pawn = null)
		{
			var def = DefDatabase<HediffDef>.GetNamed(parent.def.defName);
			//pick random pawn to create temp hediff
			pawn = PawnsFinder.AllMaps_FreeColonistsAndPrisonersSpawned?.RandomElement();
			if (pawn == null)// SOS2 or other start with no colonists
				pawn = PawnsFinder.All_AliveOrDead?.RandomElement();

			Hediff hd = HediffMaker.MakeHediff(def, pawn);

			CompHediffBodyPart CompHediff = hd.TryGetComp<CompHediffBodyPart>();
			if (CompHediff != null)
			{
				CompHediff.initComp(pawn);
				CompHediff.updatesize();

				FluidType = CompHediff.FluidType;
				FluidAmmount = CompHediff.FluidAmmount;
				FluidModifier = CompHediff.FluidModifier;
				Size = CompHediff.Size;
				SizeBase = CompHediff.SizeBase;
				SizeOwner = CompHediff.SizeOwner;
				RaceOwner = "Unknown";
				PreviousOwner = "Unknown";
				Eggs = CompHediff.Eggs;
			}
		}
	}
}


code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace rjw
{
	public enum Orientation
	{
		None,
		Asexual,
		Pansexual,
		Heterosexual,
		MostlyHeterosexual,
		LeaningHeterosexual,
		Bisexual,
		LeaningHomosexual,
		MostlyHomosexual,
		Homosexual
	}
}


code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
using Verse.AI;
using RimWorld;

namespace rjw
{
	public class Quirk
	{
		public static List<Quirk> All = new List<Quirk>();

		public static readonly Quirk Breeder = new Quirk(
			"Breeder",
			"BreederQuirk");
		public static readonly Quirk Endytophile = new Quirk(
			"Endytophile",
			"EndytophileQuirk",
			(pawn, partner) => !partner.apparel.PsychologicallyNude,
			sexProps => !sexProps.pawn.apparel.PsychologicallyNude
			);
		public static readonly Quirk Exhibitionist = new Quirk(
			"Exhibitionist",
			"ExhibitionistQuirk",
			null,
			SatisfiesExhibitionist
			);
		public static readonly Quirk Fertile = new Quirk(
			"Fertile",
			"FertileQuirk");
		public static readonly Quirk Gerontophile = new Quirk(
			"Gerontophile",
			"GerontophileQuirk",
			(pawn, partner) => SexUtility.ScaleToHumanAge(partner) > 55,
			sexProps => sexProps.hasPartner() && SexUtility.ScaleToHumanAge(sexProps.partner) > 55
			);
		public static readonly Quirk ImpregnationFetish = new Quirk(
			"Impregnation fetish",
			"ImpregnationFetishQuirk",
			(pawn, partner) =>
				PregnancyHelper.CanImpregnate(pawn, partner)
				|| PregnancyHelper.CanImpregnate(partner, pawn),
			sexProps =>
				sexProps.hasPartner()
				&& (PregnancyHelper.CanImpregnate(sexProps.pawn, sexProps.partner, sexProps.sexType)
					|| PregnancyHelper.CanImpregnate(sexProps.partner, sexProps.pawn, sexProps.sexType))
			);
		public static readonly Quirk Incubator = new Quirk(
			"Incubator",
			"IncubatorQuirk");
		public static readonly Quirk Infertile = new Quirk(
			"Infertile",
			"InfertileQuirk");
		public static readonly Quirk Messy = new Quirk(
			"Messy",
			"MessyQuirk");
		public static readonly Quirk Podophile = new Quirk(
			"Podophile",
			"PodophileQuirk",
			null,
			sexProps => sexProps.hasPartner() && sexProps.sexType == xxx.rjwSextype.Footjob && sexProps.IsSubmissive()
			);
		public static readonly Quirk Cumslut = new Quirk(
			"Cumslut",
			"CumslutQuirk",
			null,
			sexProps => sexProps.hasPartner() && sexProps.sexType == xxx.rjwSextype.Fellatio && sexProps.IsSubmissive()
			);
		public static readonly Quirk Buttslut = new Quirk(
			"Buttslut",
			"ButtslutQuirk",
			null,
			sexProps => sexProps.hasPartner() && sexProps.sexType == xxx.rjwSextype.Anal && sexProps.IsSubmissive()
			);
		public static readonly Quirk PregnancyFetish = new Quirk(
			"Pregnancy fetish",
			"PregnancyFetishQuirk",
			(pawn, partner) => partner.IsVisiblyPregnant(),
			sexProps => sexProps.hasPartner() && sexProps.partner.IsVisiblyPregnant()
			);
		public static readonly Quirk Sapiosexual = new Quirk(
			"Sapiosexual",
			"SapiosexualQuirk",
			(pawn, partner) => SatisfiesSapiosexual(partner),
			null
			);
		public static readonly Quirk Somnophile = new Quirk(
			"Somnophile",
			"SomnophileQuirk",
			(pawn, partner) => !partner.Awake(),
			sexProps => sexProps.hasPartner() && !sexProps.partner.Awake()
			);
		public static readonly Quirk Teratophile = new Quirk(
			"Teratophile",
			"TeratophileQuirk",
			(pawn, partner) => SatisfiesTeratophile(partner),
			null
			);
		public static readonly Quirk Vigorous = new Quirk(
			"Vigorous",
			"VigorousQuirk");

		// There might be too many of these I dunno.
		// People have expressed "special interest" in some of them so I thought
		// it would be cool to have them in the game but since people are weird you end up with a lot of fetishes.
		public static readonly Quirk ChitinLover = MakeTagBasedQuirk("Chitin lover", "ChitinLoverQuirk", RaceTag.Chitin);
		public static readonly Quirk DemonLover = MakeTagBasedQuirk("Demon lover", "DemonLoverQuirk", RaceTag.Demon);
		public static readonly Quirk FeatherLover = MakeTagBasedQuirk("Feather lover", "FeatherLoverQuirk", RaceTag.Feathers);
		public static readonly Quirk FurLover = MakeTagBasedQuirk("Fur lover", "FurLoverQuirk", RaceTag.Fur);
		public static readonly Quirk PlantLover = MakeTagBasedQuirk("Plant lover", "PlantLoverQuirk", RaceTag.Plant);
		public static readonly Quirk RobotLover = MakeTagBasedQuirk("Robot lover", "RobotLoverQuirk", RaceTag.Robot);
		public static readonly Quirk ScaleLover = MakeTagBasedQuirk("Scale lover", "ScaleLoverQuirk", RaceTag.Scales);
		public static readonly Quirk SkinLover = MakeTagBasedQuirk("Skin lover", "SkinLoverQuirk", RaceTag.Skin);
		public static readonly Quirk SlimeLover = MakeTagBasedQuirk("Slime lover", "SlimeLoverQuirk", RaceTag.Slime);

		public string Key { get; }
		public string LocaliztionKey { get; }
		// Hack, quirk generation logic should be in the quirk not based on flags on the quirk.
		public RaceTag RaceTag { get; }
		readonly Func<Pawn, Pawn, bool> PawnSatisfiesFunc;
		readonly Func<SexProps, bool> SexSatisfiesFunc;
		readonly Action<Pawn> AfterAddFunc;

		public static Quirk MakeTagBasedQuirk(string key, string localizationKey, RaceTag tag)
		{
			return new Quirk(
				key,
				localizationKey,
				(pawn, partner) => partner.Has(tag),
				sexProps => sexProps.hasPartner() && sexProps.partner.Has(tag),
				null,
				tag);
		}

		public Quirk(
			string key,
			string localizationKey,
			Func<Pawn, Pawn, bool> pawnSatisfies = null,
			Func<SexProps, bool> sexSatisfies = null,
			Action<Pawn> afterAdd = null,
			RaceTag raceTag = null)
		{
			Key = key;
			LocaliztionKey = localizationKey;
			PawnSatisfiesFunc = pawnSatisfies;
			SexSatisfiesFunc = sexSatisfies;
			AfterAddFunc = afterAdd;
			RaceTag = raceTag;
			All.Add(this);
		}

		public bool IsSatisfiedBy(Pawn pawn, Pawn partner)
		{
			return pawn != null
				&& partner != null
				&& pawn.Has(this)
				&& PawnSatisfiesFunc != null
				&& PawnSatisfiesFunc(pawn, partner);
		}

		public static int CountSatisfiedQuirks(SexProps props)
		{
			Pawn pawn = props.pawn;
			Pawn partner = props.partner;
			var satisfies = All.Where(quirk =>
				quirk.SexSatisfiesFunc != null
				&& pawn.Has(quirk)
				&& quirk.SexSatisfiesFunc(props));
			return satisfies.Count();
		}

		public void DoAfterAdd(Pawn pawn)
		{
			AfterAddFunc?.Invoke(pawn);
		}

		public static bool SatisfiesExhibitionist(SexProps sexProps)
		{
			var zoo = xxx.is_zoophile(sexProps.pawn);
			return sexProps.pawn.Map.mapPawns.AllPawnsSpawned.Any(x =>
				x != sexProps.pawn
				&& x != sexProps.partner
				&& !x.Dead
				&& (zoo || !xxx.is_animal(x))
				&& x.CanSee(sexProps.pawn));
		}

		public static bool SatisfiesSapiosexual(Pawn partner)
		{
			if (!xxx.has_traits(partner)) return false;
			return partner.story.traits.HasTrait(TraitDefOf.TooSmart)
				|| (xxx.CTIsActive && partner.story.traits.HasTrait(xxx.RCT_Savant))
				|| (xxx.IndividualityIsActive && partner.story.traits.HasTrait(xxx.SYR_CreativeThinker))
				|| (xxx.CTIsActive && partner.story.traits.HasTrait(xxx.RCT_Inventor))
				|| partner.story.traits.HasTrait(TraitDefOf.GreatMemory)
				|| partner.story.traits.HasTrait(TraitDefOf.Transhumanist)
				|| partner.skills.GetSkill(SkillDefOf.Intellectual).levelInt >= 15;
		}

		public static bool SatisfiesTeratophile(Pawn partner)
		{
			if (partner.story == null) return false;
			var story = partner.story;
			return RelationsUtility.IsDisfigured(partner)
				|| story.bodyType == BodyTypeDefOf.Fat
				|| story.traits.HasTrait(TraitDefOf.CreepyBreathing)
				|| (story.traits.HasTrait(TraitDefOf.Beauty) && story.traits.DegreeOfTrait(TraitDefOf.Beauty) < 0)
				|| partner.GetStatValue(StatDefOf.PawnBeauty) < 0;
		}

		public static void AddThought(Pawn pawn)
		{
			var thoughtDef = DefDatabase<ThoughtDef>.GetNamed("ThatsMyFetish");
			pawn.needs.mood.thoughts.memories.TryGainMemory(thoughtDef);
		}
	}
}


code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
using Verse.AI;
using RimWorld;
using Multiplayer.API;

namespace rjw
{
	public static class QuirkAdder
	{
		public static void Add(Pawn pawn, Quirk quirk, bool warnOnFail = false)
		{
			if (!pawn.Has(quirk))
			{
				var hasFertility = pawn.RaceHasFertility();
				if (quirk == Quirk.Fertile && (!hasFertility || CompRJW.Comp(pawn).quirks.ToString().Contains(Quirk.Infertile.Key)))
				{
					if (warnOnFail)
					{
						ModLog.Warning($"Tried to add quirk {quirk} to {pawn.Name}, but either {pawn.def} does not have fertility or {pawn.Name} has a conflicting quirk");
					}
					return;
				}
				if (quirk == Quirk.Infertile && (!hasFertility || CompRJW.Comp(pawn).quirks.ToString().Contains(Quirk.Fertile.Key)))
				{
					if (warnOnFail)
					{
						ModLog.Warning($"Tried to add quirk {quirk} to {pawn.Name}, but either {pawn.def} does not have fertility or {pawn.Name} has a conflicting quirk");
					}
					return;
				}
				// No fair having a fetish for your own race.
				// But tags don't conflict so having a fetish for robot plant dragons is fine.
				if (quirk.RaceTag != null && pawn.Has(quirk.RaceTag))
				{
					if (warnOnFail)
					{
						ModLog.Warning($"Tried to add quirk {quirk} to {pawn.Name}, but {pawn} already has the associated race tag {quirk.RaceTag}");
					}
					return;
				}
				if (quirk == Quirk.Fertile)
				{
					var fertility = HediffDef.Named("IncreasedFertility");
					if (fertility != null)
						pawn.health.AddHediff(fertility);
				}
				if (quirk == Quirk.Infertile)
				{
					var infertility = HediffDef.Named("DecreasedFertility");
					if (infertility != null)
						pawn.health.AddHediff(infertility);
				}
				if ((quirk == Quirk.Buttslut && !RJWPreferenceSettings.PlayerIsButtSlut)
					|| (quirk == Quirk.Podophile && !RJWPreferenceSettings.PlayerIsFootSlut)
					|| (quirk == Quirk.Cumslut && !RJWPreferenceSettings.PlayerIsCumSlut))
				{
					if (warnOnFail)
					{
						ModLog.Warning($"Tried to add quirk {quirk} to {pawn.Name}, but all relevant sex types are pseudo-disabled (i.e. given minimum weight in settings)");
					}
					return;
				}

				CompRJW.Comp(pawn).quirks.AppendWithComma(quirk.Key);
				CompRJW.Comp(pawn).quirksave = CompRJW.Comp(pawn).quirks.ToString();
				quirk.DoAfterAdd(pawn);
			}
		}
		public static void Remove(Pawn pawn, Quirk quirk)
		{
			if (pawn.Has(quirk))
			{
				if (quirk == Quirk.Fertile)
				{
					var fertility = HediffDef.Named("IncreasedFertility");
					if (fertility != null)
						pawn.health.RemoveHediff(pawn.health.hediffSet.GetFirstHediffOfDef(fertility));
				}
				if (quirk == Quirk.Infertile)
				{
					var infertility = HediffDef.Named("DecreasedFertility");
					if (infertility != null)
						pawn.health.RemoveHediff(pawn.health.hediffSet.GetFirstHediffOfDef(infertility));
				}

				//CompRJW.Comp(pawn).quirks.AppendWithComma(quirk.Key);
				CompRJW.Comp(pawn).quirks.Replace(quirk.Key, null);

				if (CompRJW.Comp(pawn).quirks.Length == 0)
					CompRJW.Comp(pawn).quirks.Append("None");

				CompRJW.Comp(pawn).quirksave = CompRJW.Comp(pawn).quirks.ToString();
			}
		}

		public static void Clear(Pawn pawn)
		{
			Hediff fertility = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("IncreasedFertility"));
			if (fertility != null)
				pawn.health.RemoveHediff(fertility);
			Hediff infertility = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("DecreasedFertility"));
			if (infertility != null)
				pawn.health.RemoveHediff(infertility);

			CompRJW.Comp(pawn).quirks = new StringBuilder();

			if (CompRJW.Comp(pawn).quirks.Length == 0)
				CompRJW.Comp(pawn).quirks.Append("None");

			CompRJW.Comp(pawn).quirksave = CompRJW.Comp(pawn).quirks.ToString();
		}

		public static void Generate(Pawn pawn)
		{
			if (!pawn.RaceHasSexNeed() || (pawn.kindDef.race.defName.ToLower().Contains("droid") && !AndroidsCompatibility.IsAndroid(pawn)))
			{
				return;
			}
			else if (pawn.IsAnimal())
			{
				GenerateForAnimal(pawn);
			}
			else
			{
				GenerateForHumanlike(pawn);
			}
		}

		[SyncMethod]
		static void GenerateForHumanlike(Pawn pawn)
		{
			var count = Rand.RangeInclusive(0, RJWPreferenceSettings.MaxQuirks);
			var list = Quirk.All.ToList();
			list.Shuffle();

			// Some quirks may be hard for a given pawn to indulge in.
			// For example a female homosexual will have a hard time satisfying an impregnation fetish.
			// But rimworld is a weird place and you never know what the pawn will be capable of in the future.
			// We still don't want straight up contradictory results like fertile + infertile.
			var hasFertility = pawn.RaceHasFertility();
			var actual = new List<Quirk>();
			foreach (var quirk in list)
			{
				if (count == 0)
				{
					break;
				}

				// These special cases are sort of hacked in.
				// In theory there should be a general way for the quirk itself to decide when it applies.
				if (quirk == Quirk.Fertile && (!hasFertility || actual.Contains(Quirk.Infertile)))
				{
					continue;
				}
				if (quirk == Quirk.Infertile && (!hasFertility || actual.Contains(Quirk.Fertile)))
				{
					continue;
				}
				// Have to earn these.
				if (quirk == Quirk.Breeder || quirk == Quirk.Incubator)
				{
					continue;
				}
				// No fair having a fetish for your own race.
				// But tags don't conflict so having a fetish for robot plant dragons is fine.
				if (quirk.RaceTag != null && pawn.Has(quirk.RaceTag))
				{
					continue;
				}

				count--;
				actual.Add(quirk);
			}

			foreach (var quirk in actual)
			{
				pawn.Add(quirk);
			}
		}

		[SyncMethod]
		static void GenerateForAnimal(Pawn pawn)
		{
			if (Rand.Chance(0.1f))
			{
				pawn.Add(Quirk.Messy);
			}

			if (!pawn.RaceHasFertility())
			{
				return;
			}

			if (Rand.Chance(0.1f))
			{
				pawn.Add(Quirk.Fertile);
			}
			else if (Rand.Chance(0.1f))
			{
				pawn.Add(Quirk.Infertile);
			}
		}
	}
}


code:
using Verse;
using RimWorld;
using Verse.AI;

namespace rjw
{
	/// <summary>
	/// data for sex related stuff/outcome
	/// </summary>
	public class SexProps : IExposable
	{
		public Pawn pawn;
		public Pawn partner;
		public bool hasPartner() => partner != null && partner != pawn;

		public xxx.rjwSextype sexType = xxx.rjwSextype.None;
		public InteractionDef dictionaryKey = null;
		public string rulePack = null;

		public bool usedCondom = false;
		public bool isRape = false;
		public bool isReceiver = false;// as JobDriver_SexBaseReciever
		public bool isRevese = false;// interaction.HasInteractionTag(InteractionTag.Reverse)
		public bool isRapist = false;
		public bool isCoreLovin = false;//should really clean this up someday
		public bool isWhoring = false;
		public bool canBeGuilty = true;// can initiator pawn be counted guilty for percepts, player initiated/rmb actrions = false

		public int orgasms = 0; // The orgasms had by the paw
		public SexProps()
		{
		}

		public bool IsInitiator() => !isReceiver;

		public bool IsSubmissive() => (isReceiver && !isRevese) || (!isReceiver && isRevese);

		public SexProps GetForPartner()
		{
			return new SexProps
			{
				pawn = partner,
				partner = pawn,
				sexType = sexType,
				dictionaryKey = dictionaryKey,
				rulePack = rulePack,
				usedCondom = usedCondom,
				isRape = isRape,
				isReceiver = !isReceiver,
				isRevese = isRevese,
				isRapist = isRapist,
				isCoreLovin = isCoreLovin,
				isWhoring = isWhoring,
				canBeGuilty = canBeGuilty,
				orgasms = orgasms
			};
		}

		public void ExposeData()
		{
			Scribe_References.Look(ref pawn, "pawn");
			Scribe_References.Look(ref partner, "partner");

			Scribe_Values.Look(ref sexType, "sexType");
			Scribe_Defs.Look(ref dictionaryKey, "dictionaryKey");
			Scribe_Values.Look(ref rulePack, "rulePack");

			Scribe_Values.Look(ref usedCondom, "usedCondom");
			Scribe_Values.Look(ref isRape, "isRape");
			Scribe_Values.Look(ref isReceiver, "isReceiver");
			Scribe_Values.Look(ref isRapist, "isRapist");
			Scribe_Values.Look(ref isCoreLovin, "isCoreLovin");
			Scribe_Values.Look(ref isWhoring, "isWhoring");
			Scribe_Values.Look(ref canBeGuilty, "canBeGuilty");
			Scribe_Values.Look(ref orgasms, "orgasms");
		}
	}
}


code:
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;

namespace rjw
{
    [DefOf]
    public static class JobDefOf
    {
        static JobDefOf()
        {
            DefOfHelper.EnsureInitializedInCtor(typeof(JobDefOf));
        }

        public static JobDef RJW_AdjustParts;
    }
}


code:
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
using Verse.AI;

namespace Rimlaser
{
    public class JobDriver_AdjustParts : JobDriver
    {
        private Thing Gun => job.GetTarget(TargetIndex.A).Thing;

        private IBeamColorThing BeamColorThing => job.GetTarget(TargetIndex.A).Thing as IBeamColorThing;

        private Thing Prism => job.GetTarget(TargetIndex.B).Thing;

        public override bool TryMakePreToilReservations(bool errorOnFailed)
        {
            if (BeamColorThing == null) return false;

            return pawn.Reserve(Gun, job, 1, -1, null, errorOnFailed) && pawn.Reserve(Prism, job, 1, -1, null, errorOnFailed);
        }

        protected override IEnumerable<Toil> MakeNewToils()
        {
            this.FailOnDespawnedNullOrForbidden(TargetIndex.A);
            yield return Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.Touch).FailOnDespawnedNullOrForbidden(TargetIndex.B).FailOnSomeonePhysicallyInteracting(TargetIndex.B);
            yield return Toils_Haul.StartCarryThing(TargetIndex.B, false, false, false);
            yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch).FailOnDespawnedOrNull(TargetIndex.A);
            Toil repair = Toils_General.Wait(75, TargetIndex.None);
            repair.FailOnDespawnedOrNull(TargetIndex.A);
            repair.FailOnCannotTouch(TargetIndex.A, PathEndMode.Touch);
            repair.WithEffect(Gun.def.repairEffect, TargetIndex.A);
            repair.WithProgressBarToilDelay(TargetIndex.A, false, -0.5f);
            yield return repair;
            yield return new Toil
            {
                initAction = delegate ()
                {

                    BeamColorThing.BeamColor = pawn.CurJob.maxNumMeleeAttacks;

                    var targetInfo = new TargetInfo(Gun.Position, Map, false);
                    Effecter effecter = EffecterDefOf.Deflect_Metal.Spawn();
                    effecter.Trigger(targetInfo, targetInfo);
                    effecter.Cleanup();
                    this.Prism.Destroy(DestroyMode.Vanish);
                }
            };
            yield break;
        }
    }
}


code:
using Verse;
using RimWorld;

namespace rjw
{
    [DefOf]
    public static class RJWHediffDefOf
    {
        public static HediffDef HumpShroomAddiction;

        public static HediffDef HumpShroomEffect;
    }
}


code:
using RimWorld;
using Verse;

namespace rjw
{
	[DefOf]
	public static class RJW_RecipeDefOf
	{
		public static RecipeDef AttachPenis;
		public static RecipeDef InstallPenis;
		public static RecipeDef RemovePenis;
	}
}


code:
using Verse;
using RimWorld;
using Multiplayer.API;

namespace rjw
{
	public static class PawnDesignations_Breedee
	{
		public static bool UpdateCanDesignateBreeding(this Pawn pawn)
		{
			//no permission to change designation for NON prisoner hero/ other player
			if (!pawn.CanChangeDesignationPrisoner() && !pawn.CanChangeDesignationColonist())
				return pawn.GetRJWPawnData().CanDesignateBreeding = false;

			//no permission to change designation for prisoner hero/ self
			if (!pawn.CanChangeDesignationPrisoner())
				return pawn.GetRJWPawnData().CanDesignateBreeding = false;

			//cant have penetrative sex
			if (!xxx.can_be_fucked(pawn))
				return pawn.GetRJWPawnData().CanDesignateBreeding = false;

			if (RJWSettings.bestiality_enabled && xxx.is_human(pawn))
			{
				if (!pawn.IsDesignatedHero())
				{
					if ((xxx.is_zoophile(pawn) || (RJWSettings.override_RJW_designation_checks && !MP.IsInMultiplayer)) && pawn.IsColonist)
						return pawn.GetRJWPawnData().CanDesignateBreeding = true;
				}
				else if (pawn.IsHeroOwner())
					return pawn.GetRJWPawnData().CanDesignateBreeding = true;

				if (pawn.IsPrisonerOfColony || xxx.is_slave(pawn))
					return pawn.GetRJWPawnData().CanDesignateBreeding = true;
			}

			if (RJWSettings.animal_on_animal_enabled && xxx.is_animal(pawn)
				&& pawn.Faction == Faction.OfPlayer)
				return pawn.GetRJWPawnData().CanDesignateBreeding = true;

			return pawn.GetRJWPawnData().CanDesignateBreeding = false;
		}
		public static bool CanDesignateBreeding(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().CanDesignateBreeding;
		}
		public static void ToggleBreeding(this Pawn pawn)
		{
			pawn.UpdateCanDesignateBreeding();
			if (pawn.CanDesignateBreeding())
			{
				if (!pawn.IsDesignatedBreeding())
					DesignateBreeding(pawn);
				else
					UnDesignateBreeding(pawn);
			}
		}
		public static bool IsDesignatedBreeding(this Pawn pawn)
		{
			if (pawn.GetRJWPawnData().Breeding)
			{
				if (!xxx.is_animal(pawn))
				{
					if (!RJWSettings.bestiality_enabled)
						UnDesignateBreeding(pawn);

					else if (!pawn.IsDesignatedHero())
						if (!(xxx.is_zoophile(pawn) || pawn.IsPrisonerOfColony || xxx.is_slave(pawn)))
							if (!(RJWSettings.WildMode || (RJWSettings.override_RJW_designation_checks && !MP.IsInMultiplayer)))
								UnDesignateBreeding(pawn);
				}
				else
				{
					if (!RJWSettings.animal_on_animal_enabled)
						UnDesignateBreeding(pawn);

					else if (!pawn.Faction?.IsPlayer ?? false)
						UnDesignateBreeding(pawn);
				}
				if (pawn.Dead)
					pawn.UnDesignateBreeding();
			}

			return pawn.GetRJWPawnData().Breeding;
		}
		[SyncMethod]
		public static void DesignateBreeding(this Pawn pawn)
		{
			DesignatorsData.rjwBreeding.AddDistinct(pawn);
			pawn.GetRJWPawnData().Breeding = true;
		}
		[SyncMethod]
		public static void UnDesignateBreeding(this Pawn pawn)
		{
			DesignatorsData.rjwBreeding.Remove(pawn);
			pawn.GetRJWPawnData().Breeding = false;
		}
	}
}


code:
using Verse;
using RimWorld;
using Multiplayer.API;

namespace rjw
{
	public static class PawnDesignations_Breeder
	{
		public static bool UpdateCanDesignateBreedingAnimal(this Pawn pawn)
		{
			//no permission to change designation for NON prisoner hero/ other player
			if (!pawn.CanChangeDesignationPrisoner() && !pawn.CanChangeDesignationColonist())
				return pawn.GetRJWPawnData().CanDesignateBreedingAnimal = false;

			//no permission to change designation for prisoner hero/ self
			if (!pawn.CanChangeDesignationPrisoner())
				return pawn.GetRJWPawnData().CanDesignateBreedingAnimal = false;

			//Log.Message("CanDesignateAnimal for " + xxx.get_pawnname(pawn) + " " + SaveStorage.bestiality_enabled);
			//Log.Message("checking animal props " + (pawn.Faction?.IsPlayer.ToString()?? "tynanfag") + xxx.is_animal(pawn) + xxx.can_rape(pawn));
			if ((RJWSettings.bestiality_enabled || RJWSettings.animal_on_animal_enabled)
				&& xxx.is_animal(pawn)
				&& xxx.can_fuck(pawn)
				&& pawn.Faction == Faction.OfPlayer)
				return pawn.GetRJWPawnData().CanDesignateBreedingAnimal = true;

			return pawn.GetRJWPawnData().CanDesignateBreedingAnimal = false;
		}
		public static bool CanDesignateBreedingAnimal(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().CanDesignateBreedingAnimal;
		}
		public static void ToggleBreedingAnimal(this Pawn pawn)
		{
			pawn.UpdateCanDesignateBreedingAnimal();
			if (pawn.CanDesignateBreedingAnimal())
			{
				if (!pawn.IsDesignatedBreedingAnimal())
					DesignateBreedingAnimal(pawn);
				else
					UnDesignateBreedingAnimal(pawn);
			}
		}
		public static bool IsDesignatedBreedingAnimal(this Pawn pawn)
		{
			if (pawn.GetRJWPawnData().BreedingAnimal)
			{
				if (!pawn.Faction?.IsPlayer ?? false)
					UnDesignateBreedingAnimal(pawn);

				if (pawn.Dead)
					pawn.UnDesignateBreedingAnimal();
			}

			return pawn.GetRJWPawnData().BreedingAnimal;
		}
		[SyncMethod]
		public static void DesignateBreedingAnimal(this Pawn pawn)
		{
			DesignatorsData.rjwBreedingAnimal.AddDistinct(pawn);
			pawn.GetRJWPawnData().BreedingAnimal = true;
		}
		[SyncMethod]
		public static void UnDesignateBreedingAnimal(this Pawn pawn)
		{
			DesignatorsData.rjwBreedingAnimal.Remove(pawn);
			pawn.GetRJWPawnData().BreedingAnimal = false;
		}
	}
}


code:
using Verse;
using Multiplayer.API;

namespace rjw
{
	public static class PawnDesignations_Comfort
	{
		public static bool UpdateCanDesignateComfort(this Pawn pawn)
		{
			//rape disabled
			if (!RJWSettings.rape_enabled)
				return pawn.GetRJWPawnData().CanDesignateComfort = false;

			//no permission to change designation for NON prisoner hero/ other player
			if (!pawn.CanChangeDesignationPrisoner() && !pawn.CanChangeDesignationColonist())
				return pawn.GetRJWPawnData().CanDesignateComfort = false;

			//no permission to change designation for prisoner hero/ self
			if (!pawn.CanChangeDesignationPrisoner())
				return pawn.GetRJWPawnData().CanDesignateComfort = false;

			//cant sex
			if (!(xxx.can_fuck(pawn) || xxx.can_be_fucked(pawn)))
				return pawn.GetRJWPawnData().CanDesignateComfort = false;

			if (!pawn.IsDesignatedHero())
			{
				if ((xxx.is_masochist(pawn) || (RJWSettings.override_RJW_designation_checks && !MP.IsInMultiplayer)) && pawn.IsColonist)
					return pawn.GetRJWPawnData().CanDesignateComfort = true;
			}
			else if (pawn.IsHeroOwner())
				return pawn.GetRJWPawnData().CanDesignateComfort = true;

			if (pawn.IsPrisonerOfColony || xxx.is_slave(pawn))
				return pawn.GetRJWPawnData().CanDesignateComfort = true;

			return pawn.GetRJWPawnData().CanDesignateComfort = false;
		}
		public static bool CanDesignateComfort(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().CanDesignateComfort;
		}
		public static void ToggleComfort(this Pawn pawn)
		{
			pawn.UpdateCanDesignateComfort();
			if (pawn.CanDesignateComfort())
			{
				if (!pawn.IsDesignatedComfort())
					DesignateComfort(pawn);
				else
					UnDesignateComfort(pawn);
			}
		}
		public static bool IsDesignatedComfort(this Pawn pawn)
		{
			if (pawn.GetRJWPawnData().Comfort)
			{
				if (!pawn.IsDesignatedHero())
				{
					if (!pawn.IsPrisonerOfColony)
						if (!(xxx.is_masochist(pawn) || xxx.is_slave(pawn)))
						{
							if (!pawn.IsColonist)
								UnDesignateComfort(pawn);
							else if (!(RJWSettings.WildMode || (RJWSettings.override_RJW_designation_checks && !MP.IsInMultiplayer)))
								UnDesignateComfort(pawn);
						}
				}

				if (pawn.Dead)
					pawn.UnDesignateComfort();
			}

			return pawn.GetRJWPawnData().Comfort;
		}
		[SyncMethod]
		public static void DesignateComfort(this Pawn pawn)
		{
			DesignatorsData.rjwComfort.AddDistinct(pawn);
			pawn.GetRJWPawnData().Comfort = true;
		}
		[SyncMethod]
		public static void UnDesignateComfort(this Pawn pawn)
		{
			DesignatorsData.rjwComfort.Remove(pawn);
			pawn.GetRJWPawnData().Comfort = false;
		}
	}
}


code:
using Verse;
using RimWorld;
using Multiplayer.API;

namespace rjw
{
	public static class PawnDesignations_Hero
	{
		public static bool UpdateCanDesignateHero(this Pawn pawn)
		{
			if ((RJWSettings.RPG_hero_control)
				&& xxx.is_human(pawn)
				&& pawn.IsColonist
				&& !xxx.is_slave(pawn)
				&& !pawn.IsPrisoner)
			{
				if (!pawn.IsDesignatedHero())
				{
					foreach (Pawn item in DesignatorsData.rjwHero)
					{
						if (item.IsHeroOwner())
						{
							if (RJWSettings.RPG_hero_control_Ironman && !SaveStorage.DataStore.GetPawnData(item).Ironman)
								SetHeroIronman(item);
							if (item.Dead && !SaveStorage.DataStore.GetPawnData(item).Ironman)
							{
								UnDesignateHero(item);
								//Log.Warning("CanDesignateHero:: "  + MP.PlayerName + " hero is dead remove hero tag from " + item.Name);
							}
							else
							{
								//Log.Warning("CanDesignateHero:: "  + MP.PlayerName + " already has hero - " + item.Name);
								return pawn.GetRJWPawnData().CanDesignateHero = false;
							}

						}
						else
							continue;
					}
					return pawn.GetRJWPawnData().CanDesignateHero = true;
				}
			}
			return pawn.GetRJWPawnData().CanDesignateHero = false;
		}
		public static bool CanDesignateHero(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().CanDesignateHero;
		}
		public static void ToggleHero(this Pawn pawn)
		{
			pawn.UpdateCanDesignateHero();
			if (pawn.CanDesignateHero() && Find.Selector.NumSelected <= 1)
			{
				if (!pawn.IsDesignatedHero())
					DesignateHero(pawn);
			}
		}
		public static bool IsDesignatedHero(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().Hero;
		}
		public static void DesignateHero(this Pawn pawn)
		{
			SyncHero(pawn, MP.PlayerName);
		}
		[SyncMethod]
		public static void UnDesignateHero(this Pawn pawn)
		{
			DesignatorsData.rjwHero.Remove(pawn);
			pawn.GetRJWPawnData().Hero = false;
		}
		public static bool IsHeroOwner(this Pawn pawn)
		{
			if (!MP.enabled)
				return pawn.GetRJWPawnData().HeroOwner == "Player" || pawn.GetRJWPawnData().HeroOwner == null || pawn.GetRJWPawnData().HeroOwner == "";
			else
				return pawn.GetRJWPawnData().HeroOwner == MP.PlayerName;
		}
		[SyncMethod]
		static void SyncHero(Pawn pawn, string theName)
		{
			if (!MP.enabled)
				theName = "Player";
			pawn.GetRJWPawnData().Hero = true;
			pawn.GetRJWPawnData().HeroOwner = theName;
			pawn.GetRJWPawnData().Ironman = RJWSettings.RPG_hero_control_Ironman;
			DesignatorsData.rjwHero.AddDistinct(pawn);
			string text = pawn.Name + " is now hero of " + theName;
			Messages.Message(text, pawn, MessageTypeDefOf.NeutralEvent);
			//Log.Message(MP.PlayerName + "  set " + pawn.Name + " to hero:" + pawn.GetPawnData().Hero);

			pawn.UpdatePermissions();
		}
		[SyncMethod]
		public static void SetHeroIronman(this Pawn pawn)
		{
			pawn.GetRJWPawnData().Ironman = true;
		}
	}
}


code:
using Verse;
using Multiplayer.API;

namespace rjw
{
	public static class PawnDesignations_Milking
	{
		public static bool UpdateCanDesignateMilking(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().CanDesignateMilking = false;
		}
		public static bool CanDesignateMilking(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().CanDesignateMilking = false;
		}
		public static void ToggleMilking(this Pawn pawn)
		{
			if (pawn.CanDesignateMilking())
			{
				if (!pawn.IsDesignatedMilking())
					DesignateMilking(pawn);
				else
					UnDesignateMilking(pawn);
			}
		}
		public static bool IsDesignatedMilking(this Pawn pawn)
		{
			if (pawn.GetRJWPawnData().Milking)
			{
				if (!pawn.IsDesignatedHero())
					if (!(pawn.IsColonist || pawn.IsPrisonerOfColony || xxx.is_slave(pawn)))
						UnDesignateMilking(pawn);

				if (pawn.Dead)
					pawn.UnDesignateMilking();
			}

			return pawn.GetRJWPawnData().Milking;
		}
		[SyncMethod]
		public static void DesignateMilking(this Pawn pawn)
		{
			DesignatorsData.rjwMilking.AddDistinct(pawn);
			pawn.GetRJWPawnData().Milking = true;
		}
		[SyncMethod]
		public static void UnDesignateMilking(this Pawn pawn)
		{
			DesignatorsData.rjwMilking.Remove(pawn);
			pawn.GetRJWPawnData().Milking = false;
		}
	}
}


code:
using Verse;
using Multiplayer.API;

namespace rjw
{
	public static class PawnDesignations_Service
	{
		public static bool UpdateCanDesignateService(this Pawn pawn)
		{
			//no permission to change designation for NON prisoner hero/ other player
			if (!pawn.CanChangeDesignationPrisoner() && !pawn.CanChangeDesignationColonist())
				return pawn.GetRJWPawnData().CanDesignateService = false;

			//no permission to change designation for prisoner hero/ self
			if (!pawn.CanChangeDesignationPrisoner())
				return pawn.GetRJWPawnData().CanDesignateService = false;

			//cant sex
			if (!(xxx.can_fuck(pawn) || xxx.can_be_fucked(pawn)))
				return pawn.GetRJWPawnData().CanDesignateService = false;

			if (!pawn.IsDesignatedHero())
			{
				if (pawn.IsColonist)
					return pawn.GetRJWPawnData().CanDesignateService = true;
			}
			else if (pawn.IsHeroOwner())
				return pawn.GetRJWPawnData().CanDesignateService = true;

			if (pawn.IsPrisonerOfColony || xxx.is_slave(pawn))
				return pawn.GetRJWPawnData().CanDesignateService = true;

			return pawn.GetRJWPawnData().CanDesignateService = false;
		}
		public static bool CanDesignateService(this Pawn pawn)
		{
			return SaveStorage.DataStore.GetPawnData(pawn).CanDesignateService;
		}
		public static void ToggleService(this Pawn pawn)
		{
			pawn.UpdateCanDesignateService();
			if (pawn.CanDesignateService())
			{
				if (!pawn.IsDesignatedService())
					DesignateService(pawn);
				else
					UnDesignateService(pawn);
			}
		}
		public static bool IsDesignatedService(this Pawn pawn)
		{
			if (SaveStorage.DataStore.GetPawnData(pawn).Service)
			{
				if (!pawn.IsDesignatedHero())
					if (!(pawn.IsColonist || pawn.IsPrisonerOfColony || xxx.is_slave(pawn)))
						UnDesignateService(pawn);

				if (pawn.Dead)
					pawn.UnDesignateService();
			}

			return SaveStorage.DataStore.GetPawnData(pawn).Service;
		}
		[SyncMethod]
		public static void DesignateService(this Pawn pawn)
		{
			DesignatorsData.rjwService.AddDistinct(pawn);
			SaveStorage.DataStore.GetPawnData(pawn).Service = true;
		}
		[SyncMethod]
		public static void UnDesignateService(this Pawn pawn)
		{
			DesignatorsData.rjwService.Remove(pawn);
			SaveStorage.DataStore.GetPawnData(pawn).Service = false;
		}
	}
}


code:
using Verse;
using System.Diagnostics;
using RimWorld;

namespace rjw
{
	public static class PawnDesignations_Utility
	{
		public static bool UpdatePermissions(this Pawn pawn)
		{
			pawn.UpdateCanChangeDesignationPrisoner();
			pawn.UpdateCanChangeDesignationColonist();
			pawn.UpdateCanDesignateService();
			pawn.UpdateCanDesignateComfort();
			pawn.UpdateCanDesignateBreedingAnimal();
			pawn.UpdateCanDesignateBreeding();
			pawn.UpdateCanDesignateHero();
			return true;
		}
		public static bool UpdateCanChangeDesignationColonist(this Pawn pawn)
		{
			//check if pawn is a hero of other player
			//if yes - limit widget access in mp for this pawn

			if ((pawn.IsDesignatedHero() && !pawn.IsHeroOwner()))
			{
				//Log.Warning("CanChangeDesignationColonist:: Pawn:" + xxx.get_pawnname(pawn));
				//Log.Warning("CanChangeDesignationColonist:: IsDesignatedHero:" + pawn.IsDesignatedHero());
				//Log.Warning("CanChangeDesignationColonist:: IsHeroOwner:" + pawn.IsHeroOwner());
				return pawn.GetRJWPawnData().CanChangeDesignationColonist = false;
			}

			return pawn.GetRJWPawnData().CanChangeDesignationColonist = true;
		}
		public static bool CanChangeDesignationColonist(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().CanChangeDesignationColonist;
		}
		public static bool UpdateCanChangeDesignationPrisoner(this Pawn pawn)
		{
			//check if player hero is a slave/prisoner
			//if yes - limit widget access in mp for all widgets

			//Stopwatch sw = new Stopwatch();
			//sw.Start();

			//Log.Warning("rjwHero:: Count " + DesignatorsData.rjwHero.Count);
			//Log.Warning("rjwComfort:: Count " + DesignatorsData.rjwComfort.Count);
			//Log.Warning("rjwService:: Count " + DesignatorsData.rjwService.Count);
			//Log.Warning("rjwMilking:: Count " + DesignatorsData.rjwMilking.Count);
			//Log.Warning("rjwBreeding:: Count " + DesignatorsData.rjwBreeding.Count);
			//Log.Warning("rjwBreedingAnimal:: Count " + DesignatorsData.rjwBreedingAnimal.Count);

			foreach (Pawn item in DesignatorsData.rjwHero)
			{
				//Log.Warning("CanChangeDesignationPrisoner:: Pawn:" + xxx.get_pawnname(item));
				//Log.Warning("CanChangeDesignationPrisoner:: IsHeroOwner:" + item.IsHeroOwner());
				if (item.IsHeroOwner())
				{
					if (item.IsPrisonerOfColony || item.IsPrisoner || xxx.is_slave(item))
					{
						//Log.Warning("CanChangeDesignationPrisoner:: Pawn:" + xxx.get_pawnname(item));
						//Log.Warning("CanChangeDesignationPrisoner:: Hero of " + MP.PlayerName);
						//Log.Warning("CanChangeDesignationPrisoner:: is prisoner(colony):" + item.IsPrisonerOfColony);
						//Log.Warning("CanChangeDesignationPrisoner:: is prisoner:" + item.IsPrisoner);
						//Log.Warning("CanChangeDesignationPrisoner:: is slave:" + xxx.is_slave(item));
						return pawn.GetRJWPawnData().CanChangeDesignationPrisoner = false;
					}
				}
			}
			//sw.Stop();
			//Log.Warning("Elapsed={0}" + sw.Elapsed);

			return pawn.GetRJWPawnData().CanChangeDesignationPrisoner = true;
		}
		public static bool CanChangeDesignationPrisoner(this Pawn pawn)
		{
			return pawn.GetRJWPawnData().CanChangeDesignationPrisoner;
		}
	}
}


code:
using System.Collections.Generic;
using Verse;
using UnityEngine;

namespace rjw
{
	/// <summary>
	/// Handles creation of RJWdesignations button group for gui
	/// </summary>
	public class RJWdesignations : Command
	{
		//is actually a group of four buttons, but I've wanted them be small and so vanilla gizmo system is mostly bypassed for them

		private const float ContentPadding = 5f;
		private const float IconSize = 32f;
		private const float IconGap = 1f;

		private readonly Pawn parent;
		private Rect gizmoRect;
		/// <summary>
		/// This should keep track of last pressed pseudobutton. It is set in the pseudobutton callback.
		/// Then, the callback to encompassed Gizmo is performed by game, and this field is used to determine what exact button was pressed
		/// The callback is called by the tynancode right after the loop which detects click on button,
		/// so it will be called then and only then when it should be (no unrelated events).
		/// event handling  shit is needed to apply settings to all selected pawns.
		/// </summary>
		private static SubIcon lastClicked;

		static readonly List<SubIcon> subIcons = new List<SubIcon> {
			new Comfort(),
			//new Service(),
			//new BreederHuman(),
			new BreedingHuman(),
			new BreedingAnimal(),
			new Breeder(),
			//new Milking(),
			new Hero(),
			new HelpImStupid()
		};

		public RJWdesignations(Pawn pawn)
		{
			parent = pawn;
			defaultLabel = "RJWdesignations";
			defaultDesc = "RJWdesignations";
		}

		public override GizmoResult GizmoOnGUI(Vector2 topLeft, float maxWidth, GizmoRenderParms parms)
		{
			Rect rect = new Rect(topLeft.x, topLeft.y, 75f, 75f);
			gizmoRect = rect.ContractedBy(ContentPadding);
			Widgets.DrawWindowBackground(rect);

			//Log.Message("RJWgizmo");
			foreach (SubIcon icon in subIcons)
			{
				if (DrawSubIcon(icon))
				{
					lastClicked = icon;
					icon.state = icon.applied(parent);
					return new GizmoResult(GizmoState.Interacted, Event.current);
				}
			}
			return new GizmoResult(GizmoState.Clear);
		}

		//this and class mess below was supposed to be quick shortcut to not write four repeated chunks of code in GizmoOnGUI
		private bool DrawSubIcon(SubIcon icon)
		{
			if (!icon.applicable(parent)) { return false; }
			//Log.Message("sub gizmo");
			Rect iconRect = new Rect(gizmoRect.x + icon.offset.x, gizmoRect.y + icon.offset.y, IconSize, IconSize);
			TooltipHandler.TipRegion(iconRect, icon.desc(parent).Translate());
			bool applied = icon.applied(parent);
			Texture2D texture = applied ? icon.cancel : icon.texture(parent);
			GUI.DrawTexture(iconRect, texture);
			//GUI.color = Color.white;

			return Widgets.ButtonInvisible(iconRect, false);
		}

		public override void ProcessInput(Event ev)
		{
			SubIcon icon = lastClicked;
			if (icon.state)
				icon.unapply(parent);
			else
				icon.apply(parent);
		}

		[StaticConstructorOnStartup]//this  is needed for textures
		public abstract class SubIcon
		{
			public abstract Texture2D texture(Pawn pawn);
			public abstract Vector2 offset { get; }
			public abstract string desc(Pawn pawn);
			public abstract bool applicable(Pawn pawn);
			public abstract bool applied(Pawn pawn);
			public abstract void apply(Pawn pawn);
			public abstract void unapply(Pawn pawn);

			static readonly Texture2D cancellText = ContentFinder<Texture2D>.Get("UI/Commands/cancel");
			public virtual Texture2D cancel => cancellText;

			public bool state;
		}
		[StaticConstructorOnStartup]
		public class Comfort : SubIcon
		{
			//comfort raping
			static readonly Texture2D iconAccept = ContentFinder<Texture2D>.Get("UI/Commands/ComfortPrisoner_off");
			static readonly Texture2D iconRefuse = ContentFinder<Texture2D>.Get("UI/Commands/ComfortPrisoner_Refuse");
			static readonly Texture2D iconCancel = ContentFinder<Texture2D>.Get("UI/Commands/ComfortPrisoner_on");
			public override Texture2D texture(Pawn pawn) => (pawn.CanDesignateComfort() || pawn.IsDesignatedComfort()) && xxx.is_human(pawn) ? iconAccept : iconRefuse;
			public override Texture2D cancel { get; } = iconCancel;

			static readonly Vector2 posComf = new Vector2(IconGap + IconSize, 0);
			public override Vector2 offset => posComf;

			public override string desc(Pawn pawn) => pawn.CanDesignateComfort() ? "ForComfortDesc" :
														!pawn.CanChangeDesignationPrisoner() ? "ForHeroRefuse2Desc" :
														!pawn.CanChangeDesignationColonist() ? "ForHeroRefuse1Desc" : "ForComfortRefuseDesc";

			public override bool applicable(Pawn pawn) => RJWSettings.rape_enabled && xxx.is_human(pawn);
			public override bool applied(Pawn pawn) => pawn.IsDesignatedComfort();
			public override void apply(Pawn pawn) => pawn.ToggleComfort();
			public override void unapply(Pawn pawn) => pawn.ToggleComfort();
		}
		[StaticConstructorOnStartup]
		public class Service : SubIcon
		{
			//whoring
			static readonly Texture2D iconAccept = ContentFinder<Texture2D>.Get("UI/Commands/Service_off");
			static readonly Texture2D iconRefuse = ContentFinder<Texture2D>.Get("UI/Commands/Service_Refuse");
			static readonly Texture2D iconCancel = ContentFinder<Texture2D>.Get("UI/Commands/Service_on");
			public override Texture2D texture(Pawn pawn) => (pawn.CanDesignateService() || pawn.IsDesignatedService()) && xxx.is_human(pawn) ? iconAccept : iconRefuse;
			public override Texture2D cancel { get; } = iconCancel;

			public override Vector2 offset { get; } = new Vector2(0, 0);

			public override string desc(Pawn pawn) => pawn.CanDesignateService() ? "ForServiceDesc" :
														!pawn.CanChangeDesignationPrisoner() ? "ForHeroRefuse2Desc" :
														!pawn.CanChangeDesignationColonist() ? "ForHeroRefuse1Desc" : "ForServiceRefuseDesc";

			public override bool applicable(Pawn pawn) => xxx.is_human(pawn);
			public override bool applied(Pawn pawn) => pawn.IsDesignatedService() && xxx.is_human(pawn);
			public override void apply(Pawn pawn) => pawn.ToggleService();
			public override void unapply(Pawn pawn) => pawn.ToggleService();
		}
		[StaticConstructorOnStartup]
		public class BreedingHuman : SubIcon
		{
			//Breed humanlike
			static readonly Texture2D iconAccept = ContentFinder<Texture2D>.Get("UI/Commands/Breeding_Pawn_off");
			static readonly Texture2D iconRefuse = ContentFinder<Texture2D>.Get("UI/Commands/Breeding_Pawn_Refuse");
			static readonly Texture2D iconCancel = ContentFinder<Texture2D>.Get("UI/Commands/Breeding_Pawn_on");
			public override Texture2D texture(Pawn pawn) => (pawn.CanDesignateBreeding() || pawn.IsDesignatedBreeding()) && xxx.is_human(pawn) ? iconAccept : iconRefuse;
			public override Texture2D cancel { get; } = iconCancel;

			public override Vector2 offset { get; } = new Vector2(0, IconSize + IconGap);

			public override string desc(Pawn pawn) => pawn.CanDesignateBreeding() && xxx.is_human(pawn) ? "ForBreedingDesc" :
														!pawn.CanChangeDesignationPrisoner() ? "ForHeroRefuse2Desc" :
														!pawn.CanChangeDesignationColonist() ? "ForHeroRefuse1Desc" : "ForBreedingRefuseDesc";

			public override bool applicable(Pawn pawn) =>  RJWSettings.bestiality_enabled && xxx.is_human(pawn);
			public override bool applied(Pawn pawn) => pawn.IsDesignatedBreeding() && xxx.is_human(pawn);
			public override void apply(Pawn pawn) => pawn.ToggleBreeding();
			public override void unapply(Pawn pawn) => pawn.ToggleBreeding();
		}

		[StaticConstructorOnStartup]
		public class BreedingAnimal : SubIcon
		{
			//Breed animal
			static readonly Texture2D iconAccept = ContentFinder<Texture2D>.Get("UI/Commands/Breeding_Animal_off");
			static readonly Texture2D iconCancel = ContentFinder<Texture2D>.Get("UI/Commands/Breeding_Animal_on");
			public override Texture2D texture(Pawn pawn) => iconAccept;
			public override Texture2D cancel { get; } = iconCancel;

			public override Vector2 offset { get; } = new Vector2(0, IconSize + IconGap);

			public override string desc(Pawn pawn) => !pawn.CanChangeDesignationPrisoner() ? "ForHeroRefuse2Desc" : "ForBreedingDesc";

			public override bool applicable(Pawn pawn) => (pawn.CanDesignateBreeding() || pawn.IsDesignatedBreeding()) && xxx.is_animal(pawn);
			public override bool applied(Pawn pawn) => pawn.IsDesignatedBreeding() && xxx.is_animal(pawn);
			public override void apply(Pawn pawn) => pawn.ToggleBreeding();
			public override void unapply(Pawn pawn) => pawn.ToggleBreeding();
		}
		[StaticConstructorOnStartup]
		public class Breeder : SubIcon
		{
			//Breeder(fucker) animal
			static readonly Texture2D iconAccept = ContentFinder<Texture2D>.Get("UI/Commands/Breeder_Animal_off");
			static readonly Texture2D iconCancel = ContentFinder<Texture2D>.Get("UI/Commands/Breeder_Animal_on");
			public override Texture2D texture(Pawn pawn) => iconAccept;
			public override Texture2D cancel { get; } = iconCancel;

			public override Vector2 offset { get; } = new Vector2(0, 0);

			public override string desc(Pawn pawn) => !pawn.CanChangeDesignationPrisoner() ? "ForHeroRefuse2Desc" : "ForBreedingAnimalDesc";

			public override bool applicable(Pawn pawn) => pawn.CanDesignateBreedingAnimal() || pawn.IsDesignatedBreedingAnimal();
			public override bool applied(Pawn pawn) => pawn.IsDesignatedBreedingAnimal();
			public override void apply(Pawn pawn) => pawn.ToggleBreedingAnimal();
			public override void unapply(Pawn pawn) => pawn.ToggleBreedingAnimal();
		}
		[StaticConstructorOnStartup]
		public class Milking : SubIcon
		{
			static readonly Texture2D iconAccept = ContentFinder<Texture2D>.Get("UI/Commands/Milking_off");
			static readonly Texture2D iconCancel = ContentFinder<Texture2D>.Get("UI/Commands/Milking_on");
			public override Texture2D texture(Pawn pawn) => iconAccept;
			public override Texture2D cancel { get; } = iconCancel;

			public override Vector2 offset { get; } = new Vector2(IconGap + IconSize, IconSize + IconGap);

			public override string desc(Pawn pawn) => !pawn.CanChangeDesignationPrisoner() ? "ForHeroRefuse2Desc" : "ForMilkingDesc";

			public override bool applicable(Pawn pawn) => pawn.CanDesignateMilking() || pawn.IsDesignatedMilking();
			public override bool applied(Pawn pawn) => pawn.IsDesignatedMilking();
			public override void apply(Pawn pawn) => pawn.ToggleMilking();
			public override void unapply(Pawn pawn) => pawn.ToggleMilking();
		}
		[StaticConstructorOnStartup]
		public class Hero : SubIcon
		{
			static readonly Texture2D iconAccept = ContentFinder<Texture2D>.Get("UI/Commands/Hero_off");
			static readonly Texture2D iconCancel = ContentFinder<Texture2D>.Get("UI/Commands/Hero_on");
			public override Texture2D texture(Pawn pawn) => iconAccept;
			public override Texture2D cancel { get; } = iconCancel;

			public override Vector2 offset { get; } = new Vector2(IconGap + IconSize, IconSize + IconGap);

			//public override string desc(Pawn pawn) => pawn.CanDesignateHero() || (pawn.IsDesignatedHero() && pawn.IsHeroOwner()) ? "ForHeroDesc" : "Hero of " + pawn.GetPawnData().HeroOwner;
			public override string desc(Pawn pawn) => pawn.CanDesignateHero() ? "ForHeroDesc" :
														pawn.IsDesignatedHero() ? "Hero of " + pawn.GetRJWPawnData().HeroOwner : "ForHeroDesc";

			public override bool applicable(Pawn pawn) => pawn.CanDesignateHero() || pawn.IsDesignatedHero();
			public override bool applied(Pawn pawn) => pawn.IsDesignatedHero();
			public override void apply(Pawn pawn) => pawn.ToggleHero();
			public override void unapply(Pawn pawn) => pawn.ToggleHero();
		}
		[StaticConstructorOnStartup]
		public class HelpImStupid : SubIcon
		{
			// a question mark that shows when no other icons show; shows a hint to look at mod settings
			static readonly Texture2D myicon = ContentFinder<Texture2D>.Get("UI/Commands/HelpImStupid");
			public override Texture2D texture(Pawn pawn) => myicon;
			public override Texture2D cancel { get; } = myicon;

			static readonly Vector2 posComf = new Vector2(IconGap + IconSize, 0);
			public override Vector2 offset => posComf;

			public override string desc(Pawn pawn) => "GoToModSettings";

			public override bool applicable(Pawn pawn) => !(RJWSettings.rape_enabled && xxx.is_human(pawn)) && // comfort
														!(pawn.CanDesignateHero() || pawn.IsDesignatedHero()) && // hero
														//!(pawn.CanDesignateMilking() || pawn.IsDesignatedMilking()) && // milking
														!(pawn.CanDesignateBreedingAnimal() || pawn.IsDesignatedBreedingAnimal()) && // breeder
														!((pawn.CanDesignateBreeding() || pawn.IsDesignatedBreeding()) && xxx.is_animal(pawn)) && // breeding animal
														!(RJWSettings.bestiality_enabled && xxx.is_human(pawn));// && // breeding human
														//!(pawn.IsDesignatedService() && xxx.is_human(pawn)); // service

			public override bool applied(Pawn pawn) => true;
			public override void apply(Pawn pawn) { }
			public override void unapply(Pawn pawn) { }
		}
	}
}


code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib;
using Verse;
using RimWorld;
using UnityEngine;

// Non-pregnancy Biotech-related patches
namespace rjw
{
    [HarmonyPatch]
    class LifeStageWorker_HumanlikeX_Notify_LifeStageStarted
    {
        static IEnumerable<MethodBase> TargetMethods()
        {
            const string lifeStageStarted = nameof(LifeStageWorker.Notify_LifeStageStarted);
            yield return AccessTools.Method(typeof(LifeStageWorker_HumanlikeChild), lifeStageStarted);
            yield return AccessTools.Method(typeof(LifeStageWorker_HumanlikeAdult), lifeStageStarted);
        }

        // Fixes errors caused by trying to spawn a biotech-only effector when a child starts a new lifestage
        // and by trying to send a biotech-only letter when a child turns three
        [HarmonyTranspiler]
        static IEnumerable<CodeInstruction> FixLifeStageStartError(IEnumerable<CodeInstruction> instructions, MethodBase original)
        {
            PropertyInfo thingSpawned = AccessTools.DeclaredProperty(typeof(Thing), nameof(Thing.Spawned));
            MethodInfo shouldSendNotificationsAbout = AccessTools.Method(typeof(PawnUtility), nameof(PawnUtility.ShouldSendNotificationAbout));
            bool foundAny = false;

            foreach (var instruction in instructions)
            {
                yield return instruction;

                // if (pawn.Spawned) SpawnBiotechOnlyEffector()
                // => if (pawn.Spawned && ModsConfig.IsBiotechActive) SpawnBiotechOnlyEffector()
                if (instruction.Calls(thingSpawned.GetMethod) || instruction.Calls(shouldSendNotificationsAbout))
                {
                    yield return CodeInstruction.Call(typeof(ModsConfig), "get_BiotechActive");
                    yield return new CodeInstruction(OpCodes.And);
                    foundAny = true;
                }
            }

            if (!foundAny)
            {
                ModLog.Error("Failed to patch " + original.Name);
            }
        }
    }

    [HarmonyPatch(typeof(WidgetsWork), "get_WorkBoxBGTex_AgeDisabled")]
    class WidgetsWork_WorkBoxBGTex_AgeDisabled
    {
        [HarmonyPrefix]
        static bool DontLoadMissingTexture(ref Texture2D __result)
        {
            if (!ModsConfig.BiotechActive)
            {
                __result = WidgetsWork.WorkBoxBGTex_Awful;
                return false;
            }

            return true;
        }
    }

    // If biotech is disabled, TeachOpportunity will NRE due to a null ConceptDef argument
    // Silence the error that interrupts AgeTick results by adding a null check.
    [HarmonyPatch(typeof(LessonAutoActivator), nameof(LessonAutoActivator.TeachOpportunity), new [] {typeof(ConceptDef), typeof(Thing), typeof(OpportunityType)})]
    static class Patch_LessonAutoActivator_TeachOpportunity
    {
        public static bool Prefix(ConceptDef conc)
        {
            // call the underlying method if concept is non-null
            return conc != null;
        }
    }

    // If biotech is disabled, make the Baby() method return false in the targeted method.
    [HarmonyPatch]
    static class Patch_DevelopmentalStageExtensions_Baby_Callers
    {

        static IEnumerable<MethodBase> TargetMethods()
        {
            // Make babies follow adult rules for food eligibility instead of requiring milk/baby food
            yield return AccessTools.Method(typeof(FoodUtility), nameof(FoodUtility.WillEat_NewTemp), new [] {typeof(Pawn), typeof(ThingDef), typeof(Pawn), typeof(bool), typeof(bool)});
            // Make babies able to be fed in bed as a patient in lieu of nursing
            yield return AccessTools.Method(typeof(WorkGiver_FeedPatient), nameof(WorkGiver_FeedPatient.HasJobOnThing), new [] {typeof(Pawn), typeof(Thing), typeof(bool)});
        }

        [HarmonyTranspiler]
        public static IEnumerable<CodeInstruction> BabyMethodShouldReturnFalse(IEnumerable<CodeInstruction> instructions, MethodBase original)
        {
            bool foundAny = false;
            MethodInfo developmentalStageIsBabyMethod = AccessTools.Method(typeof(DevelopmentalStageExtensions), nameof(DevelopmentalStageExtensions.Baby));
            List<CodeInstruction> codeInstructions = instructions.ToList();
            foreach (CodeInstruction instruction in codeInstructions)
            {
                yield return instruction;
                if (instruction.Calls(developmentalStageIsBabyMethod))
                {
                    foundAny = true;
                    if (!ModsConfig.BiotechActive)
                    {
                        // After calling the Baby() method, AND the result with 0, to make it as if DevelopmentalStageExtensions::Baby() returned false.
                        yield return new CodeInstruction(OpCodes.Ldc_I4_0);
                        yield return new CodeInstruction(OpCodes.And);
                    }
                }
            }
            if (!foundAny)
            {
                ModLog.Error("Failed to patch " + original.Name);
            }
        }
    }

	// Check for fertile penis instead of gender when compiling list of pawns that could fertilize ovum
	[HarmonyPatch]
	static class Patch_HumanOvum_CanFertilizeReport
	{
		static IEnumerable<MethodBase> TargetMethods()
		{
			yield return AccessTools.Method(typeof(HumanOvum), "CanFertilizeReport", new[] { typeof(Pawn) });
		}

		static bool hasPenis(Pawn p)
		{
			// need to use current hediffSet, else has_penis_fertile reads data from save (an issue if a pawn lost their penis since then)
			List<Hediff> parts = p?.health?.hediffSet?.hediffs;
			return Genital_Helper.has_penis_fertile(p, parts);
		}

		[HarmonyTranspiler]
		public static IEnumerable<CodeInstruction> CheckForPenisInsteadOfGender(IEnumerable<CodeInstruction> instructions, MethodBase original)
		{
			MethodInfo checkForPenis = AccessTools.Method(typeof(Patch_HumanOvum_CanFertilizeReport), nameof(Patch_HumanOvum_CanFertilizeReport.hasPenis));
			bool foundGenderCheck = false;

			foreach (CodeInstruction ci in instructions)
			{
				string cis = ci.ToString();
				if (cis.Contains("Verse.Gender Verse.Pawn::gender"))
				{
					// check for fertile penis instead of male gender
					foundGenderCheck = true;
					yield return new CodeInstruction(OpCodes.Call, checkForPenis);
				}
				else
				{
					yield return ci;
				}
			}
			if (!foundGenderCheck)
			{
				ModLog.Warning("Failed to patch " + original.Name);
			}
		}
	}

	// If babies are malnourished, mark them as needing urgent medical rest, despite being permanently downed.
	[HarmonyPatch(typeof(HealthAIUtility), nameof(HealthAIUtility.ShouldSeekMedicalRestUrgent), new [] {typeof(Pawn)})]
    static class Patch_HealthAIUtility_ShouldSeekMedicalRestUrgent
    {
        public static bool Prefix(Pawn pawn, ref bool __result)
        {
            if (!ModsConfig.BiotechActive && pawn.DevelopmentalStage.Baby())
            {
                __result = true;
                return false;
            }
            return true;
        }
    }
}


code:
using HarmonyLib;
using Verse;
using System;
using RimWorld;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

/// <summary>
/// patches Building_Bed to add stuff for WhoreBeds
///
/// Also contains smaller patches for RoomRoleWorker_Barracks (don't count whore beds) (disabled) and Toils_LayDown.ApplyBedThoughts (slept in brothel thought)
/// </summary>

namespace rjw
{
	public static class Building_Bed_Patch
	{

		private static readonly Color sheetColorForWhores = new Color(181 / 255f, 55 / 255f, 109 / 255f);

		// Set color for whore beds
		[HarmonyPatch(typeof(Building_Bed))]
		[HarmonyPatch(nameof(Building_Bed.DrawColorTwo), MethodType.Getter)]
		public static class Building_Bed_DrawColor_Patch
		{
			[HarmonyPostfix]
			public static void Postfix(Building_Bed __instance, ref Color __result)
			{
				if (__instance.IsAllowedForWhoringAll())
				{
					__result = sheetColorForWhores;
				}
			}
		}

		// add whoring toggles to beds
		[HarmonyPatch(typeof(Building_Bed), nameof(Building_Bed.GetGizmos))]
		public static class Building_Bed_GetGizmos_Patch
		{
			[HarmonyPostfix]
			public static void Postfix(Building_Bed __instance, ref IEnumerable<Gizmo> __result)
			{
				__result = Process(__instance, __result);
			}

			private static IEnumerable<Gizmo> Process(Building_Bed __instance, IEnumerable<Gizmo> __result)
			{

				var isPrisonCell = __instance.GetRoom()?.IsPrisonCell == true;
				if (!__instance.ForPrisoners && !__instance.Medical && __instance.def.building.bed_humanlike && __instance.Faction == Faction.OfPlayerSilentFail && !__instance.def.defName.Contains("Guest") && !isPrisonCell)
				{

					yield return
						new Command_Toggle
						{
							defaultLabel = "CommandBedAllowWhoringLabel".Translate(),
							defaultDesc = "CommandBedAllowWhoringDesc".Translate(),
							icon = ContentFinder<Texture2D>.Get("UI/Commands/AsWhore"),
							isActive = __instance.IsAllowedForWhoringOwner,
							toggleAction = __instance.ToggleAllowedForWhoringOwner,
							hotKey = KeyBindingDefOf.Misc5, // Guest Beds uses Misc4
							disabled = !__instance.def.HasAssignableCompFrom(typeof(CompAssignableToPawn_Bed)),
							disabledReason = "This bed type is not assignable to pawns."
						};

					yield return
						new Command_Toggle
						{
							defaultLabel = "CommandBedSetAsWhoreBedLabel".Translate(),
							defaultDesc = "CommandBedSetAsWhoreBedDesc".Translate(),
							icon = ContentFinder<Texture2D>.Get("UI/Commands/AsWhoreMany"),
							isActive = __instance.IsAllowedForWhoringAll,
							toggleAction = __instance.ToggleAllowedForWhoringAll,
							hotKey = KeyBindingDefOf.Misc6, // Guest Beds uses Misc4
							disabled = !__instance.def.HasAssignableCompFrom(typeof(CompAssignableToPawn_Bed)),
							disabledReason = "This bed type is not assignable to pawns."
						};
				}

				foreach (var gizmo in __result)
				{
					if (__instance.IsAllowedForWhoringAll())
					{
						if (gizmo is Command_Toggle && ((Command_Toggle)gizmo).defaultLabel == "CommandBedSetAsGuestLabel".Translate())
						{
							// hide set as guest bed
							continue;
						};
						// old: instead of hiding, just disable
						/*switch (gizmo)
						{
							case Command_Toggle toggle:
								{
									// Disable prisoner and medical, and guest buttons
									if (//toggle.defaultLabel == "CommandBedSetForPrisonersLabel".Translate() ||
										//toggle.defaultLabel == "CommandBedSetAsMedicalLabel".Translate() ||
										toggle.defaultLabel == "CommandBedSetAsGuestLabel".Translate()) gizmo.Disable();
									break;
								}
						}//*/
					}
					yield return gizmo;
				}
			}
		}

		// add description of whore price factor to inspect string (bottom left corner if item selected)
		[HarmonyPatch(typeof(Building_Bed), nameof(Building_Bed.GetInspectString))]
		public static class Building_Bed_GetInspectString_Patch
		{
			[HarmonyPostfix]
			public static void Postfix(Building_Bed __instance, ref string __result)
			{
				if (__instance.def.building.bed_humanlike && __instance.Faction == Faction.OfPlayerSilentFail && (__instance.IsAllowedForWhoringAll() || __instance.IsAllowedForWhoringOwner()))
				{
					__result = __result + "\n" + "WhorePriceCalcDesc".Translate(WhoreBed_Utility.CalculatePriceFactor(__instance).ToString("F2"));
					if (RJWSettings.DebugWhoring)
					{
						__result = __result + "\nbed.thingIDNumber: " + __instance.thingIDNumber.ToString();

						__result = __result + "\nscoreUpdateTickDelay: " + SaveStorage.DataStore.GetBedData(__instance).scoreUpdateTickDelay.ToString();

						if (SaveStorage.DataStore.GetBedData(__instance).reservedUntilGameTick > GenTicks.TicksGame)
						{
							__result = __result + "\nreserved by pawn id: " + SaveStorage.DataStore.GetBedData(__instance).reservedForPawnID.ToString();
						}
					}
				}
			}
		}

		// add whore price factor as overlay
		[HarmonyPatch(typeof(Building_Bed), nameof(Building_Bed.DrawGUIOverlay))]
		public static class Building_Bed_DrawGUIOverlay_Patch
		{
			[HarmonyPrefix]
			public static bool Prefix(Building_Bed __instance)
			{
				if (RJWSettings.show_whore_price_factor_on_bed && __instance.def.building.bed_humanlike && __instance.Faction == Faction.OfPlayerSilentFail) {
					// if whore bed, print price factor on it
					if (Find.CameraDriver.CurrentZoom == CameraZoomRange.Closest
						&& ((__instance.IsAllowedForWhoringOwner() && __instance.OwnersForReading.Any<Pawn>())
							|| __instance.IsAllowedForWhoringAll()))
					{
						Color defaultThingLabelColor = GenMapUI.DefaultThingLabelColor;

						// make string
						float whore_price_factor = WhoreBed_Utility.CalculatePriceFactor(__instance);
						string wpf;
						if (Math.Abs(whore_price_factor) >= 100)
						{
							wpf = ((int)whore_price_factor).ToString("D");
						}
						else if (Math.Abs(whore_price_factor) >= 10)
						{
							wpf = whore_price_factor.ToString("F1");
						}
						else
						{
							wpf = whore_price_factor.ToString("F2");
						}

						// get dimensions of text and make it appear above names
						Vector2 textsize = Text.CalcSize(wpf);
						Vector2 baseLabelPos = GenMapUI.LabelDrawPosFor(__instance, -0.4f); // -0.4f is copied from vanilla code
						baseLabelPos.y -= textsize.y * 0.75f;

						GenMapUI.DrawThingLabel(baseLabelPos, wpf, defaultThingLabelColor);

						if (__instance.IsAllowedForWhoringAll() && !__instance.OwnersForReading.Any<Pawn>())
						{
							// hide "Unowned" if whore bed with no owner
							return false;
						}
					}
				}
				// after drawing whore price factor, draw the actual names
				// could have been done as a postfix, but I started with a prefix, hoping I could get by with only one draw call
				return true;
			}

		}

		// barracks don't count whore beds, so room type switches to brothel sooner
		// disabled - barracks have their own slept in ~ debuff; doesn't really matter; put some effort in your brothels!
		/*[HarmonyPatch(typeof(RoomRoleWorker_Barracks), nameof(RoomRoleWorker_Barracks.GetScore))]
		public static class RoomRoleWorker_Barracks_GetScore_Patch
		{
			public static bool Prefix(Room room, ref float __result)
			{
				int num = 0;
				int num2 = 0;
				List<Thing> containedAndAdjacentThings = room.ContainedAndAdjacentThings;
				for (int i = 0; i < containedAndAdjacentThings.Count; i++)
				{
					Building_Bed building_Bed = containedAndAdjacentThings[i] as Building_Bed;
					if (building_Bed != null && building_Bed.def.building.bed_humanlike)
					{
						if (building_Bed.ForPrisoners)
						{
							__result = 0f;
							return false;
						}
						num++;
						if (!building_Bed.Medical && !building_Bed.IsAllowedForWhoringAll())
						{
							num2++;
						}
					}
				}
				if (num <= 1)
				{
					__result = 0f;
					return false;
				}
				__result = (float)num2 * 100100f;
				return false;
			}
		}*/

		// if pawns sleep in a brothel or a whoring bed, they get a thought
		[HarmonyPatch(typeof(Toils_LayDown), "ApplyBedThoughts")]
		public class Toils_LayDown_ApplyBedThoughts_Patch
		{
			[HarmonyPostfix]
			public static void Postfix(Pawn actor)
			{
				if (actor?.needs?.mood == null) return;

				Building_Bed building_Bed = actor.CurrentBed();

				actor?.needs?.mood?.thoughts?.memories?.RemoveMemoriesOfDef(WhoringThoughtDefOf.SleptInBrothel);

				if (building_Bed == null) return;

				if (building_Bed?.GetRoom()?.Role == WhoreBed_Utility.roleDefBrothel || building_Bed.IsAllowedForWhoringAll())
				{
					var memoryHandler = actor.needs.mood.thoughts.memories;
					int thoughtStage = 0;

					foreach (var thoughtDef in DefDatabase<ThoughtDef_Whore>.AllDefsListForReading)
					{
						var memory = memoryHandler.GetFirstMemoryOfDef(thoughtDef);
						if (memory?.CurStageIndex >= thoughtDef.stages.Count - 1)
						{
							thoughtStage = 1;
							break;
						}
					}

					memoryHandler.TryGainMemory(ThoughtMaker.MakeThought(WhoringThoughtDefOf.SleptInBrothel, thoughtStage));
				}
			}
		}

		// if room stats are updated, update beds within
		//	"necessary" if beds are toggled during pause
		[HarmonyPatch(typeof(Room), "UpdateRoomStatsAndRole")]
		public class Room_UpdateRoomStatsAndRole_Patch
		{
			[HarmonyPostfix]
			public static void Postfix(Room __instance)
			{
				// note: with room stat display enabled, this get's called quite often for whatever room the mouse hovers over
				//	even large outdoor areas
				//	where iterating over all things to find all beds (even if there are none) is expensive
				//	for now, skip doing anything if even the game decides it's not worth it
				//	(game sets role to None if region count >36 or something)
				//	- the beds will update eventually

				if (/*Find.PlaySettings.showRoomStats && */__instance.Role == RoomRoleDefOf.None)
					return;

				if (Find.TickManager.Paused)
				{
					// if paused, update immediately
					WhoreBed_Utility.CalculateBedFactorsForRoom(__instance);
				}
				else
				{
					// else, just make beds update as soon as needed
					WhoreBed_Utility.ResetTicksUntilUpdate(__instance);
				}
			}
		}
	}
}


code:
using System.Reflection;
using Harmony;
using RimWorld;
using Verse;

namespace rjw
{
	/// <summary>
	/// Conditional patching class that only does patching if CnP is active
	/// </summary>
	public class CnPcompatibility
	{
		//CnP (or BnC) try to address the joy need of a child, prisoners don't have that.
		//Considering how you can arrest children without rjw, it is more of a bug of that mod than ours.
		[HarmonyPatch(typeof(Pawn_NeedsTracker), "BindDirectNeedFields")]
		static class jfpk
		{
			[HarmonyPostfix]
			static void postfix(ref Pawn_NeedsTracker __instance)
			{
				Pawn_NeedsTracker tr = __instance;
				FieldInfo fieldInfo = AccessTools.Field(typeof(Pawn_NeedsTracker), "pawn");
				Pawn pawn = fieldInfo.GetValue(__instance) as Pawn;
				if (xxx.is_human(pawn) && pawn.ageTracker.CurLifeStageIndex < AgeStage.Teenager)
				{
					if (tr.TryGetNeed(NeedDefOf.Joy) == null)
					{
						MethodInfo method = AccessTools.Method(typeof(Pawn_NeedsTracker), "AddNeed");
						method.Invoke(tr, new object[] { NeedDefOf.Joy });
					}
				}
			}
		}

		//For whatever reason, harmony shits itself, when trying to patch non void private fields, below are variants the code that would work nicely, if it didn't
		//[HarmonyPatch]
		//[StaticConstructorOnStartup]
		//internal static class joy_for_prison_kids
		//{
		//    [HarmonyTargetMethod]
		//    static MethodBase CalculateMethod(HarmonyInstance instance)
		//    {
		//        var r = AccessTools.Method(typeof(Pawn_NeedsTracker), "ShouldHaveNeed");

		//        //Log.Message("Found method "+ r.ReturnType + ' ' + r.FullDescription());
		//        //Log.Message("Parameters " + r.GetType() );
		//        //Log.Message("return " + r.ReturnParameter);
		//        return AccessTools.Method(typeof(Pawn_NeedsTracker), "ShouldHaveNeed");
		//    }
		//    [HarmonyPrepare]
		//    static bool should_patch(HarmonyInstance instance)
		//    {
		//        Log.Clear();
		//        Log.Message("Will patch "+ xxx.RimWorldChildrenIsActive);
		//        return xxx.RimWorldChildrenIsActive;
		//    }

		//doesn't work, gets:  System.Reflection.TargetParameterCountException: parameters do not match signature
		//static void Postfix(HarmonyInstance instance)
		//{
		//    Log.Message("FOO");
		//}
		//[HarmonyPrefix]
		//static bool foo(NeedDef nd)
		//{
		//    Log.Message("Prerun ");
		//    return true;
		//}
		//[HarmonyPostfix]
		//static void postfix(ref bool __result, ref Pawn_NeedsTracker __instance, NeedDef nd)
		//{
		//    if (nd != NeedDefOf.Joy) { return; }
		//    FieldInfo fieldInfo = AccessTools.Field(typeof(Pawn_NeedsTracker), "pawn");
		//    Pawn pawn = fieldInfo.GetValue(__instance) as Pawn;
		//    if (pawn.ageTracker.CurLifeStageIndex < AgeStage.Teenager)
		//    {
		//        __result = true;
		//    }
		//}
		//}
		public static void Patch(HarmonyInstance harmony)
		{
			if (!xxx.RimWorldChildrenIsActive) return;
			Doit(harmony);
		}
		private static void Doit(HarmonyInstance harmony)
		{
			var original = typeof(RimWorldChildren.ChildrenUtility).GetMethod("CanBreastfeed");
			var postfix = typeof(CnPcompatibility).GetMethod("CanBreastfeed");
			harmony.Patch(original, null, new HarmonyMethod(postfix));

			original = typeof(Building_Bed).GetMethod("get_AssigningCandidates");
			postfix = typeof(CnPcompatibility).GetMethod("BedCandidates");
			harmony.Patch(original, null, new HarmonyMethod(postfix));

			//doesn't work cannot reflect private class
			//original = typeof(RimWorldChildren.Hediff_UnhappyBaby).GetMethod("IsBabyUnhappy", BindingFlags.Static | BindingFlags.NonPublic);
			//Log.Message("original is nul " + (original == null));
			//var prefix = typeof(CnPcompatibility).GetMethod("IsBabyUnhappy");
			//harmony.Patch(original, new HarmonyMethod(prefix), null);
		}
		private static void CanBreastfeed(ref  bool __result, ref Pawn __instance)//Postfix
		{
			__result = __instance.health.hediffSet.HasHediff(HediffDef.Named("Lactating"));//I'm a simple man
		}
		private static void BedCandidates(ref IEnumerable<Pawn> __result, ref Building_Bed bed)
		{
			if (!RimWorldChildren.BedPatchMethods.IsCrib(bed)) return;
			__result = bed.Map.mapPawns.FreeColonists.Where(x => x.ageTracker.CurLifeStageIndex <= 2 && x.Faction == Faction.OfPlayer);//Basically do all the work second time but with a tweak
		}
		private static bool IsBabyUnhappy(ref bool __result, ref RimWorldChildren.Hediff_UnhappyBaby __instance)
		{
			var pawn = __instance.pawn;

			if ((pawn.needs?.joy.CurLevelPercentage??1) < 0.2f)
				__result = true;
			else
				__result =  false;
			return false;
		}
	}
}


code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using HarmonyLib;

namespace rjw
{
	public static class CodeExtensions
	{
		/// <summary>
		/// <para>Breaks apart a list of instructions at some specific point, identified by a
		/// predicate function.  The first instruction that the predicate matches will be
		/// included in the `before` list, while all remaining instructions will be
		/// in the `after` list.</para>
		/// <para>If no instructions matched the predicate, all instructions will be in
		/// the `before` list and the `after` list will be empty.</para>
		/// <para>This is useful for breaking apart the instructions into more manageable
		/// chunks to better identify the target of your patch.</para>
		/// </summary>
		/// <param name="instructions">This list of instructions.</param>
		/// <param name="predicate">The predicate to identify the break point.</param>
		/// <returns>A tuple, the first being the instructions up to and including the
		/// instruction that matched the predicate and the second being everything
		/// afterward.</returns>
		public static (List<CodeInstruction> before, List<CodeInstruction> after) SplitAfter(
			this List<CodeInstruction> instructions,
			Predicate<CodeInstruction> predicate)
		{
			if (instructions.FindIndex(predicate) is var idx and not -1)
			{
				var before = instructions.Take(idx + 1).ToList();
				var after = instructions.Skip(before.Count).ToList();
				return (before, after);
			}

			return (instructions, new());
		}

		/// <summary>
		/// <para>Checks the next instructions in this list of instructions to make sure
		/// they all match some expectation, one predicate per instruction.  If the
		/// predicates all match, it produces two new lists, one with the matched
		/// instructions and the other with those matched instructions removed.</para>
		/// <para>If any predicate fails to match, the `cut` list will be empty and
		/// the `remainder` list will be the same instance as `instructions`.</para>
		/// <para>Use this to validate that the code actually is the code you expect
		/// and isolate it from other instructions so you can tweak it safely.</para>
		/// </summary>
		/// <param name="instructions">This list of instructions.</param>
		/// <param name="predicates">One or more predicates to test each instruction.</param>
		/// <returns>A tuple, the first being the list of cut instructions and the second
		/// being the remaining instructions after the cut.</returns>
		public static (List<CodeInstruction> cut, List<CodeInstruction> remainder) CutMatchingSequence(
			this List<CodeInstruction> instructions,
			params Predicate<CodeInstruction>[] predicates)
		{
			if (predicates.Length == 0)
				return (new(), instructions);
			if (instructions.Count < predicates.Length)
				return (new(), instructions);
			if (instructions.Zip(predicates, (il, pred) => pred(il)).Contains(false))
				return (new(), instructions);

			var cut = instructions.Take(predicates.Length).ToList();
			var remainder = instructions.Skip(predicates.Length).ToList();
			return (cut, remainder);
		}

		/// <summary>
		/// <para>Determines if this instruction is some form of `stloc` that matches the
		/// given index in the locals table.</para>
		/// <para>Why is this not a part of Harmony's API?</para>
		/// </summary>
		/// <param name="il">This instruction.</param>
		/// <param name="index">The locals table index to check for.</param>
		/// <returns>Whether this is a `stloc` targeting the given index.</returns>
		public static bool IsStlocOf(this CodeInstruction il, int index) => index switch
		{
			0 when il.opcode == OpCodes.Stloc_0 => true,
			1 when il.opcode == OpCodes.Stloc_1 => true,
			2 when il.opcode == OpCodes.Stloc_2 => true,
			3 when il.opcode == OpCodes.Stloc_3 => true,
			// Most common thing we'll see...
			_ when il.IsStloc() && il.operand is LocalBuilder lb => lb.LocalIndex == index,
			// ...but these are also technically possible with `stloc_s` and `stloc`.
			_ when il.IsStloc() && il.operand is byte bIndex => bIndex == Convert.ToByte(index),
			_ when il.IsStloc() && il.operand is ushort uIndex => uIndex == Convert.ToUInt16(index),
			_ => false
		};

		/// <summary>
		/// Copies the labels from this instruction to its replacement.  If the replacement
		/// instruction also has labels, it ensures that duplicate labels are discarded.
		/// </summary>
		/// <param name="il">This instruction.</param>
		/// <param name="newIl">The instruction that will replace it.</param>
		/// <returns>The replacement instruction.</returns>
		public static CodeInstruction Replace(this CodeInstruction il, CodeInstruction newIl)
		{
			var copyLabels = newIl.labels.ToList();
			newIl.labels.Clear();
			newIl.labels.AddRange(copyLabels.Concat(il.labels).Distinct());
			return newIl;
		}
	}
}


code:
using HarmonyLib;
using RimWorld;
using System;
using Verse;

namespace rjw
{
	///
	///unset designators on GuestRelease
	///until pawn leaves map, pawn is still guest/slave/prisoner, so they can actually be changed back
	///
	[HarmonyPatch(typeof(GenGuest), "GuestRelease")]
	[StaticConstructorOnStartup]
	static class PATCH_GenGuest_GuestRelease
	{
		[HarmonyPrefix]
		private static void GuestRelease_Update_Designators(Pawn p)
		{
			if (p != null)
			{
				//ModLog.Message("GenGuest GuestRelease");
				//ModLog.Message("pawn: " + xxx.get_pawnname(p));
				p.UnDesignateComfort();
				p.UnDesignateService();
				p.UnDesignateBreeding();
				p.UnDesignateBreedingAnimal();
				p.UnDesignateMilking();
				p.UnDesignateHero();
				//ModLog.Message(p.IsDesignatedComfort().ToString());
			}
		}
	}

	///
	///unset designators on Pawn_ExitMap
	///now pawn actually leaves map and get their factions reset
	///
	[HarmonyPatch(typeof(Pawn), "ExitMap")]
	[StaticConstructorOnStartup]
	static class PATCH_Pawn_ExitMap
	{
		[HarmonyPrefix]
		private static void Pawn_ExitMap_Update_Designators(Pawn __instance, bool allowedToJoinOrCreateCaravan, Rot4 exitDir)
		{
			Pawn p = __instance;
			if (p != null)
				if (!p.IsColonist)
				{
					//ModLog.Message("Pawn ExitMap");
					//ModLog.Message("pawn: " + xxx.get_pawnname(p));
					p.UnDesignateComfort();
					p.UnDesignateService();
					p.UnDesignateBreeding();
					p.UnDesignateBreedingAnimal();
					p.UnDesignateMilking();
					p.UnDesignateHero();
					//ModLog.Message(p.IsDesignatedComfort().ToString());
				}
		}
	}
}