forked from Biotronic/TweakScale
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScaleExponents.cs
432 lines (384 loc) · 16.1 KB
/
ScaleExponents.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace TweakScale
{
[KSPAddon(KSPAddon.Startup.MainMenu, false)]
class ScaleExponentsLoader : RescalableRegistratorAddon
{
public override void OnStart()
{
ScaleExponents.LoadGlobalExponents();
}
}
public class ScaleExponents
{
struct ScalingMode
{
public readonly string Exponent;
public readonly bool UseRelativeScaling;
public ScalingMode(string exponent, bool useRelativeScaling)
: this()
{
Exponent = exponent;
UseRelativeScaling = useRelativeScaling;
}
}
private readonly string _id;
private readonly string _name;
private readonly Dictionary<string, ScalingMode> _exponents;
private readonly List<string> _ignores;
private readonly Dictionary<string, ScaleExponents> _children;
private static Dictionary<string, ScaleExponents> _globalList;
private static bool _globalListLoaded;
private const string ExponentConfigName = "TWEAKSCALEEXPONENTS";
private static bool IsExponentBlock(ConfigNode node)
{
return node.name == ExponentConfigName || node.name == "MODULE";
}
/// <summary>
/// Load all TWEAKSCALEEXPONENTS that are globally defined.
/// </summary>
public static void LoadGlobalExponents()
{
if (_globalListLoaded)
return;
var tmp = GameDatabase.Instance.GetConfigs(ExponentConfigName)
.Select(a => new ScaleExponents(a.config));
_globalList = tmp
.GroupBy(a => a._id)
.Select(a => a.Aggregate(Merge))
.ToDictionary(a => a._id, a => a);
_globalListLoaded = true;
}
/// <summary>
/// Creates modules copy of the ScaleExponents.
/// </summary>
/// <returns>A copy of the object on which the function is called.</returns>
private ScaleExponents Clone()
{
return new ScaleExponents(this);
}
private ScaleExponents(ScaleExponents source)
{
_id = source._id;
_exponents = source._exponents.Clone();
_children = source
._children
.Select(a => new KeyValuePair<string, ScaleExponents>(a.Key, a.Value.Clone()))
.ToDictionary(a => a.Key, a => a.Value);
_ignores = new List<string>(source._ignores);
}
private ScaleExponents(ConfigNode node, ScaleExponents source = null)
{
_id = IsExponentBlock(node) ? node.GetValue("name") : node.name;
_name = node.GetValue("name");
if (_id == null)
{
_id = "";
}
if (IsExponentBlock(node))
{
if (string.IsNullOrEmpty(_id))
{
_id = "Part";
_name = "Part";
}
}
_exponents = new Dictionary<string, ScalingMode>();
_children = new Dictionary<string, ScaleExponents>();
_ignores = new List<string>();
foreach (var value in node.values.OfType<ConfigNode.Value>().Where(a=>a.name != "name"))
{
if (value.name.StartsWith("!"))
{
_exponents[value.name.Substring(1)] = new ScalingMode(value.value, true);
}
else if (value.name.Equals("-ignore"))
{
_ignores.Add(value.value);
}
else
{
_exponents[value.name] = new ScalingMode(value.value, false);
}
}
foreach (var childNode in node.nodes.OfType<ConfigNode>())
{
_children[childNode.name] = new ScaleExponents(childNode);
}
if (source != null)
{
Merge(this, source);
}
}
/// <summary>
/// Merge two ScaleExponents. All the values in <paramref name="source"/> that are not already present in <paramref name="destination"/> will be added to <paramref name="destination"/>
/// </summary>
/// <param name="destination">The ScaleExponents to update.</param>
/// <param name="source">The ScaleExponents to add to <paramref name="destination"/></param>
/// <returns>The updated exponentValue of <paramref name="destination"/>. Note that this exponentValue is also changed, so using the return exponentValue is not necessary.</returns>
public static ScaleExponents Merge(ScaleExponents destination, ScaleExponents source)
{
if (destination._id != source._id)
{
Tools.LogWf("Wrong merge target! A name {0}, B name {1}", destination._id, source._id);
}
foreach (var value in source._exponents.Where(value => !destination._exponents.ContainsKey(value.Key)))
{
destination._exponents[value.Key] = value.Value;
}
foreach (var value in source._ignores.Where(value => !destination._ignores.Contains(value)))
{
destination._ignores.Add(value);
}
foreach (var child in source._children)
{
if (destination._children.ContainsKey(child.Key))
{
Merge(destination._children[child.Key], child.Value);
}
else
{
destination._children[child.Key] = child.Value.Clone();
}
}
return destination;
}
/// <summary>
/// Rescales destination exponentValue according to its associated exponent.
/// </summary>
/// <param name="current">The current exponentValue.</param>
/// <param name="baseValue">The unscaled exponentValue, gotten from the prefab.</param>
/// <param name="name">The name of the field.</param>
/// <param name="scalingMode">Information on exactly how to scale this.</param>
/// <param name="factor">The rescaling factor.</param>
/// <returns>The rescaled exponentValue.</returns>
static private void Rescale(MemberUpdater current, MemberUpdater baseValue, string name, ScalingMode scalingMode, ScalingFactor factor)
{
var exponentValue = scalingMode.Exponent;
var exponent = double.NaN;
double[] values = null;
if (exponentValue.Contains(','))
{
if (factor.index == -1)
{
Tools.LogWf("Value list used for freescale part exponent field {0}: {1}", name, exponentValue);
return;
}
values = Tools.ConvertString(exponentValue, new double[] { });
if (values.Length <= factor.index)
{
Tools.LogWf("Too few values given for {0}. Expected at least {1}, got {2}: {3}", name, factor.index + 1, values.Length, exponentValue);
return;
}
}
else if (!double.TryParse(exponentValue, out exponent))
{
Tools.LogWf("Invalid exponent {0} for field {1}", exponentValue, name);
}
if (current.MemberType.GetInterface("IList") != null)
{
var v = (IList)current.Value;
var v2 = (IList)baseValue.Value;
for (var i = 0; i < v.Count && i < v2.Count; ++i)
{
if (values != null)
{
v[i] = values[factor.index];
}
else if (!double.IsNaN(exponent))
{
if (v[i] is float)
{
v[i] = (float)v2[i] * Math.Pow(factor.relative.linear, exponent);
}
else if (v[i] is double)
{
v[i] = (double)v2[i] * Math.Pow(factor.relative.linear, exponent);
}
else if (v[i] is Vector3)
{
v[i] = (Vector3)v2[i] * (float)Math.Pow(factor.relative.linear, exponent);
}
}
}
}
if (values != null)
{
if (current.MemberType == typeof (float))
{
current.Set((float)values[factor.index]);
}
else if (current.MemberType == typeof(float))
{
current.Set(values[factor.index]);
}
}
else if (!double.IsNaN(exponent))
{
current.Scale(Math.Pow(scalingMode.UseRelativeScaling ? factor.relative.linear : factor.absolute.linear, exponent), baseValue);
}
}
private bool ShouldIgnore(Part part)
{
return _ignores.Any(v => part.Modules.Contains(v));
}
/// <summary>
/// Rescale the field of <paramref name="obj"/> according to the exponents of the ScaleExponents and <paramref name="factor"/>.
/// </summary>
/// <param name="obj">The object to rescale.</param>
/// <param name="baseObj">The corresponding object in the prefab.</param>
/// <param name="factor">The new scale.</param>
/// <param name="part">The part the object is on.</param>
private void UpdateFields(object obj, object baseObj, ScalingFactor factor, Part part)
{
if ((object)obj == null)
return;
if (obj is PartModule && obj.GetType().Name != _id)
{
Tools.LogWf("This ScaleExponent is intended for {0}, not {1}", _id, obj.GetType().Name);
return;
}
if (ShouldIgnore(part))
return;
var enumerable = obj as IEnumerable;
if (enumerable != null)
{
UpdateEnumerable(enumerable, (IEnumerable)baseObj, factor, part);
return;
}
foreach (var nameExponentKV in _exponents)
{
var value = MemberUpdater.Create(obj, nameExponentKV.Key);
if (value == null)
{
continue;
}
var baseValue = nameExponentKV.Value.UseRelativeScaling ? null : MemberUpdater.Create(baseObj, nameExponentKV.Key);
Rescale(value, baseValue ?? value, nameExponentKV.Key, nameExponentKV.Value, factor);
}
foreach (var child in _children)
{
var childName = child.Key;
var childObjField = MemberUpdater.Create(obj, childName);
if (childObjField == null || child.Value == null)
continue;
var baseChildObjField = MemberUpdater.Create(baseObj, childName);
child.Value.UpdateFields(childObjField.Value, (baseChildObjField ?? childObjField).Value, factor, part);
}
}
/// <summary>
/// For IEnumerables (arrays, lists, etc), we want to update the items, not the list.
/// </summary>
/// <param name="obj">The list whose items we want to update.</param>
/// <param name="prefabObj">The corresponding list in the prefab.</param>
/// <param name="factor">The scaling factor.</param>
/// <param name="part">The part the object is on.</param>
private void UpdateEnumerable(IEnumerable obj, IEnumerable prefabObj, ScalingFactor factor, Part part = null)
{
var prefabObjects = prefabObj as object[] ?? prefabObj.Cast<object>().ToArray();
var urrentObjects = obj as object[] ?? obj.Cast<object>().ToArray();
if (prefabObj == null || urrentObjects.Length != prefabObjects.Length)
{
prefabObjects = ((object)null).Repeat().Take(urrentObjects.Length).ToArray();
}
foreach (var item in urrentObjects.Zip(prefabObjects, ModuleAndPrefab.Create))
{
if (!string.IsNullOrEmpty(_name) && _name != "*") // Operate on specific elements, not all.
{
var childName = item.Current.GetType().GetField("name");
if (childName != null)
{
if (childName.FieldType != typeof(string) || (string)childName.GetValue(item.Current) != _name)
{
continue;
}
}
}
UpdateFields(item.Current, item.Prefab, factor, part);
}
}
struct ModuleAndPrefab
{
public object Current { get; private set; }
public object Prefab { get; private set; }
private ModuleAndPrefab(object current, object prefab)
: this()
{
Current = current;
Prefab = prefab;
}
public static ModuleAndPrefab Create(object current, object prefab)
{
return new ModuleAndPrefab(current, prefab);
}
}
struct ModulesAndExponents
{
public object Current { get; private set; }
public object Prefab { get; private set; }
public ScaleExponents Exponents { get; private set; }
private ModulesAndExponents(ModuleAndPrefab modules, ScaleExponents exponents)
: this()
{
Current = modules.Current;
Prefab = modules.Prefab;
Exponents = exponents;
}
public static ModulesAndExponents Create(ModuleAndPrefab modules, KeyValuePair<string, ScaleExponents> exponents)
{
return new ModulesAndExponents(modules, exponents.Value);
}
}
public static void UpdateObject(Part part, Part prefabObj, Dictionary<string, ScaleExponents> exponents, ScalingFactor factor)
{
if (exponents.ContainsKey("Part"))
{
exponents["Part"].UpdateFields(part, prefabObj, factor, part);
}
var modulePairs = part.Modules.Zip(prefabObj.Modules, ModuleAndPrefab.Create);
var modulesAndExponents = modulePairs.Join(exponents,
modules => ((PartModule)modules.Current).moduleName,
exps => exps.Key,
ModulesAndExponents.Create).ToArray();
foreach (var modExp in modulesAndExponents)
{
modExp.Exponents.UpdateFields(modExp.Current, modExp.Prefab, factor, part);
}
}
public static Dictionary<string, ScaleExponents> CreateExponentsForModule(ConfigNode node, Dictionary<string, ScaleExponents> parent)
{
var local = node.nodes
.OfType<ConfigNode>()
.Where(IsExponentBlock)
.Select(a => new ScaleExponents(a))
.ToDictionary(a => a._id);
foreach (var pExp in parent.Values)
{
if (local.ContainsKey(pExp._id))
{
Merge(local[pExp._id], pExp);
}
else
{
local[pExp._id] = pExp;
}
}
foreach (var gExp in _globalList.Values)
{
if (local.ContainsKey(gExp._id))
{
Merge(local[gExp._id], gExp);
}
else
{
local[gExp._id] = gExp;
}
}
return local;
}
}
}