forked from ferram4/Ferram-Aerospace-Research
-
Notifications
You must be signed in to change notification settings - Fork 32
/
VehicleAerodynamics.cs
2104 lines (1694 loc) · 88.1 KB
/
VehicleAerodynamics.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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Ferram Aerospace Research v0.16.0.5 "Mader"
=========================
Aerodynamics model for Kerbal Space Program
Copyright 2022, Michael Ferrara, aka Ferram4
This file is part of Ferram Aerospace Research.
Ferram Aerospace Research is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Ferram Aerospace Research is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Ferram Aerospace Research. If not, see <http://www.gnu.org/licenses/>.
Serious thanks: a.g., for tons of bugfixes and code-refactorings
stupid_chris, for the RealChuteLite implementation
Taverius, for correcting a ton of incorrect values
Tetryds, for finding lots of bugs and issues and not letting me get away with them, and work on example crafts
sarbian, for refactoring code for working with MechJeb, and the Module Manager updates
ialdabaoth (who is awesome), who originally created Module Manager
Regex, for adding RPM support
DaMichel, for some ferramGraph updates and some control surface-related features
Duxwing, for copy editing the readme
CompatibilityChecker by Majiir, BSD 2-clause http://opensource.org/licenses/BSD-2-Clause
Part.cfg changes powered by sarbian & ialdabaoth's ModuleManager plugin; used with permission
http://forum.kerbalspaceprogram.com/threads/55219
ModularFLightIntegrator by Sarbian, Starwaster and Ferram4, MIT: http://opensource.org/licenses/MIT
http://forum.kerbalspaceprogram.com/threads/118088
Toolbar integration powered by blizzy78's Toolbar plugin; used with permission
http://forum.kerbalspaceprogram.com/threads/60863
*/
using System;
using System.Collections.Generic;
using System.Threading;
using ferram4;
using FerramAerospaceResearch.FARPartGeometry;
using FerramAerospaceResearch.FARPartGeometry.GeometryModification;
using FerramAerospaceResearch.FARThreading;
using FerramAerospaceResearch.Settings;
using UnityEngine;
namespace FerramAerospaceResearch.FARAeroComponents
{
internal class VehicleAerodynamics
{
private static double[] indexSqrt = new double[1];
private static readonly object _commonLocker = new object();
private static Stack<FARAeroSection> currentlyUnusedSections;
private readonly Dictionary<Part, PartTransformInfo> _partWorldToLocalMatrixDict =
new Dictionary<Part, PartTransformInfo>(ObjectReferenceEqualityComparer<Part>.Default);
private readonly Dictionary<FARAeroPartModule, FARAeroPartModule.ProjectedArea> _moduleAndAreasDict =
new Dictionary<FARAeroPartModule, FARAeroPartModule.ProjectedArea>(ObjectReferenceEqualityComparer<
FARAeroPartModule>.Default);
private readonly List<FARAeroPartModule> includedModules = new List<FARAeroPartModule>();
private readonly List<float> weighting = new List<float>();
private VehicleVoxel _voxel;
private VoxelCrossSection[] _vehicleCrossSection = new VoxelCrossSection[1];
private double[] _ductedAreaAdjustment = new double[1];
private int _voxelCount;
private double _maxCrossSectionArea;
private Matrix4x4 _worldToLocalMatrix, _localToWorldMatrix;
private Vector3d _voxelLowerRightCorner;
private double _voxelElementSize;
private double _sectionThickness;
private Vector3 _vehicleMainAxis;
private List<Part> _vehiclePartList;
private List<GeometryPartModule> _currentGeoModules;
private List<FARAeroPartModule> _currentAeroModules = new List<FARAeroPartModule>();
private List<FARAeroPartModule> _newAeroModules = new List<FARAeroPartModule>();
private List<FARAeroPartModule> _currentUnusedAeroModules = new List<FARAeroPartModule>();
private List<FARAeroPartModule> _newUnusedAeroModules = new List<FARAeroPartModule>();
private List<FARAeroSection> _currentAeroSections = new List<FARAeroSection>();
private List<FARAeroSection> _newAeroSections = new List<FARAeroSection>();
private List<FARWingAerodynamicModel> _legacyWingModels = new List<FARWingAerodynamicModel>();
private List<ICrossSectionAdjuster> activeAdjusters = new List<ICrossSectionAdjuster>();
private int validSectionCount;
private int firstSection;
private bool visualizing;
public bool Voxelizing { get; private set; }
public VehicleAerodynamics()
{
if (currentlyUnusedSections == null)
currentlyUnusedSections = new Stack<FARAeroSection>();
}
public double Length { get; private set; }
public double MaxCrossSectionArea
{
get { return _maxCrossSectionArea; }
}
public bool CalculationCompleted { get; private set; }
public double SonicDragArea { get; private set; }
public double CriticalMach { get; private set; }
public double SectionThickness
{
get { return _sectionThickness; }
}
public void ForceCleanup()
{
if (_voxel != null)
{
_voxel.CleanupVoxel();
_voxel = null;
}
_vehicleCrossSection = null;
_ductedAreaAdjustment = null;
_currentAeroModules = null;
_newAeroModules = null;
_currentUnusedAeroModules = null;
_newUnusedAeroModules = null;
_currentAeroSections = null;
_newAeroSections = null;
_legacyWingModels = null;
_vehiclePartList = null;
activeAdjusters = null;
}
private static void GenerateIndexSqrtLookup(int numStations)
{
indexSqrt = new double[numStations];
for (int i = 0; i < numStations; i++)
indexSqrt[i] = Math.Sqrt(i);
}
//Used by other classes to update their aeroModule and aeroSection lists
//When these functions fire, all the data that was once restricted to the voxelization thread is passed over to the main unity thread
public void GetNewAeroData(
out List<FARAeroPartModule> aeroModules,
out List<FARAeroPartModule> unusedAeroModules,
out List<FARAeroSection> aeroSections,
out List<FARWingAerodynamicModel> legacyWingModel
)
{
CalculationCompleted = false;
List<FARAeroPartModule> tmpAeroModules = _currentAeroModules;
aeroModules = _currentAeroModules = _newAeroModules;
_newAeroModules = tmpAeroModules;
List<FARAeroSection> tmpAeroSections = _currentAeroSections;
aeroSections = _currentAeroSections = _newAeroSections;
_newAeroSections = tmpAeroSections;
tmpAeroModules = _currentUnusedAeroModules;
unusedAeroModules = _currentUnusedAeroModules = _newUnusedAeroModules;
_newUnusedAeroModules = tmpAeroModules;
legacyWingModel = LEGACY_UpdateWingAerodynamicModels();
}
public void GetNewAeroData(out List<FARAeroPartModule> aeroModules, out List<FARAeroSection> aeroSections)
{
CalculationCompleted = false;
List<FARAeroPartModule> tmpAeroModules = _currentAeroModules;
aeroModules = _currentAeroModules = _newAeroModules;
_newAeroModules = tmpAeroModules;
List<FARAeroSection> tmpAeroSections = _currentAeroSections;
aeroSections = _currentAeroSections = _newAeroSections;
_newAeroSections = tmpAeroSections;
tmpAeroModules = _currentUnusedAeroModules;
_currentUnusedAeroModules = _newUnusedAeroModules;
_newUnusedAeroModules = tmpAeroModules;
LEGACY_UpdateWingAerodynamicModels();
}
private List<FARWingAerodynamicModel> LEGACY_UpdateWingAerodynamicModels()
{
_legacyWingModels.Clear();
foreach (FARAeroPartModule aeroModule in _currentAeroModules)
{
Part p = aeroModule.part;
if (!p)
continue;
if (p.Modules.Contains<FARWingAerodynamicModel>())
{
var w = p.Modules.GetModule<FARWingAerodynamicModel>();
if (w is null)
continue;
w.isShielded = false;
w.NUFAR_ClearExposedAreaFactor();
_legacyWingModels.Add(w);
}
else if (p.Modules.Contains<FARControllableSurface>())
{
FARWingAerodynamicModel w = p.Modules.GetModule<FARControllableSurface>();
if (w is null)
continue;
w.isShielded = false;
w.NUFAR_ClearExposedAreaFactor();
_legacyWingModels.Add(w);
}
}
foreach (FARWingAerodynamicModel w in _legacyWingModels)
w.NUFAR_CalculateExposedAreaFactor();
foreach (FARWingAerodynamicModel w in _legacyWingModels)
w.NUFAR_SetExposedAreaFactor();
foreach (FARWingAerodynamicModel w in _legacyWingModels)
w.NUFAR_UpdateShieldingStateFromAreaFactor();
return _legacyWingModels;
}
//returns various data for use in displaying outside this class
public Matrix4x4 VoxelAxisToLocalCoordMatrix()
{
return Matrix4x4.TRS(Vector3.zero, Quaternion.FromToRotation(_vehicleMainAxis, Vector3.up), Vector3.one);
}
public double FirstSectionXOffset()
{
double offset = Vector3d.Dot(_vehicleMainAxis, _voxelLowerRightCorner);
offset += firstSection * _sectionThickness;
return offset;
}
public double[] GetPressureCoeffs()
{
var pressureCoeffs = new double[validSectionCount];
return GetPressureCoeffs(pressureCoeffs);
}
public double[] GetPressureCoeffs(double[] pressureCoeffs)
{
for (int i = firstSection; i < validSectionCount + firstSection; i++)
pressureCoeffs[i - firstSection] = _vehicleCrossSection[i].cpSonicForward;
return pressureCoeffs;
}
public double[] GetCrossSectionAreas()
{
var areas = new double[validSectionCount];
return GetCrossSectionAreas(areas);
}
public double[] GetCrossSectionAreas(double[] areas)
{
for (int i = firstSection; i < validSectionCount + firstSection; i++)
areas[i - firstSection] = _vehicleCrossSection[i].area;
return areas;
}
public double[] GetCrossSection2ndAreaDerivs()
{
var areaDerivs = new double[validSectionCount];
return GetCrossSection2ndAreaDerivs(areaDerivs);
}
public double[] GetCrossSection2ndAreaDerivs(double[] areaDerivs)
{
for (int i = firstSection; i < validSectionCount + firstSection; i++)
areaDerivs[i - firstSection] = _vehicleCrossSection[i].secondAreaDeriv;
return areaDerivs;
}
//Handling for display of debug voxels
private void ClearDebugVoxel()
{
_voxel.ClearVisualVoxels();
visualizing = false;
}
private void DisplayDebugVoxels(Matrix4x4 localToWorldMatrix)
{
_voxel.VisualizeVoxel(localToWorldMatrix);
visualizing = true;
}
public void DebugVisualizeVoxels(Matrix4x4 localToWorldMatrix)
{
if (visualizing)
ClearDebugVoxel();
else
DisplayDebugVoxels(localToWorldMatrix);
}
//This function will attempt to voxelize the vessel, as long as it isn't being voxelized currently all data that is on the Unity thread should be processed here before being passed to the other threads
public bool TryVoxelUpdate(
Matrix4x4 worldToLocalMatrix,
Matrix4x4 localToWorldMatrix,
int voxelCount,
List<Part> vehiclePartList,
List<GeometryPartModule> currentGeoModules,
bool updateGeometryPartModules = true,
Vessel vessel = null
)
{
//set to true when this function ends; only continue to voxelizing if the voxelization thread has not been queued
//this should catch conditions where this function is called again before the voxelization thread starts
if (Voxelizing)
return false;
//only continue if the voxelizing thread has not locked this object
if (!Monitor.TryEnter(this, 0))
return false;
try
{
//ensure that the main thread isn't going to try to read the updated section data while it is being worked with
CalculationCompleted = false;
//Bunch of voxel setup data
_voxelCount = voxelCount;
_worldToLocalMatrix = worldToLocalMatrix;
_localToWorldMatrix = localToWorldMatrix;
_vehiclePartList = vehiclePartList;
_currentGeoModules = currentGeoModules;
_partWorldToLocalMatrixDict.Clear();
foreach (GeometryPartModule g in _currentGeoModules)
{
_partWorldToLocalMatrixDict.Add(g.part, new PartTransformInfo(g.part.partTransform));
if (updateGeometryPartModules)
g.UpdateTransformMatrixList(_worldToLocalMatrix);
}
_vehicleMainAxis = CalculateVehicleMainAxis();
//If the voxel still exists, cleanup everything so we can continue;
visualizing = false;
_voxel?.CleanupVoxel();
//set flag so that this function can't run again before voxelizing completes and queue voxelizing thread
Voxelizing = true;
VoxelizationThreadpool.Instance.QueueVoxelization(() => CreateVoxel(vessel));
return true;
}
finally
{
Monitor.Exit(this);
}
}
//And this actually creates the voxel and then begins the aero properties determination
private void CreateVoxel(Vessel vessel = null)
{
lock (this) //lock this object to prevent race with main thread
{
try
{
//Actually voxelize it
_voxel = VehicleVoxel.CreateNewVoxel(_currentGeoModules, _voxelCount, vessel: vessel);
if (_vehicleCrossSection.Length < _voxel.MaxArrayLength)
_vehicleCrossSection = _voxel.EmptyCrossSectionArray;
_voxelLowerRightCorner = _voxel.LocalLowerRightCorner;
_voxelElementSize = _voxel.ElementSize;
CalculateVesselAeroProperties();
CalculationCompleted = true;
}
catch (Exception e)
{
ThreadSafeDebugLogger.Exception(e);
}
finally
{
//Always, when we finish up, if we're in flight, cleanup the voxel
if (HighLogic.LoadedSceneIsFlight && !VoxelizationSettings.DebugInFlight && _voxel != null)
{
_voxel.CleanupVoxel();
_voxel = null;
}
//And unset the flag so that the main thread can queue it again
Voxelizing = false;
}
}
}
private Vector3 CalculateVehicleMainAxis()
{
Vector3 axis = Vector3.zero;
var hitParts = new HashSet<Part>();
bool hasPartsForAxis = false;
foreach (Part p in _vehiclePartList)
{
if (p == null || hitParts.Contains(p))
continue;
// Could be left null if a launch clamp
var geoModule = p.Modules.GetModule<GeometryPartModule>();
hitParts.Add(p);
Vector3 tmpCandVector = Vector3.zero;
Vector3 candVector = Vector3.zero;
//intakes are probably pointing in the direction we're gonna be going in
if (p.Modules.Contains<ModuleResourceIntake>())
{
var intake = p.Modules.GetModule<ModuleResourceIntake>();
Transform intakeTrans = p.FindModelTransform(intake.intakeTransformName);
if (!(intakeTrans is null))
candVector = intakeTrans.TransformDirection(Vector3.forward);
}
//aggregate wings for later calc...
else if (geoModule == null ||
geoModule.IgnoreForMainAxis ||
p.Modules.Contains<FARWingAerodynamicModel>() ||
p.Modules.Contains<FARControllableSurface>() ||
p.Modules.Contains<ModuleWheelBase>() ||
p.Modules.Contains("KSPWheelBase"))
{
continue;
}
else
{
if (p.srfAttachNode != null && p.srfAttachNode.attachedPart != null)
{
tmpCandVector = p.srfAttachNode.orientation;
tmpCandVector = new Vector3(0,
Math.Abs(tmpCandVector.x) + Math.Abs(tmpCandVector.z),
Math.Abs(tmpCandVector.y));
if (p.srfAttachNode.position.sqrMagnitude.NearlyEqual(0) && tmpCandVector == Vector3.forward)
tmpCandVector = Vector3.up;
if (tmpCandVector.z > tmpCandVector.x && tmpCandVector.z > tmpCandVector.y)
tmpCandVector = Vector3.forward;
else if (tmpCandVector.y > tmpCandVector.x && tmpCandVector.y > tmpCandVector.z)
tmpCandVector = Vector3.up;
else
tmpCandVector = Vector3.right;
}
else
{
tmpCandVector = Vector3.up;
}
candVector = p.partTransform.TransformDirection(tmpCandVector);
}
foreach (Part q in p.symmetryCounterparts)
{
if (q == null || hitParts.Contains(q))
continue;
hitParts.Add(q);
//intakes are probably pointing in the direction we're gonna be going in
if (q.Modules.Contains<ModuleResourceIntake>())
{
var intake = q.Modules.GetModule<ModuleResourceIntake>();
Transform intakeTrans = q.FindModelTransform(intake.intakeTransformName);
if (!(intakeTrans is null))
candVector += intakeTrans.TransformDirection(Vector3.forward);
}
else
{
candVector += q.partTransform.TransformDirection(tmpCandVector);
}
}
//set that we will get a valid axis out of this operation
hasPartsForAxis = true;
candVector = _worldToLocalMatrix.MultiplyVector(candVector);
candVector.x = Math.Abs(candVector.x);
candVector.y = Math.Abs(candVector.y);
candVector.z = Math.Abs(candVector.z);
Vector3 size = geoModule.overallMeshBounds.size;
axis += size.x * size.y * size.z * candVector; //scale part influence by approximate size
}
if (axis == Vector3.zero)
axis = Vector3.up; //something in case things fall through somehow
if (!hasPartsForAxis)
return Vector3.up; //welp, no parts that we can rely on for determining the axis; fall back to up
float dotProdX = Math.Abs(Vector3.Dot(axis, Vector3.right));
float dotProdY = Math.Abs(Vector3.Dot(axis, Vector3.up));
float dotProdZ = Math.Abs(Vector3.Dot(axis, Vector3.forward));
if (dotProdY > 2 * dotProdX && dotProdY > 2 * dotProdZ)
return Vector3.up;
if (dotProdX > 2 * dotProdY && dotProdX > 2 * dotProdZ)
return Vector3.right;
if (dotProdZ > 2 * dotProdX && dotProdZ > 2 * dotProdY)
return Vector3.forward;
//Otherwise, now we need to use axis, since it's obviously not close to anything else
return axis.normalized;
}
//Smooths out area and area 2nd deriv distributions to deal with noise in the representation
private static unsafe void GaussianSmoothCrossSections(
VoxelCrossSection[] vehicleCrossSection,
double stdDevCutoff,
double lengthPercentFactor,
double sectionThickness,
double length,
int frontIndex,
int backIndex,
int areaSmoothingIterations,
int derivSmoothingIterations
)
{
double stdDev = length * lengthPercentFactor;
int numVals = (int)Math.Ceiling(stdDevCutoff * stdDev / sectionThickness);
if (numVals <= 1)
return;
double* gaussianFactors = stackalloc double[numVals];
double* prevUncorrectedVals = stackalloc double[numVals];
double* futureUncorrectedVals = stackalloc double[numVals - 1];
double invVariance = 1 / (stdDev * stdDev);
//calculate Gaussian factors for each of the points that will be hit
for (int i = 0; i < numVals; i++)
{
double factor = i * sectionThickness;
factor *= factor;
gaussianFactors[i] = Math.Exp(-0.5 * factor * invVariance);
}
//then sum them up...
double sum = 0;
for (int i = 0; i < numVals; i++)
if (i == 0)
sum += gaussianFactors[i];
else
sum += 2 * gaussianFactors[i];
double invSum = 1 / sum; //and then use that to normalize the factors
for (int i = 0; i < numVals; i++)
gaussianFactors[i] *= invSum;
//first smooth the area itself. This has a greater effect on the 2nd deriv due to the effect of noise on derivatives
for (int j = 0; j < areaSmoothingIterations; j++)
{
for (int i = 0; i < numVals; i++)
//set all the vals to 0 to prevent screwups between iterations
prevUncorrectedVals[i] = vehicleCrossSection[frontIndex].area;
for (int i = frontIndex; i <= backIndex; i++) //area smoothing pass
{
for (int k = numVals - 1; k > 0; k--)
prevUncorrectedVals[k] = prevUncorrectedVals[k - 1]; //shift prev vals down
double curValue = vehicleCrossSection[i].area;
prevUncorrectedVals[0] = curValue; //and set the central value
for (int k = 0; k < numVals - 1; k++) //update future vals
if (i + k < backIndex)
futureUncorrectedVals[k] = vehicleCrossSection[i + k + 1].area;
else
futureUncorrectedVals[k] = vehicleCrossSection[backIndex].area;
curValue = 0; //zero for coming calculations...
double borderScaling = 1; //factor to correct for the 0s lurking at the borders of the curve...
for (int k = 0; k < numVals; k++)
{
double val = prevUncorrectedVals[k];
double gaussianFactor = gaussianFactors[k];
curValue += gaussianFactor * val; //central and previous values;
if (val.NearlyEqual(0))
borderScaling -= gaussianFactor;
}
for (int k = 0; k < numVals - 1; k++)
{
double val = futureUncorrectedVals[k];
double gaussianFactor = gaussianFactors[k + 1];
curValue += gaussianFactor * val; //future values
if (val.NearlyEqual(0))
borderScaling -= gaussianFactor;
}
if (borderScaling > 0)
curValue /= borderScaling; //and now all of the 0s beyond the edge have been removed
vehicleCrossSection[i].area = curValue;
}
}
CalculateCrossSectionSecondDerivs(vehicleCrossSection, numVals, frontIndex, backIndex, sectionThickness);
//and now smooth the derivs
for (int j = 0; j < derivSmoothingIterations; j++)
{
for (int i = 0; i < numVals; i++)
//set all the vals to 0 to prevent screwups between iterations
prevUncorrectedVals[i] = vehicleCrossSection[frontIndex].secondAreaDeriv;
for (int i = frontIndex; i <= backIndex; i++) //deriv smoothing pass
{
for (int k = numVals - 1; k > 0; k--)
prevUncorrectedVals[k] = prevUncorrectedVals[k - 1]; //shift prev vals down
double curValue = vehicleCrossSection[i].secondAreaDeriv;
prevUncorrectedVals[0] = curValue; //and set the central value
for (int k = 0; k < numVals - 1; k++) //update future vals
if (i + k < backIndex)
futureUncorrectedVals[k] = vehicleCrossSection[i + k + 1].secondAreaDeriv;
else
futureUncorrectedVals[k] = vehicleCrossSection[backIndex].secondAreaDeriv;
curValue = 0; //zero for coming calculations...
double borderScaling = 1; //factor to correct for the 0s lurking at the borders of the curve...
for (int k = 0; k < numVals; k++)
{
double val = prevUncorrectedVals[k];
double gaussianFactor = gaussianFactors[k];
curValue += gaussianFactor * val; //central and previous values;
if (val.NearlyEqual(0))
borderScaling -= gaussianFactor;
}
for (int k = 0; k < numVals - 1; k++)
{
double val = futureUncorrectedVals[k];
double gaussianFactor = gaussianFactors[k + 1];
curValue += gaussianFactor * val; //future values
if (val.NearlyEqual(0))
borderScaling -= gaussianFactor;
}
if (borderScaling > 0)
curValue /= borderScaling; //and now all of the 0s beyond the edge have been removed
vehicleCrossSection[i].secondAreaDeriv = curValue;
}
}
}
//Based on http://www.holoborodko.com/pavel/downloads/NoiseRobustSecondDerivative.pdf
private static unsafe void CalculateCrossSectionSecondDerivs(
VoxelCrossSection[] vehicleCrossSection,
int oneSidedFilterLength,
int frontIndex,
int backIndex,
double sectionThickness
)
{
if (oneSidedFilterLength < 2)
{
oneSidedFilterLength = 2;
ThreadSafeDebugLogger.Info("Needed to adjust filter length up");
}
else if (oneSidedFilterLength > 40)
{
oneSidedFilterLength = 40;
ThreadSafeDebugLogger.Info("Reducing filter length to prevent overflow");
}
int M = oneSidedFilterLength;
int N = M * 2 + 1;
long* sK = stackalloc long[M + 1];
for (int i = 0; i <= M; i++)
sK[i] = CalculateSk(i, M, N);
double denom = Math.Pow(2, N - 3);
denom *= sectionThickness * sectionThickness;
denom = 1 / denom;
int lowIndex = Math.Max(frontIndex - 1, 0);
int highIndex = Math.Min(backIndex + 1, vehicleCrossSection.Length - 1);
for (int i = lowIndex + M; i <= highIndex - M; i++)
{
double secondDeriv = 0;
if (i >= frontIndex && i <= backIndex)
secondDeriv = sK[0] * vehicleCrossSection[i].area;
for (int k = 1; k <= M; k++)
{
double forwardArea, backwardArea;
if (i + k <= backIndex)
backwardArea = vehicleCrossSection[i + k].area;
else
backwardArea = 0;
if (i - k >= frontIndex)
forwardArea = vehicleCrossSection[i - k].area;
else
forwardArea = 0;
secondDeriv += sK[k] * (forwardArea + backwardArea);
}
vehicleCrossSection[i].secondAreaDeriv = secondDeriv * denom;
}
//forward difference
for (int i = frontIndex; i < lowIndex + M; i++)
{
double secondDeriv = 0;
secondDeriv += vehicleCrossSection[i].area;
if (i + 2 <= backIndex)
secondDeriv += vehicleCrossSection[i + 2].area;
if (i + 1 <= backIndex)
secondDeriv -= 2 * vehicleCrossSection[i + 1].area;
secondDeriv /= sectionThickness * sectionThickness;
vehicleCrossSection[i].secondAreaDeriv = secondDeriv;
}
//backward difference
for (int i = highIndex - M + 1; i <= backIndex; i++)
{
double secondDeriv = 0;
secondDeriv += vehicleCrossSection[i].area;
if (i - 2 >= frontIndex)
secondDeriv += vehicleCrossSection[i - 2].area;
if (i - 1 >= frontIndex)
secondDeriv -= 2 * vehicleCrossSection[i - 1].area;
secondDeriv /= sectionThickness * sectionThickness;
vehicleCrossSection[i].secondAreaDeriv = secondDeriv;
}
}
private static long CalculateSk(long k, int M, int N)
{
if (k > M)
return 0;
if (k == M)
return 1;
long val = (2 * N - 10) * CalculateSk(k + 1, M, N);
val -= (N + 2 * k + 3) * CalculateSk(k + 2, M, N);
val /= N - 2 * k - 1;
return val;
}
private void AdjustCrossSectionForAirDucting(
VoxelCrossSection[] vehicleCrossSection,
List<GeometryPartModule> geometryModules,
int front,
int back,
ref double maxCrossSectionArea
)
{
foreach (GeometryPartModule g in geometryModules)
g.GetICrossSectionAdjusters(activeAdjusters, _worldToLocalMatrix, _vehicleMainAxis);
double intakeArea = 0;
double engineExitArea = 0;
foreach (ICrossSectionAdjuster adjuster in activeAdjusters)
switch (adjuster)
{
case AirbreathingEngineCrossSectionAdjuster _:
engineExitArea += Math.Abs(adjuster.AreaRemovedFromCrossSection());
break;
case IntakeCrossSectionAdjuster _:
intakeArea += Math.Abs(adjuster.AreaRemovedFromCrossSection());
break;
case IntegratedIntakeEngineCrossSectionAdjuster _:
engineExitArea += Math.Abs(adjuster.AreaRemovedFromCrossSection());
intakeArea += Math.Abs(adjuster.AreaRemovedFromCrossSection());
break;
}
//if they exist, go through the calculations
if (!intakeArea.NearlyEqual(0) && !engineExitArea.NearlyEqual(0))
{
if (_ductedAreaAdjustment.Length != vehicleCrossSection.Length)
_ductedAreaAdjustment = new double[vehicleCrossSection.Length];
int frontMostIndex = -1, backMostIndex = -1;
//sweep through entire vehicle
for (int i = 0; i < _ductedAreaAdjustment.Length; i++)
{
double ductedArea = 0; //area based on the voxel size
double voxelCountScale = _voxelElementSize * _voxelElementSize;
//and all the intakes / engines
if (i >= front && i <= back)
{
foreach (ICrossSectionAdjuster adjuster in activeAdjusters)
{
if (adjuster.IntegratedCrossSectionIncreaseDecrease())
continue;
if (adjuster.AreaRemovedFromCrossSection().NearlyEqual(0))
continue;
Part p = adjuster.GetPart();
//see if you can find that in this section
if (!vehicleCrossSection[i]
.partSideAreaValues.TryGetValue(p, out VoxelCrossSection.SideAreaValues val))
continue;
if (adjuster.AreaRemovedFromCrossSection() > 0)
ductedArea += Math.Max(0,
val.crossSectionalAreaCount * voxelCountScale +
adjuster.AreaThreshold());
else
ductedArea -= Math.Max(0,
val.crossSectionalAreaCount * voxelCountScale +
adjuster.AreaThreshold());
}
ductedArea *= 0.75;
if (!ductedArea.NearlyEqual(0))
if (frontMostIndex < 0)
frontMostIndex = i;
else
backMostIndex = i;
}
_ductedAreaAdjustment[i] = ductedArea;
}
double tmpArea = _ductedAreaAdjustment[0];
for (int i = 1; i < _ductedAreaAdjustment.Length; i++)
{
double areaAdjustment = _ductedAreaAdjustment[i];
double prevAreaAdjustment = tmpArea;
tmpArea = areaAdjustment; //store for next iteration
if (areaAdjustment <= 0 || prevAreaAdjustment <= 0)
continue;
double areaChange = areaAdjustment - prevAreaAdjustment;
if (areaChange > 0)
//this transforms this into a change in area, but only for increases (intakes)
{
_ductedAreaAdjustment[i] = areaChange;
}
else
{
tmpArea = prevAreaAdjustment;
_ductedAreaAdjustment[i] = 0;
}
}
tmpArea = _ductedAreaAdjustment[_ductedAreaAdjustment.Length - 1];
for (int i = _ductedAreaAdjustment.Length - 1; i >= 0; i--)
{
double areaAdjustment = _ductedAreaAdjustment[i];
double prevAreaAdjustment = tmpArea;
tmpArea = areaAdjustment; //store for next iteration
if (areaAdjustment >= 0 || prevAreaAdjustment >= 0)
continue;
double areaChange = areaAdjustment - prevAreaAdjustment;
if (areaChange < 0)
//this transforms this into a change in area, but only for decreases (engines)
{
_ductedAreaAdjustment[i] = areaChange;
}
else
{
tmpArea = prevAreaAdjustment;
_ductedAreaAdjustment[i] = 0;
}
}
for (int i = _ductedAreaAdjustment.Length - 1; i >= 0; i--)
{
double areaAdjustment = 0;
for (int j = 0; j <= i; j++)
areaAdjustment += _ductedAreaAdjustment[j];
_ductedAreaAdjustment[i] = areaAdjustment;
}
for (int i = 0; i < vehicleCrossSection.Length; i++)
{
double ductedArea = 0; //area based on the voxel size
double actualArea = 0; //area based on intake and engine data
//and all the intakes / engines
foreach (ICrossSectionAdjuster adjuster in activeAdjusters)
{
if (!adjuster.IntegratedCrossSectionIncreaseDecrease())
continue;
Part p = adjuster.GetPart();
//see if you can find that in this section
if (!vehicleCrossSection[i]
.partSideAreaValues.TryGetValue(p, out VoxelCrossSection.SideAreaValues val))
continue;
ductedArea += val.crossSectionalAreaCount;
actualArea += adjuster.AreaRemovedFromCrossSection();
}
ductedArea *= _voxelElementSize * _voxelElementSize * 0.75;
if (Math.Abs(actualArea) < Math.Abs(ductedArea))
ductedArea = actualArea;
if (!ductedArea.NearlyEqual(0))
if (i < frontMostIndex)
frontMostIndex = i;
else if (i > backMostIndex)
backMostIndex = i;
_ductedAreaAdjustment[i] += ductedArea;
}
int index = _ductedAreaAdjustment.Length - 1;
double endVoxelArea = _ductedAreaAdjustment[index];
double currentArea = endVoxelArea;
while (currentArea > 0)
{
currentArea -= endVoxelArea;
_ductedAreaAdjustment[index] = currentArea;
--index;
if (index < 0)
break;
currentArea = _ductedAreaAdjustment[index];
}
maxCrossSectionArea = 0;
//put upper limit on area lost
for (int i = 0; i < vehicleCrossSection.Length; i++)
{
double areaUnchanged = vehicleCrossSection[i].area;
double areaChanged = -_ductedAreaAdjustment[i];