aboutsummaryrefslogtreecommitdiff
path: root/sp/src/game/server/fourwheelvehiclephysics.cpp
blob: 3a70d02d79312d82dbd662791ae20f298d131a10 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: A moving vehicle that is used as a battering ram
//
// $NoKeywords: $
//=============================================================================//

#include "cbase.h"
#include "fourwheelvehiclephysics.h"
#include "engine/IEngineSound.h"
#include "soundenvelope.h"
#include "in_buttons.h"
#include "player.h"
#include "IEffects.h"
#include "physics_saverestore.h"
#include "vehicle_base.h"
#include "isaverestore.h"
#include "movevars_shared.h"
#include "te_effect_dispatch.h"
#include "particle_parse.h"

// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"

#define STICK_EXTENTS	400.0f


#define DUST_SPEED			5		// speed at which dust starts
#define REAR_AXLE			1		// indexes of axlex
#define	FRONT_AXLE			0
#define MAX_GUAGE_SPEED		100.0	// 100 mph is max speed shown on guage

#define BRAKE_MAX_VALUE				1.0f
#define BRAKE_BACK_FORWARD_SCALAR	2.0f

ConVar r_vehicleBrakeRate( "r_vehicleBrakeRate", "1.5", FCVAR_CHEAT );

ConVar xbox_throttlebias("xbox_throttlebias", "100", FCVAR_ARCHIVE );
ConVar xbox_throttlespoof("xbox_throttlespoof", "200", FCVAR_ARCHIVE );
ConVar xbox_autothrottle("xbox_autothrottle", "1", FCVAR_ARCHIVE );
ConVar xbox_steering_deadzone( "xbox_steering_deadzone", "0.0" );

// remaps an angular variable to a 3 band function:
// 0 <= t < start :		f(t) = 0
// start <= t <= end :	f(t) = end * spline(( t-start) / (end-start) )  // s curve between clamped and linear
// end < t :			f(t) = t
float RemapAngleRange( float startInterval, float endInterval, float value )
{
	// Fixup the roll
	value = AngleNormalize( value );
	float absAngle = fabs(value);

	// beneath cutoff?
	if ( absAngle < startInterval )
	{
		value = 0;
	}
	// in spline range?
	else if ( absAngle <= endInterval )
	{
		float newAngle = SimpleSpline( (absAngle - startInterval) / (endInterval-startInterval) ) * endInterval;
		// grab the sign from the initial value
		if ( value < 0 )
		{
			newAngle *= -1;
		}
		value = newAngle;
	}
	// else leave it alone, in linear range
	
	return value;
}

enum vehicle_pose_params
{
	VEH_FL_WHEEL_HEIGHT=0,
	VEH_FR_WHEEL_HEIGHT,
	VEH_RL_WHEEL_HEIGHT,
	VEH_RR_WHEEL_HEIGHT,
	VEH_FL_WHEEL_SPIN,
	VEH_FR_WHEEL_SPIN,
	VEH_RL_WHEEL_SPIN,
	VEH_RR_WHEEL_SPIN,
	VEH_STEER,
	VEH_ACTION,
	VEH_SPEEDO,

};


BEGIN_DATADESC_NO_BASE( CFourWheelVehiclePhysics )

// These two are reset every time 
//	DEFINE_FIELD( m_pOuter, FIELD_EHANDLE ),
//											m_pOuterServerVehicle;

	// Quiet down classcheck
	// DEFINE_FIELD( m_controls, vehicle_controlparams_t ),

	// Controls
	DEFINE_FIELD( m_controls.throttle, FIELD_FLOAT ),
	DEFINE_FIELD( m_controls.steering, FIELD_FLOAT ),
	DEFINE_FIELD( m_controls.brake, FIELD_FLOAT ),
	DEFINE_FIELD( m_controls.boost, FIELD_FLOAT ),
	DEFINE_FIELD( m_controls.handbrake, FIELD_BOOLEAN ),
	DEFINE_FIELD( m_controls.handbrakeLeft, FIELD_BOOLEAN ),
	DEFINE_FIELD( m_controls.handbrakeRight, FIELD_BOOLEAN ),
	DEFINE_FIELD( m_controls.brakepedal, FIELD_BOOLEAN ),
	DEFINE_FIELD( m_controls.bHasBrakePedal, FIELD_BOOLEAN ),

	// This has to be handled by the containing class owing to 'owner' issues
//	DEFINE_PHYSPTR( m_pVehicle ),

	DEFINE_FIELD( m_nSpeed, FIELD_INTEGER ),
	DEFINE_FIELD( m_nLastSpeed, FIELD_INTEGER ),
	DEFINE_FIELD( m_nRPM, FIELD_INTEGER ),
	DEFINE_FIELD( m_fLastBoost, FIELD_FLOAT ),
	DEFINE_FIELD( m_nBoostTimeLeft, FIELD_INTEGER ),
	DEFINE_FIELD( m_nHasBoost, FIELD_INTEGER ),

	DEFINE_FIELD( m_maxThrottle, FIELD_FLOAT ),
	DEFINE_FIELD( m_flMaxRevThrottle, FIELD_FLOAT ),
	DEFINE_FIELD( m_flMaxSpeed, FIELD_FLOAT ),
	DEFINE_FIELD( m_actionSpeed, FIELD_FLOAT ),

	// This has to be handled by the containing class owing to 'owner' issues
//	DEFINE_PHYSPTR_ARRAY( m_pWheels ),

	DEFINE_FIELD( m_wheelCount, FIELD_INTEGER ),

	DEFINE_ARRAY( m_wheelPosition, FIELD_VECTOR, 4 ),
	DEFINE_ARRAY( m_wheelRotation, FIELD_VECTOR, 4 ),
	DEFINE_ARRAY( m_wheelBaseHeight, FIELD_FLOAT, 4 ),
	DEFINE_ARRAY( m_wheelTotalHeight, FIELD_FLOAT, 4 ),
	DEFINE_ARRAY( m_poseParameters, FIELD_INTEGER, 12 ),
	DEFINE_FIELD( m_actionValue, FIELD_FLOAT ),
	DEFINE_KEYFIELD( m_actionScale, FIELD_FLOAT, "actionScale" ),
	DEFINE_FIELD( m_debugRadius, FIELD_FLOAT ),
	DEFINE_FIELD( m_throttleRate, FIELD_FLOAT ),
	DEFINE_FIELD( m_throttleStartTime, FIELD_FLOAT ),
	DEFINE_FIELD( m_throttleActiveTime, FIELD_FLOAT ),
	DEFINE_FIELD( m_turboTimer, FIELD_FLOAT ),

	DEFINE_FIELD( m_flVehicleVolume, FIELD_FLOAT ),
	DEFINE_FIELD( m_bIsOn, FIELD_BOOLEAN ),
	DEFINE_FIELD( m_bLastThrottle, FIELD_BOOLEAN ),
	DEFINE_FIELD( m_bLastBoost, FIELD_BOOLEAN ),
	DEFINE_FIELD( m_bLastSkid, FIELD_BOOLEAN ),
END_DATADESC()


//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CFourWheelVehiclePhysics::CFourWheelVehiclePhysics( CBaseAnimating *pOuter )
{
	m_flVehicleVolume = 0.5;
	m_pOuter = NULL;
	m_pOuterServerVehicle = NULL;
	m_flMaxSpeed = 30;
}

//-----------------------------------------------------------------------------
// Destructor
//-----------------------------------------------------------------------------
CFourWheelVehiclePhysics::~CFourWheelVehiclePhysics ()
{
	physenv->DestroyVehicleController( m_pVehicle );
}

//-----------------------------------------------------------------------------
// A couple wrapper methods to perform common operations
//-----------------------------------------------------------------------------
inline int CFourWheelVehiclePhysics::LookupPoseParameter( const char *szName )
{
	return m_pOuter->LookupPoseParameter( szName );
}

inline float CFourWheelVehiclePhysics::GetPoseParameter( int iParameter )
{
	return m_pOuter->GetPoseParameter( iParameter );
}

inline float CFourWheelVehiclePhysics::SetPoseParameter( int iParameter, float flValue )
{
	Assert(IsFinite(flValue));
	return m_pOuter->SetPoseParameter( iParameter, flValue );
}

inline bool CFourWheelVehiclePhysics::GetAttachment( const char *szName, Vector &origin, QAngle &angles )
{
	return m_pOuter->GetAttachment( szName, origin, angles );
}

//-----------------------------------------------------------------------------
// Methods related to spawn
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::InitializePoseParameters()
{
	m_poseParameters[VEH_FL_WHEEL_HEIGHT] = LookupPoseParameter( "vehicle_wheel_fl_height" );
	m_poseParameters[VEH_FR_WHEEL_HEIGHT] = LookupPoseParameter( "vehicle_wheel_fr_height" );
	m_poseParameters[VEH_RL_WHEEL_HEIGHT] = LookupPoseParameter( "vehicle_wheel_rl_height" );
	m_poseParameters[VEH_RR_WHEEL_HEIGHT] = LookupPoseParameter( "vehicle_wheel_rr_height" );
	m_poseParameters[VEH_FL_WHEEL_SPIN] = LookupPoseParameter( "vehicle_wheel_fl_spin" );
	m_poseParameters[VEH_FR_WHEEL_SPIN] = LookupPoseParameter( "vehicle_wheel_fr_spin" );
	m_poseParameters[VEH_RL_WHEEL_SPIN] = LookupPoseParameter( "vehicle_wheel_rl_spin" );
	m_poseParameters[VEH_RR_WHEEL_SPIN] = LookupPoseParameter( "vehicle_wheel_rr_spin" );
	m_poseParameters[VEH_STEER] = LookupPoseParameter( "vehicle_steer" );
	m_poseParameters[VEH_ACTION] = LookupPoseParameter( "vehicle_action" );
	m_poseParameters[VEH_SPEEDO] = LookupPoseParameter( "vehicle_guage" );


	// move the wheels to a neutral position
	SetPoseParameter( m_poseParameters[VEH_SPEEDO], 0 );
	SetPoseParameter( m_poseParameters[VEH_STEER], 0 );
	SetPoseParameter( m_poseParameters[VEH_FL_WHEEL_HEIGHT], 0 );
	SetPoseParameter( m_poseParameters[VEH_FR_WHEEL_HEIGHT], 0 );
	SetPoseParameter( m_poseParameters[VEH_RL_WHEEL_HEIGHT], 0 );
	SetPoseParameter( m_poseParameters[VEH_RR_WHEEL_HEIGHT], 0 );
	m_pOuter->InvalidateBoneCache();
}

//-----------------------------------------------------------------------------
// Purpose: Parses the vehicle's script
//-----------------------------------------------------------------------------
bool CFourWheelVehiclePhysics::ParseVehicleScript( const char *pScriptName, solid_t &solid, vehicleparams_t &vehicle)
{
	// Physics keeps a cache of these to share among spawns of vehicles or flush for debugging
	PhysFindOrAddVehicleScript( pScriptName, &vehicle, NULL );

	m_debugRadius = vehicle.axles[0].wheels.radius;
	CalcWheelData( vehicle );

	PhysModelParseSolid( solid, m_pOuter, m_pOuter->GetModelIndex() );
	
	// Allow the script to shift the center of mass
	if ( vehicle.body.massCenterOverride != vec3_origin )
	{
		solid.massCenterOverride = vehicle.body.massCenterOverride;
		solid.params.massCenterOverride = &solid.massCenterOverride;
	}

	// allow script to change the mass of the vehicle body
	if ( vehicle.body.massOverride > 0 )
	{
		solid.params.mass = vehicle.body.massOverride;
	}

	return true;
}

void CFourWheelVehiclePhysics::CalcWheelData( vehicleparams_t &vehicle )
{
	const char *pWheelAttachments[4] = { "wheel_fl", "wheel_fr", "wheel_rl", "wheel_rr" };
	Vector left, right;
	QAngle dummy;
	SetPoseParameter( m_poseParameters[VEH_FL_WHEEL_HEIGHT], 0 );
	SetPoseParameter( m_poseParameters[VEH_FR_WHEEL_HEIGHT], 0 );
	SetPoseParameter( m_poseParameters[VEH_RL_WHEEL_HEIGHT], 0 );
	SetPoseParameter( m_poseParameters[VEH_RR_WHEEL_HEIGHT], 0 );
	m_pOuter->InvalidateBoneCache();
	if ( GetAttachment( "wheel_fl", left, dummy ) && GetAttachment( "wheel_fr", right, dummy ) )
	{
		VectorITransform( left, m_pOuter->EntityToWorldTransform(), left );
		VectorITransform( right, m_pOuter->EntityToWorldTransform(), right );
		Vector center = (left + right) * 0.5;
		vehicle.axles[0].offset = center;
		vehicle.axles[0].wheelOffset = right - center;
		// Cache the base height of the wheels in body space
		m_wheelBaseHeight[0] = left.z;
		m_wheelBaseHeight[1] = right.z;
	}

	if ( GetAttachment( "wheel_rl", left, dummy ) && GetAttachment( "wheel_rr", right, dummy ) )
	{
		VectorITransform( left, m_pOuter->EntityToWorldTransform(), left );
		VectorITransform( right, m_pOuter->EntityToWorldTransform(), right );
		Vector center = (left + right) * 0.5;
		vehicle.axles[1].offset = center;
		vehicle.axles[1].wheelOffset = right - center;
		// Cache the base height of the wheels in body space
		m_wheelBaseHeight[2] = left.z;
		m_wheelBaseHeight[3] = right.z;
	}
	SetPoseParameter( m_poseParameters[VEH_FL_WHEEL_HEIGHT], 1 );
	SetPoseParameter( m_poseParameters[VEH_FR_WHEEL_HEIGHT], 1 );
	SetPoseParameter( m_poseParameters[VEH_RL_WHEEL_HEIGHT], 1 );
	SetPoseParameter( m_poseParameters[VEH_RR_WHEEL_HEIGHT], 1 );
	m_pOuter->InvalidateBoneCache();
	if ( GetAttachment( "wheel_fl", left, dummy ) && GetAttachment( "wheel_fr", right, dummy ) )
	{
		VectorITransform( left, m_pOuter->EntityToWorldTransform(), left );
		VectorITransform( right, m_pOuter->EntityToWorldTransform(), right );
		// Cache the height range of the wheels in body space
		m_wheelTotalHeight[0] = m_wheelBaseHeight[0] - left.z;
		m_wheelTotalHeight[1] = m_wheelBaseHeight[1] - right.z;
		vehicle.axles[0].wheels.springAdditionalLength = m_wheelTotalHeight[0];
	}

	if ( GetAttachment( "wheel_rl", left, dummy ) && GetAttachment( "wheel_rr", right, dummy ) )
	{
		VectorITransform( left, m_pOuter->EntityToWorldTransform(), left );
		VectorITransform( right, m_pOuter->EntityToWorldTransform(), right );
		// Cache the height range of the wheels in body space
		m_wheelTotalHeight[2] = m_wheelBaseHeight[0] - left.z;
		m_wheelTotalHeight[3] = m_wheelBaseHeight[1] - right.z;
		vehicle.axles[1].wheels.springAdditionalLength = m_wheelTotalHeight[2];
	}
	for ( int i = 0; i < 4; i++ )
	{
		if ( m_wheelTotalHeight[i] == 0.0f )
		{
			DevWarning("Vehicle %s has invalid wheel attachment for %s - no movement\n", STRING(m_pOuter->GetModelName()), pWheelAttachments[i]);
			m_wheelTotalHeight[i] = 1.0f;
		}
	}

	SetPoseParameter( m_poseParameters[VEH_FL_WHEEL_HEIGHT], 0 );
	SetPoseParameter( m_poseParameters[VEH_FR_WHEEL_HEIGHT], 0 );
	SetPoseParameter( m_poseParameters[VEH_RL_WHEEL_HEIGHT], 0 );
	SetPoseParameter( m_poseParameters[VEH_RR_WHEEL_HEIGHT], 0 );
	m_pOuter->InvalidateBoneCache();

	// Get raytrace offsets if they exist.
	if ( GetAttachment( "raytrace_fl", left, dummy ) && GetAttachment( "raytrace_fr", right, dummy ) )
	{
		VectorITransform( left, m_pOuter->EntityToWorldTransform(), left );
		VectorITransform( right, m_pOuter->EntityToWorldTransform(), right );
		Vector center = ( left + right ) * 0.5;
		vehicle.axles[0].raytraceCenterOffset = center;
		vehicle.axles[0].raytraceOffset = right - center;
	}

	if ( GetAttachment( "raytrace_rl", left, dummy ) && GetAttachment( "raytrace_rr", right, dummy ) )
	{
		VectorITransform( left, m_pOuter->EntityToWorldTransform(), left );
		VectorITransform( right, m_pOuter->EntityToWorldTransform(), right );
		Vector center = ( left + right ) * 0.5;
		vehicle.axles[1].raytraceCenterOffset = center;
		vehicle.axles[1].raytraceOffset = right - center;
	}
}


//-----------------------------------------------------------------------------
// Spawns the vehicle
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::Spawn( )
{
	Assert( m_pOuter );

	m_actionValue = 0;
	m_actionSpeed = 0;

	m_bIsOn = false;
	m_controls.handbrake = false;
	m_controls.handbrakeLeft = false;
	m_controls.handbrakeRight = false;
	m_controls.bHasBrakePedal = true;
	m_controls.bAnalogSteering = false;
	
	SetMaxThrottle( 1.0 );
	SetMaxReverseThrottle( -1.0f );

	InitializePoseParameters();
}


//-----------------------------------------------------------------------------
// Purpose: Initializes the vehicle physics
//			Called by our outer vehicle in it's Spawn()
//-----------------------------------------------------------------------------
bool CFourWheelVehiclePhysics::Initialize( const char *pVehicleScript, unsigned int nVehicleType )
{
	// Ok, turn on the simulation now
	// FIXME: Disabling collisions here is necessary because we seem to be
	// getting a one-frame collision between the old + new collision models
	if ( m_pOuter->VPhysicsGetObject() )
	{
		m_pOuter->VPhysicsGetObject()->EnableCollisions(false);
	}
	m_pOuter->VPhysicsDestroyObject();

	// Create the vphysics model + teleport it into position
	solid_t solid;
	vehicleparams_t vehicle;
	if (!ParseVehicleScript( pVehicleScript, solid, vehicle ))
	{
		UTIL_Remove(m_pOuter);
		return false;
	}

	// NOTE: this needs to be greater than your max framerate (so zero is still instant)
	m_throttleRate = 10000.0;
	if ( vehicle.engine.throttleTime > 0 )
	{
		m_throttleRate = 1.0 / vehicle.engine.throttleTime;
	}

	m_flMaxSpeed = vehicle.engine.maxSpeed;

	IPhysicsObject *pBody = m_pOuter->VPhysicsInitNormal( SOLID_VPHYSICS, 0, false, &solid );
	PhysSetGameFlags( pBody, FVPHYSICS_NO_SELF_COLLISIONS | FVPHYSICS_MULTIOBJECT_ENTITY );
	m_pVehicle = physenv->CreateVehicleController( pBody, vehicle, nVehicleType, physgametrace );
	m_wheelCount = m_pVehicle->GetWheelCount();
	for ( int i = 0; i < m_wheelCount; i++ )
	{
		m_pWheels[i] = m_pVehicle->GetWheel( i );
	}
	return true;
}


//-----------------------------------------------------------------------------
// Various steering parameters
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::SetThrottle( float flThrottle )
{
	m_controls.throttle = flThrottle;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::SetMaxThrottle( float flMaxThrottle )
{
	m_maxThrottle = flMaxThrottle;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::SetMaxReverseThrottle( float flMaxThrottle )
{
	m_flMaxRevThrottle = flMaxThrottle;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::SetSteering( float flSteering, float flSteeringRate )
{
	if ( !flSteeringRate )
	{
		m_controls.steering = flSteering;
	}
	else
	{
		m_controls.steering = Approach( flSteering, m_controls.steering, flSteeringRate );
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::SetSteeringDegrees( float flDegrees )
{
	vehicleparams_t &vehicleParams = m_pVehicle->GetVehicleParamsForChange();
	vehicleParams.steering.degreesSlow = flDegrees;
	vehicleParams.steering.degreesFast = flDegrees;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::SetAction( float flAction )
{
	m_actionSpeed = flAction;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::TurnOn( )
{
	if ( IsEngineDisabled() )
		return;

	if ( !m_bIsOn )
	{
		m_pOuterServerVehicle->SoundStart();
		m_bIsOn = true;
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::TurnOff( )
{
	ResetControls();

	if ( m_bIsOn )
	{
		m_pOuterServerVehicle->SoundShutdown();
		m_bIsOn = false;
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::SetBoost( float flBoost )
{
	if ( !IsEngineDisabled() )
	{
		m_controls.boost = flBoost;
	}
}

//------------------------------------------------------
// UpdateBooster - Calls UpdateBooster() in the vphysics
// code to allow the timer to be updated
//
// Returns: false if timer has expired (can use again and
//			can stop think
//			true if timer still running
//------------------------------------------------------
bool CFourWheelVehiclePhysics::UpdateBooster( void )
{
	float retval = m_pVehicle->UpdateBooster(gpGlobals->frametime );
	return ( retval > 0 );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::SetHasBrakePedal( bool bHasBrakePedal )
{
	m_controls.bHasBrakePedal = bHasBrakePedal;
}

//-----------------------------------------------------------------------------
// Teleport
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::Teleport( matrix3x4_t& relativeTransform )
{
	// We basically just have to make sure the wheels are in the right place
	// after teleportation occurs

	for ( int i = 0; i < m_wheelCount; i++ )
	{
		matrix3x4_t matrix, newMatrix;
		m_pWheels[i]->GetPositionMatrix( &matrix );
		ConcatTransforms( relativeTransform, matrix, newMatrix );
		m_pWheels[i]->SetPositionMatrix( newMatrix, true );
	}
	
	// Wake the vehicle back up after a teleport
	if ( m_pOuterServerVehicle && m_pOuterServerVehicle->GetFourWheelVehicle() )
	{
		IPhysicsObject *pObj = m_pOuterServerVehicle->GetFourWheelVehicle()->VPhysicsGetObject();
		if ( pObj )
		{
			pObj->Wake();
		}
	}
}

#if 1
// For the #if 0 debug code below!
#define HL2IVP_FACTOR	METERS_PER_INCH
#define IVP2HL(x)		(float)(x * (1.0f/HL2IVP_FACTOR))
#define HL2IVP(x)		(double)(x * HL2IVP_FACTOR)		
#endif

//-----------------------------------------------------------------------------
// Debugging methods
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::DrawDebugGeometryOverlays()
{
	for ( int iWheel = 0; iWheel < m_wheelCount; iWheel++ )
	{
		IPhysicsObject *pWheel = m_pVehicle->GetWheel( iWheel );
		float radius = pWheel->GetSphereRadius();
		
		Vector vecPos;
		QAngle vecRot;
		pWheel->GetPosition( &vecPos, &vecRot );
		// draw the physics object position/orientation
		NDebugOverlay::Sphere( vecPos, vecRot, radius, 0, 255, 0, 0, false, 0 );
		// draw the animation position/orientation
		NDebugOverlay::Sphere(m_wheelPosition[iWheel], m_wheelRotation[iWheel], radius, 255, 255, 0, 0, false, 0);
	}

	// Render vehicle data.
	IPhysicsObject *pBody = m_pOuter->VPhysicsGetObject();
	if ( pBody )
	{
		const vehicleparams_t vehicleParams = m_pVehicle->GetVehicleParams();

		// Draw a red cube as the "center" of the vehicle.
		Vector vecBodyPosition; 
		QAngle angBodyDirection;
		pBody->GetPosition( &vecBodyPosition, &angBodyDirection );
		NDebugOverlay::BoxAngles( vecBodyPosition, Vector( -5, -5, -5 ), Vector( 5, 5, 5 ), angBodyDirection, 255, 0, 0, 0 ,0 );

		matrix3x4_t matrix;
		AngleMatrix( angBodyDirection, vecBodyPosition, matrix );

		// Draw green cubes at axle centers.
		Vector vecAxlePositions[2], vecAxlePositionsHL[2];
		vecAxlePositions[0] = vehicleParams.axles[0].offset;
		vecAxlePositions[1] = vehicleParams.axles[1].offset;

		VectorTransform( vecAxlePositions[0], matrix, vecAxlePositionsHL[0] );		
		VectorTransform( vecAxlePositions[1], matrix, vecAxlePositionsHL[1] );

		NDebugOverlay::BoxAngles( vecAxlePositionsHL[0], Vector( -3, -3, -3 ), Vector( 3, 3, 3 ), angBodyDirection, 0, 255, 0, 0 ,0 );
		NDebugOverlay::BoxAngles( vecAxlePositionsHL[1], Vector( -3, -3, -3 ), Vector( 3, 3, 3 ), angBodyDirection, 0, 255, 0, 0 ,0 );

		// Draw wheel raycasts in yellow
		vehicle_debugcarsystem_t debugCarSystem;
		m_pVehicle->GetCarSystemDebugData( debugCarSystem );
		for ( int iWheel = 0; iWheel < 4; ++iWheel )
		{
			Vector vecStart, vecEnd, vecImpact;

			// Hack for now.
			float tmpY = IVP2HL( debugCarSystem.vecWheelRaycasts[iWheel][0].z );
			vecStart.z = -IVP2HL( debugCarSystem.vecWheelRaycasts[iWheel][0].y );
			vecStart.y = tmpY;
			vecStart.x = IVP2HL( debugCarSystem.vecWheelRaycasts[iWheel][0].x );

			tmpY = IVP2HL( debugCarSystem.vecWheelRaycasts[iWheel][1].z );
			vecEnd.z = -IVP2HL( debugCarSystem.vecWheelRaycasts[iWheel][1].y );
			vecEnd.y = tmpY;
			vecEnd.x = IVP2HL( debugCarSystem.vecWheelRaycasts[iWheel][1].x );

			tmpY = IVP2HL( debugCarSystem.vecWheelRaycastImpacts[iWheel].z );
			vecImpact.z = -IVP2HL( debugCarSystem.vecWheelRaycastImpacts[iWheel].y );
			vecImpact.y = tmpY;
			vecImpact.x = IVP2HL( debugCarSystem.vecWheelRaycastImpacts[iWheel].x );

			NDebugOverlay::BoxAngles( vecStart, Vector( -1 , -1, -1 ), Vector( 1, 1, 1 ), angBodyDirection, 0, 255, 0, 0, 0  );
			NDebugOverlay::Line( vecStart, vecEnd, 255, 255, 0, true, 0 );
			NDebugOverlay::BoxAngles( vecEnd, Vector( -1, -1, -1 ), Vector( 1, 1, 1 ), angBodyDirection, 255, 0, 0, 0, 0 );

			NDebugOverlay::BoxAngles( vecImpact, Vector( -0.5f , -0.5f, -0.5f ), Vector( 0.5f, 0.5f, 0.5f ), angBodyDirection, 0, 0, 255, 0, 0  );
			DebugDrawContactPoints( m_pVehicle->GetWheel(iWheel) );
		}
	}
}

int CFourWheelVehiclePhysics::DrawDebugTextOverlays( int nOffset )
{
	const vehicle_operatingparams_t &params = m_pVehicle->GetOperatingParams();
	char tempstr[512];
	Q_snprintf( tempstr,sizeof(tempstr), "Speed %.1f  T/S/B (%.0f/%.0f/%.1f)", params.speed, m_controls.throttle, m_controls.steering, m_controls.brake );
	m_pOuter->EntityText( nOffset, tempstr, 0 );
	nOffset++;
	Msg( "%s", tempstr );

	Q_snprintf( tempstr,sizeof(tempstr), "Gear: %d, RPM %4d", params.gear, (int)params.engineRPM );
	m_pOuter->EntityText( nOffset, tempstr, 0 );
	nOffset++;
	Msg( " %s\n", tempstr );

	return nOffset;
}

//----------------------------------------------------
// Place dust at vector passed in
//----------------------------------------------------
void CFourWheelVehiclePhysics::PlaceWheelDust( int wheelIndex, bool ignoreSpeed )
{
	// New vehicles handle this deeper into the base class
	if ( hl2_episodic.GetBool() )
		return;

	// Old dust
	Vector	vecPos, vecVel;
	m_pVehicle->GetWheelContactPoint( wheelIndex, &vecPos, NULL );

	vecVel.Random( -1.0f, 1.0f );
	vecVel.z = random->RandomFloat( 0.3f, 1.0f );

	VectorNormalize( vecVel );

	// Higher speeds make larger dust clouds
	float flSize;
	if ( ignoreSpeed )
	{
		flSize = 1.0f;
	}
	else
	{
		flSize = RemapValClamped( m_nSpeed, DUST_SPEED, m_flMaxSpeed, 0.0f, 1.0f );
	}

	if ( flSize )
	{
		CEffectData	data;

		data.m_vOrigin = vecPos;
		data.m_vNormal = vecVel;
		data.m_flScale = flSize;

		DispatchEffect( "WheelDust", data );
	}
}

//-----------------------------------------------------------------------------
// Frame-based updating 
//-----------------------------------------------------------------------------
bool CFourWheelVehiclePhysics::Think()
{
	if (!m_pVehicle)
		return false;

	// Update sound + physics state
	const vehicle_operatingparams_t &carState = m_pVehicle->GetOperatingParams();
	const vehicleparams_t &vehicleData = m_pVehicle->GetVehicleParams();

	// Set save data.
	float carSpeed = fabs( INS2MPH( carState.speed ) );
	m_nLastSpeed = m_nSpeed;
	m_nSpeed = ( int )carSpeed;
	m_nRPM = ( int )carState.engineRPM;
	m_nHasBoost = vehicleData.engine.boostDelay;	// if we have any boost delay, vehicle has boost ability

	m_pVehicle->Update( gpGlobals->frametime, m_controls);

	// boost sounds
	if( IsBoosting() && !m_bLastBoost )
	{
		m_bLastBoost = true;
		m_turboTimer = gpGlobals->curtime + 2.75f;		// min duration for turbo sound
	}
	else if( !IsBoosting() && m_bLastBoost )
	{
		if ( gpGlobals->curtime >= m_turboTimer )
		{
			m_bLastBoost = false;
		}
	}

	m_fLastBoost = carState.boostDelay;
	m_nBoostTimeLeft =  carState.boostTimeLeft;

	// UNDONE: Use skid info from the physics system?
	// Only check wheels if we're not being carried by a dropship
	if ( m_pOuter->VPhysicsGetObject() && !m_pOuter->VPhysicsGetObject()->GetShadowController() )
	{
		const float skidFactor = 0.15f;
		const float minSpeed = DEFAULT_SKID_THRESHOLD / skidFactor;
		// we have to slide at least 15% of our speed at higher speeds to make the skid sound (otherwise it can be too frequent)
		float skidThreshold = m_bLastSkid ? DEFAULT_SKID_THRESHOLD : (carState.speed * 0.15f);
		if ( skidThreshold < DEFAULT_SKID_THRESHOLD )
		{
			// otherwise, ramp in the skid threshold to avoid the sound at really low speeds unless really skidding
			skidThreshold = RemapValClamped( fabs(carState.speed), 0, minSpeed, DEFAULT_SKID_THRESHOLD*8, DEFAULT_SKID_THRESHOLD );
		}
		// check for skidding, if we're skidding, need to play the sound
		if ( carState.skidSpeed > skidThreshold && m_bIsOn )
		{
			if ( !m_bLastSkid )	// only play sound once
			{
				m_bLastSkid = true;
				CPASAttenuationFilter filter( m_pOuter );
				m_pOuterServerVehicle->PlaySound( VS_SKID_FRICTION_NORMAL );
			}

			// kick up dust from the wheels while skidding
			for ( int i = 0; i < 4; i++ )
			{
				PlaceWheelDust( i, true );
			}
		}
		else if ( m_bLastSkid == true )
		{
			m_bLastSkid = false;
			m_pOuterServerVehicle->StopSound( VS_SKID_FRICTION_NORMAL );
		}

		// toss dust up from the wheels of the vehicle if we're moving fast enough
		if ( m_nSpeed >= DUST_SPEED && vehicleData.steering.dustCloud && m_bIsOn )
		{
			for ( int i = 0; i < 4; i++ )
			{
				PlaceWheelDust( i );
			}
		}
	}

	// Make the steering wheel match the input, with a little dampening.
	#define STEER_DAMPING	0.8
	float flSteer = GetPoseParameter( m_poseParameters[VEH_STEER] );
	float flPhysicsSteer = carState.steeringAngle / vehicleData.steering.degreesSlow;
	SetPoseParameter( m_poseParameters[VEH_STEER], (STEER_DAMPING * flSteer) + ((1 - STEER_DAMPING) * flPhysicsSteer) );

	m_actionValue += m_actionSpeed * m_actionScale * gpGlobals->frametime;
	SetPoseParameter( m_poseParameters[VEH_ACTION], m_actionValue );

	// setup speedometer
	if ( m_bIsOn == true )
	{
		float displaySpeed = m_nSpeed / MAX_GUAGE_SPEED;
		SetPoseParameter( m_poseParameters[VEH_SPEEDO], displaySpeed );
	}

	return m_bIsOn;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
bool CFourWheelVehiclePhysics::VPhysicsUpdate( IPhysicsObject *pPhysics )
{
	// must be a wheel
	if ( pPhysics == m_pOuter->VPhysicsGetObject() )
		return true;

	// This is here so we can make the pose parameters of the wheels
	// reflect their current physics state
	for ( int i = 0; i < m_wheelCount; i++ )
	{
		if ( pPhysics == m_pWheels[i] )
		{
			Vector tmp;
			pPhysics->GetPosition( &m_wheelPosition[i], &m_wheelRotation[i] );

			// transform the wheel into body space
			VectorITransform( m_wheelPosition[i], m_pOuter->EntityToWorldTransform(), tmp );
			SetPoseParameter( m_poseParameters[VEH_FL_WHEEL_HEIGHT + i], (m_wheelBaseHeight[i] - tmp.z) / m_wheelTotalHeight[i] );
			SetPoseParameter( m_poseParameters[VEH_FL_WHEEL_SPIN + i], -m_wheelRotation[i].z );
			return false;
		}
	}

	return false;
}


//-----------------------------------------------------------------------------
// Shared code to compute the vehicle view position
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::GetVehicleViewPosition( const char *pViewAttachment, float flPitchFactor, Vector *pAbsOrigin, QAngle *pAbsAngles )
{
	matrix3x4_t vehicleEyePosToWorld;
	Vector vehicleEyeOrigin;
	QAngle vehicleEyeAngles;
	GetAttachment( pViewAttachment, vehicleEyeOrigin, vehicleEyeAngles );
	AngleMatrix( vehicleEyeAngles, vehicleEyePosToWorld );

#ifdef HL2_DLL
	// View dampening.
	if ( r_VehicleViewDampen.GetInt() )
	{
		m_pOuterServerVehicle->GetFourWheelVehicle()->DampenEyePosition( vehicleEyeOrigin, vehicleEyeAngles );
	}
#endif

	// Compute the relative rotation between the unperterbed eye attachment + the eye angles
	matrix3x4_t cameraToWorld;
	AngleMatrix( *pAbsAngles, cameraToWorld );

	matrix3x4_t worldToEyePos;
	MatrixInvert( vehicleEyePosToWorld, worldToEyePos );

	matrix3x4_t vehicleCameraToEyePos;
	ConcatTransforms( worldToEyePos, cameraToWorld, vehicleCameraToEyePos );

	// Now perterb the attachment point
	vehicleEyeAngles.x = RemapAngleRange( PITCH_CURVE_ZERO * flPitchFactor, PITCH_CURVE_LINEAR, vehicleEyeAngles.x );
	vehicleEyeAngles.z = RemapAngleRange( ROLL_CURVE_ZERO * flPitchFactor, ROLL_CURVE_LINEAR, vehicleEyeAngles.z );
	AngleMatrix( vehicleEyeAngles, vehicleEyeOrigin, vehicleEyePosToWorld );

	// Now treat the relative eye angles as being relative to this new, perterbed view position...
	matrix3x4_t newCameraToWorld;
	ConcatTransforms( vehicleEyePosToWorld, vehicleCameraToEyePos, newCameraToWorld );

	// output new view abs angles
	MatrixAngles( newCameraToWorld, *pAbsAngles );

	// UNDONE: *pOrigin would already be correct in single player if the HandleView() on the server ran after vphysics
	MatrixGetColumn( newCameraToWorld, 3, *pAbsOrigin );
}


//-----------------------------------------------------------------------------
// Control initialization
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::ResetControls()
{
	m_controls.handbrake = true;
	m_controls.handbrakeLeft = false;
	m_controls.handbrakeRight = false;
	m_controls.boost = 0;
	m_controls.brake = 0.0f;
	m_controls.throttle = 0;
	m_controls.steering = 0;
}

void CFourWheelVehiclePhysics::ReleaseHandbrake()
{
	m_controls.handbrake = false;
}

void CFourWheelVehiclePhysics::SetHandbrake( bool bBrake )
{
	m_controls.handbrake = bBrake;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::EnableMotion( void )
{
	for( int iWheel = 0; iWheel < m_wheelCount; ++iWheel )
	{
		m_pWheels[iWheel]->EnableMotion( true );
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::DisableMotion( void )
{
	Vector vecZero( 0.0f, 0.0f, 0.0f );
	AngularImpulse angNone( 0.0f, 0.0f, 0.0f );

	for( int iWheel = 0; iWheel < m_wheelCount; ++iWheel )
	{
		m_pWheels[iWheel]->SetVelocity( &vecZero, &angNone );
		m_pWheels[iWheel]->EnableMotion( false );
	}
}

float CFourWheelVehiclePhysics::GetHLSpeed() const
{
	const vehicle_operatingparams_t &carState = m_pVehicle->GetOperatingParams();
	return carState.speed;
}

float CFourWheelVehiclePhysics::GetSteering() const
{
	return m_controls.steering;
}

float CFourWheelVehiclePhysics::GetSteeringDegrees() const
{
	const vehicleparams_t vehicleParams = m_pVehicle->GetVehicleParams();
	return vehicleParams.steering.degreesSlow;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::SteeringRest( float carSpeed, const vehicleparams_t &vehicleData )
{
	float flSteeringRate = RemapValClamped( carSpeed, vehicleData.steering.speedSlow, vehicleData.steering.speedFast, 
		vehicleData.steering.steeringRestRateSlow, vehicleData.steering.steeringRestRateFast );
	m_controls.steering = Approach(0, m_controls.steering, flSteeringRate * gpGlobals->frametime );
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::SteeringTurn( float carSpeed, const vehicleparams_t &vehicleData, bool bTurnLeft, bool bBrake, bool bThrottle )
{
	float flTargetSteering = bTurnLeft ? -1.0f : 1.0f;
	// steering speeds are stored in MPH
	float flSteeringRestRate = RemapValClamped( carSpeed, vehicleData.steering.speedSlow, vehicleData.steering.speedFast, 
		vehicleData.steering.steeringRestRateSlow, vehicleData.steering.steeringRestRateFast );

	float carSpeedIns = MPH2INS(carSpeed);
	// engine speeds are stored in in/s
	if ( carSpeedIns > vehicleData.engine.maxSpeed )
	{
		flSteeringRestRate = RemapValClamped( carSpeedIns, vehicleData.engine.maxSpeed, vehicleData.engine.boostMaxSpeed, vehicleData.steering.steeringRestRateFast, vehicleData.steering.steeringRestRateFast*0.5f );
	}

	const vehicle_operatingparams_t &carState = m_pVehicle->GetOperatingParams();
	bool bIsBoosting = carState.isTorqueBoosting;

	// if you're recovering from a boost and still going faster than max, use the boost steering values
	bool bIsBoostRecover = (carState.boostTimeLeft == 100 || carState.boostTimeLeft == 0) ? false : true;
	float boostMinSpeed = vehicleData.engine.maxSpeed * vehicleData.engine.autobrakeSpeedGain;
	if ( !bIsBoosting && bIsBoostRecover && carSpeedIns > boostMinSpeed )
	{
		bIsBoosting = true;
	}

	if ( bIsBoosting )
	{
		flSteeringRestRate *= vehicleData.steering.boostSteeringRestRateFactor;
	}
	else if ( bThrottle )
	{
		flSteeringRestRate *= vehicleData.steering.throttleSteeringRestRateFactor;
	}

	float flSteeringRate = RemapValClamped( carSpeed, vehicleData.steering.speedSlow, vehicleData.steering.speedFast, 
		vehicleData.steering.steeringRateSlow, vehicleData.steering.steeringRateFast );

	if ( fabs(flSteeringRate) < flSteeringRestRate )
	{
		if ( Sign(flTargetSteering) != Sign(m_controls.steering) )
		{
			flSteeringRate = flSteeringRestRate;
		}
	}
	if ( bIsBoosting )
	{
		flSteeringRate *= vehicleData.steering.boostSteeringRateFactor;
	}
	else if ( bBrake )
	{
		flSteeringRate *= vehicleData.steering.brakeSteeringRateFactor;
	}
	flSteeringRate *= gpGlobals->frametime;
	m_controls.steering = Approach( flTargetSteering, m_controls.steering, flSteeringRate );
	m_controls.bAnalogSteering = false;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::SteeringTurnAnalog( float carSpeed, const vehicleparams_t &vehicleData, float sidemove )
{

	// OLD Code
#if 0
	float flSteeringRate = STEERING_BASE_RATE;

	float factor = clamp( fabs( sidemove ) / STICK_EXTENTS, 0.0f, 1.0f );

	factor *= 30;
	flSteeringRate *= log( factor );
	flSteeringRate *= gpGlobals->frametime;

	SetSteering( sidemove < 0.0f ? -1 : 1, flSteeringRate );
#else
	// This is tested with gamepads with analog sticks.  It gives full analog control allowing the player to hold shallow turns.
	float steering = ( sidemove / STICK_EXTENTS );

	float flSign = ( steering > 0 ) ? 1.0f : -1.0f;
	float flSteerAdj = RemapValClamped( fabs( steering ), xbox_steering_deadzone.GetFloat(), 1.0f, 0.0f, 1.0f );

	float flSteeringRate = RemapValClamped( carSpeed, vehicleData.steering.speedSlow, vehicleData.steering.speedFast, 
		vehicleData.steering.steeringRateSlow, vehicleData.steering.steeringRateFast );
	flSteeringRate *= vehicleData.steering.throttleSteeringRestRateFactor;

	m_controls.bAnalogSteering = true;
	SetSteering( flSign * flSteerAdj, flSteeringRate * gpGlobals->frametime );
#endif
}

//-----------------------------------------------------------------------------
// Methods related to actually driving the vehicle
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::UpdateDriverControls( CUserCmd *cmd, float flFrameTime )
{
	const float SPEED_THROTTLE_AS_BRAKE = 2.0f;
	int nButtons = cmd->buttons;

	// Get vehicle data.
	const vehicle_operatingparams_t &carState = m_pVehicle->GetOperatingParams();
	const vehicleparams_t &vehicleData = m_pVehicle->GetVehicleParams();

	// Get current speed in miles/hour.
	float flCarSign = 0.0f;
	if (carState.speed >= SPEED_THROTTLE_AS_BRAKE) 
	{
		flCarSign = 1.0f;
	}
	else if ( carState.speed <= -SPEED_THROTTLE_AS_BRAKE )
	{
		flCarSign = -1.0f;
	}
	float carSpeed = fabs(INS2MPH(carState.speed));

	// If going forward and turning hard, keep the throttle applied.
	if( xbox_autothrottle.GetBool() && cmd->forwardmove > 0.0f )
	{
		if( carSpeed > GetMaxSpeed() * 0.75 )
		{
			if( fabs(cmd->sidemove) > cmd->forwardmove )
			{
				cmd->forwardmove = STICK_EXTENTS;
			}
		}
	}

	//Msg("F: %4.1f \tS: %4.1f!\tSTEER: %3.1f\n", cmd->forwardmove, cmd->sidemove, carState.steeringAngle);
	// If changing direction, use default "return to zero" speed to more quickly transition.
	if ( ( nButtons & IN_MOVELEFT ) || ( nButtons & IN_MOVERIGHT ) )
	{
		bool bTurnLeft = ( (nButtons & IN_MOVELEFT) != 0 );
		bool bBrake = ((nButtons & IN_BACK) != 0);
		bool bThrottleDown = ( (nButtons & IN_FORWARD) != 0 ) && !bBrake;
		SteeringTurn( carSpeed, vehicleData, bTurnLeft, bBrake, bThrottleDown );
	}
	else if ( cmd->sidemove != 0.0f )
	{
		SteeringTurnAnalog( carSpeed, vehicleData, cmd->sidemove );
	}
	else
	{
		SteeringRest( carSpeed, vehicleData );
	}

	// Set vehicle control inputs.
	m_controls.boost = 0;
	m_controls.handbrake = false;
	m_controls.handbrakeLeft = false;
	m_controls.handbrakeRight = false;
	m_controls.brakepedal = false;	
	bool bThrottle;

	//-------------------------------------------------------------------------
	// Analog throttle biasing - This code gives the player a bit of control stick
	// 'slop' in the opposite direction that they are driving. If a player is 
	// driving forward and makes a hard turn in which the stick actually goes
	// below neutral (toward reverse), this code continues to propel the car 
	// forward unless the player makes a significant motion towards reverse.
	// (The inverse is true when driving in reverse and the stick is moved slightly forward)
	//-------------------------------------------------------------------------
	CBaseEntity *pDriver = m_pOuterServerVehicle->GetDriver();
	CBasePlayer *pPlayerDriver;
	float flBiasThreshold = xbox_throttlebias.GetFloat();

	if( pDriver && pDriver->IsPlayer() )
	{
		pPlayerDriver = dynamic_cast<CBasePlayer*>(pDriver);

		if( cmd->forwardmove == 0.0f && (fabs(cmd->sidemove) < 200.0f) )
		{
			// If the stick goes neutral, clear out the bias. When the bias is neutral, it will begin biasing
			// in whichever direction the user next presses the analog stick.
			pPlayerDriver->SetVehicleAnalogControlBias( VEHICLE_ANALOG_BIAS_NONE );
		}
		else if( cmd->forwardmove > 0.0f)
		{
			if( pPlayerDriver->GetVehicleAnalogControlBias() == VEHICLE_ANALOG_BIAS_REVERSE )
			{
				// Player is pushing forward, but the controller is currently biased for reverse driving.
				// Must pass a threshold to be accepted as forward input. Otherwise we just spoof a reduced reverse input 
				// to keep the car moving in the direction the player probably expects.
				if( cmd->forwardmove < flBiasThreshold )
				{
					cmd->forwardmove = -xbox_throttlespoof.GetFloat();
				}
				else
				{
					// Passed the threshold. Allow the direction change to occur.
					pPlayerDriver->SetVehicleAnalogControlBias( VEHICLE_ANALOG_BIAS_FORWARD );
				}
			}
			else if( pPlayerDriver->GetVehicleAnalogControlBias() == VEHICLE_ANALOG_BIAS_NONE )
			{
				pPlayerDriver->SetVehicleAnalogControlBias( VEHICLE_ANALOG_BIAS_FORWARD );
			}
		}
		else if( cmd->forwardmove < 0.0f )
		{
			if( pPlayerDriver->GetVehicleAnalogControlBias() == VEHICLE_ANALOG_BIAS_FORWARD )
			{
				// Inverse of above logic
				if( cmd->forwardmove > -flBiasThreshold )
				{
					cmd->forwardmove = xbox_throttlespoof.GetFloat();
				}
				else
				{
					pPlayerDriver->SetVehicleAnalogControlBias( VEHICLE_ANALOG_BIAS_REVERSE );
				}
			}
			else if( pPlayerDriver->GetVehicleAnalogControlBias() == VEHICLE_ANALOG_BIAS_NONE )
			{
				pPlayerDriver->SetVehicleAnalogControlBias( VEHICLE_ANALOG_BIAS_REVERSE );
			}
		}
	}

	//=========================
	// analog control
	//=========================
	if( cmd->forwardmove > 0.0f )
	{
		float flAnalogThrottle = cmd->forwardmove / STICK_EXTENTS;

		flAnalogThrottle = clamp( flAnalogThrottle, 0.25f, 1.0f );

		bThrottle = true;
		if ( m_controls.throttle < 0 )
		{
			m_controls.throttle = 0;
		}

		float flMaxThrottle = MAX( 0.1, m_maxThrottle );
		if ( m_controls.steering != 0 )
		{
			float flThrottleReduce = 0;

			// ramp this in, don't just start at the slow speed reduction (helps accelerate from a stop)
			if ( carSpeed < vehicleData.steering.speedSlow )
			{
				flThrottleReduce = RemapValClamped( carSpeed, 0, vehicleData.steering.speedSlow, 
					0, vehicleData.steering.turnThrottleReduceSlow );
			}
			else
			{
				flThrottleReduce = RemapValClamped( carSpeed, vehicleData.steering.speedSlow, vehicleData.steering.speedFast, 
					vehicleData.steering.turnThrottleReduceSlow, vehicleData.steering.turnThrottleReduceFast );
			}

			float limit = 1.0f - (flThrottleReduce * fabs(m_controls.steering));
			if ( limit < 0 )
				limit = 0;
			flMaxThrottle = MIN( flMaxThrottle, limit );
		}

		m_controls.throttle = Approach( flMaxThrottle * flAnalogThrottle, m_controls.throttle, flFrameTime * m_throttleRate );

		// Apply the brake.
		if ( ( flCarSign < 0.0f ) && m_controls.bHasBrakePedal )
		{
			m_controls.brake = Approach( BRAKE_MAX_VALUE, m_controls.brake, flFrameTime * r_vehicleBrakeRate.GetFloat() * BRAKE_BACK_FORWARD_SCALAR );
			m_controls.brakepedal = true;	
			m_controls.throttle = 0.0f;
			bThrottle = false;
		}
		else
		{
			m_controls.brake = 0.0f;
		}
	}
	else if( cmd->forwardmove < 0.0f )
	{
		float flAnalogBrake = fabs(cmd->forwardmove / STICK_EXTENTS);

		flAnalogBrake = clamp( flAnalogBrake, 0.25f, 1.0f );

		bThrottle = true;
		if ( m_controls.throttle > 0 )
		{
			m_controls.throttle = 0;
		}

		float flMaxThrottle = MIN( -0.1, m_flMaxRevThrottle  );
		m_controls.throttle = Approach( flMaxThrottle * flAnalogBrake, m_controls.throttle, flFrameTime * m_throttleRate );

		// Apply the brake.
		if ( ( flCarSign > 0.0f ) && m_controls.bHasBrakePedal )
		{
			m_controls.brake = Approach( BRAKE_MAX_VALUE, m_controls.brake, flFrameTime * r_vehicleBrakeRate.GetFloat() );
			m_controls.brakepedal = true;
			m_controls.throttle = 0.0f;
			bThrottle = false;
		}
		else
		{
			m_controls.brake = 0.0f;
		}
	}
	// digital control
	else if ( nButtons & IN_FORWARD )
	{
		bThrottle = true;
		if ( m_controls.throttle < 0 )
		{
			m_controls.throttle = 0;
		}

		float flMaxThrottle = MAX( 0.1, m_maxThrottle );

		if ( m_controls.steering != 0 )
		{
			float flThrottleReduce = 0;

			// ramp this in, don't just start at the slow speed reduction (helps accelerate from a stop)
			if ( carSpeed < vehicleData.steering.speedSlow )
			{
				flThrottleReduce = RemapValClamped( carSpeed, 0, vehicleData.steering.speedSlow, 
					0, vehicleData.steering.turnThrottleReduceSlow );
			}
			else
			{
				flThrottleReduce = RemapValClamped( carSpeed, vehicleData.steering.speedSlow, vehicleData.steering.speedFast, 
					vehicleData.steering.turnThrottleReduceSlow, vehicleData.steering.turnThrottleReduceFast );
			}
			
			float limit = 1.0f - (flThrottleReduce * fabs(m_controls.steering));
			if ( limit < 0 )
				limit = 0;
			flMaxThrottle = MIN( flMaxThrottle, limit );
		}

		m_controls.throttle = Approach( flMaxThrottle, m_controls.throttle, flFrameTime * m_throttleRate );

		// Apply the brake.
		if ( ( flCarSign < 0.0f ) && m_controls.bHasBrakePedal )
		{
			m_controls.brake = Approach( BRAKE_MAX_VALUE, m_controls.brake, flFrameTime * r_vehicleBrakeRate.GetFloat() * BRAKE_BACK_FORWARD_SCALAR );
			m_controls.brakepedal = true;	
			m_controls.throttle = 0.0f;
			bThrottle = false;
		}
		else
		{
			m_controls.brake = 0.0f;
		}
	}
	else if ( nButtons & IN_BACK )
	{
		bThrottle = true;
		if ( m_controls.throttle > 0 )
		{
			m_controls.throttle = 0;
		}

		float flMaxThrottle = MIN( -0.1, m_flMaxRevThrottle );
		m_controls.throttle = Approach( flMaxThrottle, m_controls.throttle, flFrameTime * m_throttleRate );

		// Apply the brake.
		if ( ( flCarSign > 0.0f ) && m_controls.bHasBrakePedal )
		{
			m_controls.brake = Approach( BRAKE_MAX_VALUE, m_controls.brake, flFrameTime * r_vehicleBrakeRate.GetFloat() );
			m_controls.brakepedal = true;
			m_controls.throttle = 0.0f;
			bThrottle = false;
		}
		else
		{
			m_controls.brake = 0.0f;
		}
	}
	else
	{
		bThrottle = false;
		m_controls.throttle = 0;
		m_controls.brake = 0.0f;
	}

	if ( ( nButtons & IN_SPEED ) && !IsEngineDisabled() && bThrottle )
	{
		m_controls.boost = 1.0f;
	}

	// Using has brakepedal for handbrake as well.
	if ( ( nButtons & IN_JUMP ) && m_controls.bHasBrakePedal )
	{
		m_controls.handbrake = true;	

		if ( cmd->sidemove < -100 )
		{
			m_controls.handbrakeLeft = true;
		}
		else if ( cmd->sidemove > 100 )
		{
			m_controls.handbrakeRight = true;
		}

		// Prevent playing of the engine revup when we're braking
		bThrottle = false;
	}

	if ( IsEngineDisabled() )
	{
		m_controls.throttle = 0.0f;
		m_controls.handbrake = true;
		bThrottle = false;
	}

	// throttle sounds
	// If we dropped a bunch of speed, restart the throttle
	if ( bThrottle && (m_nLastSpeed > m_nSpeed && (m_nLastSpeed - m_nSpeed > 10)) )
	{
		m_bLastThrottle = false;
	}

	// throttle down now but not before??? (or we're braking)
	if ( !m_controls.handbrake && !m_controls.brakepedal && bThrottle && !m_bLastThrottle )
	{
		m_throttleStartTime = gpGlobals->curtime;		// need to track how long throttle is down
		m_bLastThrottle = true;
	}
	// throttle up now but not before??
	else if ( !bThrottle && m_bLastThrottle && IsEngineDisabled() == false )
	{
		m_throttleActiveTime = gpGlobals->curtime - m_throttleStartTime;
		m_bLastThrottle = false;
	}

	float flSpeedPercentage = clamp( m_nSpeed / m_flMaxSpeed, 0.f, 1.f );
	vbs_sound_update_t params;
	params.Defaults();
	params.bReverse = (m_controls.throttle < 0);
	params.bThrottleDown = bThrottle;
	params.bTurbo = IsBoosting();
	params.bVehicleInWater = m_pOuterServerVehicle->IsVehicleBodyInWater();
	params.flCurrentSpeedFraction = flSpeedPercentage;
	params.flFrameTime = flFrameTime;
	params.flWorldSpaceSpeed = carState.speed;
	m_pOuterServerVehicle->SoundUpdate( params );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CFourWheelVehiclePhysics::IsBoosting( void )
{
	const vehicleparams_t *pVehicleParams = &m_pVehicle->GetVehicleParams();
	const vehicle_operatingparams_t *pVehicleOperating = &m_pVehicle->GetOperatingParams();
	if ( pVehicleParams && pVehicleOperating )
	{	
		if ( ( pVehicleOperating->boostDelay - pVehicleParams->engine.boostDelay ) > 0.0f )
			return true;
	}

	return false;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CFourWheelVehiclePhysics::SetDisableEngine( bool bDisable )
{
	// Set the engine state.
	m_pVehicle->SetEngineDisabled( bDisable );
}

static int AddPhysToList( IPhysicsObject **pList, int listMax, int count, IPhysicsObject *pPhys )
{
	if ( pPhys )
	{
		if ( count < listMax )
		{
			pList[count] = pPhys;
			count++;
		}
	}
	return count;
}

int CFourWheelVehiclePhysics::VPhysicsGetObjectList( IPhysicsObject **pList, int listMax )
{
	int count = 0;
	// add the body
	count = AddPhysToList( pList, listMax, count, m_pOuter->VPhysicsGetObject() );
	for ( int i = 0; i < 4; i++ )
	{
		count = AddPhysToList( pList, listMax, count, m_pWheels[i] );
	}
	return count;
}