-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsurf_ramp_optimizer.cpp
1738 lines (1423 loc) · 49.8 KB
/
surf_ramp_optimizer.cpp
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
#include "surf_ramp_optimizer.h"
#include <cmath>
#include <algorithm>
#include <memory>
#include <mutex>
#include <unordered_map>
#include <vector>
#include <optional>
#include <functional>
#include <cassert>
#include <immintrin.h>
#include <limits>
// Forward declarations
class SurfRampOptimizer;
class CBrachistochroneOptimizer;
class PlayerMovementTracking;
class BVHNode;
class Matrix;
class Vector;
class Ramp;
class CBaseEntity;
namespace CollisionDetection {}
namespace NumericalMethods {}
namespace MathUtils {}
namespace Optimization {}
namespace Pathfinding {}
// Global constants
constexpr float MAX_PLAYER_DIST_TO_PATH = 50.0f;
constexpr float GRADIENT_TOLERANCE = 1e-6f;
constexpr int MAX_OPTIMIZATION_ITERATIONS = 100;
// Global variables
SurfRampOptimizer g_SurfRampOptimizer;
SMEXT_LINK(&g_SurfRampOptimizer);
IForward* g_fwdOnStartTouchRamp = nullptr;
IGameConfig* g_pGameConf = nullptr;
ISDKTools* g_pSDKTools = nullptr;
IServerGameEnts* gameents = nullptr;
IGameHelpers* g_pGameHelpers = nullptr;
CGlobalVars* gpGlobals = nullptr;
IBinTools* g_pBinTools = nullptr;
IGameMovement* g_pGameMovement = nullptr;
IPlayerInfoManager* playerinfomngr = nullptr;
std::mutex g_SurfRampsMutex;
std::mutex g_RampCacheMutex;
std::vector<std::unique_ptr<CBrachistochroneOptimizer>> g_SurfRamps;
BVHNode* g_BVHRoot = nullptr;
std::unordered_map<CBaseEntity*, Ramp> g_RampCache;
// SurfRampOptimizer methods
bool SurfRampOptimizer::SDK_OnLoad(char* error, size_t maxlength, bool late)
{
if (!SetupGameInterfaces(error, maxlength))
{
return false;
}
if (!LoadConfigurations(error, maxlength))
{
return false;
}
InitializeDataStructures();
return true;
}
bool SurfRampOptimizer::SetupGameInterfaces(char* error, size_t maxlength)
{
gameents = gamehelpers->GetIServerGameEnts();
g_pGameHelpers = gamehelpers;
gpGlobals = gamehelpers->GetGlobalVars();
g_pSDKTools = sdktools;
g_pBinTools = g_pSDKTools->GetBinTools();
g_pGameMovement = g_pBinTools->GetGameMovement();
playerinfomngr = playerhelpers->GetPlayerInfoManager();
if (!gameents || !g_pGameHelpers || !gpGlobals || !g_pSDKTools || !g_pBinTools || !g_pGameMovement || !playerinfomngr)
{
snprintf(error, maxlength, "Failed to get required game interfaces");
return false;
}
return true;
}
bool SurfRampOptimizer::LoadConfigurations(char* error, size_t maxlength)
{
sharesys->AddDependency(myself, "bintools.ext", true, true);
sharesys->AddDependency(myself, "sdktools.ext", true, true);
sharesys->AddDependency(myself, "playerhelpers.ext", true, true);
sharesys->RegisterLibrary(myself, "surframpoptimizer");
return true;
}
void SurfRampOptimizer::InitializeDataStructures()
{
g_SurfRamps.clear();
delete g_BVHRoot;
g_BVHRoot = new BVHNode(Vector(-1000.0f, -1000.0f, -1000.0f), Vector(1000.0f, 1000.0f, 1000.0f));
}
void SurfRampOptimizer::SDK_OnUnload()
{
g_pSDKTools->RemoveEntityListener(&g_SurfRampOptimizer);
{
std::lock_guard<std::mutex> lock(g_SurfRampsMutex);
g_SurfRamps.clear();
}
delete g_BVHRoot;
g_BVHRoot = nullptr;
}
void SurfRampOptimizer::SDK_OnAllLoaded()
{
SM_GET_LATE_IFACE(SDKTOOLS, g_pSDKTools);
SM_GET_LATE_IFACE(BINTOOLS, g_pBinTools);
if (!g_pSDKTools || !g_pBinTools)
{
smutils->LogError(myself, "Failed to get bin tools or SDK tools interfaces");
return;
}
g_pGameMovement = g_pBinTools->GetGameMovement();
if (!g_pGameMovement)
{
smutils->LogError(myself, "Failed to get IGameMovement interface");
return;
}
g_fwdOnStartTouchRamp = g_pGameHelpers->CreateForward("OnStartTouchRamp", ET_Event, 2, nullptr);
g_pSDKTools->AddEntityListener(&g_SurfRampOptimizer);
CollisionDetection::Initialize();
smutils->LogMessage(myself, "SurfRampOptimizer is loaded (Server Tickrate: %.2f)", gpGlobals->tickRate);
}
bool SurfRampOptimizer::QueryRunning(char* error, size_t maxlength)
{
SM_CHECK_IFACE(SDKTOOLS, g_pSDKTools);
SM_CHECK_IFACE(BINTOOLS, g_pBinTools);
return true;
}
void SurfRampOptimizer::OnEntityCreated(CBaseEntity* pEntity, const char* classname)
{
if (!pEntity || !classname || std::string(classname) != "surf_ramp")
{
return;
}
Ramp ramp = GetRampFromEntity(pEntity);
auto optimizer = std::make_unique<CBrachistochroneOptimizer>(ramp, pEntity);
{
std::lock_guard<std::mutex> lock(g_SurfRampsMutex);
pEntity->SetTouch(SurfRampOptimizer::OnStartTouch);
g_SurfRamps.push_back(std::move(optimizer));
}
CollisionDetection::InsertRamp(&ramp);
}
void SurfRampOptimizer::OnEntityDestroyed(CBaseEntity* pEntity)
{
std::lock_guard<std::mutex> lock(g_SurfRampsMutex);
g_SurfRamps.erase(std::remove_if(g_SurfRamps.begin(), g_SurfRamps.end(), [&](const auto& optimizer)
{
return optimizer->GetRamp().startPoint == pEntity->GetAbsOrigin();
}), g_SurfRamps.end());
{
std::lock_guard<std::mutex> lock(g_RampCacheMutex);
g_RampCache.erase(pEntity);
}
}
void SurfRampOptimizer::OnStartTouch(CBaseEntity* pOther)
{
if (!pOther || !pOther->IsPlayer())
{
return;
}
if (pOther->GetClassName() == "surf_ramp")
{
FireOnStartTouchRampForward(pOther, gameents->BaseEntityToEdict(this));
Ramp ramp;
{
std::lock_guard<std::mutex> lock(g_RampCacheMutex);
auto it = g_RampCache.find(this);
if (it != g_RampCache.end())
{
ramp = it->second;
}
}
if (ramp.startPoint.Length() > 0)
{
CBasePlayer* pPlayer = static_cast<CBasePlayer*>(pOther);
if (pPlayer)
{
Optimize(pPlayer, ramp);
}
}
for (const auto& bc : g_SurfRamps)
{
if (bc->GetRamp() == ramp)
{
Vector pos = pOther->GetAbsOrigin();
Vector vel = pOther->GetAbsVelocity();
float tickInterval = 1.0f / gpGlobals->tickRate;
std::vector<Vector> points = bc->Optimize(pos, vel, tickInterval);
bc->Update(pos, vel, pOther->GetAbsVelocity() - vel, tickInterval);
break;
}
}
}
}
bool SurfRampOptimizer::SDK_OnMetamodLoad(ISmmAPI* ismm, char* error, size_t maxlen, bool late)
{
GET_V_IFACE_CURRENT(GetEngineFactory, g_pCVar, ICvar, CVAR_INTERFACE_VERSION);
GET_V_IFACE_CURRENT(GetEngineFactory, gameents, IServerGameEnts, INTERFACEVERSION_SERVERGAMEENTS);
GET_V_IFACE_ANY(GetServerFactory, playerhelpers, IPlayerInfoManager, INTERFACEVERSION_PLAYERINFOMANAGER);
return true;
}
// CBrachistochroneOptimizer methods
CBrachistochroneOptimizer::CBrachistochroneOptimizer(const Ramp& ramp, CBaseEntity* player)
: m_Ramp(ramp)
, m_Player(player)
, m_PlayerTracker(MAX_PLAYER_DIST_TO_PATH)
{
m_AirAccelerate = gpGlobals->airAccelerate;
m_Gravity = gpGlobals->gravity;
}
std::vector<Vector> CBrachistochroneOptimizer::Optimize(const Vector& startPos, const Vector& startVel, float tickInterval)
{
float pathTime = NumericalMethods::CalculateBrachistochronePathTime(startPos, m_Ramp.endPoint, m_Gravity);
if (pathTime <= 0.0f)
{
return {};
}
const float timeStep = tickInterval;
Vector prevPos = startPos;
Vector currVel = startVel;
Vector currAccel(0.0f, 0.0f, -m_Gravity);
m_OptimizedPath.clear();
m_OptimizedPath.push_back(startPos);
for (float t = 0.0f; t <= pathTime; t += timeStep)
{
Vector pos = NumericalMethods::SolveBrachistochrone(startPos, m_Ramp.endPoint, t, m_Gravity, m_AirAccelerate);
Vector accelDir = (pos - prevPos).Normalized();
float wishSpeed = currVel.Length();
float maxWishSpeed = g_pCVar->FindVar("sv_air_max_wishspeed")->GetFloat();
float maxVelocity = g_pCVar->FindVar("sv_maxvelocity")->GetFloat();
float accelAmount = m_AirAccelerate * timeStep * std::min(wishSpeed, maxWishSpeed);
currVel += accelDir * accelAmount - currAccel * timeStep;
currAccel = accelDir * accelAmount / timeStep;
if (currVel.Length() > maxVelocity)
{
currVel = currVel.Normalized() * maxVelocity;
}
trace_t trace;
TracePlayerBBox(prevPos, pos, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, trace);
if (trace.fraction == 1.0f)
{
if (IsPathValid(pos))
{
m_OptimizedPath.push_back(pos);
prevPos = pos;
}
else
{
break;
}
}
else
{
// collision detected, perform collision resolution
Vector move = pos - prevPos;
//PerformFlyCollisionResolution(trace, move);
pos = trace.endpos;
if (IsPathValid(pos))
{
m_OptimizedPath.push_back(pos);
prevPos = pos;
}
else
{
break;
}
}
}
if (IsPathValid(m_Ramp.endPoint))
{
m_OptimizedPath.push_back(m_Ramp.endPoint);
}
m_OptimizedPath = Optimization::OptimizePath(m_OptimizedPath, m_Ramp, m_Gravity, m_AirAccelerate);
return m_OptimizedPath;
}
void CBrachistochroneOptimizer::Update(const Vector& playerPos, const Vector& playerVel, const Vector& playerAccel, float tickInterval)
{
m_PlayerTracker.UpdatePlayerState(playerPos, playerVel, playerAccel, tickInterval);
std::vector<Ramp> ramps;
{
std::lock_guard<std::mutex> lock(g_RampCacheMutex);
for (auto it = g_RampCache.begin(); it != g_RampCache.end(); ++it)
{
ramps.push_back(it->second);
}
}
m_PlayerTracker.RecalibratePath(m_OptimizedPath, ramps, *this, tickInterval);
}
void CBrachistochroneOptimizer::PerformFlyCollisionResolution(trace_t& trace, Vector& move)
{
if (!m_Player) return;
Vector& velocity = m_Player->GetVelocity();
float dotProduct = DotProduct(velocity, trace.plane.normal);
// Calculate the reflection direction of the velocity based on the collision normal
Vector reflectionDirection = velocity - 2 * dotProduct * trace.plane.normal;
// Ensure that the reflection doesn't result in the player going back into the collision surface
if (DotProduct(reflectionDirection, trace.plane.normal) > 0) {
// Maintain the original speed but change the direction to the reflection direction
velocity = reflectionDirection.Normalized() * velocity.Length();
} else {
// If the reflection direction is still pointing into the surface, just invert the velocity
// This might happen with glancing blows where the reflection calculation isn't enough
velocity = -velocity;
}
// Update the player's velocity with the new calculated value
m_Player->SetVelocity(velocity);
// Optionally, handle any gameplay effects or animations that result from the collision
m_Player->OnCollision(trace.plane.normal);
}
bool CBrachistochroneOptimizer::IsPathValid(const Vector& point) const
{
return !CollisionDetection::Intersects(point, m_Ramp);
}
const Ramp& CBrachistochroneOptimizer::GetRamp() const
{
return m_Ramp;
}
const std::vector<Vector>& CBrachistochroneOptimizer::GetPath() const
{
return m_OptimizedPath;
}
CBaseEntity* CBrachistochroneOptimizer::GetPlayer() const
{
return m_Player;
}
// PlayerMovementTracking methods
PlayerMovementTracking::PlayerMovementTracking(float maxDeviationDistance, size_t bufferCapacity)
: m_MaxDeviationDistance(maxDeviationDistance)
, m_Positions(bufferCapacity)
, m_Velocities(bufferCapacity)
, m_Accelerations(bufferCapacity)
, m_TimeIntervals(bufferCapacity)
{}
void PlayerMovementTracking::UpdatePlayerState(const Vector& position, const Vector& velocity, const Vector& acceleration, float tickInterval)
{
m_Positions.push_back(position);
m_Velocities.push_back(velocity);
m_Accelerations.push_back(acceleration);
m_TimeIntervals.push_back(tickInterval);
if (m_Positions.size() > m_Positions.capacity())
{
m_Positions.pop_front();
m_Velocities.pop_front();
m_Accelerations.pop_front();
m_TimeIntervals.pop_front();
}
}
Vector PlayerMovementTracking::EstimatePlayerPosition(float timeStep) const
{
if (m_Positions.empty())
{
return {};
}
size_t n = m_Positions.size() - 1;
Vector position = m_Positions[n];
Vector velocity = m_Velocities[n];
Vector acceleration = m_Accelerations[n];
float timeInterval = m_TimeIntervals[n];
return position + velocity * timeStep + 0.5f * acceleration * timeStep * timeStep;
}
bool PlayerMovementTracking::HasDeviatedFromPath(const std::vector<Vector>& path) const
{
if (m_Positions.empty() || path.empty())
{
return false;
}
Vector playerPos = m_Positions.back();
float minDistance = std::numeric_limits<float>::max();
for (const Vector& point : path)
{
float distance = (playerPos - point).LengthSqr();
minDistance = std::min(minDistance, distance);
}
return minDistance > m_MaxDeviationDistance * m_MaxDeviationDistance;
}
void PlayerMovementTracking::RecalibratePath(const std::vector<Vector>& currentPath, const std::vector<Ramp>& ramps, CBrachistochroneOptimizer& optimizer, float tickInterval)
{
if (HasDeviatedFromPath(currentPath))
{
Vector currentPos = m_Positions.back();
Vector currentVel = m_Velocities.back();
Vector goal = currentPath.back();
std::vector<Vector> newPath = Pathfinding::Pathfinding(currentPos, goal, ramps);
if (!newPath.empty())
{
optimizer.m_OptimizedPath = optimizer.Optimize(currentPos, currentVel, tickInterval);
}
}
}
// BVHNode methods
BVHNode::BVHNode(const Vector& min, const Vector& max)
: minExtents(min)
, maxExtents(max)
, left(nullptr)
, right(nullptr)
{}
BVHNode::~BVHNode()
{
delete left;
delete right;
}
void BVHNode::Insert(Ramp* ramp)
{
if (!left && !right)
{
objects.push_back(ramp);
if (objects.size() > 4)
{
Vector center = (minExtents + maxExtents) * 0.5f;
left = new BVHNode(minExtents, center);
right = new BVHNode(center, maxExtents);
for (Ramp* obj : objects)
{
if (obj->minExtents.x < center.x)
{
left->Insert(obj);
}
else
{
right->Insert(obj);
}
}
objects.clear();
}
}
else
{
if (ramp->minExtents.x < left->maxExtents.x)
{
left->Insert(ramp);
}
else
{
right->Insert(ramp);
}
}
}
std::vector<Ramp*> BVHNode::Query(const Vector& point) const
{
std::vector<Ramp*> result;
if (point.x >= minExtents.x && point.x <= maxExtents.x &&
point.y >= minExtents.y && point.y <= maxExtents.y &&
point.z >= minExtents.z && point.z <= maxExtents.z)
{
result.insert(result.end(), objects.begin(), objects.end());
if (left)
{
std::vector<Ramp*> leftResult = left->Query(point);
result.insert(result.end(), leftResult.begin(), leftResult.end());
}
if (right)
{
std::vector<Ramp*> rightResult = right->Query(point);
result.insert(result.end(), rightResult.begin(), rightResult.end());
}
}
return result;
}
// CollisionDetection methods
void CollisionDetection::Initialize()
{
g_BVHRoot = new BVHNode(Vector(-1000.0f, -1000.0f, -1000.0f), Vector(1000.0f, 1000.0f, 1000.0f));
}
void CollisionDetection::Shutdown()
{
delete g_BVHRoot;
g_BVHRoot = nullptr;
}
void CollisionDetection::InsertRamp(Ramp* ramp)
{
g_BVHRoot->Insert(ramp);
}
bool CollisionDetection::Intersects(const Vector& point, const Ramp& ramp)
{
Ramp pointRamp;
pointRamp.startPoint = point;
pointRamp.endPoint = point;
pointRamp.width = 0.0f;
return GJKIntersection(pointRamp, ramp);
}
bool CollisionDetection::GJKIntersection(const Ramp& ramp1, const Ramp& ramp2)
{
Vector support[4];
Vector direction = ramp2.startPoint - ramp1.startPoint;
support[0] = SupportPoint(ramp1, ramp2, direction);
support[1] = SupportPoint(ramp1, ramp2, -direction);
Vector simplex[3];
simplex[0] = support[0];
simplex[1] = support[1];
direction = MathUtils::SIMDCrossProduct(simplex[1] - simplex[0], -simplex[0]);
int index = 2;
while (true)
{
support[index] = SupportPoint(ramp1, ramp2, direction);
if (MathUtils::SIMDDotProduct(support[index], direction) < 0)
{
return false;
}
simplex[index] = support[index];
if (UpdateSimplex(simplex, direction, index))
{
return true;
}
index = (index + 1) % 3;
}
}
Vector CollisionDetection::SupportPoint(const Ramp& ramp1, const Ramp& ramp2, const Vector& direction)
{
Vector support1 = FarthestPointInDirection(ramp1, direction);
Vector support2 = FarthestPointInDirection(ramp2, -direction);
return support1 - support2;
}
Vector CollisionDetection::FarthestPointInDirection(const Ramp& ramp, const Vector& direction)
{
float maxDot = -std::numeric_limits<float>::max();
Vector farthestPoint;
std::vector<Vector> vertices =
{
ramp.startPoint,
ramp.endPoint,
ramp.startPoint + Vector(0, ramp.width, 0),
ramp.endPoint + Vector(0, ramp.width, 0)
};
for (const Vector& vertex : vertices)
{
float dot = MathUtils::SIMDDotProduct(vertex, direction);
if (dot > maxDot)
{
maxDot = dot;
farthestPoint = vertex;
}
}
return farthestPoint;
}
bool CollisionDetection::UpdateSimplex(Vector* simplex, Vector& direction, int index)
{
Vector a = simplex[index];
Vector b = simplex[(index + 1) % 3];
Vector c = simplex[(index + 2) % 3];
Vector ab = b - a;
Vector ac = c - a;
Vector ao = -a;
Vector abPerp = MathUtils::SIMDCrossProduct(ac, ab);
if (MathUtils::SIMDDotProduct(abPerp, ao) > 0)
{
direction = abPerp;
}
else
{
Vector acPerp = MathUtils::SIMDCrossProduct(ab, ac);
if (MathUtils::SIMDDotProduct(acPerp, ao) > 0)
{
simplex[0] = a;
simplex[1] = c;
direction = acPerp;
}
else
{
if (MathUtils::SIMDDotProduct(ab, ao) > 0)
{
simplex[0] = a;
simplex[1] = b;
direction = MathUtils::SIMDCrossProduct(ab, ao);
}
else
{
simplex[0] = b;
simplex[1] = c;
direction = MathUtils::SIMDCrossProduct(ac, ao);
}
}
}
return false;
}
// NumericalMethods methods
Vector NumericalMethods::SolveBrachistochrone(const Vector& startPos, const Vector& endPos, float time, float gravity, float airAccelerate)
{
return SolveBrachistochroneAdaptive(startPos, endPos, time, gravity, airAccelerate, 1e-6f);
}
Vector NumericalMethods::SolveBrachistochroneAdaptive(const Vector& startPos, const Vector& endPos, float time, float gravity, float airAccelerate, float errorTolerance)
{
auto brachistochroneEquation = [](float t, Vector y, void* params)
{
Vector* p = static_cast<Vector*>(params);
Vector startPos = p[0];
Vector endPos = p[1];
float gravity = p[2].x;
float airAccelerate = p[3].x;
Vector pos = Vector(y.x, y.y, y.z);
Vector vel = Vector(y.v, y.w, y.u);
Vector accel = Vector(0.0f, 0.0f, -gravity) + airAccelerate * vel.Normalized();
return Vector(vel.x, vel.y, vel.z, accel.x, accel.y, accel.z);
};
Vector y0 = Vector(startPos.x, startPos.y, startPos.z, 0.0f, 0.0f, 0.0f);
Vector params[] = { startPos, endPos, Vector(gravity, 0.0f, 0.0f), Vector(airAccelerate, 0.0f, 0.0f) };
float h = 1e-3f;
Vector result = DormandPrince54(0.0f, time, y0, brachistochroneEquation, params, h);
return Vector(result.x, result.y, result.z);
}
float NumericalMethods::CalculateBrachistochronePathTime(const Vector& startPos, const Vector& endPos, float gravity)
{
auto integrand = [](float t, void* params)
{
Vector* p = static_cast<Vector*>(params);
Vector startPos = p[0];
Vector endPos = p[1];
float gravity = p[2].x;
Vector displacement = endPos - startPos;
float distanceSquared = displacement.LengthSqr();
float height = std::abs(displacement.z);
return std::sqrt(distanceSquared / (2.0f * gravity * height));
};
Vector params[] = { startPos, endPos, Vector(gravity, 0.0f, 0.0f) };
int n = 100;
return GaussianQuadrature(0.0f, 1.0f, n, integrand, params);
}
Vector NumericalMethods::CalculateGradient(const Vector& point, const Ramp& ramp, float gravity, float airAccelerate)
{
float h = 0.001f;
Vector dx = SolveBrachistochrone(point + Vector(h, 0.0f, 0.0f), ramp.endPoint, gravity, airAccelerate) -
SolveBrachistochrone(point, ramp.endPoint, gravity, airAccelerate);
Vector dy = SolveBrachistochrone(point + Vector(0.0f, h, 0.0f), ramp.endPoint, gravity, airAccelerate) -
SolveBrachistochrone(point, ramp.endPoint, gravity, airAccelerate);
Vector dz = SolveBrachistochrone(point + Vector(0.0f, 0.0f, h), ramp.endPoint, gravity, airAccelerate) -
SolveBrachistochrone(point, ramp.endPoint, gravity, airAccelerate);
return Vector(dx.x / h, dy.y / h, dz.z / h);
}
float NumericalMethods::GaussianQuadrature(float a, float b, int n, float (*f)(float, void*), void* params)
{
const float x[] = { -0.5773502692, 0.5773502692 };
const float w[] = { 1.0, 1.0 };
float h = (b - a) / n;
float sum = 0.0;
for (int i = 0; i < n; ++i)
{
float x0 = a + i * h;
float x1 = a + (i + 1) * h;
float mid = (x0 + x1) / 2;
float dx = (x1 - x0) / 2;
for (int j = 0; j < 2; ++j)
{
float xj = mid + dx * x[j];
sum += w[j] * f(xj, params);
}
}
return sum * h / 2;
}
Vector NumericalMethods::DormandPrince54(float t0, float tf, const Vector& y0, float (*f)(float, Vector, void*), void* params, float& h)
{
const float a[] = { 0.0, 0.2, 0.3, 0.8, 8.0 / 9.0, 1.0, 1.0 };
const float b[][6] =
{
{0.2},
{3.0 / 40.0, 9.0 / 40.0},
{44.0 / 45.0, -56.0 / 15.0, 32.0 / 9.0},
{19372.0 / 6561.0, -25360.0 / 2187.0, 64448.0 / 6561.0, -212.0 / 729.0},
{9017.0 / 3168.0, -355.0 / 33.0, 46732.0 / 5247.0, 49.0 / 176.0, -5103.0 / 18656.0},
{35.0 / 384.0, 0.0, 500.0 / 1113.0, 125.0 / 192.0, -2187.0 / 6784.0, 11.0 / 84.0}
};
const float c[] = { 35.0 / 384.0, 0.0, 500.0 / 1113.0, 125.0 / 192.0, -2187.0 / 6784.0, 11.0 / 84.0, 0.0 };
const float d[] = { 5179.0 / 57600.0, 0.0, 7571.0 / 16695.0, 393.0 / 640.0, -92097.0 / 339200.0, 187.0 / 2100.0, 1.0 / 40.0 };
Vector y = y0;
float t = t0;
float h_min = 1e-6;
float h_max = tf - t0;
float tol = 1e-6;
while (t < tf)
{
if (t + h > tf)
{
h = tf - t;
}
Vector k1 = f(t, y, params);
Vector k2 = f(t + a[1] * h, y + h * (b[1][0] * k1), params);
Vector k3 = f(t + a[2] * h, y + h * (b[2][0] * k1 + b[2][1] * k2), params);
Vector k4 = f(t + a[3] * h, y + h * (b[3][0] * k1 + b[3][1] * k2 + b[3][2] * k3), params);
Vector k5 = f(t + a[4] * h, y + h * (b[4][0] * k1 + b[4][1] * k2 + b[4][2] * k3 + b[4][3] * k4), params);
Vector k6 = f(t + a[5] * h, y + h * (b[5][0] * k1 + b[5][1] * k2 + b[5][2] * k3 + b[5][3] * k4 + b[5][4] * k5), params);
Vector y_next = y + h * (c[0] * k1 + c[1] * k2 + c[2] * k3 + c[3] * k4 + c[4] * k5 + c[5] * k6);
Vector y_error = h * (d[0] * k1 + d[1] * k2 + d[2] * k3 + d[3] * k4 + d[4] * k5 + d[5] * k6 + d[6] * f(t + h, y_next, params));
float error = y_error.Length();
float h_new = h * std::pow(tol / error, 0.2);
h_new = std::max(h_min, std::min(h_new, h_max));
if (error < tol)
{
t += h;
y = y_next;
}
h = h_new;
}
return y;
}
// MathUtils methods
Vector MathUtils::SIMDCrossProduct(const Vector& a, const Vector& b)
{
__m128 a_simd = _mm_set_ps(0.0f, a.z, a.y, a.x);
__m128 b_simd = _mm_set_ps(0.0f, b.z, b.y, b.x);
__m128 a_yzx = _mm_shuffle_ps(a_simd, a_simd, _MM_SHUFFLE(3, 0, 2, 1));
__m128 b_yzx = _mm_shuffle_ps(b_simd, b_simd, _MM_SHUFFLE(3, 0, 2, 1));
__m128 c_zxy = _mm_sub_ps(_mm_mul_ps(a_simd, b_yzx), _mm_mul_ps(a_yzx, b_simd));
return Vector(c_zxy[0], c_zxy[1], c_zxy[2]);
}
float MathUtils::SIMDDotProduct(const Vector& a, const Vector& b)
{
__m128 a_simd = _mm_set_ps(0.0f, a.z, a.y, a.x);
__m128 b_simd = _mm_set_ps(0.0f, b.z, b.y, b.x);
__m128 result = _mm_mul_ps(a_simd, b_simd);
result = _mm_hadd_ps(result, result);
result = _mm_hadd_ps(result, result);
return _mm_cvtss_f32(result);
}
void MathUtils::ClipVelocity(const Vector& in, const Vector& normal, Vector& out, float overbounce)
{
float backoff = DotProduct(in, normal) * overbounce;
for (int i = 0; i < 3; i++) {
out[i] = in[i] - backoff * normal[i];
}
// Ensure that the new velocity is not directing back into the collision plane
float adjust = DotProduct(out, normal);
if (adjust < 0.0f) {
out -= normal * adjust;
}
}
float MathUtils::SIMDLength(const Vector& v)
{
__m128 v_simd = _mm_set_ps(0.0f, v.z, v.y, v.x);
__m128 squared = _mm_mul_ps(v_simd, v_simd);
squared = _mm_hadd_ps(squared, squared);
squared = _mm_hadd_ps(squared, squared);
return _mm_cvtss_f32(_mm_sqrt_ss(squared));
}
Vector MathUtils::SIMDNormalized(const Vector& v)
{
__m128 v_simd = _mm_set_ps(0.0f, v.z, v.y, v.x);
__m128 squared = _mm_mul_ps(v_simd, v_simd);
squared = _mm_hadd_ps(squared, squared);
squared = _mm_hadd_ps(squared, squared);
__m128 length = _mm_sqrt_ss(squared);
__m128 normalized = _mm_div_ps(v_simd, _mm_shuffle_ps(length, length, 0));
return Vector(normalized[0], normalized[1], normalized[2]);
}
// Optimization methods
std::vector<Vector> Optimization::OptimizePath(const std::vector<Vector>& path, const Ramp& ramp, float gravity, float airAccelerate)
{
if (path.empty())
{
return {};
}
return OptimizePathBFGS(path, ramp, gravity, airAccelerate);
}
std::vector<Vector> Optimization::OptimizePathConjugateGradient(const std::vector<Vector>& path, const Ramp& ramp, float gravity, float airAccelerate)
{
if (path.empty())
{
return {};
}
std::vector<Vector> optimizedPath = path;
std::vector<Vector> gradients(path.size());
Vector direction(0.0f, 0.0f, 0.0f);
for (int i = 0; i < MAX_OPTIMIZATION_ITERATIONS; ++i)
{
bool converged = true;
for (size_t j = 1; j < optimizedPath.size() - 1; ++j)
{
Vector& point = optimizedPath[j];
gradients[j] = NumericalMethods::CalculateGradient(point, ramp, gravity, airAccelerate);
if (gradients[j].LengthSqr() > GRADIENT_TOLERANCE)
{
converged = false;
if (i == 0)
{
direction = -gradients[j];
}
else
{
float beta = std::max(0.0f, gradients[j].Dot(gradients[j] - gradients[j - 1]) / gradients[j - 1].Dot(gradients[j - 1]));
direction = -gradients[j] + beta * direction;
}
float alpha = LineSearch(point, direction, ramp, gravity, airAccelerate).first;
point -= direction * alpha;
}
}
if (converged)
{
break;
}
}
return optimizedPath;
}
std::vector<Vector> Optimization::OptimizePathBFGS(const std::vector<Vector>& path, const Ramp& ramp, float gravity, float airAccelerate)
{
std::vector<Vector> optimizedPath = path;
std::vector<Vector> gradients(path.size());
std::vector<Matrix> inverseHessians(path.size(), Matrix::Identity(3));
for (int i = 0; i < MAX_OPTIMIZATION_ITERATIONS; ++i)
{
bool converged = true;
for (size_t j = 1; j < optimizedPath.size() - 1; ++j)
{
Vector& point = optimizedPath[j];
gradients[j] = NumericalMethods::CalculateGradient(point, ramp, gravity, airAccelerate);
if (gradients[j].LengthSqr() > GRADIENT_TOLERANCE)
{
converged = false;
Vector direction = -inverseHessians[j] * gradients[j];
float alpha = LineSearch(point, direction, ramp, gravity, airAccelerate).first;
point += direction * alpha;
Vector gradientDifference = NumericalMethods::CalculateGradient(point, ramp, gravity, airAccelerate) - gradients[j];
UpdateInverseHessian(inverseHessians[j], direction * alpha, gradientDifference);
}