/
VesselExtensions.cs
418 lines (345 loc) · 15.6 KB
/
VesselExtensions.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
using System;
using System.Collections.Generic;
using Smooth.Slinq;
using Smooth.Slinq.Context;
using UniLinq;
using UnityEngine;
namespace MuMech
{
public static class VesselExtensions
{
public static bool VesselOffGround(this Vessel vessel)
{
return vessel.situation is Vessel.Situations.FLYING or Vessel.Situations.ESCAPING
or Vessel.Situations.ORBITING or Vessel.Situations.SUB_ORBITAL;
}
public static List<ITargetable> GetTargetables(this Vessel vessel)
{
List<Part> parts;
if (HighLogic.LoadedSceneIsEditor) parts = EditorLogic.fetch.ship.parts;
else if (vessel == null) return new List<ITargetable>();
else parts = vessel.Parts;
return parts.SelectMany(part => part.Modules.OfType<ITargetable>()).ToList();
}
public static List<T> GetModules<T>(this Vessel vessel) where T : PartModule
{
List<Part> parts;
if (HighLogic.LoadedSceneIsEditor && EditorLogic.fetch != null) parts = EditorLogic.fetch.ship.parts;
else if (vessel == null || vessel.Parts == null) return new List<T>();
else parts = vessel.Parts;
var list = new List<T>();
for (int p = 0; p < parts.Count; p++)
{
Part part = parts[p];
if (part.Modules == null)
continue;
int count = part.Modules.Count;
for (int m = 0; m < count; m++)
{
if (part.Modules[m] is T mod)
{
list.Add(mod);
;
}
}
}
return list;
}
public static T GetModule<T>(this Vessel vessel, Predicate<T> predicate) where T : PartModule
{
List<Part> parts;
if (HighLogic.LoadedSceneIsEditor && EditorLogic.fetch != null) parts = EditorLogic.fetch.ship.parts;
else if (vessel == null || vessel.Parts == null) return default;
else parts = vessel.Parts;
for (int p = 0; p < parts.Count; p++)
{
Part part = parts[p];
if (part.Modules == null)
continue;
int count = part.Modules.Count;
for (int m = 0; m < count; m++)
{
if (part.Modules[m] is T mod && predicate(mod))
{
return mod;
}
}
}
return default;
}
private static float lastFixedTime;
private static readonly Dictionary<Guid, MechJebCore> masterMechJeb = new();
public static MechJebCore GetMasterMechJeb(this Vessel vessel)
{
if (lastFixedTime != Time.fixedTime)
{
masterMechJeb.Clear();
lastFixedTime = Time.fixedTime;
}
Guid vesselKey = vessel == null ? Guid.Empty : vessel.id;
if (!masterMechJeb.TryGetValue(vesselKey, out MechJebCore mj))
{
mj = vessel.GetModule<MechJebCore>(p => p.running);
if (mj != null)
masterMechJeb.Add(vesselKey, mj);
return mj;
}
return mj;
}
public static double TotalResourceAmount(this Vessel vessel, PartResourceDefinition definition)
{
if (definition == null) return 0;
List<Part> parts = HighLogic.LoadedSceneIsEditor ? EditorLogic.fetch.ship.parts : vessel.parts;
double amount = 0;
for (int i = 0; i < parts.Count; i++)
{
Part p = parts[i];
for (int j = 0; j < p.Resources.Count; j++)
{
PartResource r = p.Resources[j];
if (r.info.id == definition.id)
{
amount += r.amount;
}
}
}
return amount;
}
public static double TotalResourceAmount(this Vessel vessel, string resourceName)
{
return vessel.TotalResourceAmount(PartResourceLibrary.Instance.GetDefinition(resourceName));
}
public static double TotalResourceAmount(this Vessel vessel, int resourceId)
{
return vessel.TotalResourceAmount(PartResourceLibrary.Instance.GetDefinition(resourceId));
}
public static double TotalResourceMass(this Vessel vessel, string resourceName)
{
PartResourceDefinition definition = PartResourceLibrary.Instance.GetDefinition(resourceName);
return vessel.TotalResourceAmount(definition) * definition.density;
}
public static double TotalResourceMass(this Vessel vessel, int resourceId)
{
PartResourceDefinition definition = PartResourceLibrary.Instance.GetDefinition(resourceId);
return vessel.TotalResourceAmount(definition) * definition.density;
}
public static double MaxResourceAmount(this Vessel vessel, PartResourceDefinition definition)
{
if (definition == null) return 0;
List<Part> parts = HighLogic.LoadedSceneIsEditor ? EditorLogic.fetch.ship.parts : vessel.parts;
double amount = 0;
for (int i = 0; i < parts.Count; i++)
{
Part p = parts[i];
for (int j = 0; j < p.Resources.Count; j++)
{
PartResource r = p.Resources[j];
if (r.info.id == definition.id)
{
amount += r.maxAmount;
}
}
}
return amount;
}
public static double MaxResourceAmount(this Vessel vessel, int id)
{
PartResourceDefinition definition = PartResourceLibrary.Instance.GetDefinition(id);
return vessel.MaxResourceAmount(definition);
}
public static double MaxResourceAmount(this Vessel vessel, string resourceName)
{
return vessel.MaxResourceAmount(PartResourceLibrary.Instance.GetDefinition(resourceName));
}
public static bool HasElectricCharge(this Vessel vessel)
{
if (vessel == null)
return false;
List<Part> parts = HighLogic.LoadedSceneIsEditor ? EditorLogic.fetch.ship.parts : vessel.parts;
PartResourceDefinition definition = PartResourceLibrary.Instance.GetDefinition(PartResourceLibrary.ElectricityHashcode);
if (definition == null) return false;
PartResource r;
if (vessel.GetReferenceTransformPart() != null)
{
r = vessel.GetReferenceTransformPart().Resources.Get(definition.id);
// check the command pod first since most have their batteries
if (r != null && r.amount > 0)
return true;
}
for (int i = 0; i < parts.Count; i++)
{
Part p = parts[i];
r = p.Resources.Get(definition.id);
if (r != null && r.amount > 0)
{
return true;
}
}
return false;
}
public static bool LiftedOff(this Vessel vessel)
{
return vessel.situation != Vessel.Situations.PRELAUNCH;
}
public static Orbit GetPatchAtUT(this Vessel vessel, double UT)
{
IEnumerable<ManeuverNode> earlierNodes = vessel.patchedConicSolver.maneuverNodes.Where(n => n.UT <= UT);
Orbit o = vessel.orbit;
if (earlierNodes.Any())
{
o = earlierNodes.OrderByDescending(n => n.UT).First().nextPatch;
}
while (o.patchEndTransition != Orbit.PatchTransitionType.FINAL && o.nextPatch.StartUT <= UT)
{
o = o.nextPatch;
}
return o;
}
//If there is a maneuver node on this patch, returns the patch that follows that maneuver node
//Otherwise, if this patch ends in an SOI transition, returns the patch that follows that transition
//Otherwise, returns null
public static Orbit GetNextPatch(this Vessel vessel, Orbit patch, ManeuverNode ignoreNode = null)
{
if (patch == null)
{
return null;
}
//Determine whether this patch ends in an SOI transition or if it's the final one:
bool finalPatch = patch.patchEndTransition == Orbit.PatchTransitionType.FINAL;
if (vessel.patchedConicSolver == null)
{
vessel.patchedConicSolver = vessel.gameObject.AddComponent<PatchedConicSolver>();
vessel.patchedConicSolver.Load(vessel.flightPlanNode);
}
//See if any maneuver nodes occur during this patch. If there is one
//return the patch that follows it
Slinq<ManeuverNode, PredicateContext<ManeuverNode, IListContext<ManeuverNode>, Orbit>> nodes = vessel.patchedConicSolver.maneuverNodes
.Slinq().Where((n, p) => n.patch == p && n != ignoreNode, patch);
// Slinq is nice but you can only enumerate it once
ManeuverNode first = nodes.FirstOrDefault();
if (first != null) return first.nextPatch;
//return the next patch, or null if there isn't one:
if (!finalPatch) return patch.nextPatch;
return null;
}
//input dV should be in world coordinates
public static ManeuverNode PlaceManeuverNode(this Vessel vessel, Orbit ignoredParameterThatNeedsDeleting, Vector3d dV, double UT)
{
// get the right for the time
Orbit patch = vessel.GetPatchAtUT(UT);
//placing a maneuver node with bad dV values can really mess up the game, so try to protect against that
//and log an exception if we get a bad dV vector:
for (int i = 0; i < 3; i++)
{
if (double.IsNaN(dV[i]) || double.IsInfinity(dV[i]))
{
throw new Exception("MechJeb VesselExtensions.PlaceManeuverNode: bad dV: " + dV);
}
}
if (double.IsNaN(UT) || double.IsInfinity(UT))
{
throw new Exception("MechJeb VesselExtensions.PlaceManeuverNode: bad UT: " + UT);
}
//It seems that sometimes the game can freak out if you place a maneuver node in the past, so this
//protects against that.
UT = Math.Max(UT, Planetarium.GetUniversalTime());
//convert a dV in world coordinates into the coordinate system of the maneuver node,
//which uses (x, y, z) = (radial+, normal-, prograde)
Vector3d nodeDV = patch.DeltaVToManeuverNodeCoordinates(UT, dV);
ManeuverNode mn = vessel.patchedConicSolver.AddManeuverNode(UT);
mn.DeltaV = nodeDV;
vessel.patchedConicSolver.UpdateFlightPlan();
return mn;
}
public static void RemoveAllManeuverNodes(this Vessel vessel)
{
if (!vessel.patchedConicsUnlocked())
return;
while (vessel.patchedConicSolver.maneuverNodes.Count > 0)
{
vessel.patchedConicSolver.maneuverNodes.Last().RemoveSelf();
}
}
// From FAR with ferram4 authorisation
public static MechJebModuleDockingAutopilot.Box3d GetBoundingBox(this Vessel vessel, bool debug = false)
{
var minBounds = new Vector3();
var maxBounds = new Vector3();
if (debug)
{
MonoBehaviour.print("[GetBoundingBox] Start " + vessel.vesselName);
}
for (int i = 0; i < vessel.parts.Count; i++)
{
Part p = vessel.parts[i];
PartExtensions.Vector3Pair partBox = p.GetBoundingBox();
if (debug)
{
MonoBehaviour.print("[GetBoundingBox] " + p.name + " " + (partBox.p1 - partBox.p2).magnitude.ToString("F3"));
}
maxBounds.x = Mathf.Max(maxBounds.x, partBox.p1.x);
minBounds.x = Mathf.Min(minBounds.x, partBox.p2.x);
maxBounds.y = Mathf.Max(maxBounds.y, partBox.p1.y);
minBounds.y = Mathf.Min(minBounds.y, partBox.p2.y);
maxBounds.z = Mathf.Max(maxBounds.z, partBox.p1.z);
minBounds.z = Mathf.Min(minBounds.z, partBox.p2.z);
//foreach (var sympart in p.symmetryCounterparts)
//{
// partBox = sympart.GetBoundingBox();
// maxBounds.x = Mathf.Max(maxBounds.x, partBox.p1.x);
// minBounds.x = Mathf.Min(minBounds.x, partBox.p2.x);
// maxBounds.y = Mathf.Max(maxBounds.y, partBox.p1.y);
// minBounds.y = Mathf.Min(minBounds.y, partBox.p2.y);
// maxBounds.z = Mathf.Max(maxBounds.z, partBox.p1.z);
// minBounds.z = Mathf.Min(minBounds.z, partBox.p2.z);
//}
}
if (debug)
{
MonoBehaviour.print("[GetBoundingBox] End " + vessel.vesselName);
}
var box = new MechJebModuleDockingAutopilot.Box3d();
box.center = new Vector3d((maxBounds.x + minBounds.x) / 2, (maxBounds.y + minBounds.y) / 2, (maxBounds.z + minBounds.z) / 2);
box.size = new Vector3d(Math.Abs(box.center.x - maxBounds.x), Math.Abs(box.center.y - maxBounds.y), Math.Abs(box.center.z - maxBounds.z));
return box;
}
// 0.90 added a building upgrade to unlock Orbit visualization and patched conics
// Unfortunately when patchedConics are disabled vessel.patchedConicSolver is null
// So we need to add a lot of sanity check and/or disable modules
public static bool patchedConicsUnlocked(this Vessel vessel)
{
return GameVariables.Instance.GetOrbitDisplayMode(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.TrackingStation)) ==
GameVariables.OrbitDisplayMode.PatchedConics;
}
public static void UpdateNode(this ManeuverNode node, Vector3d dV, double ut)
{
node.DeltaV = dV;
node.UT = ut;
node.solver.UpdateFlightPlan();
if (node.attachedGizmo == null)
return;
node.attachedGizmo.patchBefore = node.patch;
node.attachedGizmo.patchAhead = node.nextPatch;
}
public static Vector3d WorldDeltaV(this ManeuverNode node)
{
return node.patch.Prograde(node.UT) * node.DeltaV.z + node.patch.RadialPlus(node.UT) * node.DeltaV.x +
-node.patch.NormalPlus(node.UT) * node.DeltaV.y;
}
// The part loop in VesselState could expose this, but it gets disabled when the RCS action group is disabled.
// This method is also useful when the RCS AG is off.
public static bool hasEnabledRCSModules(this Vessel vessel)
{
List<ModuleRCS> rcsModules = vessel.FindPartModulesImplementing<ModuleRCS>();
for (int m = 0; m < rcsModules.Count; m++)
{
ModuleRCS rcs = rcsModules[m];
if (rcs == null)
continue;
if (rcs.rcsEnabled && rcs.isEnabled && !rcs.isJustForShow)
return true;
}
return false;
}
}
}