code
stringlengths 0
56.1M
| repo_name
stringlengths 3
57
| path
stringlengths 2
176
| language
stringclasses 672
values | license
stringclasses 8
values | size
int64 0
56.8M
|
|---|---|---|---|---|---|
<Patch>
<Operation Class="PatchOperationSequence">
<operations>
<li Class="PatchOperationFindMod">
<mods>
<li>Royalty</li>
</mods>
<match Class="PatchOperationFindMod">
<mods>
<li>Anime Tree</li>
</mods>
<match Class="PatchOperationAdd">
<xpath>/Defs/ThingDef[defName="Plant_TreeAnima"]/comps/li[@Class="CompProperties_MeditationFocus"]/focusTypes</xpath>
<value>
<li>Sex</li>
</value>
</match>
</match>
</li>
</operations>
</Operation>
</Patch>
|
jojo1541/rjw
|
1.4/Patches/Animetree_Meditation.xml
|
XML
|
mit
| 529
|
<?xml version="1.0" encoding="utf-8" ?>
<Patch>
<!--Better Infestations-->
<Operation Class="PatchOperationSequence">
<success>Always</success>
<operations>
<li Class="PatchOperationTest">
<xpath>Defs/DutyDef[defName="BI_DefendAndExpandHive"]</xpath>
</li>
<li Class="PatchOperationInsert">
<xpath>Defs/DutyDef[defName="BI_DefendAndExpandHive"]/thinkNode/subNodes/li[@Class="ThinkNode_ChancePerHour_Constant"]</xpath>
<value>
<li Class="rjw.JobGiver_RapeEnemy" />
</value>
</li>
</operations>
</Operation>
</Patch>
|
jojo1541/rjw
|
1.4/Patches/Better_Infestations_AiRapeEnemy.xml
|
XML
|
mit
| 558
|
<?xml version="1.0" encoding="utf-8" ?>
<Patch>
<!-- Animals, Insects, Birds, modded pawns -->
<Operation Class="PatchOperationAdd">
<xpath>Defs/BodyDef[defName != "Human"]/corePart[def != "MechanicalThorax" and def != "MechanicalThoraxCanManipulate" and def != "MechanicalCentipedeBodyFirstRing" and def != "MechanicalTermiteBodyFirstRing" and def != "MechanicalDiabolusBodyFirstRing" and def != "MechanicalWarqueenBodyFirstRing"]/parts</xpath>
<value>
<li>
<def>Genitals</def>
<coverage>0.005</coverage>
<height>Bottom</height>
<depth>Outside</depth>
<groups>
<li>Torso</li>
<li>GenitalsBPG</li>
</groups>
</li>
</value>
</Operation>
<Operation Class="PatchOperationAdd">
<xpath>Defs/BodyDef[defName != "Human"]/corePart[def != "MechanicalThorax" and def != "MechanicalThoraxCanManipulate" and def != "MechanicalCentipedeBodyFirstRing" and def != "MechanicalTermiteBodyFirstRing" and def != "MechanicalDiabolusBodyFirstRing" and def != "MechanicalWarqueenBodyFirstRing"]/parts</xpath>
<value>
<li>
<def>Chest</def>
<coverage>0.02</coverage>
<height>Top</height>
<depth>Outside</depth>
<groups>
<li>Torso</li>
<li>ChestBPG</li>
</groups>
</li>
</value>
</Operation>
<Operation Class="PatchOperationAdd">
<xpath>Defs/BodyDef[defName != "Human"]/corePart[def != "MechanicalThorax" and def != "MechanicalThoraxCanManipulate" and def != "MechanicalCentipedeBodyFirstRing" and def != "MechanicalTermiteBodyFirstRing" and def != "MechanicalDiabolusBodyFirstRing" and def != "MechanicalWarqueenBodyFirstRing"]/parts</xpath>
<value>
<li>
<def>Flank</def>
<coverage>0.02</coverage>
<height>Bottom</height>
<depth>Outside</depth>
<groups>
<li>Torso</li>
<li>FlankBPG</li>
</groups>
</li>
</value>
</Operation>
<Operation Class="PatchOperationAdd">
<xpath>Defs/BodyDef[defName != "Human"]/corePart[def != "MechanicalThorax" and def != "MechanicalThoraxCanManipulate" and def != "MechanicalCentipedeBodyFirstRing" and def != "MechanicalTermiteBodyFirstRing" and def != "MechanicalDiabolusBodyFirstRing" and def != "MechanicalWarqueenBodyFirstRing"]/parts</xpath>
<value>
<li>
<def>Anus</def>
<coverage>0.001</coverage>
<height>Bottom</height>
<depth>Inside</depth>
<groups>
<li>Torso</li>
<li>AnusBPG</li>
</groups>
</li>
</value>
</Operation>
</Patch>
|
jojo1541/rjw
|
1.4/Patches/BodyParts_Animals&Aliens.xml
|
XML
|
mit
| 2,437
|
<?xml version="1.0" encoding="utf-8" ?>
<Patch>
<!-- Humans -->
<Operation Class="PatchOperationAdd">
<xpath>Defs/BodyDef[defName = "Human"]/corePart/parts</xpath>
<value>
<li>
<def>Genitals</def>
<coverage>0.005</coverage>
<height>Bottom</height>
<depth>Outside</depth>
<groups>
<li>Torso</li>
<li>GenitalsBPG</li>
</groups>
</li>
<li>
<def>Chest</def>
<coverage>0.02</coverage>
<height>Top</height>
<depth>Outside</depth>
<groups>
<li>Torso</li>
<li>ChestBPG</li>
</groups>
</li>
<li>
<def>Anus</def>
<coverage>0.001</coverage>
<height>Bottom</height>
<depth>Inside</depth>
<groups>
<li>Torso</li>
<li>AnusBPG</li>
</groups>
</li>
</value>
</Operation>
<!-- lower abdomen? -->
<Operation Class="PatchOperationAdd">
<xpath>Defs/BodyDef[defName = "Human"]/corePart/parts</xpath>
<value>
<li>
<def>Flank</def>
<coverage>0.02</coverage>
<height>Bottom</height>
<depth>Outside</depth>
<groups>
<li>Torso</li>
<li>FlankBPG</li>
</groups>
</li>
</value>
</Operation>
</Patch>
|
jojo1541/rjw
|
1.4/Patches/BodyParts_Humanoid.xml
|
XML
|
mit
| 1,149
|
<?xml version="1.0" encoding="utf-8" ?>
<Patch>
<!-- Mechanoids, maybe even modded -->
<Operation Class="PatchOperationAdd">
<xpath>Defs/BodyDef/corePart[def = "MechanicalThorax"]/parts</xpath>
<value>
<li>
<def>MechGenitals</def>
<coverage>0.001</coverage>
<depth>Inside</depth>
</li>
</value>
</Operation>
<Operation Class="PatchOperationAdd">
<xpath>Defs/BodyDef/corePart[def = "MechanicalThoraxCanManipulate"]/parts</xpath>
<value>
<li>
<def>MechGenitals</def>
<coverage>0.001</coverage>
<depth>Inside</depth>
</li>
</value>
</Operation>
<Operation Class="PatchOperationAdd">
<xpath>Defs/BodyDef/corePart[def = "MechanicalCentipedeBodyFirstRing"]/parts/li[def = "MechanicalCentipedeBodySecondRing"]/parts</xpath>
<value>
<li>
<def>MechGenitals</def>
<coverage>0.001</coverage>
<depth>Inside</depth>
</li>
</value>
</Operation>
<Operation Class="PatchOperationAdd">
<xpath>Defs/BodyDef/corePart[def = "MechanicalTermiteBodyFirstRing"]/parts/li[def = "MechanicalTermiteBodySecondRing"]/parts</xpath>
<value>
<li>
<def>MechGenitals</def>
<coverage>0.001</coverage>
<depth>Inside</depth>
</li>
</value>
</Operation>
<Operation Class="PatchOperationFindMod">
<mods>
<li>Biotech</li>
</mods>
<match Class="PatchOperationAdd">
<xpath>Defs/BodyDef/corePart[def = "MechanicalDiabolusBodyFirstRing"]/parts</xpath>
<value>
<li>
<def>MechGenitals</def>
<coverage>0.001</coverage>
<depth>Inside</depth>
</li>
</value>
</match>
</Operation>
<Operation Class="PatchOperationFindMod">
<mods>
<li>Biotech</li>
</mods>
<match Class="PatchOperationAdd">
<xpath>Defs/BodyDef/corePart[def = "MechanicalWarqueenBodyFirstRing"]/parts/li[def = "MechanicalWarqueenBodySecondRing"]/parts</xpath>
<value>
<li>
<def>MechGenitals</def>
<coverage>0.001</coverage>
<depth>Inside</depth>
</li>
</value>
</match>
</Operation>
</Patch>
|
jojo1541/rjw
|
1.4/Patches/BodyParts_Mechanoid.xml
|
XML
|
mit
| 2,008
|
<?xml version="1.0" encoding="utf-8"?>
<Patch>
<Operation Class="PatchOperationFindMod">
<mods>
<li>Combat Extended</li>
</mods>
<match Class="PatchOperationSequence">
<operations>
<li Class="PatchOperationAdd">
<xpath>Defs/ThingDef[defName="Condom"]/statBases</xpath>
<value>
<Bulk>0.01</Bulk>
</value>
</li>
<li Class="PatchOperationAdd">
<xpath>Defs/ThingDef[defName="HumpShroom"]/statBases</xpath>
<value>
<Bulk>0.25</Bulk>
</value>
</li>
<li Class="PatchOperationAdd">
<xpath>Defs/ThingDef[defName="Aphrodisiac"]/statBases</xpath>
<value>
<Bulk>0.05</Bulk>
</value>
</li>
<li Class="PatchOperationAdd">
<xpath>Defs/ThingDef[defName="RJW_Contraceptive"]/statBases</xpath>
<value>
<Bulk>0.01</Bulk>
</value>
</li>
<li Class="PatchOperationAdd">
<xpath>Defs/ThingDef[defName="RJW_FertPill"]/statBases</xpath>
<value>
<Bulk>0.01</Bulk>
</value>
</li>
<li Class="PatchOperationAdd">
<xpath>Defs/ThingDef[defName="Holokey"]/statBases</xpath>
<value>
<Bulk>0.05</Bulk>
</value>
</li>
</operations>
</match>
</Operation>
</Patch>
|
jojo1541/rjw
|
1.4/Patches/CEbulk_patch.xml
|
XML
|
mit
| 1,220
|
<?xml version="1.0" encoding="utf-8" ?>
<Patch>
<!--Removes CnP contraceptive because rjw has its own which works for both mods-->
<!--Fucking Tynan. Not removing anything, because the game will error about empty xml in CnP then-->
<!--Instead we'll delete RJW_contraceptive and insert the effect into CnP hediff-->
<!--Fuck it. I'm out-->
<!--<Operation Class="PatchOperationSequence">
<operations>
<li Class="PatchOperationTest">
<xpath>Defs/ThingDef[defName="Contraceptive"]</xpath>
</li>
<li Class="PatchOperationAdd">
<xpath>Defs/HediffDef[defName="Contraceptive"]</xpath>
<value>
<stages>
<li>
<label>Contracepted</label>
<capMods>
<li>
<capacity>RJW_Fertility</capacity>
<setMax>0.1</setMax>
</li>
</capMods>
</li>
</stages>
</value>
</li>
<li Class="PatchOperationRemove">
<xpath>Defs/ThingDef[defName="RJW_Contraceptive"]</xpath>
</li>
</operations>
</Operation>-->
</Patch>
|
jojo1541/rjw
|
1.4/Patches/CnP_compatibility.xml
|
XML
|
mit
| 999
|
<?xml version="1.0" encoding="utf-8" ?>
<Patch>
<!--Rape prisoners in NonPlayerHome-->
<Operation Class="PatchOperationInsert">
<xpath>Defs/DutyDef[defName = "DefendBase"]/thinkNode/subNodes/li[@Class="ThinkNode_ForbidOutsideFlagRadius"]/subNodes/li[@Class="ThinkNode_Subtree"]</xpath>
<value>
<li Class="rjw.JobGiver_AIRapePrisoner" />
</value>
</Operation>
</Patch>
|
jojo1541/rjw
|
1.4/Patches/Duty_AIRapePrisoner.xml
|
XML
|
mit
| 379
|
<?xml version="1.0" encoding="utf-8" ?>
<Patch>
<Operation Class="PatchOperationInsert">
<xpath>Defs/DutyDef[defName = "AssaultColony"]/thinkNode/subNodes/li[@Class="JobGiver_AIFightEnemies"]</xpath>
<value>
<li Class="rjw.JobGiver_RapeEnemy" />
</value>
</Operation>
<Operation Class="PatchOperationInsert">
<xpath>Defs/DutyDef[defName = "AssaultColony"]/thinkNode/subNodes/li[@Class="JobGiver_AITrashColonyClose"]</xpath>
<value>
<li Class="rjw.JobGiver_RapeEnemy">
</li>
</value>
</Operation>
<Operation Class="PatchOperationInsert">
<xpath>Defs/DutyDef[defName = "Sapper"]/thinkNode/subNodes/li[@Class="JobGiver_AIFightEnemies"]</xpath>
<value>
<li Class="rjw.JobGiver_RapeEnemy" />
</value>
</Operation>
<Operation Class="PatchOperationInsert">
<xpath>Defs/DutyDef[defName = "Defend"]/thinkNode/subNodes/li[@Class="ThinkNode_ForbidOutsideFlagRadius"]</xpath>
<value>
<li Class="rjw.JobGiver_RapeEnemy" />
</value>
</Operation>
<Operation Class="PatchOperationInsert">
<xpath>Defs/DutyDef[defName = "DefendBase"]/thinkNode/subNodes/li[@Class="JobGiver_AIDefendPoint"]</xpath>
<value>
<li Class="rjw.JobGiver_RapeEnemy" />
</value>
</Operation>
<Operation Class="PatchOperationInsert">
<xpath>Defs/DutyDef[defName = "HuntEnemiesIndividual"]/thinkNode/subNodes/li[@Class="JobGiver_AIFightEnemies"]</xpath>
<value>
<li Class="rjw.JobGiver_RapeEnemy" />
</value>
</Operation>
<Operation Class="PatchOperationInsert">
<xpath>Defs/DutyDef[defName = "DefendAndExpandHive"]/thinkNode/subNodes/li[@Class="ThinkNode_Tagger"]</xpath>
<value>
<li Class="rjw.JobGiver_RapeEnemy" />
</value>
</Operation>
<Operation Class="PatchOperationInsert">
<xpath>Defs/DutyDef[defName = "DefendHiveAggressively"]/thinkNode/subNodes/li[@Class="JobGiver_HiveDefense"]</xpath>
<value>
<li Class="rjw.JobGiver_RapeEnemy" />
</value>
</Operation>
<Operation Class="PatchOperationInsert">
<xpath>Defs/ThinkTreeDef[defName="MentalStateNonCritical"]/thinkRoot[@Class="ThinkNode_Tagger"]/subNodes/li[stateClass="MentalState_Manhunter"]/subNodes/li[@Class="ThinkNode_Priority"]/subNodes/li[@Class="JobGiver_Manhunter"]</xpath>
<value>
<li Class="rjw.JobGiver_RapeEnemy" />
<li Class="rjw.JobGiver_NymphSapper" />
</value>
</Operation>
<!--<Operation Class="PatchOperationInsert">
<xpath>Defs/ThinkTreeDef[defName="MentalStateNonCritical"]/thinkRoot[@Class="ThinkNode_Tagger"]/subNodes/li[state="ManhunterPermanent"]/subNodes/li[@Class="ThinkNode_Priority"]/subNodes/li[@Class="JobGiver_Manhunter"]</xpath>
<value>
<li Class="rjw.JobGiver_RapeEnemy" />
</value>
</Operation>-->
<!--<Operation Class="PatchOperationInsert">
<xpath>Defs/DutyDef[defName = "Sapper"]/thinkNode/subNodes/li[Class="JobGiver_AITrashColonyClose"]</xpath>
<value>
<li Class=" rjw.JobGiver_RapeEnemy" />
</value>
</Operation>
<Operation Class="PatchOperationInsert">
<xpath>Defs/DutyDef[defName = "TakeWoundedGuest"]/thinkNode/subNodes/li[0]</xpath>
<value>
<li Class=" rjw.JobGiver_RapeEnemy" />
</value>
</Operation>
<Operation Class="PatchOperationInsert">
<xpath>Defs/DutyDef[defName = "Kidnap"]/thinkNode/subNodes/li[0]</xpath>
<value>
<li Class=" rjw.JobGiver_RapeEnemy" />
</value>
</Operation>-->
</Patch>
|
jojo1541/rjw
|
1.4/Patches/Duty_AiRapeEnemy.xml
|
XML
|
mit
| 3,304
|
<?xml version="1.0" encoding="utf-8"?>
<Patch>
<Operation Class="PatchOperationFindMod">
<mods>
<li>[NL] Facial Animation - WIP</li>
</mods>
<match Class="PatchOperationSequence">
<success>Always</success>
<operations>
<li Class="PatchOperationAdd">
<xpath>/Defs/FacialAnimation.FaceAnimationDef[defName="Lovin" or defName="Lovin2"]/targetJobs</xpath>
<success>Always</success>
<value>
<li>RJW_Masturbate</li>
<li>GettinBred</li>
<li>Bestiality</li>
<li>BestialityForFemale</li>
<li>ViolateCorpse</li>
<li>Quickie</li>
<li>GettingQuickie</li>
<li>GettinRaped</li>
<li>JoinInBed</li>
<li>GettinLoved</li>
<li>GettinLicked</li>
<li>GettinSucked</li>
</value>
</li>
<li Class="PatchOperationAdd">
<xpath>/Defs/FacialAnimation.FaceAnimationDef[defName="WaitCombat" or defName="Wait_Combat_Rare"]/targetJobs</xpath>
<success>Always</success>
<value>
<li>RapeComfortPawn</li>
<li>RandomRape</li>
<li>RapeEnemy</li>
</value>
</li>
<li Class="PatchOperationAdd">
<xpath>/Defs/FacialAnimation.FaceAnimationDef[defName="Wear" or defName="Wear2" or defName="Wear3"]/targetJobs</xpath>
<success>Always</success>
<value>
<li>StruggleInBondageGear</li>
</value>
</li>
<li Class="PatchOperationFindMod">
<mods>
<li>Rimworld-Animations</li>
</mods>
<match Class="PatchOperationSequence">
<success>Always</success>
<operations>
<li Class="PatchOperationRemove">
<xpath>/Defs/FacialAnimation.FaceAnimationDef[defName="Lovin" or defName="Lovin2"]/animationFrames/li[1]/headOffset</xpath>
<success>Always</success>
</li>
<li Class="PatchOperationRemove">
<xpath>/Defs/FacialAnimation.FaceAnimationDef[defName="Lovin"]/animationFrames/li[2]/headOffset</xpath>
<success>Always</success>
</li>
<li Class="PatchOperationRemove">
<xpath>/Defs/FacialAnimation.FaceAnimationDef[defName="Lovin"]/animationFrames/li[3]/headOffset</xpath>
<success>Always</success>
</li>
<li Class="PatchOperationAdd">
<xpath>/Defs/FacialAnimation.FaceAnimationDef[defName="Lovin" or defName="Lovin2"]/targetJobs</xpath>
<success>Always</success>
<value>
<li>JoinInBedAnimation</li>
<li>GettinLovedAnimation</li>
</value>
</li>
</operations>
</match>
</li>
</operations>
</match>
</Operation>
</Patch>
|
jojo1541/rjw
|
1.4/Patches/FacialAnimation_compatibility.xml
|
XML
|
mit
| 2,879
|
<?xml version="1.0" encoding="utf-8" ?>
<Patch>
<!-- Copied from Vanilla BingingDrug. live selfish till rape someone. tweak if you want add some action. -->
<Operation Class="PatchOperationAdd">
<xpath>Defs/ThinkTreeDef[defName="MentalStateCritical"]/thinkRoot[@Class="ThinkNode_Tagger"]/subNodes</xpath>
<value>
<li Class="ThinkNode_ConditionalMentalState">
<state>RandomRape</state>
<subNodes>
<li Class="ThinkNode_ConditionalNeedPercentageAbove">
<need>Rest</need>
<threshold>0.05</threshold>
<invert>true</invert>
<subNodes>
<li Class="JobGiver_GetRest"/>
</subNodes>
</li>
<li Class="ThinkNode_PrioritySorter">
<minPriority>0.5</minPriority>
<subNodes>
<li Class="JobGiver_GetFood"/>
<li Class="ThinkNode_Priority_GetJoy">
<subNodes>
<li Class="JobGiver_GetJoy"/>
</subNodes>
</li>
</subNodes>
</li>
<li Class="rjw.JobGiver_RandomRape"/>
<li Class="JobGiver_WanderColony" />
</subNodes>
</li>
</value>
</Operation>
</Patch>
|
jojo1541/rjw
|
1.4/Patches/MentalStateCritical_AiRandomRape.xml
|
XML
|
mit
| 1,086
|
<?xml version="1.0" encoding="utf-8" ?>
<Patch>
<Operation Class="PatchOperationSequence">
<success>Always</success>
<operations>
<li Class="PatchOperationTest">
<xpath>Defs/TraitDef[defName="Prude"]</xpath>
</li>
<li Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Nymphomaniac"]/conflictingTraits</xpath>
<value>
<li>Prude</li>
</value>
</li>
<li Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Prude"]/conflictingTraits</xpath>
<value>
<li>Nymphomaniac</li>
</value>
</li>
<li Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Prude"]/degreeDatas/li</xpath>
<value>
<statOffsets>
<SexFrequency>-0.3</SexFrequency>
</statOffsets>
</value>
</li>
</operations>
</Operation>
<Operation Class="PatchOperationSequence">
<success>Always</success>
<operations>
<li Class="PatchOperationTest">
<xpath>Defs/TraitDef[defName="Faithful"]</xpath>
</li>
<li Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Nymphomaniac"]/conflictingTraits</xpath>
<value>
<li>Faithful</li>
</value>
</li>
<li Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Faithful"]/conflictingTraits</xpath>
<value>
<li>Nymphomaniac</li>
</value>
</li>
</operations>
</Operation>
<Operation Class="PatchOperationConditional">
<xpath>Defs/TraitDef[defName="Nimble"]/degreeDatas/li/statOffsets</xpath>
<nomatch Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Nimble"]/degreeDatas/li</xpath>
<value>
<statOffsets>
<Vulnerability>-0.1</Vulnerability>
</statOffsets>
</value>
</nomatch>
<match Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Nimble"]/degreeDatas/li/statOffsets</xpath>
<value>
<Vulnerability>-0.1</Vulnerability>
</value>
</match>
</Operation>
<Operation Class="PatchOperationConditional">
<xpath>Defs/TraitDef[defName="Bloodlust"]/degreeDatas/li/statOffsets</xpath>
<nomatch Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Bloodlust"]/degreeDatas/li</xpath>
<value>
<statOffsets>
<Vulnerability>-0.1</Vulnerability>
</statOffsets>
</value>
</nomatch>
<match Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Bloodlust"]/degreeDatas/li/statOffsets</xpath>
<value>
<Vulnerability>-0.1</Vulnerability>
</value>
</match>
</Operation>
<!-- Brawler does not need vulnerability patching: they already get hefty bonus from melee-->
<Operation Class="PatchOperationConditional">
<xpath>Defs/TraitDef[defName="Tough"]/degreeDatas/li/statOffsets</xpath>
<nomatch Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Tough"]/degreeDatas/li</xpath>
<value>
<statOffsets>
<Vulnerability>-0.4</Vulnerability>
</statOffsets>
</value>
</nomatch>
<match Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Tough"]/degreeDatas/li/statOffsets</xpath>
<value>
<Vulnerability>-0.4</Vulnerability>
</value>
</match>
</Operation>
<!-- Lower vulnerability because TooSmart pwans are better prepared and/or likely to outwit the potential rapist-->
<Operation Class="PatchOperationConditional">
<xpath>Defs/TraitDef[defName="TooSmart"]/degreeDatas/li/statOffsets</xpath>
<nomatch Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="TooSmart"]/degreeDatas/li</xpath>
<value>
<statOffsets>
<Vulnerability>-0.3</Vulnerability>
</statOffsets>
</value>
</nomatch>
<match Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="TooSmart"]/degreeDatas/li/statOffsets</xpath>
<value>
<Vulnerability>-0.3</Vulnerability>
</value>
</match>
</Operation>
<Operation Class="PatchOperationConditional">
<xpath>Defs/TraitDef[defName="Wimp"]/degreeDatas/li/statOffsets</xpath>
<nomatch Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Wimp"]/degreeDatas/li</xpath>
<value>
<statOffsets>
<Vulnerability>0.2</Vulnerability>
</statOffsets>
</value>
</nomatch>
<match Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Wimp"]/degreeDatas/li/statOffsets</xpath>
<value>
<Vulnerability>0.2</Vulnerability>
</value>
</match>
</Operation>
<Operation Class="PatchOperationConditional">
<xpath>Defs/TraitDef[defName="Masochist"]/degreeDatas/li/statOffsets</xpath>
<nomatch Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Masochist"]/degreeDatas/li</xpath>
<value>
<statOffsets>
<Vulnerability>0.3</Vulnerability>
</statOffsets>
</value>
</nomatch>
<match Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Masochist"]/degreeDatas/li/statOffsets</xpath>
<value>
<Vulnerability>0.3</Vulnerability>
</value>
</match>
</Operation>
<Operation Class="PatchOperationConditional">
<xpath>Defs/TraitDef[defName="Ascetic"]/degreeDatas/li/statOffsets</xpath>
<nomatch Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Ascetic"]/degreeDatas/li</xpath>
<value>
<statOffsets>
<SexFrequency>-0.3</SexFrequency>
</statOffsets>
</value>
</nomatch>
<match Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Ascetic"]/degreeDatas/li/statOffsets</xpath>
<value>
<SexFrequency>-0.3</SexFrequency>
</value>
</match>
</Operation>
<Operation Class="PatchOperationConditional">
<xpath>Defs/TraitDef[defName="BodyPurist"]/degreeDatas/li/statOffsets</xpath>
<nomatch Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="BodyPurist"]/degreeDatas/li</xpath>
<value>
<statOffsets>
<SexFrequency>-0.1</SexFrequency>
</statOffsets>
</value>
</nomatch>
<match Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="BodyPurist"]/degreeDatas/li/statOffsets</xpath>
<value>
<SexFrequency>-0.1</SexFrequency>
</value>
</match>
</Operation>
<Operation Class="PatchOperationSequence">
<success>Always</success>
<operations>
<li Class="PatchOperationTest">
<xpath>Defs/TraitDef[defName="Asexual"]</xpath>
</li>
<li Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Necrophiliac"]/conflictingTraits</xpath>
<value>
<li>Asexual</li>
</value>
</li>
<li Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Nymphomaniac"]/conflictingTraits</xpath>
<value>
<li>Asexual</li>
</value>
</li>
<li Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Rapist"]/conflictingTraits</xpath>
<value>
<li>Asexual</li>
</value>
</li>
<li Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Zoophile"]/conflictingTraits</xpath>
<value>
<li>Asexual</li>
</value>
</li>
<li Class="PatchOperationAdd">
<xpath>Defs/TraitDef[defName="Asexual"]/conflictingTraits</xpath>
<value>
<li>Necrophiliac</li>
<li>Nymphomaniac</li>
<li>Rapist</li>
<li>Zoophile</li>
</value>
</li>
</operations>
</Operation>
</Patch>
|
jojo1541/rjw
|
1.4/Patches/ModdedTraits_compatibility.xml
|
XML
|
mit
| 7,021
|
<?xml version="1.0" encoding="utf-8" ?>
<Patch>
<!-- Animals -->
<Operation Class="PatchOperationAdd">
<xpath>Defs/ThingDef[@Name="AnimalThingBase"]/recipes</xpath>
<value>
<li>DeterminePregnancy</li>
<li>RJW_AbortionHuman</li>
<li>RJW_AbortionBeast</li>
<li>RJW_AbortionMech</li>
<li>RJW_HackMech</li>
<li>RJW_RemoveRestraints</li>
<li>RJW_RemoveCocoon</li>
<li>RemoveUdder</li>
</value>
</Operation>
</Patch>
|
jojo1541/rjw
|
1.4/Patches/Recipes_Animals.xml
|
XML
|
mit
| 443
|
<?xml version="1.0" encoding="utf-8" ?>
<Patch>
<!-- Add peg arms -->
<!-- Races_Humanlike -->
<!--
<Operation Class="PatchOperationAdd">
<xpath>Defs/ThingDef[defName = "Human"]/recipes</xpath>
<value>
<li>InstallPegArm</li>
</value>
</Operation>
-->
</Patch>
|
jojo1541/rjw
|
1.4/Patches/Recipes_PegArm_Human.xml
|
XML
|
mit
| 277
|
<?xml version="1.0" encoding="utf-8" ?>
<Patch>
<Operation Class="PatchOperationAdd">
<xpath>Defs/RulePackDef[defName = "GlobalUtility"]/include</xpath>
<value>
<li>TalkTopicsSex</li>
</value>
</Operation>
<Operation Class="PatchOperationAdd">
<xpath>Defs/InteractionDef[defName = "DeepTalk"]/logRulesInitiator/rulesStrings</xpath>
<value>
<li>subject(p=0.24)->[TalkTopicSex]</li>
</value>
</Operation>
<Operation Class="PatchOperationAdd">
<xpath>Defs/InteractionDef[defName = "Chitchat"]/logRulesInitiator/rulesStrings</xpath>
<value>
<li>r_logentry(p=0.12)->[INITIATOR_nameDef] and [RECIPIENT_nameDef] [talkedabout] [TalkTopicSex].</li>
<li>r_logentry(p=0.12)->[INITIATOR_nameDef] [talkedabout] [TalkTopicSex] with [RECIPIENT_nameDef].</li>
<li>r_logentry(p=0.24)->[INITIATOR_nameDef] [commentedabout] [TalkTopicSex] to [RECIPIENT_nameDef].</li>
</value>
</Operation>
</Patch>
|
jojo1541/rjw
|
1.4/Patches/TalkTopics_Sex.xml
|
XML
|
mit
| 961
|
<Patch>
<Operation Class="PatchOperationSequence">
<success>Always</success>
<operations>
<li Class="PatchOperationAdd">
<xpath>Defs/ThoughtDef[defName="HarmedMe"]/nullifyingTraits</xpath>
<value>
<li>Masochist</li>
</value>
</li>
</operations>
</Operation>
</Patch>
|
jojo1541/rjw
|
1.4/Patches/Thought_Masochist.xml
|
XML
|
mit
| 297
|
<Patch>
<Operation Class="PatchOperationSequence">
<success>Always</success>
<operations>
<li Class="PatchOperationAdd">
<xpath>Defs/ThoughtDef[defName="ObservedLayingCorpse"]/nullifyingTraits</xpath>
<value>
<li>Necrophiliac</li>
</value>
</li>
<li Class="PatchOperationAdd">
<xpath>Defs/ThoughtDef[defName="ObservedLayingRottingCorpse"]/nullifyingTraits</xpath>
<value>
<li>Necrophiliac</li>
</value>
</li>
</operations>
</Operation>
</Patch>
|
jojo1541/rjw
|
1.4/Patches/Thought_Necro.xml
|
XML
|
mit
| 498
|
<Patch>
<!--
Nymph: everyone should fuck me!!!
<Operation Class="PatchOperationSequence">
<success>Always</success>
<operations>
<li Class="PatchOperationAdd">
<xpath>Defs/ThoughtDef[defName="CheatedOnMe"]/nullifyingTraits</xpath>
<value>
<li>Nymphomaniac</li>
</value>
</li>
<li Class="PatchOperationAdd">
<xpath>Defs/ThoughtDef[defName="CheatedOnMeMood"]/nullifyingTraits</xpath>
<value>
<li>Necrophiliac</li>
</value>
</li>
</operations>
</Operation>
-->
</Patch>
|
jojo1541/rjw
|
1.4/Patches/Thought_Nymph.xml
|
XML
|
mit
| 523
|
<?xml version="1.0" encoding="utf-8" ?>
<Patch>
<!-- Add RJW Sex meditation focus icon to VanillaPsycastsExpanded -->
<Operation Class="PatchOperationFindMod">
<mods>
<li>Vanilla Psycasts Expanded</li>
</mods>
<match Class="PatchOperationAddModExtension">
<xpath>/Defs/MeditationFocusDef[defName="Sex"]</xpath>
<value>
<li Class="VanillaPsycastsExpanded.MeditationFocusExtension">
<icon>UI/PsyfocusIcons/PsyfocusSex</icon>
</li>
</value>
</match>
</Operation>
</Patch>
|
jojo1541/rjw
|
1.4/Patches/VanillaPsycastsExpanded_Icon.xml
|
XML
|
mit
| 504
|
root=true
[*.{cs,xml}]
indent_style = tab
|
jojo1541/rjw
|
1.4/Source/.editorconfig
|
none
|
mit
| 43
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RimJobWorld")]
[assembly: AssemblyDescription("Adult mod for Rimworld")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Community Project")]
[assembly: AssemblyProduct("RimJobWorld")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c2825019-7f0b-456d-85a3-479c1a2a8805")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
|
jojo1541/rjw
|
1.4/Source/0trash/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,231
|
/*
Core versions of scripts addapted for Greater Good
*/
using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using RimWorld.Planet;
using Verse;
using rjw;
namespace rjw_CORE_EXPOSED
{
// used in Vulnerability StatDef calculation
public class SkillNeed_BaseBonus : SkillNeed
{
private float baseValue = 0.5f;
private float bonusPerLevel = 0.05f;
public override float ValueFor(Pawn pawn)
{
if (pawn.skills == null)
{
return 1f;
}
int level = pawn.skills.GetSkill(this.skill).Level;
// remove melee bonus for pawns: downed, sleeping/resting/lying, wearing armbinder
if (pawn.Downed || pawn.GetPosture() != PawnPosture.Standing ||
(xxx.RjwExIsActive && pawn.health.hediffSet.HasHediff(xxx.RjwEx_Armbinder))) // Simple verification on RJW side, but ideally this method should just be patched in RJW-EX to return valueAtLevel(0) if Armbinder active
level = 0;
return this.ValueAtLevel(level);
}
private float ValueAtLevel(int level)
{
return this.baseValue + this.bonusPerLevel * (float)level;
}
public override IEnumerable<string> ConfigErrors()
{
foreach (string error in base.ConfigErrors())
{
yield return error;
}
for (int i = 1; i <= 20; i++)
{
float factor = this.ValueAtLevel(i);
if (factor <= 0f)
{
yield return "SkillNeed yields factor < 0 at skill level " + i;
}
}
}
}
public static class LovePartnerRelationUtility
{
public static float LovinMtbSinglePawnFactor(Pawn pawn)
{
float num = 1f;
num /= 1f - pawn.health.hediffSet.PainTotal;
float efficiency = pawn.health.capacities.GetLevel(PawnCapacityDefOf.Consciousness);
if (efficiency < 0.5f)
{
num /= efficiency * 2f;
}
if (!pawn.RaceProps.Humanlike)
{
return num * 4f;
}
if (RimWorld.LovePartnerRelationUtility.ExistingLovePartner(pawn) != null)
{
num *= 2f; //This is a factor which makes pawns with love partners less likely to do fappin/random raping/rapingCP/bestiality/necro.
}
else if (pawn.gender == Gender.Male)
{
num /= 1.25f; //This accounts for single men
}
return num / GenMath.FlatHill(0.0001f, 8f, 13f, 28f, 50f, 0.15f, pawn.ageTracker.AgeBiologicalYearsFloat);//this needs to be changed
}
}
public static class MedicalRecipesUtility
{
public static bool IsCleanAndDroppable(Pawn pawn, BodyPartRecord part)
{
return IsClean(pawn, part) && part.def.spawnThingOnRemoved != null;
}
//TODO: add check if hediff are bad?
public static bool IsClean(Pawn pawn, BodyPartRecord part)
{
//in vanilla Hediff = always bad?
return !pawn.Dead && !(from x in pawn.health.hediffSet.hediffs
where (x.Part == part)
select x).Any<Hediff>();
}
public static bool IsViolationOnPawn(Pawn pawn, BodyPartRecord part, Faction billDoerFaction)
{
return pawn.Faction != billDoerFaction || HealthUtility.PartRemovalIntent(pawn, part) == BodyPartRemovalIntent.Harvest;
}
public static void RestorePartAndSpawnAllPreviousParts(Pawn pawn, BodyPartRecord part, IntVec3 pos, Map map)
{
SpawnNaturalPartIfClean(pawn, part, pos, map);
SpawnThingsFromHediffs(pawn, part, pos, map);
pawn.health.RestorePart(part, null, true);
}
// always false since rjw uses hediffs for genitals, thus its always dirty
public static Thing SpawnNaturalPartIfClean(Pawn pawn, BodyPartRecord part, IntVec3 pos, Map map)
{
if (MedicalRecipesUtility.IsCleanAndDroppable(pawn, part))
{
//normal/rimworld parts
return GenSpawn.Spawn(part.def.spawnThingOnRemoved, pos, map);
}
return null;
}
/// <summary>
/// spawn rjw parts after operation
/// </summary>
/// <param name="pawn"></param>
/// <param name="part"></param>
/// <param name="pos"></param>
/// <param name="map"></param>
public static void SpawnThingsFromHediffs(Pawn pawn, BodyPartRecord part, IntVec3 pos, Map map)
{
if (!pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).Contains(part))
{
return;
}
if (pawn.Dead)
{
return;
}
IEnumerable<Hediff> enumerable = from x in pawn.health.hediffSet.hediffs
where x.Part == part
select x;
//RJW parts and other implants?
foreach (Hediff current in enumerable)
{
if (current.def.spawnThingOnRemoved != null)
{
//Thing thing = GenSpawn.Spawn(current.def.spawnThingOnRemoved, pos, map);
//spawn thing
GenSpawn.Spawn(SexPartAdder.recipePartRemover(current), pos, map);
}
}
//spawn sub parts? not sure why would it call itself but w/e
for (int i = 0; i < part.parts.Count; i++)
{
MedicalRecipesUtility.SpawnThingsFromHediffs(pawn, part.parts[i], pos, map);
}
}
}
public class Recipe_RemoveBodyPart : Recipe_Surgery
{
public virtual bool blocked(Pawn p)
{
return false;
}
public override IEnumerable<BodyPartRecord> GetPartsToApplyOn(Pawn pawn, RecipeDef recipe)
{
if (!blocked(pawn))
{
IEnumerable<BodyPartRecord> parts = pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined);
foreach (BodyPartRecord part in parts)
{
if (pawn.health.hediffSet.HasDirectlyAddedPartFor(part))
{
yield return part;
}
if (MedicalRecipesUtility.IsCleanAndDroppable(pawn, part))
{
yield return part;
}
if (part != pawn.RaceProps.body.corePart && part.def.canSuggestAmputation && pawn.health.hediffSet.hediffs.Any((Hediff d) => !(d is Hediff_Injury) && d.def.isBad && d.Visible && d.Part == part))
{
yield return part;
}
}
}
}
private const int ViolationGoodwillImpact = -15;
public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, List<Thing> ingredients, Bill bill)
{
bool flag = MedicalRecipesUtility.IsClean(pawn, part);
bool flag2 = MedicalRecipesUtility.IsViolationOnPawn(pawn, part, Faction.OfPlayer);
if (billDoer != null)
{
if (base.CheckSurgeryFail(billDoer, pawn, ingredients, part, bill))
{
return;
}
TaleRecorder.RecordTale(TaleDefOf.DidSurgery, new object[]
{
billDoer,
pawn
});
MedicalRecipesUtility.SpawnNaturalPartIfClean(pawn, part, billDoer.Position, billDoer.Map);
MedicalRecipesUtility.SpawnThingsFromHediffs(pawn, part, billDoer.Position, billDoer.Map);
}
DamageDef surgicalCut = DamageDefOf.SurgicalCut;
float amount = 99999f;
float armorPenetration = 999f;
pawn.TakeDamage(new DamageInfo(surgicalCut, amount, armorPenetration, -1f, null, part, null, DamageInfo.SourceCategory.ThingOrUnknown, null));
if (flag)
{
if (pawn.Dead)
{
ThoughtUtility.GiveThoughtsForPawnExecuted(pawn, billDoer, PawnExecutionKind.OrganHarvesting);
}
ThoughtUtility.GiveThoughtsForPawnOrganHarvested(pawn, billDoer);
}
if (flag2 && pawn.Faction != null && billDoer != null && billDoer.Faction != null)
{
Faction faction = pawn.Faction;
Faction faction2 = billDoer.Faction;
HistoryEventDef reason = DefDatabase<HistoryEventDef>.GetNamedSilentFail("GoodwillChangedReason_RemovedBodyPart");
//string reason = "GoodwillChangedReason_RemovedBodyPart".Translate(part.LabelShort);
GlobalTargetInfo? lookTarget = pawn;
faction.TryAffectGoodwillWith(faction2, ViolationGoodwillImpact, true, true, reason, lookTarget);
}
}
public override string GetLabelWhenUsedOn(Pawn pawn, BodyPartRecord part)
{
if (pawn.RaceProps.IsMechanoid || pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(part))
{
return RecipeDefOf.RemoveBodyPart.LabelCap;
}
BodyPartRemovalIntent bodyPartRemovalIntent = HealthUtility.PartRemovalIntent(pawn, part);
if (bodyPartRemovalIntent == BodyPartRemovalIntent.Harvest)
{
return "Harvest".Translate();
}
if (bodyPartRemovalIntent != BodyPartRemovalIntent.Amputate)
{
throw new InvalidOperationException();
}
if (part.depth == BodyPartDepth.Inside)
{
return "RemoveOrgan".Translate();
}
return "Amputate".Translate();
}
}
public class Recipe_InstallOrReplaceBodyPart : Recipe_Surgery
{
public virtual bool blocked(Pawn p)
{
return false;
}
public override IEnumerable<BodyPartRecord> GetPartsToApplyOn(Pawn pawn, RecipeDef recipe)
{
if (!blocked(pawn))
{
//ModLog.Message("Recipe_InstallOrReplaceBodyPart Recipe: " + recipe.defName);
// For all parts listed in the recipe
for (int i = 0; i < recipe.appliedOnFixedBodyParts.Count; i++)
{
// Grab the recipe part
BodyPartDef part = recipe.appliedOnFixedBodyParts[i];
// For all parts on the pawn
List<BodyPartRecord> bpList = pawn.RaceProps.body.AllParts;
for (int j = 0; j < bpList.Count; j++)
{
// Grab the pawn part
BodyPartRecord record = bpList[j];
// If the recipe part and pawn part match
if (record.def == part)
{
// Grab all pawn hediffs for natural and artificial parts that are on the current pawn body part
IEnumerable<Hediff> diffs = from x in pawn.health.hediffSet.hediffs
where x.Part == record && (x is Hediff_PartBaseNatural || x is Hediff_PartBaseArtifical)
select x;
//ModLog.Message("Recipe_InstallOrReplaceBodyPart GetPartsToApplyOn: Pawn=" + pawn.Name + " Part=" + record.Label + ", diffs.Count=" + diffs.Count<Hediff>() + ", First Diff=" + diffs.First<Hediff>().def.defName + " recipe.addsHediff=" + recipe.addsHediff.defName);
// If the pawn doesn't have exactly 1 diff for that part OR the first diff found is not the one being added by the recipe
//if (diffs.Count<Hediff>() != 1 || diffs.First<Hediff>().def != recipe.addsHediff)
{
//ModLog.Message("Diff Matched. Recipe parent=" + record.parent?.Label);
// If this is the base body OR the pawn has the parent body part of the recipe part
if (record.parent == null || pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined, null, null).Contains(record.parent))
{
//ModLog.Message("Parent Found. PartOrAnyAncestorHasDirectlyAddedParts=" + pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(record) + ", HasDirectlyAddedPartFor=" + pawn.health.hediffSet.HasDirectlyAddedPartFor(record));
if (!pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(record) || pawn.health.hediffSet.HasDirectlyAddedPartFor(record))
{
//ModLog.Message("Recipe: " + recipe.defName + "Applies to: " + record.Label + " of " + pawn.Name);
yield return record;
}
}
}
}
}
}
}
}
public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, List<Thing> ingredients, Bill bill)
{
if (billDoer != null)
{
if (base.CheckSurgeryFail(billDoer, pawn, ingredients, part, bill))
{
DamageDef surgicalCut = DamageDefOf.SurgicalCut;
float amount = 99999f;
float armorPenetration = 999f;
pawn.TakeDamage(new DamageInfo(surgicalCut, amount, armorPenetration, -1f, null, part, null, DamageInfo.SourceCategory.ThingOrUnknown, null));
return;
}
TaleRecorder.RecordTale(TaleDefOf.DidSurgery, new object[]
{
billDoer,
pawn
});
MedicalRecipesUtility.RestorePartAndSpawnAllPreviousParts(pawn, part, billDoer.Position, billDoer.Map);
}
//pawn.health.AddHediff(recipe.addsHediff, part, null, null);
pawn.health.AddHediff(SexPartAdder.recipePartAdder(recipe, pawn, part, ingredients), part, null, null);
}
}
public class Recipe_AddBodyPart : Recipe_Surgery
{
public virtual bool blocked(Pawn p)
{
return false;
}
public override IEnumerable<BodyPartRecord> GetPartsToApplyOn(Pawn pawn, RecipeDef recipe)
{
if (!blocked(pawn))
{
for (int i = 0; i < recipe.appliedOnFixedBodyParts.Count; i++)
{
BodyPartDef part = recipe.appliedOnFixedBodyParts[i];
List<BodyPartRecord> bpList = pawn.RaceProps.body.AllParts;
for (int j = 0; j < bpList.Count; j++)
{
BodyPartRecord record = bpList[j];
if (record.def == part)
{
IEnumerable<Hediff> diffs = from x in pawn.health.hediffSet.hediffs
where x.Part == record && (x is Hediff_PartBaseNatural || x is Hediff_PartBaseArtifical)
select x;
// If the pawn doesn't have exactly 1 diff for that part OR the first diff found is not the one being added by the recipe
//if (diffs.Count<Hediff>() != 1 || diffs.First<Hediff>().def != recipe.addsHediff)
{
if (record.parent == null || pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined, null, null).Contains(record.parent))
{
if (!pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(record) || pawn.health.hediffSet.HasDirectlyAddedPartFor(record))
{
yield return record;
}
}
}
}
}
}
}
}
public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, List<Thing> ingredients, Bill bill)
{
if (billDoer != null)
{
if (base.CheckSurgeryFail(billDoer, pawn, ingredients, part, bill))
{
DamageDef surgicalCut = DamageDefOf.SurgicalCut;
float amount = 99999f;
float armorPenetration = 999f;
pawn.TakeDamage(new DamageInfo(surgicalCut, amount, armorPenetration, -1f, null, part, null, DamageInfo.SourceCategory.ThingOrUnknown, null));
return;
}
TaleRecorder.RecordTale(TaleDefOf.DidSurgery, new object[]
{
billDoer,
pawn
});
//pawn.health.AddHediff(recipe.addsHediff, part, null, null);
pawn.health.AddHediff(SexPartAdder.recipePartAdder(recipe, pawn, part, ingredients), part, null, null);
}
}
}
public class Recipe_RemovePart : Recipe_Surgery
{
public virtual bool blocked(Pawn p)
{
return false;
}
public override IEnumerable<BodyPartRecord> GetPartsToApplyOn(Pawn pawn, RecipeDef recipe)
{
if (!blocked(pawn))
{
for (int i = 0; i < recipe.appliedOnFixedBodyParts.Count; i++)
{
BodyPartDef part = recipe.appliedOnFixedBodyParts[i];
List<BodyPartRecord> bpList = pawn.RaceProps.body.AllParts;
for (int j = 0; j < bpList.Count; j++)
{
BodyPartRecord record = bpList[j];
if (record.def == part)
{
IEnumerable<Hediff> diffs = from x in pawn.health.hediffSet.hediffs
where x.Part == record && (x is Hediff_PartBaseNatural || x is Hediff_PartBaseArtifical)
select x;
// If the pawn doesn't have exactly 1 diff for that part OR the first diff found is not the one being added by the recipe
//if (diffs.Count<Hediff>() != 1 || diffs.First<Hediff>().def != recipe.addsHediff)
{
if (record.parent == null || pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined, null, null).Contains(record.parent))
{
if (!pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(record) || pawn.health.hediffSet.HasDirectlyAddedPartFor(record))
{
yield return record;
}
}
}
}
}
}
}
}
public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, List<Thing> ingredients, Bill bill)
{
if (billDoer != null)
{
if (base.CheckSurgeryFail(billDoer, pawn, ingredients, part, bill))
{
DamageDef surgicalCut = DamageDefOf.SurgicalCut;
float amount = 99999f;
float armorPenetration = 999f;
pawn.TakeDamage(new DamageInfo(surgicalCut, amount, armorPenetration, -1f, null, part, null, DamageInfo.SourceCategory.ThingOrUnknown, null));
return;
}
TaleRecorder.RecordTale(TaleDefOf.DidSurgery, new object[]
{
billDoer,
pawn
});
//pawn.health.AddHediff(recipe.addsHediff, part, null, null);
pawn.health.AddHediff(SexPartAdder.recipePartAdder(recipe, pawn, part, ingredients), part, null, null);
}
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/CORE_EXPOSED/CORE_EXPOSED.cs
|
C#
|
mit
| 16,075
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using UnityEngine;
using Verse;
using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using RimWorld.Planet;
using Verse;
namespace rjw_CORE_EXPOSED
{
[StaticConstructorOnStartup]
public static class rjwHealthCardUtility
{
public static Vector2 scrollPosition = Vector2.zero;
public static float scrollViewHeight = 0f;
public static bool highlight = true;
public static bool onOperationTab = false;
public static Vector2 billsScrollPosition = Vector2.zero;
public static float billsScrollHeight = 1000f;
public static bool showAllHediffs = false;
public static bool showHediffsDebugInfo = false;
public const float TopPadding = 20f;
public const float ThoughtLevelHeight = 25f;
public const float ThoughtLevelSpacing = 4f;
public const float IconSize = 20f;
public static readonly Color HighlightColor = new Color(0.5f, 0.5f, 0.5f, 1f);
public static readonly Color StaticHighlightColor = new Color(0.75f, 0.75f, 0.85f, 1f);
public static readonly Color VeryPoorColor = new Color(0.4f, 0.4f, 0.4f);
public static readonly Color PoorColor = new Color(0.55f, 0.55f, 0.55f);
public static readonly Color WeakenedColor = new Color(0.7f, 0.7f, 0.7f);
public static readonly Color EnhancedColor = new Color(0.5f, 0.5f, 0.9f);
public static readonly Color MediumPainColor = new Color(0.9f, 0.9f, 0f);
public static readonly Color SeverePainColor = new Color(0.9f, 0.5f, 0f);
public static readonly Texture2D BleedingIcon = ContentFinder<Texture2D>.Get("UI/Icons/Medical/Bleeding", true);
public static List<ThingDef> tmpMedicineBestToWorst = new List<ThingDef>();
public static void DrawPawnHealthCard(Rect outRect, Pawn pawn, bool allowOperations, bool showBloodLoss, Thing thingForMedBills)
{
if (pawn.Dead && allowOperations)
{
Log.Error("Called DrawPawnHealthCard with a dead pawn and allowOperations=true. Operations are disallowed on corpses.", false);
allowOperations = false;
}
outRect = outRect.Rounded();
Rect rect = new Rect(outRect.x, outRect.y, outRect.width * 0.375f, outRect.height).Rounded();
Rect rect2 = new Rect(rect.xMax, outRect.y, outRect.width - rect.width, outRect.height);
rect.yMin += 11f;
rjwHealthCardUtility.DrawHealthSummary(rect, pawn, allowOperations, thingForMedBills);
rjwHealthCardUtility.DrawHediffListing(rect2.ContractedBy(10f), pawn, showBloodLoss);
}
public static void DrawHealthSummary(Rect rect, Pawn pawn, bool allowOperations, Thing thingForMedBills)
{
GUI.color = Color.white;
if (!allowOperations)
{
rjwHealthCardUtility.onOperationTab = false;
}
Widgets.DrawMenuSection(rect);
List<TabRecord> list = new List<TabRecord>();
list.Add(new TabRecord("HealthOverview".Translate(), delegate
{
rjwHealthCardUtility.onOperationTab = false;
}, !rjwHealthCardUtility.onOperationTab));
if (allowOperations)
{
string label = (!pawn.RaceProps.IsMechanoid) ? "MedicalOperationsShort".Translate(pawn.BillStack.Count) : "MedicalOperationsMechanoidsShort".Translate(pawn.BillStack.Count);
list.Add(new TabRecord(label, delegate
{
rjwHealthCardUtility.onOperationTab = true;
}, rjwHealthCardUtility.onOperationTab));
}
TabDrawer.DrawTabs(rect, list, 200f);
rect = rect.ContractedBy(9f);
GUI.BeginGroup(rect);
float curY = 0f;
Text.Font = GameFont.Medium;
GUI.color = Color.white;
Text.Anchor = TextAnchor.UpperCenter;
if (rjwHealthCardUtility.onOperationTab)
{
PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.MedicalOperations, KnowledgeAmount.FrameDisplayed);
curY = rjwHealthCardUtility.DrawMedOperationsTab(rect, pawn, thingForMedBills, curY);
}
else
{
curY = rjwHealthCardUtility.DrawOverviewTab(rect, pawn, curY);
}
Text.Font = GameFont.Small;
GUI.color = Color.white;
Text.Anchor = TextAnchor.UpperLeft;
GUI.EndGroup();
}
public static void DrawHediffListing(Rect rect, Pawn pawn, bool showBloodLoss)
{
GUI.color = Color.white;
if (Prefs.DevMode && Current.ProgramState == ProgramState.Playing)
{
rjwHealthCardUtility.DoDebugOptions(rect, pawn);
}
GUI.BeginGroup(rect);
float lineHeight = Text.LineHeight;
Rect outRect = new Rect(0f, 0f, rect.width, rect.height - lineHeight);
Rect viewRect = new Rect(0f, 0f, rect.width - 16f, rjwHealthCardUtility.scrollViewHeight);
Rect rect2 = rect;
if (viewRect.height > outRect.height)
{
rect2.width -= 16f;
}
Widgets.BeginScrollView(outRect, ref rjwHealthCardUtility.scrollPosition, viewRect, true);
GUI.color = Color.white;
float num = 0f;
rjwHealthCardUtility.highlight = true;
bool flag = false;
foreach (IGrouping<BodyPartRecord, Hediff> current in rjwHealthCardUtility.VisibleHediffGroupsInOrder(pawn, showBloodLoss))
{
flag = true;
rjwHealthCardUtility.DrawHediffRow(rect2, pawn, current, ref num);
}
if (!flag)
{
Widgets.NoneLabelCenteredVertically(new Rect(0f, 0f, viewRect.width, outRect.height), "(" + "NoHealthConditions".Translate() + ")");
num = outRect.height - 1f;
}
if (Event.current.type == EventType.Layout)
{
rjwHealthCardUtility.scrollViewHeight = num;
}
Widgets.EndScrollView();
float bleedRateTotal = pawn.health.hediffSet.BleedRateTotal;
if (bleedRateTotal > 0.01f)
{
Rect rect3 = new Rect(0f, rect.height - lineHeight, rect.width, lineHeight);
string text = string.Concat(new string[]
{
"BleedingRate".Translate(),
": ",
bleedRateTotal.ToStringPercent(),
"/",
"LetterDay".Translate()
});
int num2 = HealthUtility.TicksUntilDeathDueToBloodLoss(pawn);
if (num2 < 60000)
{
text = text + " (" + "TimeToDeath".Translate(num2.ToStringTicksToPeriod()) + ")";
}
else
{
text = text + " (" + "WontBleedOutSoon".Translate() + ")";
}
Widgets.Label(rect3, text);
}
GUI.EndGroup();
GUI.color = Color.white;
}
[DebuggerHidden]
public static IEnumerable<IGrouping<BodyPartRecord, Hediff>> VisibleHediffGroupsInOrder(Pawn pawn, bool showBloodLoss)
{
foreach (IGrouping<BodyPartRecord, Hediff> group in from x in rjwHealthCardUtility.VisibleHediffs(pawn, showBloodLoss)
group x by x.Part into x
orderby rjwHealthCardUtility.GetListPriority(x.First<Hediff>().Part) descending
select x)
{
yield return group;
}
}
public static float GetListPriority(BodyPartRecord rec)
{
if (rec == null)
{
return 9999999f;
}
return (float)((int)rec.height * 10000) + rec.coverageAbsWithChildren;
}
[DebuggerHidden]
public static IEnumerable<Hediff> VisibleHediffs(Pawn pawn, bool showBloodLoss)
{
if (!rjwHealthCardUtility.showAllHediffs)
{
List<Hediff_MissingPart> mpca = pawn.health.hediffSet.GetMissingPartsCommonAncestors();
for (int i = 0; i < mpca.Count; i++)
{
yield return mpca[i];
}
IEnumerable<Hediff> visibleDiffs = from d in pawn.health.hediffSet.hediffs
where !(d is Hediff_MissingPart) && d.Visible && (showBloodLoss || d.def != HediffDefOf.BloodLoss)
select d;
foreach (Hediff diff in visibleDiffs)
{
yield return diff;
}
}
else
{
foreach (Hediff diff2 in pawn.health.hediffSet.hediffs)
{
yield return diff2;
}
}
}
public static float DrawMedOperationsTab(Rect leftRect, Pawn pawn, Thing thingForMedBills, float curY)
{
curY += 2f;
Func<List<FloatMenuOption>> recipeOptionsMaker = delegate
{
List<FloatMenuOption> list = new List<FloatMenuOption>();
foreach (RecipeDef current in thingForMedBills.def.AllRecipes)
{
if (current.AvailableNow)
{
IEnumerable<ThingDef> enumerable = current.PotentiallyMissingIngredients(null, thingForMedBills.Map);
if (!enumerable.Any((ThingDef x) => x.isTechHediff))
{
if (!enumerable.Any((ThingDef x) => x.IsDrug))
{
if (!enumerable.Any<ThingDef>() || !current.dontShowIfAnyIngredientMissing)
{
if (current.targetsBodyPart)
{
foreach (BodyPartRecord current2 in current.Worker.GetPartsToApplyOn(pawn, current))
{
list.Add(rjwHealthCardUtility.GenerateSurgeryOption(pawn, thingForMedBills, current, enumerable, current2));
}
}
else
{
list.Add(rjwHealthCardUtility.GenerateSurgeryOption(pawn, thingForMedBills, current, enumerable, null));
}
}
}
}
}
}
return list;
};
Rect rect = new Rect(leftRect.x - 9f, curY, leftRect.width, leftRect.height - curY - 20f);
((IBillGiver)thingForMedBills).BillStack.DoListing(rect, recipeOptionsMaker, ref rjwHealthCardUtility.billsScrollPosition, ref rjwHealthCardUtility.billsScrollHeight);
return curY;
}
public static FloatMenuOption GenerateSurgeryOption(Pawn pawn, Thing thingForMedBills, RecipeDef recipe, IEnumerable<ThingDef> missingIngredients, BodyPartRecord part = null)
{
string text = recipe.Worker.GetLabelWhenUsedOn(pawn, part).CapitalizeFirst();
if (part != null && !recipe.hideBodyPartNames)
{
text = text + " (" + part.Label + ")";
}
FloatMenuOption floatMenuOption;
if (missingIngredients.Any<ThingDef>())
{
text += " (";
bool flag = true;
foreach (ThingDef current in missingIngredients)
{
if (!flag)
{
text += ", ";
}
flag = false;
text += "MissingMedicalBillIngredient".Translate(current.label);
}
text += ")";
floatMenuOption = new FloatMenuOption(text, null, MenuOptionPriority.Default, null, null, 0f, null, null);
}
else
{
Action action = delegate
{
Pawn pawn2 = thingForMedBills as Pawn;
if (pawn2 == null)
{
return;
}
Bill_Medical bill_Medical = new Bill_Medical(recipe);
pawn2.BillStack.AddBill(bill_Medical);
bill_Medical.Part = part;
if (recipe.conceptLearned != null)
{
PlayerKnowledgeDatabase.KnowledgeDemonstrated(recipe.conceptLearned, KnowledgeAmount.Total);
}
Map map = thingForMedBills.Map;
if (!map.mapPawns.FreeColonists.Any((Pawn col) => recipe.PawnSatisfiesSkillRequirements(col)))
{
Bill.CreateNoPawnsWithSkillDialog(recipe);
}
if (!pawn2.InBed() && pawn2.RaceProps.IsFlesh)
{
if (pawn2.RaceProps.Humanlike)
{
if (!map.listerBuildings.allBuildingsColonist.Any((Building x) => x is Building_Bed && RestUtility.CanUseBedEver(pawn, x.def) && ((Building_Bed)x).Medical))
{
Messages.Message("MessageNoMedicalBeds".Translate(), pawn2, MessageTypeDefOf.CautionInput, false);
}
}
else if (!map.listerBuildings.allBuildingsColonist.Any((Building x) => x is Building_Bed && RestUtility.CanUseBedEver(pawn, x.def)))
{
Messages.Message("MessageNoAnimalBeds".Translate(), pawn2, MessageTypeDefOf.CautionInput, false);
}
}
if (pawn2.Faction != null && !pawn2.Faction.def.hidden && !pawn2.Faction.HostileTo(Faction.OfPlayer) && recipe.Worker.IsViolationOnPawn(pawn2, part, Faction.OfPlayer))
{
Messages.Message("MessageMedicalOperationWillAngerFaction".Translate(pawn2.Faction), pawn2, MessageTypeDefOf.CautionInput, false);
}
ThingDef minRequiredMedicine = rjwHealthCardUtility.GetMinRequiredMedicine(recipe);
if (minRequiredMedicine != null && pawn2.playerSettings != null && !pawn2.playerSettings.medCare.AllowsMedicine(minRequiredMedicine))
{
Messages.Message("MessageTooLowMedCare".Translate(minRequiredMedicine.label, pawn2.LabelShort, pawn2.playerSettings.medCare.GetLabel(), pawn2.Named("PAWN")), pawn2, MessageTypeDefOf.CautionInput, false);
}
};
floatMenuOption = new FloatMenuOption(text, action, MenuOptionPriority.Default, null, null, 0f, null, null);
}
floatMenuOption.extraPartWidth = 29f;
floatMenuOption.extraPartOnGUI = ((Rect rect) => Widgets.InfoCardButton(rect.x + 5f, rect.y + (rect.height - 24f) / 2f, recipe));
return floatMenuOption;
}
public static ThingDef GetMinRequiredMedicine(RecipeDef recipe)
{
rjwHealthCardUtility.tmpMedicineBestToWorst.Clear();
List<ThingDef> allDefsListForReading = DefDatabase<ThingDef>.AllDefsListForReading;
for (int i = 0; i < allDefsListForReading.Count; i++)
{
if (allDefsListForReading[i].IsMedicine)
{
rjwHealthCardUtility.tmpMedicineBestToWorst.Add(allDefsListForReading[i]);
}
}
rjwHealthCardUtility.tmpMedicineBestToWorst.SortByDescending((ThingDef x) => x.GetStatValueAbstract(StatDefOf.MedicalPotency, null));
ThingDef thingDef = null;
for (int j = 0; j < recipe.ingredients.Count; j++)
{
ThingDef thingDef2 = null;
for (int k = 0; k < rjwHealthCardUtility.tmpMedicineBestToWorst.Count; k++)
{
if (recipe.ingredients[j].filter.Allows(rjwHealthCardUtility.tmpMedicineBestToWorst[k]))
{
thingDef2 = rjwHealthCardUtility.tmpMedicineBestToWorst[k];
}
}
if (thingDef2 != null && (thingDef == null || thingDef2.GetStatValueAbstract(StatDefOf.MedicalPotency, null) > thingDef.GetStatValueAbstract(StatDefOf.MedicalPotency, null)))
{
thingDef = thingDef2;
}
}
rjwHealthCardUtility.tmpMedicineBestToWorst.Clear();
return thingDef;
}
public static float DrawOverviewTab(Rect leftRect, Pawn pawn, float curY)
{
curY += 4f;
Text.Font = GameFont.Tiny;
Text.Anchor = TextAnchor.UpperLeft;
GUI.color = new Color(0.9f, 0.9f, 0.9f);
string text = string.Empty;
if (pawn.gender != Gender.None)
{
text = pawn.GetGenderLabel() + " ";
}
text = text + pawn.def.label + ", " + "AgeIndicator".Translate(pawn.ageTracker.AgeNumberString);
Rect rect = new Rect(0f, curY, leftRect.width, 34f);
Widgets.Label(rect, text.CapitalizeFirst());
TooltipHandler.TipRegion(rect, () => pawn.ageTracker.AgeTooltipString, 73412);
if (Mouse.IsOver(rect))
{
Widgets.DrawHighlight(rect);
}
GUI.color = Color.white;
curY += 34f;
if (pawn.foodRestriction != null && pawn.foodRestriction.Configurable)
{
Rect rect2 = new Rect(0f, curY, leftRect.width * 0.42f, 23f);
Text.Anchor = TextAnchor.MiddleLeft;
Widgets.Label(rect2, "FoodRestriction".Translate());
GenUI.ResetLabelAlign();
Rect rect3 = new Rect(rect2.width, curY, leftRect.width - rect2.width, 23f);
if (Widgets.ButtonText(rect3, pawn.foodRestriction.CurrentFoodRestriction.label, true, false, true))
{
List<FloatMenuOption> list = new List<FloatMenuOption>();
List<FoodRestriction> allFoodRestrictions = Current.Game.foodRestrictionDatabase.AllFoodRestrictions;
for (int i = 0; i < allFoodRestrictions.Count; i++)
{
FoodRestriction localRestriction = allFoodRestrictions[i];
list.Add(new FloatMenuOption(localRestriction.label, delegate
{
pawn.foodRestriction.CurrentFoodRestriction = localRestriction;
}, MenuOptionPriority.Default, null, null, 0f, null, null));
}
list.Add(new FloatMenuOption("ManageFoodRestrictions".Translate(), delegate
{
Find.WindowStack.Add(new Dialog_ManageFoodRestrictions(null));
}, MenuOptionPriority.Default, null, null, 0f, null, null));
Find.WindowStack.Add(new FloatMenu(list));
}
curY += 23f;
}
if (pawn.IsColonist && !pawn.Dead)
{
bool selfTend = pawn.playerSettings.selfTend;
Rect rect4 = new Rect(0f, curY, leftRect.width, 24f);
Widgets.CheckboxLabeled(rect4, "SelfTend".Translate(), ref pawn.playerSettings.selfTend, false, null, null, false);
if (pawn.playerSettings.selfTend && !selfTend)
{
if (pawn.story.WorkTypeIsDisabled(WorkTypeDefOf.Doctor))
{
pawn.playerSettings.selfTend = false;
Messages.Message("MessageCannotSelfTendEver".Translate(pawn.LabelShort, pawn), MessageTypeDefOf.RejectInput, false);
}
else if (pawn.workSettings.GetPriority(WorkTypeDefOf.Doctor) == 0)
{
Messages.Message("MessageSelfTendUnsatisfied".Translate(pawn.LabelShort, pawn), MessageTypeDefOf.CautionInput, false);
}
}
TooltipHandler.TipRegion(rect4, "SelfTendTip".Translate(Faction.OfPlayer.def.pawnsPlural, 0.7f.ToStringPercent()).CapitalizeFirst());
curY += 28f;
}
if (pawn.playerSettings != null && !pawn.Dead && Current.ProgramState == ProgramState.Playing)
{
Rect rect5 = new Rect(0f, curY, 140f, 28f);
MedicalCareUtility.MedicalCareSetter(rect5, ref pawn.playerSettings.medCare);
if (Widgets.ButtonText(new Rect(leftRect.width - 70f, curY, 70f, 28f), "MedGroupDefaults".Translate(), true, false, true))
{
Find.WindowStack.Add(new Dialog_MedicalDefaults());
}
curY += 32f;
}
Text.Font = GameFont.Small;
if (pawn.def.race.IsFlesh)
{
Pair<string, Color> painLabel = rjwHealthCardUtility.GetPainLabel(pawn);
string painTip = rjwHealthCardUtility.GetPainTip(pawn);
curY = rjwHealthCardUtility.DrawLeftRow(leftRect, curY, "PainLevel".Translate(), painLabel.First, painLabel.Second, painTip);
}
if (!pawn.Dead)
{
IEnumerable<PawnCapacityDef> source;
if (pawn.def.race.Humanlike)
{
source = from x in DefDatabase<PawnCapacityDef>.AllDefs
where x.showOnHumanlikes
select x;
}
else if (pawn.def.race.Animal)
{
source = from x in DefDatabase<PawnCapacityDef>.AllDefs
where x.showOnAnimals
select x;
}
else
{
source = from x in DefDatabase<PawnCapacityDef>.AllDefs
where x.showOnMechanoids
select x;
}
foreach (PawnCapacityDef current in from act in source
orderby act.listOrder
select act)
{
if (PawnCapacityUtility.BodyCanEverDoCapacity(pawn.RaceProps.body, current))
{
PawnCapacityDef activityLocal = current;
Pair<string, Color> efficiencyLabel = rjwHealthCardUtility.GetEfficiencyLabel(pawn, current);
Func<string> textGetter = () => (!pawn.Dead) ? rjwHealthCardUtility.GetPawnCapacityTip(pawn, activityLocal) : string.Empty;
curY = rjwHealthCardUtility.DrawLeftRow(leftRect, curY, current.GetLabelFor(pawn.RaceProps.IsFlesh, pawn.RaceProps.Humanlike).CapitalizeFirst(), efficiencyLabel.First, efficiencyLabel.Second, new TipSignal(textGetter, pawn.thingIDNumber ^ (int)current.index));
}
}
}
return curY;
}
public static float DrawLeftRow(Rect leftRect, float curY, string leftLabel, string rightLabel, Color rightLabelColor, TipSignal tipSignal)
{
Rect rect = new Rect(0f, curY, leftRect.width, 20f);
if (Mouse.IsOver(rect))
{
GUI.color = rjwHealthCardUtility.HighlightColor;
GUI.DrawTexture(rect, TexUI.HighlightTex);
}
GUI.color = Color.white;
Widgets.Label(new Rect(0f, curY, leftRect.width * 0.65f, 30f), leftLabel);
GUI.color = rightLabelColor;
Widgets.Label(new Rect(leftRect.width * 0.65f, curY, leftRect.width * 0.35f, 30f), rightLabel);
TooltipHandler.TipRegion(new Rect(0f, curY, leftRect.width, 20f), tipSignal);
curY += 20f;
return curY;
}
public static void DrawHediffRow(Rect rect, Pawn pawn, IEnumerable<Hediff> diffs, ref float curY)
{
float num = rect.width * 0.375f;
float width = rect.width - num - 20f;
BodyPartRecord part = diffs.First<Hediff>().Part;
float a;
if (part == null)
{
a = Text.CalcHeight("WholeBody".Translate(), num);
}
else
{
a = Text.CalcHeight(part.LabelCap, num);
}
float b = 0f;
float num2 = curY;
float num3 = 0f;
foreach (IGrouping<int, Hediff> current in from x in diffs
group x by x.UIGroupKey)
{
int num4 = current.Count<Hediff>();
string text = current.First<Hediff>().LabelCap;
if (num4 != 1)
{
text = text + " x" + num4.ToString();
}
num3 += Text.CalcHeight(text, width);
}
b = num3;
Rect rect2 = new Rect(0f, curY, rect.width, Mathf.Max(a, b));
rjwHealthCardUtility.DoRightRowHighlight(rect2);
if (part != null)
{
GUI.color = HealthUtility.GetPartConditionLabel(pawn, part).Second;
Widgets.Label(new Rect(0f, curY, num, 100f), part.LabelCap);
}
else
{
GUI.color = HealthUtility.DarkRedColor;
Widgets.Label(new Rect(0f, curY, num, 100f), "WholeBody".Translate());
}
GUI.color = Color.white;
foreach (IGrouping<int, Hediff> current2 in from x in diffs
group x by x.UIGroupKey)
{
int num5 = 0;
Hediff hediff = null;
Texture2D texture2D = null;
TextureAndColor textureAndColor = null;
float num6 = 0f;
foreach (Hediff current3 in current2)
{
if (num5 == 0)
{
hediff = current3;
}
textureAndColor = current3.StateIcon;
if (current3.Bleeding)
{
texture2D = rjwHealthCardUtility.BleedingIcon;
}
num6 += current3.BleedRate;
num5++;
}
string text2 = hediff.LabelCap;
if (num5 != 1)
{
text2 = text2 + " x" + num5.ToStringCached();
}
GUI.color = hediff.LabelColor;
float num7 = Text.CalcHeight(text2, width);
Rect rect3 = new Rect(num, curY, width, num7);
Widgets.Label(rect3, text2);
GUI.color = Color.white;
Rect rect4 = new Rect(rect2.xMax - 20f, curY, 20f, 20f);
if (texture2D)
{
Rect position = rect4.ContractedBy(GenMath.LerpDouble(0f, 0.6f, 5f, 0f, Mathf.Min(num6, 1f)));
GUI.DrawTexture(position, texture2D);
rect4.x -= rect4.width;
}
if (textureAndColor.HasValue)
{
GUI.color = textureAndColor.Color;
GUI.DrawTexture(rect4, textureAndColor.Texture);
GUI.color = Color.white;
rect4.x -= rect4.width;
}
curY += num7;
}
GUI.color = Color.white;
curY = num2 + Mathf.Max(a, b);
if (Widgets.ButtonInvisible(rect2, false))
{
rjwHealthCardUtility.EntryClicked(diffs, pawn);
}
TooltipHandler.TipRegion(rect2, new TipSignal(() => rjwHealthCardUtility.GetTooltip(diffs, pawn, part), (int)curY + 7857));
}
public static string GetPainTip(Pawn pawn)
{
return "PainLevel".Translate() + ": " + (pawn.health.hediffSet.PainTotal * 100f).ToString("F0") + "%";
}
public static string GetPawnCapacityTip(Pawn pawn, PawnCapacityDef capacity)
{
List<PawnCapacityUtility.CapacityImpactor> list = new List<PawnCapacityUtility.CapacityImpactor>();
float num = PawnCapacityUtility.CalculateCapacityLevel(pawn.health.hediffSet, capacity, list);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendLine(capacity.LabelCap + ": " + (num * 100f).ToString("F0") + "%");
if (list.Count > 0)
{
stringBuilder.AppendLine();
stringBuilder.AppendLine("AffectedBy".Translate());
for (int i = 0; i < list.Count; i++)
{
if (list[i] is PawnCapacityUtility.CapacityImpactorHediff)
{
stringBuilder.AppendLine(string.Format(" {0}", list[i].Readable(pawn)));
}
}
for (int j = 0; j < list.Count; j++)
{
if (list[j] is PawnCapacityUtility.CapacityImpactorBodyPartHealth)
{
stringBuilder.AppendLine(string.Format(" {0}", list[j].Readable(pawn)));
}
}
for (int k = 0; k < list.Count; k++)
{
if (list[k] is PawnCapacityUtility.CapacityImpactorCapacity)
{
stringBuilder.AppendLine(string.Format(" {0}", list[k].Readable(pawn)));
}
}
for (int l = 0; l < list.Count; l++)
{
if (list[l] is PawnCapacityUtility.CapacityImpactorPain)
{
stringBuilder.AppendLine(string.Format(" {0}", list[l].Readable(pawn)));
}
}
}
return stringBuilder.ToString();
}
public static string GetTooltip(IEnumerable<Hediff> diffs, Pawn pawn, BodyPartRecord part)
{
StringBuilder stringBuilder = new StringBuilder();
if (part != null)
{
stringBuilder.Append(part.LabelCap + ": ");
stringBuilder.AppendLine(" " + pawn.health.hediffSet.GetPartHealth(part).ToString() + " / " + part.def.GetMaxHealth(pawn).ToString());
float num = PawnCapacityUtility.CalculatePartEfficiency(pawn.health.hediffSet, part, false, null);
if (num != 1f)
{
stringBuilder.AppendLine("Efficiency".Translate() + ": " + num.ToStringPercent());
}
}
else
{
stringBuilder.AppendLine("WholeBody".Translate());
}
stringBuilder.AppendLine("------------------");
foreach (IGrouping<int, Hediff> current in from x in diffs
group x by x.UIGroupKey)
{
foreach (Hediff current2 in current)
{
string severityLabel = current2.SeverityLabel;
bool flag = rjwHealthCardUtility.showHediffsDebugInfo && !current2.DebugString().NullOrEmpty();
if (!current2.Label.NullOrEmpty() || !severityLabel.NullOrEmpty() || !current2.CapMods.NullOrEmpty<PawnCapacityModifier>() || flag)
{
stringBuilder.Append(current2.LabelCap);
if (!severityLabel.NullOrEmpty())
{
stringBuilder.Append(": " + severityLabel);
}
stringBuilder.AppendLine();
string tipStringExtra = current2.TipStringExtra;
if (!tipStringExtra.NullOrEmpty())
{
stringBuilder.AppendLine(tipStringExtra.TrimEndNewlines().Indented(" "));
}
if (flag)
{
stringBuilder.AppendLine(current2.DebugString().TrimEndNewlines());
}
}
}
}
string s;
LogEntry logEntry;
if (rjwHealthCardUtility.GetCombatLogInfo(diffs, out s, out logEntry))
{
stringBuilder.AppendLine();
stringBuilder.AppendLine("Cause:");
stringBuilder.AppendLine(s.Indented(" "));
}
return stringBuilder.ToString().TrimEnd(new char[0]);
}
public static void EntryClicked(IEnumerable<Hediff> diffs, Pawn pawn)
{
LogEntry combatLogEntry;
string text;
if (!rjwHealthCardUtility.GetCombatLogInfo(diffs, out text, out combatLogEntry) || combatLogEntry == null)
{
return;
}
if (!Find.BattleLog.Battles.Any((Battle b) => b.Concerns(pawn) && b.Entries.Any((LogEntry e) => e == combatLogEntry)))
{
return;
}
ITab_Pawn_Log tab_Pawn_Log = InspectPaneUtility.OpenTab(typeof(ITab_Pawn_Log)) as ITab_Pawn_Log;
if (tab_Pawn_Log == null)
{
return;
}
tab_Pawn_Log.SeekTo(combatLogEntry);
tab_Pawn_Log.Highlight(combatLogEntry);
}
public static bool GetCombatLogInfo(IEnumerable<Hediff> diffs, out string combatLogText, out LogEntry combatLogEntry)
{
combatLogText = null;
combatLogEntry = null;
foreach (Hediff current in diffs)
{
if ((current.combatLogEntry != null && current.combatLogEntry.Target != null) || (combatLogText.NullOrEmpty() && !current.combatLogText.NullOrEmpty()))
{
combatLogEntry = ((current.combatLogEntry == null) ? null : current.combatLogEntry.Target);
combatLogText = current.combatLogText;
}
if (combatLogEntry != null)
{
return true;
}
}
return false;
}
public static void DoRightRowHighlight(Rect rowRect)
{
if (rjwHealthCardUtility.highlight)
{
GUI.color = rjwHealthCardUtility.StaticHighlightColor;
GUI.DrawTexture(rowRect, TexUI.HighlightTex);
}
rjwHealthCardUtility.highlight = !rjwHealthCardUtility.highlight;
if (Mouse.IsOver(rowRect))
{
GUI.color = rjwHealthCardUtility.HighlightColor;
GUI.DrawTexture(rowRect, TexUI.HighlightTex);
}
}
public static void DoDebugOptions(Rect rightRect, Pawn pawn)
{
Widgets.CheckboxLabeled(new Rect(rightRect.x, rightRect.y - 25f, 110f, 30f), "Dev: AllDiffs", ref rjwHealthCardUtility.showAllHediffs, false, null, null, false);
Widgets.CheckboxLabeled(new Rect(rightRect.x + 115f, rightRect.y - 25f, 120f, 30f), "DiffsDebugInfo", ref rjwHealthCardUtility.showHediffsDebugInfo, false, null, null, false);
if (Widgets.ButtonText(new Rect(rightRect.x + 240f, rightRect.y - 27f, 115f, 25f), "Debug info", true, false, true))
{
List<FloatMenuOption> list = new List<FloatMenuOption>();
list.Add(new FloatMenuOption("Parts hit chance (this part or any child node)", delegate
{
StringBuilder stringBuilder = new StringBuilder();
foreach (BodyPartRecord current in from x in pawn.RaceProps.body.AllParts
orderby x.coverageAbsWithChildren descending
select x)
{
stringBuilder.AppendLine(current.LabelCap + " " + current.coverageAbsWithChildren.ToStringPercent());
}
Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false, null, null));
}, MenuOptionPriority.Default, null, null, 0f, null, null));
list.Add(new FloatMenuOption("Parts hit chance (exactly this part)", delegate
{
StringBuilder stringBuilder = new StringBuilder();
float num = 0f;
foreach (BodyPartRecord current in from x in pawn.RaceProps.body.AllParts
orderby x.coverageAbs descending
select x)
{
stringBuilder.AppendLine(current.LabelCap + " " + current.coverageAbs.ToStringPercent());
num += current.coverageAbs;
}
stringBuilder.AppendLine();
stringBuilder.AppendLine("Total " + num.ToStringPercent());
Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false, null, null));
}, MenuOptionPriority.Default, null, null, 0f, null, null));
list.Add(new FloatMenuOption("Per-part efficiency", delegate
{
StringBuilder stringBuilder = new StringBuilder();
foreach (BodyPartRecord current in pawn.RaceProps.body.AllParts)
{
stringBuilder.AppendLine(current.LabelCap + " " + PawnCapacityUtility.CalculatePartEfficiency(pawn.health.hediffSet, current, false, null).ToStringPercent());
}
Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false, null, null));
}, MenuOptionPriority.Default, null, null, 0f, null, null));
list.Add(new FloatMenuOption("BodyPartGroup efficiency (of only natural parts)", delegate
{
StringBuilder stringBuilder = new StringBuilder();
foreach (BodyPartGroupDef current in from x in DefDatabase<BodyPartGroupDef>.AllDefs
where pawn.RaceProps.body.AllParts.Any((BodyPartRecord y) => y.groups.Contains(x))
select x)
{
stringBuilder.AppendLine(current.LabelCap + " " + PawnCapacityUtility.CalculateNaturalPartsAverageEfficiency(pawn.health.hediffSet, current).ToStringPercent());
}
Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false, null, null));
}, MenuOptionPriority.Default, null, null, 0f, null, null));
list.Add(new FloatMenuOption("IsSolid", delegate
{
StringBuilder stringBuilder = new StringBuilder();
foreach (BodyPartRecord current in pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined, null, null))
{
stringBuilder.AppendLine(current.LabelCap + " " + current.def.IsSolid(current, pawn.health.hediffSet.hediffs));
}
Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false, null, null));
}, MenuOptionPriority.Default, null, null, 0f, null, null));
list.Add(new FloatMenuOption("IsSkinCovered", delegate
{
StringBuilder stringBuilder = new StringBuilder();
foreach (BodyPartRecord current in pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined, null, null))
{
stringBuilder.AppendLine(current.LabelCap + " " + current.def.IsSkinCovered(current, pawn.health.hediffSet));
}
Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false, null, null));
}, MenuOptionPriority.Default, null, null, 0f, null, null));
list.Add(new FloatMenuOption("does have added parts", delegate
{
StringBuilder stringBuilder = new StringBuilder();
foreach (BodyPartRecord current in pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined, null, null))
{
stringBuilder.AppendLine(current.LabelCap + " " + pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(current));
}
Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false, null, null));
}, MenuOptionPriority.Default, null, null, 0f, null, null));
list.Add(new FloatMenuOption("GetNotMissingParts", delegate
{
StringBuilder stringBuilder = new StringBuilder();
foreach (BodyPartRecord current in pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined, null, null))
{
stringBuilder.AppendLine(current.LabelCap);
}
Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false, null, null));
}, MenuOptionPriority.Default, null, null, 0f, null, null));
list.Add(new FloatMenuOption("GetCoverageOfNotMissingNaturalParts", delegate
{
StringBuilder stringBuilder = new StringBuilder();
foreach (BodyPartRecord current in from x in pawn.RaceProps.body.AllParts
orderby pawn.health.hediffSet.GetCoverageOfNotMissingNaturalParts(x) descending
select x)
{
stringBuilder.AppendLine(current.LabelCap + ": " + pawn.health.hediffSet.GetCoverageOfNotMissingNaturalParts(current).ToStringPercent());
}
Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false, null, null));
}, MenuOptionPriority.Default, null, null, 0f, null, null));
list.Add(new FloatMenuOption("parts nutrition (assuming adult)", delegate
{
StringBuilder stringBuilder = new StringBuilder();
float totalCorpseNutrition = StatDefOf.Nutrition.Worker.GetValueAbstract(pawn.RaceProps.corpseDef, null);
foreach (BodyPartRecord current in from x in pawn.RaceProps.body.AllParts
orderby FoodUtility.GetBodyPartNutrition(totalCorpseNutrition, pawn, x) descending
select x)
{
stringBuilder.AppendLine(current.LabelCap + ": " + FoodUtility.GetBodyPartNutrition(totalCorpseNutrition, pawn, current));
}
Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false, null, null));
}, MenuOptionPriority.Default, null, null, 0f, null, null));
list.Add(new FloatMenuOption("test permanent injury pain factor probability", delegate
{
StringBuilder stringBuilder = new StringBuilder();
int num = 0;
int num2 = 0;
int num3 = 0;
float num4 = 0f;
int num5 = 10000;
for (int i = 0; i < num5; i++)
{
float num6 = Mathf.Max(0f, Rand.ByCurve(HealthTuning.PermanentInjuryPainFactorRandomCurve));
if (num6 < 0f)
{
Log.Error("Pain factor < 0", false);
}
if (num6 == 0f)
{
num++;
}
if (num6 < 1f)
{
num2++;
}
if (num6 < 5f)
{
num3++;
}
if (num6 > num4)
{
num4 = num6;
}
}
stringBuilder.AppendLine("total: " + num5);
stringBuilder.AppendLine(string.Concat(new object[]
{
"0: ",
num,
" (",
((float)num / (float)num5).ToStringPercent(),
")"
}));
stringBuilder.AppendLine(string.Concat(new object[]
{
"< 1: ",
num2,
" (",
((float)num2 / (float)num5).ToStringPercent(),
")"
}));
stringBuilder.AppendLine(string.Concat(new object[]
{
"< 5: ",
num3,
" (",
((float)num3 / (float)num5).ToStringPercent(),
")"
}));
stringBuilder.AppendLine("max: " + num4);
Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false, null, null));
}, MenuOptionPriority.Default, null, null, 0f, null, null));
list.Add(new FloatMenuOption("HediffGiver_Birthday chance at age", delegate
{
List<FloatMenuOption> list2 = new List<FloatMenuOption>();
foreach (HediffGiverSetDef current in pawn.RaceProps.hediffGiverSets)
{
foreach (HediffGiver_Birthday current2 in current.hediffGivers.OfType<HediffGiver_Birthday>())
{
HediffGiver_Birthday hLocal = current2;
FloatMenuOption item = new FloatMenuOption(current.defName + " - " + current2.hediff.defName, delegate
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendLine("% of pawns which will have at least 1 " + hLocal.hediff.label + " at age X:");
stringBuilder.AppendLine();
int num = 1;
while ((float)num < pawn.RaceProps.lifeExpectancy + 20f)
{
stringBuilder.AppendLine(num + ": " + hLocal.DebugChanceToHaveAtAge(pawn, num).ToStringPercent());
num++;
}
Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false, null, null));
}, MenuOptionPriority.Default, null, null, 0f, null, null);
list2.Add(item);
}
}
Find.WindowStack.Add(new FloatMenu(list2));
}, MenuOptionPriority.Default, null, null, 0f, null, null));
list.Add(new FloatMenuOption("HediffGiver_Birthday count at age", delegate
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendLine("Average hediffs count (from HediffGiver_Birthday) at age X:");
stringBuilder.AppendLine();
int num = 1;
while ((float)num < pawn.RaceProps.lifeExpectancy + 20f)
{
float num2 = 0f;
foreach (HediffGiverSetDef current in pawn.RaceProps.hediffGiverSets)
{
foreach (HediffGiver_Birthday current2 in current.hediffGivers.OfType<HediffGiver_Birthday>())
{
num2 += current2.DebugChanceToHaveAtAge(pawn, num);
}
}
stringBuilder.AppendLine(num + ": " + num2.ToStringDecimalIfSmall());
num++;
}
Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false, null, null));
}, MenuOptionPriority.Default, null, null, 0f, null, null));
Find.WindowStack.Add(new FloatMenu(list));
}
}
public static Pair<string, Color> GetEfficiencyLabel(Pawn pawn, PawnCapacityDef activity)
{
float level = pawn.health.capacities.GetLevel(activity);
string first = string.Empty;
Color second = Color.white;
if (level <= 0f)
{
first = "None".Translate();
second = HealthUtility.DarkRedColor;
}
else if (level < 0.4f)
{
first = "VeryPoor".Translate();
second = rjwHealthCardUtility.VeryPoorColor;
}
else if (level < 0.7f)
{
first = "Poor".Translate();
second = rjwHealthCardUtility.PoorColor;
}
else if (level < 1f && !Mathf.Approximately(level, 1f))
{
first = "Weakened".Translate();
second = rjwHealthCardUtility.WeakenedColor;
}
else if (Mathf.Approximately(level, 1f))
{
first = "GoodCondition".Translate();
second = HealthUtility.GoodConditionColor;
}
else
{
first = "Enhanced".Translate();
second = rjwHealthCardUtility.EnhancedColor;
}
return new Pair<string, Color>(first, second);
}
public static Pair<string, Color> GetPainLabel(Pawn pawn)
{
float painTotal = pawn.health.hediffSet.PainTotal;
string first = string.Empty;
Color second = Color.white;
if (Mathf.Approximately(painTotal, 0f))
{
first = "NoPain".Translate();
second = HealthUtility.GoodConditionColor;
}
else if (painTotal < 0.15f)
{
first = "LittlePain".Translate();
second = Color.gray;
}
else if (painTotal < 0.4f)
{
first = "MediumPain".Translate();
second = rjwHealthCardUtility.MediumPainColor;
}
else if (painTotal < 0.8f)
{
first = "SeverePain".Translate();
second = rjwHealthCardUtility.SeverePainColor;
}
else
{
first = "ExtremePain".Translate();
second = HealthUtility.DarkRedColor;
}
return new Pair<string, Color>(first, second);
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/CORE_EXPOSED/HealthCardUtility.cs
|
C#
|
mit
| 39,842
|
using System;
using System.Linq;
using Verse;
namespace rjw
{
public class AgeConfigDef : Def
{
public SimpleCurve attractivenessByAgeFemale;
public SimpleCurve attractivenessByAgeMale;
public SimpleCurve lovinIntervalHoursByAge;
public SimpleCurve rigidityByAge;
public SimpleCurve whoringPriceByAge;
static readonly Lazy<AgeConfigDef> instance = new Lazy<AgeConfigDef>(() => DefDatabase<AgeConfigDef>.AllDefs.Single());
public static AgeConfigDef Instance
{
get
{
return instance.Value;
}
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Data/AgeConfigDef.cs
|
C#
|
mit
| 537
|
using System.Collections.Generic;
using Verse;
using RimWorld;
using RimWorld.Planet;
namespace rjw
{
/// <summary>
/// Hugslib Utility Data object storing the RJW info
/// also implements extensions to Pawn method
/// is used as a static field in PawnData
/// </summary>
public class DataStore : WorldComponent
{
public DataStore(World world) : base(world)
{
}
public Dictionary<int, PawnData> PawnData = new Dictionary<int, PawnData> ();
//public Dictionary<int, PartsData> PartsData = new Dictionary<int, PartsData> ();
public override void ExposeData()
{
if (Scribe.mode == LoadSaveMode.Saving)
{
PawnData.RemoveAll(item => item.Value == null || !item.Value.IsValid);
}
base.ExposeData();
Scribe_Collections.Look(ref PawnData, "Data", LookMode.Value, LookMode.Deep);
if (Scribe.mode == LoadSaveMode.LoadingVars)
{
if (PawnData == null) PawnData = new Dictionary<int, PawnData>();
}
}
public PawnData GetPawnData(Pawn pawn)
{
PawnData res;
//--Log.Message("Getting data for " + pawn);
//--Log.Message("Pawn " + pawn + " id " + pawn.thingIDNumber);
//--Log.Message("PawnData isn't null " + !(PawnData == null));
var filled = PawnData.TryGetValue(pawn.thingIDNumber, out res);
//--Log.Message("Output is not null" + PawnData.TryGetValue(pawn.thingIDNumber, out res));
//--Log.Message("Out is not null " + (res != null));
//--Log.Message("Out is valid " + (res != null && res.IsValid));
if ((res==null) || (!res.IsValid))
{
if (filled)
{
//--Log.Message("Clearing incorrect data for " + pawn);
PawnData.Remove(pawn.thingIDNumber);
}
//--Log.Message("PawnData missing, creating for " + pawn);
res = new PawnData(pawn);
PawnData.Add(pawn.thingIDNumber, res);
}
//--Log.Message("Finishing");
//--Log.Message("PawnData is " + res.Comfort + " " + res.Service + " " + res.Breeding);
return res;
}
void SetPawnData(Pawn pawn, PawnData data)
{
PawnData.Add(pawn.thingIDNumber, data);
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Data/DataStore.cs
|
C#
|
mit
| 2,038
|
using Verse;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using RimWorld.Planet;
namespace rjw
{
/// <summary>
/// Collection of pawn designators lists
/// </summary>
public class DesignatorsData : WorldComponent
{
public DesignatorsData(World world) : base(world)
{
}
public static List<Pawn> rjwHero = new List<Pawn>();
public static List<Pawn> rjwComfort = new List<Pawn>();
public static List<Pawn> rjwService = new List<Pawn>();
public static List<Pawn> rjwMilking = new List<Pawn>();
public static List<Pawn> rjwBreeding = new List<Pawn>();
public static List<Pawn> rjwBreedingAnimal = new List<Pawn>();
//public static Dictionary<string, List<Pawn>> Designators = new Dictionary<string, List<Pawn>>();
/// <summary>
/// update designators on game load
/// </summary>
public void Update()
{
//if (RJWSettings.DevMode)
//ModLog.Message("DesignatorsData::Update()");
rjwHero = PawnsFinder.All_AliveOrDead.Where(p => p.IsDesignatedHero()).ToList();
rjwComfort = PawnsFinder.All_AliveOrDead.Where(p => p.IsDesignatedComfort()).ToList();
rjwService = PawnsFinder.All_AliveOrDead.Where(p => p.IsDesignatedService()).ToList();
rjwMilking = PawnsFinder.All_AliveOrDead.Where(p => p.IsDesignatedMilking()).ToList();
rjwBreeding = PawnsFinder.All_AliveOrDead.Where(p => p.IsDesignatedBreeding()).ToList();
rjwBreedingAnimal = PawnsFinder.All_AliveOrDead.Where(p => p.IsDesignatedBreedingAnimal()).ToList();
//ModLog.Message("rjwHero "+rjwHero.Count());
//ModLog.Message("rjwComfort "+rjwComfort.Count());
//ModLog.Message("rjwService "+rjwService.Count());
//ModLog.Message("rjwMilking "+rjwMilking.Count());
//ModLog.Message("rjwBreeding "+rjwBreeding.Count());
//ModLog.Message("rjwBreedingAnimal "+rjwBreedingAnimal.Count());
//Designators = new Dictionary<string, List<Pawn>>();
//Designators.Add("rjwHero", rjwHero);
//Designators.Add("rjwComfort", rjwComfort);
//Designators.Add("rjwService", rjwService);
//Designators.Add("rjwMilking", rjwMilking);
//Designators.Add("rjwBreeding", rjwBreeding);
//Designators.Add("rjwBreedingAnimal", rjwBreedingAnimal);
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Data/DesignatorsData.cs
|
C#
|
mit
| 2,197
|
using HugsLib;
using RimWorld;
using Verse;
namespace rjw
{
/// <summary>
/// Rjw settings store
/// </summary>
public class SaveStorage : ModBase
{
public override string ModIdentifier => ModId;
public static string ModId => "RJW";
public static DataStore DataStore;//reference to savegame data, hopefully
public static DesignatorsData DesignatorsData;//reference to savegame data, hopefully
public override void SettingsChanged()
{
ToggleTabIfNeeded();
}
public override void WorldLoaded()
{
DataStore = Find.World.GetComponent<DataStore>();
DesignatorsData = Find.World.GetComponent<DesignatorsData>();
DesignatorsData.Update();
ToggleTabIfNeeded();
FixRjwHediffsOnlLoad();
}
protected override bool HarmonyAutoPatch { get => false; }//first.cs creates harmony and does some convoulted stuff with it
private void ToggleTabIfNeeded()
{
//DefDatabase<MainButtonDef>.GetNamed("RJW_Brothel").buttonVisible = RJWSettings.whoringtab_enabled;
}
private void FixRjwHediffsOnlLoad()
{
foreach (var pawn in PawnsFinder.All_AliveOrDead)
{
foreach (var hd in pawn.health.hediffSet.hediffs)
{
if (hd is Hediff_PartBaseNatural || hd is Hediff_PartBaseArtifical)
{
hd.TryGetComp<CompHediffBodyPart>().updatepartposition();
}
}
}
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Data/ModData.cs
|
C#
|
mit
| 1,331
|
using System.Collections.Generic;
using Verse;
using System;
using System.ComponentModel;
using System.Linq;
using Verse.Noise;
namespace rjw
{
/// <summary>
/// Data about part sizes that is not tied to an individual hediffdef.
/// </summary>
public class PartStagesDef : Def
{
public float bandSizeBase;
public float bandSizeInterval;
public float cupSizeInterval;
public List<string> cupSizeLabels;
static readonly Lazy<PartStagesDef> instance = new Lazy<PartStagesDef>(() => DefDatabase<PartStagesDef>.AllDefs.Single());
public static PartStagesDef Instance
{
get
{
return instance.Value;
}
}
public static string GetCupSizeLabel(float size)
{
var i = Math.Max(0, Math.Min(Instance.cupSizeLabels.Count - 1, (int)size));
return Instance.cupSizeLabels[i];
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Data/PartStagesDef.cs
|
C#
|
mit
| 818
|
using System;
using Verse;
using System.Linq;
using RimWorld;
using System.Collections.Generic;
namespace rjw
{
/// <summary>
/// Utility data object and a collection of extension methods for Pawn
/// </summary>
public class PawnData : IExposable
{
public Pawn Pawn = null;
public bool Comfort = false;
public bool Service = false;
public bool Breeding = false;
public bool Milking = false;
public bool Hero = false;
public bool Ironman = false;
public string HeroOwner = "";
public bool BreedingAnimal = false;
public bool CanChangeDesignationColonist = false;
public bool CanChangeDesignationPrisoner = false;
public bool CanDesignateService = false;
public bool CanDesignateMilking = false;
public bool CanDesignateComfort = false;
public bool CanDesignateBreedingAnimal = false;
public bool CanDesignateBreeding = false;
public bool CanDesignateHero = false;
public bool isSlime = false;
public bool isDemon = false;
public bool oviPregnancy = false;
public float raceSexDrive = 1.0f;
public SexProps SexProps;// temp variable for rmb interactions cache
public List<Hediff> genitals = new List<Hediff>();
public List<Hediff> breasts = new List<Hediff>();
public List<Hediff> udders = new List<Hediff>();
public List<Hediff> anus = new List<Hediff>();
public List<Hediff> torso = new List<Hediff>();
public RaceGroupDef RaceSupportDef
{
get
{
if (raceSupportDef == null)
RaceGroupDef_Helper.TryGetRaceGroupDef(Pawn, out var raceGroupDef);
return raceSupportDef;
}
}
public RaceGroupDef raceSupportDef = null;
public PawnData() { }
public PawnData(Pawn pawn)
{
//Log.Message("Creating pawndata for " + pawn);
Pawn = pawn;
//Log.Message("This data is valid " + this.IsValid);
if (RaceGroupDef_Helper.TryGetRaceGroupDef(Pawn, out var raceGroupDef))
{
raceSupportDef = raceGroupDef;
//Log.Message("RaceSupportDef " + RaceSupportDef);
oviPregnancy = raceGroupDef.oviPregnancy;
raceSexDrive = raceGroupDef.raceSexDrive;
}
isDemon = Pawn.Has(RaceTag.Demon);
isSlime = Pawn.Has(RaceTag.Slime);
//Log.Warning("PawnData:: Pawn:" + xxx.get_pawnname(pawn));
//Log.Warning("PawnData:: isSlime:" + isSlime);
//Log.Warning("PawnData:: isDemon:" + isDemon);
//Log.Warning("PawnData:: oviPregnancy:" + oviPregnancy);
}
public void ExposeData()
{
Scribe_References.Look(ref Pawn, "Pawn");
Scribe_Values.Look(ref Comfort, "Comfort", false, true);
Scribe_Values.Look(ref Service, "Service", false, true);
Scribe_Values.Look(ref Breeding, "Breeding", false, true);
Scribe_Values.Look(ref Milking, "Milking", false, true);
Scribe_Values.Look(ref Hero, "Hero", false, true);
Scribe_Values.Look(ref Ironman, "Ironman", false, true);
Scribe_Values.Look(ref HeroOwner, "HeroOwner", "", true);
Scribe_Values.Look(ref BreedingAnimal, "BreedingAnimal", false, true);
Scribe_Values.Look(ref CanChangeDesignationColonist, "CanChangeDesignationColonist", false, true);
Scribe_Values.Look(ref CanChangeDesignationPrisoner, "CanChangeDesignationPrisoner", false, true);
Scribe_Values.Look(ref CanDesignateService, "CanDesignateService", false, true);
Scribe_Values.Look(ref CanDesignateMilking, "CanDesignateMilking", false, true);
Scribe_Values.Look(ref CanDesignateComfort, "CanDesignateComfort", false, true);
Scribe_Values.Look(ref CanDesignateBreedingAnimal, "CanDesignateBreedingAnimal", false, true);
Scribe_Values.Look(ref CanDesignateBreeding, "CanDesignateBreeding", false, true);
Scribe_Values.Look(ref CanDesignateHero, "CanDesignateHero", false, true);
Scribe_Values.Look(ref isSlime, "isSlime", false, true);
Scribe_Values.Look(ref isDemon, "isDemon", false, true);
Scribe_Values.Look(ref oviPregnancy, "oviPregnancy", false, true);
Scribe_Values.Look(ref raceSexDrive, "raceSexDrive", 1.0f, true);
Scribe_Defs.Look(ref raceSupportDef, "RaceSupportDef");
}
public bool IsValid { get { return Pawn != null; } }
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Data/PawnData.cs
|
C#
|
mit
| 4,034
|
using System.Collections.Generic;
using Verse;
using System;
namespace rjw
{
/// <summary>
/// Defines all RJW configuration related to a specific race or group of races.
/// Core races should have RaceGroupDefs in RJW.
/// Non-core races should have RaceGroupDefs in the separate RJWRaceSupport mod.
/// Technically any mod could add a RaceGroupDef for its own races but we expect that to be rare.
/// </summary>
public class RaceGroupDef : Def
{
public List<string> raceNames = null;
public List<string> pawnKindNames = null;
public List<PartAdder> partAdders;
public List<string> anuses = null;
public List<float> chanceanuses = null;
public List<string> femaleBreasts = null;
public List<float> chancefemaleBreasts = null;
public List<string> femaleGenitals = null;
public List<float> chancefemaleGenitals = null;
public List<string> maleBreasts = null;
public List<float> chancemaleBreasts = null;
public List<string> maleGenitals = null;
public List<float> chancemaleGenitals = null;
public List<string> hybridRaceParents = null;
public List<string> hybridChildKindDef = null;
public List<string> backstoryChildTribal = null;
public List<string> backstoryChildCivil = null;
public List<string> tags = null;
public bool hasSingleGender = false;
public bool hasSexNeed = true;
public bool hasFertility = true;
public bool hasPregnancy = true;
public bool oviPregnancy = false;
public bool ImplantEggs = false;
public bool HasUdder = false;
public bool isDemon = false;
public bool isSlime = false;
public float raceSexDrive = 1.0f;
public string eggFertilizedDef = "RJW_EggFertilized";
public string eggUnfertilizedDef = "RJW_EggUnfertilized";
public float eggProgressUnfertilizedMax = 1.0f;
public float eggLayIntervalDays = 3.5f;
/// <summary>
/// limit age at which sex becomes available for humans/animals
/// </summary>
public int teenAge;
public int adultAge;
//public int pPregnancyGrowth = 12;
//public float eggCountRange = 3.5f;
//public float eggFertilizationCountMax = 3.5f;
//public float eggLayFemaleOnly = 3.5f;
public List<string> GetRacePartDefNames(SexPartType sexPartType)
{
return sexPartType switch
{
SexPartType.Anus => anuses,
SexPartType.FemaleBreast => femaleBreasts,
SexPartType.FemaleGenital => femaleGenitals,
SexPartType.MaleBreast => maleBreasts,
SexPartType.MaleGenital => maleGenitals,
_ => throw new ApplicationException($"Unrecognized sexPartType: {sexPartType}"),
};
}
public List<float> GetChances(SexPartType sexPartType)
{
return sexPartType switch
{
SexPartType.Anus => chanceanuses,
SexPartType.FemaleBreast => chancefemaleBreasts,
SexPartType.FemaleGenital => chancefemaleGenitals,
SexPartType.MaleBreast => chancemaleBreasts,
SexPartType.MaleGenital => chancemaleGenitals,
_ => throw new ApplicationException($"Unrecognized sexPartType: {sexPartType}"),
};
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Data/RaceGroupDef.cs
|
C#
|
mit
| 2,987
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Verse;
namespace rjw
{
/// <summary>
/// Defines how to create a single sex part on a newly created pawn.
/// </summary>
public class RacePartDef : Def
{
public bool IsNone => string.IsNullOrEmpty(hediffName);
public static readonly RacePartDef None = new RacePartDef();
/// <summary>
/// The name of the hediff to create.
/// Doesn't use the hediff directly because that causes issues when another mod wants to
/// create and reference custom parts inheriting from rjw base defs.
/// </summary>
public string hediffName;
public string fluidType;
public float? fluidModifier;
public SimpleCurve severityCurve;
public bool TryGetHediffDef(out HediffDef hediffDef)
{
hediffDef = DefDatabase<HediffDef>.GetNamedSilentFail(hediffName);
if (hediffDef == null)
{
ModLog.Error($"Could not find a HediffDef named {hediffName} referenced by RacePartDef named {defName}.");
return false;
}
else
{
return true;
}
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Data/RacePartDef.cs
|
C#
|
mit
| 1,103
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RimWorld;
using Verse;
namespace rjw
{
public class RaceTag
{
// I only created tags for RaceGroupDef properties that seemed like keywords (like slime) rather than behavior (like oviPregnancy).
public readonly static RaceTag Chitin = new RaceTag("Chitin");
public readonly static RaceTag Demon = new RaceTag("Demon");
public readonly static RaceTag Feathers = new RaceTag("Feathers");
public readonly static RaceTag Fur = new RaceTag("Fur");
public readonly static RaceTag Plant = new RaceTag("Plant");
public readonly static RaceTag Robot = new RaceTag("Robot");
public readonly static RaceTag Scales = new RaceTag("Scales");
public readonly static RaceTag Skin = new RaceTag("Skin");
public readonly static RaceTag Slime = new RaceTag("Slime");
public string Key { get; }
RaceTag(string key)
{
Key = key;
}
/// <summary>
/// For backwards compatability only. Shouldn't add more special cases here.
/// </summary>
public bool DefaultWhenNoRaceGroupDef(Pawn pawn)
{
if (this == Demon)
{
return xxx.is_demon(pawn);
}
else if (this == Slime)
{
return xxx.is_slime(pawn);
}
else if (this == Skin)
{
return true;
}
else
{
return false;
}
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Data/RaceTag.cs
|
C#
|
mit
| 1,337
|
using System.Collections.Generic;
using Verse;
namespace rjw
{
/// <summary>
/// Just a simplest form of passing data from xml to the code
/// </summary>
public class StringListDef : Def
{
public List<string> strings = new List<string>();
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Data/StringListDef.cs
|
C#
|
mit
| 256
|
///Better not leave it be, this mod is not intended to reimpelement base functionality and break other mods by that.
//using Harmony;
//using RimWorld;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Reflection;
//using System.Text;
//using UnityEngine;
//using Verse;
//using Verse.Sound;
//namespace rjw.Source.Common
//{
// public static class ExpandedPawnCharacterCard
// {
// /// <summary>
// /// Better to leave it be, since it doesn't affect anything much.
// /// </summary>
// public static float cardX = 570f; // vanilla is 570
// /// <summary>
// /// Basically, you want to increase this value if you want character info card be taller (thus allowing to have more
// /// traits and skills shown). Height is in pixels, increase by ~25 pixels for each additional row of skill/trait.
// /// </summary>
// public static float cardY = 470f; // vanilla is 470
// [HarmonyPatch(typeof(CharacterCardUtility), "DrawCharacterCard", new[] { typeof(Rect), typeof(Pawn), typeof(Action), typeof(Rect), })]
// public static class CharacterCardUtilityPatch
// {
// private static IEnumerable<WorkTags> WorkTagsFrom(WorkTags tags)
// {
// foreach (WorkTags workTag in tags.GetAllSelectedItems<WorkTags>())
// {
// if (workTag != WorkTags.None)
// {
// yield return workTag;
// }
// }
// }
// [HarmonyPrefix]
// public static bool DrawCharacterCardP(ref Rect rect, ref Pawn pawn, ref Action randomizeCallback, ref Rect creationRect)
// {
// rect.position = new Vector2(17f, 17f);
// rect.size = new Vector2(cardX, cardY);
// bool flag = randomizeCallback != null;
// GUI.BeginGroup((!flag) ? rect : creationRect);
// Rect rectLabel = new Rect(0f, 0f, 300f, 30f);
// NameTriple nameTriple = pawn.Name as NameTriple;
// if (flag && nameTriple != null)
// {
// Rect rect3 = new Rect(rectLabel);
// rect3.width *= 0.333f;
// Rect rect4 = new Rect(rectLabel);
// rect4.width *= 0.333f;
// rect4.x += rect4.width;
// Rect rect5 = new Rect(rectLabel);
// rect5.width *= 0.333f;
// rect5.x += rect4.width * 2f;
// string first = nameTriple.First;
// string nick = nameTriple.Nick;
// string last = nameTriple.Last;
// CharacterCardUtility.DoNameInputRect(rect3, ref first, 12);
// if (nameTriple.Nick == nameTriple.First || nameTriple.Nick == nameTriple.Last)
// {
// GUI.color = new Color(1f, 1f, 1f, 0.5f);
// }
// CharacterCardUtility.DoNameInputRect(rect4, ref nick, 9);
// GUI.color = Color.white;
// CharacterCardUtility.DoNameInputRect(rect5, ref last, 12);
// if (nameTriple.First != first || nameTriple.Nick != nick || nameTriple.Last != last)
// {
// pawn.Name = new NameTriple(first, nick, last);
// }
// TooltipHandler.TipRegion(rect3, "FirstNameDesc".Translate());
// TooltipHandler.TipRegion(rect4, "ShortIdentifierDesc".Translate());
// TooltipHandler.TipRegion(rect5, "LastNameDesc".Translate());
// }
// else
// {
// rectLabel.width = 999f;
// Text.Font = GameFont.Medium;
// Widgets.Label(rectLabel, pawn.Name.ToStringFull);
// Text.Font = GameFont.Small;
// }
// if (randomizeCallback != null)
// {
// Rect rectRandomise = new Rect(creationRect.width - 24f - 100f, 0f, 100f, rectLabel.height);
// if (Widgets.ButtonText(rectRandomise, "Randomize".Translate(), true, false, true))
// {
// SoundDefOf.TickTiny.PlayOneShotOnCamera(null);
// randomizeCallback();
// }
// UIHighlighter.HighlightOpportunity(rectRandomise, "RandomizePawn");
// }
// if (flag)
// {
// Widgets.InfoCardButton(creationRect.width - 24f, 0f, pawn);
// }
// else if (!pawn.health.Dead)
// {
// float num = CharacterCardUtility.PawnCardSize.x - 85f;
// if ((pawn.Faction == Faction.OfPlayer || pawn.IsPrisonerOfColony) && pawn.Spawned)
// {
// Rect rectBanish = new Rect(num, 0f, 30f, 30f);
// TooltipHandler.TipRegion(rectBanish, PawnBanishUtility.GetBanishButtonTip(pawn));
// if (Widgets.ButtonImage(rectBanish, ContentFinder<Texture2D>.Get("UI/Buttons/Banish", true)))
// {
// if (pawn.Downed)
// {
// Messages.Message("MessageCantBanishDownedPawn".Translate(new object[]
// {
// pawn.LabelShort
// }).AdjustedFor(pawn), pawn, MessageTypeDefOf.RejectInput);
// }
// else
// {
// PawnBanishUtility.ShowBanishPawnConfirmationDialog(pawn);
// }
// }
// num -= 40f;
// }
// if (pawn.IsColonist)
// {
// Rect rect8 = new Rect(num, 0f, 30f, 30f);
// TooltipHandler.TipRegion(rect8, "RenameColonist".Translate());
// if (Widgets.ButtonImage(rect8, ContentFinder<Texture2D>.Get("UI/Buttons/Rename", true)))
// {
// Find.WindowStack.Add(new Dialog_ChangeNameTriple(pawn));
// }
// num -= 40f;
// }
// }
// string label = pawn.MainDesc(true);
// Rect rectMainDesc = new Rect(0f, 45f, rect.width, 60f);
// Widgets.Label(rectMainDesc, label);
// Pawn p = pawn;
// TooltipHandler.TipRegion(rectMainDesc, () => p.ageTracker.AgeTooltipString, 6873641);
// Rect positionLeftHalf = new Rect(0f, 100f, 250f, cardY);
// Rect positionRightHalf = new Rect(positionLeftHalf.xMax, 100f, 258f, cardY);
// GUI.BeginGroup(positionLeftHalf);
// float currentY = 0f;
// Text.Font = GameFont.Medium;
// Widgets.Label(new Rect(0f, 0f, 200f, 30f), "Backstory".Translate());
// currentY += 30f;
// Text.Font = GameFont.Small;
// foreach (BackstorySlot backstorySlot in Enum.GetValues(typeof(BackstorySlot)))
// {
// Backstory backstory = pawn.story.GetBackstory(backstorySlot);
// if (backstory != null)
// {
// Rect rect10 = new Rect(0f, currentY, positionLeftHalf.width, 24f);
// if (Mouse.IsOver(rect10))
// {
// Widgets.DrawHighlight(rect10);
// }
// TooltipHandler.TipRegion(rect10, backstory.FullDescriptionFor(pawn));
// Text.Anchor = TextAnchor.MiddleLeft;
// string str = (backstorySlot != BackstorySlot.Adulthood) ? "Childhood".Translate() : "Adulthood".Translate();
// Widgets.Label(rect10, str + ":");
// Text.Anchor = TextAnchor.UpperLeft;
// Rect rect11 = new Rect(rect10);
// rect11.x += 90f;
// rect11.width -= 90f;
// string title = backstory.Title;
// Widgets.Label(rect11, title);
// currentY += rect10.height + 2f;
// }
// }
// currentY += 25f;
// Text.Font = GameFont.Small;
// Widgets.Label(new Rect(0f, currentY, 200f, 30f), "IncapableOf".Translate());
// currentY += 30f;
// Text.Font = GameFont.Small;
// StringBuilder stringBuilder = new StringBuilder();
// WorkTags combinedDisabledWorkTags = pawn.story.CombinedDisabledWorkTags;
// if (combinedDisabledWorkTags == WorkTags.None)
// {
// stringBuilder.Append("(" + "NoneLower".Translate() + "), ");
// }
// else
// {
// List<WorkTags> list = WorkTagsFrom(combinedDisabledWorkTags).ToList<WorkTags>();
// bool flag2 = true;
// foreach (WorkTags current in list)
// {
// if (flag2)
// {
// stringBuilder.Append(current.LabelTranslated().CapitalizeFirst());
// }
// else
// {
// stringBuilder.Append(current.LabelTranslated());
// }
// stringBuilder.Append(", ");
// flag2 = false;
// }
// }
// string text = stringBuilder.ToString();
// text = text.Substring(0, text.Length - 2);
// Rect rect12 = new Rect(0f, currentY, positionLeftHalf.width, 999f);
// Widgets.Label(rect12, text);
// currentY += 100f;
// Text.Font = GameFont.Medium;
// Widgets.Label(new Rect(0f, currentY, 200f, 30f), "Traits".Translate());
// currentY += 30f;
// Text.Font = GameFont.Small;
// for (int i = 0; i < pawn.story.traits.allTraits.Count; i++)
// {
// Trait trait = pawn.story.traits.allTraits[i];
// Rect rectCurrentTrait = new Rect(0f, currentY, positionLeftHalf.width, 24f);
// if (Mouse.IsOver(rectCurrentTrait))
// {
// Widgets.DrawHighlight(rectCurrentTrait);
// }
// Widgets.Label(rectCurrentTrait, trait.LabelCap);
// currentY += rectCurrentTrait.height + 2f;
// Trait trLocal = trait;
// TipSignal tip = new TipSignal(() => trLocal.TipString(p), (int)currentY * 37);
// TooltipHandler.TipRegion(rectCurrentTrait, tip);
// }
// GUI.EndGroup();
// GUI.BeginGroup(positionRightHalf);
// Text.Font = GameFont.Medium;
// Widgets.Label(new Rect(0f, 0f, 200f, 30f), "Skills".Translate());
// SkillUI.SkillDrawMode mode;
// if (Current.ProgramState == ProgramState.Playing)
// {
// mode = SkillUI.SkillDrawMode.Gameplay;
// }
// else
// {
// mode = SkillUI.SkillDrawMode.Menu;
// }
// SkillUI.DrawSkillsOf(pawn, new Vector2(0f, 35f), mode);
// GUI.EndGroup();
// GUI.EndGroup();
// return false;
// }
// }
// [HarmonyPatch(typeof(ITab_Pawn_Character), "FillTab")]
// public static class ITab_Pawn_CharacterPatch
// {
// [HarmonyPrefix]
// public static bool FillTabP(ITab_Pawn_Character __instance)
// {
// FieldInfo fi = typeof(ITab_Pawn_Character).GetField("size", Unprivater.flags);
// fi.SetValue(__instance, new Vector2(cardX+34f, cardY+34f));
// var p = Unprivater.GetProtectedProperty<Pawn>("PawnToShowInfoAbout", __instance);
// Rect rect = new Rect(17f, 17f, 570f, cardY);
// CharacterCardUtility.DrawCharacterCard(rect, p, null, default(Rect));
// return false;
// }
// }
// }
//}
|
jojo1541/rjw
|
1.4/Source/Common/ExpandedPawnCharacterCard.cs
|
C#
|
mit
| 9,613
|
using System.Linq;
using RimWorld;
using UnityEngine;
using Verse;
using Verse.AI;
using Multiplayer.API;
using System.Collections.Generic;
namespace rjw
{
public static class AfterSexUtility
{
//aftersex thoughts
public static readonly ThoughtDef got_raped = DefDatabase<ThoughtDef>.GetNamed("GotRaped");
public static readonly ThoughtDef got_anal_raped = DefDatabase<ThoughtDef>.GetNamed("GotAnalRaped");
public static readonly ThoughtDef got_anal_raped_byfemale = DefDatabase<ThoughtDef>.GetNamed("GotAnalRapedByFemale");
public static readonly ThoughtDef got_raped_unconscious = DefDatabase<ThoughtDef>.GetNamed("GotRapedUnconscious");
public static readonly ThoughtDef masochist_got_raped_unconscious = DefDatabase<ThoughtDef>.GetNamed("MasochistGotRapedUnconscious");
public static readonly ThoughtDef got_bred = DefDatabase<ThoughtDef>.GetNamed("GotBredByAnimal");
public static readonly ThoughtDef got_anal_bred = DefDatabase<ThoughtDef>.GetNamed("GotAnalBredByAnimal");
public static readonly ThoughtDef got_licked = DefDatabase<ThoughtDef>.GetNamed("GotLickedByAnimal");
public static readonly ThoughtDef got_groped = DefDatabase<ThoughtDef>.GetNamed("GotGropedByAnimal");
public static readonly ThoughtDef masochist_got_raped = DefDatabase<ThoughtDef>.GetNamed("MasochistGotRaped");
public static readonly ThoughtDef masochist_got_anal_raped = DefDatabase<ThoughtDef>.GetNamed("MasochistGotAnalRaped");
public static readonly ThoughtDef masochist_got_anal_raped_byfemale = DefDatabase<ThoughtDef>.GetNamed("MasochistGotAnalRapedByFemale");
public static readonly ThoughtDef masochist_got_bred = DefDatabase<ThoughtDef>.GetNamed("MasochistGotBredByAnimal");
public static readonly ThoughtDef masochist_got_anal_bred = DefDatabase<ThoughtDef>.GetNamed("MasochistGotAnalBredByAnimal");
public static readonly ThoughtDef masochist_got_licked = DefDatabase<ThoughtDef>.GetNamed("MasochistGotLickedByAnimal");
public static readonly ThoughtDef masochist_got_groped = DefDatabase<ThoughtDef>.GetNamed("MasochistGotGropedByAnimal");
public static readonly ThoughtDef allowed_animal_to_breed = DefDatabase<ThoughtDef>.GetNamed("AllowedAnimalToBreed");
public static readonly ThoughtDef allowed_animal_to_lick = DefDatabase<ThoughtDef>.GetNamed("AllowedAnimalToLick");
public static readonly ThoughtDef allowed_animal_to_grope = DefDatabase<ThoughtDef>.GetNamed("AllowedAnimalToGrope");
public static readonly ThoughtDef zoophile_got_bred = DefDatabase<ThoughtDef>.GetNamed("ZoophileGotBredByAnimal");
public static readonly ThoughtDef zoophile_got_anal_bred = DefDatabase<ThoughtDef>.GetNamed("ZoophileGotAnalBredByAnimal");
public static readonly ThoughtDef zoophile_got_licked = DefDatabase<ThoughtDef>.GetNamed("ZoophileGotLickedByAnimal");
public static readonly ThoughtDef zoophile_got_groped = DefDatabase<ThoughtDef>.GetNamed("ZoophileGotGropedByAnimal");
public static readonly ThoughtDef hate_my_rapist = DefDatabase<ThoughtDef>.GetNamed("HateMyRapist");
public static readonly ThoughtDef kinda_like_my_rapist = DefDatabase<ThoughtDef>.GetNamed("KindaLikeMyRapist");
public static readonly ThoughtDef allowed_me_to_get_raped = DefDatabase<ThoughtDef>.GetNamed("AllowedMeToGetRaped");
public static readonly ThoughtDef stole_some_lovin = DefDatabase<ThoughtDef>.GetNamed("StoleSomeLovin");
public static readonly ThoughtDef bloodlust_stole_some_lovin = DefDatabase<ThoughtDef>.GetNamed("BloodlustStoleSomeLovin");
public static readonly ThoughtDef violated_corpse = DefDatabase<ThoughtDef>.GetNamed("ViolatedCorpse");
public static readonly ThoughtDef gave_virginity = DefDatabase<ThoughtDef>.GetNamed("FortunateGaveVirginity");
public static readonly ThoughtDef lost_virginity = DefDatabase<ThoughtDef>.GetNamed("UnfortunateLostVirginity");
public static readonly ThoughtDef took_virginity = DefDatabase<ThoughtDef>.GetNamed("TookVirginity");
//violent - mark true when pawn rape partner
//Note: violent is not reliable, since either pawn could be the rapist. Check jobdrivers instead, they're still active since this is called before ending the job.
public static void think_about_sex(SexProps props)
{
Pawn receiving = props.partner;//TODO: replace this shit at some point when interaction has reversed roles
think_about_sex(props.pawn, props.partner, receiving == props.pawn, props, props.isWhoring);
think_about_sex(props.partner, props.pawn, receiving == props.partner, props, false);
}
public static void think_about_sex(Pawn pawn, Pawn partner, bool isReceiving, SexProps props, bool whoring = false)
{
// Partner should never be null, but just in case something gets changed elsewhere..
if (partner == null)
{
ModLog.Error("xxx::think-after_sex( ERROR: " + xxx.get_pawnname(pawn) + " has no partner. This should not be called from solo acts. Sextype: " + props.sexType);
return;
}
// Both pawns are now checked individually, instead of giving thoughts to the partner.
//Can just return if the currently checked pawn is dead or can't have thoughts, which simplifies the checks.
if (pawn.Dead || !xxx.is_human(pawn))
return;
bool masochist = xxx.is_masochist(pawn);
bool zoophile = xxx.is_zoophile(pawn);
bool guilty = props.canBeGuilty;
if (HasLoveEnhancer(pawn, partner))
{
masochist = true;
zoophile = true;
}
if (masochist)
{
if (RJWSettings.rape_beating)
pawn.needs.mood.thoughts.memories.RemoveMemoriesOfDefWhereOtherPawnIs(ThoughtDefOf.HarmedMe, partner);
}
if (!masochist)
{
//TODO: someday rough sex?
//foreach (DirectPawnRelation relation in pawn.relations.DirectRelations)
//{
// if (relation.otherPawn == partner)
// if (relation.def == PawnRelationDefOf.Lover ||
// relation.def == PawnRelationDefOf.Fiance ||
// relation.def == PawnRelationDefOf.Spouse)
// {
// masochist = true;
// break;
// }
//}
//if (pawn.IsPrisoner || masochist || is_slave(pawn) || pawn.IsDesignatedComfort())
if (pawn.IsPrisoner || xxx.is_slave(pawn) || pawn.IsDesignatedComfort())
{
guilty = false;
}
}
else
guilty = false;
ThoughtDef thoughtgain = null;
//unconscious pawns has no thoughts
//and if they has sex, its probably rape, since they have no choice
if (!pawn.health.capacities.CanBeAwake)
{
thoughtgain = xxx.is_masochist(pawn) ? masochist_got_raped_unconscious : got_raped_unconscious;
pawn.needs.mood.thoughts.memories.TryGainMemory(thoughtgain);
return;
}
// TODO: refactor all these repeated arguments to be a `ref struct`.
// This would be a breaking change, though.
thoughtgain = think_about_sex_Bestiality(pawn, partner, isReceiving, props, whoring, masochist, zoophile, guilty);
if (thoughtgain == null)
thoughtgain = think_about_sex_Rapist(pawn, partner, isReceiving, props, whoring, masochist, zoophile, guilty);
if (thoughtgain == null)
thoughtgain = think_about_sex_Victim(pawn, partner, isReceiving, props, whoring, masochist, zoophile, guilty);
if (thoughtgain == null)
thoughtgain = think_about_sex_Consensual(pawn, partner, isReceiving, props, whoring, masochist, zoophile, guilty);
if (thoughtgain != null)
{
var newMemory = FinalizeThought(thoughtgain, pawn, partner, isReceiving, props, whoring, masochist, zoophile, guilty);
pawn.needs.mood?.thoughts.memories.TryGainMemory(newMemory, partner);
}
}
public static Thought_Memory FinalizeThought(
ThoughtDef thoughtgain,
Pawn pawn,
Pawn partner,
bool isReceiving,
SexProps props,
bool whoring,
bool masochist,
bool zoophile,
bool guilty
)
{
var newMemory = (Thought_Memory)ThoughtMaker.MakeThought(thoughtgain);
// Apply mood boost for vanilla lovin' from love enhancer.
if (thoughtgain == ThoughtDefOf.GotSomeLovin && HasLoveEnhancer(pawn, partner))
newMemory.moodPowerFactor = 1.5f;
return newMemory;
}
public static ThoughtDef think_about_sex_Bestiality(
Pawn pawn,
Pawn partner,
bool isReceiving,
SexProps props,
bool whoring,
bool masochist,
bool zoophile,
bool guilty
)
{
//ModLog.Message("xxx::think-after_sex( ERROR: 3");
// Thoughts for animal-on-colonist.
ThoughtDef thoughtDef = null;
if (xxx.is_animal(partner) && isReceiving)
{
if (!zoophile && !props.isRape)
{
//ModLog.Message("xxx::think-after_sex( ERROR: 3.1");
if (props.sexType == xxx.rjwSextype.Oral)
thoughtDef = (allowed_animal_to_lick);
else if (props.sexType == xxx.rjwSextype.Anal || props.sexType == xxx.rjwSextype.Vaginal)
thoughtDef = (allowed_animal_to_breed);
else //Other rarely seen sex types, such as fingering (by primates, monster girls, etc)
thoughtDef = (allowed_animal_to_grope);
}
else
{
//ModLog.Message("xxx::think-after_sex( ERROR: 3.2");
if (!zoophile)
{
if (props.sexType == xxx.rjwSextype.Oral)
thoughtDef = (masochist ? masochist_got_licked : got_licked);
else if (props.sexType == xxx.rjwSextype.Vaginal)
thoughtDef = (masochist ? masochist_got_bred : got_bred);
else if (props.sexType == xxx.rjwSextype.Anal)
thoughtDef = (masochist ? masochist_got_anal_bred : got_anal_bred);
else //Other types
thoughtDef = (masochist ? masochist_got_groped : got_groped);
}
else
{
if (props.sexType == xxx.rjwSextype.Oral)
thoughtDef = (zoophile_got_licked);
else if (props.sexType == xxx.rjwSextype.Vaginal)
thoughtDef = (zoophile_got_bred);
else if (props.sexType == xxx.rjwSextype.Anal)
thoughtDef = (zoophile_got_anal_bred);
else //Other types
thoughtDef = (zoophile_got_groped);
}
}
think_about_sex_Bestiality_TameAttempt(pawn, partner, isReceiving, props, whoring, masochist, zoophile, guilty);
}
return thoughtDef;
}
public static void think_about_sex_Bestiality_TameAttempt(
Pawn pawn,
Pawn partner,
bool isReceiving,
SexProps props,
bool whoring,
bool masochist,
bool zoophile,
bool guilty
)
{
if (pawn.CurJob != null)
if (!(pawn.Downed && partner.Downed))
if (!partner.Dead && zoophile && (pawn.CurJob.def != xxx.gettin_raped) && partner.Faction == null && pawn.Faction == Faction.OfPlayer)
{
InteractionDef intDef = !partner.AnimalOrWildMan() ? InteractionDefOf.RecruitAttempt : InteractionDefOf.TameAttempt;
pawn.interactions.TryInteractWith(partner, intDef);
}
}
public static ThoughtDef think_about_sex_Rapist(
Pawn pawn,
Pawn partner,
bool isReceiving,
SexProps props,
bool whoring,
bool masochist,
bool zoophile,
bool guilty
)
{
ThoughtDef thoughtDef = null;
if (partner.Dead || (partner.CurJob != null && partner.CurJob.def == xxx.gettin_raped) || pawn.jobs?.curDriver is JobDriver_Rape)
{
thoughtDef = (xxx.is_rapist(pawn) || xxx.is_bloodlust(pawn) || xxx.is_psychopath(pawn)) ? bloodlust_stole_some_lovin : stole_some_lovin;
if ((xxx.is_necrophiliac(pawn) || xxx.is_psychopath(pawn)) && partner.Dead)
{
thoughtDef = (violated_corpse);
}
}
return thoughtDef;
}
public static ThoughtDef think_about_sex_Victim(
Pawn pawn,
Pawn partner,
bool isReceiving,
SexProps props,
bool whoring,
bool masochist,
bool zoophile,
bool guilty
)
{
ThoughtDef thoughtDef = null;
if (pawn.CurJob != null && pawn.CurJob.def == xxx.gettin_raped || partner.jobs?.curDriver is JobDriver_Rape)
{
if (xxx.is_human(partner))
{
if (props.sexType == xxx.rjwSextype.Anal)
{
if (xxx.is_female(partner))
{
thoughtDef = masochist ? masochist_got_anal_raped_byfemale : got_anal_raped_byfemale;
}
else
{
thoughtDef = masochist ? masochist_got_anal_raped : got_anal_raped;
}
}
else
{
thoughtDef = masochist ? masochist_got_raped : got_raped;
}
ThoughtDef pawn_thought_about_rapist = masochist ? kinda_like_my_rapist : hate_my_rapist;
pawn.needs.mood.thoughts.memories.TryGainMemory(pawn_thought_about_rapist, partner);
if (guilty)
partner.guilt.Notify_Guilty(GenDate.TicksPerDay);
}
think_about_sex_Victim_Blame(pawn, partner, isReceiving, props, whoring, masochist, zoophile, guilty);
}
return thoughtDef;
}
public static void think_about_sex_Victim_Blame(
Pawn pawn,
Pawn partner,
bool isReceiving,
SexProps props,
bool whoring,
bool masochist,
bool zoophile,
bool guilty
)
{
if (pawn.Faction != null && pawn.Map != null && !masochist && !(xxx.is_animal(partner) && zoophile))
{
foreach (Pawn bystander in pawn.Map.mapPawns.SpawnedPawnsInFaction(pawn.Faction).Where(x => !xxx.is_animal(x) && x != pawn && x != partner && !x.Downed && !x.Suspended))
{
// dont see through walls, dont see whole map, only 15 cells around
if (pawn.CanSee(bystander) && pawn.Position.DistanceTo(bystander.Position) < 15)
{
pawn.needs.mood.thoughts.memories.TryGainMemory(allowed_me_to_get_raped, bystander);
}
}
}
}
public static ThoughtDef think_about_sex_Consensual(
Pawn pawn,
Pawn partner,
bool isReceiving,
SexProps props,
bool whoring,
bool masochist,
bool zoophile,
bool guilty
)
{
ThoughtDef thoughtDef = null;
if (xxx.is_human(partner))
{
if (!props.isCoreLovin && !whoring)
{
// human partner and not part of rape or necrophilia. add the vanilla GotSomeLovin thought
thoughtDef = ThoughtDefOf.GotSomeLovin;
}
}
return thoughtDef;
}
public static bool HasLoveEnhancer(Pawn pawn) =>
pawn.health.hediffSet.hediffs.Any((Hediff h) => h.def == HediffDefOf.LoveEnhancer);
public static bool HasLoveEnhancer(Pawn pawn, Pawn partner) =>
HasLoveEnhancer(pawn) || HasLoveEnhancer(partner);
public static void UpdateRecords(SexProps props)
{
UpdateRecordsInitiator(props);
if (props.sexType != xxx.rjwSextype.Masturbation)
UpdateRecordsPartner(props);
}
private static void UpdateRecordsInitiator(SexProps props)
{
Pawn pawn = props.pawn;
Pawn partner = props.partner;
if (props.sexType == xxx.rjwSextype.Masturbation)
{
pawn.records.Increment(xxx.CountOfFappin);
return;
}
//bool isVirginSex = xxx.is_Virgin(pawn); //need copy value before count increase.
//ThoughtDef currentThought = null;
pawn.records.Increment(xxx.CountOfSex);
//bool masochist = xxx.is_masochist(pawn);
//bool zoophile = xxx.is_zoophile(pawn);
//if (HasLoveEnhancer(pawn, partner))
//{
// masochist = true;
// zoophile = true;
//}
if (props.partner.Dead)
{
pawn.records.Increment(xxx.CountOfSexWithCorpse);
}
if (!props.isRape)
{
if (xxx.is_human(partner))
{
pawn.records.Increment(xxx.CountOfSexWithHumanlikes);
//currentThought = isLoveSex ? xxx.gave_virginity : null;
}
else if (xxx.is_insect(partner))
{
pawn.records.Increment(xxx.CountOfSexWithInsects);
}
else if (xxx.is_animal(partner))
{
pawn.records.Increment(xxx.CountOfSexWithAnimals);
//currentThought = zoophile ? xxx.gave_virginity : null;
}
else
{
pawn.records.Increment(xxx.CountOfSexWithOthers);
}
}
else
{
//if (!pawnIsRaper)
//{
// currentThought = masochist ? xxx.gave_virginity : xxx.lost_virginity;
//}
if (xxx.is_human(partner))
{
pawn.records.Increment(xxx.CountOfRapedHumanlikes);
//if (pawnIsRaper && (xxx.is_rapist(pawn) || xxx.is_bloodlust(pawn)))
// currentThought = xxx.gave_virginity;
}
else if (xxx.is_insect(partner))
{
pawn.records.Increment(xxx.CountOfSexWithInsects);
pawn.records.Increment(xxx.CountOfRapedInsects);
}
else if (xxx.is_animal(partner))
{
pawn.records.Increment(xxx.CountOfSexWithAnimals);
pawn.records.Increment(xxx.CountOfRapedAnimals);
//if (zoophile) currentThought = xxx.gave_virginity;
}
else
{
pawn.records.Increment(xxx.CountOfSexWithOthers);
pawn.records.Increment(xxx.CountOfRapedOthers);
}
}
//if (isVirginSex) //&& (sextype == rjwSextype.Vaginal || sextype == rjwSextype.DoublePenetration))
//{
// Log.Message(xxx.get_pawnname(pawn) + " | " + xxx.get_pawnname(partner) + " | " + currentThought);
// Log.Message("1");
// if (!is_animal(partner))//passive
// {
// if (currentThought != null)
// partner.needs.mood.thoughts.memories.TryGainMemory(currentThought);
// }
// Log.Message("2");
// if (!is_animal(pawn))//active
// {
// currentThought = took_virginity;
// pawn.needs.mood.thoughts.memories.TryGainMemory(currentThought);
// }
//}
}
private static void UpdateRecordsPartner(SexProps props)
{
if (props.partner == null || props.partner.Dead) // masturbation or corpse fucking
return;
Pawn pawn = props.partner;
Pawn partner = props.pawn;
//bool isVirginSex = xxx.is_Virgin(pawn); //need copy value before count increase.
//ThoughtDef currentThought = null;
pawn.records.Increment(xxx.CountOfSex);
//bool masochist = xxx.is_masochist(pawn);
//bool zoophile = xxx.is_zoophile(pawn);
//if (HasLoveEnhancer(pawn, partner))
//{
// masochist = true;
// zoophile = true;
//}
if (!props.isRape)
{
if (xxx.is_human(partner))
{
pawn.records.Increment(xxx.CountOfSexWithHumanlikes);
//currentThought = isLoveSex ? xxx.gave_virginity : null;
}
else if (xxx.is_insect(partner))
{
pawn.records.Increment(xxx.CountOfSexWithInsects);
}
else if (xxx.is_animal(partner))
{
pawn.records.Increment(xxx.CountOfSexWithAnimals);
//currentThought = zoophile ? xxx.gave_virginity : null;
}
else
{
pawn.records.Increment(xxx.CountOfSexWithOthers);
}
}
else
{
//if (!pawnIsRaper)
//{
// currentThought = masochist ? xxx.gave_virginity : xxx.lost_virginity;
//}
if (xxx.is_human(partner))
{
pawn.records.Increment(xxx.CountOfBeenRapedByHumanlikes);
//if (pawnIsRaper && (xxx.is_rapist(pawn) || xxx.is_bloodlust(pawn)))
// currentThought = xxx.gave_virginity;
}
else if (xxx.is_insect(partner))
{
pawn.records.Increment(xxx.CountOfSexWithInsects);
pawn.records.Increment(xxx.CountOfBeenRapedByInsects);
}
else if (xxx.is_animal(partner))
{
pawn.records.Increment(xxx.CountOfSexWithAnimals);
pawn.records.Increment(xxx.CountOfBeenRapedByAnimals);
//if (zoophile) currentThought = xxx.gave_virginity;
}
else
{
pawn.records.Increment(xxx.CountOfSexWithOthers);
pawn.records.Increment(xxx.CountOfBeenRapedByOthers);
}
}
//if (isVirginSex) //&& (sextype == rjwSextype.Vaginal || sextype == rjwSextype.DoublePenetration))
//{
// Log.Message(xxx.get_pawnname(pawn) + " | " + xxx.get_pawnname(partner) + " | " + currentThought);
// Log.Message("1");
// if (!is_animal(partner))//passive
// {
// if (currentThought != null)
// partner.needs.mood.thoughts.memories.TryGainMemory(currentThought);
// }
// Log.Message("2");
// if (!is_animal(pawn))//active
// {
// currentThought = took_virginity;
// pawn.needs.mood.thoughts.memories.TryGainMemory(currentThought);
// }
//}
}
//============↓======Section of processing the broken body system===============↓=============
public static bool BodyIsBroken(Pawn pawn)
{
return pawn.health.hediffSet.HasHediff(xxx.feelingBroken);
}
[SyncMethod]
public static bool BadlyBroken(Pawn pawn, out Trait addedTrait)
{
addedTrait = null;
if (!BodyIsBroken(pawn))
{
return false;
}
int stage = pawn.health.hediffSet.GetFirstHediffOfDef(xxx.feelingBroken).CurStageIndex;
if (stage >= 3)
{
//when broken make character masochist
//todo remove/replace social/needs dubuffs
if (RJWSettings.AddTrait_Masocist && !xxx.is_masochist(pawn))
{
var chance = 0.05f;
if (Rand.Chance(chance))
{
if (xxx.is_rapist(pawn))
{
pawn.story.traits.allTraits.Remove(pawn.story.traits.GetTrait(xxx.rapist));
//Log.Message(xxx.get_pawnname(pawn) + " BadlyBroken, switch rapist -> masochist");
}
addedTrait = new Trait(xxx.masochist);
pawn.story.traits.GainTrait(addedTrait);
//Log.Message(xxx.get_pawnname(pawn) + " BadlyBroken, not masochist, adding masochist trait");
pawn.needs.mood.thoughts.memories.RemoveMemoriesOfDef(got_raped);
pawn.needs.mood.thoughts.memories.RemoveMemoriesOfDef(got_licked);
pawn.needs.mood.thoughts.memories.RemoveMemoriesOfDef(hate_my_rapist);
pawn.needs.mood.thoughts.memories.RemoveMemoriesOfDef(allowed_me_to_get_raped);
pawn.needs.mood.thoughts.memories.RemoveMemoriesOfDef(got_anal_raped);
pawn.needs.mood.thoughts.memories.RemoveMemoriesOfDef(got_anal_raped_byfemale);
}
}
if (pawn.IsPrisonerOfColony)
{
pawn.guest.resistance = Mathf.Max(pawn.guest.resistance - 1f, 0f);
//Log.Message(xxx.get_pawnname(pawn) + " BadlyBroken, reduce prisoner resistance");
}
}
return stage > 1;
}
//add variant for eggs?
public static void processBrokenPawn(Pawn pawn, List<Trait> addedTraits)
{
// Called after rape/breed
if (pawn is null)
return;
if (xxx.is_human(pawn) && !pawn.Dead && pawn.records != null)
{
if (xxx.has_traits(pawn))
{
if (xxx.is_slime(pawn))
return;
if (!BodyIsBroken(pawn))
pawn.health.AddHediff(xxx.feelingBroken);
else
{
float brokenSeverityGain = xxx.feelingBroken.initialSeverity;
int feelingBrokenStage = pawn.health.hediffSet.GetFirstHediffOfDef(xxx.feelingBroken).CurStageIndex;
if (xxx.RoMIsActive)
if (pawn.story.traits.HasTrait(xxx.Succubus))
brokenSeverityGain *= 0.25f;
if (pawn.story.traits.HasTrait(TraitDefOf.Tough))
{
brokenSeverityGain *= 0.5f;
}
if (pawn.story.traits.HasTrait(TraitDefOf.Wimp))
{
brokenSeverityGain *= 2.0f;
}
if (pawn.story.traits.HasTrait(TraitDefOf.Nerves))
{
int currentNervesDegree = pawn.story.traits.DegreeOfTrait(TraitDefOf.Nerves);
switch (currentNervesDegree)
{
case -2:
brokenSeverityGain *= 2.0f;
break;
case -1:
brokenSeverityGain *= 1.5f;
break;
case 1:
brokenSeverityGain *= 0.5f;
break;
case 2:
brokenSeverityGain *= 0.25f;
break;
}
if (RJWSettings.AddTrait_Nerves)
{
int newNervesDegree = 0;
if (feelingBrokenStage >= 3 && currentNervesDegree > -2)
{
newNervesDegree = -2;
}
else if (feelingBrokenStage >= 2 && currentNervesDegree > -1)
{
newNervesDegree = -1;
}
if (newNervesDegree < 0)
{
pawn.story.traits.RemoveTrait(pawn.story.traits.GetTrait(TraitDefOf.Nerves));
Trait newNerves = new Trait(TraitDefOf.Nerves, newNervesDegree);
pawn.story.traits.GainTrait(newNerves);
addedTraits.Add(newNerves);
}
}
}
else if (RJWSettings.AddTrait_Nerves && feelingBrokenStage > 1)
{
pawn.story.traits.GainTrait(new Trait(TraitDefOf.Nerves, -1));
Trait nervous = new Trait(TraitDefOf.Nerves, -1);
pawn.story.traits.GainTrait(nervous);
addedTraits.Add(nervous);
}
pawn.health.hediffSet.GetFirstHediffOfDef(xxx.feelingBroken).Severity += brokenSeverityGain;
}
BadlyBroken(pawn, out Trait newMasochistTrait);
if (newMasochistTrait != null)
{
addedTraits.Add(newMasochistTrait);
}
}
}
}
//============↑======Section of processing the broken body system===============↑=============
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Helpers/AfterSexUtility.cs
|
C#
|
mit
| 24,053
|
using Verse;
using Verse.AI;
using System.Linq;
using RimWorld;
using System;
namespace rjw
{
public static class Bed_Utility
{
public static bool bed_has_at_least_two_occupants(Building_Bed bed)
{
return bed.CurOccupants.Count() >= 2;
}
public static bool in_same_bed(Pawn pawn, Pawn partner)
{
if (pawn.InBed() && partner.InBed())
{
if (pawn.CurrentBed() == partner.CurrentBed())
return true;
}
return false;
}
public static bool is_laying_down_alone(Pawn pawn)
{
if (pawn == null || !pawn.InBed()) return false;
if (pawn.CurrentBed() != null)
return !bed_has_at_least_two_occupants(pawn.CurrentBed());
return true;
}
public static IntVec3 SleepPosOfAssignedPawn(this Building_Bed bed, Pawn pawn)
{
int slotIndex = 0;
if (bed.OwnersForReading.Contains(pawn))
{
for (byte i = 0; i < bed.OwnersForReading.Count; i++)
{
if (bed.OwnersForReading[i] == pawn)
{
slotIndex = i;
}
}
}
else
{
// get random position
slotIndex = GenTicks.TicksGame % bed.SleepingSlotsCount;
}
return bed.GetSleepingSlotPos(slotIndex);
}
public static void FailOnBedNoLongerUsable(this Toil toil, TargetIndex bedIndex, Building_Bed bed)
{
if (toil == null)
{
throw new ArgumentNullException(nameof(toil));
}
toil.FailOnDespawnedOrNull(bedIndex);
toil.FailOn(bed.IsBurning);
toil.FailOn(() => HealthAIUtility.ShouldSeekMedicalRestUrgent(toil.actor));
toil.FailOn(() => toil.actor.IsColonist && !toil.actor.CurJob.ignoreForbidden && !toil.actor.Downed && bed.IsForbidden(toil.actor));
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Helpers/Bed_Utility.cs
|
C#
|
mit
| 1,633
|
//#define TESTMODE // Uncomment to enable logging.
using Verse;
using Verse.AI;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using System.Diagnostics;
using Multiplayer.API;
namespace rjw
{
/// <summary>
/// Helper for sex with animals
/// </summary>
public class BreederHelper
{
public const int max_animals_at_once = 1; // lets not forget that the purpose is procreation, not sodomy
[Conditional("TESTMODE")]
private static void DebugText(string msg)
{
ModLog.Message(msg);
}
//animal try to find best designated pawn to breed
[SyncMethod]
public static Pawn find_designated_breeder(Pawn pawn, Map m)
{
if (!DesignatorsData.rjwBreeding.Any())
return null;
DebugText("BreederHelper::find_designated_breeder( " + xxx.get_pawnname(pawn) + " ) called");
float min_fuckability = 0.10f; // Don't rape pawns with <10% fuckability
float avg_fuckability = 0f; // Average targets fuckability, choose target higher than that
var valid_targets = new Dictionary<Pawn, float>(); // Valid pawns and their fuckability
Pawn chosentarget = null; // Final target pawn
DebugText(" breeder.Faction( " + pawn.Faction + " )");
if (pawn.Faction == null)// HostileTo causes error on fresh colony(w/o name)
return null;
DebugText(" DesignatorsData.rjwBreeding.Count( " + DesignatorsData.rjwBreeding.Count() + " )");
IEnumerable<Pawn> targets = DesignatorsData.rjwBreeding.Where(x
=> x != pawn
&& xxx.is_not_dying(x)
&& xxx.can_get_raped(x)
&& !x.IsForbidden(pawn)
&& !x.Suspended
&& !x.HostileTo(pawn)
&& !(x.IsPregnant() && xxx.is_animal(x))
&& pawn.CanReserveAndReach(x, PathEndMode.Touch, Danger.Some, max_animals_at_once)
&& ((RJWSettings.bestiality_enabled && xxx.is_human(x)) || (RJWSettings.animal_on_animal_enabled && xxx.is_animal(x)))
);
DebugText(" initial targets( " + targets.Count() + " )");
var parts = pawn.GetGenitalsList();
foreach (Pawn target in targets)
{
DebugText(" Checking target " + target.kindDef.race.defName.ToLower());
if (!Pather_Utility.cells_to_target_rape(pawn, target.Position))
continue;// too far
var fuc = SexAppraiser.would_fuck(pawn, target, invert_opinion: true, ignore_gender: (Genital_Helper.has_male_bits(pawn, parts) || xxx.is_insect(pawn)));
DebugText(" target score( " + xxx.get_pawnname(pawn) + " -> " + xxx.get_pawnname(target) + " (" + fuc.ToString() + " / " + min_fuckability.ToString() + ")");
if (fuc > min_fuckability)
if (Pather_Utility.can_path_to_target(pawn, target.Position))
valid_targets.Add(target, fuc);
}
DebugText(" valid_targets( " + valid_targets.Count() + " )");
if (valid_targets.Any())
{
//avg_fuckability = valid_targets.Average(x => x.Value);
// choose pawns to fuck with above average fuckability
var valid_targetsFilteredAnimals = valid_targets.Where(x => x.Value >= avg_fuckability);
if (valid_targetsFilteredAnimals.Any())
chosentarget = valid_targetsFilteredAnimals.RandomElement().Key;
}
DebugText(" chosentarget( " + xxx.get_pawnname(chosentarget) + " )");
return chosentarget;
}
//animal or human try to find animals to breed (non designation)
//public static Pawn find_breeder_animal(Pawn pawn, Map m, bool SameRace = true)
[SyncMethod]
public static Pawn find_breeder_animal(Pawn pawn, Map m)
{
DebugText("BreederHelper::find_breeder_animal( " + xxx.get_pawnname(pawn) + " ) called");
float min_fuckability = 0.10f; // Don't rape pawns with <10% fuckability
float avg_fuckability = 0f; // Average targets fuckability, choose target higher than that
var valid_targets = new Dictionary<Pawn, float>(); // Valid pawns and their fuckability
Pawn chosentarget = null; // Final target pawn
DebugText(" m.mapPawns.AllPawnsSpawned.Count( " + m.mapPawns.AllPawnsSpawned.Count() + " )");
//Pruning initial pawn list.
IEnumerable<Pawn> targets = m.mapPawns.AllPawnsSpawned.Where(x
=> x != pawn
&& xxx.is_animal(x)
&& xxx.can_get_raped(x)
&& !x.IsForbidden(pawn)
&& !x.Suspended
&& !x.HostileTo(pawn)
&& pawn.CanReserveAndReach(x, PathEndMode.Touch, Danger.Some, max_animals_at_once)
&& ((RJWSettings.bestiality_enabled && xxx.is_human(pawn)) || (RJWSettings.animal_on_animal_enabled && xxx.is_animal(pawn)))
//&& SameRace ? pawn.kindDef.race == x.kindDef.race : true
);
DebugText(" initial targets( " + targets.Count() + " )");
if (targets.Any())
{
var parts = pawn.GetGenitalsList();
//filter pawns for female, who can fuck her
//not sure if faction check should be but w/e
if (!Genital_Helper.has_male_bits(pawn, parts) && (Genital_Helper.has_vagina(pawn, parts) || Genital_Helper.has_anus(pawn)))
{
targets = targets.Where(x => xxx.can_fuck(x) && x.Faction == pawn.Faction);
}
//for humans, animals dont have need - always = 3f
//if not horny, seek only targets with safe temp
if (xxx.need_some_sex(pawn) < 3.0f)
{
targets = targets.Where(x => pawn.CanReach(x, PathEndMode.Touch, Danger.None));
}
//Used for interspecies animal-on-animal.
//Animals will only go for targets they can see.
if (xxx.is_animal(pawn))
{
targets = targets.Where(x => pawn.CanSee(x) && pawn.def.defName != x.def.defName);
}
else
{
// Pickier about the targets if the pawn has no prior experience.
if (pawn.records.GetValue(xxx.CountOfSexWithAnimals) < 3 && !xxx.is_zoophile(pawn))
{
min_fuckability *= 2f;
}
if (xxx.is_frustrated(pawn))
{ // Less picky when frustrated...
min_fuckability *= 0.6f;
}
else if (!xxx.is_hornyorfrustrated(pawn))
{ // ...and far more picky when satisfied.
min_fuckability *= 2.5f;
}
}
}
if (!targets.Any())
{
DebugText(" valid_targets( " + targets.Count() + " )");
return null; //None found.
}
foreach (Pawn target in targets)
{
DebugText(" Checking target " + target.kindDef.race.defName.ToLower());
if (!Pather_Utility.cells_to_target_rape(pawn, target.Position))
continue;// too far
float fuc = SexAppraiser.would_fuck_animal(pawn, target); // 0.0 to ~3.0, orientation checks etc.
DebugText(" target score( " + xxx.get_pawnname(pawn) + " -> " + xxx.get_pawnname(target) + " (" + fuc.ToString() + " / " + min_fuckability.ToString() + ")");
if (fuc > min_fuckability)
if (Pather_Utility.can_path_to_target(pawn, target.Position))
valid_targets.Add(target, fuc);
}
DebugText(" valid_targets( " + valid_targets.Count() + " )");
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
if (valid_targets.Any())
{
avg_fuckability = valid_targets.Average(x => x.Value);
// choose pawns to fuck with above average fuckability
var valid_targetsFilteredAnimals = valid_targets.Where(x => x.Value >= avg_fuckability);
if (valid_targetsFilteredAnimals.Any())
chosentarget = valid_targetsFilteredAnimals.RandomElement().Key;
}
DebugText(" chosentarget( " + xxx.get_pawnname(chosentarget) + " )");
return chosentarget;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Helpers/Breeder_Helper.cs
|
C#
|
mit
| 7,288
|
using Verse;
using Verse.AI;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Multiplayer.API;
namespace rjw
{
/// <summary>
/// Helper for sex with (humanlikes)
/// </summary>
public class CasualSex_Helper
{
public static readonly HashSet<string> quickieAllowedJobs = new HashSet<string>(DefDatabase<StringListDef>.GetNamed("QuickieInterruptibleJobs").strings);
public static bool CanHaveSex(Pawn target)
{
return xxx.can_fuck(target) || xxx.can_be_fucked(target);
}
[SyncMethod]
public static bool roll_to_skip(Pawn pawn, Pawn target, out float fuckability)
{
fuckability = SexAppraiser.would_fuck(pawn, target); // 0.0 to 1.0
if (fuckability < RJWHookupSettings.MinimumFuckabilityToHookup)
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" roll_to_skip(I, {xxx.get_pawnname(pawn)} won't fuck {xxx.get_pawnname(target)}), ({fuckability})");
return false;
}
float reciprocity = xxx.is_animal(target) ? 1.0f : SexAppraiser.would_fuck(target, pawn);
if (reciprocity < RJWHookupSettings.MinimumFuckabilityToHookup)
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" roll_to_skip({xxx.get_pawnname(target)} won't fuck me, {xxx.get_pawnname(pawn)}), ({reciprocity})");
return false;
}
float chance_to_skip = 0.9f - 0.7f * fuckability;
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
return Rand.Value < chance_to_skip;
}
[SyncMethod]
public static Pawn find_partner(Pawn pawn, Map map, bool bedsex = false)
{
string pawnName = xxx.get_pawnname(pawn);
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({pawnName}): starting.");
bool pawnIsNympho = xxx.is_nympho(pawn);
bool pawnCanPickAnyone = RJWSettings.WildMode;// || (pawnIsNympho && RJWHookupSettings.NymphosCanPickAnyone);
bool pawnCanPickAnimals = (pawnCanPickAnyone || xxx.is_zoophile(pawn)) && RJWSettings.bestiality_enabled;
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({pawnName}): nympho:{pawnIsNympho}, ignores rules:{pawnCanPickAnyone}, zoo:{pawnCanPickAnimals}");
if (!RJWHookupSettings.ColonistsCanHookup && pawn.IsFreeColonist && !pawnCanPickAnyone)
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({pawnName}): is a colonist and colonist hookups are disabled in mod settings");
return null;
}
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
// Check AllPawns, not just colonists, to include guests.
List<Pawn> targets = map.mapPawns.AllPawns.Where(x
=> x != pawn
&& ((!bedsex && !x.InBed()) || (bedsex && (Bed_Utility.is_laying_down_alone(x) || Bed_Utility.in_same_bed(x, pawn))))
&& !x.IsForbidden(pawn)
&& xxx.IsTargetPawnOkay(x)
&& CanHaveSex(x)
&& x.Map == pawn.Map
&& !x.HostileTo(pawn)
//&& ((pawnCanPickAnimals && xxx.is_animal(x)) || !xxx.is_animal(x))
&& !xxx.is_animal(x)
).ToList();
if (!targets.Any())
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({pawnName}): no eligible targets");
return null;
}
// HippieMode means: everyone is allowed to have sex with everyone else ("free love")
// - no prioritization of partners
// - not necessary to be horny
// - never cheating
// -> just pick a partner
if (!RJWSettings.HippieMode)
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({pawnName}): considering {targets.Count} targets");
// find lover/partner on same map
List<Pawn> partners = targets.Where(x
=> pawn.relations.DirectRelationExists(PawnRelationDefOf.Lover, x)
|| pawn.relations.DirectRelationExists(PawnRelationDefOf.Fiance, x)
|| pawn.relations.DirectRelationExists(PawnRelationDefOf.Spouse, x)
).ToList();
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({pawnName}): considering {partners.Count} partners");
if (partners.Any())
{
partners.Shuffle(); //Randomize order.
foreach (Pawn target in partners)
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({pawnName}): checking lover {xxx.get_pawnname(target)}");
//interruptible jobs
if (!bedsex && target.jobs?.curJob != null &&
(target.jobs.curJob.playerForced ||
!quickieAllowedJobs.Contains(target.jobs.curJob.def.defName)
))
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_pawn_to_fuck({pawnName}): lover has important job ({target.jobs.curJob.def}), skipping");
continue;
}
if (Pather_Utility.cells_to_target_casual(pawn, target.Position)
&& pawn.CanReserveAndReach(target, PathEndMode.OnCell, Danger.Some, 1, 0)
&& target.CanReserve(pawn, 1, 0)
&& SexAppraiser.would_fuck(pawn, target) > 0.1f
&& SexAppraiser.would_fuck(target, pawn) > 0.1f)
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({pawnName}): banging lover {xxx.get_pawnname(target)}");
return target;
}
}
}
// No lovers around... see if the pawn fancies a hookup. Nymphos and frustrated pawns always do!
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({pawnName}): no partners available. checking canHookup");
bool canHookup = pawnIsNympho || pawnCanPickAnyone || xxx.is_frustrated(pawn) || (xxx.is_horny(pawn) && Rand.Value < RJWHookupSettings.HookupChanceForNonNymphos);
if (!canHookup)
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({pawnName}): no hookup today");
return null;
}
// No cheating from casual hookups... would probably make colony relationship management too annoying
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({pawnName}): checking hookupWouldBeCheating");
bool hookupWouldBeCheating = xxx.HasNonPolyPartner(pawn);
if (hookupWouldBeCheating)
{
if (RJWHookupSettings.NymphosCanCheat && pawnIsNympho && xxx.is_frustrated(pawn))
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({pawnName}): I'm a nympho and I'm so frustrated that I'm going to cheat");
// No return here so they continue searching for hookup
}
else if (pawn.health.hediffSet.HasHediff(HediffDef.Named("AlcoholHigh")))
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({pawnName}): I want to bang and im too drunk to care if its cheating");
}
else
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({pawnName}): I want to bang but that's cheating");
return null;
}
}
}
Pawn best_fuckee = FindBestPartner(pawn, targets, pawnCanPickAnyone, pawnIsNympho);
return best_fuckee;
}
/// <summary> Checks all of our potential partners to see if anyone's eligible, returning the most attractive and convenient one. </summary>
public static Pawn FindBestPartner(Pawn pawn, List<Pawn> targets, bool pawnCanPickAnyone, bool pawnIsNympho)
{
string pawnName = xxx.get_pawnname(pawn);
Pawn best_fuckee = null;
float best_fuckability_score = 0;
foreach (Pawn targetPawn in targets)
{
if (targetPawn.relations == null) // probably droids or who knows what modded abomination
continue;
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" FindBestPartner({pawnName}): checking hookup {xxx.get_pawnname(targetPawn)}");
// Check to see if the mod settings for hookups allow this pairing
if (!pawnCanPickAnyone && !HookupAllowedViaSettings(pawn, targetPawn))
continue;
//interruptible jobs
if (targetPawn.jobs?.curJob != null &&
(targetPawn.jobs.curJob.playerForced ||
!quickieAllowedJobs.Contains(targetPawn.jobs.curJob.def.defName)
))
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" FindBestPartner({pawnName}): targetPawn has important job ({targetPawn.jobs.curJob.def}, playerForced: {targetPawn.jobs.curJob.playerForced}), skipping");
continue;
}
// Check for homewrecking (banging a pawn who's in a relationship)
if (!xxx.is_animal(targetPawn) &&
!RJWSettings.HippieMode &&
xxx.HasNonPolyPartner(targetPawn))
{
if (RJWHookupSettings.NymphosCanHomewreck && pawnIsNympho && xxx.is_frustrated(pawn))
{
// Hookup allowed... rip colony mood
}
else if (RJWHookupSettings.NymphosCanHomewreckReverse && xxx.is_nympho(targetPawn) && xxx.is_frustrated(targetPawn))
{
// Hookup allowed... rip colony mood
}
else if (!pawn.health.hediffSet.HasHediff(HediffDef.Named("AlcoholHigh")))
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" FindBestPartner({pawnName}): not hooking up with {xxx.get_pawnname(targetPawn)} to avoid homewrecking");
continue;
}
}
// If the pawn has had sex recently and isn't horny right now, skip them.
if (!SexUtility.ReadyForLovin(targetPawn) && !xxx.is_hornyorfrustrated(targetPawn))
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" FindBestPartner({pawnName}): hookup {xxx.get_pawnname(targetPawn)} isn't ready for lovin'");
continue;
}
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" FindBestPartner({pawnName}): hookup {xxx.get_pawnname(targetPawn)} is sufficiently single");
if (!xxx.is_animal(targetPawn))
{
float relations = pawn.relations.OpinionOf(targetPawn);
if (relations < RJWHookupSettings.MinimumRelationshipToHookup)
{
if (!(relations > 0 && xxx.is_nympho(pawn)))
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" FindBestPartner({pawnName}): hookup {xxx.get_pawnname(targetPawn)}, i don't like them:({relations})");
continue;
}
}
relations = targetPawn.relations.OpinionOf(pawn);
if (relations < RJWHookupSettings.MinimumRelationshipToHookup)
{
if (!(relations > 0 && xxx.is_nympho(targetPawn)))
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" FindBestPartner({pawnName}): hookup {xxx.get_pawnname(targetPawn)}, don't like me:({relations})");
continue;
}
}
float attraction = pawn.relations.SecondaryRomanceChanceFactor(targetPawn);
if (attraction < RJWHookupSettings.MinimumAttractivenessToHookup)
{
if (!(attraction > 0 && xxx.is_nympho(pawn)))
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" FindBestPartner({pawnName}): hookup {xxx.get_pawnname(targetPawn)}, i don't find them attractive:({attraction})");
continue;
}
}
attraction = targetPawn.relations.SecondaryRomanceChanceFactor(pawn);
if (attraction < RJWHookupSettings.MinimumAttractivenessToHookup)
{
if (!(attraction > 0 && xxx.is_nympho(targetPawn)))
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" FindBestPartner({pawnName}): hookup {xxx.get_pawnname(targetPawn)}, doesn't find me attractive:({attraction})");
continue;
}
}
}
// Check to see if the two pawns are willing to bang, and if so remember how much attractive we find them
float fuckability = 0f;
if (pawn.CanReserveAndReach(targetPawn, PathEndMode.OnCell, Danger.Some, 1, 0) &&
targetPawn.CanReserve(pawn, 1, 0) &&
roll_to_skip(pawn, targetPawn, out fuckability)) // do NOT check pawnIgnoresRules here - these checks, particularly roll_to_skip, are critical
{
float dis = pawn.Position.DistanceTo(targetPawn.Position);
if (dis <= 4)
{
// Right next to me (in my bed)? You'll do.
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" FindBestPartner({pawnName}): hookup {xxx.get_pawnname(targetPawn)} is right next to me. we'll bang, ok?");
best_fuckability_score = 1.0e6f;
best_fuckee = targetPawn;
break;
}
else if (dis > RJWSettings.maxDistanceCellsCasual)
{
// too far
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" FindBestPartner({pawnName}): hookup {xxx.get_pawnname(targetPawn)} is too far... distance:{dis} max:{RJWSettings.maxDistanceCellsCasual}");
continue;
}
else
{
// scaling fuckability by distance may give us more varied results and give the less attractive folks a chance
float fuckability_score = fuckability / GenMath.Sqrt(GenMath.Sqrt(dis));
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" FindBestPartner({pawnName}): hookup {xxx.get_pawnname(targetPawn)} is totally bangable. attraction: {fuckability}, score:{fuckability_score}");
if (fuckability_score > best_fuckability_score)
{
best_fuckee = targetPawn;
best_fuckability_score = fuckability_score;
}
}
}
}
if (best_fuckee == null)
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" FindBestPartner({pawnName}): couldn't find anyone to bang");
}
else
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" FindBestPartner({pawnName}): found rando {xxx.get_pawnname(best_fuckee)} with score {best_fuckability_score}");
}
return best_fuckee;
}
/// <summary> Checks to see if the mod settings allow the two pawns to hookup. </summary>
public static bool HookupAllowedViaSettings(Pawn pawn, Pawn targetPawn)
{
// Can prisoners hook up?
if (pawn.IsPrisonerOfColony || pawn.IsPrisoner || xxx.is_slave(pawn))
{
if (!RJWHookupSettings.PrisonersCanHookupWithNonPrisoner && !(targetPawn.IsPrisonerOfColony || targetPawn.IsPrisoner || xxx.is_slave(targetPawn)))
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({xxx.get_pawnname(pawn)}): not hooking up with {xxx.get_pawnname(targetPawn)} due to mod setting PrisonersCanHookupWithNonPrisoner");
return false;
}
if (!RJWHookupSettings.PrisonersCanHookupWithPrisoner && (targetPawn.IsPrisonerOfColony || targetPawn.IsPrisoner || xxx.is_slave(targetPawn)))
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({xxx.get_pawnname(pawn)}): not hooking up with {xxx.get_pawnname(targetPawn)} due to mod setting PrisonersCanHookupWithPrisoner");
return false;
}
}
else
{
// Can non prisoners hook up with prisoners?
if (!RJWHookupSettings.CanHookupWithPrisoner && (targetPawn.IsPrisonerOfColony || targetPawn.IsPrisoner || xxx.is_slave(targetPawn)))
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({xxx.get_pawnname(pawn)}): not hooking up with {xxx.get_pawnname(targetPawn)} due to mod setting CanHookupWithPrisoner");
return false;
}
}
// Can slave hook up?
//if (xxx.is_slave(pawn))
//{
// if (!RJWHookupSettings.SlaveCanHookup)
// {
// if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({xxx.get_pawnname(pawn)}): not hooking up with {xxx.get_pawnname(targetPawn)} due to mod setting SlaveCanHookup");
// return false;
// }
//}
// Can colonist hook up with visitors?
if (pawn.IsFreeColonist && !xxx.is_slave(pawn))
{
if (!RJWHookupSettings.ColonistsCanHookupWithVisitor && targetPawn.Faction != Faction.OfPlayer && !targetPawn.IsPrisonerOfColony)
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({xxx.get_pawnname(pawn)}): not hooking up with {xxx.get_pawnname(targetPawn)} due to mod setting ColonistsCanHookupWithVisitor");
return false;
}
}
// Can visitors hook up?
if (pawn.Faction != Faction.OfPlayer && !pawn.IsPrisonerOfColony)
{
// visitors vs colonist
if (!RJWHookupSettings.VisitorsCanHookupWithColonists && targetPawn.IsColonist)
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({xxx.get_pawnname(pawn)}): not hooking up with {xxx.get_pawnname(targetPawn)} due to mod setting VisitorsCanHookupWithColonists");
return false;
}
// visitors vs visitors
if (!RJWHookupSettings.VisitorsCanHookupWithVisitors && targetPawn.Faction != Faction.OfPlayer)
{
if (RJWSettings.DebugLogJoinInBed) ModLog.Message($" find_partner({xxx.get_pawnname(pawn)}): not hooking up with {xxx.get_pawnname(targetPawn)} due to mod setting VisitorsCanHookupWithVisitors");
return false;
}
}
// TODO: Not sure if this handles all the pawn-on-animal cases.
return true;
}
[SyncMethod]
public static IntVec3 FindSexLocation(Pawn pawn, Pawn partner = null)
{
IntVec3 position = pawn.Position;
int bestPosition = -100;
IntVec3 cell = pawn.Position;
int maxDistance = 40;
FloatRange temperature = pawn.ComfortableTemperatureRange();
List<Pawn> all_pawns = pawn.Map.mapPawns.AllPawnsSpawned.Where(x
=> x.Position.DistanceTo(pawn.Position) < 100
&& xxx.is_human(x)
&& x != pawn
&& x != partner
).ToList();
bool is_somnophile = xxx.has_quirk(pawn, "Somnophile");
bool is_exhibitionist = xxx.has_quirk(pawn, "Exhibitionist");
//ModLog.Message(" Pawn is " + xxx.get_pawnname(pawn) + ", current cell is " + cell);
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
List<IntVec3> random_cells = new List<IntVec3>();
Dictionary<int, int> random_cells_rooms_doors = new Dictionary<int, int>();
for (int loop = 0; loop < 50; ++loop)
{
random_cells.Add(position + IntVec3.FromVector3(Vector3Utility.HorizontalVectorFromAngle(Rand.Range(0, 360)) * Rand.RangeInclusive(1, maxDistance)));
}
random_cells = random_cells.Where(x
=> x.Standable(pawn.Map)
&& x.InAllowedArea(pawn)
&& x.GetDangerFor(pawn, pawn.Map) != Danger.Deadly
&& !x.ContainsTrap(pawn.Map)
&& !x.ContainsStaticFire(pawn.Map)
).Distinct().ToList();
//ModLog.Message(" Found " + random_cells.Count + " valid cells.");
foreach (var rcell in random_cells)
{
var rooom = rcell.GetRoom(pawn.Map);
if (!random_cells_rooms_doors.ContainsKey(rooom.ID) && !rooom.PsychologicallyOutdoors)
random_cells_rooms_doors.Add(rooom.ID, rooom.ContainedAndAdjacentThings.Count(
x => x.def.IsDoor
&& x.def.holdsRoof && x.def.blockLight)); //dubs hyg toilets stall doors(false,false)?
}
foreach (IntVec3 random_cell in random_cells)
{
if (!Pather_Utility.cells_to_target_casual(pawn, random_cell))
continue;// too far
int score = 0;
Room room = random_cell.GetRoom(pawn.Map);
bool might_be_seen = MightBeSeen(all_pawns, random_cell, pawn, partner);
if (is_exhibitionist)
{
if (might_be_seen)
score += 5;
else
score -= 10;
}
else
{
if (might_be_seen)
score -= 30;
}
if (partner == null && is_somnophile) // Fap while Watching someone sleep. Not creepy at all!
{
if (all_pawns.Any(x
=> !x.Awake()
&& x.Position.DistanceTo(random_cell) < 6
&& GenSight.LineOfSight(random_cell, x.Position, pawn.Map)
))
score += 50;
}
if (random_cell.GetTemperature(pawn.Map) > temperature.min && random_cell.GetTemperature(pawn.Map) < temperature.max)
score += 20;
else
score -= 20;
if (random_cell.Roofed(pawn.Map))
score += 5;
if (random_cell.HasEatSurface(pawn.Map))
score += 5; // Hide in vegetation.
if (random_cell.GetDangerFor(pawn, pawn.Map) == Danger.Some)
score -= 25;
else if (random_cell.GetDangerFor(pawn, pawn.Map) == Danger.None)
score += 5;
if (random_cell.GetTerrain(pawn.Map) == TerrainDefOf.WaterShallow ||
random_cell.GetTerrain(pawn.Map) == TerrainDefOf.WaterMovingShallow ||
random_cell.GetTerrain(pawn.Map) == TerrainDefOf.WaterOceanShallow)
score -= 20;
if (random_cell.GetThingList(pawn.Map).Any(x => x.def.IsWithinCategory(ThingCategoryDefOf.Corpses)))
if (xxx.is_necrophiliac(pawn))
score += 20;
else
score -= 20;
if (random_cell.GetThingList(pawn.Map).Any(x => x.def.IsWithinCategory(ThingCategoryDefOf.Foods)))
score -= 10;
if (room == pawn.Position.GetRoom(pawn.MapHeld))
score -= 10;
if (room.PsychologicallyOutdoors)
score += 5;
if (room.IsHuge)
score -= 5;
if (room.ContainedBeds.Any())
{
score += 5;
if (room.ContainedBeds.Any(x => x.Position == random_cell))
score += 5;
}
if (!room.Owners.Any())
score += 10;
else if (room.Owners.Contains(pawn))
score += 20;
if (room.IsDoorway && !is_exhibitionist)
score -= 100;
if (room.Role == RoomRoleDefOf.Bedroom)
score += 10;
else if (room.Role == RoomRoleDefOf.Barracks || room.Role == RoomRoleDefOf.PrisonBarracks || room.Role == RoomRoleDefOf.PrisonCell
|| room.Role == RoomRoleDefOf.Laboratory || room.Role == RoomRoleDefOf.RecRoom
|| room.Role == RoomRoleDefOf.DiningRoom || room.Role == RoomRoleDefOf.Hospital
)
if (is_exhibitionist)
score += 10;
else
score -= 5;
if (room.GetStat(RoomStatDefOf.Cleanliness) < 0.01f)
score -= 5;
if (room.GetStat(RoomStatDefOf.GraveVisitingJoyGainFactor) > 0.1f)
if (xxx.is_necrophiliac(pawn))
{
score += 5;
}
else
{
score -= 5;
}
var doors = random_cells_rooms_doors.TryGetValue(room.ID);
if (doors > 1)
if (is_exhibitionist)
{
score += 2 * doors;
}
else
{
score -= 5 * doors;
}
if (score <= bestPosition) continue;
bestPosition = score;
cell = random_cell;
}
return cell;
//ModLog.Message(" Best cell is " + cell);
}
public static bool MightBeSeen(List<Pawn> otherPawns, IntVec3 cell, Pawn pawn, Pawn partner = null)
{
return otherPawns.Any(x
=> x != partner
&& x.Awake()
&& x.Position.DistanceTo(cell) < 50
&& GenSight.LineOfSight(x.Position, cell, pawn.Map)
);
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Helpers/CasualSex_Helper.cs
|
C#
|
mit
| 21,726
|
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Verse;
namespace rjw
{
//TODO: this needs rewrite to account reverse and group sex
public class CondomUtility
{
public static readonly RecordDef CountOfCondomsUsed = DefDatabase<RecordDef>.GetNamed("CountOfCondomsUsed");
public static readonly ThoughtDef SexWithCondom = DefDatabase<ThoughtDef>.GetNamed("SexWithCondom");
public static readonly ThingDef Condom = DefDatabase<ThingDef>.GetNamedSilentFail("Condom");
public static readonly ThingDef UsedCondom = DefDatabase<ThingDef>.GetNamedSilentFail("UsedCondom");
/// <summary>
/// Returns whether it was able to remove one condom from the pawn
/// </summary>
/// <param name="pawn"></param>
/// <returns></returns>
public static bool TryUseCondom(Pawn pawn)
{
if (Condom == null) return false;
if (!xxx.is_human(pawn)) return false;
if (xxx.has_quirk(pawn, "ImpregnationFetish")) return false;
List<Thing> pawn_condoms = pawn.inventory.innerContainer.ToList().FindAll(obj => obj.def == Condom);
if (pawn_condoms.Any())
{
var stack = pawn_condoms.Pop();
stack.stackCount--;
if (stack.stackCount <= 0)
{
stack.Destroy();
}
return true;
}
return false;
}
/// <summary>
/// Applies the effects of having used a condom.
/// </summary>
/// <param name="pawn"></param>
public static void useCondom(Pawn pawn)
{
if (Condom == null) return;
if (!xxx.is_human(pawn)) return;
pawn.records.Increment(CountOfCondomsUsed);
pawn.needs.mood.thoughts.memories.TryGainMemory(SexWithCondom);
}
/// <summary>
/// Try to get condom near sex location
/// </summary>
/// <param name="pawn"></param>
public static void GetCondomFromRoom(Pawn pawn)
{
if (Condom == null) return;
if (!xxx.is_human(pawn)) return;
if (xxx.has_quirk(pawn, "ImpregnationFetish")) return;
List<Thing> condoms_in_room = pawn.GetRoom().ContainedAndAdjacentThings.FindAll(obj => obj.def == Condom && pawn.Position.DistanceTo(obj.Position) < 10);
//List<Thing> condoms_in_room = pawn.ownership.OwnedRoom?.ContainedAndAdjacentThings.FindAll(obj => obj.def == Condom);
if (condoms_in_room.Any())
{
pawn.inventory.innerContainer.TryAdd(condoms_in_room.Pop().SplitOff(1));
}
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Helpers/CondomUtility.cs
|
C#
|
mit
| 2,310
|
using System.Collections.Generic;
using RimWorld;
using Verse;
using System.Linq;
using System;
//This one is helper lib for handling all the trans surgery.
namespace rjw
{
public static class GenderHelper
{
public enum Sex { male, female, trap, futa, none }//there is Verse,Gender but it is shit
//These would probably be better packed in some enumerable structure, so that functions below weren't if-trees, but I don't know C#, sry.
public static HediffDef was_boy = HediffDef.Named("hediff_was_boy");
public static HediffDef was_girl = HediffDef.Named("hediff_was_girl");
public static HediffDef was_futa = HediffDef.Named("hediff_was_futa");
public static HediffDef was_trap = HediffDef.Named("hediff_was_trap");
static List<HediffDef> old_sex_list = new List<HediffDef> { was_boy, was_girl, was_futa, was_trap };
static Dictionary<Sex, HediffDef> sex_to_old_sex = new Dictionary<Sex, HediffDef>() {
{Sex.male, was_boy },{Sex.female, was_girl},{Sex.trap, was_trap},{Sex.futa, was_futa}
};
static Dictionary<HediffDef, Sex> old_sex_to_sex = sex_to_old_sex.ToDictionary(x => x.Value, x => x.Key);
public static HediffDef m2t = HediffDef.Named("hediff_male2trap");
public static HediffDef m2f = HediffDef.Named("hediff_male2female");
public static HediffDef m2h = HediffDef.Named("hediff_male2futa");
public static HediffDef f2t = HediffDef.Named("hediff_female2trap");
public static HediffDef f2m = HediffDef.Named("hediff_female2male");
public static HediffDef f2h = HediffDef.Named("hediff_female2futa");
public static HediffDef h2t = HediffDef.Named("hediff_futa2trap");
public static HediffDef h2m = HediffDef.Named("hediff_futa2male");
public static HediffDef h2f = HediffDef.Named("hediff_futa2female");
public static HediffDef t2h = HediffDef.Named("hediff_trap2futa");
public static HediffDef t2m = HediffDef.Named("hediff_trap2male");
public static HediffDef t2f = HediffDef.Named("hediff_trap2female");
static List<HediffDef> SexChangeThoughts = new List<HediffDef> { m2t, m2f, m2h, f2t, f2m, f2h, h2t, h2m, h2f };
public static Sex GetSex(Pawn pawn)
{
var parts = pawn.GetGenitalsList();
bool has_vagina = Genital_Helper.has_vagina(pawn, parts);
bool has_penis = Genital_Helper.has_male_bits(pawn, parts);
bool has_breasts = Genital_Helper.has_breasts(pawn);
bool has_male_breasts = Genital_Helper.has_male_breasts(pawn);
//BodyType? bt = pawn.story?.bodyType;
//if (bt != null)
// bt = BodyType.Undefined;
Sex res;
if (has_vagina && !has_penis)
res = Sex.female;
else if (has_vagina && has_penis)
res = Sex.futa;
else if (has_penis && has_breasts && !has_male_breasts)
res = Sex.trap;
else if (has_penis) //probably should change this later
res = Sex.male;
else if (pawn.gender == Gender.Male)
res = Sex.male;
else if (pawn.gender == Gender.Female)
res = Sex.female;
else
res = Sex.none;
return res;
}
/// <summary>
/// Checks to see if two sexes can do hetero stuff.
/// </summary>
public static bool CanBeHetero(Sex pawnSex, Sex partnerSex) => (pawnSex, partnerSex) switch
{
// Get un-gendered out of the possibilities.
(Sex.none, _) or (_, Sex.none) => false,
// Futa can be straight towards anything remaining.
(Sex.futa, _) or (_, Sex.futa) => true,
// Female vs male.
(Sex.female, Sex.male or Sex.trap) => true,
// Male vs female.
(Sex.male or Sex.trap, Sex.female) => true,
// Otherwise, nah.
_ => false
};
/// <summary>
/// <para>Checks to see if two pawns can do hetero stuff.</para>
/// <para>If you are also going to check `CanBeHomo`, get the sexes first.</para>
/// </summary>
public static bool CanBeHetero(Pawn pawn, Pawn partner) =>
CanBeHetero(GetSex(pawn), GetSex(partner));
/// <summary>
/// Checks to see if two sexes can do homo stuff.
/// </summary>
public static bool CanBeHomo(Sex pawnSex, Sex partnerSex) => (pawnSex, partnerSex) switch
{
// Get un-gendered out of the possibilities.
(Sex.none, _) or (_, Sex.none) => false,
// Futa can be gay towards anything remaining.
(Sex.futa, _) or (_, Sex.futa) => true,
// Male vs male.
(Sex.male or Sex.trap, Sex.male or Sex.trap) => true,
// Female vs female.
(Sex.female, Sex.female) => true,
// Otherwise, nah.
_ => false
};
/// <summary>
/// <para>Checks to see if two pawns can do homo stuff.</para>
/// <para>If you are also going to check `CanBeHetero`, get the sexes first.</para>
/// </summary>
public static bool CanBeHomo(Pawn pawn, Pawn partner) =>
CanBeHomo(GetSex(pawn), GetSex(partner));
/*
public static HediffDef GetReactionHediff(Sex before, Sex after)
{
if (before == after)
return null;
if (before == Sex.male)
return (after == Sex.female) ? m2f : m2t;
else if (before == Sex.female)
{
if (after == Sex.male)
return f2m;
else if (after == Sex.trap)
return f2t;
else if (after == Sex.futa)
return f2h;
else
return null;
}
else if (before == Sex.futa && (after == Sex.female || after == Sex.none))
return h2f;
else//trap to anything, futa to trap; probably won't even be reached ever
return null;
}
*/
//TODO: fix reactions
public static HediffDef GetReactionHediff(Sex before, Sex after)
{
if (before == after)
return null;
else if (before == Sex.male)
{
if (after == Sex.female)
return m2f;
else if (after == Sex.trap)
return m2t;
else if (after == Sex.futa)
return m2h;
else
return null;
}
else if (before == Sex.female)
{
if (after == Sex.male)
return f2m;
else if (after == Sex.trap)
return f2t;
else if (after == Sex.futa)
return f2h;
else
return null;
}
else if (before == Sex.futa)
{
if (after == Sex.male)
return h2m;
else if (after == Sex.female)
return h2f;
else if (after == Sex.trap)
return h2t;
else
return null;
}
else if (before == Sex.trap)
{
if (after == Sex.male)
return t2m;
else if (after == Sex.female)
return t2f;
else if (after == Sex.futa)
return t2h;
else
return null;
}
else//unicorns?
return null;
}
public static bool WasThisBefore(Pawn pawn, Sex after)
{
Hediff was = null;
switch (after)
{
case Sex.male:
was = pawn.health.hediffSet.GetFirstHediffOfDef(was_boy);
break;
case Sex.female:
was = pawn.health.hediffSet.GetFirstHediffOfDef(was_girl);
break;
case Sex.trap:
was = pawn.health.hediffSet.GetFirstHediffOfDef(was_trap);
break;
case Sex.futa:
was = pawn.health.hediffSet.GetFirstHediffOfDef(was_futa);
break;
}
return (was != null) ? true : false;
}
//Get one of the sexes that were on this pawn before
public static Sex GetOriginalSex(Pawn pawn)
{
foreach (var os in old_sex_list)
{
if (pawn.health.hediffSet.GetFirstHediffOfDef(os) != null)
return old_sex_to_sex[os];
}
return Sex.none;//it shouldnt reach here though
}
public static Hediff IsInDenial(Pawn pawn)
{
Hediff res = null;
foreach (var h in SexChangeThoughts)
{
res = pawn.health.hediffSet.GetFirstHediffOfDef(h);
if (res != null)
break;
}
return res;
}
//roll how much gender fluid the pawn is.
//In ideal world this would actually take into account from where to where transition is moving and so on.
//Same applies to the thought hediffs themselves, but we get what we can get now
static float RollSexChangeSeverity(Pawn pawn)
{
float res = 1;
if (xxx.is_bisexual(pawn))
res *= 0.5f;
if (pawn.story != null && (pawn.story.bodyType == BodyTypeDefOf.Thin || pawn.story.bodyType == BodyTypeDefOf.Fat))
res *= 0.8f;
if (!pawn.ageTracker.CurLifeStage.reproductive)
res *= 0.2f;
else
res *= AgeConfigDef.Instance.rigidityByAge.Evaluate(SexUtility.ScaleToHumanAge(pawn));
return res;
}
//Quick hack to check if hediff is adding happiness
static bool is_happy(this Hediff thought)
{
return thought.CurStageIndex == 0;
}
static void make_happy(this Hediff thought)
{
if (thought.Severity > 0.24f)
thought.Severity = 0.24f;//this is currently max severity for hediff, that is associated with positive mood
}
static void mix_thoughts(this Hediff newer, Hediff older)
{
newer.Severity = (newer.Severity + older.Severity) / 2f;
}
static void GiveThought(Pawn pawn, HediffDef thought, bool happy = false, Hediff old_thought = null)
{
pawn.health.AddHediff(thought);
var new_thought = pawn.health.hediffSet.GetFirstHediffOfDef(thought);
if (happy)
{
new_thought.make_happy();
return;
}
new_thought.Severity = RollSexChangeSeverity(pawn);
if (old_thought != null)
{
new_thought.Severity = (new_thought.Severity + old_thought.Severity) / 2f;
}
}
/// <summary>
/// Executes action and then changes sex if necessary.
/// </summary>
public static void ChangeSex(Pawn pawn, Action action)
{
var before = GetSex(pawn);
action();
var after = GetSex(pawn);
try
{
ChangeSex(pawn, before, after);
}
catch
{
ModLog.Error("ChangeSex error: " + xxx.get_pawnname(pawn));
}
}
public static void ChangeSex(Pawn pawn, Sex oldsex, Sex newsex)
{
if (CompRJW.Comp(pawn) == null)
{
ModLog.Warning(" ChangeSex error: CompRJW.Comp(pawn) should not be null");
return;
}
//Log.Message("ChangeSex 1" + oldsex);
//Log.Message("ChangeSex 2" + newsex);
// Wakeup pawn sexuality if it has none before
if (!(CompRJW.Comp(pawn).orientation == Orientation.Asexual || CompRJW.Comp(pawn).orientation == Orientation.None))
if (oldsex == newsex)
return;
//update ingame genders
if (newsex == Sex.none)
return;
else if (newsex == Sex.male || newsex == Sex.trap)
pawn.gender = Gender.Male;
else
pawn.gender = Gender.Female;
// Sexualize pawn after installation of parts if it was "not interested in".
if (oldsex == Sex.none || CompRJW.Comp(pawn).orientation == Orientation.Asexual || CompRJW.Comp(pawn).orientation == Orientation.None)
if (pawn.kindDef.race.defName.ToLower().Contains("droid") && !AndroidsCompatibility.IsAndroid(pawn))
{
//basic droids,they don't care
return;
}
else
{
CompRJW.Comp(pawn).Sexualize(pawn, true);
}
var old_thought = IsInDenial(pawn);
var react = GetReactionHediff(oldsex, newsex);
if (old_thought == null || old_thought.is_happy())//pawn either liked it or got used already
{
//Log.Message("ChangeSex 1 old_thought" + old_thought);
//Log.Message("ChangeSex 1 react" + react);
if (react != null)
{
// IsDesignatedHero() crash world gen when adding rjw artificial tech hediffs to royalty, assume they are happy with their implants
try
{
GiveThought(pawn, react, pawn.IsDesignatedHero());//give unhappy, if not hero}
}
catch
{
ModLog.Warning(" ChangeSex error " + xxx.get_pawnname(pawn) + " faction " + pawn.Faction.Name + ". Probably tried to change sex at world gen for royalty implant, skipping");
GiveThought(pawn, react, happy: true);
}
}
if (old_thought != null)
pawn.health.RemoveHediff(old_thought);
//add tracking hediff
pawn.health.AddHediff(sex_to_old_sex[oldsex]);
}
else//pawn was unhappy
{
if (WasThisBefore(pawn, newsex))//pawn is happy to be previous self
{
GiveThought(pawn, react, happy: true);
pawn.health.RemoveHediff(old_thought);
}
else//pawn is still unhappy mix the unhappiness from two
{
react = GetReactionHediff(GetOriginalSex(pawn), newsex);//check reaction from original sex
if (react != null)
{
GiveThought(pawn, react, old_thought: old_thought);
pawn.health.RemoveHediff(old_thought);
}
//else pawn keeps old unhappy thought
}
}
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Helpers/Gender_Helper.cs
|
C#
|
mit
| 12,021
|
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Verse;
using rjw.Modules.Testing;
using GenitalFamily = rjw.Modules.Interactions.Enums.GenitalFamily;
using GenitalTag = rjw.Modules.Interactions.Enums.GenitalTag;
using GenitalPartExtension = rjw.Modules.Interactions.DefModExtensions.GenitalPartExtension;
namespace rjw
{
public static class Genital_Helper
{
public static HediffDef generic_anus = HediffDef.Named("GenericAnus");
public static HediffDef generic_penis = HediffDef.Named("GenericPenis");
public static HediffDef generic_vagina = HediffDef.Named("GenericVagina");
public static HediffDef generic_breasts = HediffDef.Named("GenericBreasts");
public static HediffDef average_penis = HediffDef.Named("Penis");
public static HediffDef hydraulic_penis = HediffDef.Named("HydraulicPenis");
public static HediffDef bionic_penis = HediffDef.Named("BionicPenis");
public static HediffDef archotech_penis = HediffDef.Named("ArchotechPenis");
public static HediffDef average_vagina = HediffDef.Named("Vagina");
public static HediffDef hydraulic_vagina = HediffDef.Named("HydraulicVagina");
public static HediffDef bionic_vagina = HediffDef.Named("BionicVagina");
public static HediffDef archotech_vagina = HediffDef.Named("ArchotechVagina");
public static HediffDef average_breasts = HediffDef.Named("Breasts");
public static HediffDef hydraulic_breasts = HediffDef.Named("HydraulicBreasts");
public static HediffDef bionic_breasts = HediffDef.Named("BionicBreasts");
public static HediffDef archotech_breasts = HediffDef.Named("ArchotechBreasts");
public static HediffDef featureless_chest = HediffDef.Named("FeaturelessChest");
public static HediffDef udder_breasts = HediffDef.Named("UdderBreasts");
public static HediffDef average_anus = HediffDef.Named("Anus");
public static HediffDef hydraulic_anus = HediffDef.Named("HydraulicAnus");
public static HediffDef bionic_anus = HediffDef.Named("BionicAnus");
public static HediffDef archotech_anus = HediffDef.Named("ArchotechAnus");
public static HediffDef peg_penis = HediffDef.Named("PegDick");
public static HediffDef insect_anus = HediffDef.Named("InsectAnus");
public static HediffDef ovipositorM = HediffDef.Named("OvipositorM");
public static HediffDef ovipositorF = HediffDef.Named("OvipositorF");
public static HediffDef demonT_penis = HediffDef.Named("DemonTentaclePenis");
public static HediffDef demon_penis = HediffDef.Named("DemonPenis");
public static HediffDef demon_vagina = HediffDef.Named("DemonVagina");
public static HediffDef demon_anus = HediffDef.Named("DemonAnus");
public static HediffDef slime_breasts = HediffDef.Named("SlimeBreasts");
public static HediffDef slime_penis = HediffDef.Named("SlimeTentacles");
public static HediffDef slime_vagina = HediffDef.Named("SlimeVagina");
public static HediffDef slime_anus = HediffDef.Named("SlimeAnus");
public static HediffDef feline_penis = HediffDef.Named("CatPenis");
public static HediffDef feline_vagina = HediffDef.Named("CatVagina");
public static HediffDef canine_penis = HediffDef.Named("DogPenis");
public static HediffDef canine_vagina = HediffDef.Named("DogVagina");
public static HediffDef equine_penis = HediffDef.Named("HorsePenis");
public static HediffDef equine_vagina = HediffDef.Named("HorseVagina");
public static HediffDef dragon_penis = HediffDef.Named("DragonPenis");
public static HediffDef dragon_vagina = HediffDef.Named("DragonVagina");
public static HediffDef raccoon_penis = HediffDef.Named("RaccoonPenis");
public static HediffDef hemipenis = HediffDef.Named("HemiPenis");
public static HediffDef crocodilian_penis = HediffDef.Named("CrocodilianPenis");
// I'm not a big fan of looking for defs through string matching, but
// I suppose it handles the odd rebelious race mod.
public static readonly BodyPartTagDef BodyPartTagDefEatingSource = DefDatabase<BodyPartTagDef>.GetNamed("EatingSource");
public static readonly BodyPartTagDef BodyPartTagDefMetabolismSource = DefDatabase<BodyPartTagDef>.GetNamed("MetabolismSource");
public static readonly BodyPartTagDef BodyPartTagDefTongue = DefDatabase<BodyPartTagDef>.GetNamed("Tongue");
private static readonly HashSet<BodyPartDef> mouthBPs =
DefDatabase<BodyPartDef>.AllDefsListForReading
.Where((def) => def.defName.ToLower().ContainsAny("mouth", "teeth", "jaw", "beak") || def.tags.Contains(BodyPartTagDefEatingSource))
.ToHashSet();
private static readonly HashSet<BodyPartDef> tongueBPs =
DefDatabase<BodyPartDef>.AllDefsListForReading
.Where((def) => def.defName.ToLower().Contains("tongue") || def.tags.Contains(BodyPartTagDefTongue))
.ToHashSet();
private static readonly HashSet<BodyPartDef> stomachBPs =
DefDatabase<BodyPartDef>.AllDefsListForReading
.Where((def) => def.defName.ToLower().Contains("stomach") || def.tags.Contains(BodyPartTagDefMetabolismSource))
.ToHashSet();
private static readonly HashSet<BodyPartDef> torsoBPs =
DefDatabase<BodyPartDef>.AllDefsListForReading
.Where((def) => def.defName.ToLower().Contains("torso"))
.ToHashSet();
private static readonly HashSet<BodyPartDef> tailBPs =
DefDatabase<BodyPartDef>.AllDefsListForReading
.Where((def) => def.defName.ToLower().Contains("tail"))
.ToHashSet();
private static readonly HashSet<BodyPartDef> bodyBPs =
DefDatabase<BodyPartDef>.AllDefsListForReading
.Where((def) => def.defName.ToLower().Contains("body"))
.ToHashSet();
private static readonly BodyPartTagDef bodyPartTagDef_tongue =
DefDatabase<BodyPartTagDef>.GetNamed("Tongue");
// These BPRs are added by RJW. They must have some sex part attached
// to count as being present.
public static BodyPartRecord get_genitalsBPR(Pawn pawn)
{
//--Log.Message("Genital_Helper::get_genitals( " + xxx.get_pawnname(pawn) + " ) called");
var bpr = pawn?.RaceProps.body.AllParts.Find(bpr => bpr.def == xxx.genitalsDef);
if (bpr is not null) return bpr;
//--ModLog.Message(" get_genitals( " + xxx.get_pawnname(pawn) + " ) - Part is null");
return null;
}
public static BodyPartRecord get_anusBPR(Pawn pawn)
{
//--ModLog.Message(" get_anus( " + xxx.get_pawnname(pawn) + " ) called");
var bpr = pawn?.RaceProps.body.AllParts.Find(bpr => bpr.def == xxx.anusDef);
if (bpr is not null) return bpr;
//--ModLog.Message(" get_anus( " + xxx.get_pawnname(pawn) + " ) - Part is null");
return null;
}
public static BodyPartRecord get_breastsBPR(Pawn pawn)
{
//--ModLog.Message(" get_breasts( " + xxx.get_pawnname(pawn) + " ) called");
var bpr = pawn?.RaceProps.body.AllParts.Find(bpr => bpr.def == xxx.breastsDef);
if (bpr is not null) return bpr;
//--ModLog.Message(" get_breasts( " + xxx.get_pawnname(pawn) + " ) - Part is null");
return null;
}
public static BodyPartRecord get_uddersBPR(Pawn pawn)
{
//--ModLog.Message(" get_udder( " + xxx.get_pawnname(pawn) + " ) called");
var bpr = pawn?.RaceProps.body.AllParts.Find(bpr => bpr.def == xxx.flankDef);
if (bpr is not null) return bpr;
//--ModLog.Message(" get_udders( " + xxx.get_pawnname(pawn) + " ) - Part is null");
return null;
}
// These BPRs are either pre-existing or added by other mods. They are considered
// present as long as they have no `Hediff_PartRemoved` on them. Use the `has_bpr`
// method to check that they're not chopped off, blown off, smashed off, or whatever
// other kinds of terrible things can befall a poor pawn.
public static BodyPartRecord get_mouthBPR(Pawn pawn)
{
//--ModLog.Message(" get_mouth( " + xxx.get_pawnname(pawn) + " ) called");
var bpr = pawn?.RaceProps.body.AllParts.Find((bpr) => mouthBPs.Contains(bpr.def));
if (bpr is not null) return bpr;
//--ModLog.Message(" get_mouth( " + xxx.get_pawnname(pawn) + " ) - Part is null");
return null;
}
public static BodyPartRecord get_tongueBPR(Pawn pawn)
{
//--ModLog.Message(" get_tongue( " + xxx.get_pawnname(pawn) + " ) called");
if (pawn?.RaceProps.body.AllParts is { } allParts)
{
foreach (var bpr in allParts)
{
if (tongueBPs.Contains(bpr.def)) return bpr;
if (bpr.def.tags.Contains(bodyPartTagDef_tongue)) return bpr;
}
}
//--ModLog.Message(" get_tongue( " + xxx.get_pawnname(pawn) + " ) - Part is null");
return null;
}
public static BodyPartRecord get_stomachBPR(Pawn pawn)
{
//--ModLog.Message(" get_stomach( " + xxx.get_pawnname(pawn) + " ) called");
if (pawn?.RaceProps.body.AllParts is { } allParts)
{
var bpr = allParts.Find((bpr) => stomachBPs.Contains(bpr.def));
if (bpr is not null) return bpr;
//--ModLog.Message(" get_stomach( " + xxx.get_pawnname(pawn) + " ) - Part is null, trying to get torso...");
bpr = allParts.Find((bpr) => torsoBPs.Contains(bpr.def));
if (bpr is not null) return bpr;
}
//--ModLog.Message(" get_stomach( " + xxx.get_pawnname(pawn) + " ) - Part is null, no stomach or torso.");
return null;
}
public static BodyPartRecord get_tailBPR(Pawn pawn)
{
//should probably make scale race check or something
//--ModLog.Message(" get_tail( " + xxx.get_pawnname(pawn) + " ) called");
var bpr = pawn?.RaceProps.body.AllParts.Find(bpr => tailBPs.Contains(bpr.def));
if (bpr is not null) return bpr;
//--ModLog.Message(" get_tail( " + xxx.get_pawnname(pawn) + " ) - Part is null");
return null;
}
public static BodyPartRecord get_torsoBPR(Pawn pawn)
{
//--ModLog.Message(" get_torsoBPR( " + xxx.get_pawnname(pawn) + " ) called");
if (pawn?.RaceProps.body.AllParts is { } allParts)
{
var bpr = allParts.Find((bpr) => torsoBPs.Contains(bpr.def));
if (bpr is not null) return bpr;
//--ModLog.Message(" get_torsoBPR( " + xxx.get_pawnname(pawn) + " ) - Part is null, trying to get body...");
bpr = allParts.Find((bpr) => bodyBPs.Contains(bpr.def));
if (bpr is not null) return bpr;
}
//--ModLog.Message(" get_torsoBPR( " + xxx.get_pawnname(pawn) + " ) - Part is null, no torso or body");
return null;
}
public static bool breasts_blocked(Pawn pawn)
{
if (pawn.apparel?.WornApparel is not { } wornApparel) return false;
return wornApparel.ToBondageGear().Any((def) => def.blocks_breasts);
}
public static bool udder_blocked(Pawn pawn)
{
if (pawn.apparel?.WornApparel is not { } wornApparel) return false;
return wornApparel.ToBondageGear().Any((def) => def.blocks_udder);
}
public static bool anus_blocked(Pawn pawn)
{
if (pawn.apparel?.WornApparel is not { } wornApparel) return false;
return wornApparel.ToBondageGear().Any((def) => def.blocks_anus);
}
public static bool genitals_blocked(Pawn pawn)
{
if (pawn.apparel?.WornApparel is not { } wornApparel) return false;
return wornApparel.ToBondageGear().Any((def) => def.blocks_penis || def.blocks_vagina);
}
public static bool hands_blocked(Pawn pawn)
{
if (pawn.apparel?.WornApparel is not { } wornApparel) return false;
return wornApparel.ToBondageGear().Any((def) => def.blocks_hands);
}
public static bool penis_blocked(Pawn pawn)
{
if (pawn.apparel?.WornApparel is not { } wornApparel) return false;
return wornApparel.ToBondageGear().Any((def) => def.blocks_penis);
}
public static bool oral_blocked(Pawn pawn)
{
if (pawn.apparel?.WornApparel is not { } wornApparel) return false;
return wornApparel.ToBondageGear().Any((def) => def.blocks_oral);
}
public static bool vagina_blocked(Pawn pawn)
{
if (pawn.apparel?.WornApparel is not { } wornApparel) return false;
return wornApparel.ToBondageGear().Any((def) => def.blocks_vagina);
}
private static IEnumerable<bondage_gear_def> ToBondageGear(this List<Apparel> wornApparel) =>
wornApparel.Select((app) => app.def).OfType<bondage_gear_def>();
public static bool is_sex_part(Hediff hed) =>
hed is Hediff_PartBaseNatural || hed is Hediff_PartBaseArtifical;
public static List<Hediff> get_PartsHediffList(Pawn pawn, BodyPartRecord Part) =>
pawn.health.hediffSet.hediffs.FindAll((hed) => is_sex_part(hed) && hed.Part == Part);
public static List<Hediff> get_AllPartsHediffList(Pawn pawn) =>
pawn.health.hediffSet.hediffs.FindAll(is_sex_part);
public static bool has_genitals(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
return !parts.NullOrEmpty();
}
public static bool has_breasts(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetBreastList();
if (parts.NullOrEmpty()) return false;
return parts.Any((hed) => hed.def != featureless_chest);
}
public static bool has_udder(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetUdderList();
return !parts.NullOrEmpty();
}
public static bool has_male_breasts(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetBreastList();
if (parts.NullOrEmpty()) return false;
return parts.Any((hed) => is_sex_part(hed) && hed.CurStageIndex == 0);
}
/// <summary>
/// Can do breastjob if breasts are average or bigger
/// </summary>
/// <param name="pawn"></param>
/// <returns></returns>
public static bool can_do_breastjob(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetBreastList();
if (parts.NullOrEmpty()) return false;
return parts.Any((hed) => is_sex_part(hed) && hed.CurStageIndex > 1);
}
public static bool has_tail(Pawn pawn) =>
has_bpr(pawn, get_tailBPR(pawn));
public static bool has_mouth(Pawn pawn) =>
has_bpr(pawn, get_mouthBPR(pawn));
public static bool has_tongue(Pawn pawn) =>
has_bpr(pawn, get_tongueBPR(pawn));
/// <summary>
/// <para>Checks to see if a body part is actually attached.</para>
/// <para>This applies to BPRs that are not added by RJW. For those,
/// we count the part as missing if they do not have an accompanying
/// sex-part.</para>
/// </summary>
/// <param name="pawn">The pawn to check.</param>
/// <param name="bpr">The `BodyPartRecord` indicating the body part.</param>
/// <returns>Whether the part is missing.</returns>
public static bool has_bpr(Pawn pawn, BodyPartRecord bpr)
{
if (bpr is null) return false;
return !pawn.health.hediffSet.hediffs
.Where((hed) => hed.Part == bpr)
.Any((hed) => hed is Hediff_MissingPart);
}
public static bool has_anus(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetAnusList();
if (parts.NullOrEmpty()) return false;
for (int i = 0; i < parts.Count; i++)
if (is_anus(parts[i]))
return true;
return false;
}
public static bool is_anus(Hediff hed)
{
if (!GenitalPartExtension.TryGet(hed, out var ext)) return false;
return ext.family == GenitalFamily.Anus;
}
/// <summary>
/// Insertable, this is both vagina and ovipositorf
/// </summary>
/// <param name="pawn"></param>
/// <param name="parts"></param>
/// <returns></returns>
public static bool has_vagina(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
if (parts.NullOrEmpty()) return false;
for (int i = 0; i < parts.Count; i++)
if (is_vagina(parts[i]))
return true;
return false;
}
private static bool is_vagina_family(GenitalFamily family) => family switch
{
GenitalFamily.Vagina => true,
GenitalFamily.FemaleOvipositor => true,
_ => false
};
public static bool is_vagina(Hediff hed) =>
GenitalPartExtension.TryGet(hed, out var ext) && is_vagina_family(ext.family);
/// <summary>
/// <para>Checks to see if a pawn has a penis, whether fertile or not.</para>
/// <para>This includes male ovipositors, but not female ovipositors (that is
/// regarded more like a vagina).</para>
/// </summary>
/// <param name="pawn">The pawn to inspect.</param>
/// <param name="parts">The pre-obtained parts, if available.</param>
public static bool has_male_bits(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
if (parts.NullOrEmpty()) return false;
return parts.Any(is_penis);
}
public static bool has_penis_fertile(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
if (parts.NullOrEmpty()) return false;
for (int i = 0; i < parts.Count; i++)
if (is_fertile_penis(parts[i]))
return true;
return false;
}
public static bool has_penis_infertile(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
if (parts.NullOrEmpty()) return false;
for (int i = 0; i < parts.Count; i++)
if (is_infertile_penis(parts[i]))
return true;
return false;
}
private static bool is_penis_family(GenitalFamily family) => family switch
{
GenitalFamily.Penis => true,
GenitalFamily.MaleOvipositor => true,
_ => false
};
private static bool is_fertile_tag(GenitalTag tag) => tag switch
{
GenitalTag.CanFertilize => true,
GenitalTag.CanFertilizeEgg => true,
_ => false
};
public static bool is_penis(Hediff hed) =>
GenitalPartExtension.TryGet(hed, out var ext) && is_penis_family(ext.family);
public static bool is_fertile_penis(Hediff hed)
{
if (!GenitalPartExtension.TryGet(hed, out var ext)) return false;
if (!is_penis_family(ext.family)) return false;
for (int i = 0; i < ext.tags.Count; i++)
if (is_fertile_tag(ext.tags[i]))
return true;
return false;
}
public static bool is_infertile_penis(Hediff hed)
{
if (!GenitalPartExtension.TryGet(hed, out var ext)) return false;
if (!is_penis_family(ext.family)) return false;
for (int i = 0; i < ext.tags.Count; i++)
if (is_fertile_tag(ext.tags[i]))
return false;
return true;
}
public static bool has_multipenis(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
if (parts.NullOrEmpty()) return false;
int count = 0;
foreach (Hediff hed in parts)
{
if (!is_penis(hed)) continue;
// Matches hemipenis.
if (PartProps.TryGetProps(hed, out var props))
if (props.Contains("Multiple"))
return true;
count += 1;
if (count > 1) return true;
}
return false;
}
public static bool has_ovipositorM(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
if (parts.NullOrEmpty()) return false;
for (int i = 0; i < parts.Count; i++)
if (is_male_ovipositor(parts[i]))
return true;
return false;
static bool is_male_ovipositor(Hediff hed)
{
if (!GenitalPartExtension.TryGet(hed, out var ext)) return false;
return ext.family == GenitalFamily.MaleOvipositor;
}
}
public static bool has_ovipositorF(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
if (parts.NullOrEmpty()) return false;
for (int i = 0; i < parts.Count; i++)
if (is_female_ovipositor(parts[i]))
return true;
return false;
static bool is_female_ovipositor(Hediff hed)
{
if (!GenitalPartExtension.TryGet(hed, out var ext)) return false;
return ext.family == GenitalFamily.FemaleOvipositor;
}
}
/// <summary>
/// Can do autofellatio if penis is huge or bigger
/// </summary>
/// <param name="pawn"></param>
/// <returns></returns>
public static bool can_do_autofelatio(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
if (parts.NullOrEmpty()) return false;
return parts.Any((hed) => is_penis(hed) && hed.CurStageIndex > 3);
}
/// <summary>
/// Count only fertile penises
/// </summary>
/// <param name="pawn"></param>
/// <returns></returns>
public static bool is_futa(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
return has_vagina(pawn, parts) && has_penis_fertile(pawn, parts);
}
public static int min_EggsProduced(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
// No fitting parts - return 0
if (parts.NullOrEmpty()) return 0;
// set min to 1 in case it is not defined in the xml file
int minEggsProduced = 1;
var eggParts = parts.Select(part => part.def).OfType<HediffDef_PartBase>();
foreach (HediffDef_PartBase hed in eggParts)
{
//if (hed.minEggAmount)
if (minEggsProduced > 0)
{
minEggsProduced = hed.minEggsProduced;
}
}
return minEggsProduced;
}
public static int max_EggsProduced(Pawn pawn, List<Hediff> parts = null)
{
parts ??= pawn.GetGenitalsList();
// No fitting parts - return 0
if (parts.NullOrEmpty()) return 0;
// set min to 1 in case it is not defined in the xml file
int maxEggsProduced = 1;
var eggParts = parts.Select(part => part.def).OfType<HediffDef_PartBase>();
foreach (HediffDef_PartBase hed in eggParts)
{
//if (hed.minEggAmount)
if (maxEggsProduced > 0)
{
maxEggsProduced = hed.maxEggsProduced;
}
}
return maxEggsProduced;
}
/// <summary>
/// <para>This utility appears in the "Output" tab of the debug menu.</para>
/// <para>It generates every kind of pawn in the game and runs all these methods
/// against them. You can use this to validate changes to these utilities.</para>
/// <para>Just run this before your changes, then after, and use some kind of diff
/// utility to see if anything is ...different.</para>
/// <para>Be aware that sometimes pawns can just generate in an imperfect way,
/// like an iguana whose tail is currently severed off will change how `has_tail`
/// might generate its output.</para>
/// </summary>
[DebugOutput("RJW", onlyWhenPlaying = true)]
public static void GenitalsOfAllPawnKinds()
{
var artificialParts = DefDatabase<RecipeDef>.AllDefsListForReading
.Where((r) => r.workerClass == typeof(Recipe_InstallGenitals))
.Where((r) => typeof(Hediff_PartBaseArtifical).IsAssignableFrom(r.addsHediff.hediffClass))
.ToArray();
var dataSources = DefDatabase<PawnKindDef>.AllDefsListForReading
.Where((d) => d.race != null)
.OrderBy((d) => d.defName)
.SelectMany(CreatePawns)
.ToArray();
var table = new TableDataGetter<(Pawn pawn, string label)>[]
{
new("kind", (d) => d.pawn.kindDef.defName),
new("sex", (d) => GenderHelper.GetSex(d.pawn).ToString().CapitalizeFirst()),
new("gender", (d) => d.pawn.gender),
new("label", (d) => d.label),
new("genitalsBPR", (d) => get_genitalsBPR(d.pawn)?.def.defName),
new("breastsBPR", (d) => get_breastsBPR(d.pawn)?.def.defName),
new("uddersBPR", (d) => get_uddersBPR(d.pawn)?.def.defName),
new("mouthBPR", (d) => get_mouthBPR(d.pawn)?.def.defName),
new("tongueBPR", (d) => get_tongueBPR(d.pawn)?.def.defName),
new("stomachBPR", (d) => get_stomachBPR(d.pawn)?.def.defName),
new("tailBPR", (d) => get_tailBPR(d.pawn)?.def.defName),
new("anusBPR", (d) => get_anusBPR(d.pawn)?.def.defName),
new("torsoBPR", (d) => get_torsoBPR(d.pawn)?.def.defName),
new("has_genitals", (d) => has_genitals(d.pawn)),
new("has_breasts", (d) => has_breasts(d.pawn)),
new("has_udder", (d) => has_udder(d.pawn)),
new("has_male_breasts", (d) => has_male_breasts(d.pawn)),
new("can_do_breastjob", (d) => can_do_breastjob(d.pawn)),
new("has_tail", (d) => has_tail(d.pawn)),
new("has_mouth", (d) => has_mouth(d.pawn)),
new("has_tongue", (d) => has_tongue(d.pawn)),
new("has_anus", (d) => has_anus(d.pawn)),
new("has_vagina", (d) => has_vagina(d.pawn)),
new("has_male_bits", (d) => has_male_bits(d.pawn)),
new("has_penis_fertile", (d) => has_penis_fertile(d.pawn)),
new("has_penis_infertile", (d) => has_penis_infertile(d.pawn)),
new("has_multipenis", (d) => has_multipenis(d.pawn)),
new("has_ovipositorM", (d) => has_ovipositorM(d.pawn)),
new("has_ovipositorF", (d) => has_ovipositorF(d.pawn)),
new("is_futa", (d) => is_futa(d.pawn)),
new("min_EggsProduced", (d) => min_EggsProduced(d.pawn)),
new("max_EggsProduced", (d) => max_EggsProduced(d.pawn))
};
DebugTables.MakeTablesDialog(dataSources, table);
IEnumerable<PawnGenerationRequest> CreateRequests(PawnKindDef def)
{
if (!def.RaceProps.hasGenders)
{
yield return new PawnGenerationRequest(kind: def)
.RequestDefaults();
}
else
{
yield return new PawnGenerationRequest(kind: def, fixedGender: Gender.Male)
.RequestDefaults();
yield return new PawnGenerationRequest(kind: def, fixedGender: Gender.Female)
.RequestDefaults();
}
}
IEnumerable<(Pawn pawn, string label)> CreatePawns(PawnKindDef def)
{
foreach (var request in CreateRequests(def))
if (TestHelper.GenerateSeededPawn(request) is { } pawn)
yield return (pawn, "natural");
// Only going to test artificial parts and complex sexes on colonists.
if (def.defName != "Colonist") yield break;
// Producing fertile and infertile futa.
foreach (var request in CreateRequests(def))
{
if (request.FixedGender == Gender.Female)
{
if (TestHelper.GenerateSeededPawn(request) is { } fertileFemale)
if (TestHelper.MakeIntoFuta(fertileFemale))
yield return (fertileFemale, "as fertile female futa");
if (TestHelper.GenerateSeededPawn(request) is { } infertileFemale)
if (TestHelper.MakeIntoFuta(infertileFemale, true))
yield return (infertileFemale, "as infertile female futa");
}
else if (request.FixedGender == Gender.Male)
{
if (TestHelper.GenerateSeededPawn(request) is { } fertileMale)
if (TestHelper.MakeIntoFuta(fertileMale))
yield return (fertileMale, "as fertile male futa");
if (TestHelper.GenerateSeededPawn(request) is { } infertileMale)
if (TestHelper.MakeIntoFuta(infertileMale))
yield return (infertileMale, "as infertile male futa");
}
}
// Producing a trap.
foreach (var request in CreateRequests(def))
{
if (request.FixedGender != Gender.Male) continue;
if (TestHelper.GenerateSeededPawn(request) is { } malePawn)
if (TestHelper.MakeIntoTrap(malePawn))
yield return (malePawn, "as trap");
}
// Testing artifical parts.
foreach (var recipe in artificialParts)
{
foreach (var request in CreateRequests(def))
{
var pawn = TestHelper.GenerateSeededPawn(request);
if (pawn is null) continue;
if (!TestHelper.ApplyPartToPawn(pawn, recipe)) continue;
yield return (pawn, $"has {recipe.addsHediff.defName}");
}
}
}
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Helpers/Genital_Helper.cs
|
C#
|
mit
| 26,494
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
namespace rjw
{
public class HediffHelper
{
/// <summary>
/// Creates hediff with custom hediff class
/// </summary>
/// <typeparam name="T">hediff class. Should be class defined by hediff or subclass of that class</typeparam>
/// <param name="def">hediffDef</param>
/// <param name="pawn">owner of newly created hediff</param>
/// <param name="partRecord">bodypart heduff assigned to</param>
/// <returns>newly created hediff</returns>
public static T MakeHediff<T>(HediffDef def, Pawn pawn, BodyPartRecord partRecord = null) where T : Hediff
{
if (!def.hediffClass.IsAssignableFrom(typeof(T)))
{
throw new InvalidOperationException($"trying to create hediff with incompatible class: {typeof(T).Name} is not a {def.hediffClass.Name} or its subclass");
}
T hediff = (T)Activator.CreateInstance(typeof(T));
hediff.def = def;
hediff.pawn = pawn;
hediff.Part = partRecord;
hediff.loadID = Find.UniqueIDsManager.GetNextHediffID();
hediff.PostMake();
return hediff;
}
/// <summary>
/// Fill existing hediff class with data
/// </summary>
/// <typeparam name="T">hediff class. Should be class defined by hediff or subclass of that class</typeparam>
/// <param name="def">hediffDef</param>
/// <param name="hediff">empty hediff instance</Hediff>
/// <param name="pawn">owner of newly created hediff</param>
/// <param name="partRecord">bodypart heduff assigned to</param>
/// <returns>newly created hediff</returns>
public static T FillHediff<T>(HediffDef def, T hediff, Pawn pawn, BodyPartRecord partRecord = null) where T : Hediff
{
if (!def.hediffClass.IsAssignableFrom(typeof(T)))
{
throw new InvalidOperationException($"trying to create hediff with incompatible class: {typeof(T).Name} is not a {def.hediffClass.Name} or its subclass");
}
hediff.def = def;
hediff.pawn = pawn;
hediff.Part = partRecord;
hediff.loadID = Find.UniqueIDsManager.GetNextHediffID();
hediff.PostMake();
return hediff;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Helpers/HediffHelper.cs
|
C#
|
mit
| 2,120
|
using System.Collections.Generic;
using Verse;
using RimWorld;
using static rjw.PreceptDefOf;
namespace rjw
{
public static class IdeoHelper
{
public static readonly List<PreceptDef> freeLovePrecepts;
public static readonly List<PreceptDef> nonPolyPrecepts;
public static readonly List<PreceptDef> prudePrecepts;
public static bool ClassicMode => !ModsConfig.IdeologyActive || Find.IdeoManager.classicMode;
static IdeoHelper()
{
if (ModsConfig.IdeologyActive)
{
freeLovePrecepts = new() { Lovin_Free, Lovin_FreeApproved };
nonPolyPrecepts = new() {
Lovin_SpouseOnly_Mild,
Lovin_SpouseOnly_Moderate,
Lovin_SpouseOnly_Strict
};
prudePrecepts = new() { Lovin_Prohibited, Lovin_Horrible };
}
else
{
freeLovePrecepts = new() { Lovin_Free };
}
}
/// <summary>
/// Check whether pawn has an ideo with a free love precept.
/// </summary>
/// <param name="pawn">The pawn whose ideo is being checked</param>
/// <param name="allowClassic">
/// Whether the hidden 'Lovin: Free' precept included in classic and non-DLC ideos should be respected.<br />
/// In other words, whether we are strong enough to accept canon or cling fearfully to our silly 21st century mores.
/// </param>
/// <returns>True if etc etc, false otherwise</returns>
public static bool IsIdeologicallyPoly(this Pawn pawn, bool allowClassic = true)
{
if (pawn.Ideo == null)
{
return false;
}
if (ClassicMode)
{
return allowClassic;
}
var lovinPrecept = GetLovinPreceptDef(pawn.Ideo);
if (lovinPrecept == null)
{
return false;
}
return freeLovePrecepts.Contains(lovinPrecept);
}
public static bool IsIdeologicallyPrudish(this Pawn pawn)
{
if (pawn.Ideo == null || ClassicMode)
{
return false;
}
var lovinPrecept = GetLovinPreceptDef(pawn.Ideo);
if (lovinPrecept == null)
{
return false;
}
return prudePrecepts.Contains(lovinPrecept);
}
private static PreceptDef GetLovinPreceptDef(Ideo ideo)
{
return ideo.PreceptsListForReading.FirstOrDefault(p => p.def.issue == IssueDefOf.Lovin)?.def;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Helpers/IdeoHelper.cs
|
C#
|
mit
| 2,152
|
using Multiplayer.API;
using RimWorld;
using Verse;
namespace rjw
{
/// <summary>
/// Old, hardcoded part choosing code. Used as a fallback if no RaceGroupDef is found.
/// </summary>
public static class LegacySexPartAdder
{
static bool privates_gender(Pawn pawn, Gender gender)
{
return SexPartAdder.IsAddingPenis(pawn, gender);
}
[SyncMethod]
public static double GenderTechLevelCheck(Pawn pawn)
{
bool lowtechlevel = true;
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
double value = Rand.Value;
if (pawn?.Faction != null)
lowtechlevel = (int)pawn.Faction.def.techLevel < 5;
else if (pawn == null)
lowtechlevel = false;
//--save savages from inventing hydraulic and bionic genitals
while (lowtechlevel && value >= 0.90)
{
value = Rand.Value;
}
return value;
}
public static void AddBreasts(Pawn pawn, BodyPartRecord bpr, Pawn parent)
{
var temppawn = parent ?? pawn;
HediffDef part;
double value = GenderTechLevelCheck(pawn);
string racename = temppawn.kindDef.race.defName.ToLower();
part = Genital_Helper.generic_breasts;
if (xxx.is_mechanoid(pawn))
{
return;
}
if (xxx.is_insect(temppawn))
{
// this will probably need override in case there are humanoid insect race
//--ModLog.Message(" add_breasts( " + xxx.get_pawnname(pawn) + " ) - is insect,doesn't need breasts");
return;
}
//alien races - MoreMonstergirls
else if (racename.Contains("slime"))
{
//slimes are always females, and idc what anyone else say!
part = Genital_Helper.slime_breasts;
}
else
{
if (pawn.RaceProps.Humanlike)
{
//alien races - ChjDroid, ChjAndroid
if (racename.ContainsAny("mantis", "rockman", "slug", "zoltan", "engie", "sergal", "cutebold", "dodo", "owl", "parrot",
"penguin", "cassowary", "chicken", "vulture"))
{
if (!pawn.health.hediffSet.HasHediff(Genital_Helper.featureless_chest))
pawn.health.AddHediff(Genital_Helper.featureless_chest, bpr);
return;
}
else if (racename.ContainsAny("avali", "khess"))
{
return;
}
else if (AndroidsCompatibility.IsAndroid(pawn))
{
if (pawn.story.GetBackstory(BackstorySlot.Childhood) != null)
{
if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("bishojo"))
part = Genital_Helper.bionic_breasts;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("pleasure"))
part = Genital_Helper.bionic_breasts;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("idol"))
part = Genital_Helper.bionic_breasts;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("social"))
part = Genital_Helper.hydraulic_breasts;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("substitute"))
part = Genital_Helper.average_breasts;
else if (pawn.story.GetBackstory(BackstorySlot.Adulthood) != null)
{
if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("courtesan"))
part = Genital_Helper.bionic_breasts;
else if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("social"))
part = Genital_Helper.hydraulic_breasts;
}
else
return;
}
else if (pawn.story.GetBackstory(BackstorySlot.Adulthood) != null)
{
if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("courtesan"))
part = Genital_Helper.bionic_breasts;
else if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("social"))
part = Genital_Helper.hydraulic_breasts;
}
if (part == Genital_Helper.generic_breasts)
return;
}
//alien races - MoreMonstergirls
else if (racename.Contains("cowgirl"))
{
part = Genital_Helper.average_breasts;
if (value < 0.50 && !pawn.health.hediffSet.HasHediff(Genital_Helper.udder_breasts) && pawn.gender != Gender.Male)
{
var bp = Genital_Helper.get_uddersBPR(pawn);
pawn.health.AddHediff(SexPartAdder.MakePart(Genital_Helper.udder_breasts, pawn, bp), bp);
}
}
else
{
if (value < 0.90 || (pawn.ageTracker.AgeBiologicalYears < 2))
part = Genital_Helper.average_breasts;
else if (value < 0.95)
part = Genital_Helper.hydraulic_breasts;
else
part = Genital_Helper.bionic_breasts;
}
}
else if (racename.ContainsAny("mammoth", "elasmotherium", "chalicotherium", "megaloceros", "sivatherium", "deinotherium",
"aurochs", "zygolophodon", "uintatherium", "gazelle", "ffalo", "boomalope", "cow", "miltank", "elk", "reek", "nerf",
"bantha", "tauntaun", "caribou", "deer", "ibex", "dromedary", "alpaca", "llama", "goat", "moose", "horse", "donkey", "yak"))
{
if (!pawn.health.hediffSet.HasHediff(Genital_Helper.udder_breasts) && pawn.gender != Gender.Male)
{
bpr = Genital_Helper.get_uddersBPR(pawn);
part = Genital_Helper.udder_breasts;
}
else
return;
}
else if (racename.ContainsAny("cassowary", "emu", "dinornis", "ostrich", "turkey", "chicken", "duck", "murkroW", "bustard", "palaeeudyptes",
"goose", "tukiri", "porg", "yi", "kiwi", "penguin", "quail", "ptarmigan", "doduo", "flamingo", "plup", "empoleon", "meadow ave") && !racename.ContainsAny("duck-billed"))
{
return; // Separate list for birds, to make it easier to add cloaca at some later date.
} // Other breastless creatures.
else if (racename.ContainsAny("titanis", "titanoboa", "guan", "tortoise", "turt", "aerofleet", "quinkana", "megalochelys",
"purussaurus", "cobra", "dewback", "rancor", "frog", "onyx", "flommel", "lapras", "aron", "chinchou",
"squirtle", "wartortle", "blastoise", "totodile", "croconaw", "feraligatr", "litwick", "pumpkaboo", "shuppet", "haunter",
"gastly", "oddish", "hoppip", "tropius", "budew", "roselia", "bellsprout", "drifloon", "chikorita", "bayleef", "meganium",
"char", "drago", "dratini", "saur", "tyrannus", "carnotaurus", "baryonyx", "minmi", "diplodocus", "phodon", "indominus",
"raptor", "caihong", "coelophysis", "cephale", "compsognathus", "mimus", "troodon", "dactyl", "tanystropheus", "geosternbergia",
"deino", "suchus", "dracorex", "cephalus", "trodon", "quetzalcoatlus", "pteranodon", "antarctopelta", "stygimoloch", "rhabdodon",
"rhamphorhynchus", "ceratops", "ceratus", "zalmoxes", "mochlodon", "gigantophis", "crab", "pulmonoscorpius", "manipulator",
"meganeura", "euphoberia", "holcorobeus", "protosolpuga", "barbslinger", "blizzarisk", "frostmite", "devourer", "hyperweaver",
"macrelcana", "acklay", "elemental", "megalania", "gecko", "gator", "komodo", "scolipede", "shuckle", "combee", "shedinja",
"caterpie", "wurmple", "lockjaw", "needlepost", "needleroll", "squid", "slug", "gila", "pleura"))
{
return;
}
pawn.health.AddHediff(SexPartAdder.MakePart(part, pawn, bpr), bpr);
}
}
public static void AddGenitals(Pawn pawn, Pawn parent, Gender gender, BodyPartRecord bpr, HediffDef part)
{
var temppawn = parent ?? pawn;
double value = GenderTechLevelCheck(pawn);
string racename = temppawn.kindDef.race.defName.ToLower();
//Log.Message("Genital_Helper::add_genitals( " + xxx.get_pawnname(pawn));
//Log.Message("Genital_Helper::add_genitals( " + pawn.kindDef.race.defName);
//Log.Message("Genital_Helper::is male( " + privates_gender(pawn, gender));
//Log.Message("Genital_Helper::is male1( " + pawn.gender);
//Log.Message("Genital_Helper::is male2( " + gender);
if (xxx.is_mechanoid(pawn))
{
return;
}
//insects
else if (xxx.is_insect(temppawn)
|| racename.Contains("apini")
|| racename.Contains("mantodean")
|| racename.Contains("insect")
|| racename.Contains("bug"))
{
part = (privates_gender(pawn, gender)) ? Genital_Helper.ovipositorM : Genital_Helper.ovipositorF;
//override for Better infestations, since queen is male at creation
if (racename.Contains("Queen"))
part = Genital_Helper.ovipositorF;
}
//space cats pawns
else if ((racename.Contains("orassan") || racename.Contains("neko")) && !racename.ContainsAny("akaneko"))
{
if ((value < 0.70) || (pawn.ageTracker.AgeBiologicalYears < 2) || !pawn.RaceProps.Humanlike)
part = (privates_gender(pawn, gender)) ? Genital_Helper.feline_penis : Genital_Helper.feline_vagina;
else if (value < 0.90)
part = (privates_gender(pawn, gender)) ? Genital_Helper.hydraulic_penis : Genital_Helper.hydraulic_vagina;
else
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
}
//space dog pawns
else if (racename.Contains("fennex")
|| racename.Contains("xenn")
|| racename.Contains("leeani")
|| racename.Contains("ferian")
|| racename.Contains("callistan"))
{
if ((value < 0.70) || (pawn.ageTracker.AgeBiologicalYears < 2) || !pawn.RaceProps.Humanlike)
part = (privates_gender(pawn, gender)) ? Genital_Helper.canine_penis : Genital_Helper.canine_vagina;
else if (value < 0.90)
part = (privates_gender(pawn, gender)) ? Genital_Helper.hydraulic_penis : Genital_Helper.hydraulic_vagina;
else
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
}
//space horse pawns
else if (racename.Contains("equium"))
{
if ((value < 0.70) || (pawn.ageTracker.AgeBiologicalYears < 2) || !pawn.RaceProps.Humanlike)
part = (privates_gender(pawn, gender)) ? Genital_Helper.equine_penis : Genital_Helper.equine_vagina;
else if (value < 0.90)
part = (privates_gender(pawn, gender)) ? Genital_Helper.hydraulic_penis : Genital_Helper.hydraulic_vagina;
else
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
}
//space raccoon pawns
else if (racename.Contains("racc") && !racename.Contains("raccoon"))
{
if ((value < 0.70) || (pawn.ageTracker.AgeBiologicalYears < 2) || !pawn.RaceProps.Humanlike)
part = (privates_gender(pawn, gender)) ? Genital_Helper.raccoon_penis : Genital_Helper.generic_vagina;
else if (value < 0.90)
part = (privates_gender(pawn, gender)) ? Genital_Helper.hydraulic_penis : Genital_Helper.hydraulic_vagina;
else
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
}
//alien races - ChjDroid, ChjAndroid
else if (AndroidsCompatibility.IsAndroid(pawn))
{
if (pawn.story.GetBackstory(BackstorySlot.Childhood) != null)
{
if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("bishojo"))
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("pleasure"))
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("idol"))
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("social"))
part = (privates_gender(pawn, gender)) ? Genital_Helper.hydraulic_penis : Genital_Helper.hydraulic_vagina;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("substitute"))
part = (privates_gender(pawn, gender)) ? Genital_Helper.average_penis : Genital_Helper.average_vagina;
else if (pawn.story.GetBackstory(BackstorySlot.Adulthood) != null)
{
if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("courtesan"))
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
else if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("social"))
part = (privates_gender(pawn, gender)) ? Genital_Helper.hydraulic_penis : Genital_Helper.hydraulic_vagina;
}
else
return;
}
else if (pawn.story.GetBackstory(BackstorySlot.Adulthood) != null)
{
if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("courtesan"))
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
else if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("social"))
part = (privates_gender(pawn, gender)) ? Genital_Helper.hydraulic_penis : Genital_Helper.hydraulic_vagina;
}
if (part == Genital_Helper.generic_penis || part == Genital_Helper.generic_vagina)
return;
}
//animal cats
else if (racename.ContainsAny("cat", "cougar", "lion", "leopard", "cheetah", "panther", "tiger", "lynx", "smilodon", "akaneko"))
{
part = (privates_gender(pawn, gender)) ? Genital_Helper.feline_penis : Genital_Helper.feline_vagina;
}
//animal canine/dogs
else if (racename.ContainsAny("husky", "warg", "terrier", "collie", "hound", "retriever", "mastiff", "wolf", "fox",
"vulptex", "dachshund", "schnauzer", "corgi", "pug", "doberman", "chowchow", "borzoi", "saintbernard", "newfoundland",
"poodle", "dog", "coyote"))
{
part = (privates_gender(pawn, gender)) ? Genital_Helper.canine_penis : Genital_Helper.canine_vagina;
}
//animal horse - MoreMonstergirls
else if (racename.ContainsAny("horse", "centaur", "zebra", "donkey", "dryad"))
{
part = (privates_gender(pawn, gender)) ? Genital_Helper.equine_penis : Genital_Helper.equine_vagina;
}
//animal raccoon
else if (racename.Contains("racc"))
{
part = (privates_gender(pawn, gender)) ? Genital_Helper.raccoon_penis : Genital_Helper.generic_vagina;
}
//animal crocodilian (alligator, crocodile, etc)
else if (racename.ContainsAny("alligator", "crocodile", "caiman", "totodile", "croconaw", "feraligatr", "quinkana", "purussaurus", "kaprosuchus", "sarcosuchus"))
{
part = (privates_gender(pawn, gender)) ? Genital_Helper.crocodilian_penis : Genital_Helper.generic_vagina;
}
//hemipenes - mostly reptiles and snakes
else if (racename.ContainsAny("guana", "cobra", "gecko", "snake", "boa", "quinkana", "megalania", "gila", "gigantophis", "komodo", "basilisk", "thorny", "onix", "lizard", "slither") && !racename.ContainsAny("boar"))
{
part = (privates_gender(pawn, gender)) ? Genital_Helper.hemipenis : Genital_Helper.generic_vagina;
}
//animal dragon - MoreMonstergirls
else if (racename.ContainsAny("dragon", "thrumbo", "drake", "charizard", "saurus"))
{
part = (privates_gender(pawn, gender)) ? Genital_Helper.dragon_penis : Genital_Helper.dragon_vagina;
}
//animal slime - MoreMonstergirls
else if (racename.Contains("slime"))
{
// slime always futa
pawn.health.AddHediff(SexPartAdder.MakePart(privates_gender(pawn, gender) ? Genital_Helper.slime_penis : Genital_Helper.slime_vagina, pawn, bpr), bpr);
pawn.health.AddHediff(SexPartAdder.MakePart(privates_gender(pawn, gender) ? Genital_Helper.slime_vagina : Genital_Helper.slime_penis, pawn, bpr), bpr);
return;
}
//animal demons - MoreMonstergirls
else if (racename.Contains("impmother") || racename.Contains("demon"))
{
// 25% futa
pawn.health.AddHediff(SexPartAdder.MakePart(privates_gender(pawn, gender) ? Genital_Helper.demon_penis : Genital_Helper.demon_vagina, pawn, bpr), bpr);
if (Rand.Value < 0.25f)
pawn.health.AddHediff(SexPartAdder.MakePart(privates_gender(pawn, gender) ? Genital_Helper.demon_penis : Genital_Helper.demonT_penis, pawn, bpr), bpr);
return;
}
//animal demons - MoreMonstergirls
else if (racename.Contains("baphomet"))
{
if (Rand.Value < 0.50f)
pawn.health.AddHediff(SexPartAdder.MakePart(privates_gender(pawn, gender) ? Genital_Helper.demon_penis : Genital_Helper.demon_vagina, pawn, bpr), bpr);
else
pawn.health.AddHediff(SexPartAdder.MakePart(privates_gender(pawn, gender) ? Genital_Helper.equine_penis : Genital_Helper.demon_vagina, pawn, bpr), bpr);
return;
}
else if (pawn.RaceProps.Humanlike)
{
//--Log.Message("Genital_Helper::add_genitals( " + xxx.get_pawnname(pawn) + " ) - race is humanlike");
if (value < 0.90 || (pawn.ageTracker.AgeBiologicalYears < 2))
part = (privates_gender(pawn, gender)) ? Genital_Helper.average_penis : Genital_Helper.average_vagina;
else if (value < 0.95)
part = (privates_gender(pawn, gender)) ? Genital_Helper.hydraulic_penis : Genital_Helper.hydraulic_vagina;
else
part = (privates_gender(pawn, gender)) ? Genital_Helper.bionic_penis : Genital_Helper.bionic_vagina;
}
//--Log.Message("Genital_Helper::add_genitals final ( " + xxx.get_pawnname(pawn) + " ) " + part.defName);
var hd = SexPartAdder.MakePart(part, pawn, bpr);
//Log.Message("Genital_Helper::add_genitals final ( " + xxx.get_pawnname(pawn) + " ) " + hd.def.defName + " sev " + hd.Severity + " bpr " + BPR.def.defName);
pawn.health.AddHediff(hd, bpr);
//Log.Message("Genital_Helper::add_genitals final ( " + xxx.get_pawnname(pawn) + " ) " + pawn.health.hediffSet.HasHediff(hd.def));
}
public static void AddAnus(Pawn pawn, BodyPartRecord bpr, Pawn parent)
{
var temppawn = parent ?? pawn;
HediffDef part;
double value = GenderTechLevelCheck(pawn);
string racename = temppawn.kindDef.race.defName.ToLower();
part = Genital_Helper.generic_anus;
if (xxx.is_mechanoid(pawn))
{
return;
}
else if (xxx.is_insect(temppawn))
{
part = Genital_Helper.insect_anus;
}
//alien races - ChjDroid, ChjAndroid
else if (AndroidsCompatibility.IsAndroid(pawn))
{
if (pawn.story.GetBackstory(BackstorySlot.Childhood) != null)
{
if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("bishojo"))
part = Genital_Helper.bionic_anus;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("pleasure"))
part = Genital_Helper.bionic_anus;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("idol"))
part = Genital_Helper.bionic_anus;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("social"))
part = Genital_Helper.hydraulic_anus;
else if (pawn.story.Childhood.untranslatedTitleShort.ToLower().Contains("substitute"))
part = Genital_Helper.average_anus;
else if (pawn.story.GetBackstory(BackstorySlot.Adulthood) != null)
{
if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("courtesan"))
part = Genital_Helper.bionic_anus;
else if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("social"))
part = Genital_Helper.hydraulic_anus;
}
}
else if (pawn.story.GetBackstory(BackstorySlot.Adulthood) != null)
{
if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("courtesan"))
part = Genital_Helper.bionic_anus;
else if (pawn.story.Adulthood.untranslatedTitleShort.ToLower().Contains("social"))
part = Genital_Helper.hydraulic_anus;
}
if (part == Genital_Helper.generic_anus)
return;
}
else if (racename.Contains("slime"))
{
part = Genital_Helper.slime_anus;
}
//animal demons - MoreMonstergirls
else if (racename.Contains("impmother") || racename.Contains("baphomet") || racename.Contains("demon"))
{
part = Genital_Helper.demon_anus;
}
else if (pawn.RaceProps.Humanlike)
{
if (value < 0.90 || (pawn.ageTracker.AgeBiologicalYears < 2))
part = Genital_Helper.average_anus;
else if (value < 0.95)
part = Genital_Helper.hydraulic_anus;
else
part = Genital_Helper.bionic_anus;
}
pawn.health.AddHediff(SexPartAdder.MakePart(part, pawn, bpr), bpr);
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Helpers/LegacySexPartAdder.cs
|
C#
|
mit
| 19,960
|
using System;
using System.Collections.Generic;
using RimWorld;
using Verse;
namespace rjw
{
class OviHelper
{
static readonly IDictionary<PawnKindDef, ThingDef> FertileEggPawnKinds = new Dictionary<PawnKindDef, ThingDef>();
static readonly IDictionary<PawnKindDef, ThingDef> UnfertileEggPawnKinds = new Dictionary<PawnKindDef, ThingDef>();
public static CompProperties_EggLayer GenerateEggLayerProperties(PawnKindDef pawnKindDef, RaceGroupDef raceGroupDef)
{
CompProperties_EggLayer comp = new CompProperties_EggLayer();
comp.eggFertilizedDef = DefDatabase<ThingDef>.GetNamed(raceGroupDef.eggFertilizedDef);
comp.eggUnfertilizedDef = DefDatabase<ThingDef>.GetNamed(raceGroupDef.eggUnfertilizedDef);
comp.eggProgressUnfertilizedMax = raceGroupDef.eggProgressUnfertilizedMax;
comp.eggLayIntervalDays = raceGroupDef.eggLayIntervalDays;
return comp;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Helpers/OviHelper.cs
|
C#
|
mit
| 889
|
using Verse;
using Verse.AI;
namespace rjw
{
public static class Pather_Utility
{
public static bool cells_to_target_casual(Pawn pawn, IntVec3 Position)
{
//less taxing, ignores walls
return pawn.Position.DistanceTo(Position) < RJWSettings.maxDistanceCellsCasual;
}
public static bool cells_to_target_rape(Pawn pawn, IntVec3 Position)
{
//less taxing, ignores walls
return pawn.Position.DistanceTo(Position) < RJWSettings.maxDistanceCellsRape;
}
public static bool can_path_to_target(Pawn pawn, IntVec3 Position)
{
//more taxing, using real pathing
bool canit = true;
if (RJWSettings.maxDistancePathCost > 0)
{
PawnPath pawnPath = pawn.Map.pathFinder.FindPath(pawn.Position, Position, pawn);
if (pawnPath.TotalCost > RJWSettings.maxDistancePathCost)
canit = false;// too far
pawnPath.Dispose();
}
return canit;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Helpers/Pather_Utility.cs
|
C#
|
mit
| 890
|
using System.Collections.Generic;
using System.Linq;
using Verse;
namespace rjw
{
class RaceGroupDef_Helper
{
/// <summary>
/// Cache for TryGetRaceGroupDef.
/// </summary>
static readonly IDictionary<PawnKindDef, RaceGroupDef> RaceGroupByPawnKind = new Dictionary<PawnKindDef, RaceGroupDef>();
public static bool TryGetRaceGroupDef(PawnKindDef pawnKindDef, out RaceGroupDef raceGroupDef)
{
if (RaceGroupByPawnKind.TryGetValue(pawnKindDef, out raceGroupDef))
{
return raceGroupDef != null;
}
else
{
raceGroupDef = GetRaceGroupDefInternal(pawnKindDef);
RaceGroupByPawnKind.Add(pawnKindDef, raceGroupDef);
return raceGroupDef != null;
}
}
public static bool TryGetRaceGroupDef(Pawn pawn, out RaceGroupDef raceGroupDef)
{
return TryGetRaceGroupDef(pawn.kindDef, out raceGroupDef);
}
/// <summary>
/// Returns the best match RaceGroupDef for the given pawn, or null if none is found.
/// </summary>
static RaceGroupDef GetRaceGroupDefInternal(Pawn pawn)
{
return GetRaceGroupDefInternal(pawn.kindDef);
}
static RaceGroupDef GetRaceGroupDefInternal(PawnKindDef kindDef)
{
var raceName = kindDef.race.defName;
var pawnKindName = kindDef.defName;
var groups = DefDatabase<RaceGroupDef>.AllDefs;
var kindMatches = groups.Where(group => group.pawnKindNames?.Contains(pawnKindName) ?? false).ToList();
var raceMatches = groups.Where(group => group.raceNames?.Contains(raceName) ?? false).ToList();
var count = kindMatches.Count() + raceMatches.Count();
if (count == 0)
{
//ModLog.Message($"Pawn named '{pawn.Name}' matched no RaceGroupDef. If you want to create a matching RaceGroupDef you can use the raceName '{raceName}' or the pawnKindName '{pawnKindName}'.");
return null;
}
else if (count == 1)
{
// ModLog.Message($"Pawn named '{pawn.Name}' matched 1 RaceGroupDef.");
return kindMatches.Concat(raceMatches).Single();
}
else
{
// ModLog.Message($"Pawn named '{pawn.Name}' matched {count} RaceGroupDefs.");
// If there are multiple RaceGroupDef matches, choose one of them.
// First prefer defs NOT defined in rjw.
// Then prefer a match by kind over a match by race.
return kindMatches.FirstOrDefault(match => !IsThisMod(match))
?? raceMatches.FirstOrDefault(match => !IsThisMod(match))
?? kindMatches.FirstOrDefault()
?? raceMatches.FirstOrDefault();
}
}
static bool IsThisMod(Def def)
{
var rjwContent = LoadedModManager.RunningMods.Single(pack => pack.Name == "RimJobWorld");
return rjwContent.AllDefs.Contains(def);
}
/// <summary>
/// Returns true if a race part was chosen (even if that part is "no part").
/// </summary>
public static bool TryAddRacePart(Pawn pawn, SexPartType sexPartType)
{
if (!TryGetRaceGroupDef(pawn, out var raceGroupDef))
{
// No race, so nothing was chosen.
return false;
}
if (!RacePartDef_Helper.TryChooseRacePartDef(raceGroupDef, sexPartType, out var racePartDef))
{
// Failed to find a part, so nothing was chosen.
return false;
}
if (racePartDef.IsNone)
{
// "no part" was explicitly chosen.
return true;
}
if (raceGroupDef.HasUdder && sexPartType == SexPartType.FemaleBreast && !pawn.health.hediffSet.HasHediff(Genital_Helper.udder_breasts))
{
var bp = Genital_Helper.get_uddersBPR(pawn);
pawn.health.AddHediff(SexPartAdder.MakePart(Genital_Helper.udder_breasts, pawn, bp), bp);
}
var target = sexPartType.GetBodyPartDef();
var bodyPartRecord = pawn.RaceProps.body.AllParts.Find(bpr => bpr.def == target);
if (!racePartDef.TryGetHediffDef(out var hediffDef))
{
// Failed to find hediffDef.
return false;
}
var hediff = RacePartDef_Helper.MakePart(hediffDef, pawn, bodyPartRecord, racePartDef);
pawn.health.AddHediff(hediff, bodyPartRecord);
// A part was chosen and added.
return true;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Helpers/RaceGroupDef_Helper.cs
|
C#
|
mit
| 3,945
|
using Multiplayer.API;
using System.Collections.Generic;
using System.Linq;
using Verse;
using RimWorld;
namespace rjw
{
class RacePartDef_Helper
{
/// <summary>
/// Returns true if a partAdders was chosen (even if that part is "no part").
/// </summary>
[SyncMethod]
public static bool TryRacePartDef_partAdders(Pawn pawn)
{
//RaceGroupDef_Helper.TryGetRaceGroupDef(pawn.kindDef, out var raceGroupDef);
if (!RaceGroupDef_Helper.TryGetRaceGroupDef(pawn.kindDef, out var raceGroupDef))
return false;
if (raceGroupDef.partAdders.NullOrEmpty())
return false;
List<BodyPartRecord> pawnParts = pawn.RaceProps?.body?.AllParts;
pawnParts = pawnParts.FindAll(record => !pawn.health.hediffSet.PartIsMissing(record));
foreach (var Adder in raceGroupDef.partAdders)
{
if (Adder.chance <= Rand.Value)
continue;
var racePartDef = DefDatabase<RacePartDef>.GetNamedSilentFail(Adder.rjwPart);
if (racePartDef == null)
{
//No part found
continue;
}
if (!racePartDef.TryGetHediffDef(out var rjwPartDef))
{
//No part found
continue;
}
pawnParts = pawnParts.FindAll(record => Adder.bodyParts.Contains(record.def.defName));
foreach (BodyPartRecord record in pawnParts)
{
var hediff = RacePartDef_Helper.MakePart(rjwPartDef, pawn, record, racePartDef);
pawn.health.AddHediff(hediff, record);
}
}
return true;
}
/// <summary>
/// Returns true if a race part was chosen (even if that part is "no part").
/// </summary>
[SyncMethod]
public static bool TryChooseRacePartDef(RaceGroupDef raceGroupDef, SexPartType sexPartType, out RacePartDef racePartDef)
{
var partNames = raceGroupDef.GetRacePartDefNames(sexPartType);
if (partNames == null)
{
// Missing list, so nothing was chosen.
racePartDef = null;
return false;
}
else if (!partNames.Any())
{
// Empty list, so "no part" was chosen.
racePartDef = RacePartDef.None;
return true;
}
var chances = raceGroupDef.GetChances(sexPartType);
var hasChances = chances != null && chances.Count() > 0;
if (hasChances && chances.Count() != partNames.Count())
{
// No need for this to be runtime, should probably be a config error in RaceGroupDef.
ModLog.Error($"RaceGroupDef named {raceGroupDef.defName} has {partNames.Count()} parts but {chances.Count()} chances for {sexPartType}.");
racePartDef = null;
return false;
}
string partName;
if (hasChances)
{
var indexes = partNames.Select((x, i) => i);
partName = partNames[indexes.RandomElementByWeight(i => chances[i])];
}
else
{
partName = partNames.RandomElement();
}
racePartDef = DefDatabase<RacePartDef>.GetNamedSilentFail(partName);
if (racePartDef == null)
{
ModLog.Error($"Could not find a RacePartDef named {partName} referenced by RaceGroupDef named {raceGroupDef.defName}.");
return false;
}
else
{
return true;
}
}
[SyncMethod]
public static Hediff MakePart(HediffDef hediffDef, Pawn pawn, BodyPartRecord bodyPartRecord, RacePartDef racePartDef)
{
var hediff = HediffMaker.MakeHediff(hediffDef, pawn, bodyPartRecord);
var compHediff = hediff.TryGetComp<CompHediffBodyPart>();
if (compHediff != null)
{
compHediff.initComp(pawn);
if (racePartDef.fluidType != null)
{
compHediff.FluidType = racePartDef.fluidType;
}
if (racePartDef.fluidModifier != null)
{
compHediff.FluidModifier = racePartDef.fluidModifier.Value;
}
if (racePartDef.severityCurve != null && racePartDef.severityCurve.Any())
{
// Size math is in flux right now, but the idea is that for an individual pawn
// the size chosen in the RaceGroupDef is the size reported in the UI regardless of pawn's BodySize.
// Check for males to only get nipple sized (flat) breasts
// Trap calculation is done in initComp method above, by this point only pawns with SizeBase of 0.01
// should be those that failed the Trap calc, are male, or are very unlucky on their breast size roll
// Check for is male at the end because its possible (though very unlikely) for a female to roll a 0.01, and
// the severity curve for that race's breasts may actually have it as impossible for a female to be that small
if (compHediff.SizeBase == 0.01f && hediff.def.defName.ToLower().Contains("breast") && pawn.gender == Gender.Male)
{
compHediff.updatesize();
}
else
{
var severity = racePartDef.severityCurve.Evaluate(Rand.Value);
compHediff.SizeBase = severity;
compHediff.EffSize = severity;
compHediff.updatesize(severity);
}
}
else
{
compHediff.updatesize();
}
}
return hediff;
}
/// <summary>
/// Generates and logs RacePartDef xml shells for each RJW hediff so they can be manually saved as a def file and referenced by RaceGroupDefs.
/// In theory this could be done automatically at run time. But then we also might want to add real configuration
/// to the shells so for now just checking in the shells.
/// </summary>
public static void GeneratePartShells()
{
var defs = DefDatabase<HediffDef_PartBase>.AllDefs.OrderBy(def => def.defName);
var template = "\t<rjw.RacePartDef>\n\t\t<defName>{0}</defName>\n\t\t<hediffName>{0}</hediffName>\n\t</rjw.RacePartDef>";
var strings = defs.Select(def => string.Format(template, def.defName));
ModLog.Message(" RacePartDef shells:\n" + string.Join("\n", strings));
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Helpers/RacePartDef_Helper.cs
|
C#
|
mit
| 5,566
|
using Multiplayer.API;
using RimWorld;
using Verse;
using System.Collections.Generic;
namespace rjw
{
public class SexPartAdder
{
/// <summary>
/// return true if going to set penis,
/// return false for vagina
/// </summary>
public static bool IsAddingPenis(Pawn pawn, Gender gender)
{
return (pawn.gender == Gender.Male) ? (gender != Gender.Female) : (gender == Gender.Male);
}
/// <summary>
/// generate part hediff
/// </summary>
public static Hediff MakePart(HediffDef def, Pawn pawn, BodyPartRecord bpr)
{
//Log.Message("SexPartAdder::PartMaker ( " + xxx.get_pawnname(pawn) + " ) " + def.defName);
Hediff hd = HediffMaker.MakeHediff(def, pawn, bpr);
//Log.Message("SexPartAdder::PartMaker ( " + xxx.get_pawnname(pawn) + " ) " + hd.def.defName);
CompHediffBodyPart compHediff = hd.TryGetComp<CompHediffBodyPart>();
if (compHediff != null)
{
//Log.Message("SexPartAdder::PartMaker init comps");
compHediff.initComp(pawn);
compHediff.updatesize();
}
return hd;
}
/// <summary>
/// operation - move part data from thing to hediff
/// </summary>
public static Hediff recipePartAdder(RecipeDef recipe, Pawn pawn, BodyPartRecord part, List<Thing> ingredients)
{
Hediff hd = HediffMaker.MakeHediff(recipe.addsHediff, pawn, part);
Thing thing = ingredients.Find(x => x.def.defName == recipe.addsHediff.defName);
CompThingBodyPart CompThing = thing.TryGetComp<rjw.CompThingBodyPart>();
CompHediffBodyPart CompHediff = hd.TryGetComp<rjw.CompHediffBodyPart>();
if (CompHediff != null && CompThing != null)
if (CompThing.SizeBase > 0)
{
CompHediff.FluidType = CompThing.FluidType;
CompHediff.FluidAmmount = CompThing.FluidAmmount;
CompHediff.FluidModifier = CompThing.FluidModifier;
CompHediff.SizeBase = CompThing.SizeBase;
CompHediff.SizeOwner = CompThing.SizeOwner;
CompHediff.RaceOwner = CompThing.RaceOwner;
CompHediff.PreviousOwner = CompThing.PreviousOwner;
CompHediff.Eggs = CompThing.Eggs;
CompHediff.Transplanted = true;
CompHediff.updatesize();
}
else //not initialised things, drop pods, trader? //TODO: figure out how to populate rjw parts at gen
hd = MakePart(hd.def, pawn, part);
return hd;
}
/// <summary>
/// operation - move part data from hediff to thing
/// </summary>
public static Thing recipePartRemover(Hediff hd)
{
Thing thing = ThingMaker.MakeThing(hd.def.spawnThingOnRemoved);
CompThingBodyPart CompThing = thing.TryGetComp<rjw.CompThingBodyPart>();
CompHediffBodyPart CompHediff = hd.TryGetComp<rjw.CompHediffBodyPart>();
if (CompThing != null && CompHediff != null)
{
CompThing.FluidType = CompHediff.FluidType;
CompThing.FluidAmmount = CompHediff.FluidAmmount;
CompThing.FluidModifier = CompHediff.FluidModifier;
CompThing.Size = CompHediff.Size;
CompThing.SizeBase = CompHediff.SizeBase;
CompThing.SizeOwner = CompHediff.SizeOwner;
CompThing.RaceOwner = CompHediff.RaceOwner;
CompThing.PreviousOwner = xxx.get_pawnname(CompHediff.Pawn);
CompThing.Eggs = CompHediff.Eggs;
}
return thing;
}
[SyncMethod]
public static void add_genitals(Pawn pawn, Pawn parent = null, Gender gender = Gender.None)
{
//--Log.Message("Genital_Helper::add_genitals( " + xxx.get_pawnname(pawn) + " ) called");
BodyPartRecord partBPR = Genital_Helper.get_genitalsBPR(pawn);
var parts = pawn.GetGenitalsList();
//--Log.Message("Genital_Helper::add_genitals( " + xxx.get_pawnname(pawn) + " ) - checking genitals");
if (partBPR == null)
{
//--ModLog.Message(" add_genitals( " + xxx.get_pawnname(pawn) + " ) doesn't have a genitals");
return;
}
else if (pawn.health.hediffSet.PartIsMissing(partBPR))
{
//--ModLog.Message(" add_genitals( " + xxx.get_pawnname(pawn) + " ) had a genital but was removed.");
return;
}
if (Genital_Helper.has_genitals(pawn, parts) && gender == Gender.None)//allow to add gender specific genitals(futa)
{
//--ModLog.Message(" add_genitals( " + xxx.get_pawnname(pawn) + " ) already has genitals");
return;
}
HediffDef part;
// maybe add some check based on bodysize of pawn for genitals size limit
//Log.Message("Genital_Helper::add_genitals( " + pawn.RaceProps.baseBodySize + " ) - 1");
//Log.Message("Genital_Helper::add_genitals( " + pawn.kindDef.race.size. + " ) - 2");
part = (IsAddingPenis(pawn, gender)) ? Genital_Helper.generic_penis : Genital_Helper.generic_vagina;
if (Genital_Helper.has_vagina(pawn, parts) && part == Genital_Helper.generic_vagina)
{
//--ModLog.Message(" add_genitals( " + xxx.get_pawnname(pawn) + " ) already has vagina");
return;
}
if (Genital_Helper.has_male_bits(pawn, parts) && part == Genital_Helper.generic_penis)
{
//--ModLog.Message(" add_genitals( " + xxx.get_pawnname(pawn) + " ) already has penis");
return;
}
//override race genitals
if (part == Genital_Helper.generic_vagina && pawn.TryAddRacePart(SexPartType.FemaleGenital))
{
return;
}
if (part == Genital_Helper.generic_penis && pawn.TryAddRacePart(SexPartType.MaleGenital))
{
return;
}
LegacySexPartAdder.AddGenitals(pawn, parent, gender, partBPR, part);
}
public static void add_breasts(Pawn pawn, Pawn parent = null, Gender gender = Gender.None)
{
//--ModLog.Message(" add_breasts( " + xxx.get_pawnname(pawn) + " ) called");
BodyPartRecord partBPR = Genital_Helper.get_breastsBPR(pawn);
if (partBPR == null)
{
//--ModLog.Message(" add_breasts( " + xxx.get_pawnname(pawn) + " ) - pawn doesn't have a breasts");
return;
}
else if (pawn.health.hediffSet.PartIsMissing(partBPR))
{
//--ModLog.Message(" add_breasts( " + xxx.get_pawnname(pawn) + " ) had breasts but were removed.");
return;
}
if (pawn.GetBreastList().Count > 0)
//if (Genital_Helper.has_breasts(pawn))
{
//--ModLog.Message(" add_breasts( " + xxx.get_pawnname(pawn) + " ) - pawn already has breasts");
return;
}
//TODO: figure out how to add (flat) breasts to males
//Check for (flat) breasts to males done in RacepartDef_Helper.cs when severity curve checked
var racePartType = (pawn.gender == Gender.Female || gender == Gender.Female)
? SexPartType.FemaleBreast
: SexPartType.MaleBreast;
if (pawn.TryAddRacePart(racePartType))
{
return;
}
LegacySexPartAdder.AddBreasts(pawn, partBPR, parent);
}
public static void add_anus(Pawn pawn, Pawn parent = null)
{
BodyPartRecord partBPR = Genital_Helper.get_anusBPR(pawn);
if (partBPR == null)
{
//--ModLog.Message(" add_anus( " + xxx.get_pawnname(pawn) + " ) doesn't have an anus");
return;
}
else if (pawn.health.hediffSet.PartIsMissing(partBPR))
{
//--ModLog.Message(" add_anus( " + xxx.get_pawnname(pawn) + " ) had an anus but was removed.");
return;
}
if (pawn.GetAnusList().Count > 0)
{
//--ModLog.Message(" add_anus( " + xxx.get_pawnname(pawn) + " ) already has an anus");
return;
}
if (pawn.TryAddRacePart(SexPartType.Anus))
{
return;
}
LegacySexPartAdder.AddAnus(pawn, partBPR, parent);
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Helpers/SexPartAdder.cs
|
C#
|
mit
| 7,228
|
using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using UnityEngine;
using Verse;
using Verse.AI;
using Verse.Sound;
using HarmonyLib;
using Multiplayer.API;
using rjw.Modules.Interactions.Contexts;
using rjw.Modules.Interactions.Implementation;
using rjw.Modules.Interactions;
using rjw.Modules.Interactions.Objects;
using rjw.Modules.Interactions.Enums;
using static HarmonyLib.Code;
namespace rjw
{
public class SexUtility
{
private const float base_sat_per_fuck = 0.40f;
private const float base_sat_per_quirk = 0.20f;
public static readonly InteractionDef AnimalSexChat = DefDatabase<InteractionDef>.GetNamed("AnimalSexChat");
private static readonly ThingDef cum = ThingDef.Named("FilthCum");
private static readonly ThingDef girlcum = ThingDef.Named("FilthGirlCum");
public static readonly List<InteractionDef> SexInterractions = DefDatabase<InteractionDef>.AllDefsListForReading.Where(x => x.HasModExtension<InteractionExtension>()).ToList();
// Alert checker that is called from several jobs. Checks the pawn relation, and whether it should sound alert.
// notification in top left corner
// rape attempt
public static void RapeTargetAlert(Pawn rapist, Pawn target)
{
if (target.IsDesignatedComfort() && rapist.jobs.curDriver.GetType() == typeof(JobDriver_RapeComfortPawn))
if (!RJWPreferenceSettings.ShowForCP)
return;
if (target.IsDesignatedComfort() && rapist.jobs.curDriver.GetType() == typeof(JobDriver_Breeding))
if (target.IsDesignatedBreeding())
if (!RJWPreferenceSettings.ShowForBreeding)
return;
bool silent = false;
PawnRelationDef relation = rapist.GetMostImportantRelation(target);
string rapeverb = "rape";
if (xxx.is_mechanoid(rapist)) rapeverb = "assault";
else if (xxx.is_animal(rapist) || xxx.is_animal(target)) rapeverb = "breed";
// TODO: Need to write a cherker method for family relations. Would be useful for other things than just this, such as incest settings/quirk.
string message = (xxx.get_pawnname(rapist) + " is trying to " + rapeverb + " " + xxx.get_pawnname(target));
message += relation == null ? "." : (", " + rapist.Possessive() + " " + relation.GetGenderSpecificLabel(target) + ".");
switch (RJWPreferenceSettings.rape_attempt_alert)
{
case RJWPreferenceSettings.RapeAlert.Enabled:
break;
case RJWPreferenceSettings.RapeAlert.Humanlikes:
if (!xxx.is_human(target))
return;
break;
case RJWPreferenceSettings.RapeAlert.Colonists:
if (!target.IsColonist)
return;
break;
case RJWPreferenceSettings.RapeAlert.Silent:
silent = true;
break;
default:
return;
}
if (!silent)
{
Messages.Message(message, rapist, MessageTypeDefOf.NegativeEvent);
}
else
{
Messages.Message(message, rapist, MessageTypeDefOf.SilentInput);
}
}
// Alert checker that is called from several jobs.
// notification in top left corner
// rape started
public static void BeeingRapedAlert(Pawn rapist, Pawn target)
{
if (target.IsDesignatedComfort() && rapist.jobs.curDriver.GetType() == typeof(JobDriver_RapeComfortPawn))
if (!RJWPreferenceSettings.ShowForCP)
return;
if (target.IsDesignatedComfort() && rapist.jobs.curDriver.GetType() == typeof(JobDriver_Breeding))
if (target.IsDesignatedBreeding())
if (!RJWPreferenceSettings.ShowForBreeding)
return;
bool silent = false;
switch (RJWPreferenceSettings.rape_alert)
{
case RJWPreferenceSettings.RapeAlert.Enabled:
break;
case RJWPreferenceSettings.RapeAlert.Humanlikes:
if (!xxx.is_human(target))
return;
break;
case RJWPreferenceSettings.RapeAlert.Colonists:
if (!target.IsColonist)
return;
break;
case RJWPreferenceSettings.RapeAlert.Silent:
silent = true;
break;
default:
return;
}
if (!silent)
{
Messages.Message(xxx.get_pawnname(target) + " is getting raped.", target, MessageTypeDefOf.NegativeEvent);
}
else
{
Messages.Message(xxx.get_pawnname(target) + " is getting raped.", target, MessageTypeDefOf.SilentInput);
}
}
// Quick method that return a body part by name. Used for checking if a pawn has a specific body part, etc.
public static BodyPartRecord GetPawnBodyPart(Pawn pawn, string bodyPart)
{
return pawn.RaceProps.body.AllParts.Find(x => x.def == DefDatabase<BodyPartDef>.GetNamed(bodyPart));
}
public static void CumFilthGenerator(Pawn pawn)
{
if (pawn == null) return;
if (pawn.Dead) return;
if (xxx.is_slime(pawn)) return;
if (!RJWSettings.cum_filth) return;
// Larger creatures, larger messes.
float pawn_cum = Math.Min(80 / ScaleToHumanAge(pawn), 2.0f) * pawn.BodySize;
// Increased output if the pawn has the Messy quirk.
if (xxx.has_quirk(pawn, "Messy"))
pawn_cum *= 2.0f;
var parts = pawn.GetGenitalsList();
if (Genital_Helper.has_vagina(pawn, parts))
FilthMaker.TryMakeFilth(pawn.PositionHeld, pawn.MapHeld, girlcum, pawn.LabelIndefinite(), (int)Math.Max(pawn_cum / 2, 1.0f));
if (Genital_Helper.has_penis_fertile(pawn, parts))
FilthMaker.TryMakeFilth(pawn.PositionHeld, pawn.MapHeld, cum, pawn.LabelIndefinite(), (int)Math.Max(pawn_cum, 1.0f));
}
// The pawn may or may not clean up the mess after fapping.
[SyncMethod]
public static bool ConsiderCleaning(Pawn fapper)
{
if (!RJWSettings.cum_filth) return false;
if (!xxx.has_traits(fapper) || fapper.story == null) return false;
if (fapper.WorkTagIsDisabled(WorkTags.Cleaning)) return false;
float do_cleaning = 0.5f; // 50%
if (!fapper.PositionHeld.Roofed(fapper.Map))
do_cleaning -= 0.25f; // Less likely to clean if outdoors.
if (xxx.CTIsActive && fapper.story.traits.HasTrait(xxx.RCT_NeatFreak))
do_cleaning += 1.00f;
if (xxx.has_quirk(fapper, "Messy"))
do_cleaning -= 0.75f;
switch (fapper.needs?.rest?.CurCategory)
{
case RestCategory.Exhausted:
do_cleaning -= 0.5f;
break;
case RestCategory.VeryTired:
do_cleaning -= 0.3f;
break;
case RestCategory.Tired:
do_cleaning -= 0.1f;
break;
case RestCategory.Rested:
do_cleaning += 0.3f;
break;
}
if (fapper.story.traits.DegreeOfTrait(TraitDefOf.NaturalMood) == -2) // Depressive
do_cleaning -= 0.3f;
if (fapper.story.traits.DegreeOfTrait(TraitDefOf.Industriousness) == 2) // Industrious
do_cleaning += 1.0f;
else if (fapper.story.traits.DegreeOfTrait(TraitDefOf.Industriousness) == 1) // Hard worker
do_cleaning += 0.5f;
else if (fapper.story.traits.DegreeOfTrait(TraitDefOf.Industriousness) == -1) // Lazy
do_cleaning -= 0.5f;
else if (fapper.story.traits.DegreeOfTrait(TraitDefOf.Industriousness) == -2) // Slothful
do_cleaning -= 1.0f;
if (xxx.is_ascetic(fapper))
do_cleaning += 0.2f;
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
return Rand.Chance(do_cleaning);
}
/// <summary>Handles after-sex trait and thought gain, and fluid creation. Initiator of the act (whore, rapist, female zoophile, etc) should be first.</summary>
[SyncMethod]
public static void Aftersex(SexProps props)
{
if (props.sexType == xxx.rjwSextype.Masturbation)
{
AfterMasturbation(props);
return;
}
bool bothInMap = false;
if (!props.partner.Dead)
bothInMap = props.pawn.Map != null && props.partner.Map != null; //Added by Hoge. false when called this function for despawned pawn: using for background rape like a kidnappee
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
if (bothInMap)
{
//Catch-all timer increase, for ensuring that pawns don't get stuck repeating jobs.
if (!props.isCoreLovin)
{
props.pawn.rotationTracker.Face(props.partner.DrawPos);
props.pawn.rotationTracker.FaceCell(props.partner.Position);
}
if (!props.partner.Dead)
{
if (!props.isCoreLovin)
{
props.partner.rotationTracker.Face(props.pawn.DrawPos);
props.partner.rotationTracker.FaceCell(props.pawn.Position);
}
if (RJWSettings.sounds_enabled)
{
if (props.isRape)
{
if (Rand.Value > 0.30f)
LifeStageUtility.PlayNearestLifestageSound(props.partner, (ls) => ls.soundAngry, null, 1.2f);
else
LifeStageUtility.PlayNearestLifestageSound(props.partner, (ls) => ls.soundCall, g => g.soundCall, 1.2f);
props.pawn.Drawer.Notify_MeleeAttackOn(props.partner);
props.partner.stances.stagger.StaggerFor(Rand.Range(10, 300));
}
else
LifeStageUtility.PlayNearestLifestageSound(props.partner, (ls) => ls.soundCall, g => g.soundCall);
}
if (props.sexType == xxx.rjwSextype.Vaginal || props.sexType == xxx.rjwSextype.DoublePenetration)
if (xxx.is_Virgin(props.partner))
{
//TODO: bind virginity to parts of pawn
/*
string thingdef_penis_name = Genital_Helper.get_penis_all(pawn)?.def.defName ?? "";
ThingDef thingdef_penis = null;
Log.Message("SexUtility::thingdef_penis_name " + thingdef_penis_name);
Log.Message("SexUtility::thingdef_penis 1 " + thingdef_penis);
if (thingdef_penis_name != "")
thingdef_penis = (from x in DefDatabase<ThingDef>.AllDefs where x.defName == thingdef_penis_name select x).RandomElement();
Log.Message("SexUtility::thingdef_penis 2 " + thingdef_penis);
partner.TakeDamage(new DamageInfo(DamageDefOf.Stab, 1, 999, -1.0f, null, xxx.genitals, thingdef_penis));
*/
}
}
if (RJWSettings.sounds_enabled && props.isCoreLovin)
SoundDef.Named("Cum").PlayOneShot(!props.partner.Dead
? new TargetInfo(props.partner.Position, props.pawn.Map)
: new TargetInfo(props.pawn.Position, props.pawn.Map));
if (props.isRape)
{
if (Rand.Value > 0.30f)
LifeStageUtility.PlayNearestLifestageSound(props.pawn, (ls) => ls.soundAngry, null, 1.2f);
else
LifeStageUtility.PlayNearestLifestageSound(props.pawn, (ls) => ls.soundCall, g => g.soundCall, 1.2f);
}
else
LifeStageUtility.PlayNearestLifestageSound(props.pawn, (ls) => ls.soundCall, g => g.soundCall);
}
if (props.usedCondom)
{
if (CondomUtility.UsedCondom != null)
GenSpawn.Spawn(CondomUtility.UsedCondom, props.pawn.Position, props.pawn.Map);
CondomUtility.useCondom(props.pawn);
CondomUtility.useCondom(props.partner);
}
else
{
if (props.isCoreLovin) // non core handled by jobdriver
{
//apply cum to floor:
CumFilthGenerator(props.pawn);
CumFilthGenerator(props.partner);
PregnancyHelper.impregnate(props);
TransferNutrition(props);
}
}
List<Trait> newInitiatorTraits = new(), newReceiverTraits = new();
if (props.isRape && !props.partner.Dead)
AfterSexUtility.processBrokenPawn(props.partner, newReceiverTraits);
//Satisfy(pawn, partner, sextype, rape);
//TODO: below is fucked up, unfuck it someday
AfterSexUtility.UpdateRecords(props);
GiveTraits(props, newInitiatorTraits);
GiveTraits(props.GetForPartner(), newReceiverTraits);
if (RJWSettings.sendTraitGainLetters)
{
SendTraitGainLetter(props.pawn, newInitiatorTraits);
SendTraitGainLetter(props.partner, newReceiverTraits);
}
}
// <summary>Solo acts.</summary>
public static void AfterMasturbation(SexProps props)
{
IncreaseTicksToNextLovin(props.pawn);
//apply cum to floor:
CumFilthGenerator(props.pawn);
AfterSexUtility.UpdateRecords(props);
// No traits from solo. Enable if some are edded. (Voyerism?)
//check_trait_gain(pawn);
}
// Scales alien lifespan to human age.
// Some aliens have broken lifespans, that can be manually corrected here.
public static int ScaleToHumanAge(Pawn pawn, int humanLifespan = 80)
{
float pawnAge = pawn.ageTracker.AgeBiologicalYearsFloat;
float pawnLifespan = pawn.RaceProps.lifeExpectancy;
if (pawn.def.defName == "Human") return (int)pawnAge; // Human, no need to scale anything.
// Xen races, all broken and need a fix.
if (pawn.def.defName.ContainsAny("Alien_Sergal", "Alien_SergalNME", "Alien_Xenn", "Alien_Racc", "Alien_Ferrex", "Alien_Wolvx", "Alien_Frijjid", "Alien_Fennex") && pawnLifespan >= 2000f)
{
pawnAge = Math.Min(pawnAge, 80f); // Clamp to 80.
pawnLifespan = 80f;
}
if (pawn.def.defName.ContainsAny("Alien_Gnoll", "Alien_StripedGnoll") && pawnLifespan >= 2000f)
{
pawnAge = Math.Min(pawnAge, 60f); // Clamp to 60.
pawnLifespan = 60f; // Mature faster than humans.
}
// Immortal races that mature at similar rate to humans.
if (pawn.def.defName.ContainsAny("LF_Dragonia", "LotRE_ElfStandardRace", "Alien_Crystalloid", "Alien_CrystalValkyrie"))
{
pawnAge = Math.Min(pawnAge, 40f); // Clamp to 40 - never grow 'old'.
pawnLifespan = 80f;
}
float age_scaling = humanLifespan / pawnLifespan;
float scaled_age = pawnAge * age_scaling;
if (scaled_age < 1)
scaled_age = 1;
return (int)scaled_age;
}
// Used in complex impregnation calculation. Pawns/animals with similar parts have better compatibility.
public static float BodySimilarity(Pawn pawn, Pawn partner)
{
float size_adjustment = Mathf.Lerp(0.3f, 1.05f, 1.0f - Math.Abs(pawn.BodySize - partner.BodySize));
//ModLog.Message(" Size adjustment: " + size_adjustment);
List<BodyPartDef> pawn_partlist = new List<BodyPartDef> { };
List<BodyPartDef> pawn_mismatched = new List<BodyPartDef> { };
List<BodyPartDef> partner_mismatched = new List<BodyPartDef> { };
//ModLog.Message("Checking compatibility for " + xxx.get_pawnname(pawn) + " and " + xxx.get_pawnname(partner));
bool pawnHasHands = pawn.health.hediffSet.GetNotMissingParts().Any(part => part.IsInGroup(BodyPartGroupDefOf.RightHand) || part.IsInGroup(BodyPartGroupDefOf.LeftHand));
foreach (BodyPartRecord part in pawn.RaceProps.body.AllParts)
{
pawn_partlist.Add(part.def);
}
float pawn_count = pawn_partlist.Count();
foreach (BodyPartRecord part in partner.RaceProps.body.AllParts)
{
partner_mismatched.Add(part.def);
}
float partner_count = partner_mismatched.Count();
foreach (BodyPartDef part in pawn_partlist)
{
if (partner_mismatched.Contains(part))
{
pawn_mismatched.Add(part);
partner_mismatched.Remove(part);
}
}
float pawn_mismatch = pawn_mismatched.Count() / pawn_count;
float partner_mismatch = partner_mismatched.Count() / partner_count;
//ModLog.Message("Body type similarity for " + xxx.get_pawnname(pawn) + " and " + xxx.get_pawnname(partner) + ": " + Math.Round(((pawn_mismatch + partner_mismatch) * 50) * size_adjustment, 1) + "%");
return ((pawn_mismatch + partner_mismatch) / 2) * size_adjustment;
}
public static void SatisfyPersonal(SexProps props, float satisfaction = 0.4f)
{
Pawn pawn = props.pawn;
Pawn partner = props.partner;
//--Log.Message("xxx::satisfy( " + pawn_name + ", " + partner_name + ", " + violent + "," + isCoreLovin + " ) - modifying partner satisfaction");
var sex_need = pawn?.needs?.TryGetNeed<Need_Sex>();
if (sex_need == null) return;
float Trait_Satisfaction = 1f;
float Quirk_Satisfaction = 1f;
float Stat_Satisfaction = 0f;
float Circumstances_Satisfaction = 0f; // violence/broken
float joysatisfaction = satisfaction;
// Bonus satisfaction from traits
if (pawn != null && partner != null)
{
if (xxx.is_animal(partner) && xxx.is_zoophile(pawn))
{
Trait_Satisfaction += 0.5f;
}
if (partner.Dead && xxx.is_necrophiliac(pawn))
{
Trait_Satisfaction += 0.5f;
}
}
// Calculate bonus satisfaction from quirks
var quirkCount = Quirk.CountSatisfiedQuirks(props);
Quirk_Satisfaction += quirkCount * base_sat_per_quirk;
// Apply sex satisfaction stat (min 0.1 default 1) as a modifier to total satisfaction
Stat_Satisfaction += Math.Max(xxx.get_sex_satisfaction(pawn), 0.1f);
// Apply extra multiplier for special/violence circumstances
Circumstances_Satisfaction += get_satisfaction_circumstance_multiplier(props);
satisfaction *= Trait_Satisfaction * Quirk_Satisfaction * Stat_Satisfaction;
joysatisfaction = satisfaction;
satisfaction *= Circumstances_Satisfaction;
if (!RJWSettings.Disable_RecreationDrain)
joysatisfaction *= (Circumstances_Satisfaction - 1);
else
joysatisfaction *= Circumstances_Satisfaction;
//Log.Message("SatisfyPersonal( " + pawn + ", " + satisfaction + " ) - setting pawn sexneed");
sex_need.CurLevel += satisfaction;
if (quirkCount > 0)
{
Quirk.AddThought(pawn);
}
var joy_need = pawn.needs.TryGetNeed<Need_Joy>();
if (joy_need == null) return;
joysatisfaction *= joysatisfaction > 0 ? 0.5f : 1f; // convert half of positive satisfaction to joy
//Log.Message("SatisfyPersonal( " + pawn + ", " + joysatisfaction + " ) - setting pawn joyneed");
pawn.needs.joy.CurLevel += joysatisfaction;
//add Ahegao
//sex&joy > 95%
//sex&broken
var lev = sex_need.CurLevel;
if (lev >= sex_need.thresh_ahegao() &&
(joy_need.CurLevelPercentage > sex_need.thresh_ahegao()) ||
(AfterSexUtility.BodyIsBroken(pawn) && pawn.health.hediffSet.GetFirstHediffOfDef(xxx.feelingBroken)?.CurStageIndex >= 3))
{
var thoughtDef = DefDatabase<ThoughtDef>.GetNamed("RJW_Ahegao");
pawn.needs.mood.thoughts.memories.TryGainMemory(thoughtDef);
}
}
public static void GiveTraits(SexProps props, List<Trait> newTraits)
{
var pawn = props.pawn;
var partner = props.partner;
if (!xxx.has_traits(pawn) || pawn.records.GetValue(xxx.CountOfSex) <= 10)
{
return;
}
GiveQuirkTraits(props, newTraits, 0.05f);
if (props.IsInitiator())
{
if (RJWSettings.AddTrait_Rapist && !xxx.is_rapist(pawn) && !xxx.is_masochist(pawn) && props.isRape && pawn.records.GetValue(xxx.CountOfRapedHumanlikes) > 0.12 * pawn.records.GetValue(xxx.CountOfSex))
{
var chance = 0.5f;
if (xxx.is_kind(pawn)) chance -= 0.25f;
if (xxx.is_prude(pawn)) chance -= 0.25f;
if (xxx.is_zoophile(pawn)) chance -= 0.25f; // Less interested in raping humanlikes.
if (xxx.is_ascetic(pawn)) chance -= 0.2f;
if (xxx.is_bloodlust(pawn)) chance += 0.2f;
if (xxx.is_psychopath(pawn)) chance += 0.25f;
if (Rand.Chance(chance))
{
Trait rapist = new Trait(xxx.rapist);
pawn.story.traits.GainTrait(rapist);
newTraits.Add(rapist);
//--Log.Message(xxx.get_pawnname(pawn) + " aftersex, not rapist, adding rapist trait");
}
}
if (RJWSettings.AddTrait_Necrophiliac && !xxx.is_necrophiliac(pawn) && partner.Dead && pawn.records.GetValue(xxx.CountOfSexWithCorpse) > 0.5 * pawn.records.GetValue(xxx.CountOfSex))
{
Trait necropphiliac = new Trait(xxx.necrophiliac);
pawn.story.traits.GainTrait(necropphiliac);
newTraits.Add(necropphiliac);
//Log.Message(xxx.get_pawnname(necro) + " aftersex, not necro, adding necro trait");
}
}
if (RJWSettings.AddTrait_Zoophiliac && !xxx.is_zoophile(pawn) && xxx.is_animal(partner)
&& (pawn.records.GetValue(xxx.CountOfSexWithAnimals) + pawn.records.GetValue(xxx.CountOfSexWithInsects) > 0.5 * pawn.records.GetValue(xxx.CountOfSex)))
{
Trait zoophile = new Trait(xxx.zoophile);
pawn.story.traits.GainTrait(zoophile);
newTraits.Add(zoophile);
MemoryThoughtHandler memories = pawn.needs.mood.thoughts.memories;
foreach (ThoughtDef memory in new[] {xxx.got_bred, xxx.got_anal_bred, xxx.got_groped, xxx.got_licked})
{
memories.RemoveMemoriesOfDef(memory);
}
//--Log.Message(xxx.get_pawnname(pawn) + " aftersex, not zoo, adding zoo trait");
}
if (RJWSettings.AddTrait_Nymphomaniac && !xxx.is_nympho(pawn))
{
if (pawn.health.hediffSet.HasHediff(RJWHediffDefOf.HumpShroomAddiction) && pawn.health.hediffSet.HasHediff(RJWHediffDefOf.HumpShroomEffect))
{
Trait nymphomaniac = new Trait(xxx.nymphomaniac);
pawn.story.traits.GainTrait(nymphomaniac);
newTraits.Add(nymphomaniac);
//Log.Message(xxx.get_pawnname(pawn) + " is HumpShroomAddicted, not nymphomaniac, adding nymphomaniac trait");
}
}
}
[SyncMethod]
private static void GiveQuirkTraits(SexProps props, List<Trait> newTraits, float traitGainChance = 0.05f)
{
var pawn = props.pawn;
if (RJWPreferenceSettings.PlayerIsFootSlut && !pawn.Has(Quirk.Podophile))
{
if (props.sexType == xxx.rjwSextype.Footjob)
if (props.IsSubmissive())
{
if (Rand.Chance(traitGainChance) || pawn.story.traits.HasTrait(xxx.footSlut))
{
pawn.Add(Quirk.Podophile);
if (RJWSettings.AddTrait_FootSlut)
{
Trait footSlut = new Trait(xxx.footSlut);
pawn.story.traits.GainTrait(footSlut);
newTraits.Add(footSlut);
}
}
}
}
if (RJWPreferenceSettings.PlayerIsCumSlut && !pawn.Has(Quirk.Cumslut))
{
if (props.sexType == xxx.rjwSextype.Fellatio)
if (props.IsSubmissive())
{
if (Rand.Chance(traitGainChance) || pawn.story.traits.HasTrait(xxx.cumSlut))
{
pawn.Add(Quirk.Cumslut);
if (RJWSettings.AddTrait_CumSlut)
{
Trait cumSlut = new Trait(xxx.cumSlut);
pawn.story.traits.GainTrait(cumSlut);
newTraits.Add(cumSlut);
}
}
}
}
if (RJWPreferenceSettings.PlayerIsButtSlut && !pawn.Has(Quirk.Buttslut))
{
if (props.sexType == xxx.rjwSextype.Anal)
if (props.IsSubmissive())
{
if (Rand.Chance(traitGainChance) || pawn.story.traits.HasTrait(xxx.buttSlut))
{
pawn.Add(Quirk.Buttslut);
if (RJWSettings.AddTrait_ButtSlut)
{
Trait buttSlut = new Trait(xxx.buttSlut);
pawn.story.traits.GainTrait(buttSlut);
newTraits.Add(buttSlut);
}
}
}
}
}
private static void SendTraitGainLetter(Pawn pawn, List<Trait> newTraits)
{
if (newTraits.Count == 0 || !PawnUtility.ShouldSendNotificationAbout(pawn))
{
return;
}
TaggedString letterLabel;
TaggedString letterDescription;
if (newTraits.Count == 1)
{
string traitLabel = newTraits[0].Label;
string letterLabelKey = TranslationKeyFor("LetterLabelGainedTraitFromSex", newTraits[0]);
letterLabel = letterLabelKey.Translate(traitLabel.Named("TRAIT"), pawn.Named("PAWN")).CapitalizeFirst();
string letterDescriptionKey = TranslationKeyFor("GainedTraitFromSex", newTraits[0]);
letterDescription = letterDescriptionKey.Translate(traitLabel.Named("TRAIT"), pawn.Named("PAWN")).CapitalizeFirst();
}
else
{
letterLabel = "LetterLabelGainedMultipleTraitsFromSex".Translate(pawn.Named("PAWN"));
letterDescription = "GainedMultipleTraitsFromSex".Translate(pawn.Named("PAWN"));
letterDescription += "\n";
foreach (var trait in newTraits)
{
letterDescription += "\n" + "GainedMultipleTraitsFromSexListItem".Translate(trait.LabelCap);
}
}
Find.LetterStack.ReceiveLetter(letterLabel, letterDescription, LetterDefOf.NeutralEvent, pawn);
string TranslationKeyFor(string stem, Trait trait)
{
string traitKey = stem + trait.def.defName;
string traitKeyWithDegree = traitKey + trait.Degree;
if (traitKeyWithDegree.CanTranslate())
{
return traitKeyWithDegree;
}
if (traitKey.CanTranslate())
{
return traitKey;
}
return stem;
}
}
// Checks if enough time has passed from previous lovin'.
public static bool ReadyForLovin(Pawn pawn)
{
return Find.TickManager.TicksGame > pawn.mindState.canLovinTick;
}
// Checks if enough time has passed from previous search for a hookup.
// Checks if hookups allowed during working hours, exlcuding nymphs
public static bool ReadyForHookup(Pawn pawn)
{
if (!xxx.is_nympho(pawn) && RJWHookupSettings.NoHookupsDuringWorkHours && ((pawn.timetable != null) ? pawn.timetable.CurrentAssignment : TimeAssignmentDefOf.Anything) == TimeAssignmentDefOf.Work) return false;
return Find.TickManager.TicksGame > CompRJW.Comp(pawn).NextHookupTick;
}
private static void IncreaseTicksToNextLovin(Pawn pawn)
{
if (pawn == null || pawn.Dead) return;
int currentTime = Find.TickManager.TicksGame;
if (pawn.mindState.canLovinTick <= currentTime)
pawn.mindState.canLovinTick = currentTime + GenerateMinTicksToNextLovin(pawn);
}
[SyncMethod]
public static int GenerateMinTicksToNextLovin(Pawn pawn)
{
if (DebugSettings.alwaysDoLovin) return 100;
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
float tick = 1.0f;
// Nymphs automatically get the tick increase from the trait influence on sex drive.
if (xxx.is_animal(pawn))
{
//var mateMtbHours = pawn.RaceProps.mateMtbHours / 24 * GenDate.TicksPerDay;
//if (mateMtbHours > 0)
// interval = mateMtbHours
if (RJWSettings.Animal_mating_cooldown == 0)
tick = 0.75f;
else
return RJWSettings.Animal_mating_cooldown * 2500;
}
else if (xxx.is_prude(pawn))
tick = 1.5f;
if (pawn.Has(Quirk.Vigorous))
tick *= 0.8f;
float sex_drive = xxx.get_sex_drive(pawn);
if (sex_drive <= 0.05f)
sex_drive = 0.05f;
float interval = AgeConfigDef.Instance.lovinIntervalHoursByAge.Evaluate(ScaleToHumanAge(pawn));
float rinterval = Math.Max(0.5f, Rand.Gaussian(interval, 0.3f));
return (int)(tick * rinterval * (2500.0f / sex_drive));
}
public static void IncreaseTicksToNextHookup(Pawn pawn)
{
if (pawn == null || pawn.Dead)
return;
// There are 2500 ticks per rimworld hour. Sleeping an hour between checks seems like a good start.
// We could get fancier and weight it by sex drive and stuff, but would people even notice?
const int TicksBetweenHookups = 2500;
int currentTime = Find.TickManager.TicksGame;
CompRJW.Comp(pawn).NextHookupTick = currentTime + TicksBetweenHookups;
}
/// <summary>
/// <para>Determines the sex type and handles the log output.</para>
/// <para>`props.pawn` should be initiator of the act (rapist, whore, etc).</para>
/// <para>`props.partner` should be the target.</para>
/// </summary>
public static void ProcessSex(SexProps props)
{
//Log.Message("usedCondom=" + usedCondom);
if (props.pawn == null || props.partner == null)
{
if (props.pawn == null)
ModLog.Error("[SexUtility] ERROR: pawn is null.");
if (props.partner == null)
ModLog.Error("[SexUtility] ERROR: partner is null.");
return;
}
IncreaseTicksToNextLovin(props.pawn);
IncreaseTicksToNextLovin(props.partner);
Aftersex(props);
AfterSexUtility.think_about_sex(props);
}
[SyncMethod]
public static SexProps SelectSextype(Pawn pawn, Pawn partner, bool rape, bool whoring)
{
var SP = new SexProps();
SP.pawn = pawn;
SP.partner = partner;
SP.isRape = rape;
SP.isWhoring = whoring;
//Caufendra's magic is happening here
InteractionInputs inputs = new InteractionInputs()
{
Initiator = pawn,
Partner = partner,
IsRape = rape,
IsWhoring = whoring
};
//this should be added as a static readonly but ... since the class is so big,
//it's probably best not to overload the static constructor
ILewdInteractionService lewdInteractionService = LewdInteractionService.Instance;
InteractionOutputs outputs = lewdInteractionService.GenerateInteraction(inputs);
SP.sexType = outputs.Generated.RjwSexType;
SP.rulePack = outputs.Generated.RulePack.defName;
SP.dictionaryKey = outputs.Generated.InteractionDef.Interaction;
return SP;
}
public static void LogSextype(Pawn giving, Pawn receiving, string rulepack, InteractionDef dictionaryKey)
{
List<RulePackDef> extraSentencePacks = new List<RulePackDef>();
if (!rulepack.NullOrEmpty())
extraSentencePacks.Add(RulePackDef.Named(rulepack));
LogSextype(giving, receiving, extraSentencePacks, dictionaryKey);
}
public static void LogSextype(Pawn giving, Pawn receiving, List<RulePackDef> extraSentencePacks, InteractionDef dictionaryKey)
{
if (extraSentencePacks.NullOrEmpty())
{
extraSentencePacks = new List<RulePackDef>();
string extraSentenceRulePack = SexRulePackGet(dictionaryKey);
if (!extraSentenceRulePack.NullOrEmpty())
extraSentencePacks.Add(RulePackDef.Named(extraSentenceRulePack));
}
PlayLogEntry_Interaction playLogEntry = new PlayLogEntry_Interaction(dictionaryKey, giving, receiving, extraSentencePacks);
Find.PlayLog.Add(playLogEntry);
}
[SyncMethod]
public static string SexRulePackGet(InteractionDef dictionaryKey)
{
var extension = Modules.Interactions.Helpers.InteractionHelper.GetWithExtension(dictionaryKey).Extension;
string extraSentenceRulePack = "";
if (!extension.rulepack_defs.NullOrEmpty())
{
extraSentenceRulePack = extension.rulepack_defs.RandomElement();
}
try
{
if (RulePackDef.Named(extraSentenceRulePack) != null)
{
}
}
catch
{
ModLog.Warning("RulePackDef " + extraSentenceRulePack + " for " + dictionaryKey + " not found");
extraSentenceRulePack = "";
}
return extraSentenceRulePack;
}
public static xxx.rjwSextype rjwSextypeGet(InteractionDef dictionaryKey)
{
var extension = Modules.Interactions.Helpers.InteractionHelper.GetWithExtension(dictionaryKey).Extension;
var sextype = xxx.rjwSextype.None;
if (!extension.rjwSextype.NullOrEmpty())
sextype = ParseHelper.FromString<xxx.rjwSextype>(extension.rjwSextype);
if (RJWSettings.DevMode) ModLog.Message("rjwSextypeGet:dictionaryKey " + dictionaryKey + " sextype " + sextype);
return sextype;
}
[SyncMethod]
public static void Sex_Beatings(SexProps props)
{
Pawn pawn = props.pawn;
Pawn partner = props.partner;
if ((xxx.is_animal(pawn) && xxx.is_animal(partner)))
return;
//dont remember what it does, probably manhunter stuff or not? disable and wait reports
//if (!xxx.is_human(pawn))
// return;
//If a pawn is incapable of violence/has low melee, they most likely won't beat their partner
if (pawn.skills?.GetSkill(SkillDefOf.Melee).Level < 1)
return;
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
float rand_value = Rand.Value;
//float rand_value = RJW_Multiplayer.RJW_MP_RAND();
float victim_pain = partner.health.hediffSet.PainTotal;
// bloodlust makes the aggressor more likely to hit the prisoner
float beating_chance = xxx.config.base_chance_to_hit_prisoner * (xxx.is_bloodlust(pawn) ? 1.5f : 1.0f);
// psychopath makes the aggressor more likely to hit the prisoner past the significant_pain_threshold
float beating_threshold = xxx.is_psychopath(pawn) ? xxx.config.extreme_pain_threshold : pawn.HostileTo(partner) ? xxx.config.significant_pain_threshold : xxx.config.minor_pain_threshold;
//--Log.Message("roll_to_hit: rand = " + rand_value + ", beating_chance = " + beating_chance + ", victim_pain = " + victim_pain + ", beating_threshold = " + beating_threshold);
if ((victim_pain < beating_threshold && rand_value < beating_chance) || (rand_value < (beating_chance / 2) && xxx.is_bloodlust(pawn)))
{
Sex_Beatings_Dohit(pawn, partner, props.isRapist);
}
}
public static void Sex_Beatings_Dohit(Pawn pawn, Pawn partner, bool isRape = false)
{
//--Log.Message(" done told her twice already...");
if (InteractionUtility.TryGetRandomVerbForSocialFight(pawn, out Verb v))
{
//Log.Message(" v. : " + v);
//Log.Message(" v.GetDamageDef : " + v.GetDamageDef());
//Log.Message(" v.v.tool - " + v.tool.label);
//Log.Message(" v.v.tool.power base - " + v.tool.power);
var orgpower = v.tool.power;
//in case something goes wrong
try
{
//Log.Message(" v.v.tool.power base - " + v.tool.power);
if (RJWSettings.gentle_rape_beating || !isRape)
{
v.tool.power = 0;
//partner.stances.stunner.StunFor(600, pawn);
}
//Log.Message(" v.v.tool.power mod - " + v.tool.power);
var guilty = true;
if (!pawn.guilt.IsGuilty)
{
guilty = false;
}
pawn.meleeVerbs.TryMeleeAttack(partner, v);
if (pawn.guilt.IsGuilty && !guilty)
pawn.guilt.Notify_Guilty(0);
}
catch
{ }
v.tool.power = orgpower;
//Log.Message(" v.v.tool.power reset - " + v.tool.power);
}
}
// Overrides the current clothing. Defaults to nude, with option to keep headgear on.
public static void DrawNude(Pawn pawn, bool keep_hat_on = false)
{
if (!xxx.is_human(pawn)) return;
if (pawn.Map != Find.CurrentMap) return;
if (RJWPreferenceSettings.sex_wear == RJWPreferenceSettings.Clothing.Clothed) return;
//undress
pawn.Drawer.renderer.graphics.ClearCache();
pawn.Drawer.renderer.graphics.apparelGraphics.Clear();
//pawn.Drawer.renderer.graphics.ResolveApparelGraphics();
//Log.Message("DrawNude: " + pawn.Name);
//add "clothes"
foreach (Apparel current in pawn.apparel.WornApparel.Where(x
=> x.def is bondage_gear_def
|| (!x.def.thingCategories.NullOrEmpty() && x.def.thingCategories.Any(x => x.defName.ToLower().ContainsAny("vibrator", "piercing", "strapon")))
|| RJWPreferenceSettings.sex_wear == RJWPreferenceSettings.Clothing.Headgear
|| keep_hat_on
&& (!x.def.apparel.bodyPartGroups.NullOrEmpty() && (x.def.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf.FullHead)
|| x.def.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf.UpperHead)))))
{
ApparelGraphicRecord item;
if (ApparelGraphicRecordGetter.TryGetGraphicApparel(current, pawn.story.bodyType, out item))
{
pawn.Drawer.renderer.graphics.apparelGraphics.Add(item);
}
}
GlobalTextureAtlasManager.TryMarkPawnFrameSetDirty(pawn);
}
public static void reduce_rest(Pawn pawn, float x = 1f)
{
if (pawn.Has(Quirk.Vigorous)) x -= x / 2;
Need_Rest need_rest = pawn.needs.TryGetNeed<Need_Rest>();
if (need_rest == null)
return;
need_rest.CurLevel -= need_rest.RestFallPerTick * x;
}
public static void OffsetPsyfocus(Pawn pawn, float x = 0)//0-1
{
if (ModsConfig.RoyaltyActive)
{
//pawn.psychicEntropy.Notify_Meditated();
if (pawn.HasPsylink)
{
pawn.psychicEntropy.OffsetPsyfocusDirectly(x);
}
}
}
//Takes the nutrition away from the one penetrating(probably) and injects it to the one on the receiving end
//As with everything in the mod, this could be greatly extended, current focus though is to prevent starvation of those caught in a huge horde of rappers (that may happen with some mods)
public static void TransferNutrition(SexProps props)
{
//Log.Message("xxx::TransferNutrition:: " + xxx.get_pawnname(pawn) + " => " + xxx.get_pawnname(partner));
if (props.partner?.needs == null)
{
//Log.Message("xxx::TransferNutrition() failed due to lack of transfer equipment or pawn ");
return;
}
if (props.pawn?.needs == null)
{
//Log.Message("xxx::TransferNutrition() failed due to lack of transfer equipment or pawn ");
return;
}
//transfer nutrition from presumanbly "giver" to partner
if (props.sexType == xxx.rjwSextype.Sixtynine ||
props.sexType == xxx.rjwSextype.Oral ||
props.sexType == xxx.rjwSextype.Cunnilingus ||
props.sexType == xxx.rjwSextype.Fellatio)
{
Pawn pawn = props.pawn;
Pawn partner = props.partner;
Pawn giver, receiver;
List<Hediff> pawnparts = pawn.GetGenitalsList();
List<Hediff> partnerparts = partner.GetGenitalsList();
bool t = false;
if (props.sexType == xxx.rjwSextype.Sixtynine || Genital_Helper.has_penis_fertile(pawn, pawnparts) || Genital_Helper.has_ovipositorF(pawn, pawnparts))
{
giver = pawn;
receiver = partner;
Need_Food need = giver.needs?.TryGetNeed<Need_Food>();
if (need == null)
{
//Log.Message("TransferNutrition() " + xxx.get_pawnname(giver) + " doesn't track nutrition in itself, probably shouldn't feed the others");
return;
}
float nutrition_amount = Math.Min(need.MaxLevel / 15f, need.CurLevel); //body size is taken into account implicitly by need.MaxLevel
giver.needs.food.CurLevel = need.CurLevel - nutrition_amount;
//Log.Message("TransferNutrition() " + xxx.get_pawnname(giver) + " sent " + nutrition_amount + " of nutrition");
if (receiver.needs?.TryGetNeed<Need_Food>() != null)
{
//Log.Message("xxx::TransferNutrition() " + xxx.get_pawnname(receiver) + " can receive");
receiver.needs.food.CurLevel += nutrition_amount;
}
TransferThirst(giver, receiver);
t = true;
}
if (props.sexType == xxx.rjwSextype.Sixtynine || (t == false && props.isCoreLovin && (Genital_Helper.has_penis_fertile(partner, partnerparts) || Genital_Helper.has_ovipositorF(partner, partnerparts))))
{
giver = partner;
receiver = pawn;
Need_Food need = giver.needs?.TryGetNeed<Need_Food>();
if (need == null)
{
//Log.Message("TransferNutrition() " + xxx.get_pawnname(giver) + " doesn't track nutrition in itself, probably shouldn't feed the others");
return;
}
float nutrition_amount = Math.Min(need.MaxLevel / 15f, need.CurLevel); //body size is taken into account implicitly by need.MaxLevel
giver.needs.food.CurLevel = need.CurLevel - nutrition_amount;
//Log.Message("TransferNutrition() " + xxx.get_pawnname(giver) + " sent " + nutrition_amount + " of nutrition");
if (receiver.needs?.TryGetNeed<Need_Food>() != null)
{
//Log.Message("TransferNutrition() " + xxx.get_pawnname(receiver) + " can receive");
receiver.needs.food.CurLevel += nutrition_amount;
}
TransferThirst(giver, receiver);
}
}
TransferNutritionSucc(props);
}
public static void TransferThirst(Pawn pawn, Pawn receiver)
{
if (xxx.DubsBadHygieneIsActive)
{
Need DBHThirst = receiver.needs?.AllNeeds.Find(x => x.def == xxx.DBHThirst);
if (DBHThirst != null)
{
//Log.Message("TransferThirst() " + xxx.get_pawnname(receiver) + " decreasing thirst");
receiver.needs.TryGetNeed(DBHThirst.def).CurLevel += 0.1f;
}
}
}
public static void TransferNutritionSucc(SexProps props)
{
//succubus mana and rest regen stuff
if (props.sexType == xxx.rjwSextype.Oral ||
props.sexType == xxx.rjwSextype.Cunnilingus ||
props.sexType == xxx.rjwSextype.Fellatio ||
props.sexType == xxx.rjwSextype.Vaginal ||
props.sexType == xxx.rjwSextype.Anal ||
props.sexType == xxx.rjwSextype.DoublePenetration)
{
if (xxx.has_traits(props.partner))
{
bool gainrest = false;
if (xxx.RoMIsActive && (props.partner.story.traits.HasTrait(xxx.Succubus) || props.partner.story.traits.HasTrait(xxx.Warlock)))
{
Need TM_Mana = props.partner?.needs?.AllNeeds.Find(x => x.def == xxx.TM_Mana);
if (TM_Mana != null)
{
//Log.Message("TransferNutritionSucc() " + xxx.get_pawnname(partner) + " increase mana");
props.partner.needs.TryGetNeed(TM_Mana.def).CurLevel += 0.1f;
}
gainrest = true;
}
if (xxx.NightmareIncarnationIsActive)
{
foreach (var x in props.partner.AllComps?.Where(x => x.props?.ToString() == "NightmareIncarnation.CompProperties_SuccubusRace"))
{
Need NI_Need_Mana = props.partner?.needs?.AllNeeds.Find(x => x.def == xxx.NI_Need_Mana);
if (NI_Need_Mana != null)
{
//Log.Message("TransferNutritionSucc() " + xxx.get_pawnname(partner) + " increase mana");
props.partner.needs.TryGetNeed(NI_Need_Mana.def).CurLevel += 0.1f;
}
gainrest = true;
break;
}
}
if (gainrest)
{
Need_Rest need1 = props.pawn.needs?.TryGetNeed<Need_Rest>();
Need_Rest need2 = props.partner.needs?.TryGetNeed<Need_Rest>();
if (need1 != null && need2 != null)
{
//Log.Message("TransferNutritionSucc() " + xxx.get_pawnname(partner) + " increase rest");
props.partner.needs.TryGetNeed(need2.def).CurLevel += 0.25f;
//Log.Message("TransferNutritionSucc() " + xxx.get_pawnname(pawn) + " decrease rest");
props.pawn.needs.TryGetNeed(need1.def).CurLevel -= 0.25f;
}
}
}
if (xxx.has_traits(props.pawn))
{
bool gainrest = false;
if (xxx.RoMIsActive && (props.pawn.story.traits.HasTrait(xxx.Succubus) || props.pawn.story.traits.HasTrait(xxx.Warlock)))
{
Need TM_Mana = props.pawn?.needs?.AllNeeds.Find(x => x.def == xxx.TM_Mana);
if (TM_Mana != null)
{
//Log.Message("TransferNutritionSucc() " + xxx.get_pawnname(pawn) + " increase mana");
props.pawn.needs.TryGetNeed(TM_Mana.def).CurLevel += 0.1f;
}
}
if (xxx.NightmareIncarnationIsActive)
{
foreach (var x in props.pawn.AllComps?.Where(x => x.props?.ToString() == "NightmareIncarnation.CompProperties_SuccubusRace"))
{
Need NI_Need_Mana = props.pawn?.needs?.AllNeeds.Find(x => x.def == xxx.NI_Need_Mana);
if (NI_Need_Mana != null)
{
//Log.Message("TransferNutritionSucc() " + xxx.get_pawnname(partner) + " increase mana");
props.pawn.needs.TryGetNeed(NI_Need_Mana.def).CurLevel += 0.1f;
}
gainrest = true;
break;
}
}
if (gainrest)
{
Need_Rest need1 = props.partner.needs.TryGetNeed<Need_Rest>();
Need_Rest need2 = props.pawn.needs.TryGetNeed<Need_Rest>();
if (need1 != null && need2 != null)
{
//Log.Message("TransferNutritionSucc() " + xxx.get_pawnname(pawn) + " increase rest");
props.pawn.needs.TryGetNeed(need2.def).CurLevel += 0.25f;
//Log.Message("TransferNutritionSucc() " + xxx.get_pawnname(partner) + " decrease rest");
props.partner.needs.TryGetNeed(need1.def).CurLevel -= 0.25f;
}
}
}
}
}
public static float get_broken_consciousness_debuff(Pawn pawn)
{
if (pawn == null)
{
return 1.0f;
}
try
{
Hediff broken = pawn.health.hediffSet.GetFirstHediffOfDef(xxx.feelingBroken);
foreach (PawnCapacityModifier capMod in broken.CapMods)
{
if (capMod.capacity == PawnCapacityDefOf.Consciousness)
{
if (RJWSettings.DevMode) ModLog.Message("Broken Pawn Consciousness factor: " + capMod.postFactor);
return capMod.postFactor;
}
}
// fallback
return 1.0f;
}
catch (NullReferenceException)
{
//Log.Warning(e.ToString());
return 1f;
}
}
public static float get_satisfaction_circumstance_multiplier(SexProps props)
{
// Get a multiplier for satisfaction that should apply on top of the sex satisfaction stat
// This is mostly for traits that only affect satisfaction in some circumstances
Pawn pawn = props.pawn;
Boolean isViolentSex = props.isRape;
float multiplier = 1.0f;
if (xxx.is_human(pawn))
{
// Negate consciousness debuffs for broken pawns (counters the sex satisfaction score being affected by low consciousness)
multiplier = (1.0f / get_broken_consciousness_debuff(pawn));
// Multiplier bonus for violent traits and violent sex
if (!props.isReceiver)
{
// Rapists/Bloodlusts get 50% more satisfaction from violent encounters, and less from non-violent
if (isViolentSex)
{
if (xxx.is_rapist(pawn) || xxx.is_bloodlust(pawn) || xxx.is_psychopath(pawn))
multiplier += 0.5f;
else
multiplier -= 0.2f;
}
else
{
if (xxx.is_rapist(pawn) || xxx.is_bloodlust(pawn))
multiplier -= 0.2f;
else
multiplier += 0.2f;
}
}
else if (props.isReceiver)
{
// Masochists get 50% more satisfaction from receiving violent sex and 20% less from normal sex
if (isViolentSex)
{
if (xxx.is_masochist(pawn))
multiplier += 0.5f;
else
multiplier -= 0.2f;
}
else
{
if (xxx.is_masochist(pawn))
multiplier -= 0.2f;
else
multiplier += 0.2f;
}
// Multiplier for broken pawns
if (isViolentSex && AfterSexUtility.BodyIsBroken(pawn))
{
// Add bonus satisfaction based on stage
switch (pawn.health.hediffSet.GetFirstHediffOfDef(xxx.feelingBroken).CurStageIndex)
{
case 0:
break;
case 1:
// 50% bonus for stage 2
//multiplier += 0.5f;
break;
case 2:
// 100% bonus for stage 2
multiplier += 1.0f;
break;
}
}
}
//ModLog.Message("Sex satisfaction multiplier: " + multiplier);
}
return multiplier;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Helpers/SexUtility.cs
|
C#
|
mit
| 44,693
|
using Multiplayer.API;
using Verse;
namespace rjw
{
public static class Sexualizer
{
static void SexualizeSingleGenderPawn(Pawn pawn)
{
// Single gender is futa without the female gender change.
SexPartAdder.add_genitals(pawn, null, Gender.Male);
SexPartAdder.add_genitals(pawn, null, Gender.Female);
SexPartAdder.add_breasts(pawn, null, Gender.Female);
SexPartAdder.add_anus(pawn, null);
}
static void SexualizeGenderlessPawn(Pawn pawn)
{
if (RJWSettings.GenderlessAsFuta && !xxx.is_mechanoid(pawn) && (pawn.RaceProps.Animal || pawn.RaceProps.Humanlike))
{
if (RJWSettings.DevMode)
ModLog.Message(" SexualizeGenderlessPawn() - genderless pawn, treating Genderless pawn As Futa" + xxx.get_pawnname(pawn));
//set gender to female for futas
pawn.gender = Gender.Female;
SexPartAdder.add_genitals(pawn, null, Gender.Male);
SexPartAdder.add_genitals(pawn, null, Gender.Female);
SexPartAdder.add_breasts(pawn, null, Gender.Female);
SexPartAdder.add_anus(pawn, null);
}
else
{
if (RJWSettings.DevMode)
ModLog.Message(" SexualizeGenderlessPawn() - unable to sexualize genderless pawn " + xxx.get_pawnname(pawn) + " gender: " + pawn.gender);
}
}
[SyncMethod]
static void SexualizeGenderedPawn(Pawn pawn)
{
//apply normal gender
SexPartAdder.add_genitals(pawn, null, pawn.gender);
//apply futa gender
//if (pawn.gender == Gender.Female) // changing male to futa will break pawn generation due to relations
if (pawn.Faction != null && !xxx.is_animal(pawn)) //null faction throws error
{
//ModLog.Message(" SexualizeGenderedPawn( " + xxx.get_pawnname(pawn) + " ) techLevel: " + (int)pawn.Faction.def.techLevel);
//ModLog.Message(" SexualizeGenderedPawn( " + xxx.get_pawnname(pawn) + " ) techLevel: " + pawn.Faction.Name);
//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;
// ModLog.Message($"SexualizeGenderedPawn {chance} from {RJWSettings.futa_nymph_chance} {RJWSettings.futa_natives_chance} {RJWSettings.futa_spacers_chance}");
if (Rand.Chance(chance))
{
//make futa
if (pawn.gender == Gender.Female && RJWSettings.FemaleFuta)
SexPartAdder.add_genitals(pawn, null, Gender.Male);
//make trap
else if (pawn.gender == Gender.Male && RJWSettings.MaleTrap)
SexPartAdder.add_breasts(pawn, null, Gender.Female);
}
}
SexPartAdder.add_breasts(pawn, null, pawn.gender);
SexPartAdder.add_anus(pawn, null);
}
[SyncMethod]
public static void sexualize_pawn(Pawn pawn)
{
//ModLog.Message(" sexualize_pawn( " + xxx.get_pawnname(pawn) + " ) called");
if (pawn == null)
{
return;
}
//override pawn
if (RacePartDef_Helper.TryRacePartDef_partAdders(pawn))
return;
if (RaceGroupDef_Helper.TryGetRaceGroupDef(pawn, out var raceGroupDef) &&
raceGroupDef.hasSingleGender)
{
if (RJWSettings.DevMode)
ModLog.Message($"sexualize_pawn() - sexualizing single gender pawn {xxx.get_pawnname(pawn)} race: {raceGroupDef.defName}");
SexualizeSingleGenderPawn(pawn);
}
else if (pawn.RaceProps.hasGenders)
{
SexualizeGenderedPawn(pawn);
}
else
{
if (Current.ProgramState == ProgramState.Playing) // DO NOT run at world generation, throws error in generating relationship stuff
{
SexualizeGenderlessPawn(pawn);
return;
}
}
if (!pawn.Dead)
{
//Add ticks at generation, so pawns don't instantly start lovin' when generated (esp. on scenario start).
//if (xxx.RoMIsActive && pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_ShapeshiftHD"))) // Rimworld of Magic's polymorph/shapeshift
// pawn.mindState.canLovinTick = Find.TickManager.TicksGame + (int)(SexUtility.GenerateMinTicksToNextLovin(pawn) * Rand.Range(0.01f, 0.05f));
if (!xxx.is_insect(pawn))
pawn.mindState.canLovinTick = Find.TickManager.TicksGame + (int)(SexUtility.GenerateMinTicksToNextLovin(pawn) * Rand.Range(0.1f, 1.0f));
else
pawn.mindState.canLovinTick = Find.TickManager.TicksGame + (int)(SexUtility.GenerateMinTicksToNextLovin(pawn) * Rand.Range(0.01f, 0.2f));
//ModLog.Message(" sexualize_pawn( " + xxx.get_pawnname(pawn) + " ) add sexneed");
if (pawn.RaceProps.Humanlike)
{
var sex_need = pawn.needs.TryGetNeed<Need_Sex>();
if (pawn.Faction != null && !(pawn.Faction?.IsPlayer ?? false) && sex_need != null)
{
sex_need.CurLevel = Rand.Range(0.01f, 0.75f);
}
}
}
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Helpers/Sexualizer.cs
|
C#
|
mit
| 4,679
|
using System;
using System.Diagnostics;
using UnityEngine;
using Verse;
namespace rjw
{
public static class Logger
{
private static readonly LogMessageQueue messageQueueRJW = new LogMessageQueue();
public static void Message(string text)
{
bool DevModeEnabled = RJWSettings.DevMode;
if (!DevModeEnabled) return;
UnityEngine.Debug.Log(text);
messageQueueRJW.Enqueue(new LogMessage(LogMessageType.Message, text, StackTraceUtility.ExtractStackTrace()));
}
public static void Warning(string text)
{
bool DevModeEnabled = RJWSettings.DevMode;
if (!DevModeEnabled) return;
UnityEngine.Debug.Log(text);
messageQueueRJW.Enqueue(new LogMessage(LogMessageType.Warning, text, StackTraceUtility.ExtractStackTrace()));
}
public static void Error(string text)
{
bool DevModeEnabled = RJWSettings.DevMode;
if (!DevModeEnabled) return;
UnityEngine.Debug.Log(text);
messageQueueRJW.Enqueue(new LogMessage(LogMessageType.Error, text, StackTraceUtility.ExtractStackTrace()));
}
public static TimeSpan Time(Action action)
{
Stopwatch stopwatch = Stopwatch.StartNew();
action();
stopwatch.Stop();
return stopwatch.Elapsed;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Logger.cs
|
C#
|
mit
| 1,190
|
using Verse;
namespace rjw
{
public class MapCom_Injector : MapComponent
{
public bool injected_designator = false;
public bool triggered_after_load = false;
public MapCom_Injector(Map m) : base(m)
{
}
public override void MapComponentUpdate()
{
}
public override void MapComponentTick()
{
}
public override void MapComponentOnGUI()
{
var currently_visible = Find.CurrentMap == map;
if ((!injected_designator) && currently_visible)
{
//Find.ReverseDesignatorDatabase.AllDesignators.Add(new Designator_ComfortPrisoner());
//Find.ReverseDesignatorDatabase.AllDesignators.Add(new Designator_Breed());
injected_designator = true;
}
else if (injected_designator && (!currently_visible))
injected_designator = false;
}
public override void ExposeData()
{
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/MapCom_Injector.cs
|
C#
|
mit
| 833
|
using System;
using Verse;
namespace rjw
{
public sealed class MiscTranslationDef : Def
{
public Type targetClass;
public string stringA = null;
public string stringB = null;
public string stringC = null;
private void Assert(bool check, string errorMessage)
{
if (!check)
{
ModLog.Error($"Invalid data in MiscTranslationDef {defName}: {errorMessage}");
}
}
public override void PostLoad()
{
Assert(targetClass != null, "targetClass field must be set");
}
public override void ResolveReferences()
{
base.ResolveReferences();
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/MiscTranslationDef.cs
|
C#
|
mit
| 584
|
using Verse;
namespace rjw
{
public static class ModLog
{
/// <summary>
/// Logs the given message with [SaveStorage.ModId] appended.
/// </summary>
public static void Error(string message)
{
Log.Error($"[{SaveStorage.ModId}] {message}");
}
/// <summary>
/// Logs the given message with [SaveStorage.ModId] appended.
/// </summary>
public static void Message(string message)
{
Log.Message($"[{SaveStorage.ModId}] {message}");
}
/// <summary>
/// Logs the given message with [SaveStorage.ModId] appended.
/// </summary>
public static void Warning(string message)
{
Log.Warning($"[{SaveStorage.ModId}] {message}");
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/ModLog.cs
|
C#
|
mit
| 673
|
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
namespace rjw
{
public static class PawnExtensions
{
public static bool RaceHasFertility(this Pawn pawn)
{
// True by default.
if (RaceGroupDef_Helper.TryGetRaceGroupDef(pawn, out var raceGroupDef))
return raceGroupDef.hasFertility;
return true;
}
public static bool RaceHasPregnancy(this Pawn pawn)
{
// True by default.
if (RaceGroupDef_Helper.TryGetRaceGroupDef(pawn, out var raceGroupDef))
return raceGroupDef.hasPregnancy;
return true;
}
public static bool RaceHasOviPregnancy(this Pawn pawn)
{
// False by default.
if (RaceGroupDef_Helper.TryGetRaceGroupDef(pawn, out var raceGroupDef))
return raceGroupDef.oviPregnancy;
return false;
}
public static bool RaceImplantEggs(this Pawn pawn)
{
// False by default.
if (RaceGroupDef_Helper.TryGetRaceGroupDef(pawn, out var raceGroupDef))
return raceGroupDef.ImplantEggs;
return false;
}
public static bool RaceHasSexNeed(this Pawn pawn)
{
// True by default.
if (RaceGroupDef_Helper.TryGetRaceGroupDef(pawn, out var raceGroupDef))
return raceGroupDef.hasSexNeed;
return true;
}
public static bool TryAddRacePart(this Pawn pawn, SexPartType sexPartType)
{
return RaceGroupDef_Helper.TryAddRacePart(pawn, sexPartType);
}
public static bool Has(this Pawn pawn, Quirk quirk)
{
return xxx.has_quirk(pawn, quirk.Key);
}
public static bool Has(this Pawn pawn, RaceTag tag)
{
if (RaceGroupDef_Helper.TryGetRaceGroupDef(pawn, out var raceGroupDef))
{
return raceGroupDef.tags != null && raceGroupDef.tags.Contains(tag.Key);
}
else
{
return tag.DefaultWhenNoRaceGroupDef(pawn);
}
}
public static void Add(this Pawn pawn, Quirk quirk)
{
QuirkAdder.Add(pawn, quirk);
}
public static bool IsSexyRobot(this Pawn pawn)
{
return AndroidsCompatibility.IsAndroid(pawn);
}
// In theory I think this should involve RaceGroupDef.
public static bool IsUnsexyRobot(this Pawn pawn)
{
return !IsSexyRobot(pawn)
&& (xxx.is_mechanoid(pawn) || pawn.kindDef.race.defName.ToLower().Contains("droid"));
}
public static bool IsAnimal(this Pawn pawn)
{
return xxx.is_animal(pawn);
}
public static bool IsHuman(this Pawn pawn)
{
return xxx.is_human(pawn);
}
public static bool IsPoly(this Pawn pawn)
{
if (!pawn.IsHuman())
{
return true;
}
if (pawn.IsIdeologicallyPoly())
{
return true;
}
if (pawn.story?.traits == null)
{
return false;
}
if (xxx.AnyPolyamoryModIsActive && pawn.story.traits.HasTrait(xxx.polyamorous))
{
return true;
}
if (xxx.AnyPolygamyModIsActive && pawn.story.traits.HasTrait(xxx.polygamous))
{
return true;
}
return false;
}
public static bool IsVisiblyPregnant(this Pawn pawn)
{
return pawn.IsPregnant(true);
}
public static bool IsPregnant(this Pawn pawn, bool mustBeVisible = false)
{
var set = pawn.health.hediffSet;
return set.HasHediff(HediffDefOf.PregnantHuman, mustBeVisible) ||
set.HasHediff(HediffDefOf.Pregnant, mustBeVisible) ||
Hediff_BasePregnancy.KnownPregnancies().Any(x => set.HasHediff(HediffDef.Named(x), mustBeVisible));
}
public static List<Hediff> GetGenitalsList(this Pawn pawn)
{
List<Hediff> set;
try//error at world gen
{
set = pawn.GetRJWPawnData().genitals;
if (set.NullOrEmpty())
{
var partBPR = Genital_Helper.get_genitalsBPR(pawn);
set = Genital_Helper.get_PartsHediffList(pawn, partBPR);
pawn.GetRJWPawnData().genitals = set;
}
}
catch
{
var partBPR = Genital_Helper.get_genitalsBPR(pawn);
set = Genital_Helper.get_PartsHediffList(pawn, partBPR);
}
return set;
}
public static List<Hediff> GetBreastList(this Pawn pawn)
{
List<Hediff> set;
try//error at world gen
{
set = pawn.GetRJWPawnData().breasts;
if (set.NullOrEmpty())
{
var partBPR = Genital_Helper.get_breastsBPR(pawn);
set = Genital_Helper.get_PartsHediffList(pawn, partBPR);
pawn.GetRJWPawnData().breasts = set;
}
}
catch
{
var partBPR = Genital_Helper.get_breastsBPR(pawn);
set = Genital_Helper.get_PartsHediffList(pawn, partBPR);
}
return set;
}
public static List<Hediff> GetUdderList(this Pawn pawn)
{
List<Hediff> set;
try//error at world gen
{
set = pawn.GetRJWPawnData().udders;
if (set.NullOrEmpty())
{
var partBPR = Genital_Helper.get_uddersBPR(pawn);
set = Genital_Helper.get_PartsHediffList(pawn, partBPR);
pawn.GetRJWPawnData().udders = set;
}
}
catch
{
var partBPR = Genital_Helper.get_breastsBPR(pawn);
set = Genital_Helper.get_PartsHediffList(pawn, partBPR);
}
return set;
}
public static List<Hediff> GetAnusList(this Pawn pawn)
{
List<Hediff> set;
try//error at world gen
{
set = pawn.GetRJWPawnData().anus;
if (set.NullOrEmpty())
{
var partBPR = Genital_Helper.get_anusBPR(pawn);
set = Genital_Helper.get_PartsHediffList(pawn, partBPR);
pawn.GetRJWPawnData().anus = set;
}
}
catch
{
var partBPR = Genital_Helper.get_anusBPR(pawn);
set = Genital_Helper.get_PartsHediffList(pawn, partBPR);
}
return set;
}
public static List<Hediff> GetTorsoList(this Pawn pawn)
{
List<Hediff> set;
try//error at world gen
{
set = pawn.GetRJWPawnData().torso;
if (set.NullOrEmpty())
{
var partBPR = Genital_Helper.get_torsoBPR(pawn);
set = Genital_Helper.get_PartsHediffList(pawn, partBPR);
pawn.GetRJWPawnData().torso = set;
}
}
catch
{
var partBPR = Genital_Helper.get_torsoBPR(pawn);
set = Genital_Helper.get_PartsHediffList(pawn, partBPR);
}
return set;
}
public static SexProps GetRMBSexPropsCache(this Pawn pawn)
{
SexProps set;
set = pawn.GetRJWPawnData().SexProps;
return set;
}
public static PawnData GetRJWPawnData(this Pawn pawn)
{
return SaveStorage.DataStore.GetPawnData(pawn);
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/PawnExtensions.cs
|
C#
|
mit
| 6,145
|
using HarmonyLib;
using RimWorld;
using System.Collections.Generic;
using System.Linq;
using Verse;
using Verse.AI;
using Multiplayer.API;
using rjw.Modules.Interactions;
using rjw.Modules.Interactions.Implementation;
namespace rjw
{
[StaticConstructorOnStartup]
static class RMB_Masturbate
{
static RMB_Masturbate()
{
Harmony harmony = new Harmony("rjw");
//start sex options
harmony.Patch(AccessTools.Method(typeof(RMB_Menu), "GenerateRMBOptions"), prefix: null,
postfix: new HarmonyMethod(typeof(RMB_Masturbate), nameof(ChoicesAtFor)));
}
public static List<FloatMenuOption> ChoicesAtFor(List<FloatMenuOption> __instance, Pawn pawn, LocalTargetInfo target)
{
FloatMenuOption(pawn, ref __instance, ref target);
return __instance;
}
public static void FloatMenuOption(Pawn pawn, ref List<FloatMenuOption> opts, ref LocalTargetInfo target)
{
opts.AddRange(GenerateRMBOptions(pawn, target).Where(x => x.action != null));
}
public static List<FloatMenuOption> GenerateRMBOptions(Pawn pawn, LocalTargetInfo target)
{
List<FloatMenuOption> opts = new List<FloatMenuOption>();
FloatMenuOption option = null;
if (target.Pawn == pawn)
{
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_Masturbate".Translate(), delegate ()
{
FloatMenuUtility.MakeMenu(GenerateSoloSexRoleOptions(pawn, target).Where(x => x.action != null), (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
}, MenuOptionPriority.High), pawn, target);
opts.AddDistinct(option);
}
return opts;
}
//this options probably can be merged into 1, but for now/testing keep it separate
public static List<FloatMenuOption> GenerateSoloSexRoleOptions(Pawn pawn, LocalTargetInfo target)
{
List<FloatMenuOption> opts = new List<FloatMenuOption>();
FloatMenuOption option = null;
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_Masturbate_Bed".Translate(), delegate ()
{
Find.Targeter.BeginTargeting(TargetParemetersMasturbationChairOrBed(target), (LocalTargetInfo targetThing) =>
{
FloatMenuUtility.MakeMenu(GenerateSoloSexPoseOptions(pawn, targetThing).Where(x => x.action != null), (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
});
}, MenuOptionPriority.High), pawn, target);
opts.AddDistinct(option);
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_Masturbate_At".Translate(), delegate ()
{
Find.Targeter.BeginTargeting(TargetParemetersMasturbationLoc(target), (LocalTargetInfo targetThing) =>
{
FloatMenuUtility.MakeMenu(GenerateSoloSexPoseOptions(pawn, targetThing).Where(x => x.action != null), (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
});
}, MenuOptionPriority.High), pawn, target);
opts.AddDistinct(option);
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_Masturbate_Here".Translate(), delegate ()
{
FloatMenuUtility.MakeMenu(GenerateSoloSexPoseOptions(pawn, target).Where(x => x.action != null), (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
}, MenuOptionPriority.High), pawn, target);
opts.AddDistinct(option);
return opts;
}
public static TargetingParameters TargetParemetersMasturbationChairOrBed(LocalTargetInfo target)
{
return new TargetingParameters()
{
canTargetBuildings = true,
mapObjectTargetsMustBeAutoAttackable = false,
validator = (TargetInfo target) =>
{
if (!target.HasThing)
return false;
Building building = target.Thing as Building;
if (building == null)
return false;
if (building.def.building.isSittable)
return true;
if (building is Building_Bed)
return true;
return false;
}
};
}
public static TargetingParameters TargetParemetersMasturbationLoc(LocalTargetInfo target)
{
return new TargetingParameters()
{
canTargetLocations = true,
mapObjectTargetsMustBeAutoAttackable = false,
validator = (TargetInfo target) =>
{
if (!target.HasThing)
return true;
return false;
}
};
}
public static List<FloatMenuOption> GenerateSoloSexPoseOptions(Pawn pawn, LocalTargetInfo target)
{
List<FloatMenuOption> opts = new List<FloatMenuOption>();
FloatMenuOption option = null;
var job = xxx.Masturbate;
List<InteractionDef> validintdefs = new List<InteractionDef>();
foreach (InteractionDef d in SexUtility.SexInterractions)
{
var interaction = Modules.Interactions.Helpers.InteractionHelper.GetWithExtension(d);
if (interaction.Extension.rjwSextype != xxx.rjwSextype.Masturbation.ToStringSafe())
continue;
ILewdInteractionValidatorService service = LewdInteractionValidatorService.Instance;
if (service.IsValid(d, pawn, pawn))
validintdefs.Add(d);
}
foreach (InteractionDef dictionaryKey in validintdefs)
{
var interaction = Modules.Interactions.Helpers.InteractionHelper.GetWithExtension(dictionaryKey);
var dev = "";
if (RJWSettings.DevMode)
dev = " ( defName: " + dictionaryKey.defName + ")";
var label = interaction.Extension.RMBLabel.CapitalizeFirst() + dev;
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(label, delegate ()
{
RMB_Menu.HaveSex(pawn, job, target, dictionaryKey);
}, MenuOptionPriority.High), pawn, target);
opts.AddDistinct(option);
}
if (opts.NullOrEmpty())
opts.AddDistinct(new FloatMenuOption("none", null));
return opts;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/RMB/RMB_Masturbate.cs
|
C#
|
mit
| 5,628
|
using HarmonyLib;
using RimWorld;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Verse;
using Verse.AI;
using Multiplayer.API;
using rjw.Modules.Interactions.Enums;
using rjw.Modules.Interactions;
using rjw.Modules.Interactions.Implementation;
using rjw.Modules.Interactions.Objects;
using static RimWorld.MechClusterSketch;
namespace rjw
{
[StaticConstructorOnStartup]
static class RMB_Menu
{
static RMB_Menu()
{
Harmony harmony = new Harmony("rjw");
//start sex options
harmony.Patch(AccessTools.Method(typeof(FloatMenuMakerMap), "ChoicesAtFor"), prefix: null,
postfix: new HarmonyMethod(typeof(RMB_Menu), nameof(ChoicesAtFor)));
}
//show rmb on
public static TargetingParameters TargetParameters
{
get
{
if (targetParameters == null)
{
targetParameters = new TargetingParameters()
{
canTargetHumans = true,
canTargetAnimals = true,
canTargetItems = true,
mapObjectTargetsMustBeAutoAttackable = false,
};
}
return targetParameters;
}
}
private static TargetingParameters targetParameters = null;
private static Vector3 rjwclickPos;
public static TargetingParameters TargetParemetersMasturbationChairOrBed(LocalTargetInfo target)
{
return new TargetingParameters()
{
canTargetBuildings = true,
mapObjectTargetsMustBeAutoAttackable = false,
validator = (TargetInfo target) =>
{
if (!target.HasThing)
return false;
Building building = target.Thing as Building;
if (building == null)
return false;
if (building.def.building.isSittable)
return true;
if (building is Building_Bed)
return true;
return false;
}
};
}
public static TargetingParameters TargetParemetersMasturbationLoc(LocalTargetInfo target)
{
return new TargetingParameters()
{
canTargetLocations = true,
mapObjectTargetsMustBeAutoAttackable = false,
validator = (TargetInfo target) =>
{
if (!target.HasThing)
return true;
return false;
}
};
}
//TODO: dildo selection for masturbation/sex
public static TargetingParameters TargetParemetersDildos(LocalTargetInfo target)
{
return new TargetingParameters()
{
canTargetItems = true,
mapObjectTargetsMustBeAutoAttackable = false,
validator = ((TargetInfo target) =>
{
if (!target.HasThing)
return false;
Thing dildo = target.Thing as Thing;
if (dildo == null)
return false;
return true;
})
};
}
public static List<FloatMenuOption> ChoicesAtFor(List<FloatMenuOption> __instance, Vector3 clickPos, Pawn pawn, bool suppressAutoTakeableGoto = false)
{
rjwclickPos = clickPos;
if (SaveStorage.ModId == "RJW")// disable rmb for SJW
SexFloatMenuOption(pawn, ref __instance);
return __instance;
}
public static void SexFloatMenuOption(Pawn pawn, ref List<FloatMenuOption> opts)
{
if (!ShowRMB(pawn)) return;
//Log.Message("show options");
// Find valid targets for sex.
var validtargets = GenUI.TargetsAt(rjwclickPos, TargetParameters);
//Log.Message("targets count " + validtargets.Count());
foreach (LocalTargetInfo target in validtargets)
{
if (target.Pawn != null && target.Pawn.Drafted)
continue;
// Ensure target is reachable.
if (!pawn.CanReach(target, PathEndMode.ClosestTouch, Danger.Deadly))
{
//option = new FloatMenuOption("CannotReach".Translate(target.Thing.LabelCap, target.Thing) + " (" + "NoPath".Translate() + ")", null);
continue;
}
//Log.Message("target " + target.Label);
opts.AddRange(GenerateRMBOptions(pawn, target).Where(x => x.action != null));
//sex-role?-pose ?
//rjw?-sex(do fuck/rape checks)-role?-pose ?
//sex-rjwsextype?-interactiondefs?
}
}
public static bool ShowRMB(Pawn pawn)
{
// If the pawn in question cannot take jobs, don't bother.
if (pawn.jobs == null)
return false;
// If the pawn is drafted - quit.
if (pawn.Drafted)
return false;
// Getting raped - no control
if (pawn.jobs.curDriver is JobDriver_SexBaseRecieverRaped)
return false;
//is colonist?, is hospitality colonist/guest?, no control for guests
if (!pawn.IsFreeColonist || pawn.Faction == null || pawn.GetExtraHomeFaction(null) != null)
return false;
//not hero mode or override_control - quit
if (!(RJWSettings.RPG_hero_control || RJWSettings.override_control))
return false;
var HeroOK0 = false; //is hero
var HeroOK1 = false; //owned hero?
var HeroOK2 = false; //not owned hero? maybe prison check etc in future
// || xxx.is_slave(pawn)
if (RJWSettings.RPG_hero_control)
{
HeroOK0 = pawn.IsDesignatedHero();
HeroOK1 = HeroOK0 && pawn.IsHeroOwner();
HeroOK2 = HeroOK0 && !pawn.IsHeroOwner();
//Log.Message("show options HeroOK0 " + HeroOK0);
//Log.Message("show options HeroOK1 " + HeroOK1);
//Log.Message("show options HeroOK2 " + HeroOK2);
}
else if (!RJWSettings.override_control)
return false;
//not hero, not override_control - quit
if (!HeroOK0 && !RJWSettings.override_control)
return false;
//not owned hero - quit
if (HeroOK0 && HeroOK2)
return false;
if (pawn.IsPrisoner || xxx.is_slave(pawn))
return false;
return true;
}
public static List<FloatMenuOption> GenerateRMBOptions(Pawn pawn, LocalTargetInfo target)
{
List<FloatMenuOption> opts = new List<FloatMenuOption>();
FloatMenuOption option = null;
if (ModsConfig.BiotechActive)
{
if (MechanitorUtility.IsMechanitor(pawn))
{
if(target.Pawn != null)
{
if (target.Pawn.IsPregnant(true))
{
Hediff_MechanoidPregnancy pregnancy = (Hediff_MechanoidPregnancy)target.Pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("RJW_pregnancy_mech"));
if (pregnancy != null)
{
if (pregnancy.is_checked && !pregnancy.is_hacked)
{
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_HackMechPregnancy".Translate(), delegate ()
{
Job job22 = JobMaker.MakeJob(DefDatabase<JobDef>.GetNamed("RJW_HackMechPregnancy"), target.Pawn);
pawn.jobs.TryTakeOrderedJob(job22, JobTag.Misc);
}, MenuOptionPriority.High), pawn, target);
opts.AddDistinct(option);
}
}
}
}
}
else
{
if(target.Pawn != null)
if (pawn.IsColonyMechPlayerControlled)
{
//mechimplant
// option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_Masturbate".Translate(), delegate ()
// {
// FloatMenuUtility.MakeMenu(GenerateSoloSexPoseOptions(pawn, target).Where(x => x.action != null), (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
// }, MenuOptionPriority.High), pawn, target);
// opts.AddDistinct(option);
}
}
}
// Already doing sex.
// Pose switch
//if (pawn.jobs.curDriver is JobDriver_Sex)
//{
// // Masturbating
// if (target.Pawn == pawn)
// {
// if (pawn.jobs.curDriver is JobDriver_Masturbate)
// {
// option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_Masturbate".Translate(), delegate ()
// {
// FloatMenuUtility.MakeMenu(GenerateSoloSexPoseOptions(pawn, target).Where(x => x.action != null), (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
// }, MenuOptionPriority.High), pawn, target);
// opts.AddDistinct(option);
// }
// }
// // TODO: Add pose switch
// return opts;
//}
return opts;
}
public static List<FloatMenuOption> GenerateNonSoloSexRoleOptions(Pawn pawn, LocalTargetInfo target, JobDef job, bool rape, bool reverse = false)
{
List<FloatMenuOption> opts = new List<FloatMenuOption>();
FloatMenuOption option = null;
var partner = target.Pawn;
if (target.Thing is Corpse)
partner = (target.Thing as Corpse).InnerPawn;
var arraytype = 0; //sex
if (xxx.is_animal(partner))
{
arraytype = 2; //bestiality/breeding
}
else if (rape)
{
arraytype = 1; //rape
}
List<InteractionDef> validintdefs = new List<InteractionDef>();
foreach (InteractionDef d in SexUtility.SexInterractions)
{
var interaction = Modules.Interactions.Helpers.InteractionHelper.GetWithExtension(d);
if (interaction.Extension.rjwSextype == xxx.rjwSextype.None.ToStringSafe())
continue;
if (interaction.Extension.rjwSextype == xxx.rjwSextype.Masturbation.ToStringSafe())
continue;
if (
(interaction.HasInteractionTag(InteractionTag.Consensual) && arraytype == 0) ||
(interaction.HasInteractionTag(InteractionTag.Rape) && arraytype == 1) ||
(interaction.HasInteractionTag(InteractionTag.Bestiality) && arraytype == 2)
)
if (reverse && interaction.HasInteractionTag(InteractionTag.Reverse) || (!reverse && !interaction.HasInteractionTag(InteractionTag.Reverse)))
{
ILewdInteractionValidatorService service = LewdInteractionValidatorService.Instance;
if (service.IsValid(d, pawn, partner))
validintdefs.Add(d);
}
}
foreach (InteractionDef dictionaryKey in validintdefs)
{
var interaction = Modules.Interactions.Helpers.InteractionHelper.GetWithExtension(dictionaryKey);
var dev = "";
if (RJWSettings.DevMode)
dev = " ( defName: " + dictionaryKey.defName + ")";
var label = interaction.Extension.RMBLabel.CapitalizeFirst() + dev;
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(label, delegate ()
{
HaveSex(pawn, job, target, dictionaryKey);
}, MenuOptionPriority.High), pawn, target);
opts.AddDistinct(option);
}
if (opts.NullOrEmpty())
opts.AddDistinct(new FloatMenuOption("none", null));
return opts;
}
//multiplayer synch actions
[SyncMethod]
public static void HaveSex(Pawn pawn, JobDef jobDef, LocalTargetInfo target, InteractionDef dictionaryKey)
{
bool rape;
Pawn partner = null;
if (target.Thing is Corpse)
partner = (target.Thing as Corpse).InnerPawn;
else if (target.Pawn == null || pawn == target.Pawn) // masturbation
{
}
else
partner = target.Pawn;
InteractionWithExtension interaction = Modules.Interactions.Helpers.InteractionHelper.GetWithExtension(dictionaryKey);
rape = interaction.HasInteractionTag(InteractionTag.Rape);
Job job;
if (jobDef == xxx.casual_sex)
job = new Job(jobDef, target, partner.CurrentBed());
else if (jobDef == xxx.bestialityForFemale)
job = new Job(jobDef, target, pawn.ownership.OwnedBed);
else if (jobDef == xxx.Masturbate)
{
job = new Job(jobDef, pawn, null, target.Cell);
partner = pawn;
}
else
job = new Job(jobDef, target);
var SP = new SexProps();
SP.pawn = pawn;
SP.partner = partner;
SP.sexType = SexUtility.rjwSextypeGet(dictionaryKey); ;
SP.isRape = rape;
SP.isRapist = rape;
SP.canBeGuilty = false; //pawn.IsHeroOwner();//TODO: fix for MP someday
SP.dictionaryKey = dictionaryKey;
SP.rulePack = SexUtility.SexRulePackGet(dictionaryKey);
pawn.GetRJWPawnData().SexProps = SP;
pawn.jobs.EndCurrentJob(JobCondition.InterruptForced);
pawn.jobs.TryTakeOrderedJob(job);
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/RMB/RMB_Menu2.cs
|
C#
|
mit
| 11,396
|
using HarmonyLib;
using RimWorld;
using System.Collections.Generic;
using System.Linq;
using Verse;
using System;
namespace rjw
{
[StaticConstructorOnStartup]
static class RMB_Rape
{
static RMB_Rape()
{
Harmony harmony = new Harmony("rjw");
//start sex options
harmony.Patch(AccessTools.Method(typeof(RMB_Menu), "GenerateRMBOptions"), prefix: null,
postfix: new HarmonyMethod(typeof(RMB_Rape), nameof(ChoicesAtFor)));
}
public static List<FloatMenuOption> ChoicesAtFor(List<FloatMenuOption> __instance, Pawn pawn, LocalTargetInfo target)
{
FloatMenuOption(pawn, ref __instance, ref target);
return __instance;
}
public static void FloatMenuOption(Pawn pawn, ref List<FloatMenuOption> opts, ref LocalTargetInfo target)
{
opts.AddRange(GenerateRMBOptions(pawn, target).Where(x => x.action != null));
opts.AddRange(GenerateRMBOptions(pawn, target, true).Where(x => x.action != null));
}
public static List<FloatMenuOption> GenerateRMBOptions(Pawn pawn, LocalTargetInfo target, bool reverse = false)
{
List<FloatMenuOption> opts = new List<FloatMenuOption>();
FloatMenuOption option = null;
bool rape = true;
if (target.Pawn != pawn)
if (target.Thing != pawn as Thing)// && !MP.IsInMultiplayer)
{
if (target.Pawn != null || target.Thing is Corpse)
if (xxx.can_rape(pawn, true))
{
//Log.Message("targets can_rape " + target.Label);
string text = null;
Action action = null;
if (!pawn.IsDesignatedHero())
if (!pawn.IsHeroOwner())
if (target.Thing is Corpse)
{
if (SexAppraiser.would_fuck(pawn, ((Corpse)target.Thing).InnerPawn) < 0.1f)
return opts;
}
else
{
if (SexAppraiser.would_fuck(pawn, target.Pawn) < 0.1f)
return opts;
}
if (target.Thing is Corpse && RJWSettings.necrophilia_enabled)
{
if (reverse)
{
text = "RJW_RMB_RapeCorpse_Reverse".Translate() + ((Corpse)target.Thing).InnerPawn.NameShortColored;
}
else
text = "RJW_RMB_RapeCorpse".Translate() + ((Corpse)target.Thing).InnerPawn.NameShortColored;
action = delegate ()
{
JobDef job = xxx.RapeCorpse;
var validinteractions = RMB_Menu.GenerateNonSoloSexRoleOptions(pawn, target, job, rape, reverse).Where(x => x.action != null);
if (validinteractions.Any())
FloatMenuUtility.MakeMenu(validinteractions, (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
else
Messages.Message("No valid interactions found for " + text, MessageTypeDefOf.RejectInput, false);
};
}
else if (target.Pawn != null && xxx.can_be_fucked(target.Pawn) &&
(xxx.is_human(target.Pawn) || (xxx.is_animal(target.Pawn) && RJWSettings.bestiality_enabled)))
//(xxx.is_human(target.Pawn)))
{
//Log.Message("targets can_rape 1 " + target.Label);
if (target.Pawn.HostileTo(pawn))
{
//Log.Message("targets can_rape HostileTo " + target.Label);
if (target.Pawn.Downed)
{
if (reverse)
{
text = "RJW_RMB_Rape_Reverse".Translate() + target.Pawn.NameShortColored;
}
else
text = "RJW_RMB_Rape".Translate() + target.Pawn.NameShortColored;
action = delegate ()
{
JobDef job = xxx.RapeEnemy;
var validinteractions = RMB_Menu.GenerateNonSoloSexRoleOptions(pawn, target, job, rape, reverse).Where(x => x.action != null);
if (validinteractions.Any())
FloatMenuUtility.MakeMenu(validinteractions, (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
else
Messages.Message("No valid interactions found for " + text, MessageTypeDefOf.RejectInput, false);
};
}
}
else if (xxx.is_animal(target.Pawn) && xxx.can_fuck(pawn))
{
if (reverse)
{
text = "RJW_RMB_RapeAnimal_Reverse".Translate() + target.Pawn.NameShortColored;
}
else
text = "RJW_RMB_RapeAnimal".Translate() + target.Pawn.NameShortColored;
action = delegate ()
{
JobDef job = xxx.bestiality;
var validinteractions = RMB_Menu.GenerateNonSoloSexRoleOptions(pawn, target, job, rape, reverse).Where(x => x.action != null);
if (validinteractions.Any())
FloatMenuUtility.MakeMenu(validinteractions, (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
else
Messages.Message("No valid interactions found for " + text, MessageTypeDefOf.RejectInput, false);
};
}
else if (target.Pawn.IsDesignatedComfort())
{
//Log.Message("targets can_rape IsDesignatedComfort " + target.Label);
if (reverse)
{
text = "RJW_RMB_Rape_Reverse".Translate() + target.Pawn.NameShortColored;
}
else
text = "RJW_RMB_Rape".Translate() + target.Pawn.NameShortColored;
action = delegate ()
{
JobDef job = xxx.RapeCP;
var validinteractions = RMB_Menu.GenerateNonSoloSexRoleOptions(pawn, target, job, rape, reverse).Where(x => x.action != null);
if (validinteractions.Any())
FloatMenuUtility.MakeMenu(validinteractions, (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
else
Messages.Message("No valid interactions found for " + text, MessageTypeDefOf.RejectInput, false);
};
}
else if (xxx.can_get_raped(target.Pawn) && (xxx.get_vulnerability(target.Pawn) >= xxx.get_vulnerability(pawn)))
{
//Log.Message("targets can_rape else " + target.Label);
if (reverse)
{
text = "RJW_RMB_Rape_Reverse".Translate() + target.Pawn.NameShortColored;
}
else
text = "RJW_RMB_Rape".Translate() + target.Pawn.NameShortColored;
action = delegate ()
{
JobDef job = xxx.RapeRandom;
var validinteractions = RMB_Menu.GenerateNonSoloSexRoleOptions(pawn, target, job, rape, reverse).Where(x => x.action != null);
if (validinteractions.Any())
FloatMenuUtility.MakeMenu(validinteractions, (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
else
Messages.Message("No valid interactions found for " + text, MessageTypeDefOf.RejectInput, false);
};
}
}
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text, action, MenuOptionPriority.High), pawn, target);
opts.AddDistinct(option);
}
}
return opts;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/RMB/RMB_Rape.cs
|
C#
|
mit
| 6,829
|
using HarmonyLib;
using RimWorld;
using System.Collections.Generic;
using System.Linq;
using Verse;
using Verse.AI;
namespace rjw
{
[StaticConstructorOnStartup]
static class RMB_Sex
{
static RMB_Sex()
{
Harmony harmony = new Harmony("rjw");
//start sex options
harmony.Patch(AccessTools.Method(typeof(RMB_Menu), "GenerateRMBOptions"), prefix: null,
postfix: new HarmonyMethod(typeof(RMB_Sex), nameof(ChoicesAtFor)));
}
public static List<FloatMenuOption> ChoicesAtFor(List<FloatMenuOption> __instance, Pawn pawn, LocalTargetInfo target)
{
FloatMenuOption(pawn, ref __instance, ref target);
return __instance;
}
public static void FloatMenuOption(Pawn pawn, ref List<FloatMenuOption> opts, ref LocalTargetInfo target)
{
opts.AddRange(GenerateRMBOptions(pawn, target).Where(x => x.action != null));
opts.AddRange(GenerateRMBOptions(pawn, target, true).Where(x => x.action != null));
}
public static List<FloatMenuOption> GenerateRMBOptions(Pawn pawn, LocalTargetInfo target, bool reverse = false)
{
List<FloatMenuOption> opts = new List<FloatMenuOption>();
FloatMenuOption option = null;
bool rape = false;
if (target.Pawn != pawn)
if (target.Thing != pawn as Thing)// && !MP.IsInMultiplayer)
{
if (target.Pawn != null)
if (!target.Pawn.Downed && !target.Pawn.HostileTo(pawn) && (xxx.can_be_fucked(target.Pawn) || xxx.can_fuck(target.Pawn)))
{
string text = null;
//Action action = null;
float relations = pawn.relations.OpinionOf(target.Pawn);
if (!pawn.IsDesignatedHero())
if (!pawn.IsHeroOwner())
{
if (relations < RJWHookupSettings.MinimumRelationshipToHookup)
{
if (!(relations > 0 && xxx.is_nympho(pawn)))
{
return opts;
}
}
if (SexAppraiser.would_fuck(pawn, target.Pawn) < 0.1f)
{
return opts;
}
}
if (xxx.is_human(target.Pawn) && SexAppraiser.would_fuck(target.Pawn, pawn) > 0.1f)
{
relations = target.Pawn.relations.OpinionOf(pawn);
if (relations < RJWHookupSettings.MinimumRelationshipToHookup)
{
if (!(relations > 0 && xxx.is_nympho(target.Pawn)))
{
return opts;
}
}
if (reverse)
{
text = "RJW_RMB_Sex_Reverse".Translate() + target.Pawn.NameShortColored;
}
else
text = "RJW_RMB_Sex".Translate() + target.Pawn.NameShortColored;
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text, delegate ()
{
JobDef job = null;
if (target.Pawn.InBed())
job = xxx.casual_sex;
else
job = xxx.quick_sex;
var validinteractions = RMB_Menu.GenerateNonSoloSexRoleOptions(pawn, target, job, rape, reverse).Where(x => x.action != null);
if (validinteractions.Any())
FloatMenuUtility.MakeMenu(validinteractions, (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
else
Messages.Message("No valid interactions found for " + text, MessageTypeDefOf.RejectInput, false);
}, MenuOptionPriority.High), pawn, target);
opts.AddDistinct(option);
}
else if (xxx.is_animal(target.Pawn) && RJWSettings.bestiality_enabled && target.Pawn.Faction == pawn.Faction)
{
if (pawn.ownership.OwnedBed != null && target.Pawn.CanReach(pawn.ownership.OwnedBed, PathEndMode.OnCell, Danger.Some) && !AnimalPenUtility.NeedsToBeManagedByRope(target.Pawn))
{
if (reverse)
{
text = "RJW_RMB_Bestiality_Reverse".Translate() + target.Pawn.NameShortColored;
}
else
text = "RJW_RMB_Bestiality".Translate() + target.Pawn.NameShortColored;
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text, delegate ()
{
JobDef job = xxx.bestialityForFemale;
var validinteractions = RMB_Menu.GenerateNonSoloSexRoleOptions(pawn, target, job, rape, reverse).Where(x => x.action != null);
if (validinteractions.Any())
FloatMenuUtility.MakeMenu(validinteractions, (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
else
Messages.Message("No valid interactions found for " + text, MessageTypeDefOf.RejectInput, false);
}, MenuOptionPriority.High), pawn, target);
opts.AddDistinct(option);
}
}
}
}
return opts;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/RMB/RMB_Sex.cs
|
C#
|
mit
| 4,572
|
using HarmonyLib;
using RimWorld;
using System.Collections.Generic;
using System.Linq;
using Verse;
using Verse.AI;
using Multiplayer.API;
namespace rjw
{
[StaticConstructorOnStartup]
static class RMB_Socialize
{
static RMB_Socialize()
{
Harmony harmony = new Harmony("rjw");
//start sex options
harmony.Patch(AccessTools.Method(typeof(RMB_Menu), "GenerateRMBOptions"), prefix: null,
postfix: new HarmonyMethod(typeof(RMB_Socialize), nameof(ChoicesAtFor)));
}
public static List<FloatMenuOption> ChoicesAtFor(List<FloatMenuOption> __instance, Pawn pawn, LocalTargetInfo target)
{
FloatMenuOption(pawn, ref __instance, ref target);
return __instance;
}
public static void FloatMenuOption(Pawn pawn, ref List<FloatMenuOption> opts, ref LocalTargetInfo target)
{
opts.AddRange(GenerateRMBOptions(pawn, target).Where(x => x.action != null));
}
public static List<FloatMenuOption> GenerateRMBOptions(Pawn pawn, LocalTargetInfo target)
{
List<FloatMenuOption> opts = new List<FloatMenuOption>();
FloatMenuOption option = null;
if (target.Pawn != null && target.Pawn != pawn && !pawn.interactions.InteractedTooRecentlyToInteract() && pawn.interactions.CanInteractNowWith(target.Pawn))
{
//if (pawn.jobs.curDriver is JobDriver_Masturbate)
{
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_Social".Translate(), delegate ()
{
FloatMenuUtility.MakeMenu(GenerateSocialOptions(pawn, target).Where(x => x.action != null), (FloatMenuOption opt) => opt.Label, (FloatMenuOption opt) => opt.action);
}, MenuOptionPriority.High), pawn, target);
opts.AddDistinct(option);
}
}
return opts;
}
public static List<FloatMenuOption> GenerateSocialOptions(Pawn pawn, LocalTargetInfo target)
{
List<FloatMenuOption> opts = new List<FloatMenuOption>();
FloatMenuOption option = null;
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_Insult".Translate(), delegate ()
{
Socialize(pawn, target, InteractionDefOf.Insult);
}, MenuOptionPriority.High), pawn, target);
opts.AddDistinct(option);
if (!pawn.HostileTo(target.Pawn))
{
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_SocialFight".Translate(), delegate ()
{
SocializeFight(pawn, target);
}, MenuOptionPriority.High), pawn, target);
opts.AddDistinct(option);
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_Chat".Translate(), delegate ()
{
Socialize(pawn, target, InteractionDefOf.Chitchat);
}, MenuOptionPriority.High), pawn, target);
opts.AddDistinct(option);
// OP shit +12 relations, enable in cheat menu
if (RJWSettings.Allow_RMB_DeepTalk)
{
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_DeepTalk".Translate(), delegate ()
{
pawn.interactions.TryInteractWith(target.Pawn, InteractionDefOf.DeepTalk);
}, MenuOptionPriority.High), pawn, target);
opts.AddDistinct(option);
}
if (!LovePartnerRelationUtility.LovePartnerRelationExists(pawn, target.Pawn))
{
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_RomanceAttempt".Translate(), delegate ()
{
Socialize(pawn, target, InteractionDefOf.RomanceAttempt);
}, MenuOptionPriority.High), pawn, target);
opts.AddDistinct(option);
}
if (pawn.relations.DirectRelationExists(PawnRelationDefOf.Lover, target.Pawn) || pawn.relations.DirectRelationExists(PawnRelationDefOf.Fiance, target.Pawn))
{
option = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("RJW_RMB_MarriageProposal".Translate(), delegate ()
{
Socialize(pawn, target, InteractionDefOf.MarriageProposal);
}, MenuOptionPriority.High), pawn, target);
opts.AddDistinct(option);
}
}
return opts;
}
//multiplayer synch actions
[SyncMethod]
static void SocializeFight(Pawn pawn, LocalTargetInfo target)
{
pawn.interactions.StartSocialFight(target.Pawn);
}
[SyncMethod]
static void Socialize(Pawn pawn, LocalTargetInfo target, InteractionDef interaction)
{
pawn.interactions.TryInteractWith(target.Pawn, interaction);
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/RMB/RMB_Socialize.cs
|
C#
|
mit
| 4,292
|
using HarmonyLib;
using Multiplayer.API;
using RimWorld;
using rjw.Modules.Shared.Extensions;
using rjw.Modules.Shared.Helpers;
using rjw.Modules.Shared.Logs;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Verse;
using Verse.AI;
namespace rjw
{
/// <summary>
/// Responsible for judging the sexiness of potential partners.
/// </summary>
public static class SexAppraiser
{
private static ILog _log = LogManager.GetLogger(nameof(SexAppraiser));
public const float base_sat_per_fuck = 0.40f;
public const float base_attraction = 0.60f;
public const float no_partner_ability = 0.8f;
static readonly SimpleCurve fuckability_per_reserved = new SimpleCurve
{
new CurvePoint(0f, 1.0f),
new CurvePoint(0.3f, 0.4f),
new CurvePoint(1f, 0.2f)
};
/// <summary>
/// Returns boolean, no more messing around with floats.
/// Just a simple 'Would rape? True/false'.
/// </summary>
[SyncMethod]
public static bool would_rape(Pawn rapist, Pawn rapee)
{
float rape_factor = 0.3f; // start at 30%
float vulnerabilityFucker = xxx.get_vulnerability(rapist); //0 to 3
float vulnerabilityPartner = xxx.get_vulnerability(rapee); //0 to 3
// More inclined to rape someone from another faction.
if (rapist.HostileTo(rapee) || rapist.Faction != rapee.Faction)
rape_factor += 0.25f;
// More inclined to rape if the target is designated as CP.
if (rapee.IsDesignatedComfort())
rape_factor += 0.25f;
// More inclined to rape when horny.
Need_Sex horniness = rapist.needs.TryGetNeed<Need_Sex>();
if (!xxx.is_animal(rapist) && horniness?.CurLevel <= horniness?.thresh_horny())
{
rape_factor += 0.25f;
}
if (xxx.is_animal(rapist))
{
if (vulnerabilityFucker < vulnerabilityPartner)
rape_factor -= 0.1f;
else
rape_factor += 0.25f;
}
else if (xxx.is_animal(rapee))
{
if (xxx.is_zoophile(rapist))
rape_factor += 0.5f;
else
rape_factor -= 0.2f;
}
else
{
rape_factor *= 0.5f + Mathf.InverseLerp(vulnerabilityFucker, 3f, vulnerabilityPartner);
}
if (rapist.health.hediffSet.HasHediff(HediffDef.Named("AlcoholHigh")))
rape_factor *= 1.25f; //too drunk to care
// Increase factor from traits.
if (xxx.is_rapist(rapist))
rape_factor *= 1.5f;
if (xxx.is_nympho(rapist))
rape_factor *= 1.25f;
if (xxx.is_bloodlust(rapist))
rape_factor *= 1.2f;
if (xxx.is_psychopath(rapist))
rape_factor *= 1.2f;
if (xxx.is_masochist(rapee))
rape_factor *= 1.2f;
// Lower factor from traits.
if (xxx.is_masochist(rapist))
rape_factor *= 0.8f;
if (rapist.needs?.joy != null && rapist.needs.joy.CurLevel < 0.1f) // The rapist is really bored...
rape_factor *= 1.2f;
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
if (rapist.relations == null || xxx.is_animal(rapist)) return Rand.Chance(rape_factor);
float opinion = rapist.relations.OpinionOf(rapee);
//remove Pretty trait bonus
//ThoughtWorker_Pretty
float beauty = rapee.GetStatValue(StatDefOf.PawnBeauty, true) * 20f;
opinion -= beauty;
// Won't rape friends, unless rapist or psychopath.
if (xxx.is_kind(rapist))
{ //<-80: 1f /-40: 0.5f / 0+: 0f
rape_factor *= 1f - Mathf.Pow(GenMath.InverseLerp(-80, 0, opinion), 2);
}
else if (xxx.is_rapist(rapist) || xxx.is_psychopath(rapist))
{ //<40: 1f /80: 0.5f / 120+: 0f
opinion -= beauty;
rape_factor *= 1f - Mathf.Pow(GenMath.InverseLerp(40, 120, opinion), 2); // This can never be 0, since opinion caps at 100.
}
else
{ //<-60: 1f /-20: 0.5f / 40+: 0f
opinion -= beauty;
rape_factor *= 1f - Mathf.Pow(GenMath.InverseLerp(-60, 40, opinion), 2);
}
//Log.Message("rjw::xxx rape_factor for " + get_pawnname(rapee) + " is " + rape_factor);
return Rand.Chance(rape_factor);
}
public static float would_fuck(Pawn fucker, Corpse fucked, bool invert_opinion = false, bool ignore_bleeding = false, bool ignore_gender = false)
{
CompRottable comp = fucked.GetComp<CompRottable>();
//--Log.Message("rotFactor:" + rotFactor);
// Things that don't rot, such as mechanoids and weird mod-added stuff such as Rimworld of Magic's elementals.
if (comp == null)
{
// Trying to necro the weird mod-added stuff causes an error, so skipping those for now.
return 0.0f;
}
float maxRot = ((CompProperties_Rottable)comp.props).TicksToDessicated;
float rotFactor = (maxRot - comp.RotProgress) / maxRot;
//--Log.Message("rotFactor:" + rotFactor);
return would_fuck(fucker, fucked.InnerPawn, invert_opinion, ignore_bleeding, ignore_gender) * rotFactor;
}
public static float would_fuck_animal(Pawn pawn, Pawn target, bool invert_opinion = false, bool ignore_bleeding = false, bool ignore_gender = false)
{
float wildness_modifier = 1.0f;
List<float> size_preference = new List<float>() { pawn.BodySize * 0.75f, pawn.BodySize * 1.6f };
float fuc = would_fuck(pawn, target, invert_opinion, ignore_bleeding, ignore_gender); // 0.0 to ~3.0, orientation checks etc.
if (fuc < 0.1f)
{ // Would not fuck
return 0;
}
if (xxx.has_quirk(pawn, "Teratophile"))
{ // Teratophiles prefer more 'monstrous' partners.
size_preference[0] = pawn.BodySize * 0.8f;
size_preference[1] = pawn.BodySize * 2.0f;
wildness_modifier = 0.3f;
}
if (pawn.health.hediffSet.HasHediff(HediffDef.Named("AlcoholHigh")))
{
wildness_modifier = 0.5f; //Drunk and making poor judgments.
size_preference[1] *= 1.5f;
}
else if (pawn.health.hediffSet.HasHediff(HediffDef.Named("YayoHigh")))
{
wildness_modifier = 0.2f; //This won't end well.
size_preference[1] *= 2.5f;
}
var parts = pawn.GetGenitalsList();
if (Genital_Helper.has_vagina(pawn, parts) || Genital_Helper.has_anus(pawn))
{
if (!Genital_Helper.has_male_bits(pawn, parts))
{
size_preference[1] = pawn.BodySize * 1.3f;
}
}
if (xxx.is_animal(pawn))
{
size_preference[1] = pawn.BodySize * 1.3f;
wildness_modifier = 0.4f;
}
else if (xxx.has_traits(pawn))
{
if (pawn.story.traits.HasTrait(TraitDefOf.Tough) || pawn.story.traits.HasTrait(TraitDefOf.Brawler))
{
size_preference[1] += 0.2f;
wildness_modifier -= 0.2f;
}
else if (pawn.story.traits.HasTrait(TraitDefOf.Wimp))
{
size_preference[0] -= 0.2f;
size_preference[1] -= 0.2f;
wildness_modifier += 0.25f;
}
}
float wildness = target.RaceProps.wildness; // 0.0 to 1.0
float petness = target.RaceProps.petness; // 0.0 to 1.0
float distance = pawn.Position.DistanceTo(target.Position);
//ModLog.Message("would_fuck_animal:: base: " + fuc + ", wildness: " + wildness + ", petness: " + petness + ", distance: " + distance);
fuc = fuc + fuc * petness - fuc * wildness * wildness_modifier;
if (fuc < 0.1f)
{ // Would not fuck
return 0;
}
// Adjust by distance, nearby targets preferred.
fuc *= 1.0f - Mathf.Max(distance / 10000, 0.1f);
// Adjust by size difference.
if (target.BodySize < size_preference[0])
{
fuc *= Mathf.Lerp(0.1f, size_preference[0], target.BodySize);
}
else if (target.BodySize > size_preference[1])
{
fuc *= Mathf.Lerp(size_preference[1] * 10, size_preference[1], target.BodySize);
}
if (target.Faction != pawn.Faction)
{
//ModLog.Message("would_fuck_animal(NT):: base: " + fuc + ", bound1: " + fuc * 0.75f);
//ModLog.Message("would_fuck_animal(NT):: base: " + fuc + ", bound2: " + fuc + 0.25f);
fuc *= 0.75f; // Less likely to target wild animals.
}
else if (pawn.relations.DirectRelationExists(PawnRelationDefOf.Bond, target))
{
//ModLog.Message("would_fuck_animal(T):: base: " + fuc + ", bound1: " + fuc * 1.25f);
//ModLog.Message("would_fuck_animal(T):: base: " + fuc + ", bound2: " + fuc + 0.25f);
fuc *= 1.25f; // Bonded animals preferred.
}
return fuc;
}
// Returns how fuckable 'fucker' thinks 'p' is on a scale from 0.0 to 1.0
public static float would_fuck(Pawn fucker, Pawn fucked, bool invert_opinion = false, bool ignore_bleeding = false, bool ignore_gender = false)
{
//--ModLog.Message("would_fuck("+xxx.get_pawnname(fucker)+","+xxx.get_pawnname(fucked)+","+invert_opinion.ToString()+") is called");
if (xxx.is_human(fucker) && !xxx.is_healthy_enough(fucker) && !xxx.is_psychopath(fucker)) // Not healthy enough to have sex, shouldn't have got this far.
{
_log.Debug($"{nameof(would_fuck)} - {fucker.GetName()} on {fucked.GetName()}");
_log.Debug("Not healthy enough");
return 0f;
}
if ((xxx.is_animal(fucker) || xxx.is_animal(fucked)) && (!xxx.is_animal(fucker) || !xxx.is_animal(fucked)) && !RJWSettings.bestiality_enabled)
{
_log.Debug($"{nameof(would_fuck)} - {fucker.GetName()} on {fucked.GetName()}");
_log.Debug("Animals disabled");
return 0f;
}
if (fucked.Dead && !RJWSettings.necrophilia_enabled)
{
_log.Debug($"{nameof(would_fuck)} - {fucker.GetName()} on {fucked.GetName()}");
_log.Debug("Necrophilia disabled");
return 0f;
}
if (fucker.Dead || fucker.Suspended || fucked.Suspended)
{
_log.Debug($"{nameof(would_fuck)} - {fucker.GetName()} on {fucked.GetName()}");
_log.Debug("Target unreachable");
return 0f;
}
if (xxx.is_starved(fucked) && fucked.Faction == fucker.Faction && !xxx.is_psychopath(fucker) && !xxx.is_rapist(fucker))
{
_log.Debug($"{nameof(would_fuck)} - {fucker.GetName()} on {fucked.GetName()}");
_log.Debug("Target is starving");
return 0f;
}
if (xxx.is_human(fucker) && !ignore_bleeding && !xxx.is_not_dying(fucked) && !xxx.is_psychopath(fucker) && !xxx.is_rapist(fucker) && !xxx.is_bloodlust(fucker))
{
_log.Debug($"{nameof(would_fuck)} - {fucker.GetName()} on {fucked.GetName()}");
_log.Debug("Target is dying");
return 0f;
}
if (!IsGenderOk(fucker, fucked))
{
_log.Debug($"{nameof(would_fuck)} - {fucker.GetName()} on {fucked.GetName()}");
_log.Debug("Genders not compatible");
return 0.0f;
}
int fucker_age = fucker.ageTracker.AgeBiologicalYears;
//string fucker_quirks = CompRJW.Comp(fucker).quirks.ToString();
int fucked_age = fucked.ageTracker.AgeBiologicalYears;
// --- Age checks ---
if (!IsAgeOk(fucker, fucked, fucker_age, fucked_age))
{
float scaledFuckerAge = AgeHelper.ScaleToHumanAge(fucker);
float scaledFuckedAge = AgeHelper.ScaleToHumanAge(fucked);
_log.Debug($"{nameof(would_fuck)} - {fucker.GetName()} on {fucked.GetName()}");
_log.Debug($"ages KO : original {fucker_age}/{fucked_age} - scaled {scaledFuckerAge}/{scaledFuckedAge}");
return 0.0f;
}
float age_factor = GetAgeFactor(fucker, fucked, fucked_age);
// --- Orientation checks ---
float orientation_factor = GetOrientationFactor(fucker, fucked, ignore_gender);
//retry vanilla if 0
if (orientation_factor == 0.0f)
{
orientation_factor = fucker.relations.SecondaryLovinChanceFactor(fucked);
//Log.Message("would_fuck() SecondaryLovinChanceFactor:" + orientation_factor);
if (orientation_factor <= 0)
return 0.0f;
}
// --- Body and appearance checks ---
float body_factor = GetBodyFactor(fucker, fucked);
// --- Opinion checks ---
float opinion_factor = GetOpinionFactor(fucker, fucked, invert_opinion);
float horniness_factor = GetHorninessFactor(fucker);
float reservedPercentage = (fucked.Dead ? 1f : fucked.ReservedCount()) / xxx.max_rapists_per_prisoner;
//Log.Message("would_fuck() reservedPercentage:" + reservedPercentage + "fuckability_per_reserved"+ fuckability_per_reserved.Evaluate(reservedPercentage));
//Log.Message("would_fuck() - horniness_factor = " + horniness_factor.ToString());
float prenymph_att = Mathf.InverseLerp(0f, 2.8f, base_attraction * orientation_factor * horniness_factor * age_factor * body_factor * opinion_factor);
float final_att = !(xxx.is_nympho(fucker) || fucker.health.hediffSet.HasHediff(RJWHediffDefOf.HumpShroomEffect)) ? prenymph_att : 0.2f + 0.8f * prenymph_att;
//Log.Message("would_fuck( " + xxx.get_pawnname(fucker) + ", " + xxx.get_pawnname(fucked) + " ) - prenymph_att = " + prenymph_att.ToString() + ", final_att = " + final_att.ToString());
//if (xxx.is_human(fucker) && xxx.is_human(fucked))
//{
// Log.Message($"{nameof(would_fuck)} - {fucker.GetName()} on {fucked.GetName()}");
// Log.Message($"[age {age_factor}] [orientation {orientation_factor}] [body {body_factor}] [opinion {opinion_factor}] [horniness {horniness_factor}] [final {final_att}]");
//}
return Mathf.Min(final_att, fuckability_per_reserved.Evaluate(reservedPercentage));
}
/// <summary>
/// rjw settings gender sex limiters homo/nohomo
/// </summary>
/// <param name="fucker"></param>
/// <param name="fucked"></param>
/// <returns></returns>
private static bool IsGenderOk(Pawn fucker, Pawn fucked)
{
if (fucker.gender == Gender.Male)
{
switch (RJWPreferenceSettings.Malesex)
{
case RJWPreferenceSettings.AllowedSex.All:
break;
case RJWPreferenceSettings.AllowedSex.Homo:
if (fucked.gender != Gender.Male)
return false;
break;
case RJWPreferenceSettings.AllowedSex.Nohomo:
if (fucked.gender == Gender.Male)
return false;
break;
}
}
if (fucker.gender == Gender.Female)
{
switch (RJWPreferenceSettings.FeMalesex)
{
case RJWPreferenceSettings.AllowedSex.All:
break;
case RJWPreferenceSettings.AllowedSex.Homo:
if (fucked.gender != Gender.Female)
return false;
break;
case RJWPreferenceSettings.AllowedSex.Nohomo:
if (fucked.gender == Gender.Female)
return false;
break;
}
}
return true;
}
private static float GetHorninessFactor(Pawn fucker)
{
float horniness_factor; // 1 to 1.6
{
float need_sex = xxx.need_some_sex(fucker);
switch (need_sex)
{
case 3:
horniness_factor = 1.6f;
break;
case 2:
horniness_factor = 1.3f;
break;
case 1:
horniness_factor = 1.1f;
break;
default:
horniness_factor = 1f;
break;
}
}
//Log.Message("would_fuck() - horniness_factor = " + horniness_factor.ToString());
return horniness_factor;
}
private static float GetOpinionFactor(Pawn fucker, Pawn fucked, bool invert_opinion)
{
float opinion_factor;
{
if (fucked.relations != null && fucker.relations != null && !xxx.is_animal(fucker) && !xxx.is_animal(fucked))
{
float opi = !invert_opinion ? fucker.relations.OpinionOf(fucked) : 100 - fucker.relations.OpinionOf(fucked); // -100 to 100
opinion_factor = 0.8f + (opi + 100.0f) * (.45f / 200.0f); // 0.8 to 1.25
}
else if ((xxx.is_animal(fucker) || xxx.is_animal(fucked)) && fucker.relations.DirectRelationExists(PawnRelationDefOf.Bond, fucked))
{
opinion_factor = 1.3f;
}
else
{
opinion_factor = 1.0f;
}
// More likely to take advantege of CP.
if (fucked.IsDesignatedComfort() || (fucked.IsDesignatedBreeding() && xxx.is_animal(fucker)))
opinion_factor += 0.25f;
else if (fucked.IsDesignatedService())
opinion_factor += 0.1f;
// Less picky if designated for whorin'.
if (fucker.IsDesignatedService())
opinion_factor += 0.1f;
if (Quirk.Sapiosexual.IsSatisfiedBy(fucker, fucked))
{
opinion_factor *= 1.4f;
}
}
//Log.Message("would_fuck() - opinion_factor = " + opinion_factor.ToString());
return opinion_factor;
}
private static float GetBodyFactor(Pawn fucker, Pawn fucked)
{
float body_factor; //0.4 to 1.6
{
if (fucker.health.hediffSet.HasHediff(HediffDef.Named("AlcoholHigh")))
{
if (!xxx.is_zoophile(fucker) && xxx.is_animal(fucked))
body_factor = 0.8f;
else
body_factor = 1.25f; //beer lens
}
else if (xxx.is_zoophile(fucker) && !xxx.is_animal(fucked))
{
body_factor = 0.7f;
}
else if (!xxx.is_zoophile(fucker) && xxx.is_animal(fucked))
{
body_factor = 0.45f;
}
else if (Quirk.Teratophile.IsSatisfiedBy(fucker, fucked))
{
body_factor = 1.4f;
}
else if (fucked.story != null)
{
if (fucked.story.bodyType == BodyTypeDefOf.Female) body_factor = 1.25f;
else if (fucked.story.bodyType == BodyTypeDefOf.Fat) body_factor = 1.0f;
else body_factor = 1.1f;
if (fucked.story.traits.HasTrait(TraitDefOf.CreepyBreathing))
body_factor *= 0.9f;
//if (fucked.story.traits.HasTrait(TraitDefOf.Beauty))
//{
// switch (fucked.story.traits.DegreeOfTrait(TraitDefOf.Beauty))
// {
// case 2: // Beautiful
// body_factor *= 1.25f;
// break;
// case 1: // Pretty
// body_factor *= 1.1f;
// break;
// case -1: // Ugly
// body_factor *= 0.8f;
// break;
// case -2: // Staggeringly Ugly
// body_factor *= 0.5f;
// break;
// }
//}
if (fucked.GetStatValue(StatDefOf.PawnBeauty) >= 2)
body_factor *= 1.25f;
else if (fucked.GetStatValue(StatDefOf.PawnBeauty) >= 1)
body_factor *= 1.1f;
else if (fucked.GetStatValue(StatDefOf.PawnBeauty) < 0)
if (fucked.GetStatValue(StatDefOf.PawnBeauty) >= -1)
body_factor *= 0.8f;
else
body_factor *= 0.5f;
if (RelationsUtility.IsDisfigured(fucked))
{
body_factor *= 0.8f;
}
// Nude target is more tempting.
if (!fucked.Dead && fucked.apparel.PsychologicallyNude && fucker.CanSee(fucked))
body_factor *= 1.1f;
}
else
{
body_factor = 1.1f;
}
if (Quirk.Somnophile.IsSatisfiedBy(fucker, fucked))
{
body_factor *= 1.25f;
}
if (Quirk.PregnancyFetish.IsSatisfiedBy(fucker, fucked))
{
body_factor *= 1.25f;
}
if (Quirk.ImpregnationFetish.IsSatisfiedBy(fucker, fucked))
{
body_factor *= 1.25f;
}
if (xxx.AlienFrameworkIsActive && !xxx.is_animal(fucker))
{
if (xxx.is_xenophile(fucker))
{
if (fucker.def.defName == fucked.def.defName)
body_factor *= 0.5f; // Same species, xenophile less interested.
}
else if (xxx.is_xenophobe(fucker))
{
if (fucker.def.defName != fucked.def.defName)
body_factor *= 0.25f; // Different species, xenophobe less interested.
}
}
if (fucked.Dead && !xxx.is_necrophiliac(fucker))
{
body_factor *= 0.5f;
}
}
//Log.Message("would_fuck() - body_factor = " + body_factor.ToString());
return body_factor;
}
private static float GetOrientationFactor(Pawn fucker, Pawn fucked, bool ignore_gender)
{
float orientation_factor; //0 or 1
{
orientation_factor = 1.0f;
if (!ignore_gender && !xxx.is_animal(fucker))
{
if (!CompRJW.CheckPreference(fucker, fucked))
{
//Log.Message("would_fuck( " + xxx.get_pawnname(fucker) + ", " + xxx.get_pawnname(fucked) + " )");
//Log.Message("would_fuck() - preference fail");
orientation_factor = 0.0f;
}
}
}
//Log.Message("would_fuck() - orientation_factor = " + orientation_factor.ToString());
return orientation_factor;
}
private static float GetAgeFactor(Pawn fucker, Pawn fucked, int p_age)
{
float age_factor;
age_factor = fucked.gender == Gender.Male
? AgeConfigDef.Instance.attractivenessByAgeMale.Evaluate(AgeHelper.ScaleToHumanAge(fucker))
: AgeConfigDef.Instance.attractivenessByAgeFemale.Evaluate(AgeHelper.ScaleToHumanAge(fucked));
//if (RJWSettings.DevMode) ModLog.Message("would_fuck() - age_factor = " + age_factor.ToString());
if (xxx.is_animal(fucker))
{
age_factor = 1.0f; //using flat factors, since human age is not comparable to animal ages
}
else if (xxx.is_animal(fucked))
{
if (p_age <= 1 && fucked.RaceProps.lifeExpectancy > 8)
age_factor = 0.5f;
else
age_factor = 1.0f;
//--Log.Message("would_fuck() - animal age_factor = " + age_factor.ToString());
}
if (Quirk.Gerontophile.IsSatisfiedBy(fucker, fucked))
{
age_factor = 1.0f;
}
return age_factor;
}
private static bool IsAgeOk(Pawn fucker, Pawn fucked, int fucker_age, int fucked_age)
{
bool age_ok = false;
{
if (xxx.is_mechanoid(fucker) || xxx.can_do_loving(fucker))
{
age_ok = true;
}
if (age_ok && (xxx.is_mechanoid(fucked) || xxx.can_do_loving(fucked)))
{
age_ok = true;
}
else
age_ok = false;
if (age_ok && xxx.is_human(fucker) && xxx.is_human(fucked))
{
bool FuckerAgeOk = fucker.ageTracker.Growth == 1;
bool FuckedAgeOk = fucked.ageTracker.Growth == 1;
if (!FuckerAgeOk || !FuckedAgeOk)
{
//scaled ages
//float scaledFuckerAge = AgeHelper.ScaleToHumanAge(fucker);
//float scaledFuckedAge = AgeHelper.ScaleToHumanAge(fucked);
//age_ok = Math.Abs(scaledFuckerAge - scaledFuckedAge) < 2.05f;
//fixed racegroupdef ages
//if (!age_ok)
if (true)
{
if (!FuckerAgeOk)
if (fucker.GetRJWPawnData().RaceSupportDef?.adultAge != null && fucker.GetRJWPawnData().RaceSupportDef?.adultAge != 0)
{
var adultAge = fucker.GetRJWPawnData().RaceSupportDef.adultAge;
var pawnAge = fucker.ageTracker.AgeBiologicalYearsFloat;
if (adultAge <= pawnAge)
FuckerAgeOk = true;
}
if (!FuckedAgeOk)
if (fucked.GetRJWPawnData().RaceSupportDef?.adultAge != null && fucked.GetRJWPawnData().RaceSupportDef?.adultAge != 0)
{
var adultAge = fucked.GetRJWPawnData().RaceSupportDef.adultAge;
var pawnAge = fucked.ageTracker.AgeBiologicalYearsFloat;
if (adultAge <= pawnAge)
FuckedAgeOk = true;
}
//age_ok = FuckerAgeOk && FuckedAgeOk;
if (FuckerAgeOk && FuckedAgeOk)
return true;
if (!RJWSettings.AllowYouthSex)
return false;
}
}
//Log.Message(" AdultMinAge " + fucker.ageTracker.AdultMinAge);
}
}
//Log.Message("would_fuck() - age_ok = " + age_ok.ToString());
return age_ok;
}
static int ReservedCount(this Thing pawn)
{
int ret = 0;
if (pawn == null) return 0;
try
{
ReservationManager reserver = pawn.Map.reservationManager;
IList reservations = (IList)AccessTools.Field(typeof(ReservationManager), "reservations").GetValue(reserver);
if (reservations.Count == 0) return 0;
Type reserveType = reservations[0].GetType();
ret += (from object t in reservations
where t != null
let target = (LocalTargetInfo)AccessTools.Field(reserveType, "target").GetValue(t)
let claimant = (Pawn)AccessTools.Field(reserveType, "claimant").GetValue(t)
where target != null
where target.Thing != null
where target.Thing.ThingID == pawn.ThingID
select (int)AccessTools.Field(reserveType, "stackCount").GetValue(t)).Count();
}
catch (Exception e)
{
ModLog.Warning(e.ToString());
}
return ret;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/SexAppraiser.cs
|
C#
|
mit
| 23,162
|
using System;
using System.Collections.Generic;
using UnityEngine;
using Verse;
using Verse.Sound;
using RimWorld;
using Multiplayer.API;
namespace rjw
{
[StaticConstructorOnStartup]
public class SexGizmo : Gizmo
{
public SexGizmo(Pawn __instance)
{
this.pawn = __instance;
//this.order = -100f;
this.LimitedTex = ContentFinder<Texture2D>.Get("UI/Icons/EntropyLimit/Limited", true);
this.UnlimitedTex = ContentFinder<Texture2D>.Get("UI/Icons/EntropyLimit/Unlimited", true);
this.AttackTex = ContentFinder<Texture2D>.Get("UI/Icons/HostilityResponse/Attack", true);
//this.LimitedTex = ContentFinder<Texture2D>.Get("UI/Icons/HostilityResponse/Ignore", true);
//this.UnlimitedTex = ContentFinder<Texture2D>.Get("UI/Icons/HostilityResponse/Attack", true);
//this.LimitedTex = ContentFinder<Texture2D>.Get("UI/Commands/AttackMelee", true);
//this.UnlimitedTex = ContentFinder<Texture2D>.Get("UI/Commands/AttackMelee", true);
}
public override GizmoResult GizmoOnGUI(Vector2 topLeft, float maxWidth, GizmoRenderParms parms)
{
if (pawn.jobs?.curDriver is JobDriver_Sex)
{
Rect rect = new Rect(topLeft.x, topLeft.y, this.GetWidth(maxWidth), 75f);
Rect rect2 = rect.ContractedBy(6f);
Widgets.DrawWindowBackground(rect);
//row1 label1 - Orgasm
Text.Font = GameFont.Small;
Rect rect3 = rect2;
rect3.y += 6f;
rect3.height = Text.LineHeight;
Widgets.Label(rect3, "RJW_SexGizmo_Orgasm".Translate());
//row2 label2 - Stamina
Rect rect4 = rect2;
rect4.y += 38f;
rect4.height = Text.LineHeight;
Widgets.Label(rect4, "RJW_SexGizmo_RestNeed".Translate());
//row1 meter bar fill up
Rect rect5 = rect2;
rect5.x += 63f;
rect5.y += 6f;
rect5.width = 100f;
rect5.height = 22f;
float orgasm = (pawn.jobs?.curDriver as JobDriver_Sex).OrgasmProgress;
//orgasm = sex_ticks;
Widgets.FillableBar(rect5, Mathf.Max(orgasm, 0f), SexGizmo.EntropyBarTex, SexGizmo.EmptyBarTex, true);
//row1 meter values
string label = (orgasm * 100).ToString("F0") + " / " + 100;
Text.Font = GameFont.Small;
Text.Anchor = TextAnchor.MiddleCenter;
Widgets.Label(rect5, label);
Text.Anchor = TextAnchor.UpperLeft;
Text.Font = GameFont.Tiny;
GUI.color = Color.white;
//row1 meter description
//Rect rect6 = rect2;
//rect6.width = 175f;
//rect6.height = 38f;
//TooltipHandler.TipRegion(rect6, delegate()
//{
// float f = this.tracker.EntropyValue / this.tracker.RecoveryRate;
// return string.Format("PawnTooltipPsychicEntropyStats".Translate(), new object[]
// {
// Mathf.Round(this.tracker.EntropyValue),
// Mathf.Round(this.tracker.MaxEntropy),
// this.tracker.RecoveryRate.ToString("0.#"),
// Mathf.Round(f)
// }) + "\n\n" + "PawnTooltipPsychicEntropyDesc".Translate();
//}, Gen.HashCombineInt(this.tracker.GetHashCode(), 133858));
//row2 meter bar fill
Rect rect7 = rect2;
rect7.x += 63f;
rect7.y += 38f;
rect7.width = 100f;
rect7.height = 22f;
if (pawn.needs?.TryGetNeed<Need_Rest>() != null)
Widgets.FillableBar(rect7, Mathf.Min(pawn.needs.TryGetNeed<Need_Rest>().CurLevel, 1f), SexGizmo.PsyfocusBarTex, SexGizmo.EmptyBarTex, true);
GUI.color = Color.white;
//toggles
if (!MP.IsInMultiplayer) //TODO: someday write mp synchronizers?
if (pawn.IsColonistPlayerControlled && pawn.CanChangeDesignationColonist())
{
//row1 toggle - SexOverdrive
if (pawn.jobs?.curDriver is JobDriver_SexBaseInitiator)
{
float num = 32f;
float num2 = 4f;
float num3 = rect2.height / 2f - num + num2;
float num4 = rect2.width - num;
Rect rect9 = new Rect(rect2.x + num4, rect2.y + num3, num, num);
if (Widgets.ButtonImage(rect9, !(pawn.jobs?.curDriver as JobDriver_Sex).neverendingsex ? this.LimitedTex : this.UnlimitedTex, true))
{
if (pawn.jobs?.curDriver is JobDriver_SexBaseInitiator)
{
(pawn.jobs?.curDriver as JobDriver_Sex).neverendingsex = !(pawn.jobs?.curDriver as JobDriver_Sex).neverendingsex;
if ((pawn.jobs?.curDriver as JobDriver_Sex).neverendingsex)
{
SoundDefOf.Tick_Low.PlayOneShotOnCamera(null);
}
else
{
SoundDefOf.Tick_High.PlayOneShotOnCamera(null);
}
}
}
TooltipHandler.TipRegionByKey(rect9, "RJW_SexGizmo_SexOverdriveTooltip");
}
//row2 toggle - HitPawn
if (pawn.jobs?.curDriver is JobDriver_SexBaseInitiator) //TODO: maybe allow for receiver control someday?
{
if ((pawn.jobs?.curDriver as JobDriver_Sex).Sexprops != null)
if ((pawn.jobs?.curDriver as JobDriver_Sex).Sexprops.isRapist) //TODO: beating interrupts loving, fix someday?
{
float num = 32f;
float num2 = 34f;
float num3 = rect2.height / 2f - num + num2;
float num4 = rect2.width - num;
Rect rect11 = new Rect(rect2.x + num4, rect2.y + num3, num, num);
if (Widgets.ButtonImage(rect11, AttackTex, true))
{
(pawn.jobs?.curDriver as JobDriver_Sex).beatonce = true;
//SexUtility.Sex_Beatings_Dohit(pawn, ((JobDriver_Sex)pawn.jobs?.curDriver).Partner, ((JobDriver_Sex)pawn.jobs?.curDriver).isRape);
SoundDefOf.Tick_High.PlayOneShotOnCamera(null);
}
TooltipHandler.TipRegionByKey(rect11, "RJW_SexGizmo_HitPawn");
}
}
}
}
return new GizmoResult(GizmoState.Clear);
}
public override float GetWidth(float maxWidth)
{
return 212f;
}
private Pawn pawn;
private Texture2D LimitedTex;
private Texture2D UnlimitedTex;
private Texture2D AttackTex;
private const string LimitedIconPath = "UI/Icons/EntropyLimit/Limited";
private const string UnlimitedIconPath = "UI/Icons/EntropyLimit/Unlimited";
private const string AttackIconPath = "UI/Icons/HostilityResponse/Attack";
private static readonly Color PainBoostColor = new Color(0.2f, 0.65f, 0.35f);
private static readonly Texture2D EntropyBarTex = SolidColorMaterials.NewSolidColorTexture(new Color(0.46f, 0.34f, 0.35f));
private static readonly Texture2D OverLimitBarTex = SolidColorMaterials.NewSolidColorTexture(new Color(0.75f, 0.2f, 0.15f));
private static readonly Texture2D PsyfocusBarTex = SolidColorMaterials.NewSolidColorTexture(new Color(0.34f, 0.42f, 0.43f));
private static readonly Texture2D EmptyBarTex = SolidColorMaterials.NewSolidColorTexture(new Color(0.03f, 0.035f, 0.05f));
}
}
|
jojo1541/rjw
|
1.4/Source/Common/SexGizmo.cs
|
C#
|
mit
| 6,579
|
namespace rjw
{
public enum SexPartType : byte
{
Anus = 0,
FemaleBreast = 1,
FemaleGenital = 2,
MaleBreast = 3,
MaleGenital = 4
}
}
|
jojo1541/rjw
|
1.4/Source/Common/SexPartType.cs
|
C#
|
mit
| 148
|
using System;
using Verse;
namespace rjw
{
public static class SexPartTypeExtensions
{
public static BodyPartDef GetBodyPartDef(this SexPartType sexPartType)
{
return sexPartType switch
{
SexPartType.Anus => xxx.anusDef,
SexPartType.FemaleBreast => xxx.breastsDef,
SexPartType.FemaleGenital => xxx.genitalsDef,
SexPartType.MaleBreast => xxx.breastsDef,
SexPartType.MaleGenital => xxx.genitalsDef,
_ => throw new ArgumentException($"Unrecognized sexPartType: {sexPartType}")
};
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/SexPartTypeExtensions.cs
|
C#
|
mit
| 529
|
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace rjw
{
/// <summary>
/// Compares traits for equality but ignores forsed flag
/// </summary>
class TraitComparer : IEqualityComparer<Trait>
{
bool ignoreForced;
bool ignoreDegree;
public TraitComparer(bool ignoreDegree = false, bool ignoreForced = true)
{
this.ignoreDegree = ignoreDegree;
this.ignoreForced = ignoreForced;
}
public bool Equals(Trait x, Trait y)
{
return
x.def == y.def &&
(ignoreDegree || (x.Degree == y.Degree)) &&
(ignoreForced || (x.ScenForced == y.ScenForced));
}
public int GetHashCode(Trait obj)
{
return
(obj.def.GetHashCode() << 5) +
(ignoreDegree ? 0 : obj.Degree) +
((ignoreForced || obj.ScenForced) ? 0 : 0x10);
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/TraitComparer.cs
|
C#
|
mit
| 829
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace rjw
{
public static class Unprivater
{
internal const BindingFlags flags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
/// <summary>
/// T is for returned type. For instance-class fields
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static T GetProtectedValue<T>(string fieldName, object obj)
{
var fieldinfo = obj.GetType().GetField(fieldName, flags);
var readData = fieldinfo.GetValue(obj);
if (readData is T)
{
return (T)readData;
}
else
{
try
{
return (T)Convert.ChangeType(readData, typeof(T));
}
catch (InvalidCastException)
{
return default(T);
}
}
}
public static bool SetProtectedValue(string fieldName, object obj, object value)
{
var fieldinfo = obj.GetType().GetField(fieldName, flags);
try
{
fieldinfo.SetValue(obj, value);
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// T is for returned type. For instance-class properties ( [ get; thingies ] )
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static T GetProtectedProperty<T>(string propertyName, object obj)
{
var propinfo = obj.GetType().GetProperty(propertyName, flags);
var getter = propinfo.GetGetMethod(nonPublic: true);
var readData = getter.Invoke(obj, null);
if (readData is T)
{
return (T)readData;
}
else
{
try
{
return (T)Convert.ChangeType(readData, typeof(T));
}
catch (InvalidCastException)
{
return default(T);
}
}
}
public static bool SetProtectedProperty(string propertyName, object obj, object value)
{
var propinfo = obj.GetType().GetProperty(propertyName, flags);
try
{
propinfo.SetValue(obj, value, null);
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// T is for returned type. For static-class fields
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName"></param>
/// <param name="t"></param>
/// <returns></returns>
public static T GetProtectedValue<T>(string fieldName, Type t)
{
var fieldinfo = t.GetField(fieldName, flags);
var readData = fieldinfo.GetValue(null);
if (readData is T)
{
return (T)readData;
}
else
{
try
{
return (T)Convert.ChangeType(readData, typeof(T));
}
catch (InvalidCastException)
{
return default(T);
}
}
}
public static bool SetProtectedValue(string fieldName, Type t, object value)
{
var fieldinfo = t.GetField(fieldName, flags);
try
{
fieldinfo.SetValue(null, value);
return true;
}
catch (Exception)
{
return false;
}
}
// needs testing, dunno if it works for statics
public static T GetProtectedProperty<T>(string propertyName, Type t)
{
var propinfo = t.GetProperty(propertyName, flags);
var getter = propinfo.GetGetMethod(nonPublic: true);
var readData = getter.Invoke(null, null);
if (readData is T)
{
return (T)readData;
}
else
{
try
{
return (T)Convert.ChangeType(readData, typeof(T));
}
catch (InvalidCastException)
{
return default(T);
}
}
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/Unprivater.cs
|
C#
|
mit
| 3,622
|
namespace rjw
{
/*This is useless for now.
public class Verb_Fuck : Verb
{
private const int TargetCooldown = 40;
protected override bool TryCastShot()
{
Pawn casterPawn = base.CasterPawn;
Thing thing = this.currentTarget.Thing;
casterpawn.rotationTracker.Face(thing.DrawPos);
this.SoundJuicy().PlayOneShot(new TargetInfo(thing.Position, casterPawn.Map, false));
casterPawn.Drawer.Notify_MeleeAttackOn(thing);
casterpawn.rotationTracker.FaceCell(thing.Position);
if (casterPawn.caller != null) {
casterPawn.caller.Notify_DidMeleeAttack();
}
return true;
}
private SoundDef SoundJuicy()
{
return SoundDef.Named ("Sex");
}
}
*/
}
|
jojo1541/rjw
|
1.4/Source/Common/Verb_Fuck.cs
|
C#
|
mit
| 688
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Diagnostics;
using HarmonyLib;
using RimWorld;
using UnityEngine;
using Verse;
using Verse.AI;
using Verse.AI.Group;
using Verse.Sound;
using Multiplayer.API;
using System.Collections.ObjectModel;
//using static RimWorld.Planet.CaravanInventoryUtility;
//using RimWorldChildren;
namespace rjw
{
public static class xxx
{
public static readonly BindingFlags ins_public_or_no = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
public static readonly config config = DefDatabase<config>.GetNamed("the_one");
//HARDCODED MAGIC USED ACROSS DOZENS OF FILES, this is as bad place to put it as any other
//Should at the very least be encompassed in the related designation type
public static readonly int max_rapists_per_prisoner = 6;
//CombatExtended
public static bool CombatExtendedIsActive;
public static HediffDef MuscleSpasms;
//RomanceDiversified
public static bool RomanceDiversifiedIsActive; //A dirty way to check if the mod is active
public static TraitDef straight;
public static TraitDef faithful;
public static TraitDef philanderer;
public static TraitDef polyamorous;
//Psychology
public static bool PsychologyIsActive;
public static TraitDef prude;
public static TraitDef lecher;
public static TraitDef polygamous;
//Other poly mods
public static bool AnyPolyamoryModIsActive;
public static bool AnyPolygamyModIsActive;
//[SYR] Individuality
public static bool IndividualityIsActive;
public static TraitDef SYR_CreativeThinker;
public static TraitDef SYR_Haggler;
//Rimworld of Magic
public static bool RoMIsActive;
public static TraitDef Succubus;
public static TraitDef Warlock;
public static NeedDef TM_Mana;
public static HediffDef TM_ShapeshiftHD;
//Nightmare Incarnation
public static bool NightmareIncarnationIsActive;
public static NeedDef NI_Need_Mana;
//Consolidated
public static bool CTIsActive;
public static TraitDef RCT_NeatFreak;
public static TraitDef RCT_Savant;
public static TraitDef RCT_Inventor;
public static TraitDef RCT_AnimalLover;
//SimpleSlavery
public static bool SimpleSlaveryIsActive;
public static HediffDef Enslaved;
//Dubs Bad Hygiene
public static bool DubsBadHygieneIsActive;
public static NeedDef DBHThirst;
//Alien Framework
public static bool AlienFrameworkIsActive;
public static TraitDef xenophobia; // Degrees: 1: xenophobe, -1: xenophile
//Immortals
public static bool ImmortalsIsActive;
public static HediffDef IH_Immortal;
//Children&Pregnancy
public static bool RimWorldChildrenIsActive;
public static HediffDef BabyState;
public static HediffDef PostPregnancy;
public static HediffDef Lactating;
public static HediffDef NoManipulationFlag;
public static ThoughtDef IGaveBirthFirstTime;
public static ThoughtDef IGaveBirth;
public static ThoughtDef PartnerGaveBirth;
//Babies and Children(pretty much above + this)
public static HediffDef BnC_RJW_PostPregnancy;
//RJW-EX
public static bool RjwExIsActive;
public static HediffDef RjwEx_Armbinder;
//RJW Children
public static HediffDef RJW_BabyState = DefDatabase<HediffDef>.GetNamed("RJW_BabyState");
public static HediffDef RJW_NoManipulationFlag = DefDatabase<HediffDef>.GetNamed("RJW_NoManipulationFlag");
//rjw
public static readonly TraitDef nymphomaniac = DefDatabase<TraitDef>.GetNamed("Nymphomaniac");
public static readonly TraitDef rapist = DefDatabase<TraitDef>.GetNamed("Rapist");
public static readonly TraitDef masochist = DefDatabase<TraitDef>.GetNamed("Masochist");
public static readonly TraitDef necrophiliac = DefDatabase<TraitDef>.GetNamed("Necrophiliac");
public static readonly TraitDef zoophile = DefDatabase<TraitDef>.GetNamed("Zoophile");
public static readonly TraitDef footSlut = DefDatabase<TraitDef>.GetNamed("FootSlut");
public static readonly TraitDef cumSlut = DefDatabase<TraitDef>.GetNamed("CumSlut");
public static readonly TraitDef buttSlut = DefDatabase<TraitDef>.GetNamed("ButtSlut");
//The Hediff to prevent reproduction
public static readonly HediffDef sterilized = DefDatabase<HediffDef>.GetNamed("Sterilized");
//The Hediff for broken body(resulted from being raped as CP for too many times)
public static readonly HediffDef feelingBroken = DefDatabase<HediffDef>.GetNamed("FeelingBroken");
public static readonly HediffDef submitting = DefDatabase<HediffDef>.GetNamed("Hediff_Submitting");
public static PawnCapacityDef reproduction = DefDatabase<PawnCapacityDef>.GetNamed("RJW_Fertility");
//rjw Body parts
public static readonly BodyPartDef genitalsDef = DefDatabase<BodyPartDef>.GetNamed("Genitals");
public static readonly BodyPartDef breastsDef = DefDatabase<BodyPartDef>.GetNamed("Chest");
public static readonly BodyPartDef flankDef = DefDatabase<BodyPartDef>.GetNamed("Flank");
public static readonly BodyPartDef anusDef = DefDatabase<BodyPartDef>.GetNamed("Anus");
//aftersex thoughts
public static readonly ThoughtDef got_raped = DefDatabase<ThoughtDef>.GetNamed("GotRaped");
public static readonly ThoughtDef got_anal_raped = DefDatabase<ThoughtDef>.GetNamed("GotAnalRaped");
public static readonly ThoughtDef got_anal_raped_byfemale = DefDatabase<ThoughtDef>.GetNamed("GotAnalRapedByFemale");
public static readonly ThoughtDef got_raped_unconscious = DefDatabase<ThoughtDef>.GetNamed("GotRapedUnconscious");
public static readonly ThoughtDef masochist_got_raped_unconscious = DefDatabase<ThoughtDef>.GetNamed("MasochistGotRapedUnconscious");
public static readonly ThoughtDef got_bred = DefDatabase<ThoughtDef>.GetNamed("GotBredByAnimal");
public static readonly ThoughtDef got_anal_bred = DefDatabase<ThoughtDef>.GetNamed("GotAnalBredByAnimal");
public static readonly ThoughtDef got_licked = DefDatabase<ThoughtDef>.GetNamed("GotLickedByAnimal");
public static readonly ThoughtDef got_groped = DefDatabase<ThoughtDef>.GetNamed("GotGropedByAnimal");
public static readonly ThoughtDef masochist_got_raped = DefDatabase<ThoughtDef>.GetNamed("MasochistGotRaped");
public static readonly ThoughtDef masochist_got_anal_raped = DefDatabase<ThoughtDef>.GetNamed("MasochistGotAnalRaped");
public static readonly ThoughtDef masochist_got_anal_raped_byfemale = DefDatabase<ThoughtDef>.GetNamed("MasochistGotAnalRapedByFemale");
public static readonly ThoughtDef masochist_got_bred = DefDatabase<ThoughtDef>.GetNamed("MasochistGotBredByAnimal");
public static readonly ThoughtDef masochist_got_anal_bred = DefDatabase<ThoughtDef>.GetNamed("MasochistGotAnalBredByAnimal");
public static readonly ThoughtDef masochist_got_licked = DefDatabase<ThoughtDef>.GetNamed("MasochistGotLickedByAnimal");
public static readonly ThoughtDef masochist_got_groped = DefDatabase<ThoughtDef>.GetNamed("MasochistGotGropedByAnimal");
public static readonly ThoughtDef allowed_animal_to_breed = DefDatabase<ThoughtDef>.GetNamed("AllowedAnimalToBreed");
public static readonly ThoughtDef allowed_animal_to_lick = DefDatabase<ThoughtDef>.GetNamed("AllowedAnimalToLick");
public static readonly ThoughtDef allowed_animal_to_grope = DefDatabase<ThoughtDef>.GetNamed("AllowedAnimalToGrope");
public static readonly ThoughtDef zoophile_got_bred = DefDatabase<ThoughtDef>.GetNamed("ZoophileGotBredByAnimal");
public static readonly ThoughtDef zoophile_got_anal_bred = DefDatabase<ThoughtDef>.GetNamed("ZoophileGotAnalBredByAnimal");
public static readonly ThoughtDef zoophile_got_licked = DefDatabase<ThoughtDef>.GetNamed("ZoophileGotLickedByAnimal");
public static readonly ThoughtDef zoophile_got_groped = DefDatabase<ThoughtDef>.GetNamed("ZoophileGotGropedByAnimal");
public static readonly ThoughtDef hate_my_rapist = DefDatabase<ThoughtDef>.GetNamed("HateMyRapist");
public static readonly ThoughtDef kinda_like_my_rapist = DefDatabase<ThoughtDef>.GetNamed("KindaLikeMyRapist");
public static readonly ThoughtDef allowed_me_to_get_raped = DefDatabase<ThoughtDef>.GetNamed("AllowedMeToGetRaped");
public static readonly ThoughtDef stole_some_lovin = DefDatabase<ThoughtDef>.GetNamed("StoleSomeLovin");
public static readonly ThoughtDef bloodlust_stole_some_lovin = DefDatabase<ThoughtDef>.GetNamed("BloodlustStoleSomeLovin");
public static readonly ThoughtDef violated_corpse = DefDatabase<ThoughtDef>.GetNamed("ViolatedCorpse");
public static readonly ThoughtDef gave_virginity = DefDatabase<ThoughtDef>.GetNamed("FortunateGaveVirginity");
public static readonly ThoughtDef lost_virginity = DefDatabase<ThoughtDef>.GetNamed("UnfortunateLostVirginity");
public static readonly ThoughtDef took_virginity = DefDatabase<ThoughtDef>.GetNamed("TookVirginity");
public static readonly JobDef Masturbate = DefDatabase<JobDef>.GetNamed("RJW_Masturbate");
public static readonly JobDef casual_sex = DefDatabase<JobDef>.GetNamed("JoinInBed");
public static readonly JobDef knotted = DefDatabase<JobDef>.GetNamed("RJW_Knotted");
public static readonly JobDef gettin_loved = DefDatabase<JobDef>.GetNamed("GettinLoved");
public static readonly JobDef gettin_raped = DefDatabase<JobDef>.GetNamed("GettinRaped");
public static readonly JobDef gettin_bred = DefDatabase<JobDef>.GetNamed("GettinBred");
public static readonly JobDef RapeCP = DefDatabase<JobDef>.GetNamed("RapeComfortPawn");
public static readonly JobDef RapeEnemy = DefDatabase<JobDef>.GetNamed("RapeEnemy");
public static readonly JobDef RapeRandom = DefDatabase<JobDef>.GetNamed("RandomRape");
public static readonly JobDef RapeCorpse = DefDatabase<JobDef>.GetNamed("ViolateCorpse");
public static readonly JobDef bestiality = DefDatabase<JobDef>.GetNamed("Bestiality");
public static readonly JobDef bestialityForFemale = DefDatabase<JobDef>.GetNamed("BestialityForFemale");
public static readonly JobDef whore_inviting_visitors = DefDatabase<JobDef>.GetNamedSilentFail("WhoreInvitingVisitors");
public static readonly JobDef whore_is_serving_visitors = DefDatabase<JobDef>.GetNamedSilentFail("WhoreIsServingVisitors");
public static readonly JobDef animalMate = DefDatabase<JobDef>.GetNamed("RJW_Mate");
public static readonly JobDef animalBreed = DefDatabase<JobDef>.GetNamed("Breed");
public static readonly JobDef quick_sex = DefDatabase<JobDef>.GetNamed("Quickie");
public static readonly JobDef getting_quickie = DefDatabase<JobDef>.GetNamed("GettingQuickie");
public static readonly JobDef struggle_in_BondageGear = DefDatabase<JobDef>.GetNamed("StruggleInBondageGear");
public static readonly JobDef unlock_BondageGear = DefDatabase<JobDef>.GetNamed("UnlockBondageGear");
public static readonly JobDef give_BondageGear = DefDatabase<JobDef>.GetNamed("GiveBondageGear");
public static readonly FleckDef mote_noheart = DefDatabase<FleckDef>.GetNamed("Mote_NoHeart");
public static readonly StatDef sex_satisfaction = DefDatabase<StatDef>.GetNamed("SexSatisfaction");
public static readonly StatDef vulnerability_stat = DefDatabase<StatDef>.GetNamed("Vulnerability");
public static readonly StatDef sex_drive_stat = DefDatabase<StatDef>.GetNamed("SexFrequency");
public static readonly RecordDef GetRapedAsComfortPawn = DefDatabase<RecordDef>.GetNamed("GetRapedAsComfortPrisoner");
public static readonly RecordDef CountOfFappin = DefDatabase<RecordDef>.GetNamed("CountOfFappin");
public static readonly RecordDef CountOfSex = DefDatabase<RecordDef>.GetNamed("CountOfSex");
public static readonly RecordDef CountOfSexWithHumanlikes = DefDatabase<RecordDef>.GetNamed("CountOfSexWithHumanlikes");
public static readonly RecordDef CountOfSexWithAnimals = DefDatabase<RecordDef>.GetNamed("CountOfSexWithAnimals");
public static readonly RecordDef CountOfSexWithInsects = DefDatabase<RecordDef>.GetNamed("CountOfSexWithInsects");
public static readonly RecordDef CountOfSexWithOthers = DefDatabase<RecordDef>.GetNamed("CountOfSexWithOthers");
public static readonly RecordDef CountOfSexWithCorpse = DefDatabase<RecordDef>.GetNamed("CountOfSexWithCorpse");
public static readonly RecordDef CountOfRapedHumanlikes = DefDatabase<RecordDef>.GetNamed("CountOfRapedHumanlikes");
public static readonly RecordDef CountOfBeenRapedByHumanlikes = DefDatabase<RecordDef>.GetNamed("CountOfBeenRapedByHumanlikes");
public static readonly RecordDef CountOfRapedAnimals = DefDatabase<RecordDef>.GetNamed("CountOfRapedAnimals");
public static readonly RecordDef CountOfBeenRapedByAnimals = DefDatabase<RecordDef>.GetNamed("CountOfBeenRapedByAnimals");
public static readonly RecordDef CountOfRapedInsects = DefDatabase<RecordDef>.GetNamed("CountOfRapedInsects");
public static readonly RecordDef CountOfBeenRapedByInsects = DefDatabase<RecordDef>.GetNamed("CountOfBeenRapedByInsects");
public static readonly RecordDef CountOfRapedOthers = DefDatabase<RecordDef>.GetNamed("CountOfRapedOthers");
public static readonly RecordDef CountOfBeenRapedByOthers = DefDatabase<RecordDef>.GetNamed("CountOfBeenRapedByOthers");
public static readonly RecordDef CountOfBirthHuman = DefDatabase<RecordDef>.GetNamed("CountOfBirthHuman");
public static readonly RecordDef CountOfBirthAnimal = DefDatabase<RecordDef>.GetNamed("CountOfBirthAnimal");
public static readonly RecordDef CountOfBirthEgg = DefDatabase<RecordDef>.GetNamed("CountOfBirthEgg");
public static readonly MeditationFocusDef SexMeditationFocus = DefDatabase<MeditationFocusDef>.GetNamed("Sex");
public enum rjwSextype { None, Vaginal, Anal, Oral, Masturbation, DoublePenetration, Boobjob, Handjob, Footjob, Fingering, Scissoring, MutualMasturbation, Fisting, MechImplant, Rimming, Fellatio, Cunnilingus, Sixtynine }
public static readonly ReadOnlyCollection <rjwSextype> rjwSextypeCollection = Array.AsReadOnly((rjwSextype[])Enum.GetValues(typeof(rjwSextype)));
public static void bootstrap(Map m)
{
if (m.GetComponent<MapCom_Injector>() == null)
m.components.Add(new MapCom_Injector(m));
}
//<Summary>Simple method that quickly checks for match from a list.</Summary>
public static bool ContainsAny(this string haystack, params string[] needles) { return needles.Any(haystack.Contains); }
public static bool has_traits(Pawn pawn)
{
return pawn?.story?.traits != null;
}
public static bool has_quirk(Pawn pawn, string quirk)
{
return pawn != null && is_human(pawn) && CompRJW.Comp(pawn).quirks.ToString().Contains(quirk);
}
[SyncMethod]
public static string random_pick_a_trait(this Pawn pawn)
{
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
return has_traits(pawn) ? pawn.story.traits.allTraits.RandomElement().def.defName : null;
}
public static bool is_psychopath(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(TraitDefOf.Psychopath);
}
public static bool is_ascetic(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(TraitDefOf.Ascetic);
}
public static bool is_bloodlust(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(TraitDefOf.Bloodlust);
}
public static bool is_brawler(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(TraitDefOf.Brawler);
}
public static bool is_kind(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(TraitDefOf.Kind);
}
public static bool is_rapist(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(rapist);
}
public static bool is_necrophiliac(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(necrophiliac);
}
public static bool is_zoophile(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(zoophile);
}
public static bool is_masochist(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(TraitDef.Named("Masochist"));
}
/// <summary>
/// Returns true if the given pawn has the nymphomaniac trait.
/// This may or may not be a nymph pawnKind.
/// </summary>
public static bool is_nympho(Pawn pawn)
{
return has_traits(pawn) && pawn.story.traits.HasTrait(nymphomaniac);
}
public static bool is_slime(Pawn pawn)
{
string racename = pawn.kindDef.race.defName.ToLower();
//if (Prefs.DevMode) ModLog.Message(" is_slime " + xxx.get_pawnname(pawn) + " " + racename.Contains("slime"));
return racename.Contains("slime");
}
public static bool is_demon(Pawn pawn)
{
string racename = pawn.kindDef.race.defName.ToLower();
//if (Prefs.DevMode) ModLog.Message(" is_demon " + xxx.get_pawnname(pawn) + " " + racename.Contains("demon"));
return racename.Contains("demon");
}
public static bool is_asexual(Pawn pawn) => CompRJW.Comp(pawn).orientation == Orientation.Asexual;
public static bool is_bisexual(Pawn pawn) => CompRJW.Comp(pawn).orientation == Orientation.Bisexual;
public static bool is_homosexual(Pawn pawn) => (CompRJW.Comp(pawn).orientation == Orientation.Homosexual || CompRJW.Comp(pawn).orientation == Orientation.MostlyHomosexual);
public static bool is_heterosexual(Pawn pawn) => (CompRJW.Comp(pawn).orientation == Orientation.Heterosexual || CompRJW.Comp(pawn).orientation == Orientation.MostlyHeterosexual);
public static bool is_pansexual(Pawn pawn) => CompRJW.Comp(pawn).orientation == Orientation.Pansexual;
public static bool is_slave(Pawn pawn)
{
if (is_vanillaslave(pawn) || is_modslave(pawn))
return true;
else
return false;
}
public static bool is_vanillaslave(Pawn pawn)
{
if (pawn.IsSlave)//1.3
return true;
else
return false;
}
public static bool is_modslave(Pawn pawn)
{
if (SimpleSlaveryIsActive)
return pawn?.health.hediffSet.HasHediff(xxx.Enslaved) ?? false;
else
return false;
}
public static bool is_nympho_or_rapist_or_zoophile(Pawn pawn)
{
if (!has_traits(pawn)) { return false; }
return (is_rapist(pawn) || is_nympho(pawn) || is_zoophile(pawn));
}
//Humanoid Alien Framework traits
public static bool is_xenophile(Pawn pawn)
{
if (!has_traits(pawn) || !AlienFrameworkIsActive) { return false; }
return pawn.story.traits.DegreeOfTrait(xenophobia) == -1;
}
public static bool is_xenophobe(Pawn pawn)
{
if (!has_traits(pawn) || !AlienFrameworkIsActive) { return false; }
return pawn.story.traits.DegreeOfTrait(xenophobia) == 1;
}
public static bool is_whore(Pawn pawn)
{
if (!has_traits(pawn)) { return false; }
return pawn != null && pawn.IsDesignatedService() && !pawn.story.traits.HasTrait(TraitDefOf.Asexual);
//return (pawn != null && pawn.ownership != null && pawn.ownership.OwnedBed is Building_WhoreBed && (!xxx.RomanceDiversifiedIsActive || !pawn.story.traits.HasTrait(xxx.asexual)));
}
public static bool is_lecher(Pawn pawn)
{
if (!has_traits(pawn)) { return false; }
return RomanceDiversifiedIsActive && pawn.story.traits.HasTrait(philanderer) || PsychologyIsActive && pawn.story.traits.HasTrait(lecher);
}
public static bool is_prude(Pawn pawn)
{
if (!has_traits(pawn)) { return false; }
if (is_nympho(pawn)) { return false; }
if (pawn.IsIdeologicallyPrudish()) { return true; }
return RomanceDiversifiedIsActive && pawn.story.traits.HasTrait(faithful) || PsychologyIsActive && pawn.story.traits.HasTrait(prude);
}
public static bool is_animal(Pawn pawn)
{
return pawn?.RaceProps?.Animal ?? false;
}
public static bool is_insect(Pawn pawn)
{
if (pawn == null) return false;
bool isit = pawn.RaceProps.FleshType == FleshTypeDefOf.Insectoid
|| pawn.RaceProps.FleshType.corpseCategory.ToString().Contains("CorpsesInsect")
//genetic rim
|| pawn.RaceProps.FleshType.defName.Contains("GR_Insectoid");
//Log.Message("is_insect " + get_pawnname(pawn) + " - " + isit);
return isit;
}
public static bool is_mechanoid(Pawn pawn)
{
if (pawn == null) return false;
if (AndroidsCompatibility.IsAndroid(pawn)) return false;
bool isit = pawn.RaceProps.IsMechanoid
|| pawn.RaceProps.FleshType == FleshTypeDefOf.Mechanoid
|| pawn.RaceProps.FleshType.corpseCategory.ToString().Contains("CorpsesMechanoid")
//genetic rim
|| pawn.RaceProps.FleshType.defName.Contains("GR_Mechanoid")
//android tiers
|| pawn.RaceProps.FleshType.defName.Contains("MechanisedInfantry")
|| pawn.RaceProps.FleshType.defName.Contains("Android")
;
//Log.Message("is_mechanoid " + get_pawnname(pawn) + " - " + isit);
return isit;
}
public static bool is_tooluser(Pawn pawn)
{
return pawn.RaceProps.ToolUser;
}
public static bool is_human(Pawn pawn)
{
if (pawn == null) return false;
return pawn.RaceProps.Humanlike;
}
public static bool is_female(Pawn pawn)
{
return pawn.gender == Gender.Female;
}
public static bool is_male(Pawn pawn)
{
return pawn.gender == Gender.Male;
}
public static bool is_healthy(Pawn pawn)
{
return !pawn.Dead &&
pawn.health.capacities.CanBeAwake &&
pawn.health.hediffSet.BleedRateTotal <= 0.0f &&
pawn.health.hediffSet.PainTotal < config.significant_pain_threshold;
}
/// <summary>
/// not going to die soon
/// </summary>
/// <param name="pawn"></param>
/// <returns></returns>
public static bool is_healthy_enough(Pawn pawn)
{
return !pawn.Dead &&
pawn.health.capacities.CanBeAwake &&
pawn.health.hediffSet.BleedRateTotal <= 0.1f;
}
/// <summary>
/// pawn can initiate action or respond - whoring, etc
/// </summary>
public static bool IsTargetPawnOkay(Pawn pawn)
{
return xxx.is_healthy(pawn) && !pawn.Downed && !pawn.Suspended;
}
public static bool is_not_dying(Pawn pawn)
{
return !pawn.Dead &&
pawn.health.hediffSet.BleedRateTotal <= 0.3f;
}
public static bool is_starved(Pawn pawn)
{
return pawn?.needs?.food != null &&
pawn.needs.food.Starving;
}
public static float bleedingRate(Pawn pawn)
{
return pawn?.health?.hediffSet?.BleedRateTotal ?? 0f;
}
public static string get_pawnname(Pawn who)
{
//ModLog.Message("xxx::get_pawnname is "+ who.KindLabelDefinite());
//ModLog.Message("xxx::get_pawnname is "+ who.KindLabelIndefinite());
if (who == null) return "null";
string name = who.Label;
if (name != null)
{
if (who.Name?.ToStringShort != null)
name = who.Name.ToStringShort;
}
else
name = "noname";
return name;
}
public static bool is_gettin_rapedNow(Pawn pawn)
{
if (pawn?.jobs?.curDriver != null)
{
return pawn.jobs.curDriver.GetType() == typeof(JobDriver_SexBaseRecieverRaped);
}
return false;
}
//cells checks are cheap, pathing is expensive. Do pathing check last.)
public static float need_some_sex(Pawn pawn)
{
// 3=> always horny for non humanlikes
float horniness_degree = 3f;
Need_Sex need_sex = pawn.needs.TryGetNeed<Need_Sex>();
if (need_sex == null) return horniness_degree;
if (need_sex.CurLevel < need_sex.thresh_frustrated()) horniness_degree = 3f;
else if (need_sex.CurLevel < need_sex.thresh_horny()) horniness_degree = 2f;
else if (need_sex.CurLevel < need_sex.thresh_satisfied()) horniness_degree = 1f;
else horniness_degree = 0f;
return horniness_degree;
}
public enum SexNeed
{
Frustrated,
Horny,
Neutral,
Satisfied
};
public static SexNeed need_sex(Pawn pawn)
{
// 3=> always horny for non humanlikes, since they dont have need
Need_Sex need_sex = pawn.needs.TryGetNeed<Need_Sex>();
if (need_sex == null) return SexNeed.Frustrated;
if (RJWSettings.sexneed_fix)
return need_sex_fixed(pawn);
else
return need_sex_broken(pawn);
}
/// <summary>
/// Original rjw threshholds for sex
/// </summary>
/// <param name="pawn"></param>
/// <returns></returns>
private static SexNeed need_sex_broken(Pawn pawn)
{
Need_Sex need_sex = pawn.needs.TryGetNeed<Need_Sex>();
if (need_sex.CurLevel >= need_sex.thresh_satisfied())
return SexNeed.Satisfied;
else if (need_sex.CurLevel >= need_sex.thresh_neutral())
return SexNeed.Neutral;
else if (need_sex.CurLevel >= need_sex.thresh_horny())
return SexNeed.Horny;
else
return SexNeed.Frustrated;
}
private static SexNeed need_sex_fixed(Pawn pawn)
{
// 3=> always horny for non humanlikes
Need_Sex need_sex = pawn.needs.TryGetNeed<Need_Sex>();
if (need_sex.CurLevel <= need_sex.thresh_frustrated())
return SexNeed.Frustrated;
else if (need_sex.CurLevel <= need_sex.thresh_horny())
return SexNeed.Horny;
else if (need_sex.CurLevel <= need_sex.thresh_neutral())
return SexNeed.Neutral;
else
return SexNeed.Satisfied;
}
public static bool is_frustrated(Pawn pawn)
{
return need_sex(pawn) == SexNeed.Frustrated;
}
public static bool is_horny(Pawn pawn)
{
return need_sex(pawn) == SexNeed.Horny;
}
public static bool is_hornyorfrustrated(Pawn pawn)
{
return (need_sex(pawn) == SexNeed.Horny || need_sex(pawn) == SexNeed.Frustrated);
}
public static bool is_neutral(Pawn pawn)
{
return need_sex(pawn) == SexNeed.Neutral;
}
public static bool is_satisfied(Pawn pawn)
{
return need_sex(pawn) == SexNeed.Satisfied;
}
/// <summary> Checks to see if the pawn has any partners who don't have a Polyamorous/Polygamous trait or ideo; aka someone who'd get mad about sleeping around. </summary>
/// <returns> True if the pawn has at least one romantic partner who does not have a poly trait or ideo. False if no partners or all partners are poly. </returns>
public static bool HasNonPolyPartner(Pawn pawn, bool onCurrentMap = false)
{
if (pawn.relations == null) // probably droids or who knows what modded abomination
return false;
var partners = LovePartnerRelationUtility.ExistingLovePartners(pawn, allowDead: false).Select(rel => rel.otherPawn);
// If they don't have a partner at all we can bail right away.
if (!partners.Any())
return false;
foreach (var partner in partners)
{
// Stasised partners will never find out!
if (partner.Suspended)
continue;
// Neither does anyone on another map because cheating away from home is obviously never ever discovered
if (onCurrentMap) // check only on Current Map
if (pawn.Map == null || partner.Map == null || partner.Map != pawn.Map)
continue;
if (partner.IsPoly())
{
// We have a partner who has a poly trait or ideo! But they could have multiple partners so keep checking.
continue;
}
// We found a partner who isn't poly.
return true;
}
// If we got here then we checked every partner and all of them had a poly trait, so they don't have a non-poly partner.
return false;
}
public static Gender opposite_gender(Gender g)
{
switch (g)
{
case Gender.Male:
return Gender.Female;
case Gender.Female:
return Gender.Male;
default:
return Gender.None;
}
}
public static float get_sex_satisfaction(Pawn pawn)
{
try
{
return pawn.GetStatValue(xxx.sex_satisfaction, false);
}
catch (NullReferenceException)
//not seeded with stats, error for non humanlikes/corpses
//this and below should probably be rewritten to do calculations here
{
//Log.Warning(e.ToString());
return 1f;
}
}
public static float get_vulnerability(Pawn pawn)
{
try
{
return pawn.GetStatValue(vulnerability_stat, false);
}
catch (NullReferenceException)
//not seeded with stats, error for non humanlikes/corpses
{
//Log.Warning(e.ToString());
return 1f;
}
}
public static float get_sex_drive(Pawn pawn)
{
try
{
return pawn.GetStatValue(sex_drive_stat, false) * (pawn.GetRJWPawnData().raceSexDrive);
}
catch (NullReferenceException)
//not seeded with stats, error for non humanlikes/corpses
{
//Log.Warning(e.ToString());
return 1f;
}
}
public static bool IsSingleOrPartnersNotHere(Pawn pawn)
{
var relations = LovePartnerRelationUtility.ExistingLovePartners(pawn, allowDead: false);
if (!relations.Any())
{
return true;
}
return relations.All(rel => rel.otherPawn.Map != pawn.Map);
}
//base check
public static bool can_do_loving(Pawn pawn)
{
if (is_mechanoid(pawn))
return false;
if (is_human(pawn))
{
int age = pawn.ageTracker.AgeBiologicalYears;
var t = 13;
if (pawn.GetRJWPawnData().RaceSupportDef?.teenAge != null && pawn.GetRJWPawnData().RaceSupportDef?.teenAge != 0)
{
t = pawn.GetRJWPawnData().RaceSupportDef.teenAge;
}
else if (!pawn.ageTracker.CurLifeStage.reproductive)
if (pawn.ageTracker.Growth < 1)
return false;
if (age < t)
return false;
if (!pawn.apparel.WornApparel.NullOrEmpty())
if (pawn.apparel.WornApparel.Where(x => x.def.defName.ToLower().Contains("warcasket")).Any())
return false;
return true;
}
if (is_animal(pawn))
{
if (pawn.GetRJWPawnData().RaceSupportDef?.teenAge != null && pawn.GetRJWPawnData().RaceSupportDef?.teenAge != 0)
{
int age = pawn.ageTracker.AgeBiologicalYears;
int t = pawn.GetRJWPawnData().RaceSupportDef.teenAge;
if (age < t)
return false;
}
//CurLifeStageIndex/Growth for insects since they are not reproductive
else if (!pawn.ageTracker.CurLifeStage.reproductive)
if (pawn.ageTracker.Growth < 1)
return false;
return true;
}
return false;
}
public static bool can_do_animalsex(Pawn pawn1, Pawn pawn2)
{
bool v = false;
if (xxx.is_animal(pawn1) && xxx.is_animal(pawn2))
if (RJWSettings.animal_on_animal_enabled)
v = true;
else if (RJWSettings.bestiality_enabled)
v = true;
return v;
}
public static bool can_masturbate(Pawn pawn)
{
if (!RJWPreferenceSettings.FapInArmbinders)
if (Genital_Helper.hands_blocked(pawn))
return false;
if (!RJWPreferenceSettings.FapInBelts)
if (Genital_Helper.genitals_blocked(pawn))
return false;
if (!xxx.can_be_fucked(pawn) && !xxx.can_fuck(pawn)) //TODO: should improve this someday
return false;
return true;
}
// Penetrative organ check.
public static bool can_fuck(Pawn pawn)
{
//this may cause problems with human mechanoids, like misc. bots or other custom race mechanoids
if (is_mechanoid(pawn))
return true;
if (!can_do_loving(pawn))
return false;
var parts = pawn.GetGenitalsList();
if (Genital_Helper.penis_blocked(pawn) || (!Genital_Helper.has_penis_fertile(pawn, parts) && !Genital_Helper.has_penis_infertile(pawn, parts) && !Genital_Helper.has_ovipositorF(pawn, parts))) return false;
return true;
}
// Orifice check.
public static bool can_be_fucked(Pawn pawn)
{
if (is_mechanoid(pawn))
return false;
if (!can_do_loving(pawn))
return false;
if (Genital_Helper.has_anus(pawn) && !Genital_Helper.anus_blocked(pawn))
return true;
if (Genital_Helper.has_vagina(pawn) && !Genital_Helper.vagina_blocked(pawn))
return true;
if (Genital_Helper.has_mouth(pawn) && !Genital_Helper.oral_blocked(pawn))
return true;
//not sure about below, when female rape male, need to check all code so meh
//if ((Genital_Helper.has_penis(pawn) || Genital_Helper.has_penis_infertile(pawn) || Genital_Helper.has_ovipositorF(pawn)) && !Genital_Helper.penis_blocked(pawn))
// return true;
//if (Genital_Helper.has_breasts(pawn) && !Genital_Helper.breasts_blocked(pawn))
// return true;
//if (pawn.health.hediffSet.GetNotMissingParts().Any(part => part.IsInGroup(BodyPartGroupDefOf.RightHand) || part.IsInGroup(BodyPartGroupDefOf.LeftHand)) && !Genital_Helper.hands_blocked(pawn))
// return true;
return false;
}
public static bool can_rape(Pawn pawn, bool forced = false)
{
if (!RJWSettings.rape_enabled)
return false;
if (is_mechanoid(pawn))
return true;
if (!(can_fuck(pawn) ||
(!is_male(pawn) && get_vulnerability(pawn) < RJWSettings.nonFutaWomenRaping_MaxVulnerability && can_be_fucked(pawn))))
return false;
if (is_human(pawn))
{
if (pawn.ageTracker.Growth < 1 && !pawn.ageTracker.CurLifeStage.reproductive)
return false;
if (RJWSettings.WildMode || forced)
return true;
return need_some_sex(pawn) > 0;
}
return true;
}
public static bool can_get_raped(Pawn pawn)
{
if (!RJWSettings.rape_enabled)
return false;
if (!can_be_fucked(pawn))
return false;
if (is_human(pawn))
{
if (pawn.ageTracker.Growth < 1 && !pawn.ageTracker.CurLifeStage.reproductive)
return false;
if (RJWSettings.WildMode)
return true;
if (!(RJWSettings.rapee_MinVulnerability_human >= 0 && get_vulnerability(pawn) > RJWSettings.rapee_MinVulnerability_human))
return false;
}
return true;
}
public static bool is_Virgin(Pawn pawn)
{
//if (RJWSettings.DevMode) ModLog.Message("xxx::is_Virgin check:" +get_pawnname(pawn));
if (pawn.relations != null)
if (pawn.relations.ChildrenCount > 0)
{
//if (RJWSettings.DevMode) ModLog.Message("xxx::is_Virgin " + " ChildrenCount " + pawn.relations.ChildrenCount);
return false;
}
if (!(
pawn.records.GetValue(GetRapedAsComfortPawn) == 0 &&
pawn.records.GetValue(CountOfSex) == 0 &&
pawn.records.GetValue(CountOfSexWithHumanlikes) == 0 &&
pawn.records.GetValue(CountOfSexWithAnimals) == 0 &&
pawn.records.GetValue(CountOfSexWithInsects) == 0 &&
pawn.records.GetValue(CountOfSexWithOthers) == 0 &&
pawn.records.GetValue(CountOfSexWithCorpse) == 0 &&
//pawn.records.GetValue(CountOfWhore) == 0 &&
pawn.records.GetValue(CountOfRapedHumanlikes) == 0 &&
pawn.records.GetValue(CountOfBeenRapedByHumanlikes) == 0 &&
pawn.records.GetValue(CountOfRapedAnimals) == 0 &&
pawn.records.GetValue(CountOfBeenRapedByAnimals) == 0 &&
pawn.records.GetValue(CountOfRapedInsects) == 0 &&
pawn.records.GetValue(CountOfBeenRapedByInsects) == 0 &&
pawn.records.GetValue(CountOfRapedOthers) == 0 &&
pawn.records.GetValue(CountOfBeenRapedByOthers) == 0 &&
pawn.records.GetAsInt(xxx.CountOfBirthHuman) == 0 &&
pawn.records.GetAsInt(xxx.CountOfBirthAnimal) == 0 &&
pawn.records.GetAsInt(xxx.CountOfBirthEgg) == 0
))
{
//if (RJWSettings.DevMode) ModLog.Message("xxx::is_Virgin " + "records check fail");
return false;
}
return true;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Common/xxx.cs
|
C#
|
mit
| 34,476
|
using Verse;
using System.Linq;
using RimWorld;
namespace rjw
{
[StaticConstructorOnStartup]
public static class AddComp
{
static AddComp()
{
AddRJWComp();
}
/// <summary>
/// This automatically adds the comp to all races on startup.
/// </summary>
public static void AddRJWComp()
{
foreach (ThingDef thingDef in DefDatabase<ThingDef>.AllDefs.Where(thingDef =>
thingDef.race != null))
{
thingDef.comps.Add(new CompProperties_RJW());
//Log.Message("AddRJWComp to race " + thingDef.label);
}
foreach (PawnKindDef pawnKindDef in DefDatabase<PawnKindDef>.AllDefs.Where(pawnKindDef => pawnKindDef.race.race != null))
{
RaceGroupDef raceGroupDef = null;
if (RaceGroupDef_Helper.TryGetRaceGroupDef(pawnKindDef, out raceGroupDef))
{
//Log.Message("RaceGroupDef_Helper " + raceGroupDef.defName + " for " + pawnKindDef.race.defName);
if (raceGroupDef.oviPregnancy)
{
if (pawnKindDef.race.comps.Any(x => x is CompProperties_EggLayer))
{
//Log.Message(pawnKindDef.race.defName + " was already egglayer");
}
else
{
CompProperties_EggLayer eggProps = OviHelper.GenerateEggLayerProperties(pawnKindDef, raceGroupDef);
pawnKindDef.race.comps.Add(eggProps);
//Log.Message(pawnKindDef.race.defName + " is now egglayer and lays " + eggProps.eggFertilizedDef.defName + " eggs");
}
}
}
}
// For some reason eggs only grow if a pawn has a lifestage that is "milkable"
// This might not be ideal...
foreach (LifeStageDef lifeStage in DefDatabase<LifeStageDef>.AllDefs)
{
if (lifeStage.reproductive)
{
lifeStage.milkable = true;
}
}
}
}
}
|
jojo1541/rjw
|
1.4/Source/Comps/CompAdder.cs
|
C#
|
mit
| 1,705
|
using Verse;
namespace rjw
{
public class CompProperties_RJW : CompProperties
{
public CompProperties_RJW()
{
compClass = typeof(CompRJW);
}
}
public class CompProperties_HediffBodyPart : HediffCompProperties
{
public CompProperties_HediffBodyPart()
{
compClass = typeof(CompHediffBodyPart);
}
}
public class CompProperties_ThingBodyPart : CompProperties
{
public CompProperties_ThingBodyPart()
{
compClass = typeof(CompThingBodyPart);
}
}
}
|
jojo1541/rjw
|
1.4/Source/Comps/CompProperties.cs
|
C#
|
mit
| 480
|
#nullable enable
using Psychology;
using SyrTraits;
using System.Text;
using Verse;
using RimWorld;
using Multiplayer.API;
namespace rjw
{
public class CompRJW : ThingComp
{
/// <summary>
/// Core comp for genitalia and sexuality tracking.
/// </summary>
public CompRJW() { }
public CompProperties_RJW Props => (CompProperties_RJW)props;
public Orientation orientation = Orientation.None;
public StringBuilder quirks = new();
public string quirksave = ""; // Not the most elegant way to do this, but it minimizes the save bloat.
public int NextHookupTick;
private bool BootStrapTriggered = false;
public Need_Sex? sexNeed;
/// <summary>
/// <para>Gets the pawn for this comp.</para>
/// <para>May return null if the comp's parent is somehow not a pawn.</para>
/// </summary>
private Pawn? pawn;
private Pawn? Pawn => parent is Pawn pawn ? pawn : null;
// This automatically checks that genitalia has been added to all freshly spawned pawns.
public override void PostSpawnSetup(bool respawningAfterLoad)
{
base.PostSpawnSetup(respawningAfterLoad);
if (pawn == null)
{
pawn = Pawn;
if (pawn == null) return;
}
if (pawn.kindDef.race.defName.Contains("AIRobot") // No genitalia/sexuality for roombas.
|| pawn.kindDef.race.defName.Contains("AIPawn") // ...nor MAI.
|| pawn.kindDef.race.defName.Contains("RPP_Bot")
|| pawn.kindDef.race.defName.Contains("PRFDrone") // Project RimFactory Revived drones
) return;
// No genitalia
//if (!pawn.RaceProps.body.AllParts.Exists(x => x.def == DefDatabase<BodyPartDef>.GetNamed("Genitals")))
// return;
if (Comp(pawn).orientation == Orientation.None)
{
Sexualize(pawn);
Sexualize(pawn, true);
}
//Log.Message("PostSpawnSetup for " + pawn?.Name);
}
public override void CompTick()
{
base.CompTick();
if (pawn == null)
{
pawn = Pawn;
if (pawn == null) return;
}
if (pawn.IsHashIntervalTick(1500) && !pawn.health.Dead)
// The `NeedInterval` function is called every 150 ticks but was formerly
// rate limited by a factor of 10. This will make the upkeep execute at
// the same interval.
{
if (sexNeed == null)
{
sexNeed = pawn.needs?.TryGetNeed<Need_Sex>();
}
if (sexNeed != null)
{
DoUpkeep(pawn, sexNeed);
}
}
}
/// <summary>
/// Performs some upkeep tasks originally handled in `Need_Sex.NeedInterval`.
/// </summary>
private void DoUpkeep(Pawn pawn, Need_Sex sexNeed)
{
if (pawn.Map == null) return;
if (xxx.is_asexual(pawn)) return;
var curLevel = sexNeed.CurLevel;
// Update psyfocus if the pawn is awake.
if (!RJWSettings.Disable_MeditationFocusDrain && pawn.Awake() && curLevel < sexNeed.thresh_frustrated())
SexUtility.OffsetPsyfocus(pawn, -0.01f);
//if (curLevel < sexNeed.thresh_horny())
// SexUtility.OffsetPsyfocus(pawn, -0.01f);
//if (curLevel < sexNeed.thresh_frustrated() || curLevel > sexNeed.thresh_ahegao())
// SexUtility.OffsetPsyfocus(pawn, -0.05f);
if (curLevel < sexNeed.thresh_horny() && (pawn.mindState.canLovinTick - Find.TickManager.TicksGame > 300))
pawn.mindState.canLovinTick = Find.TickManager.TicksGame + 300;
// This can probably all just go, since it's now a noop.
// But I don't know if some mod is patching `xxx.bootstrap` or something.
if (!BootStrapTriggered)
{
//--ModLog.Message("CompRJW::DoUpkeep::calling boostrap - pawn is " + xxx.get_pawnname(pawn));
xxx.bootstrap(pawn.Map);
BootStrapTriggered = true;
}
}
public override void PostExposeData()
{
base.PostExposeData();
if (Pawn == null) return;
// Saves the data.
Scribe_Values.Look(ref orientation, "RJW_Orientation");
Scribe_Values.Look(ref quirksave, "RJW_Quirks", "");
Scribe_Values.Look(ref NextHookupTick, "RJW_NextHookupTick");
//Log.Message("PostExposeData for " + pawn?.Name);
// Restore quirk data from the truncated save version.
quirks = new StringBuilder(quirksave);
}
public static CompRJW Comp(Pawn pawn)
{
// Call CompRJW.Comp(pawn).<method> to check sexuality, etc.
return pawn.GetComp<CompRJW>();
}
public static void CopyPsychologySexuality(Pawn pawn)
{
try
{
int kinsey = pawn.TryGetComp<CompPsychology>().Sexuality.kinseyRating;
//Orientation originalOrientation = Comp(pawn).orientation;
if (!Genital_Helper.has_genitals(pawn) && (pawn.kindDef.race.defName.ToLower().Contains("droid") || pawn.kindDef.race.defName.ToLower().Contains("drone")))
Comp(pawn).orientation = Orientation.Asexual;
else if (kinsey == 0)
Comp(pawn).orientation = Orientation.Heterosexual;
else if (kinsey == 1)
Comp(pawn).orientation = Orientation.MostlyHeterosexual;
else if (kinsey == 2)
Comp(pawn).orientation = Orientation.LeaningHeterosexual;
else if (kinsey == 3)
Comp(pawn).orientation = Orientation.Bisexual;
else if (kinsey == 4)
Comp(pawn).orientation = Orientation.LeaningHomosexual;
else if (kinsey == 5)
Comp(pawn).orientation = Orientation.MostlyHomosexual;
else if (kinsey == 6)
Comp(pawn).orientation = Orientation.Homosexual;
else
Comp(pawn).orientation = Orientation.Asexual;
/*else
Log.Error("RJW::ERRROR - unknown kinsey scale value: " + kinsey);/*
/*if (Comp(pawn).orientation != originalOrientation)
Log.Message("RJW + Psychology: Inherited pawn " + xxx.get_pawnname(pawn) + " sexuality from Psychology - " + Comp(pawn).orientation);*/
}
catch
{
if (!pawn.IsAnimal())
ModLog.Warning("CopyPsychologySexuality " + pawn?.Name + ", def: " + pawn?.def?.defName + ", kindDef: " + pawn?.kindDef?.race.defName);
}
}
public static void CopyIndividualitySexuality(Pawn pawn)
{
try
{
CompIndividuality.Sexuality individualitySexuality = pawn.TryGetComp<CompIndividuality>().sexuality;
//Orientation originalOrientation = Comp(pawn).orientation;
if (individualitySexuality == CompIndividuality.Sexuality.Asexual)
Comp(pawn).orientation = Orientation.Asexual;
else if (!Genital_Helper.has_genitals(pawn) && (pawn.kindDef.race.defName.ToLower().Contains("droid") || pawn.kindDef.race.defName.ToLower().Contains("drone")))
Comp(pawn).orientation = Orientation.Asexual;
else if (individualitySexuality == CompIndividuality.Sexuality.Straight)
Comp(pawn).orientation = Orientation.Heterosexual;
else if (individualitySexuality == CompIndividuality.Sexuality.Bisexual)
Comp(pawn).orientation = Orientation.Bisexual;
else if (individualitySexuality == CompIndividuality.Sexuality.Gay)
Comp(pawn).orientation = Orientation.Homosexual;
else
Comp(pawn).orientation = Orientation.Asexual;
/*if (Comp(pawn).orientation != originalOrientation)
Log.Message("RJW + [SYR]Individuality: Inherited pawn " + xxx.get_pawnname(pawn) + " sexuality from Individuality - " + Comp(pawn).orientation);*/
}
catch
{
if (!pawn.IsAnimal())
ModLog.Warning("CopyIndividualitySexuality " + pawn?.Name + ", def: " + pawn?.def?.defName + ", kindDef: " + pawn?.kindDef?.race.defName);
}
}
public static void VanillaTraitCheck(Pawn pawn)
{
//Orientation originalOrientation = Comp(pawn).orientation;
if (pawn.story.traits.HasTrait(TraitDefOf.Asexual))
Comp(pawn).orientation = Orientation.Asexual;
else if (!Genital_Helper.has_genitals(pawn) && (pawn.kindDef.race.defName.ToLower().Contains("droid") || pawn.kindDef.race.defName.ToLower().Contains("drone")))
Comp(pawn).orientation = Orientation.Asexual;
else if (pawn.story.traits.HasTrait(TraitDefOf.Gay))
Comp(pawn).orientation = Orientation.Homosexual;
else if (pawn.story.traits.HasTrait(TraitDefOf.Bisexual))
Comp(pawn).orientation = Orientation.Bisexual;
else
Comp(pawn).orientation = Orientation.Heterosexual;
}
// The main method for adding genitalia and orientation.
public void Sexualize(Pawn pawn, bool reroll = false)
{
if (reroll)
{
Comp(pawn).orientation = Orientation.None;
if (xxx.has_quirk(pawn, "Fertile"))
{
Hediff fertility = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("IncreasedFertility"));
if (fertility != null)
pawn.health.RemoveHediff(fertility);
}
if (xxx.has_quirk(pawn, "Infertile"))
{
Hediff fertility = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("DecreasedFertility"));
if (fertility != null)
pawn.health.RemoveHediff(fertility);
}
quirks = new StringBuilder();
}
else if (Comp(pawn).orientation != Orientation.None)
return;
//roll random RJW orientation
Comp(pawn).orientation = xxx.is_animal(pawn) ? RollAnimalOrientation(pawn) : RollOrientation(pawn);
//Asexual nymp re-roll
//if (xxx.is_nympho(pawn))
// while (Comp(pawn).orientation == Orientation.Asexual)
// {
// Comp(pawn).orientation = RollOrientation();
// }
//Log.Message("Sexualizing pawn " + pawn?.Name + ", def: " + pawn?.def?.defName);
if (!reroll)
Sexualizer.sexualize_pawn(pawn);
//Log.Message("Orientation for pawn " + pawn?.Name + " is " + orientation);
if (xxx.has_traits(pawn) && Genital_Helper.has_genitals(pawn) && !(pawn.kindDef.race.defName.ToLower().Contains("droid") && !AndroidsCompatibility.IsAndroid(pawn)))
{
if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Vanilla)
VanillaTraitCheck(pawn);
if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Psychology)
CopyPsychologySexuality(pawn);
if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.SYRIndividuality)
CopyIndividualitySexuality(pawn);
}
else if (((pawn.kindDef.race.defName.ToLower().Contains("droid")) && !AndroidsCompatibility.IsAndroid(pawn)) || !Genital_Helper.has_genitals(pawn))
{
// Droids with no genitalia are set as asexual.
// If player later adds genitalia to the droid, the droid 'sexuality' gets rerolled.
Comp(pawn).orientation = Orientation.Asexual;
}
QuirkAdder.Generate(pawn);
if (quirks.Length == 0)
{
quirks.Append("None");
quirksave = quirks.ToString();
}
}
/// <summary>
/// check try vanilla traits/mods, check rjw genitals, futa check, some rng rolls
/// </summary>
/// <param name="pawn"></param>
/// <param name="partner"></param>
/// <returns></returns>
public static bool CheckPreference(Pawn pawn, Pawn partner)
{
if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Vanilla)
{
if (xxx.has_traits(pawn))
VanillaTraitCheck(pawn);
if (xxx.has_traits(partner))
VanillaTraitCheck(partner);
}
if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.SYRIndividuality)
{
CopyIndividualitySexuality(pawn);
CopyIndividualitySexuality(partner);
}
if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Psychology)
{
if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Psychology)
CopyPsychologySexuality(pawn);
CopyPsychologySexuality(partner);
}
//if (xxx.is_mechanoid(pawn))
// return false;
if (Comp(pawn) is CompRJW rjwComp)
{
var ori = rjwComp.orientation;
if (ori == Orientation.Pansexual || ori == Orientation.Bisexual)
return true;
if (ori == Orientation.Asexual)
return false;
var pawnSex = GenderHelper.GetSex(pawn);
var partnerSex = GenderHelper.GetSex(partner);
var isHetero = GenderHelper.CanBeHetero(pawnSex, partnerSex);
var isHomo = GenderHelper.CanBeHomo(pawnSex, partnerSex);
// Oh you crazy futas. fuck all cuz horny!
if (isHetero && isHomo)
return true;
//RMB ui lag fixes in mp intead of [SyncMethod]
if (MP.IsInMultiplayer)
return RollOriMP(ori, isHetero, isHomo);
else
return RollOriSP(ori, isHetero, isHomo);
}
else
{
//ModLog.Message("Error, pawn:" + pawn + " doesn't have orientation comp, modded race?");
return false;
}
}
//no rng no lag
public static bool RollOriMP(Orientation ori, bool isHetero, bool isHomo)
{
switch (ori)
{
case Orientation.Heterosexual:
return !isHomo;
case Orientation.MostlyHeterosexual:
return (!isHomo);
case Orientation.LeaningHeterosexual:
return (!isHomo);
case Orientation.LeaningHomosexual:
return (!isHetero);
case Orientation.MostlyHomosexual:
return (!isHetero);
case Orientation.Homosexual:
return !isHetero;
default:
ModLog.Error("ERROR - tried to check preference for undetermined sexuality.");
return false;
}
}
//slight rng, but heavy ddos lag in MP with [SyncMethod]
public static bool RollOriSP(Orientation ori, bool isHetero, bool isHomo)
{
switch (ori)
{
case Orientation.Heterosexual:
return !isHomo;
case Orientation.MostlyHeterosexual:
return (!isHomo || Rand.Chance(0.2f));
case Orientation.LeaningHeterosexual:
return (!isHomo || Rand.Chance(0.6f));
case Orientation.LeaningHomosexual:
return (!isHetero || Rand.Chance(0.6f));
case Orientation.MostlyHomosexual:
return (!isHetero || Rand.Chance(0.2f));
case Orientation.Homosexual:
return !isHetero;
default:
ModLog.Error("ERROR - tried to check preference for undetermined sexuality.");
return false;
}
}
[SyncMethod]
public Orientation RollOrientation(Pawn pawn)
{
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
float random = Rand.Range(0f, 1f);
float checkpoint = RJWPreferenceSettings.asexual_ratio / RJWPreferenceSettings.GetTotal();
float checkpoint_pan = checkpoint + (RJWPreferenceSettings.pansexual_ratio / RJWPreferenceSettings.GetTotal());
float checkpoint_het = checkpoint_pan + (RJWPreferenceSettings.heterosexual_ratio / RJWPreferenceSettings.GetTotal());
float checkpoint_bi = checkpoint_het + (RJWPreferenceSettings.bisexual_ratio / RJWPreferenceSettings.GetTotal());
float checkpoint_gay = checkpoint_bi + (RJWPreferenceSettings.homosexual_ratio / RJWPreferenceSettings.GetTotal());
if (random < checkpoint || !Genital_Helper.has_genitals(pawn))
return Orientation.Asexual;
else if (random < checkpoint_pan)
return Orientation.Pansexual;
else if (random < checkpoint_het)
return Orientation.Heterosexual;
else if (random < checkpoint_het + ((checkpoint_bi - checkpoint_het) * 0.33f))
return Orientation.MostlyHeterosexual;
else if (random < checkpoint_het + ((checkpoint_bi - checkpoint_het) * 0.66f))
return Orientation.LeaningHeterosexual;
else if (random < checkpoint_bi)
return Orientation.Bisexual;
else if (random < checkpoint_bi + ((checkpoint_gay - checkpoint_bi) * 0.33f))
return Orientation.LeaningHomosexual;
else if (random < checkpoint_bi + ((checkpoint_gay - checkpoint_bi) * 0.66f))
return Orientation.MostlyHomosexual;
else
return Orientation.Homosexual;
}
// Simpler system for animals, with most of them being heterosexual.
// Don't want to disturb player breeding projects by adding too many gay animals.
[SyncMethod]
public Orientation RollAnimalOrientation(Pawn pawn)
{
//Rand.PopState();
//Rand.PushState(RJW_Multiplayer.PredictableSeed());
float random = Rand.Range(0f, 1f);
if (random < 0.03f || !Genital_Helper.has_genitals(pawn))
return Orientation.Asexual;
else if (random < 0.85f)
return Orientation.Heterosexual;
else if (random < 0.96f)
return Orientation.Bisexual;
else
return Orientation.Homosexual;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Comps/CompRJW.cs
|
C#
|
mit
| 15,783
|
using RimWorld;
namespace rjw
{
public class CompRJWHatcher : CompHatcher
{
}
}
|
jojo1541/rjw
|
1.4/Source/Comps/CompRJWHatcher.cs
|
C#
|
mit
| 86
|
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;
}
}
}
}
|
jojo1541/rjw
|
1.4/Source/Comps/CompRJWHediffBodyPart.cs
|
C#
|
mit
| 15,262
|
using RimWorld;
namespace rjw
{
public class CompRJWProperties_Hatcher : CompProperties_Hatcher
{
public CompRJWProperties_Hatcher()
{
this.compClass = typeof(CompRJWHatcher);
}
}
}
|
jojo1541/rjw
|
1.4/Source/Comps/CompRJWProperties_Hatcher.cs
|
C#
|
mit
| 198
|
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;
}
}
}
}
|
jojo1541/rjw
|
1.4/Source/Comps/CompRJWThingBodyPart.cs
|
C#
|
mit
| 5,337
|
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
}
}
|
jojo1541/rjw
|
1.4/Source/Comps/Orientation.cs
|
C#
|
mit
| 298
|
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);
}
}
}
|
jojo1541/rjw
|
1.4/Source/Comps/Quirk.cs
|
C#
|
mit
| 7,661
|
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);
}
}
}
}
|
jojo1541/rjw
|
1.4/Source/Comps/QuirkAdder.cs
|
C#
|
mit
| 5,992
|
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;// brainfuck with who fucks who, see impregnation for clarity with tags n shit?. interaction.HasInteractionTag(InteractionTag.Reverse)
public bool isRapist = false;
public bool isCoreLovin = false;//vanilla loving, skip some mechanics. 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 pawn
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");
}
}
}
|
jojo1541/rjw
|
1.4/Source/Comps/SexProps.cs
|
C#
|
mit
| 2,382
|
using RimWorld;
namespace rjw
{
[DefOf]
public static class IssueDefOf
{
public static IssueDef Lovin;
static IssueDefOf()
{
DefOfHelper.EnsureInitializedInCtor(typeof(IssueDefOf));
}
}
}
|
jojo1541/rjw
|
1.4/Source/DefOf/IssueDefOf.cs
|
C#
|
mit
| 244
|
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;
}
}
|
jojo1541/rjw
|
1.4/Source/DefOf/JobDefOf.cs
|
C#
|
mit
| 354
|
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;
}
}
}
|
jojo1541/rjw
|
1.4/Source/DefOf/JobDriver_AdjustParts.cs
|
C#
|
mit
| 2,204
|
using RimWorld;
namespace rjw
{
[DefOf]
public static class PreceptDefOf
{
[MayRequireIdeology]
public static PreceptDef Lovin_Prohibited;
[MayRequireIdeology]
public static PreceptDef Lovin_Horrible;
[MayRequireIdeology]
public static PreceptDef Lovin_SpouseOnly_Strict;
[MayRequireIdeology]
public static PreceptDef Lovin_SpouseOnly_Moderate;
[MayRequireIdeology]
public static PreceptDef Lovin_SpouseOnly_Mild;
public static PreceptDef Lovin_Free;
[MayRequireIdeology]
public static PreceptDef Lovin_FreeApproved;
static PreceptDefOf()
{
DefOfHelper.EnsureInitializedInCtor(typeof(IssueDefOf));
}
}
}
|
jojo1541/rjw
|
1.4/Source/DefOf/PreceptDefOf.cs
|
C#
|
mit
| 690
|
using Verse;
using RimWorld;
namespace rjw
{
[DefOf]
public static class RJWHediffDefOf
{
public static HediffDef HumpShroomAddiction;
public static HediffDef HumpShroomEffect;
}
}
|
jojo1541/rjw
|
1.4/Source/DefOf/RJWHediffDefOf.cs
|
C#
|
mit
| 214
|
using RimWorld;
using Verse;
namespace rjw
{
[DefOf]
public static class RJW_RecipeDefOf
{
public static RecipeDef AttachPenis;
public static RecipeDef InstallPenis;
public static RecipeDef RemovePenis;
}
}
|
jojo1541/rjw
|
1.4/Source/DefOf/RJW_RecipeDefOf.cs
|
C#
|
mit
| 221
|
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;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Designators/Breedee.cs
|
C#
|
mit
| 2,970
|
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;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Designators/Breeder.cs
|
C#
|
mit
| 2,281
|
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;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Designators/Comfort.cs
|
C#
|
mit
| 2,597
|
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;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Designators/Hero.cs
|
C#
|
mit
| 2,861
|
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;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Designators/Milking.cs
|
C#
|
mit
| 1,258
|
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;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Designators/Service.cs
|
C#
|
mit
| 2,249
|
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;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Designators/Utility.cs
|
C#
|
mit
| 3,125
|
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) { }
}
}
}
|
jojo1541/rjw
|
1.4/Source/Designators/_RJWdesignationsWidget.cs
|
C#
|
mit
| 12,842
|
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;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Harmony/BiotechPatches.cs
|
C#
|
mit
| 7,193
|
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);
}
}
}
}
}
|
jojo1541/rjw
|
1.4/Source/Harmony/Building_Bed_Patch.cs
|
C#
|
mit
| 10,116
|
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;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Harmony/CnPcompatibility.cs
|
C#
|
mit
| 4,612
|
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;
}
}
}
|
jojo1541/rjw
|
1.4/Source/Harmony/CodeExtensions.cs
|
C#
|
mit
| 4,861
|
using HarmonyLib;
using RimWorld;
using System;
using Verse;
namespace rjw
{
///<summary>
///unset designators on GuestRelease
///until pawn leaves map, pawn is still guest/slave/prisoner, so they can actually be changed back
///</summary>
[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());
}
}
}
///<summary>
///unset designators on Pawn_ExitMap
///now pawn actually leaves map and get their factions reset
///</summary>
[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());
}
}
}
}
|
jojo1541/rjw
|
1.4/Source/Harmony/DesignatorsUnset.cs
|
C#
|
mit
| 1,618
|
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using HarmonyLib;
using RimWorld;
using Verse;
namespace rjw
{
[StaticConstructorOnStartup]
internal static class First
{
/*private static void show_bpr(String body_part_record_def_name)
{
var bpr = BodyDefOf.Human.AllParts.Find((BodyPartRecord can) => String.Equals(can.def.defName, body_part_record_def_name));
--Log.Message(body_part_record_def_name + " BPR internals:");
--Log.Message(" def: " + bpr.def.ToString());
--Log.Message(" parts: " + bpr.parts.ToString());
--Log.Message(" parts.count: " + bpr.parts.Count.ToString());
--Log.Message(" height: " + bpr.height.ToString());
--Log.Message(" depth: " + bpr.depth.ToString());
--Log.Message(" coverage: " + bpr.coverage.ToString());
--Log.Message(" groups: " + bpr.groups.ToString());
--Log.Message(" groups.count: " + bpr.groups.Count.ToString());
--Log.Message(" parent: " + bpr.parent.ToString());
--Log.Message (" fleshCoverage: " + bpr.fleshCoverage.ToString ());
--Log.Message (" absoluteCoverage: " + bpr.absoluteCoverage.ToString ());
--Log.Message (" absoluteFleshCoverage: " + bpr.absoluteFleshCoverage.ToString ());
}*/
//Children mod use same defname. but not has worker class. so overriding here.
public static void inject_Reproduction()
{
PawnCapacityDef reproduction = DefDatabase<PawnCapacityDef>.GetNamed("RJW_Fertility");
reproduction.workerClass = typeof(PawnCapacityWorker_Fertility);
}
public static void inject_whoringtab()
{
//InjectTab(typeof(MainTab.MainTabWindow_Brothel), def => def.race?.Humanlike == true);
}
private static void InjectTab(Type tabType, Func<ThingDef, bool> qualifier)
{
var defs = DefDatabase<ThingDef>.AllDefs.Where(qualifier).ToList();
defs.RemoveDuplicates();
var tabBase = InspectTabManager.GetSharedInstance(tabType);
foreach (var def in defs)
{
if (def.inspectorTabs == null || def.inspectorTabsResolved == null) continue;
if (!def.inspectorTabs.Contains(tabType))
{
def.inspectorTabs.Add(tabType);
def.inspectorTabsResolved.Add(tabBase);
//Log.Message(def.defName+": "+def.inspectorTabsResolved.Select(d=>d.GetType().Name).Aggregate((a,b)=>a+", "+b));
}
}
}
private static void inject_recipes()
{
//--ModLog.Message(" First::inject_recipes");
// Inject the recipes to create the artificial privates into the crafting spot or machining bench.
// BUT, also dynamically detect if EPOE is loaded and, if it is, inject the recipes into EPOE's
// crafting benches instead.
try
{
//Vanilla benches
var cra_spo = DefDatabase<ThingDef>.GetNamed("CraftingSpot");
var mac_ben = DefDatabase<ThingDef>.GetNamed("TableMachining");
var fab_ben = DefDatabase<ThingDef>.GetNamed("FabricationBench");
var tai_ben = DefDatabase<ThingDef>.GetNamed("ElectricTailoringBench");
// Inject the bondage gear recipes into their appropriate benches
//if (xxx.config.bondage_gear_enabled)
//{
//fab_ben.AllRecipes.Add(DefDatabase<RecipeDef>.GetNamed("MakeHololock"));
//tai_ben.AllRecipes.Add(DefDatabase<RecipeDef>.GetNamed("MakeArmbinder"));
//tai_ben.AllRecipes.Add(DefDatabase<RecipeDef>.GetNamed("MakeChastityBelt"));
//tai_ben.AllRecipes.Add(DefDatabase<RecipeDef>.GetNamed("MakeChastityBeltO"));
//tai_ben.AllRecipes.Add(DefDatabase<RecipeDef>.GetNamed("MakeChastityCage"));
//tai_ben.AllRecipes.Add(DefDatabase<RecipeDef>.GetNamed("MakeBallGag"));
//tai_ben.AllRecipes.Add(DefDatabase<RecipeDef>.GetNamed("MakeRingGag"));
//}
}
catch
{
ModLog.Warning("Unable to inject recipes.");
ModLog.Warning("Yay! Your medieval mod broke recipes. And, likely, parts too, expect errors.");
}
}
/*private static void show_bs(Backstory bs)
{
--Log.Message("Backstory \"" + bs.Title + "\" internals:");
--Log.Message(" identifier: " + bs.identifier);
--Log.Message(" slot: " + bs.slot.ToString());
--Log.Message(" Title: " + bs.Title);
--Log.Message(" TitleShort: " + bs.TitleShort);
--Log.Message(" baseDesc: " + bs.baseDesc);
--Log.Message(" skillGains: " + ((bs.skillGains == null) ? "null" : bs.skillGains.ToString()));
--Log.Message(" skillGainsResolved: " + ((bs.skillGainsResolved == null) ? "null" : bs.skillGainsResolved.ToString()));
--Log.Message(" workDisables: " + bs.workDisables.ToString());
--Log.Message(" requiredWorkTags: " + bs.requiredWorkTags.ToString());
--Log.Message(" spawnCategories: " + bs.spawnCategories.ToString());
--Log.Message(" bodyTypeGlobal: " + bs.bodyTypeGlobal.ToString());
--Log.Message(" bodyTypeFemale: " + bs.bodyTypeFemale.ToString());
--Log.Message(" bodyTypeMale: " + bs.bodyTypeMale.ToString());
--Log.Message(" forcedTraits: " + ((bs.forcedTraits == null) ? "null" : bs.forcedTraits.ToString()));
--Log.Message(" disallowedTraits: " + ((bs.disallowedTraits == null) ? "null" : bs.disallowedTraits.ToString()));
--Log.Message(" shuffleable: " + bs.shuffleable.ToString());
}*/
//Quick check to see if an another mod is loaded.
private static bool IsLoaded(string mod)
{
return LoadedModManager.RunningModsListForReading.Any(x => x.Name == mod);
}
private static void CheckingCompatibleMods()
{
{//Humanoid Alien Races Framework 2.0
xxx.xenophobia = DefDatabase<TraitDef>.GetNamedSilentFail("Xenophobia");
if (xxx.xenophobia is null)
{
xxx.AlienFrameworkIsActive = false;
}
else
{
xxx.AlienFrameworkIsActive = true;
if (RJWSettings.DevMode) ModLog.Message("Humanoid Alien Races 2.0 is detected. Xenophile and Xenophobe traits active.");
}
}
{//relations-orientation mods
{//RomanceDiversified
xxx.straight = DefDatabase<TraitDef>.GetNamedSilentFail("Straight");
xxx.faithful = DefDatabase<TraitDef>.GetNamedSilentFail("Faithful");
xxx.philanderer = DefDatabase<TraitDef>.GetNamedSilentFail("Philanderer");
xxx.polyamorous = DefDatabase<TraitDef>.GetNamedSilentFail("Polyamorous");
if (xxx.straight is null || xxx.faithful is null || xxx.philanderer is null)
{
xxx.RomanceDiversifiedIsActive = false;
}
else
{
xxx.RomanceDiversifiedIsActive = true;
if (RJWSettings.DevMode) ModLog.Message("RomanceDiversified is detected.");
}
// any mod that features a polyamorous trait
if(xxx.polyamorous is null)
{
xxx.AnyPolyamoryModIsActive = false;
}
else
{
xxx.AnyPolyamoryModIsActive = true;
}
}
{//[SYR] Individuality
xxx.SYR_CreativeThinker = DefDatabase<TraitDef>.GetNamedSilentFail("SYR_CreativeThinker");
xxx.SYR_Haggler = DefDatabase<TraitDef>.GetNamedSilentFail("SYR_Haggler");
if (xxx.SYR_CreativeThinker is null || xxx.SYR_Haggler is null)
{
xxx.IndividualityIsActive = false;
if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.SYRIndividuality)
RJWPreferenceSettings.sexuality_distribution = RJWPreferenceSettings.Rjw_sexuality.Vanilla;
}
else
{
xxx.IndividualityIsActive = true;
if (RJWSettings.DevMode) ModLog.Message("Individuality is detected.");
}
}
{//Psychology
xxx.prude = DefDatabase<TraitDef>.GetNamedSilentFail("Prude");
xxx.lecher = DefDatabase<TraitDef>.GetNamedSilentFail("Lecher");
xxx.polygamous = DefDatabase<TraitDef>.GetNamedSilentFail("Polygamous");
if (xxx.prude is null || xxx.lecher is null || xxx.polygamous is null)
{
xxx.PsychologyIsActive = false;
if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Psychology)
RJWPreferenceSettings.sexuality_distribution = RJWPreferenceSettings.Rjw_sexuality.Vanilla;
}
else
{
xxx.PsychologyIsActive = true;
if (RJWSettings.DevMode) ModLog.Message("Psychology is detected. (Note: only partially supported)");
}
// any mod that features a polygamous trait
if (xxx.polygamous is null)
{
xxx.AnyPolygamyModIsActive = false;
}
else
{
xxx.AnyPolygamyModIsActive = true;
}
}
if (xxx.PsychologyIsActive == false && xxx.IndividualityIsActive == false)
{
if (RJWPreferenceSettings.sexuality_distribution != RJWPreferenceSettings.Rjw_sexuality.Vanilla)
{
RJWPreferenceSettings.sexuality_distribution = RJWPreferenceSettings.Rjw_sexuality.Vanilla;
}
}
}
{//SimpleSlavery
xxx.Enslaved = DefDatabase<HediffDef>.GetNamedSilentFail("Enslaved");
if (xxx.Enslaved is null)
{
xxx.SimpleSlaveryIsActive = false;
}
else
{
xxx.SimpleSlaveryIsActive = true;
if (RJWSettings.DevMode) ModLog.Message("SimpleSlavery is detected.");
}
}
{//[KV] Consolidated Traits
xxx.RCT_NeatFreak = DefDatabase<TraitDef>.GetNamedSilentFail("RCT_NeatFreak");
xxx.RCT_Savant = DefDatabase<TraitDef>.GetNamedSilentFail("RCT_Savant");
xxx.RCT_Inventor = DefDatabase<TraitDef>.GetNamedSilentFail("RCT_Inventor");
xxx.RCT_AnimalLover = DefDatabase<TraitDef>.GetNamedSilentFail("RCT_AnimalLover");
if (xxx.RCT_NeatFreak is null || xxx.RCT_Savant is null || xxx.RCT_Inventor is null || xxx.RCT_AnimalLover is null)
{
xxx.CTIsActive = false;
}
else
{
xxx.CTIsActive = true;
if (RJWSettings.DevMode) ModLog.Message("Consolidated Traits found, adding trait compatibility.");
}
}
{//Rimworld of Magic
xxx.Succubus = DefDatabase<TraitDef>.GetNamedSilentFail("Succubus");
xxx.Warlock = DefDatabase<TraitDef>.GetNamedSilentFail("Warlock");
xxx.TM_Mana = DefDatabase<NeedDef>.GetNamedSilentFail("TM_Mana");
xxx.TM_ShapeshiftHD = DefDatabase<HediffDef>.GetNamedSilentFail("TM_ShapeshiftHD");
if (xxx.Succubus is null || xxx.Warlock is null || xxx.TM_Mana is null || xxx.TM_ShapeshiftHD is null)
{
xxx.RoMIsActive = false;
}
else
{
xxx.RoMIsActive = true;
if (RJWSettings.DevMode) ModLog.Message("Rimworld of Magic is detected.");
}
}
{//Nightmare Incarnation
xxx.NI_Need_Mana = DefDatabase<NeedDef>.GetNamedSilentFail("NI_Need_Mana");
if (xxx.NI_Need_Mana is null)
{
xxx.NightmareIncarnationIsActive = false;
}
else
{
xxx.NightmareIncarnationIsActive = true;
if (RJWSettings.DevMode) ModLog.Message("Nightmare Incarnation is detected.");
}
}
{//DubsBadHygiene
xxx.DBHThirst = DefDatabase<NeedDef>.GetNamedSilentFail("DBHThirst");
if (xxx.DBHThirst is null)
{
xxx.DubsBadHygieneIsActive = false;
}
else
{
xxx.DubsBadHygieneIsActive = true;
if (RJWSettings.DevMode) ModLog.Message("Dubs Bad Hygiene is detected.");
}
}
{//Immortals
xxx.IH_Immortal = DefDatabase<HediffDef>.GetNamedSilentFail("IH_Immortal");
if (xxx.IH_Immortal is null)
{
xxx.ImmortalsIsActive = false;
}
else
{
xxx.ImmortalsIsActive = true;
if (RJWSettings.DevMode) ModLog.Message("Immortals is detected.");
}
}
{//Children and Pregnancy
xxx.BabyState = DefDatabase<HediffDef>.GetNamedSilentFail("BabyState");
xxx.PostPregnancy = DefDatabase<HediffDef>.GetNamedSilentFail("PostPregnancy");
xxx.Lactating = DefDatabase<HediffDef>.GetNamedSilentFail("Lactating");
xxx.NoManipulationFlag = DefDatabase<HediffDef>.GetNamedSilentFail("NoManipulationFlag");
xxx.IGaveBirthFirstTime = DefDatabase<ThoughtDef>.GetNamedSilentFail("IGaveBirthFirstTime");
xxx.IGaveBirth = DefDatabase<ThoughtDef>.GetNamedSilentFail("IGaveBirth");
xxx.PartnerGaveBirth = DefDatabase<ThoughtDef>.GetNamedSilentFail("PartnerGaveBirth");
if (xxx.BabyState is null || xxx.PostPregnancy is null || xxx.Lactating is null || xxx.NoManipulationFlag is null || xxx.IGaveBirthFirstTime is null || xxx.IGaveBirth is null || xxx.PartnerGaveBirth is null)
{
xxx.RimWorldChildrenIsActive = false;
}
else
{
xxx.RimWorldChildrenIsActive = true;
if (RJWSettings.DevMode) ModLog.Message("Children&Pregnancy is detected.");
}
}
{//Babies and Children
xxx.BnC_RJW_PostPregnancy = DefDatabase<HediffDef>.GetNamedSilentFail("BnC_RJW_PostPregnancy");
}
{// RJW-EX
xxx.RjwEx_Armbinder = DefDatabase<HediffDef>.GetNamedSilentFail("Armbinder");
if (xxx.RjwEx_Armbinder is null) { xxx.RjwExIsActive = false;}
else { xxx.RjwExIsActive = true; }
}
{//Combat Extended
xxx.MuscleSpasms = DefDatabase<HediffDef>.GetNamedSilentFail("MuscleSpasms");
if (xxx.MuscleSpasms is null)
{
xxx.CombatExtendedIsActive = false;
}
else
{
xxx.CombatExtendedIsActive = true;
if (RJWSettings.DevMode) ModLog.Message("Combat Extended is detected. Current compatibility unknown, use at your own risk. ");
}
}
}
static First()
{
//--ModLog.Message(" First::First() called");
// check for required mods
//CheckModRequirements();
CheckIncompatibleMods();
CheckingCompatibleMods();
inject_Reproduction();
//inject_recipes(); // No Longer needed. Benches defined in recipe defs
//bondage_gear_tradeability.init();
var har = new Harmony("rjw");
har.PatchAll(Assembly.GetExecutingAssembly());
PATCH_Pawn_ApparelTracker_TryDrop.apply(har);
//CnPcompatibility.Patch(har); //CnP IS NO OUT YET
}
internal static void CheckModRequirements()
{
//--Log.Message("First::CheckModRequirements() called");
List<string> required_mods = new List<string> {
"HugsLib",
};
foreach (string required_mod in required_mods)
{
bool found = false;
foreach (ModMetaData installed_mod in ModLister.AllInstalledMods)
{
if (installed_mod.Active && installed_mod.Name.Contains(required_mod))
{
found = true;
}
if (!found)
{
ErrorMissingRequirement(required_mod);
}
}
}
}
internal static void CheckIncompatibleMods()
{
//--Log.Message("First::CheckIncompatibleMods() called");
List<string> incompatible_mods = new List<string> {
"Bogus Test Mod That Doesn't Exist",
"Lost Forest"
};
foreach (string incompatible_mod in incompatible_mods)
{
foreach (ModMetaData installed_mod in ModLister.AllInstalledMods)
{
if (installed_mod.Active && installed_mod.Name.Contains(incompatible_mod))
{
ErrorIncompatibleMod(installed_mod);
}
}
}
}
internal static void ErrorMissingRequirement(string missing)
{
ModLog.Error("Initialization error: Unable to find required mod '" + missing + "' in mod list");
}
internal static void ErrorIncompatibleMod(ModMetaData othermod)
{
ModLog.Error("Initialization Error: Incompatible mod '" + othermod.Name + "' detected in mod list");
}
}
}
|
jojo1541/rjw
|
1.4/Source/Harmony/First.cs
|
C#
|
mit
| 14,910
|