-
Notifications
You must be signed in to change notification settings - Fork 17
/
Tools.cs
496 lines (432 loc) · 15.8 KB
/
Tools.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
using RimWorld;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Verse;
using Verse.Sound;
namespace CameraPlus
{
public enum LabelMode
{
hide,
show,
dot
}
[StaticConstructorOnStartup]
class Tools : CameraPlusSettings
{
static readonly Texture2D innerColonistTexture = ContentFinder<Texture2D>.Get("InnerColonistMarker", true);
static readonly Texture2D outerColonistTexture = ContentFinder<Texture2D>.Get("OuterColonistMarker", true);
static readonly Texture2D innerAnimalTexture = ContentFinder<Texture2D>.Get("InnerAnimalMarker", true);
static readonly Texture2D outerAnimalTexture = ContentFinder<Texture2D>.Get("OuterAnimalMarker", true);
static readonly Texture2D downedTexture = ContentFinder<Texture2D>.Get("DownedMarker", true);
static readonly Texture2D draftedTexture = ContentFinder<Texture2D>.Get("DraftedMarker", true);
static readonly Color downedColor = new(0.9f, 0f, 0f);
static readonly Color draftedColor = new(0f, 0.5f, 0f);
static readonly QuotaCache<Pawn, int, bool> shouldShowDotCache = new(60, pawn => pawn.thingIDNumber, pawn =>
{
if (CameraPlusMain.Settings.customNameStyle == LabelStyle.HideAnimals && pawn.RaceProps.Animal)
return false;
if (CameraPlusMain.Settings.mouseOverShowsLabels && MouseDistanceSquared(pawn.DrawPos, true) <= 2.25f)
return false;
if (InvisibilityUtility.IsHiddenFromPlayer(pawn))
return false;
var len = FastUI.CurUICellSize;
var isSmall = len <= CameraPlusMain.Settings.dotSize;
var tamedAnimal = pawn.RaceProps.Animal && pawn.Name != null;
return isSmall && (CameraPlusMain.Settings.includeNotTamedAnimals || pawn.RaceProps.Animal == false || tamedAnimal);
});
static readonly QuotaCache<Pawn, int, bool> shouldShowLabelCache = new(60, pawn => pawn.thingIDNumber, pawn =>
{
var len = FastUI.CurUICellSize;
if (len <= CameraPlusMain.Settings.hidePawnLabelBelow)
return false;
if (InvisibilityUtility.IsHiddenFromPlayer(pawn))
return false;
if (pawn != null && CameraPlusMain.Settings.customNameStyle == LabelStyle.HideAnimals && pawn.RaceProps.Animal)
return true;
if (pawn != null && len <= CameraPlusMain.Settings.dotSize)
return false;
return true;
});
public static bool ShouldShowDot(Pawn pawn)
{
if (pawn == null || CameraPlusMain.Settings.hideNamesWhenZoomedOut == false)
return false;
return shouldShowDotCache.Get(pawn);
}
public static bool ShouldShowLabel(Pawn pawn, Vector2 screenPos = default)
{
if (CameraPlusMain.Settings.hideNamesWhenZoomedOut == false)
return true;
if (CameraPlusMain.Settings.mouseOverShowsLabels && MouseDistanceSquared(pawn?.DrawPos ?? screenPos, pawn != null) <= 2.25f)
return true;
if (pawn == null)
return FastUI.CurUICellSize > CameraPlusMain.Settings.hideThingLabelBelow;
return shouldShowLabelCache.Get(pawn);
}
public static void DrawDot(Pawn pawn, Color innerColor, Color outerColor)
{
_ = GetMarkerTextures(pawn, out var innerTexture, out var outerTexture);
var pos = pawn.DrawPos;
var v1 = (pos - new Vector3(0.75f, 0f, 0.75f)).MapToUIPosition().Rounded();
var v2 = (pos + new Vector3(0.75f, 0f, 0.75f)).MapToUIPosition().Rounded();
var markerRect = new Rect(v1, v2 - v1);
// draw outer marker
GUI.color = outerColor;
GUI.DrawTexture(markerRect, outerTexture, ScaleMode.ScaleToFit, true);
// draw inner marker
GUI.color = innerColor;
GUI.DrawTexture(markerRect, innerTexture, ScaleMode.ScaleToFit, true);
// draw extra marker
if (pawn.Downed)
{
GUI.color = downedColor;
GUI.DrawTexture(markerRect, downedTexture, ScaleMode.ScaleToFit, true);
}
else if (pawn.Drafted)
{
GUI.color = draftedColor;
GUI.DrawTexture(markerRect, draftedTexture, ScaleMode.ScaleToFit, true);
}
}
static readonly Dictionary<string, Color> cachedMainColors = [];
public static Color? GetMainColor(Pawn pawn)
{
const int resizedTo = 8;
const int maxColorAmount = 1;
const float colorLimiterPercentage = 85f;
const int uniteColorsTolerance = 5;
const float minimiumColorPercentage = 10f;
var graphic = pawn.Drawer.renderer.BodyGraphic;
if (graphic == null)
return null;
var key = pawn.GetType().FullName + ":" + graphic.path;
if (cachedMainColors.TryGetValue(key, out var color) == false)
{
var material = graphic.MatEast ?? graphic.MatSingle;
if (material == null)
{
cachedMainColors[key] = Color.gray;
return null;
}
var texture = material.mainTexture;
if (texture == null)
{
cachedMainColors[key] = Color.gray;
return null;
}
var width = texture.width;
var height = texture.width;
var outputTexture = new Texture2D(width, height, TextureFormat.ARGB32, false);
var buffer = new RenderTexture(width, height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
Graphics.Blit(texture, buffer, material, 0);
RenderTexture.active = buffer;
outputTexture.ReadPixels(new Rect(0, 0, width, height), 0, 0, false);
var color32s = ProminentColor.GetColors32FromImage(outputTexture, resizedTo, maxColorAmount, colorLimiterPercentage, uniteColorsTolerance, minimiumColorPercentage);
if (color32s == null || color32s.Count == 0)
color = Color.gray;
else
color = new Color(color32s[0].r / 255f, color32s[0].g / 255f, color32s[0].b / 255f);
UnityEngine.Object.Destroy(outputTexture);
cachedMainColors[key] = color;
}
return color;
}
public static float MouseDistanceSquared(Vector3 pos, bool mapCoordinates)
{
if (mapCoordinates)
{
var mouse = FastUI.MouseMapPosition;
var dx1 = (mouse.x - pos.x);
var dz = (mouse.z - pos.z);
return dx1 * dx1 + dz * dz;
}
else
{
var mouse = FastUI.MousePositionOnUIInverted;
var len = FastUI.CurUICellSize;
mouse.y += len / 2;
var dx2 = (mouse.x - pos.x);
var dy = (mouse.y - pos.y);
var delta = dx2 * dx2 + dy * dy;
return delta / len / len;
}
}
static readonly Dictionary<Type, CameraDelegates> cachedCameraDelegates = [];
public static CameraDelegates GetCachedCameraDelegate(Pawn pawn)
{
var type = pawn.GetType();
if (cachedCameraDelegates.TryGetValue(type, out var result) == false)
{
result = new CameraDelegates(pawn);
cachedCameraDelegates[type] = result;
}
return result;
}
public static bool CorrectLabelRendering(Pawn pawn)
{
// we fake "show all" so we need to skip if original could would not render labels
return ReversePatches.PerformsDrawPawnGUIOverlay(pawn.Drawer.ui) == false;
}
// returning true will prefer markers over labels
static readonly Color dangerousAnimalColor = new(0.62f, 0f, 0.05f);
public static bool GetMarkerColors(Pawn pawn, out Color innerColor, out Color outerColor)
{
var cameraDelegate = GetCachedCameraDelegate(pawn);
if (cameraDelegate.GetCameraColors != null)
{
var colors = cameraDelegate.GetCameraColors(pawn);
if (colors == null || colors.Length != 2)
{
innerColor = default;
outerColor = default;
return false;
}
innerColor = colors[0];
outerColor = colors[1];
return true;
}
var isAnimal = pawn.RaceProps.Animal && pawn.Name != null;
var hideAnimalMarkers = CameraPlusMain.Settings.customNameStyle == LabelStyle.HideAnimals;
if (isAnimal && hideAnimalMarkers)
{
innerColor = default;
outerColor = default;
return false;
}
innerColor = PawnNameColorUtility.PawnNameColorOf(pawn);
if (pawn.RaceProps.Animal)
{
var stateDef = pawn.mindState.mentalStateHandler.CurStateDef;
var isDangerous = stateDef == MentalStateDefOf.ManhunterPermanent || stateDef == MentalStateDefOf.Manhunter;
innerColor = isDangerous ? dangerousAnimalColor : (GetMainColor(pawn) ?? innerColor);
}
outerColor = Find.Selector.IsSelected(pawn) ? Color.black : Color.white;
return true;
}
public static bool GetMarkerTextures(Pawn pawn, out Texture2D innerTexture, out Texture2D outerTexture)
{
var cameraDelegate = GetCachedCameraDelegate(pawn);
if (cameraDelegate.GetCameraMarkers != null)
{
var textures = cameraDelegate.GetCameraMarkers(pawn);
if (textures == null || textures.Length != 2)
{
innerTexture = default;
outerTexture = default;
return false;
}
innerTexture = textures[0];
outerTexture = textures[1];
return true;
}
var isAnimal = pawn.RaceProps.Animal;
var customAnimalStyle = CameraPlusMain.Settings.customNameStyle == LabelStyle.AnimalsDifferent;
innerTexture = isAnimal && customAnimalStyle ? innerAnimalTexture : innerColonistTexture;
outerTexture = isAnimal && customAnimalStyle ? outerAnimalTexture : outerColonistTexture;
return true;
}
public static float LerpDoubleSafe(float inFrom, float inTo, float outFrom, float outTo, float x)
{
if (inFrom == inTo)
return (outFrom + outTo) / 2;
return GenMath.LerpDouble(inFrom, inTo, outFrom, outTo, x);
}
public static float LerpRootSize(float x)
{
var n = CameraPlusMain.Settings.exponentiality;
if (n == 0)
return LerpDoubleSafe(minRootInput, maxRootInput, minRootResult, maxRootResult, x);
if (minRootResult == maxRootResult)
return minRootResult;
var factor = (maxRootResult - minRootResult) / Mathf.Pow(maxRootInput - minRootInput, 2 * n);
var y = minRootResult + Mathf.Pow(x - minRootInput, 2 * n) * factor;
return (float)y;
}
public static float GetDollyRateKeys(float orthSize)
{
var f = GetScreenEdgeDollyFactor(orthSize);
var zoomedIn = CameraPlusMain.Settings.zoomedInDollyPercent * f / 9f;
var zoomedOut = CameraPlusMain.Settings.zoomedOutDollyPercent * f * 1.1f;
return LerpDoubleSafe(minRootResult, maxRootResult, zoomedIn, zoomedOut, orthSize);
}
public static float GetScreenEdgeDollyFactor(float orthSize)
{
var zoomedIn = CameraPlusMain.Settings.zoomedInScreenEdgeDollyFactor * 30;
var zoomedOut = CameraPlusMain.Settings.zoomedOutScreenEdgeDollyFactor * 30;
return LerpDoubleSafe(minRootResult, maxRootResult, zoomedIn, zoomedOut, orthSize);
}
public static float GetDollyRateMouse(float orthSize)
{
var zoomedIn = 1f * CameraPlusMain.Settings.zoomedInDollyPercent;
var zoomedOut = 10f * CameraPlusMain.Settings.zoomedOutDollyPercent;
return LerpDoubleSafe(minRootResult, maxRootResult, zoomedIn, zoomedOut, orthSize);
}
public static float GetDollySpeedDecay(float orthSize)
{
// 0.15f comes from the old zoomedInDollyFrictionPercent/zoomedOutDollyFrictionPercent
//
var minVal = 1f - 0.15f;
var maxVal = 1f - 0.15f;
return LerpDoubleSafe(minRootResult, maxRootResult, minVal, maxVal, orthSize);
}
public static string ToLabel(KeyCode code)
{
return code switch
{
// cannot be more optimized because the enum has multiple equal values
//
KeyCode.None => "None".Translate(),
KeyCode.LeftShift => "KeyLeftShift".Translate(),
KeyCode.LeftAlt => "KeyLeftAlt".Translate(),
KeyCode.LeftControl => "KeyLeftControl".Translate(),
KeyCode.LeftCommand => "KeyLeftCommand".Translate(),
KeyCode.LeftWindows => "KeyLeftWindows".Translate(),
KeyCode.RightShift => "KeyRightShift".Translate(),
KeyCode.RightAlt => "KeyRightAlt".Translate(),
KeyCode.RightControl => "KeyRightControl".Translate(),
KeyCode.RightCommand => "KeyRightCommand".Translate(),
KeyCode.RightWindows => "KeyRightWindows".Translate(),
_ => code.ToStringReadable(),
};
}
public static void KeySettingsButton(Rect rect, bool allKeys, KeyCode setting, KeyCode defaultKey, Action<KeyCode> action)
{
if (allKeys)
{
TooltipHandler.TipRegionByKey(rect, "BindingButtonToolTip");
if (Widgets.ButtonText(rect, setting == KeyCode.None ? "" : ToLabel(setting)))
{
if (Event.current.button == 0)
{
Find.WindowStack.Add(new Dialog_AskForKey(action));
Event.current.Use();
return;
}
if (Event.current.button == 1)
{
var list = new List<FloatMenuOption>
{
new("ResetBinding".Translate(), () => action(defaultKey), MenuOptionPriority.Default, null, null, 0f, null, null, true, 0),
new("ClearBinding".Translate(), () => action(KeyCode.None), MenuOptionPriority.Default, null, null, 0f, null, null, true, 0)
};
Find.WindowStack.Add(new FloatMenu(list));
}
}
return;
}
if (Widgets.ButtonText(rect, setting == KeyCode.None ? "" : ToLabel(setting)))
{
var keys = new List<KeyCode>()
{
KeyCode.None,
KeyCode.LeftShift, KeyCode.LeftAlt, KeyCode.LeftControl, KeyCode.LeftCommand, KeyCode.LeftWindows,
KeyCode.RightShift, KeyCode.RightAlt, KeyCode.RightControl, KeyCode.RightCommand, KeyCode.RightWindows,
};
var choices = keys
.Select(code => new FloatMenuOption(ToLabel(code), delegate () { action(code); }, MenuOptionPriority.Default, null, null, 0f, null, null))
.ToList();
Find.WindowStack.Add(new FloatMenu(choices));
Event.current.Use();
}
}
static Vector3 snapbackRootPos;
static float snapbackRootSize = 0;
public static void CreateSnapback()
{
Defs.SnapBack.PlayOneShotOnCamera(null);
var cameraDriver = Current.cameraDriverInt;
snapbackRootPos = cameraDriver.rootPos;
snapbackRootSize = cameraDriver.rootSize;
}
public static bool HasSnapback => snapbackRootSize != 0;
public static void ResetSnapback()
{
snapbackRootPos = default;
snapbackRootSize = default;
}
public static void RestoreSnapback()
{
var tm = Find.TickManager;
var savedSpeed = tm.curTimeSpeed;
IEnumerator ApplyRootPosAndSize()
{
yield return new WaitForSeconds(0.35f);
Current.cameraDriverInt.SetRootPosAndSize(snapbackRootPos, snapbackRootSize);
ResetSnapback();
tm.curTimeSpeed = savedSpeed;
}
tm.curTimeSpeed = TimeSpeed.Paused;
Defs.ApplySnap.PlayOneShotOnCamera(null);
_ = Current.cameraDriverInt.StartCoroutine(ApplyRootPosAndSize());
}
public static void HandleHotkeys()
{
if (Event.current.type == EventType.Repaint || Current.ProgramState != ProgramState.Playing)
return;
var settings = CameraPlusMain.Settings;
KeyCode m1, m2;
if (Input.GetKey(settings.cameraSettingsKey))
{
m1 = settings.cameraSettingsMod[0];
m2 = settings.cameraSettingsMod[1];
if (m1 == KeyCode.None && m2 == KeyCode.None)
return;
if (m1 == KeyCode.None || Input.GetKey(m1))
if (m2 == KeyCode.None || Input.GetKey(m2))
{
var stack = Find.WindowStack;
if (stack.IsOpen<Dialog_ModSettings>() == false)
{
var me = LoadedModManager.GetMod<CameraPlusMain>();
var dialog = new Dialog_ModSettings(me);
stack.Add(dialog);
}
Event.current.Use();
return;
}
}
var numKey = 0;
for (var i = 1; i <= 9; i++)
if (Input.GetKey("" + i))
{
numKey = i;
break;
}
if (numKey == 0)
return;
var map = Current.gameInt.CurrentMap;
if (map == null)
return;
var savedViews = map.GetComponent<SavedViews>();
m1 = settings.cameraSettingsLoad[0];
m2 = settings.cameraSettingsLoad[1];
if (m1 != KeyCode.None || m2 != KeyCode.None)
if (m1 == KeyCode.None || Input.GetKey(m1))
if (m2 == KeyCode.None || Input.GetKey(m2))
{
var view = savedViews.views[numKey - 1];
if (view != null)
Current.cameraDriverInt.SetRootPosAndSize(view.rootPos, view.rootSize);
Event.current.Use();
}
m1 = settings.cameraSettingsSave[0];
m2 = settings.cameraSettingsSave[1];
if (m1 != KeyCode.None || m2 != KeyCode.None)
if (m1 == KeyCode.None || Input.GetKey(m1))
if (m2 == KeyCode.None || Input.GetKey(m2))
{
var cameraDriver = Current.cameraDriverInt;
savedViews.views[numKey - 1] = new RememberedCameraPos(map)
{
rootPos = cameraDriver.rootPos,
rootSize = cameraDriver.rootSize
};
Event.current.Use();
}
}
}
}