-
Notifications
You must be signed in to change notification settings - Fork 17
/
Main.cs
610 lines (531 loc) · 17.4 KB
/
Main.cs
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
using Brrainz;
using HarmonyLib;
using RimWorld;
using RimWorld.Planet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using UnityEngine;
using Verse;
namespace CameraPlus
{
[DefOf]
public static class Defs
{
public static SoundDef SnapBack;
public static SoundDef ApplySnap;
}
public class CameraPlusMain : Mod
{
public static CameraPlusSettings Settings;
public static float orthographicSize = -1f;
// for other mods: set temporarily to true to skip any hiding
public static bool skipCustomRendering = false;
public CameraPlusMain(ModContentPack content) : base(content)
{
Settings = GetSettings<CameraPlusSettings>();
var harmony = new Harmony("net.pardeike.rimworld.mod.camera+");
harmony.PatchAll();
CrossPromotion.Install(76561197973010050);
}
public override void DoSettingsWindowContents(Rect inRect)
{
Settings.DoWindowContents(inRect);
}
public override string SettingsCategory()
{
return "Camera+";
}
}
[HarmonyPatch(typeof(CameraDriver), nameof(CameraDriver.Update))]
static class CameraDriver_Update_Patch
{
static readonly MethodInfo m_SetRootSize = SymbolExtensions.GetMethodInfo(() => SetRootSize(null, 0f));
static void SetRootSize(CameraDriver driver, float rootSize)
{
if (driver == null)
{
var info = Harmony.GetPatchInfo(AccessTools.Method(typeof(CameraDriver), nameof(CameraDriver.Update)));
var owners = "Maybe one of the mods that patch CameraDriver.Update(): ";
info.Owners.Do(owner => owners += owner + " ");
Log.ErrorOnce("Unexpected null camera driver. Looks like a mod conflict. " + owners, 506973465);
return;
}
if (Event.current.shift || CameraPlusMain.Settings.zoomToMouse == false)
{
driver.rootSize = rootSize;
return;
}
if (driver.rootSize != rootSize)
{
driver.ApplyPositionToGameObject();
var oldMousePos = FastUI.MouseMapPosition;
driver.rootSize = rootSize;
driver.ApplyPositionToGameObject();
driver.rootPos += oldMousePos - UI.MouseMapPosition(); // dont use FastUI.MouseMapPosition here
}
}
public static void Prefix(CameraDriver __instance)
{
if (CameraPlusMain.Settings.disableCameraShake)
__instance.shaker.curShakeMag = 0;
}
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
var found = false;
foreach (var instruction in instructions)
{
if (instruction.StoresField(Refs.f_rootSize))
{
instruction.opcode = OpCodes.Call;
instruction.operand = m_SetRootSize;
found = true;
}
yield return instruction;
}
if (found == false)
Log.Error("Cannot find field Stdfld rootSize in CameraDriver.Update");
}
}
[HarmonyPatch(typeof(TimeControls), nameof(TimeControls.DoTimeControlsGUI))]
static class TimeControls_DoTimeControlsGUI_Patch
{
public static void Prefix()
{
Tools.HandleHotkeys();
}
}
[HarmonyPatch(typeof(CameraDriver), nameof(CameraDriver.CalculateCurInputDollyVect))]
static class CameraDriver_CalculateCurInputDollyVect_Patch
{
public static void Postfix(ref Vector2 __result)
{
if (CameraPlusMain.orthographicSize != -1f)
__result *= Tools.GetScreenEdgeDollyFactor(CameraPlusMain.orthographicSize);
}
}
[HarmonyPatch(typeof(MoteMaker), nameof(MoteMaker.ThrowText))]
[HarmonyPatch(new Type[] { typeof(Vector3), typeof(Map), typeof(string), typeof(Color), typeof(float) })]
static class MoteMaker_ThrowText_Patch
{
public static bool Prefix(Vector3 loc)
{
if (CameraPlusMain.skipCustomRendering)
return true;
var settings = CameraPlusMain.Settings;
if (settings.hideNamesWhenZoomedOut == false)
return true;
if (Current.cameraDriverInt.CurrentZoom == CameraZoomRange.Closest)
return true;
if (settings.mouseOverShowsLabels)
return Tools.MouseDistanceSquared(loc, true) <= 2.25f;
return false;
}
}
[HarmonyPatch(typeof(PawnRenderer), nameof(PawnRenderer.RenderPawnAt))]
[HarmonyPatch(new Type[] { typeof(Vector3), typeof(Rot4?), typeof(bool) })]
static class PawnRenderer_RenderPawnAt_Patch
{
[HarmonyPriority(10000)]
public static bool Prefix(Pawn ___pawn)
{
if (CameraPlusMain.skipCustomRendering)
return true;
return Tools.ShouldShowDot(___pawn) == false;
}
[HarmonyPriority(10000)]
public static void Postfix(Pawn ___pawn)
{
if (CameraPlusMain.Settings.hideNamesWhenZoomedOut && CameraPlusMain.Settings.customNameStyle != LabelStyle.HideAnimals)
_ = Tools.GetMainColor(___pawn); // trigger caching
}
}
[HarmonyPatch(typeof(PawnUIOverlay), nameof(PawnUIOverlay.DrawPawnGUIOverlay))]
static class PawnUIOverlay_DrawPawnGUIOverlay_Patch
{
// fake everything being humanlike so Prefs.AnimalNameMode is ignored (we handle it ourselves)
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
var mHumanlike = AccessTools.PropertyGetter(typeof(RaceProperties), nameof(RaceProperties.Humanlike));
foreach (var code in instructions)
{
yield return code;
if (code.Calls(mHumanlike))
{
yield return new CodeInstruction(OpCodes.Pop);
yield return new CodeInstruction(OpCodes.Ldc_I4_1);
}
}
}
[HarmonyPriority(10000)]
public static bool Prefix(Pawn ___pawn)
{
if (CameraPlusMain.skipCustomRendering)
return true;
if (!___pawn.Spawned || ___pawn.Map.fogGrid.IsFogged(___pawn.Position))
return true;
if (___pawn.RaceProps.Humanlike)
return true;
if (___pawn.Name != null)
return true;
var useMarkers = Tools.GetMarkerColors(___pawn, out var innerColor, out var outerColor);
if (useMarkers == false)
return true; // use label
if (Tools.ShouldShowDot(___pawn))
{
Tools.DrawDot(___pawn, innerColor, outerColor);
return false;
}
return Tools.CorrectLabelRendering(___pawn);
}
}
//
// Dubs Performance Analyzer patch on PawnUIOverlay.DrawPawnGUIOverlay needs to be turned off
//
[HarmonyPatch]
static class Analyzer_Fixes_H_DrawNamesFix_Prefix_Patch
{
public static bool Prepare() => TargetMethod() != null;
public static MethodInfo TargetMethod() => AccessTools.Method("Analyzer.Fixes.H_DrawNamesFix:Prefix");
public static bool Prefix(ref bool __result)
{
__result = true;
return false;
}
}
[HarmonyPatch(typeof(GenMapUI), nameof(GenMapUI.DrawPawnLabel))]
[HarmonyPatch(new Type[] { typeof(Pawn), typeof(Vector2), typeof(float), typeof(float), typeof(Dictionary<string, string>), typeof(GameFont), typeof(bool), typeof(bool) })]
static class GenMapUI_DrawPawnLabel_Patch
{
[HarmonyPriority(10000)]
public static bool Prefix(Pawn pawn, float truncateToWidth)
{
if (CameraPlusMain.skipCustomRendering)
return true;
if (truncateToWidth != 9999f)
return true;
if (Tools.ShouldShowDot(pawn))
{
var useMarkers = Tools.GetMarkerColors(pawn, out var innerColor, out var outerColor);
if (useMarkers == false)
return Tools.CorrectLabelRendering(pawn);
Tools.DrawDot(pawn, innerColor, outerColor);
return false;
}
// we fake "show all" so we need to skip if original could would not render labels
if (ReversePatches.PerformsDrawPawnGUIOverlay(pawn.Drawer.ui) == false)
return false;
return Tools.ShouldShowLabel(pawn);
}
}
// if we zoom in a lot, tiny font labels look very out of place
// so we make them bigger with the available fonts
//
[HarmonyPatch(typeof(GenMapUI), nameof(GenMapUI.DrawThingLabel))]
[HarmonyPatch(new Type[] { typeof(Vector2), typeof(string), typeof(Color) })]
static class GenMapUI_DrawThingLabel_Patch
{
static readonly MethodInfo m_GetAdaptedGameFont = SymbolExtensions.GetMethodInfo(() => GetAdaptedGameFont(0f));
static GameFont GetAdaptedGameFont(float rootSize)
{
if (rootSize < 11f)
return GameFont.Medium;
if (rootSize < 15f)
return GameFont.Small;
return GameFont.Tiny;
}
[HarmonyPriority(10000)]
public static bool Prefix(Vector2 screenPos)
{
if (CameraPlusMain.skipCustomRendering)
return true;
return Tools.ShouldShowLabel(null, screenPos);
}
// we replace the first "GameFont.Tiny" with "GetAdaptedGameFont()"
//
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
var firstInstruction = true;
foreach (var instruction in instructions)
{
if (firstInstruction && instruction.LoadsConstant(0))
{
yield return new CodeInstruction(OpCodes.Call, Refs.p_CameraDriver);
yield return new CodeInstruction(OpCodes.Ldfld, Refs.f_rootSize);
yield return new CodeInstruction(OpCodes.Call, m_GetAdaptedGameFont);
firstInstruction = false;
}
else
yield return instruction;
}
}
}
// map our new camera settings to meaningful enum values
//
[HarmonyPatch(typeof(CameraDriver), nameof(CameraDriver.CurrentZoom), MethodType.Getter)]
static class CameraDriver_CurrentZoom_Patch
{
// these values are from vanilla. we remap them to the range 30 - 60
static readonly float[] sizes = new[] { 12f, 13.8f, 42f, 57f }
.Select(f => Tools.LerpDoubleSafe(12, 57, 30, 60, f))
.ToArray();
static readonly float size0 = sizes[0], size1 = sizes[1], size2 = sizes[2], size3 = sizes[3];
public static bool Prefix(ref CameraZoomRange __result, float ___rootSize)
{
var lerped = Tools.LerpRootSize(___rootSize);
if (lerped < size0)
__result = CameraZoomRange.Closest;
else if (lerped < size1)
__result = CameraZoomRange.Close;
else if (lerped < size2)
__result = CameraZoomRange.Middle;
else if (lerped < size3)
__result = CameraZoomRange.Far;
else
__result = CameraZoomRange.Furthest;
return false;
}
}
[HarmonyPatch(typeof(CameraDriver), nameof(CameraDriver.ApplyPositionToGameObject))]
static class CameraDriver_ApplyPositionToGameObject_Patch
{
static readonly MethodInfo m_ApplyZoom = SymbolExtensions.GetMethodInfo(() => ApplyZoom(null, null));
static void ApplyZoom(CameraDriver driver, Camera camera)
{
// small note: moving the camera too far out requires adjusting the clipping distance
//
var pos = camera.transform.position;
var cameraSpan = CameraPlusSettings.maxRootOutput - CameraPlusSettings.minRootOutput;
var f = (pos.y - CameraPlusSettings.minRootOutput) / cameraSpan;
f *= 1 - CameraPlusMain.Settings.soundNearness;
pos.y = CameraPlusSettings.minRootOutput + f * cameraSpan;
camera.transform.position = pos;
var orthSize = Tools.LerpRootSize(camera.orthographicSize);
camera.orthographicSize = orthSize;
driver.config.dollyRateKeys = Tools.GetDollyRateKeys(orthSize);
driver.config.dollyRateScreenEdge = Tools.GetDollyRateMouse(orthSize);
driver.config.camSpeedDecayFactor = Tools.GetDollySpeedDecay(orthSize);
CameraPlusMain.orthographicSize = orthSize;
}
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
foreach (var instruction in instructions)
if (instruction.opcode != OpCodes.Ret)
yield return instruction;
yield return new CodeInstruction(OpCodes.Ldarg_0);
yield return new CodeInstruction(OpCodes.Ldarg_0);
yield return new CodeInstruction(OpCodes.Call, Refs.p_MyCamera);
yield return new CodeInstruction(OpCodes.Call, m_ApplyZoom);
yield return new CodeInstruction(OpCodes.Ret);
}
}
// here, we basically add a "var lerpedRootSize = Main.LerpRootSize(this.rootSize);" to
// the beginning of this method and replace every "this.rootSize" witn "lerpedRootSize"
//
[HarmonyPatch(typeof(CameraDriver), nameof(CameraDriver.CurrentViewRect), MethodType.Getter)]
static class CameraDriver_CurrentViewRect_Patch
{
static readonly MethodInfo m_Main_LerpRootSize = SymbolExtensions.GetMethodInfo(() => Tools.LerpRootSize(0f));
public static IEnumerable<CodeInstruction> Transpiler(ILGenerator generator, IEnumerable<CodeInstruction> instructions)
{
var v_lerpedRootSize = generator.DeclareLocal(typeof(float));
// store lerped rootSize in a new local var
//
yield return new CodeInstruction(OpCodes.Ldarg_0);
yield return new CodeInstruction(OpCodes.Ldfld, Refs.f_rootSize);
yield return new CodeInstruction(OpCodes.Call, m_Main_LerpRootSize);
yield return new CodeInstruction(OpCodes.Stloc, v_lerpedRootSize);
var previousCodeWasLdArg0 = false;
foreach (var instr in instructions)
{
var instruction = instr; // make it writeable
if (instruction.opcode == OpCodes.Ldarg_0)
{
previousCodeWasLdArg0 = true;
continue; // do not emit the code
}
if (previousCodeWasLdArg0)
{
previousCodeWasLdArg0 = false;
// looking for Ldarg.0 followed by Ldfld rootSize
//
if (instruction.LoadsField(Refs.f_rootSize))
instruction = new CodeInstruction(OpCodes.Ldloc, v_lerpedRootSize);
else
yield return new CodeInstruction(OpCodes.Ldarg_0); // repeat the code we did not emit in the first check
}
yield return instruction;
}
}
}
[HarmonyPatch]
static class SaveOurShip2BackgroundPatch
{
public static bool Prepare() => TargetMethod() != null;
public static MethodBase TargetMethod() { return AccessTools.Method("SaveOurShip2.MeshRecalculateHelper:RecalculateMesh"); }
public static readonly MethodInfo mCenter = AccessTools.PropertyGetter(AccessTools.TypeByName("SaveOurShip2.SectionThreadManager"), "Center");
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
var state = 0;
foreach (var code in instructions)
{
switch (state)
{
case 0:
if (code.opcode == OpCodes.Ldsflda && code.operand is MethodInfo method && method == mCenter)
state = 1;
break;
case 1:
if (code.opcode == OpCodes.Sub)
state = 2;
break;
case 2:
state = 3;
break;
case 3:
yield return new CodeInstruction(OpCodes.Ldc_R4, 4f);
yield return new CodeInstruction(OpCodes.Mul);
state = 0;
break;
}
yield return code;
}
}
}
[HarmonyPatch(typeof(Map))]
[HarmonyPatch(nameof(Map.MapUpdate))]
static class Map_MapUpdate_Patch
{
static bool done = false;
public static bool Prepare() => ModLister.HasActiveModWithName("Save Our Ship 2");
static FieldInfo PlanetMaterialField(string typeName)
{
var type = AccessTools.TypeByName($"SaveOurShip2.{typeName}");
if (type == null)
return null;
return AccessTools.Field(type, "PlanetMaterial");
}
static void FixSoSMaterial()
{
done = true;
var fPlanetMaterial = PlanetMaterialField("RenderPlanetBehindMap") ?? PlanetMaterialField("ResourceBank");
if (fPlanetMaterial == null)
return;
var mat = fPlanetMaterial.GetValue(null) as Material;
if (mat == null)
return;
mat.mainTextureOffset = new Vector2(0.3f, 0.3f);
mat.mainTextureScale = new Vector2(0.4f, 0.4f);
}
public static void Postfix(Map __instance)
{
if (done)
return;
if (WorldRendererUtility.WorldRenderedNow)
return;
if (Find.CurrentMap != __instance)
return;
FixSoSMaterial();
}
}
[HarmonyPatch(typeof(KeyBindingDef))]
[HarmonyPatch(nameof(KeyBindingDef.KeyDownEvent))]
[HarmonyPatch(MethodType.Getter)]
static class KeyBindingDef_KeyDownEvent_Patch
{
static bool wasDown = false;
static bool downInsideTick = false;
public static void CleanupAtEndOfFrame()
{
if (Event.current.type == EventType.KeyUp && KeyBindingDefOf.TogglePause.IsDown == false)
wasDown = false;
downInsideTick = false;
}
public static bool Prefix(KeyBindingDef __instance, ref bool __result)
{
if (__instance != KeyBindingDefOf.TogglePause)
return true;
if (__instance.IsDown && wasDown == false)
{
wasDown = true;
downInsideTick = true;
}
__result = downInsideTick;
return false;
}
}
[HarmonyPatch(typeof(Root))]
[HarmonyPatch(nameof(Root.OnGUI))]
static class Root_OnGUI_Patch
{
public static void Postfix()
{
KeyBindingDef_KeyDownEvent_Patch.CleanupAtEndOfFrame();
}
}
[HarmonyPatch(typeof(Game))]
[HarmonyPatch(nameof(Game.UpdatePlay))]
static class Game_UpdatePlay_Patch
{
static DateTime lastChange = DateTime.MinValue;
static bool eventFired = false;
public static void Postfix()
{
if (Tools.HasSnapback && Current.gameInt.tickManager.Paused == false)
Tools.RestoreSnapback();
if (KeyBindingDefOf.TogglePause.IsDown && Current.gameInt.tickManager.Paused)
{
var now = DateTime.Now;
if (lastChange == DateTime.MinValue)
lastChange = now;
else if (eventFired == false && now.Subtract(lastChange).TotalSeconds > 1)
{
Tools.CreateSnapback();
eventFired = true;
}
}
else
{
lastChange = DateTime.MinValue;
eventFired = false;
}
}
}
[HarmonyPatch(typeof(TickManager))]
[HarmonyPatch(nameof(TickManager.TogglePaused))]
static class TickManager_TogglePaused_Patch
{
public static void Postfix(TickManager __instance)
{
if (Tools.HasSnapback && __instance.Paused == false)
Tools.RestoreSnapback();
}
}
[HarmonyPatch(typeof(MainTabWindow_Menu))]
[HarmonyPatch(nameof(MainTabWindow_Menu.PreOpen))]
static class MainTabWindow_Menu_PreOpen_Patch
{
public static void Postfix()
{
Tools.ResetSnapback();
}
}
[HarmonyPatch(typeof(UIRoot_Play))]
[HarmonyPatch(nameof(UIRoot_Play.UIRootOnGUI))]
static class UIRoot_Play_UIRootOnGUI_Patch
{
public static void Postfix()
{
KeyBindingDef_KeyDownEvent_Patch.CleanupAtEndOfFrame();
if (Tools.HasSnapback == false)
return;
var rect = new Rect(0, 0, UI.screenWidth, UI.screenHeight);
var color = GUI.color;
GUI.color = new Color(0, 0, 0, 0.5f);
Widgets.DrawBox(rect, 20);
GUI.color = color;
}
}
}