-
-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathItemUtility.cs
More file actions
331 lines (281 loc) · 11.5 KB
/
ItemUtility.cs
File metadata and controls
331 lines (281 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using HarmonyLib;
using JetBrains.Annotations;
using RimWorld;
using UnityEngine;
using Verse;
using Verse.AI;
using Verse.AI.Group;
using Verse.Sound;
namespace Hospitality.Utilities;
[StaticConstructorOnStartup]
public static class ItemUtility
{
private static readonly Dictionary<string, MethodInfo> alienFrameworkMethods = new();
public static float priceFactor = 0.55f;
public static bool isCELoaded = false;
static ItemUtility()
{
isCELoaded = ModsConfig.ActiveModsInLoadOrder.Any(m => m.PackageId == "CETeam.CombatExtended");
}
public static void PocketHeadgear(this Pawn pawn)
{
if (pawn?.apparel?.WornApparel == null || pawn.inventory?.innerContainer == null) return;
if (ModsConfig.IdeologyActive)
{
// Don't do it when ideology requires covered hair or face.
if (pawn.gender == Gender.Male
&& (pawn.ideo?.Ideo?.HasPrecept(InternalDefOf.Nudity_Male_UncoveredGroinChestOrHairDisapproved) == true
|| pawn.ideo?.Ideo?.HasPrecept(InternalDefOf.Nudity_Male_UncoveredGroinChestHairOrFaceDisapproved) == true))
return;
if (pawn.gender == Gender.Female
&& (pawn.ideo?.Ideo?.HasPrecept(InternalDefOf.Nudity_Female_UncoveredGroinChestOrHairDisapproved) == true
|| pawn.ideo?.Ideo?.HasPrecept(InternalDefOf.Nudity_Female_UncoveredGroinChestHairOrFaceDisapproved) == true))
return;
if (pawn.ideo?.Ideo?.HasPrecept(InternalDefOf.VME_Anonymity_Required) == true) return;
}
var headgear = pawn.apparel.WornApparel.Where(CoversHead).ToArray();
foreach (var apparel in headgear)
{
if (apparel == null) continue;
// Don't drop headgear that is required by title
if (IsRequiredByRoyalty(pawn, apparel.def)) continue;
if (pawn.GetInventorySpaceFor(apparel) < 1) continue;
if (pawn.apparel.TryDrop(apparel, out var droppedApp))
{
var item = droppedApp?.SplitOff(1);
if (item != null)
{
pawn.inventory.TryAddItemNotForSale(item);
var success = pawn.inventory.innerContainer.Contains(item);
if (!success) pawn.apparel.Wear(droppedApp);
}
}
}
}
public static bool IsRequiredByRoyalty(Pawn pawn, ThingDef apparelDef)
{
if (pawn.royalty == null) return false;
try
{
return pawn.royalty.AllTitlesForReading.Any(title => title.def.requiredApparel != null && title.def.requiredApparel.Exists(req => req.ApparelMeetsRequirement(apparelDef)));
}
catch (Exception e)
{
Log.Error($"Failed to read royalty titles or their required apparel. This means you are using a mod that changes these and broke them.\n{e}");
return false;
}
}
public static bool CoversHead(this Apparel a)
{
return a.def.apparel.bodyPartGroups.Any(g => g == BodyPartGroupDefOf.UpperHead || g == BodyPartGroupDefOf.FullHead);
}
public static void WearHeadgear(this Pawn pawn)
{
if (pawn?.apparel?.WornApparel == null || pawn.inventory?.innerContainer == null) return;
var container = pawn.inventory.innerContainer;
var headgear = container.OfType<Apparel>().Where(CoversHead).InRandomOrder().ToArray();
foreach (var apparel in headgear)
{
if (pawn.apparel.CanWearWithoutDroppingAnything(apparel.def))
{
container.Remove(apparel);
pawn.apparel.Wear(apparel);
}
}
}
public static void TryGiveBackpack(this Pawn p)
{
var def = InternalDefOf.CE_Apparel_Backpack;
if (def == null) return;
var item = p.inventory.innerContainer.OfType<Apparel>().FirstOrDefault(i => i.def == def);
if (item == null)
{
var stuff = GenStuff.RandomStuffFor(def);
item = (Apparel)ThingMaker.MakeThing(def, stuff);
item.stackCount = 1;
}
if (!p.apparel.Wearing(item))
{
p.apparel.Wear(item, false);
}
}
public static int GetMoney(this Pawn pawn)
{
var money = pawn.inventory.innerContainer.FirstOrDefault(i => i.def == ThingDefOf.Silver);
return money?.stackCount ?? 0;
}
public static bool IsIngestible(this Thing thing)
{
return thing.def.IsIngestible && thing.def.ingestible.preferability != FoodPreferability.RawBad && thing.def.ingestible.preferability != FoodPreferability.MealAwful;
}
public static bool IsFood(this Thing thing)
{
return thing.def.ingestible != null && thing.def.ingestible.preferability != FoodPreferability.NeverForNutrition && thing.def.ingestible.preferability != FoodPreferability.DesperateOnlyForHumanlikes
&& thing.def.ingestible.preferability != FoodPreferability.DesperateOnly;
}
/// <summary>
/// methodName = "CanWear", "CanEat" or "CanEquip"
/// </summary>
public static bool AlienFrameworkAllowsIt(ThingDef raceDef, ThingDef thingDef, [NotNull] string methodName)
{
if (!alienFrameworkMethods.TryGetValue(methodName, out var method))
{
var type = GenTypes.GetTypeInAnyAssembly("AlienRace.RaceRestrictionSettings");
if (type != null)
{
method = type.GetMethod(methodName, [typeof(ThingDef), typeof(ThingDef)]);
if (method == null) Log.Error($"Alien Framework does not have a method '{methodName}'.");
}
alienFrameworkMethods.Add(methodName, method); // we add it as null if not found, so it will return true
}
return method == null || (bool)method.Invoke(null, [thingDef, raceDef]);
}
public static bool IsBuyableAtAll(Pawn pawn, int pawnMoney, Thing thing)
{
if (thing.def.isUnfinishedThing) return false;
if (thing.def == ThingDefOf.Silver) return false;
if (!pawn.MayPurchaseThing(thing)) return false;
if (thing.def.thingSetMakerTags != null && thing.def.thingSetMakerTags.Contains("NotForGuests")) return false;
if (!IsBuyableNow(pawn, thing)) return false;
//if (!thing.IsSociallyProper(pawn))
//{
// Log.Message(thing.Label + ": is not proper for " + pawn.NameStringShort);
// return false;
//}
var cost = Mathf.CeilToInt(GetPurchasingCost(thing));
if (cost > pawnMoney)
{
return false;
}
if (BoughtByPlayer(pawn, thing))
{
return false;
}
//if (thing.IsInValidStorage()) Log.Message(thing.Label + " in storage ");
return true;
}
public static float GetPurchasingCost([NotNull] this Thing thing)
{
if (IsFood(thing) && thing.GetMapComponent().guestsCanTakeFoodForFree) return 0;
return thing.MarketValue * priceFactor;
}
private static bool BoughtByPlayer(Pawn pawn, Thing thing)
{
var lord = pawn.GetLord();
return lord?.CurLordToil is not LordToil_VisitPoint toil || toil.BoughtOrSoldByPlayer(thing);
}
public static bool IsBuyableNow(Pawn pawn, Thing thing)
{
if (!thing.SpawnedOrAnyParentSpawned)
{
return false;
}
if (thing.ParentHolder is Pawn)
{
//Log.Message(thing.Label+": is inside pawn "+pawn.NameStringShort);
return false;
}
if (thing.IsForbidden(Faction.OfPlayer))
{
//Log.Message(thing.Label+": is forbidden for "+pawn.NameStringShort);
return false;
}
if (!pawn.HasReserved(thing) && !pawn.CanReserve(thing))
{
//Log.Message(thing.Label+": can't be reserved or reached by "+pawn.NameStringShort);
return false;
}
if (pawn.GetInventorySpaceFor(thing) < 1)
{
return false;
}
return true;
}
public static bool MayPurchaseThing(this ITrader guestTrader, Thing thing)
{
if (thing == null || guestTrader == null) return false;
if (thing.def.tradeability.PlayerCanSell()) return true;
return guestTrader.IsGuestTrader() && thing.def.thingCategories?.Contains(DefDatabase<ThingCategoryDef>.GetNamed("FoodMeals")) == true;
}
public static Toil TakeFromPawn(Thing item, ThingOwner holder, int count = -1, TargetIndex indexToSet = TargetIndex.None)
{
var toil = ToilMaker.MakeToil();
toil.initAction = delegate
{
if (!holder.Contains(item))
{
toil.actor.jobs.EndCurrentJob(JobCondition.Incompletable);
}
else
{
count = count < 0 ? toil.actor.jobs.curJob.count : count;
holder.TryDrop(item, ThingPlaceMode.Near, count, out var droppedThing);
if (droppedThing == null)
{
Log.Warning($"Taker {toil.actor.Label} unable to take count {count} of thing {item.Label} from holder's inventory");
toil.actor.jobs.EndCurrentJob(JobCondition.Incompletable);
}
else if (indexToSet != 0)
{
toil.actor.jobs.curJob.SetTarget(indexToSet, droppedThing);
}
}
};
return toil;
}
public static Toil TakeToInventory(TargetIndex indItem)
{
var takeThing = ToilMaker.MakeToil();
takeThing.initAction = delegate
{
var actor = takeThing.actor;
var thing = actor.CurJob.GetTarget(indItem).Thing;
if (actor.carryTracker.TryDropCarriedThing(actor.PositionHeld, ThingPlaceMode.Near, out var droppedThing))
{
droppedThing.DeSpawn();
actor.inventory.TryAddItemNotForSale(droppedThing);
thing.def.soundPickup.PlayOneShot(new TargetInfo(actor.Position, actor.Map));
}
else
{
actor.jobs.EndCurrentJob(JobCondition.Errored);
}
};
return takeThing;
}
#region Combat Extended integration
private static MethodBase canFitInInventory;
public static int GetInventorySpaceFor(this Pawn pawn, Thing current)
{
if (pawn == null || current == null) return 0;
var inventory = pawn.GetInventory();
if (inventory == null) return current.stackCount;
object[] arguments = [current, 0, false, true];
try
{
canFitInInventory ??= AccessTools.GetDeclaredMethods(inventory.GetType()).First(x => x.Name == "CanFitInInventory" && x.GetParameters()[0].ParameterType == typeof(Thing));
if (canFitInInventory == null)
{
Log.ErrorOnce("CanFitInInventory not found.", 4363476);
return current.stackCount;
}
var success = (bool)canFitInInventory.Invoke(inventory, arguments);
if (!success) return 0;
return (int)arguments[1];
}
catch (Exception e)
{
Log.Error(e.StackTrace);
return current.stackCount;
}
}
private static ThingComp GetInventory(this Pawn pawn)
{
return isCELoaded ? pawn.AllComps.FirstOrDefault(c => c.GetType().Name == "CompInventory") : null;
}
#endregion
}