forked from nillerusr/source-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphysics_airboat.cpp
More file actions
1796 lines (1469 loc) · 63.4 KB
/
physics_airboat.cpp
File metadata and controls
1796 lines (1469 loc) · 63.4 KB
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
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: The airboat, a sporty nimble water craft.
//
//=============================================================================//
#include "cbase.h"
#include "physics_airboat.h"
#include "cmodel.h"
#include <ivp_ray_solver.hxx>
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#ifdef _X360
#define AIRBOAT_STEERING_RATE_MIN 0.000225f
#define AIRBOAT_STEERING_RATE_MAX (10.0f * AIRBOAT_STEERING_RATE_MIN)
#define AIRBOAT_STEERING_INTERVAL 1.5f
#else
#define AIRBOAT_STEERING_RATE_MIN 0.00045f
#define AIRBOAT_STEERING_RATE_MAX (5.0f * AIRBOAT_STEERING_RATE_MIN)
#define AIRBOAT_STEERING_INTERVAL 0.5f
#endif //_X360
#define AIRBOAT_ROT_DRAG 0.00004f
#define AIRBOAT_ROT_DAMPING 0.001f
// Mass-independent thrust values
#define AIRBOAT_THRUST_MAX 11.0f // N / kg
#define AIRBOAT_THRUST_MAX_REVERSE 7.5f // N / kg
// Mass-independent drag values
#define AIRBOAT_WATER_DRAG_LEFT_RIGHT 0.6f
#define AIRBOAT_WATER_DRAG_FORWARD_BACK 0.005f
#define AIRBOAT_WATER_DRAG_UP_DOWN 0.0025f
#define AIRBOAT_GROUND_DRAG_LEFT_RIGHT 2.0
#define AIRBOAT_GROUND_DRAG_FORWARD_BACK 1.0
#define AIRBOAT_GROUND_DRAG_UP_DOWN 0.8
#define AIRBOAT_DRY_FRICTION_SCALE 0.6f // unitless, reduces our friction on all surfaces other than water
#define AIRBOAT_RAYCAST_DIST 0.35f // m (~14in)
#define AIRBOAT_RAYCAST_DIST_WATER_LOW 0.1f // m (~4in)
#define AIRBOAT_RAYCAST_DIST_WATER_HIGH 0.35f // m (~16in)
// Amplitude of wave noise. Blend from max to min as speed increases.
#define AIRBOAT_WATER_NOISE_MIN 0.01 // m (~0.4in)
#define AIRBOAT_WATER_NOISE_MAX 0.03 // m (~1.2in)
// Frequency of wave noise. Blend from min to max as speed increases.
#define AIRBOAT_WATER_FREQ_MIN 1.5
#define AIRBOAT_WATER_FREQ_MAX 1.5
// Phase difference in wave noise between left and right pontoons
// Blend from max to min as speed increases.
#define AIRBOAT_WATER_PHASE_MIN 0.0 // s
#define AIRBOAT_WATER_PHASE_MAX 1.5 // s
#define AIRBOAT_GRAVITY 9.81f // m/s2
// Pontoon indices
enum
{
AIRBOAT_PONTOON_FRONT_LEFT = 0,
AIRBOAT_PONTOON_FRONT_RIGHT,
AIRBOAT_PONTOON_REAR_LEFT,
AIRBOAT_PONTOON_REAR_RIGHT,
};
class IVP_Ray_Solver_Template;
class IVP_Ray_Hit;
class IVP_Event_Sim;
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
class CAirboatFrictionData : public IPhysicsCollisionData
{
public:
CAirboatFrictionData()
{
m_vecPoint.Init( 0, 0, 0 );
m_vecNormal.Init( 0, 0, 0 );
m_vecVelocity.Init( 0, 0, 0 );
}
virtual void GetSurfaceNormal( Vector &out )
{
out = m_vecPoint;
}
virtual void GetContactPoint( Vector &out )
{
out = m_vecNormal;
}
virtual void GetContactSpeed( Vector &out )
{
out = m_vecVelocity;
}
public:
Vector m_vecPoint;
Vector m_vecNormal;
Vector m_vecVelocity;
};
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CPhysics_Airboat::CPhysics_Airboat( IVP_Environment *pEnv, const IVP_Template_Car_System *pCarSystem,
IPhysicsGameTrace *pGameTrace )
{
InitRaycastCarBody( pCarSystem );
InitRaycastCarEnvironment( pEnv, pCarSystem );
InitRaycastCarWheels( pCarSystem );
InitRaycastCarAxes( pCarSystem );
InitAirboat( pCarSystem );
m_pGameTrace = pGameTrace;
m_SteeringAngle = 0;
m_bSteeringReversed = false;
m_flThrust = 0;
m_bAirborne = false;
m_flAirTime = 0;
m_bWeakJump = false;
m_flPitchErrorPrev = 0;
m_flRollErrorPrev = 0;
}
//-----------------------------------------------------------------------------
// Purpose: Deconstructor
//-----------------------------------------------------------------------------
CPhysics_Airboat::~CPhysics_Airboat()
{
m_pAirboatBody->get_environment()->get_controller_manager()->remove_controller_from_environment( this, IVP_TRUE );
}
//-----------------------------------------------------------------------------
// Purpose: Setup the car system wheels.
//-----------------------------------------------------------------------------
void CPhysics_Airboat::InitAirboat( const IVP_Template_Car_System *pCarSystem )
{
for ( int iWheel = 0; iWheel < pCarSystem->n_wheels; ++iWheel )
{
m_pWheels[iWheel] = pCarSystem->car_wheel[iWheel];
m_pWheels[iWheel]->enable_collision_detection( IVP_FALSE );
}
CPhysicsObject* pBodyObject = static_cast<CPhysicsObject*>(pCarSystem->car_body->client_data);
pBodyObject->EnableGravity( false );
// We do our own buoyancy simulation.
pBodyObject->SetCallbackFlags( pBodyObject->GetCallbackFlags() & ~CALLBACK_DO_FLUID_SIMULATION );
}
//-----------------------------------------------------------------------------
// Purpose: Get the raycast wheel.
//-----------------------------------------------------------------------------
IPhysicsObject *CPhysics_Airboat::GetWheel( int index )
{
Assert( index >= 0 );
Assert( index < n_wheels );
return ( IPhysicsObject* )m_pWheels[index]->client_data;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPhysics_Airboat::SetWheelFriction( int iWheel, float flFriction )
{
change_friction_of_wheel( IVP_POS_WHEEL( iWheel ), flFriction );
}
//-----------------------------------------------------------------------------
// Purpose: Returns an amount to add to the front pontoon raycasts to simulate wave noise.
// Input : nPontoonIndex - Which pontoon we're dealing with (0 or 1).
// flSpeedRatio - Speed as a ratio of max speed [0..1]
//-----------------------------------------------------------------------------
float CPhysics_Airboat::ComputeFrontPontoonWaveNoise( int nPontoonIndex, float flSpeedRatio )
{
// Add in sinusoidal noise cause by undulating water. Reduce the amplitude of the noise at higher speeds.
IVP_FLOAT flNoiseScale = RemapValClamped( 1.0 - flSpeedRatio, 0, 1, AIRBOAT_WATER_NOISE_MIN, AIRBOAT_WATER_NOISE_MAX );
// Apply a phase shift between left and right pontoons to simulate waves passing under the boat.
IVP_FLOAT flPhaseShift = 0;
if ( flSpeedRatio < 0.3 )
{
// BUG: this allows a discontinuity in the waveform - use two superimposed sine waves instead?
flPhaseShift = nPontoonIndex * AIRBOAT_WATER_PHASE_MAX;
}
// Increase the wave frequency as speed increases.
IVP_FLOAT flFrequency = RemapValClamped( flSpeedRatio, 0, 1, AIRBOAT_WATER_FREQ_MIN, AIRBOAT_WATER_FREQ_MAX );
//Msg( "Wave amp=%f, freq=%f, phase=%f\n", flNoiseScale, flFrequency, flPhaseShift );
return flNoiseScale * sin( flFrequency * ( m_pCore->environment->get_current_time().get_seconds() + flPhaseShift ) );
}
//-----------------------------------------------------------------------------
// Purpose:: Convert data to HL2 measurements, and test direction of raycast.
//-----------------------------------------------------------------------------
void CPhysics_Airboat::pre_raycasts_gameside( int nRaycastCount, IVP_Ray_Solver_Template *pRays,
Ray_t *pGameRays, IVP_Raycast_Airboat_Impact *pImpacts )
{
IVP_FLOAT flForwardSpeedRatio = clamp( m_vecLocalVelocity.k[2] / 10.0f, 0.f, 1.0f );
//Msg( "flForwardSpeedRatio = %f\n", flForwardSpeedRatio );
IVP_FLOAT flSpeed = ( IVP_FLOAT )m_pCore->speed.real_length();
IVP_FLOAT flSpeedRatio = clamp( flSpeed / 15.0f, 0.f, 1.0f );
if ( !m_flThrust )
{
flForwardSpeedRatio *= 0.5;
}
// This is a little weird. We adjust the front pontoon ray lengths based on forward velocity,
// but ONLY if both pontoons are in the water, which we won't know until we do the raycast.
// So we do most of the work here, and cache some of the results to use them later.
Vector vecStart[4];
Vector vecDirection[4];
Vector vecZero( 0.0f, 0.0f, 0.0f );
int nFrontPontoonsInWater = 0;
int iRaycast;
for ( iRaycast = 0; iRaycast < nRaycastCount; ++iRaycast )
{
// Setup the ray.
ConvertPositionToHL( pRays[iRaycast].ray_start_point, vecStart[iRaycast] );
ConvertDirectionToHL( pRays[iRaycast].ray_normized_direction, vecDirection[iRaycast] );
float flRayLength = IVP2HL( pRays[iRaycast].ray_length );
// Check to see if that point is in water.
pImpacts[iRaycast].bInWater = IVP_FALSE;
if ( m_pGameTrace->VehiclePointInWater( vecStart[iRaycast] ) )
{
vecDirection[iRaycast].Negate();
pImpacts[iRaycast].bInWater = IVP_TRUE;
}
Vector vecEnd = vecStart[iRaycast] + ( vecDirection[iRaycast] * flRayLength );
// Adjust the trace if the pontoon is in the water.
if ( m_pGameTrace->VehiclePointInWater( vecEnd ) )
{
// Reduce the ray length in the water.
pRays[iRaycast].ray_length = AIRBOAT_RAYCAST_DIST_WATER_LOW;
if ( iRaycast < 2 )
{
nFrontPontoonsInWater++;
// Front pontoons.
// Add a little sinusoidal noise to simulate waves.
IVP_FLOAT flNoise = ComputeFrontPontoonWaveNoise( iRaycast, flSpeedRatio );
pRays[iRaycast].ray_length += flNoise;
}
else
{
// Recalculate the end position in HL coordinates.
flRayLength = IVP2HL( pRays[iRaycast].ray_length );
vecEnd = vecStart[iRaycast] + ( vecDirection[iRaycast] * flRayLength );
}
}
pGameRays[iRaycast].Init( vecStart[iRaycast], vecEnd, vecZero, vecZero );
}
// If both front pontoons are in the water, add in a bit of lift proportional to our
// forward speed. We can't do this to only one of the front pontoons because it causes
// some twist if we do.
// FIXME: this does some redundant work (computes the wave noise again)
if ( nFrontPontoonsInWater == 2 )
{
for ( int i = 0; i < 2; i++ )
{
// Front pontoons.
// Raise it higher out of the water as we go faster forward.
pRays[i].ray_length = RemapValClamped( flForwardSpeedRatio, 0, 1, AIRBOAT_RAYCAST_DIST_WATER_LOW, AIRBOAT_RAYCAST_DIST_WATER_HIGH );
// Add a little sinusoidal noise to simulate waves.
IVP_FLOAT flNoise = ComputeFrontPontoonWaveNoise( i, flSpeedRatio );
pRays[i].ray_length += flNoise;
// Recalculate the end position in HL coordinates.
float flRayLength = IVP2HL( pRays[i].ray_length );
Vector vecEnd = vecStart[i] + ( vecDirection[i] * flRayLength );
pGameRays[i].Init( vecStart[i], vecEnd, vecZero, vecZero );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
float CPhysics_Airboat::GetWaterDepth( Ray_t *pGameRay, IPhysicsObject *pPhysAirboat )
{
float flDepth = 0.0f;
trace_t trace;
Ray_t waterRay;
Vector vecStart = pGameRay->m_Start;
Vector vecEnd( vecStart.x, vecStart.y, vecStart.z + 1000.0f );
Vector vecZero( 0.0f, 0.0f, 0.0f );
waterRay.Init( vecStart, vecEnd, vecZero, vecZero );
m_pGameTrace->VehicleTraceRayWithWater( waterRay, pPhysAirboat->GetGameData(), &trace );
flDepth = 1000.0f * trace.fractionleftsolid;
return flDepth;
}
//-----------------------------------------------------------------------------
// Purpose: Performs traces to figure out what is at each of the raycast points
// and fills out the pImpacts array with that information.
// Input : nRaycastCount - Number of elements in the arrays pointed to by pRays
// and pImpacts.
// pRays - Holds the rays to trace with.
// pImpacts - Receives the trace results.
//-----------------------------------------------------------------------------
void CPhysics_Airboat::do_raycasts_gameside( int nRaycastCount, IVP_Ray_Solver_Template *pRays,
IVP_Raycast_Airboat_Impact *pImpacts )
{
Assert( nRaycastCount >= 0 );
Assert( nRaycastCount <= IVP_RAYCAST_AIRBOAT_MAX_WHEELS );
Ray_t gameRays[IVP_RAYCAST_AIRBOAT_MAX_WHEELS];
pre_raycasts_gameside( nRaycastCount, pRays, gameRays, pImpacts );
// Do the raycasts and set impact data.
trace_t trace;
for ( int iRaycast = 0; iRaycast < nRaycastCount; ++iRaycast )
{
// Trace.
if ( pImpacts[iRaycast].bInWater )
{
// The start position is underwater. Trace up to find the water surface.
IPhysicsObject *pPhysAirboat = static_cast<IPhysicsObject*>( m_pAirboatBody->client_data );
m_pGameTrace->VehicleTraceRay( gameRays[iRaycast], pPhysAirboat->GetGameData(), &trace );
pImpacts[iRaycast].flDepth = GetWaterDepth( &gameRays[iRaycast], pPhysAirboat );
}
else
{
// Trace down to find the ground or water.
IPhysicsObject *pPhysAirboat = static_cast<IPhysicsObject*>( m_pAirboatBody->client_data );
m_pGameTrace->VehicleTraceRayWithWater( gameRays[iRaycast], pPhysAirboat->GetGameData(), &trace );
}
ConvertPositionToIVP( gameRays[iRaycast].m_Start + gameRays[iRaycast].m_StartOffset, m_CarSystemDebugData.wheelRaycasts[iRaycast][0] );
ConvertPositionToIVP( gameRays[iRaycast].m_Start + gameRays[iRaycast].m_StartOffset + gameRays[iRaycast].m_Delta, m_CarSystemDebugData.wheelRaycasts[iRaycast][1] );
m_CarSystemDebugData.wheelRaycastImpacts[iRaycast] = trace.fraction * gameRays[iRaycast].m_Delta.Length();
// Set impact data.
pImpacts[iRaycast].bImpactWater = IVP_FALSE;
pImpacts[iRaycast].bImpact = IVP_FALSE;
if ( trace.fraction != 1.0f )
{
pImpacts[iRaycast].bImpact = IVP_TRUE;
// Set water surface flag.
pImpacts[iRaycast].flDepth = 0.0f;
if ( trace.contents & MASK_WATER )
{
pImpacts[iRaycast].bImpactWater = IVP_TRUE;
}
// Save impact surface data.
ConvertPositionToIVP( trace.endpos, pImpacts[iRaycast].vecImpactPointWS );
ConvertDirectionToIVP( trace.plane.normal, pImpacts[iRaycast].vecImpactNormalWS );
// Save surface properties.
const surfacedata_t *pSurfaceData = physprops->GetSurfaceData( trace.surface.surfaceProps );
pImpacts[iRaycast].nSurfaceProps = trace.surface.surfaceProps;
if (pImpacts[iRaycast].vecImpactNormalWS.k[1] < -0.707)
{
// dampening is 1/t, where t is how long it takes to come to a complete stop
pImpacts[iRaycast].flDampening = pSurfaceData->physics.dampening;
pImpacts[iRaycast].flFriction = pSurfaceData->physics.friction;
}
else
{
// This surface is too vertical -- no friction or damping from it.
pImpacts[iRaycast].flDampening = pSurfaceData->physics.dampening;
pImpacts[iRaycast].flFriction = pSurfaceData->physics.friction;
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Entry point for airboat simulation.
//-----------------------------------------------------------------------------
void CPhysics_Airboat::do_simulation_controller( IVP_Event_Sim *pEventSim, IVP_U_Vector<IVP_Core> * )
{
IVP_Ray_Solver_Template raySolverTemplates[IVP_RAYCAST_AIRBOAT_MAX_WHEELS];
IVP_Raycast_Airboat_Impact impacts[IVP_RAYCAST_AIRBOAT_MAX_WHEELS];
// Cache some data into members here so we only do the work once.
m_pCore = m_pAirboatBody->get_core();
const IVP_U_Matrix *matWorldFromCore = m_pCore->get_m_world_f_core_PSI();
// Cache the speed.
m_flSpeed = ( IVP_FLOAT )m_pCore->speed.real_length();
// Cache the local velocity vector.
matWorldFromCore->vimult3(&m_pCore->speed, &m_vecLocalVelocity);
// Raycasts.
PreRaycasts( raySolverTemplates, matWorldFromCore, impacts );
do_raycasts_gameside( n_wheels, raySolverTemplates, impacts );
if ( !PostRaycasts( raySolverTemplates, matWorldFromCore, impacts ) )
return;
UpdateAirborneState( impacts, pEventSim );
// Enumerate the controllers attached to us.
//for (int i = m_pCore->controllers_of_core.len() - 1; i >= 0; i--)
//{
// IVP_Controller *pController = m_pCore->controllers_of_core.element_at(i);
//}
// Pontoons. Buoyancy or ground impacts.
DoSimulationPontoons( impacts, pEventSim );
// Drag due to water and ground friction.
DoSimulationDrag( impacts, pEventSim );
// Turbine (fan).
DoSimulationTurbine( pEventSim );
// Steering.
DoSimulationSteering( pEventSim );
// Anti-pitch.
DoSimulationKeepUprightPitch( impacts, pEventSim );
// Anti-roll.
DoSimulationKeepUprightRoll( impacts, pEventSim );
// Additional gravity based on speed.
DoSimulationGravity( pEventSim );
}
//-----------------------------------------------------------------------------
// Purpose: Initialize the rays to be cast from the vehicle wheel positions to
// the "ground."
// Input : pRaySolverTemplates -
// matWorldFromCore -
// pImpacts -
//-----------------------------------------------------------------------------
void CPhysics_Airboat::PreRaycasts( IVP_Ray_Solver_Template *pRaySolverTemplates,
const IVP_U_Matrix *matWorldFromCore,
IVP_Raycast_Airboat_Impact *pImpacts )
{
int nPontoonPoints = n_wheels;
for ( int iPoint = 0; iPoint < nPontoonPoints; ++iPoint )
{
IVP_Raycast_Airboat_Wheel *pPontoonPoint = get_wheel( IVP_POS_WHEEL( iPoint ) );
if ( pPontoonPoint )
{
// Fill the in the ray solver template for the current wheel.
IVP_Ray_Solver_Template &raySolverTemplate = pRaySolverTemplates[iPoint];
// Transform the wheel "start" position from vehicle core-space to world-space. This is
// the raycast starting position.
matWorldFromCore->vmult4( &pPontoonPoint->raycast_start_cs, &raySolverTemplate.ray_start_point );
// Transform the shock (spring) direction from vehicle core-space to world-space. This is
// the raycast direction.
matWorldFromCore->vmult3( &pPontoonPoint->raycast_dir_cs, &pImpacts[iPoint].raycast_dir_ws );
raySolverTemplate.ray_normized_direction.set( &pImpacts[iPoint].raycast_dir_ws );
// Set the length of the ray cast.
raySolverTemplate.ray_length = AIRBOAT_RAYCAST_DIST;
// Set the ray solver template flags. This defines which objects you wish to
// collide against in the physics environment.
raySolverTemplate.ray_flags = IVP_RAY_SOLVER_ALL;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Determines whether we are airborne and whether we just performed a
// weak or strong jump. Weak jumps are jumps at below a threshold speed,
// and disable the turbine and pitch controller.
// Input : pImpacts -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
void CPhysics_Airboat::UpdateAirborneState( IVP_Raycast_Airboat_Impact *pImpacts, IVP_Event_Sim *pEventSim )
{
int nCount = CountSurfaceContactPoints(pImpacts);
if (!nCount)
{
if (!m_bAirborne)
{
m_bAirborne = true;
m_flAirTime = 0;
IVP_FLOAT flSpeed = ( IVP_FLOAT )m_pCore->speed.real_length();
if (flSpeed < 11.0f)
{
//Msg("*** WEAK JUMP at %f!!!\n", flSpeed);
m_bWeakJump = true;
}
else
{
//Msg("Strong JUMP at %f\n", flSpeed);
}
}
else
{
m_flAirTime += pEventSim->delta_time;
}
}
else
{
m_bAirborne = false;
m_bWeakJump = false;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CPhysics_Airboat::PostRaycasts( IVP_Ray_Solver_Template *pRaySolverTemplates, const IVP_U_Matrix *matWorldFromCore,
IVP_Raycast_Airboat_Impact *pImpacts )
{
bool bReturn = true;
int nPontoonPoints = n_wheels;
for( int iPoint = 0; iPoint < nPontoonPoints; ++iPoint )
{
// Get data at raycast position.
IVP_Raycast_Airboat_Wheel *pPontoonPoint = get_wheel( IVP_POS_WHEEL( iPoint ) );
IVP_Raycast_Airboat_Impact *pImpact = &pImpacts[iPoint];
IVP_Ray_Solver_Template *pRaySolver = &pRaySolverTemplates[iPoint];
if ( !pPontoonPoint || !pImpact || !pRaySolver )
continue;
// Copy the ray length back, it may have changed.
pPontoonPoint->raycast_length = pRaySolver->ray_length;
// Test for inverted raycast direction.
if ( pImpact->bInWater )
{
pImpact->raycast_dir_ws.set_multiple( &pImpact->raycast_dir_ws, -1 );
}
// Impact.
if ( pImpact->bImpact )
{
// Save impact distance.
IVP_U_Point vecDelta;
vecDelta.subtract( &pImpact->vecImpactPointWS, &pRaySolver->ray_start_point );
pPontoonPoint->raycast_dist = vecDelta.real_length();
// Get the inverse portion of the surface normal in the direction of the ray cast (shock - used in the shock simulation code for the sign
// and percentage of force applied to the shock).
pImpact->inv_normal_dot_dir = 1.1f / ( IVP_Inline_Math::fabsd( pImpact->raycast_dir_ws.dot_product( &pImpact->vecImpactNormalWS ) ) + 0.1f );
// Set the wheel friction - ground friction (if any) + wheel friction.
pImpact->friction_value = pImpact->flFriction * pPontoonPoint->friction_of_wheel;
}
// No impact.
else
{
pPontoonPoint->raycast_dist = pPontoonPoint->raycast_length;
pImpact->inv_normal_dot_dir = 1.0f;
pImpact->moveable_object_hit_by_ray = NULL;
pImpact->vecImpactNormalWS.set_multiple( &pImpact->raycast_dir_ws, -1 );
pImpact->friction_value = 1.0f;
}
// Set the new wheel position (the impact point or the full ray distance). Make this from the wheel not the ray trace position.
pImpact->vecImpactPointWS.add_multiple( &pRaySolver->ray_start_point, &pImpact->raycast_dir_ws, pPontoonPoint->raycast_dist );
// Get the speed (velocity) at the impact point.
m_pCore->get_surface_speed_ws( &pImpact->vecImpactPointWS, &pImpact->surface_speed_wheel_ws );
pImpact->projected_surface_speed_wheel_ws.set_orthogonal_part( &pImpact->surface_speed_wheel_ws, &pImpact->vecImpactNormalWS );
matWorldFromCore->vmult3( &pPontoonPoint->axis_direction_cs, &pImpact->axis_direction_ws );
pImpact->projected_axis_direction_ws.set_orthogonal_part( &pImpact->axis_direction_ws, &pImpact->vecImpactNormalWS );
if ( pImpact->projected_axis_direction_ws.normize() == IVP_FAULT )
{
DevMsg( "CPhysics_Airboat::do_simulation_controller projected_axis_direction_ws.normize failed\n" );
bReturn = false;
}
}
return bReturn;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPhysics_Airboat::DoSimulationPontoons( IVP_Raycast_Airboat_Impact *pImpacts, IVP_Event_Sim *pEventSim )
{
int nPontoonPoints = n_wheels;
for ( int iPoint = 0; iPoint < nPontoonPoints; ++iPoint )
{
IVP_Raycast_Airboat_Wheel *pPontoonPoint = get_wheel( IVP_POS_WHEEL( iPoint ) );
if ( !pPontoonPoint )
continue;
if ( pImpacts[iPoint].bImpact )
{
DoSimulationPontoonsGround( pPontoonPoint, &pImpacts[iPoint], pEventSim );
}
else if ( pImpacts[iPoint].bInWater )
{
DoSimulationPontoonsWater( pPontoonPoint, &pImpacts[iPoint], pEventSim );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Handle pontoons on ground.
//-----------------------------------------------------------------------------
void CPhysics_Airboat::DoSimulationPontoonsGround( IVP_Raycast_Airboat_Wheel *pPontoonPoint,
IVP_Raycast_Airboat_Impact *pImpact, IVP_Event_Sim *pEventSim )
{
// Check to see if we hit anything, otherwise the no force on this point.
IVP_DOUBLE flDiff = pPontoonPoint->raycast_dist - pPontoonPoint->raycast_length;
if ( flDiff >= 0 )
return;
IVP_FLOAT flSpringConstant, flSpringRelax, flSpringCompress;
flSpringConstant = pPontoonPoint->spring_constant;
flSpringRelax = pPontoonPoint->spring_damp_relax;
flSpringCompress = pPontoonPoint->spring_damp_compress;
IVP_DOUBLE flForce = -flDiff * flSpringConstant;
IVP_FLOAT flInvNormalDotDir = clamp(pImpact->inv_normal_dot_dir, 0.0f, 3.0f);
flForce *= flInvNormalDotDir;
IVP_U_Float_Point vecSpeedDelta;
vecSpeedDelta.subtract( &pImpact->projected_surface_speed_wheel_ws, &pImpact->surface_speed_wheel_ws );
IVP_DOUBLE flSpeed = vecSpeedDelta.dot_product( &pImpact->raycast_dir_ws );
if ( flSpeed > 0 )
{
flForce -= flSpringRelax * flSpeed;
}
else
{
flForce -= flSpringCompress * flSpeed;
}
if ( flForce < 0 )
{
flForce = 0.0f;
}
// NOTE: Spring constants are all mass-independent, so no need to multiply by mass here.
IVP_DOUBLE flImpulse = flForce * pEventSim->delta_time;
IVP_U_Float_Point vecImpulseWS;
vecImpulseWS.set_multiple( &pImpact->vecImpactNormalWS, flImpulse );
m_pCore->push_core_ws( &pImpact->vecImpactPointWS, &vecImpulseWS );
}
//-----------------------------------------------------------------------------
// Purpose: Handle pontoons on water.
//-----------------------------------------------------------------------------
void CPhysics_Airboat::DoSimulationPontoonsWater( IVP_Raycast_Airboat_Wheel *pPontoonPoint,
IVP_Raycast_Airboat_Impact *pImpact, IVP_Event_Sim *pEventSim )
{
#define AIRBOAT_BUOYANCY_SCALAR 1.6f
#define PONTOON_AREA_2D 2.8f // 2 pontoons x 16 in x 136 in = 4352 sq inches = 2.8 sq meters
#define PONTOON_HEIGHT 0.41f // 16 inches high = 0.41 meters
float flDepth = clamp( pImpact->flDepth, 0.f, PONTOON_HEIGHT );
//Msg("depth: %f\n", pImpact->flDepth);
// Depth is in inches, so multiply by 0.0254 meters/inch
IVP_FLOAT flSubmergedVolume = PONTOON_AREA_2D * flDepth * 0.0254;
// Buoyancy forces are equal to the mass of the water displaced, which is 1000 kg/m^3
// There are 4 pontoon points, so each one can exert 1/4th of the total buoyancy force.
IVP_FLOAT flForce = AIRBOAT_BUOYANCY_SCALAR * 0.25f * m_pCore->get_mass() * flSubmergedVolume * 1000.0f;
IVP_DOUBLE flImpulse = flForce * pEventSim->delta_time;
IVP_U_Float_Point vecImpulseWS;
vecImpulseWS.set( 0, -1, 0 );
vecImpulseWS.mult( flImpulse );
m_pCore->push_core_ws( &pImpact->vecImpactPointWS, &vecImpulseWS );
// Vector vecPoint;
// Vector vecDir(0, 0, 1);
//
// ConvertPositionToHL( pImpact->vecImpactPointWS, vecPoint );
// CPhysicsEnvironment *pEnv = (CPhysicsEnvironment *)m_pAirboatBody->get_core()->environment->client_data;
// IVPhysicsDebugOverlay *debugoverlay = pEnv->GetDebugOverlay();
// debugoverlay->AddLineOverlay(vecPoint, vecPoint + vecDir * 128, 255, 0, 255, false, 10.0 );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPhysics_Airboat::PerformFrictionNotification( float flEliminatedEnergy, float dt, int nSurfaceProp, IPhysicsCollisionData *pCollisionData )
{
CPhysicsObject *pPhysAirboat = static_cast<CPhysicsObject*>( m_pAirboatBody->client_data );
if ( ( pPhysAirboat->CallbackFlags() & CALLBACK_GLOBAL_FRICTION ) == 0 )
return;
IPhysicsCollisionEvent *pEventHandler = pPhysAirboat->GetVPhysicsEnvironment()->GetCollisionEventHandler();
if ( !pEventHandler )
return;
// scrape with an estimate for the energy per unit mass
// This assumes that the game is interested in some measure of vibration
// for sound effects. This also assumes that more massive objects require
// more energy to vibrate.
flEliminatedEnergy *= dt / pPhysAirboat->GetMass();
if ( flEliminatedEnergy > 0.05f )
{
pEventHandler->Friction( pPhysAirboat, flEliminatedEnergy, pPhysAirboat->GetMaterialIndexInternal(), nSurfaceProp, pCollisionData );
}
}
//-----------------------------------------------------------------------------
// Purpose: Drag due to water and ground friction.
//-----------------------------------------------------------------------------
void CPhysics_Airboat::DoSimulationDrag( IVP_Raycast_Airboat_Impact *pImpacts,
IVP_Event_Sim *pEventSim )
{
const IVP_U_Matrix *matWorldFromCore = m_pCore->get_m_world_f_core_PSI();
IVP_FLOAT flSpeed = ( IVP_FLOAT )m_pCore->speed.real_length();
// Used to make airboat sliding sounds
CAirboatFrictionData frictionData;
ConvertDirectionToHL( m_pCore->speed, frictionData.m_vecVelocity );
// Count the pontoons in the water.
int nPontoonPoints = n_wheels;
int nPointsInWater = 0;
int nPointsOnGround = 0;
float flGroundFriction = 0;
float flAverageDampening = 0.0f;
int *pSurfacePropCount = (int *)stackalloc( n_wheels * sizeof(int) );
int *pSurfaceProp = (int *)stackalloc( n_wheels * sizeof(int) );
memset( pSurfacePropCount, 0, n_wheels * sizeof(int) );
memset( pSurfaceProp, 0xFF, n_wheels * sizeof(int) );
int nSurfacePropCount = 0;
int nMaxSurfacePropIdx = 0;
for( int iPoint = 0; iPoint < nPontoonPoints; ++iPoint )
{
// Get data at raycast position.
IVP_Raycast_Airboat_Impact *pImpact = &pImpacts[iPoint];
if ( !pImpact || !pImpact->bImpact )
continue;
if ( pImpact->bImpactWater )
{
flAverageDampening += pImpact->flDampening;
nPointsInWater++;
}
else
{
flGroundFriction += pImpact->flFriction;
nPointsOnGround++;
// This logic is used to determine which surface prop we hit the most.
int i;
for ( i = 0; i < nSurfacePropCount; ++i )
{
if ( pSurfaceProp[i] == pImpact->nSurfaceProps )
break;
}
if ( i == nSurfacePropCount )
{
++nSurfacePropCount;
}
pSurfaceProp[i] = pImpact->nSurfaceProps;
if ( ++pSurfacePropCount[i] > pSurfacePropCount[nMaxSurfacePropIdx] )
{
nMaxSurfacePropIdx = i;
}
Vector frictionPoint, frictionNormal;
ConvertPositionToHL( pImpact->vecImpactPointWS, frictionPoint );
ConvertDirectionToHL( pImpact->vecImpactNormalWS, frictionNormal );
frictionData.m_vecPoint += frictionPoint;
frictionData.m_vecNormal += frictionNormal;
}
}
int nSurfaceProp = pSurfaceProp[nMaxSurfacePropIdx];
if ( nPointsOnGround > 0 )
{
frictionData.m_vecPoint /= nPointsOnGround;
frictionData.m_vecNormal /= nPointsOnGround;
VectorNormalize( frictionData.m_vecNormal );
}
if ( nPointsInWater > 0 )
{
flAverageDampening /= nPointsInWater;
}
//IVP_FLOAT flDebugSpeed = ( IVP_FLOAT )m_pCore->speed.real_length();
//Msg("(water=%d/land=%d) speed=%f (%f %f %f)\n", nPointsInWater, nPointsOnGround, flDebugSpeed, vecAirboatDirLS.k[0], vecAirboatDirLS.k[1], vecAirboatDirLS.k[2]);
if ( nPointsInWater )
{
// Apply the drag force opposite to the direction of motion in local space.
IVP_U_Float_Point vecAirboatNegDirLS;
vecAirboatNegDirLS.set_negative( &m_vecLocalVelocity );
// Water drag is directional -- the pontoons resist left/right motion much more than forward/back.
IVP_U_Float_Point vecDragLS;
vecDragLS.set( AIRBOAT_WATER_DRAG_LEFT_RIGHT * vecAirboatNegDirLS.k[0],
AIRBOAT_WATER_DRAG_UP_DOWN * vecAirboatNegDirLS.k[1],
AIRBOAT_WATER_DRAG_FORWARD_BACK * vecAirboatNegDirLS.k[2] );
vecDragLS.mult( flSpeed * m_pCore->get_mass() * pEventSim->delta_time );
// dvs TODO: apply flAverageDampening here
// Convert the drag force to world space and apply the drag.
IVP_U_Float_Point vecDragWS;
matWorldFromCore->vmult3(&vecDragLS, &vecDragWS);
m_pCore->center_push_core_multiple_ws( &vecDragWS );
}
//
// Calculate ground friction drag:
//
if ( nPointsOnGround && ( flSpeed > 0 ))
{
// Calculate the average friction across all contact points.
flGroundFriction /= (float)nPointsOnGround;
// Apply the drag force opposite to the direction of motion.
IVP_U_Float_Point vecAirboatNegDir;
vecAirboatNegDir.set_negative( &m_pCore->speed );
IVP_FLOAT flFrictionDrag = m_pCore->get_mass() * AIRBOAT_GRAVITY * AIRBOAT_DRY_FRICTION_SCALE * flGroundFriction;
flFrictionDrag /= flSpeed;
IPhysicsObject *pPhysAirboat = static_cast<IPhysicsObject*>( m_pAirboatBody->client_data );
float flEliminatedEnergy = pPhysAirboat->GetEnergy();
// Apply the drag force opposite to the direction of motion in local space.
IVP_U_Float_Point vecAirboatNegDirLS;
vecAirboatNegDirLS.set_negative( &m_vecLocalVelocity );
// Ground drag is directional -- the pontoons resist left/right motion much more than forward/back.
IVP_U_Float_Point vecDragLS;
vecDragLS.set( AIRBOAT_GROUND_DRAG_LEFT_RIGHT * vecAirboatNegDirLS.k[0],
AIRBOAT_GROUND_DRAG_UP_DOWN * vecAirboatNegDirLS.k[1],
AIRBOAT_GROUND_DRAG_FORWARD_BACK * vecAirboatNegDirLS.k[2] );
vecDragLS.mult( flFrictionDrag * pEventSim->delta_time );
// dvs TODO: apply flAverageDampening here
// Convert the drag force to world space and apply the drag.
IVP_U_Float_Point vecDragWS;
matWorldFromCore->vmult3(&vecDragLS, &vecDragWS);
m_pCore->center_push_core_multiple_ws( &vecDragWS );
// Figure out how much energy was eliminated by friction.
flEliminatedEnergy -= pPhysAirboat->GetEnergy();
PerformFrictionNotification( flEliminatedEnergy, pEventSim->delta_time, nSurfaceProp, &frictionData );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPhysics_Airboat::DoSimulationTurbine( IVP_Event_Sim *pEventSim )
{
// Reduce the turbine power during weak jumps to avoid unrealistic air control.
// Also, reduce reverse thrust while airborne.
float flThrust = m_flThrust;
if ((m_bWeakJump) || (m_bAirborne && (flThrust < 0)))
{
flThrust *= 0.5;
}
// Get the forward vector in world-space.
IVP_U_Float_Point vecForwardWS;
const IVP_U_Matrix *matWorldFromCore = m_pCore->get_m_world_f_core_PSI();
matWorldFromCore->get_col( IVP_COORDINATE_INDEX( index_z ), &vecForwardWS );
//Msg("thrust: %f\n", m_flThrust);
if ( ( vecForwardWS.k[1] < -0.5 ) && ( flThrust > 0 ) )
{
// Driving up a slope. Reduce upward thrust to prevent ludicrous climbing of steep surfaces.
float flFactor = 1 + vecForwardWS.k[1];
//Msg("FWD: y=%f, factor=%f\n", vecForwardWS.k[1], flFactor);
flThrust *= flFactor;
}
else if ( ( vecForwardWS.k[1] > 0.5 ) && ( flThrust < 0 ) )
{
// Reversing up a slope. Reduce upward thrust to prevent ludicrous climbing of steep surfaces.
float flFactor = 1 - vecForwardWS.k[1];
//Msg("REV: y=%f, factor=%f\n", vecForwardWS.k[1], flFactor);
flThrust *= flFactor;
}
// Forward (Front/Back) force
IVP_U_Float_Point vecImpulse;
vecImpulse.set_multiple( &vecForwardWS, flThrust * m_pCore->get_mass() * pEventSim->delta_time );
m_pCore->center_push_core_multiple_ws( &vecImpulse );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPhysics_Airboat::DoSimulationSteering( IVP_Event_Sim *pEventSim )
{
// Calculate the steering direction: forward or reverse.
// Don't mess with the steering direction while we're steering, unless thrust is applied.
// This prevents the steering from reversing because we started drifting backwards.
if ( ( m_SteeringAngle == 0 ) || ( m_flThrust != 0 ) )
{
if ( !m_bAnalogSteering )
{
// If we're applying reverse thrust, steering is always reversed.
if ( m_flThrust < 0 )
{
m_bSteeringReversed = true;
}
// Else if we are applying forward thrust or moving forward, use forward steering.
else if ( ( m_flThrust > 0 ) || ( m_vecLocalVelocity.k[2] > 0 ) )
{
m_bSteeringReversed = false;
}
}
else
{
// Create a dead zone through the middle of the joystick where we don't reverse thrust.
// If we're applying reverse thrust, steering is always reversed.
if ( m_flThrust < -2.0f )
{
m_bSteeringReversed = true;
}
// Else if we are applying forward thrust or moving forward, use forward steering.
else if ( ( m_flThrust > 2.0f ) || ( m_vecLocalVelocity.k[2] > 0 ) )
{
m_bSteeringReversed = false;
}
}
}
// Calculate the steering force.
IVP_FLOAT flForceSteering = 0.0f;
if ( fabsf( m_SteeringAngle ) > 0.01 )
{
// Get the sign of the steering force.
IVP_FLOAT flSteeringSign = m_SteeringAngle < 0.0f ? -1.0f : 1.0f;
if ( m_bSteeringReversed )
{
flSteeringSign *= -1.0f;
}
// If we changed steering sign or went from not steering to steering, reset the steer time
// to blend the new steering force in over time.
IVP_FLOAT flPrevSteeringSign = m_flPrevSteeringAngle < 0.0f ? -1.0f : 1.0f;
if ( ( fabs( m_flPrevSteeringAngle ) < 0.01 ) || ( flSteeringSign != flPrevSteeringSign ) )