summaryrefslogtreecommitdiff
path: root/game/shared/tf2/tf_gamemovement.cpp
blob: 46366d93dbe534ec0aeaecd0555f0f3c1b9793fb (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
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: 
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "tf_gamemovement.h"
#include "in_buttons.h"
#include "tier0/vprof.h"
#include "SoundEmitterSystem/isoundemittersystembase.h"

#define	SPEED_STOP_THRESHOLD		1.0f
#define BUMP_MAX_COUNT				8

//#define IMPACT_NORMAL_FLOOR			0.35f
#define	IMPACT_NORMAL_FLOOR			0.7f
#define IMPACT_NORMAL_WALL			0.0f

enum
{
	MOVEMENT_BLOCKED_NONE  = 0x0,
	MOVEMENT_BLOCKED_WALL  = 0x1,
	MOVEMENT_BLOCKED_FLOOR = 0x2,
	MOVEMENT_BLOCKED_ALL   = 0x4
};

#define SPEED_CROP_FRACTION_WALKING		0.4f
#define SPEED_CROP_FRACTION_USING		0.3f
#define SPEED_CROP_FRACTION_DUCKING		0.3f

char    *va(char *format, ...);

extern bool g_bMovementOptimizations;

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGameMovement::CategorizePosition( void )
{
	VPROF( "CTFGameMovement::CategorizePosition" );

	// Doing this before we move may introduce a potential latency in water detection, but
	// doing it after can get us stuck on the bottom in water if the amount we move up
	// is less than the 1 pixel 'threshold' we're about to snap to.	Also, we'll call
	// this several times per frame, so we really need to avoid sticking to the bottom of
	// water on each call, and the converse case will correct itself if called twice.
	CheckWater();

	trace_t trace;
	Vector vStart( mv->m_vecAbsOrigin.x, mv->m_vecAbsOrigin.y, mv->m_vecAbsOrigin.z );
	Vector vEnd( mv->m_vecAbsOrigin.x, mv->m_vecAbsOrigin.y, mv->m_vecAbsOrigin.z - 66 );

	// Assume we are not on the ground
	SetGroundEntity( NULL );
	m_pSurfaceData = NULL;
	m_surfaceFriction = 1.0f;
	m_chTextureType = 'C';

	// Check our velocity in z (are we shooting up really fast - then we are not on ground).
	if ( mv->m_vecVelocity.z <= 180.0f )
	{
		// Move downward.
		TracePlayerBBox( vStart, vEnd, MASK_PLAYERSOLID, COLLISION_GROUP_PLAYER_MOVEMENT, trace );


		// Check to see if we are on the ground
		if ( ( ( trace.plane.normal.z >= IMPACT_NORMAL_FLOOR ) || trace.IsDispSurfaceWalkable() ) && ( trace.fraction < 0.06f ) )
		{
			SetGroundEntity( &trace );
			VectorCopy( trace.plane.normal, m_vecGroundNormal );

			// Add standing on object to touch list
			if ( trace.DidHitNonWorldEntity() )
			{
				MoveHelper()->AddToTouched( trace, mv->m_vecVelocity );
			}

			// Reset water jumping.
			player->m_flWaterJumpTime = 0.0f;

			// If we could make the move, drop us down that 1 pixel
			if ( ( int )player->GetWaterLevel() < WL_Waist && !trace.startsolid && !trace.allsolid )
			{
				// check distance we would like to move -- this is supposed to just keep up
				// "on the ground" surface not stap us back to earth
				mv->m_vecAbsOrigin = vStart + trace.fraction * ( vEnd - vStart );
//				VectorCopy( trace.endpos, mv->m_vecAbsOrigin );
			}		
		}

		// NOTE: should this be surrounded by trace.fraction <= 1.0f ?????

		// Setup surface properties.
		{
			VPROF( "CTFGameMovement::CategorizePosition / Surface Props" );
			IPhysicsSurfaceProps *physprops = MoveHelper( )->GetSurfaceProps();
			m_surfaceProps = trace.surface.surfaceProps;
			m_pSurfaceData = physprops->GetSurfaceData( m_surfaceProps );
			physprops->GetPhysicsProperties( m_surfaceProps, NULL, NULL, &m_surfaceFriction, NULL );
		}

		// HACKHACK: Scale this to fudge the relationship between vphysics friction values and player friction values.
		// A value of 0.8f feels pretty normal for vphysics, whereas 1.0f is normal for players.
		// This scaling trivially makes them equivalent.  REVISIT if this affects low friction surfaces too much.
		m_surfaceFriction *= 1.25f;
		if ( m_surfaceFriction > 1.0f )
			m_surfaceFriction = 1.0f;
		m_chTextureType = m_pSurfaceData->game.material;
	}

	// If we are not on the ground...
	if ( player->GetGroundEntity() == NULL )
	{
		player->m_Local.m_flFallVelocity = -mv->m_vecVelocity.z;
	}

	// Store off the starting water level
	m_nOldWaterLevel = player->GetWaterLevel();
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGameMovement::HandleLadder( void )
{
	// No ladder movement if the player is dead or on a train.
	if ( player->pl.deadflag || ( player->GetFlags() & FL_ONTRAIN ) )
		return;

	// Ladder initialization.
	m_nOnLadder = 0;

	if ( !BaseClass::LadderMove() && ( player->GetMoveType() == MOVETYPE_LADDER ) )
	{
		// clear ladder stuff unless player is noclipping or being lifted by barnacle. 
		// it will be set immediately again next frame if necessary
		player->SetMoveType( MOVETYPE_WALK );
		player->SetMoveCollide( MOVECOLLIDE_DEFAULT );
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGameMovement::SpeedCrop( void )
{
	// Verify speed hasn't been cropped already (shouldn't have!!!).
	if ( m_iSpeedCropped & SPEED_CROPPED_DUCK )
		return;

	// Set the speed cropped flag.
	m_iSpeedCropped		|= SPEED_CROPPED_DUCK;

	// If the "walking" key is pressed -- crop speed.
	if ( mv->m_nButtons & IN_SPEED )
	{
		mv->m_flForwardMove *= SPEED_CROP_FRACTION_WALKING;
		mv->m_flSideMove *= SPEED_CROP_FRACTION_WALKING;
		mv->m_flUpMove *= SPEED_CROP_FRACTION_WALKING;
	}
	// If the "use" key is pressed and the player is on the ground -- crop speed.
	else if ( ( mv->m_nButtons & IN_USE ) && ( player->GetGroundEntity() != NULL ) )
	{
		mv->m_flForwardMove *= SPEED_CROP_FRACTION_USING;
		mv->m_flSideMove *= SPEED_CROP_FRACTION_USING;
		mv->m_flUpMove *= SPEED_CROP_FRACTION_USING;
	}
	// If the player is "ducking" -- crop speed
	else if ( player->GetFlags() & FL_DUCKING )
	{
		mv->m_flForwardMove *= SPEED_CROP_FRACTION_DUCKING;
		mv->m_flSideMove *= SPEED_CROP_FRACTION_DUCKING;
		mv->m_flUpMove *= SPEED_CROP_FRACTION_DUCKING;
	}

	// Moving backwards happens more slowly
	float flAngle = atan2( mv->m_flSideMove, mv->m_flForwardMove ) / M_PI;
	flAngle = 2.0f * (fabs(flAngle) - 0.5f);
	flAngle = clamp( flAngle, 0.0f, 1.0f );
	float flFactor = 1.0f - fabs(flAngle) * (1.0f - sv_backspeed.GetFloat());

	mv->m_flForwardMove *= flFactor;
	mv->m_flSideMove *= flFactor;
}


//-----------------------------------------------------------------------------
// Figures out how the constraint should slow us down
//-----------------------------------------------------------------------------
float CTFGameMovement::ComputeConstraintSpeedFactor( void )
{
	// If we have a constraint, slow down because of that too...
	// Get the TF movement data.
	CTFMoveData *pTFMove = TFMove();
	if ( !pTFMove || pTFMove->m_flConstraintRadius == 0.0f )
		return 1.0f;

	float flDistSq = mv->m_vecAbsOrigin.DistToSqr( pTFMove->m_vecConstraintCenter );

	float flOuterRadiusSq = pTFMove->m_flConstraintRadius * pTFMove->m_flConstraintRadius;
	float flInnerRadiusSq = pTFMove->m_flConstraintRadius - pTFMove->m_flConstraintWidth;
	flInnerRadiusSq *= flInnerRadiusSq;

	// Only slow us down if we're inside the constraint ring
	if ((flDistSq <= flInnerRadiusSq) || (flDistSq >= flOuterRadiusSq))
		return 1.0f;

	// Only slow us down if we're running away from the center
	Vector vecDesired;
	VectorMultiply( m_vecForward, mv->m_flForwardMove, vecDesired );
	VectorMA( vecDesired, mv->m_flSideMove, m_vecRight, vecDesired );
	VectorMA( vecDesired, mv->m_flUpMove, m_vecUp, vecDesired );

	Vector vecDelta;
	VectorSubtract( mv->m_vecAbsOrigin, pTFMove->m_vecConstraintCenter, vecDelta );
	VectorNormalize( vecDelta );
	VectorNormalize( vecDesired );
	if (DotProduct( vecDelta, vecDesired ) < 0.0f)
		return 1.0f;

	float flFrac = (sqrt(flDistSq) - (pTFMove->m_flConstraintRadius - pTFMove->m_flConstraintWidth)) / pTFMove->m_flConstraintWidth;

	float flSpeedFactor = Lerp( flFrac, 1.0f, pTFMove->m_flConstraintSpeedFactor ); 
	return flSpeedFactor;
}


//-----------------------------------------------------------------------------
// Purpose: Called in PrePlayerMove(), this function clamps the player's overall
//          speed.  It is clamped to either the maximum client's or server's 
//          speed (whichever is lower).
//-----------------------------------------------------------------------------
void CTFGameMovement::SetupSpeed( void )
{
	// Reset the outgoing applied velocity.
	mv->m_outWishVel.Init();

	// Don't clamp speed if we are sin an "ISOMETRIC" or "NOCLIP" movetype.
	if ( ( player->GetMoveType() == MOVETYPE_ISOMETRIC ) ||
		 ( player->GetMoveType() == MOVETYPE_NOCLIP ) )
		 return;

	// Some events negate speed, check for these first.
	if ( ( player->GetFlags() & FL_FROZEN ) || ( player->GetFlags() & FL_ONTRAIN ) ||  IsDead() )
	{
		mv->m_flForwardMove = 0;
		mv->m_flSideMove = 0;
		mv->m_flUpMove = 0;
		return;
	}

	// Calculate the players max speed given movements.
	float flSpeed = ( mv->m_flForwardMove * mv->m_flForwardMove ) +
		            ( mv->m_flSideMove * mv->m_flSideMove ) +
			 	    ( mv->m_flUpMove * mv->m_flUpMove );
	if ( flSpeed == 0.0f )
		return;

	flSpeed = sqrt( flSpeed );

	// NOTE: The client max speed was set to the movement max speed (mv->m_flMaxSpeed)
	//       in the SetupMove, however the _ProcessMovement code post sets
	//       mv->m_flMaxSpeed to the maximum server speed (sv_maxspeed),
	//       thus, the need to the check.  If we forego the maximum server speed, 
	//       this code can be removed.
	if ( mv->m_flClientMaxSpeed )
	{
		mv->m_flMaxSpeed = MIN( mv->m_flClientMaxSpeed, mv->m_flMaxSpeed );
	}

	// Slow down by the speed factor
	float flSpeedFactor = 1.0f;
	if (m_pSurfaceData)
	{
		flSpeedFactor = m_pSurfaceData->game.maxSpeedFactor;
	}

	// If we have a constraint, slow down because of that too...
	// Get the TF movement data
	float flConstraintSpeedFactor = ComputeConstraintSpeedFactor();
	if (flConstraintSpeedFactor < flSpeedFactor)
		flSpeedFactor = flConstraintSpeedFactor;

	mv->m_flMaxSpeed *= flSpeedFactor;

	if ( flSpeed > mv->m_flMaxSpeed )
	{
		float flRatio = mv->m_flMaxSpeed / flSpeed;
		mv->m_flForwardMove *= flRatio;
		mv->m_flSideMove *= flRatio;
		mv->m_flUpMove *= flRatio;
	}

	// Crop speed if necessary.
	SpeedCrop();
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGameMovement::FinishUnDuck( void )
{
	int i;
	trace_t trace;
	Vector newOrigin;

	Vector vDuckHullMin = GetPlayerMins( true );
	Vector vStandHullMin = GetPlayerMins( false );

	VectorCopy( mv->m_vecAbsOrigin, newOrigin );

	if ( player->GetGroundEntity() != NULL )
	{
		for ( i = 0; i < 3; i++ )
		{
			newOrigin[i] += ( vDuckHullMin[i] - vStandHullMin[i] );
		}
	}
	else
	{
  		Vector viewDelta = player->GetViewOffset() - GetPlayerViewOffset( false );
		VectorAdd( newOrigin, viewDelta, newOrigin );
	}
	
	TracePlayerBBox( newOrigin, newOrigin, MASK_PLAYERSOLID, COLLISION_GROUP_PLAYER_MOVEMENT, trace );

	if ( !trace.startsolid )
	{
		player->m_Local.m_bDucked = false;

		// Oh, no, changing hulls stuck us into something, try unsticking downward first.
		TracePlayerBBox( newOrigin, newOrigin, MASK_PLAYERSOLID, COLLISION_GROUP_PLAYER_MOVEMENT, trace );
		if ( trace.startsolid )
		{
			// See if we are stuck?  If so, stay ducked with the duck hull until we have a clear spot
			player->m_Local.m_bDucked = true;
			return;
		}

		player->RemoveFlag( FL_DUCKING );
		player->m_Local.m_bDucking  = false;
		player->SetViewOffset( GetPlayerViewOffset( false ) );
		player->m_Local.m_flDucktime = 0;
		
		VectorCopy( newOrigin, mv->m_vecAbsOrigin );
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGameMovement::HandleDuck( void )
{
	// Store button presses and changes.
	int buttonsChanged	= ( mv->m_nOldButtons ^ mv->m_nButtons );	// These buttons have changed this frame
	int buttonsPressed	=  buttonsChanged & mv->m_nButtons;			// The changed ones still down are "pressed"
	int buttonsReleased	=  buttonsChanged & mv->m_nOldButtons;		// The changed ones which were previously down are "released"

	if ( mv->m_nButtons & IN_DUCK )
	{
		mv->m_nOldButtons |= IN_DUCK;
	}
	else
	{
		mv->m_nOldButtons &= ~IN_DUCK;
	}

	// Handle the player dead case.
	if ( IsDead() && ( player->GetFlags() & FL_DUCKING ) )
	{
		FinishUnDuck();
		return;
	}

	if ( ( mv->m_nButtons & IN_DUCK ) || ( player->m_Local.m_bDucking ) || ( player->GetFlags() & FL_DUCKING ) )
	{
		// Remove all movement when ducking!
		mv->m_flForwardMove = 0.0f;
		mv->m_flSideMove = 0.0f;
		mv->m_flUpMove = 0.0f;

		if ( mv->m_nButtons & IN_DUCK )
		{
			if ( ( buttonsPressed & IN_DUCK ) && !( player->GetFlags() & FL_DUCKING ) )
			{
				// Use 1 second so super long jump will work
				player->m_Local.m_flDucktime = 1000;
				player->m_Local.m_bDucking    = true;
			}

			float duckmilliseconds = MAX( 0.0f, 1000.0f - (float)player->m_Local.m_flDucktime );
			float duckseconds = duckmilliseconds / 1000.0f;
			
			if ( player->m_Local.m_bDucking )
			{
				// Finish ducking immediately if duck time is over or not on ground
				if ( ( duckseconds > TIME_TO_DUCK ) || 
					( player->GetGroundEntity() == NULL ) )
				{
					FinishDuck();
				}
				else
				{
					// Calc parametric time
					float duckFraction = SimpleSpline( duckseconds / TIME_TO_DUCK );
					SetDuckedEyeOffset( duckFraction );
				}
			}
		}
		else
		{
			if ( (buttonsReleased & IN_DUCK ) && ( player->GetFlags() & FL_DUCKING ) )
			{
				// Use 1 second so super long jump will work
				player->m_Local.m_flDucktime = 1000;
				player->m_Local.m_bDucking    = true;  // or unducking
			}

			float duckmilliseconds = MAX( 0.0f, 1000.0f - (float)player->m_Local.m_flDucktime );
			float duckseconds = duckmilliseconds / 1000.0f;

			if ( player->m_Local.m_bDucking ) // or unducking
			{
				// Finish ducking immediately if duck time is over or not on ground
				if ( ( duckseconds > TIME_TO_UNDUCK ) ||
					 ( player->GetGroundEntity() == NULL ) )
				{
					FinishUnDuck();
				}
				else
				{
					// Calc parametric time
					float duckFraction = SimpleSpline( 1.0f - ( duckseconds / TIME_TO_UNDUCK ) );
					SetDuckedEyeOffset( duckFraction );
				}
			}
		}
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGameMovement::SetupViewAngles( void )
{
	// Cache the view angles.
	AngleVectors( mv->m_vecViewAngles, &m_vecForward, &m_vecRight, &m_vecUp );

	// Add a view punch if necessary.
	QAngle	v_angle = ( mv->m_vecViewAngles + player->m_Local.m_vecPunchAngle );
	
	// Adjust the view roll angle.
	if ( ( player->GetMoveType() != MOVETYPE_ISOMETRIC ) && ( player->GetMoveType() != MOVETYPE_NOCLIP ) )
	{
		mv->m_vecViewAngles[ROLL] = CalcRoll( v_angle, mv->m_vecVelocity, sv_rollangle.GetFloat(), sv_rollspeed.GetFloat() ) * 4.0f;
	}
	else
	{
		mv->m_vecViewAngles[ROLL] = 0.0f;
	}

	// Copy the yaw and pitch.
	// NOTE: Adjust the client view angles to match the values on the server.
	mv->m_vecViewAngles[PITCH] = v_angle[PITCH];
	mv->m_vecViewAngles[YAW] = v_angle[YAW];
	if ( mv->m_vecViewAngles[YAW] > 180.0f )
	{
		mv->m_vecViewAngles[YAW] -= 360.0f;
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CTFGameMovement::CheckDeath( void )
{
	// If we are dead, setup the appropriate data
	if ( IsDead() )
	{
		mv->m_flForwardMove = 0.0f;
		mv->m_flSideMove = 0.0f;
		mv->m_flUpMove = 0.0f;

		VectorCopy( mv->m_vecOldAngles, mv->m_vecViewAngles );

		player->SetViewOffset( VEC_DEAD_VIEWHEIGHT_SCALED( this ) );

		return true;
	}

	return false;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGameMovement::UpdateTimers( void )
{
	BaseClass::ReduceTimers();
	BaseClass::DecayPunchAngle();
}


//-----------------------------------------------------------------------------
// Should the step sound play?
//-----------------------------------------------------------------------------
bool CTFGameMovement::ShouldPlayStepSound( surfacedata_t *psurface, float fvol )
{
	if ( !m_nOnLadder && Vector2DLength( mv->m_vecVelocity.AsVector2D() ) <= 100 )
		return false;

	return true;
}

//-----------------------------------------------------------------------------
// Purpose: 
// Input  : step - 
//			fvol - 
//			force - force sound to play
//-----------------------------------------------------------------------------
void CTFGameMovement::PlayStepSound( surfacedata_t *psurface, float fvol, bool force )
{
	if ( gpGlobals->maxClients > 1 && !sv_footsteps.GetFloat() )
		return;

	if ( !psurface )
		return;

	if (!force && !ShouldPlayStepSound( psurface, fvol ))
		return;

// TODO:  See note above, should this be hooked up?
//	PlantFootprint( psurface );

	unsigned short stepSoundName = player->m_Local.m_nStepside ? psurface->sounds.stepleft : psurface->sounds.stepright;
	player->m_Local.m_nStepside = !player->m_Local.m_nStepside;

	if ( !stepSoundName )
		return;

	if ( !mv->m_bFirstRunOfFunctions )
		return;

	IPhysicsSurfaceProps *physprops = MoveHelper( )->GetSurfaceProps();
	const char *pSoundName = physprops->GetString( stepSoundName );
	char szSound[256];

	// Prepend our team's footsteps
	if ( player->GetTeamNumber() == TEAM_HUMANS )
	{
		Q_snprintf( szSound, sizeof(szSound), "Human.%s", pSoundName );
	}
	else if ( player->GetTeamNumber() == TEAM_ALIENS )
	{
		Q_snprintf( szSound, sizeof(szSound), "Alien.%s", pSoundName );
	}
	else
	{
		return;
	}

	CSoundParameters params;
	if ( !CBaseEntity::GetParametersForSound( szSound, params, NULL ) )
		return;

	MoveHelper( )->StartSound( mv->m_vecAbsOrigin, CHAN_BODY, params.soundname, fvol, params.soundlevel, 0, params.pitch );
}	

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CTFGameMovement::CheckStuck( void )
{
	VPROF( "CTFGameMovement::CheckStuck" );

	// NOTE: I am not bothering much with this as I am going to 
	//       implement an new UnSticking process.
	if ( ( player->GetMoveType() == MOVETYPE_NOCLIP ) ||
         ( player->GetMoveType() == MOVETYPE_NONE ) ||
		 ( player->GetMoveType() == MOVETYPE_ISOMETRIC ) )
		 return 0;

	return BaseClass::CheckStuck();
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CTFGameMovement::PrePlayerMove( void )
{
	VPROF( "CTFGameMovement::PrePlayerMove" );

	// Assume we don't touch anything (Reset the touch list).
	MoveHelper()->ResetTouchList();

	// Check to see if we are stuck.
	if ( CheckStuck() )
		return false;

	// Update (reduce) movement timers.
	UpdateTimers();

	// Check to see if the player is dead and setup death data, otherwise setup 
	// the players view angles.
	if ( !CheckDeath() )
	{
		SetupViewAngles();
	}

	// Handle ducking.
	HandleDuck();

	// Handle ladder.
	HandleLadder();

	// Categorize the player's position.
	CategorizePosition();

	// Calculate the player's movement speed (has to happen after categorize position)
	SetupSpeed();

	// Update our stepping sound (based on the player's location).
	player->UpdateStepSound( m_pSurfaceData, mv->m_vecAbsOrigin, mv->m_vecVelocity );

	return true;
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGameMovement::PostPlayerMove( void )
{
}


//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CTFGameMovement::HandlePlayerMove( void )
{
	// Handle movement.
	switch ( player->GetMoveType() )
	{
		case MOVETYPE_NONE:
			{
				break;
			}
		case MOVETYPE_NOCLIP:
			{
				FullNoClipMove( sv_noclipspeed.GetFloat(), sv_noclipaccelerate.GetFloat() );
				break;
			}
		case MOVETYPE_FLY:
		case MOVETYPE_FLYGRAVITY:
			{
				FullTossMove();
				break;
			}

		case MOVETYPE_LADDER:
			{
				FullLadderMove(); 
				break;
			}

		case MOVETYPE_WALK:
			{
				// This should be moved elsewhere!!!  Just get it going for now.
				CTFMoveData *pTFMove = TFMove();
				Vector vecPlayerOrigin( mv->m_vecAbsOrigin.x, mv->m_vecAbsOrigin.y, mv->m_vecAbsOrigin.z );
				FullWalkMove();
				Vector vecPlayerDelta;
				VectorSubtract( mv->m_vecAbsOrigin, vecPlayerOrigin, vecPlayerDelta );

				if ( ( fabs( vecPlayerDelta.x ) > 0.0001f ) || 
					 ( fabs( vecPlayerDelta.y ) > 0.0001f ) ||
					 ( fabs( vecPlayerDelta.z ) > 0.0001f ) )
				{
					VectorCopy( vecPlayerDelta, pTFMove->m_vecPosDelta );
				}
				break;
			}

		case MOVETYPE_ISOMETRIC:
			{
				//IsometricMove();
				// Could also try:  FullTossMove();
				FullWalkMove();
				break;
			}

		default:
			{
				DevMsg( 1, "Bogus pmove player movetype %i on (%i) 0=cl 1=sv\n", player->GetMoveType(), player->IsServer());
				break;
			}
	}
}


//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CTFGameMovement::PlayerMove( void )
{
	VPROF( "CTFGameMovement::PlayerMove" );

	// Setup and initialization pre-player movement.
	if (!PrePlayerMove())
		return;

	// Handle Movement
	HandlePlayerMove();

	// Clean-up and updates post-player movement.
	PostPlayerMove();
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CTFGameMovement::FullWalkMove()
{
	VPROF( "CTFGameMovement::FullWalkMove" );

	if ( !CheckWater() ) 
	{
		StartGravity();
	}

	// If we are leaping out of the water, just update the counters.
	if (player->m_flWaterJumpTime)
	{
		WaterJump();
		TryPlayerMove();
		// See if we are still in water?
		CheckWater();
		return;
	}

	// If we are swimming in the water, see if we are nudging against a place we can jump up out
	//  of, and, if so, start out jump.  Otherwise, if we are not moving up, then reset jump timer to 0
	if ( player->GetWaterLevel() >= WL_Waist ) 
	{
		if ( player->GetWaterLevel() == WL_Waist )
		{
			CheckWaterJump();
		}

			// If we are falling again, then we must not trying to jump out of water any more.
		if ( mv->m_vecVelocity[2] < 0 && 
			 player->m_flWaterJumpTime )
		{
			player->m_flWaterJumpTime = 0;
		}

		// Was jump button pressed?
		if (mv->m_nButtons & IN_JUMP)
		{
			CheckJumpButton();
		}
		else
		{
			mv->m_nOldButtons &= ~IN_JUMP;
		}

		// Perform regular water movement
		WaterMove();
		VectorSubtract (mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity);

		// Redetermine position vars
		CategorizePosition();
	}
	else
	// Not fully underwater
	{
		// Was jump button pressed?
		if (mv->m_nButtons & IN_JUMP)
		{
			CheckJumpButton();
		}
		else
		{
			mv->m_nOldButtons &= ~IN_JUMP;
		}

		// Fricion is handled before we add in any base velocity. That way, if we are on a conveyor, 
		//  we don't slow when standing still, relative to the conveyor.
		if (player->GetGroundEntity() != NULL)
		{
			mv->m_vecVelocity[2] = 0.0;
			Friction();
		}

		// Make sure velocity is valid.
		CheckVelocity();

		if (player->GetGroundEntity() != NULL)
		{
//			WalkMove();
			WalkMove2();
		}
		else
		{
 			AirMove();  // Take into account movement when in air.
		}

		// Set final flags.
		CategorizePosition();

		// Now pull the base velocity back out.   Base velocity is set if you are on a moving object, like
		//  a conveyor (or maybe another monster?)
		VectorSubtract (mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity );

		// Make sure velocity is valid.
		CheckVelocity();

		// Add any remaining gravitational component.
		if ( !CheckWater() )
		{
			FinishGravity();
		}

		// If we are on ground, no downward velocity.
		if ( player->GetGroundEntity() != NULL )
		{
			mv->m_vecVelocity[2] = 0;
		}
		CheckFalling();
	}

	if  ( ( m_nOldWaterLevel == WL_NotInWater && player->GetWaterLevel() != WL_NotInWater ) ||
		  ( m_nOldWaterLevel != WL_NotInWater && player->GetWaterLevel() == WL_NotInWater ) )
	{
		PlaySwimSound();
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGameMovement::AirMove( void )
{
	VPROF( "CTFGameMovement::AirMove" );

	// NOTE: This was causing some additional problems with walking on physics
	//       objects.  The movement system needs to be cleaned up!  Keep the old
	//       code until the system has been fixed.s
	BaseClass::AirMove();
	return;


	int			i;
	Vector		wishvel;
	float		fmove, smove;
	Vector		wishdir;
	float		wishspeed;
	Vector forward, right, up;

	// Initialize the movement stack.
	VectorCopy( mv->m_vecAbsOrigin, m_aMovementStack[0].m_vecPosition );
	VectorCopy( m_vecGroundNormal, m_aMovementStack[0].m_vecImpactNormal );
	m_nMovementStackSize = 1;

	AngleVectors (mv->m_vecViewAngles, &forward, &right, &up);  // Determine movement angles
	
	// Copy movement amounts
	fmove = mv->m_flForwardMove;
	smove = mv->m_flSideMove;
	
	// Zero out z components of movement vectors
	forward[2] = 0;
	right[2]   = 0;
	VectorNormalize(forward);  // Normalize remainder of vectors
	VectorNormalize(right);    // 

	for (i=0 ; i<2 ; i++)       // Determine x and y parts of velocity
		wishvel[i] = forward[i]*fmove + right[i]*smove;
	wishvel[2] = 0;             // Zero out z part of velocity

	VectorCopy (wishvel, wishdir);   // Determine maginitude of speed of move
	wishspeed = VectorNormalize(wishdir);

	//
	// clamp to server defined max speed
	//
	if (wishspeed > mv->m_flMaxSpeed)
	{
		VectorScale (wishvel, mv->m_flMaxSpeed/wishspeed, wishvel);
		wishspeed = mv->m_flMaxSpeed;
	}
	
	AirAccelerate( wishdir, wishspeed, sv_airaccelerate.GetFloat() );

	// Add in any base velocity to the current velocity.
	VectorAdd(mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity );

	TryPlayerMove2();

	// Try to stand up.
	TryStanding();
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGameMovement::WalkMove( void )
{
	_WalkMove();
}

//-----------------------------------------------------------------------------
// Purpose: This is here until the new movement code is complete.  I needed
//          to override hl2's walk move so that "floors" are identified 
//          differently.
//-----------------------------------------------------------------------------
void CTFGameMovement::_WalkMove( void )
{
	VPROF( "CTFGameMovement::_WalkMove" );

	int clip;
	int i;

	Vector wishvel;
	float spd;
	float fmove, smove;
	Vector wishdir;
	float wishspeed;

	Vector dest, start;
	Vector original, originalvel;
	Vector down, downvel;
	float downdist, updist;
	trace_t pm;
	Vector forward, right, up;

	AngleVectors (mv->m_vecViewAngles, &forward, &right, &up);  // Determine movement angles

	CHandle< CBaseEntity > oldground;
	oldground = player->GetGroundEntity();
	
	// Copy movement amounts
	fmove = mv->m_flForwardMove;
	smove = mv->m_flSideMove;
	
	// Zero out z components of movement vectors
	forward[2] = 0;
	right[2]   = 0;
	
	VectorNormalize (forward);  // Normalize remainder of vectors.
	VectorNormalize (right);    // 

	for (i=0 ; i<2 ; i++)       // Determine x and y parts of velocity
		wishvel[i] = forward[i]*fmove + right[i]*smove;
	
	wishvel[2] = 0;             // Zero out z part of velocity

	VectorCopy (wishvel, wishdir);   // Determine maginitude of speed of move
	wishspeed = VectorNormalize(wishdir);

	//
	// Clamp to server defined max speed
	//
	if (wishspeed > mv->m_flMaxSpeed)
	{
		VectorScale (wishvel, mv->m_flMaxSpeed/wishspeed, wishvel);
		wishspeed = mv->m_flMaxSpeed;
	}

	// Set pmove velocity
	mv->m_vecVelocity[2] = 0;
	Accelerate ( wishdir, wishspeed, sv_accelerate.GetFloat() );
	mv->m_vecVelocity[2] = 0;

	// Add in any base velocity to the current velocity.
	VectorAdd (mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity );

	spd = VectorLength( mv->m_vecVelocity );

	if (spd < 1.0f)
	{
		mv->m_vecVelocity.Init();
		return;
	}

	// first try just moving to the destination	
	dest[0] = mv->m_vecAbsOrigin[0] + mv->m_vecVelocity[0]*gpGlobals->frametime;
	dest[1] = mv->m_vecAbsOrigin[1] + mv->m_vecVelocity[1]*gpGlobals->frametime;	
	dest[2] = mv->m_vecAbsOrigin[2];

	// first try moving directly to the next spot
	VectorCopy (dest, start);

	TracePlayerBBox( mv->m_vecAbsOrigin, dest, MASK_PLAYERSOLID, COLLISION_GROUP_PLAYER_MOVEMENT, pm );

	// If we made it all the way, then copy trace end
	//  as new player position.

	mv->m_outWishVel += wishdir * wishspeed;

	if (pm.fraction == 1)
	{
		VectorCopy( pm.endpos, mv->m_vecAbsOrigin );
		return;
	}

	if (oldground == NULL &&   // Don't walk up stairs if not on ground.
		player->GetWaterLevel()  == 0)
		return;

	if (player->m_flWaterJumpTime)         // If we are jumping out of water, don't do anything more.
		return;

	// Try sliding forward both on ground and up 16 pixels
	//  take the move that goes farthest
	VectorCopy (mv->m_vecAbsOrigin, original);       // Save out original pos &
	VectorCopy (mv->m_vecVelocity, originalvel);  //  velocity.

	// Slide move
	clip = TryPlayerMove();

	// Copy the results out
	VectorCopy (mv->m_vecAbsOrigin  , down);
	VectorCopy (mv->m_vecVelocity, downvel);

	// Reset original values.
	VectorCopy (original, mv->m_vecAbsOrigin);
	VectorCopy (originalvel, mv->m_vecVelocity);

	// Start out up one stair height
	VectorCopy (mv->m_vecAbsOrigin, dest);
	dest[2] += player->m_Local.m_flStepSize;

	TracePlayerBBox( mv->m_vecAbsOrigin, dest, MASK_PLAYERSOLID, COLLISION_GROUP_PLAYER_MOVEMENT, pm );

	// If we started okay and made it part of the way at least,
	//  copy the results to the movement start position and then
	//  run another move try.
	if (!pm.startsolid && !pm.allsolid)
	{
		VectorCopy (pm.endpos, mv->m_vecAbsOrigin);
	}

	// slide move the rest of the way.
	clip = TryPlayerMove();

	// Now try going back down from the end point
	//  press down the stepheight
	VectorCopy (mv->m_vecAbsOrigin, dest);
	dest[2] -= player->m_Local.m_flStepSize;

	TracePlayerBBox( mv->m_vecAbsOrigin, dest, MASK_PLAYERSOLID, COLLISION_GROUP_PLAYER_MOVEMENT, pm );

	// If we are not on the ground any more then
	//  use the original movement attempt
	if ( pm.plane.normal[2] < IMPACT_NORMAL_FLOOR )
		goto usedown;
	// If the trace ended up in empty space, copy the end
	//  over to the origin.
	if (!pm.startsolid && !pm.allsolid)
	{
		VectorCopy (pm.endpos, mv->m_vecAbsOrigin);
	}
	// Copy this origion to up.
	VectorCopy (mv->m_vecAbsOrigin, up);

	// decide which one went farther
	downdist = (down[0] - original[0])*(down[0] - original[0])
		     + (down[1] - original[1])*(down[1] - original[1]);
	updist   = (up[0]   - original[0])*(up[0]   - original[0])
		     + (up[1]   - original[1])*(up[1]   - original[1]);

	if (downdist > updist)
	{
usedown:
	;
		VectorCopy (down   , mv->m_vecAbsOrigin);
		VectorCopy (downvel, mv->m_vecVelocity);
	}
	else // copy z value from slide move
		mv->m_vecVelocity[2] = downvel[2];

	float stepDist = mv->m_vecAbsOrigin.z - original.z;
	if ( stepDist > 0 )
	{
		mv->m_outStepHeight += stepDist;
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGameMovement::AccelerateWithoutMomentum( Vector &wishdir, float wishspeed, float accel )
{
	// No acceleration if the player is water-jumping or dead.
	if ( player->pl.deadflag || player->m_flWaterJumpTime )
		return;

	// See if we are changing direction a bit
//	float flCurrentSpeed = mv->m_vecVelocity.Dot( wishdir );
	float flCurrentSpeed = mv->m_vecVelocity.Length();

	// Reduce wishspeed by the amount of veer.
	float flAddSpeed = wishspeed - flCurrentSpeed;

	// If not going to add any speed, done.
	if ( flAddSpeed <= 0.0f )
		return;

	// Determine amount of accleration.
	float flAccelSpeed = accel * gpGlobals->frametime * wishspeed * m_surfaceFriction;

	// Cap at addspeed
	if ( flAccelSpeed > flAddSpeed )
	{
		flAccelSpeed = flAddSpeed;
	}

	// Adjust velocity.
	for ( int iAxis = 0; iAxis < 3; iAxis++ )
	{
		mv->m_vecVelocity[iAxis] += flAccelSpeed * wishdir[iAxis];
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGameMovement::Accelerate( Vector &wishdir, float wishspeed, float accel )
{
	// No acceleration if the player is water-jumping or dead.
	if ( player->pl.deadflag || player->m_flWaterJumpTime )
		return;

	// See if we are changing direction a bit
//	float flCurrentSpeed = mv->m_vecVelocity.Dot( wishdir );
	float flCurrentSpeed = mv->m_vecVelocity.Length();

	// Reduce wishspeed by the amount of veer.
	float flAddSpeed = wishspeed - flCurrentSpeed;

	// If not going to add any speed, done.
	if ( flAddSpeed <= 0.0f )
		return;

	// Determine amount of accleration.
	float flAccelSpeed = accel * gpGlobals->frametime * wishspeed * m_surfaceFriction;

	// Cap at addspeed
	if ( flAccelSpeed > flAddSpeed )
	{
		flAccelSpeed = flAddSpeed;
	}

	// Gravity.
	float flGravityAdj = CalcGravityAdjustment( wishdir );

	// Adjust velocity.
	for ( int iAxis = 0; iAxis < 3; iAxis++ )
	{
		mv->m_vecVelocity[iAxis] += ( flAccelSpeed * wishdir[iAxis] * flGravityAdj );
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
float CTFGameMovement::CalcGravityAdjustment( const Vector &wishdir )
{
	// Get the TF movement data.
	CTFMoveData *pTFMove = TFMove();
	if ( !pTFMove )
		return 1.0f;

	if ( player->GetMoveType() == MOVETYPE_NOCLIP )
		return 1.0f;

	Vector vecPositionDelta = pTFMove->m_vecPosDelta;
	VectorNormalize( vecPositionDelta );

	// Hard-code my table
	float flModifier = 0.0f;
	if ( vecPositionDelta.z < -0.342f )
	{
		flModifier = 1.25f;
	}
	else if ( vecPositionDelta.z < 0.0f )
	{
		flModifier = 1.15f;
	}
	else if ( vecPositionDelta.z < 0.342f )	/* >20 */
	{
		flModifier = 1.0f;
	}
	else if ( vecPositionDelta.z < 0.5f ) /* 20-30 */
	{
		float flDelta = 0.5f - vecPositionDelta.z;
		flDelta /= 0.158f;
		flDelta = 1.0f - flDelta;
		flModifier = 1.0f - ( 0.25 * flDelta );
	}
	else if ( vecPositionDelta.z < 0.707f ) /* 30-45 */
	{
		float flDelta = 0.707f - vecPositionDelta.z;
		flDelta /= 0.207f;
		flDelta = 1.0f - flDelta;
		flModifier = 0.75 - ( 0.25f * flDelta );
	}
	else if ( vecPositionDelta.z < 0.766f ) /* 45-50 */
	{
		float flDelta = 0.766f - vecPositionDelta.z;
		flDelta /= 0.059f;
		flDelta = 1.0f - flDelta;
		flModifier = 0.5f - ( 0.40f * flDelta );
	}
	else
	{
		flModifier = 0.35f;
	}

	AddToMomentumList( flModifier );
	flModifier = GetMomentum();

#if 0
	// Debug!
	if ( player->IsServer() )
	{
		Msg( "Server:Gravity Adj = %lf\n", flModifier );
	}
	else
	{
		Msg( "Client:Gravity Adj = %lf\n", flModifier );
	}
#endif

	return flModifier;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CTFGameMovement::CalcWishVelocityAndPosition( Vector &vWishPos, Vector &vWishDir,
												   float &flWishSpeed )
{
	//
	// Determine the movement angles.
	//
	Vector vForward, vRight, vUp;
	AngleVectors( mv->m_vecViewAngles, &vForward, &vRight, &vUp );

	//
	// Zero out the z component of the movement vectors and renormalize.
	//
	vForward.z = 0.0f;
	VectorNormalize( vForward );
	vRight.z = 0.0f;
	VectorNormalize( vRight );

	//
	// Determine the xy parts of the velocity.
	//
	Vector vWishVel( 0.0f, 0.0f, 0.0f );
	for ( int axis = 0; axis < 2; axis++ )
	{
		vWishVel[axis] = ( vForward[axis] * mv->m_flForwardMove ) +
			             ( vRight[axis] * mv->m_flSideMove );
	}
	vWishVel.z = 0.0f;

	//
	// Componentize the velocity into direction and speed.
	//
	VectorCopy( vWishVel, vWishDir );
	flWishSpeed = VectorNormalize( vWishDir );
	if ( flWishSpeed > mv->m_flMaxSpeed )
	{
		VectorScale( vWishVel, ( mv->m_flMaxSpeed / flWishSpeed ), vWishVel );
		flWishSpeed = mv->m_flMaxSpeed;
	}

	//
	// Accelerate (in the plane).
	//
	mv->m_vecVelocity.z = 0.0f;
	Accelerate( vWishDir, flWishSpeed, sv_accelerate.GetFloat() );
	mv->m_vecVelocity.z = 0.0f;

	// Add in any base velocity (from conveyers, etc.) to the current velocity.
	VectorAdd( mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity );

	//
	// Stop the player (zero out velocity) if the player's speed is below a
	// given threshold.
	//
	float flSpeed = VectorLength( mv->m_vecVelocity );
	if ( flSpeed < SPEED_STOP_THRESHOLD )
	{
		mv->m_vecVelocity.Init();
		return false;
	}

	//
	// Calculate the wish position.
	//
	vWishPos.x = mv->m_vecAbsOrigin.x + ( mv->m_vecVelocity.x * gpGlobals->frametime );
	vWishPos.y = mv->m_vecAbsOrigin.y + ( mv->m_vecVelocity.y * gpGlobals->frametime );
	vWishPos.z = mv->m_vecAbsOrigin.z;

	return true;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
inline void CTFGameMovement::TracePlayerBBoxWithStep( const Vector &vStart, const Vector &vEnd, 
							unsigned int fMask, int collisionGroup, trace_t &trace )
{
	VPROF( "CTFGameMovement::TracePlayerBBoxWithStep" );

	Vector vHullMin = GetPlayerMins( player->m_Local.m_bDucked );
	vHullMin.z += player->m_Local.m_flStepSize;
	Vector vHullMax = GetPlayerMaxs( player->m_Local.m_bDucked );

	Ray_t ray;
	ray.Init( vStart, vEnd, vHullMin, vHullMax );
	UTIL_TraceRay( ray, fMask, mv->m_nPlayerHandle.Get(), collisionGroup, &trace );
}

#if 0
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
inline void CGameMovement::TracePlayerBBox( const Vector &start, const Vector &end, 
							unsigned int fMask, int collisionGroup, trace_t& pm )
{
	VPROF( "CTFGameMovement::TracePlayerBBox" );

	Ray_t ray;
	ray.Init( start, end, GetPlayerMins( player->m_Local.m_bDucked ), GetPlayerMaxs( player->m_Local.m_bDucked ) );
	UTIL_TraceRay( ray, fMask, mv->m_nPlayerHandle.Get(), collisionGroup, &pm );
}
#endif

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
inline int CTFGameMovement::BlockerType( const Vector &vImpactNormal )
{
	// If the impact plane has a high z component in the normal, then
	// it is probably a floor.
	if ( vImpactNormal.z > IMPACT_NORMAL_FLOOR )
		return 1;

	// If the impact plane has a zero z component in the normal, then it is
	// probably a step or wall.
	if ( vImpactNormal.z == IMPACT_NORMAL_WALL )
		return 2;

	// None
	return 0;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CTFGameMovement::RedirectGroundVelocity( const trace_t &trace )
{
	// Check for max planes.
	if ( m_nImpactPlaneCount >= MAX_IMPACT_PLANES )
	{
		mv->m_vecVelocity.Init();
		return false;
	}

	// Add the impact plane normal to the list.
	VectorCopy( trace.plane.normal, m_aImpactPlaneNormals[m_nImpactPlaneCount] );
	m_nImpactPlaneCount++;
	
	int iPlane, iPlane2;
	for ( iPlane = 0; iPlane < m_nImpactPlaneCount; iPlane++ )
	{
		// Reduce and redirect the player's velocity.
		Vector vecVelocity( mv->m_vecVelocity.x, mv->m_vecVelocity.y, mv->m_vecVelocity.z );

		// Don't let negatively sloped surfaces drive you into the ground.
		if ( m_aImpactPlaneNormals[iPlane].z < 0.0f )
		{
			m_aImpactPlaneNormals[iPlane].z = 0.0f;
			VectorNormalize( m_aImpactPlaneNormals[iPlane] );
		}

		ClipVelocity( vecVelocity, m_aImpactPlaneNormals[iPlane], mv->m_vecVelocity, 1.0f );

		// Check to see if we need to continue clipping?
		for( iPlane2 = 0; iPlane2 < m_nImpactPlaneCount; iPlane2++ )
		{
			if ( iPlane != iPlane2 )
			{
				if ( mv->m_vecVelocity.Dot( m_aImpactPlaneNormals[iPlane2] ) < 0.0f )
					break;
			}
		}
		if ( iPlane2 == m_nImpactPlaneCount )
			break;
	}

	if ( iPlane == m_nImpactPlaneCount )
	{
		// Go along the crease here!
		if ( m_nImpactPlaneCount != 2 )
		{
			mv->m_vecVelocity.Init();
			return false;
		}
		else
		{
			Vector vecCross;
			CrossProduct( m_aImpactPlaneNormals[0], m_aImpactPlaneNormals[1], vecCross );
			float flScalar = vecCross.Dot( mv->m_vecVelocity );
			VectorScale( vecCross, flScalar, mv->m_vecVelocity );
		}
	}

	// If the original velocity is against the current velocity, stop dead to 
	// avoid tiny occilations in sloping corners
	if ( mv->m_vecVelocity.Dot( m_vecOriginalVelocity ) <= 0.0f )
	{
		mv->m_vecVelocity.Init();
		return false;
	}

	return true;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CTFGameMovement::RedirectAirVelocity( const trace_t &trace )
{
	// Check for max planes.
	if ( m_nImpactPlaneCount >= MAX_IMPACT_PLANES )
	{
		mv->m_vecVelocity.Init();
		return false;
	}

	// Add the impact plane normal to the list.
	VectorCopy( trace.plane.normal, m_aImpactPlaneNormals[m_nImpactPlaneCount] );
	m_nImpactPlaneCount++;

	for ( int iPlane = 0; iPlane < m_nImpactPlaneCount; iPlane++ )
	{
		// Reduce and redirect the player's velocity.
		Vector vecVelocity( mv->m_vecVelocity.x, mv->m_vecVelocity.y, mv->m_vecVelocity.z );

		// Don't let negatively sloped surfaces drive you into the ground.
		if ( m_aImpactPlaneNormals[iPlane].z < 0.0f )
		{
			m_aImpactPlaneNormals[iPlane].z = 0.0f;
			VectorNormalize( m_aImpactPlaneNormals[iPlane] );
		}

		if ( m_aImpactPlaneNormals[iPlane].z > IMPACT_NORMAL_FLOOR )
		{
			ClipVelocity( vecVelocity, m_aImpactPlaneNormals[iPlane], mv->m_vecVelocity, 1.0f );
		}
		else
		{
			ClipVelocity( vecVelocity, m_aImpactPlaneNormals[iPlane], mv->m_vecVelocity, 1.0f + sv_bounce.GetFloat() * ( 1.0f - m_surfaceFriction ) );
		}
	}	

	return true;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGameMovement::CollisionResponseNone( const trace_t &trace )
{
	// Move the player to the trace's ending position.
	VectorCopy( trace.endpos, mv->m_vecAbsOrigin );

	// Add the position to the stack.
	if ( m_nMovementStackSize < MOVEMENTSTACK_MAXSIZE )
	{
		VectorCopy( mv->m_vecAbsOrigin, m_aMovementStack[m_nMovementStackSize].m_vecPosition );
		VectorCopy( mv->m_vecVelocity, m_aMovementStack[m_nMovementStackSize].m_vecVelocity );
		VectorCopy( m_aMovementStack[m_nMovementStackSize].m_vecImpactNormal, 
			m_aMovementStack[m_nMovementStackSize].m_vecImpactNormal );
		m_nMovementStackSize++;
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGameMovement::CollisionResponseStuck( void )
{
	mv->m_vecVelocity.Init();
	//DevMsg( 1, "CollisionResponseStuck: %s is stuck (%s).\n", player->GetClassname(), player->IsServer() ? "sv" : "cl" );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CTFGameMovement::CollisionResponseGeneric( const trace_t &trace, int &nBlocked )
{
	// Check for any movement.
	if ( trace.fraction > 0.0f )
	{
		// Move the partial move and reset the impact plane count.
		VectorCopy( trace.endpos, mv->m_vecAbsOrigin );
		m_nImpactPlaneCount = 0;

		// Add the data to the movement stack. -- the velocity is wrong here!!!
		if ( m_nMovementStackSize < MOVEMENTSTACK_MAXSIZE )
		{
			VectorCopy( mv->m_vecAbsOrigin, m_aMovementStack[m_nMovementStackSize].m_vecPosition );
			VectorCopy( mv->m_vecVelocity, m_aMovementStack[m_nMovementStackSize].m_vecVelocity );
			VectorCopy( trace.plane.normal, m_aMovementStack[m_nMovementStackSize].m_vecImpactNormal );
			m_nMovementStackSize++;
		}
	}

	// Sanity check - Impact plane count.
	Assert( m_nImpactPlaneCount < MAX_IMPACT_PLANES );

	// Add the entity to the touched list (list itself maintains uniqueness).
	MoveHelper()->AddToTouched( trace, mv->m_vecVelocity );

	// Check for special "blockers" (walls, steps, floor).
    nBlocked |= BlockerType( trace.plane.normal );
	
	// Re-direct or bounce the player's velocity vector.
	if ( player->GetGroundEntity() != NULL )
	{
		return RedirectGroundVelocity( trace );
	}
	else
	{
		return RedirectAirVelocity( trace );
	}
}

//-----------------------------------------------------------------------------
// Purpose: See comment _WalkMove
//-----------------------------------------------------------------------------
int CTFGameMovement::TryPlayerMove( Vector *pFirstDest=NULL, trace_t *pFirstTrace=NULL )
{
	VPROF( "CTFGameMovement::TryPlayerMove" );

	int			bumpcount, numbumps;
	Vector		dir;
	float		d;
	int			numplanes;
	Vector		planes[5/*MAX_CLIP_PLANES*/];
	Vector		primal_velocity, original_velocity;
	Vector      new_velocity;
	int			i, j;
	trace_t	pm;
	Vector		end;
	float		time_left, allFraction;
	int			blocked;		
	
	numbumps  = 4;           // Bump up to four times
	
	blocked   = 0;           // Assume not blocked
	numplanes = 0;           //  and not sliding along any planes
	VectorCopy (mv->m_vecVelocity, original_velocity);  // Store original velocity
	VectorCopy (mv->m_vecVelocity, primal_velocity);
	
	allFraction = 0;
	time_left = gpGlobals->frametime;   // Total time for this movement operation.

	new_velocity.Init();

	for (bumpcount=0 ; bumpcount < numbumps; bumpcount++)
	{
		if ( mv->m_vecVelocity.Length() == 0.0 )
			break;

		// Assume we can move all the way from the current origin to the
		//  end point.
		VectorMA( mv->m_vecAbsOrigin, time_left, mv->m_vecVelocity, end );

		// See if we can make it from origin to end point.
		if ( g_bMovementOptimizations )
		{
			// If their velocity Z is 0, then we can avoid an extra trace here during WalkMove.
			if ( pFirstDest && end == *pFirstDest )
				pm = *pFirstTrace;
			else
				TracePlayerBBox( mv->m_vecAbsOrigin, end, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, pm );
		}
		else
		{
			TracePlayerBBox( mv->m_vecAbsOrigin, end, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, pm );
		}

		allFraction += pm.fraction;

		// If we started in a solid object, or we were in solid space
		//  the whole way, zero out our velocity and return that we
		//  are blocked by floor and wall.
		if (pm.allsolid)
		{	
			// entity is trapped in another solid
			VectorCopy (vec3_origin, mv->m_vecVelocity);
			return 4;
		}

		// If we moved some portion of the total distance, then
		//  copy the end position into the pmove.origin and 
		//  zero the plane counter.
		if( pm.fraction > 0 )
		{	
			// actually covered some distance
			VectorCopy (pm.endpos, mv->m_vecAbsOrigin);
			VectorCopy (mv->m_vecVelocity, original_velocity);
			numplanes = 0;
		}

		// If we covered the entire distance, we are done
		//  and can return.
		if (pm.fraction == 1)
		{
			 break;		// moved the entire distance
		}

		// Indicate a collision occurred...
		OnTryPlayerMoveCollision( pm );

		// Save entity that blocked us (since fraction was < 1.0)
		//  for contact
		// Add it if it's not already in the list!!!
		MoveHelper( )->AddToTouched( pm, mv->m_vecVelocity );

		// If the plane we hit has a high z component in the normal, then
		//  it's probably a floor
		if (pm.plane.normal[2] > IMPACT_NORMAL_FLOOR)
		{
			blocked |= 1;		// floor
		}
		// If the plane has a zero z component in the normal, then it's a 
		//  step or wall
		if (!pm.plane.normal[2])
		{
			blocked |= 2;		// step / wall
		}

		// Reduce amount of m_flFrameTime left by total time left * fraction
		//  that we covered.
		time_left -= time_left * pm.fraction;
		
		// Did we run out of planes to clip against?
		if (numplanes >= 5/*MAX_CLIP_PLANES*/)
		{	
			// this shouldn't really happen
			//  Stop our movement if so.
			VectorCopy (vec3_origin, mv->m_vecVelocity);
			//Con_DPrintf("Too many planes 4\n");

			break;
		}

		// Set up next clipping plane
		VectorCopy (pm.plane.normal, planes[numplanes]);
		numplanes++;

		// modify original_velocity so it parallels all of the clip planes
		//
		if ( player->GetMoveType() == MOVETYPE_WALK &&
			((player->GetGroundEntity() == NULL) /*|| (mv->m_fFriction != 1)*/ ) )	// relfect player velocity
		{
			for ( i = 0; i < numplanes; i++ )
			{
				if ( planes[i][2] > IMPACT_NORMAL_FLOOR  )
				{
					// floor or slope
					ClipVelocity( original_velocity, planes[i], new_velocity, 1 );
					VectorCopy( new_velocity, original_velocity );
				}
				else
				{
					ClipVelocity( original_velocity, planes[i], new_velocity, 1.0 + sv_bounce.GetFloat() * (1 - m_surfaceFriction) );
				}
			}

			VectorCopy( new_velocity, mv->m_vecVelocity );
			VectorCopy( new_velocity, original_velocity );
		}
		else
		{
			for (i=0 ; i < numplanes ; i++)
			{
				ClipVelocity (
					original_velocity,
					planes[i],
					mv->m_vecVelocity,
					1);

				for (j=0 ; j<numplanes ; j++)
					if (j != i)
					{
						// Are we now moving against this plane?
						if (mv->m_vecVelocity.Dot(planes[j]) < 0)
							break;	// not ok
					}
				if (j == numplanes)  // Didn't have to clip, so we're ok
					break;
			}
			
			// Did we go all the way through plane set
			if (i != numplanes)
			{	// go along this plane
				// pmove.velocity is set in clipping call, no need to set again.
				;  
			}
			else
			{	// go along the crease
				if (numplanes != 2)
				{
					VectorCopy (vec3_origin, mv->m_vecVelocity);
					break;
				}
				CrossProduct (planes[0], planes[1], dir);
				d = dir.Dot(mv->m_vecVelocity);
				VectorScale (dir, d, mv->m_vecVelocity );
			}

			//
			// if original velocity is against the original velocity, stop dead
			// to avoid tiny occilations in sloping corners
			//
			d = mv->m_vecVelocity.Dot(primal_velocity);
			if (d <= 0)
			{
				//Con_DPrintf("Back\n");
				VectorCopy (vec3_origin, mv->m_vecVelocity);
				break;
			}
		}
	}

	if ( allFraction == 0 )
	{
		VectorCopy (vec3_origin, mv->m_vecVelocity);
	}

	return blocked;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CTFGameMovement::TryPlayerMove2( void )
{
	VPROF( "CTFGameMovement::TryPlayerMove2" );

	int	nBlocked = MOVEMENT_BLOCKED_NONE;
	trace_t	trace;
	float flTimeLeft = gpGlobals->frametime;
	m_nImpactPlaneCount = 0;

	// Save off the original velocity -- coming in.
	VectorCopy( mv->m_vecVelocity, m_vecOriginalVelocity );

	float flTotalFraction = 0.0f;
	for ( int iBump = 0; iBump < BUMP_MAX_COUNT; iBump++ )
	{
		// Check to see if we have any velocity left. EXPENSIVE!!!!
		if ( mv->m_vecVelocity.Length() == 0.0f )
			break;

		//
		// Calculate the wish position. 
		//
		Vector vecWishPos;
		VectorMA( mv->m_vecAbsOrigin, flTimeLeft, mv->m_vecVelocity, vecWishPos );

		//
		// Attempt the move.
		//
		// NOTE:  This check can hit players and objects
		TracePlayerBBoxWithStep( mv->m_vecAbsOrigin, vecWishPos, MASK_PLAYERSOLID, COLLISION_GROUP_PLAYER, trace );

		//  but if it didn't no need to do another trace for movement only
		if ( trace.fraction == 1.0f )
		{
			flTotalFraction += trace.fraction;
			CollisionResponseNone( trace );
			break;
		}
		else
		{
			// Add the entity to the touched list (list itself maintains uniqueness).
			MoveHelper()->AddToTouched( trace, mv->m_vecVelocity );
			// Do a non-solid to player trace now, instead, and override what's in trace
			TracePlayerBBoxWithStep( mv->m_vecAbsOrigin, vecWishPos, MASK_PLAYERSOLID, COLLISION_GROUP_PLAYER_MOVEMENT, trace );
		}

		flTotalFraction += trace.fraction;

		// Handle stuck in solid.
		if ( trace.allsolid )
		{
			CollisionResponseStuck();
			return MOVEMENT_BLOCKED_ALL;
		}

		// Handle full movement.
		if ( trace.fraction == 1.0f )
		{
			CollisionResponseNone( trace );
			break;
		}

		// Handle partial movement.
		if ( !CollisionResponseGeneric( trace, nBlocked ) )
			break;

		// Reduce the time left.
		flTimeLeft -= ( flTimeLeft * trace.fraction );

		/*
		//
		// Attempt the move.
		//
		TracePlayerBBoxWithStep( mv->m_vecAbsOrigin, vecWishPos, MASK_PLAYERSOLID, COLLISION_GROUP_PLAYER_MOVEMENT, trace );

		flTotalFraction += trace.fraction;

		// Handle stuck in solid.
		if ( trace.allsolid )
		{
			CollisionResponseStuck();
			return MOVEMENT_BLOCKED_ALL;
		}

		// Handle full movement.
		if ( trace.fraction == 1.0f )
		{
			CollisionResponseNone( trace );
			break;
		}

		// Handle partial movement.
		if ( !CollisionResponseGeneric( trace, nBlocked ) )
			break;

		// Reduce the time left.
		flTimeLeft -= ( flTimeLeft * trace.fraction );
		*/
	}
	
	// Finally, check for any movement.
	if ( flTotalFraction == 0.0f )
	{
		CollisionResponseStuck();
	}

	return nBlocked;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGameMovement::TryStanding( void )
{
	VPROF( "CTFGameMovement::TryStanding" );

	// Step down.
	Vector vecStandPos( mv->m_vecAbsOrigin.x, mv->m_vecAbsOrigin.y, mv->m_vecAbsOrigin.z - player->m_Local.m_flStepSize );

	trace_t trace;
	TracePlayerBBoxWithStep( mv->m_vecAbsOrigin, vecStandPos, MASK_PLAYERSOLID, COLLISION_GROUP_PLAYER_MOVEMENT, trace );
	if ( trace.fraction == 1.0f )
		return;

	// Attempt to stand up.
	vecStandPos.z = mv->m_vecAbsOrigin.z + ( ( 1.0f - trace.fraction ) * player->m_Local.m_flStepSize );
	TracePlayerBBoxWithStep( mv->m_vecAbsOrigin, vecStandPos, MASK_PLAYERSOLID, COLLISION_GROUP_PLAYER_MOVEMENT, trace );

	// A fraction of 1.0 means we stood up fine - done.
	if ( trace.fraction == 1.0f )
	{
		VectorCopy( trace.endpos, mv->m_vecAbsOrigin );
		return;
	}

	// Use the movement stack to pop back and resolve the stand.
	if ( m_nMovementStackSize > 0 )
	{
		VectorCopy( m_aMovementStack[m_nMovementStackSize-1].m_vecPosition, mv->m_vecAbsOrigin );
		VectorCopy( m_aMovementStack[m_nMovementStackSize-1].m_vecVelocity, mv->m_vecVelocity );
		m_nMovementStackSize--; 
		TryStanding();
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGameMovement::ResolveStanding( void )
{
	VPROF( "CTFGameMovement::ResolveStanding" );

	//
	// Attempt to move down twice your step height.  Anything between 0.5 and 1.0
	// is a valid "stand" value.
	//
	Vector vecStandPos( mv->m_vecAbsOrigin.x, mv->m_vecAbsOrigin.y, mv->m_vecAbsOrigin.z - ( player->m_Local.m_flStepSize * 2.0f ) );

	trace_t trace;
	TracePlayerBBoxWithStep( mv->m_vecAbsOrigin, vecStandPos, MASK_PLAYERSOLID, COLLISION_GROUP_PLAYER_MOVEMENT, trace );

	// Anything between 0.5 and 1.0 is a valid stand value
	if ( fabs( trace.fraction - 0.5 ) < 0.0004f )
	{
		return;
	}

//	if ( trace.fraction == 0.5 )
//	{
//		VectorCopy( trace.endpos, mv->m_vecAbsOrigin );
//		return;
//	}

	if ( trace.fraction > 0.5f )
	{
		trace.fraction -= 0.5f;
		Vector vecNewOrigin;
		vecNewOrigin = mv->m_vecAbsOrigin + trace.fraction * ( vecStandPos - mv->m_vecAbsOrigin );
		mv->m_vecAbsOrigin = vecNewOrigin;
		return;
	}

	// Less than 0.5 mean we need to attempt to push up the difference.
	vecStandPos.z = ( mv->m_vecAbsOrigin.z + ( ( 0.5f - trace.fraction ) * ( player->m_Local.m_flStepSize * 2.0f ) ) );
	TracePlayerBBoxWithStep( mv->m_vecAbsOrigin, vecStandPos, MASK_PLAYERSOLID, COLLISION_GROUP_PLAYER_MOVEMENT, trace );
	
	// A fraction of 1.0 means we stood up fine - done.
	if ( trace.fraction == 1.0f )
	{
		VectorCopy( trace.endpos, mv->m_vecAbsOrigin );
		return;
	}

	// Use the movement stack to pop back and resolve the stand.
	if ( m_nMovementStackSize > 0 )
	{
		VectorCopy( m_aMovementStack[m_nMovementStackSize-1].m_vecPosition, mv->m_vecAbsOrigin );
		VectorCopy( m_aMovementStack[m_nMovementStackSize-1].m_vecVelocity, mv->m_vecVelocity );
		m_nMovementStackSize--; 
		ResolveStanding();
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFGameMovement::WalkMove2( void )
{
	VPROF( "CTFGameMovement::WalkMove2" );

	// Initialize the movement stack.
	VectorCopy( mv->m_vecAbsOrigin, m_aMovementStack[0].m_vecPosition );
	VectorCopy( m_vecGroundNormal, m_aMovementStack[0].m_vecImpactNormal );
	m_nMovementStackSize = 1;

	// Calculate the wish velocity and position.  The function returns false if 
	// the velocity is zero, it returns true otherwise.
	Vector vWishPos, vWishDir;
	float flWishSpeed;
	if ( !CalcWishVelocityAndPosition( vWishPos, vWishDir, flWishSpeed ) )
		return;

	// For physics player shadow.
	mv->m_outWishVel += vWishDir * flWishSpeed;

	// Lift up the players feet (bring the minimum z componenet up by the step
	// size) and sweep.
	TryPlayerMove2();

	// Try to stand up at movement's end.
	ResolveStanding();

	// For physics player shadow.
	float flStepHeight = mv->m_vecAbsOrigin.z - m_aMovementStack[0].m_vecPosition.z;
	if ( flStepHeight > 0.0f )
	{
		mv->m_outStepHeight += flStepHeight;
	}
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CTFGameMovement::SetMomentumList( float flValue )
{
	// Get the TF movement data.
	CTFMoveData *pTFMove = TFMove();
	if ( !pTFMove )
		return;

	// Fill in the momentum list.
	pTFMove->m_iMomentumHead = 0;
	for ( int iMomentum = 0; iMomentum < CTFMoveData::MOMENTUM_MAXSIZE; iMomentum++ )
	{
		pTFMove->m_aMomentum[iMomentum] = flValue;
	}
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CTFGameMovement::AddToMomentumList( float flValue )
{
	// Get the TF movement data.
	CTFMoveData *pTFMove = TFMove();
	if ( !pTFMove )
		return;

	// Insert the new gravity value into the list.
	pTFMove->m_aMomentum[pTFMove->m_iMomentumHead] = flValue;
	pTFMove->m_iMomentumHead = ( pTFMove->m_iMomentumHead + 1 ) % CTFMoveData::MOMENTUM_MAXSIZE;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
float CTFGameMovement::GetMomentum( void )
{
	// Get the TF movement data.
	CTFMoveData *pTFMove = TFMove();
	if ( !pTFMove )
		return 1.0f;

	float flTotal = 0.0f;
	for ( int iMomentum = 0; iMomentum < CTFMoveData::MOMENTUM_MAXSIZE; iMomentum++ )
	{
		flTotal += pTFMove->m_aMomentum[iMomentum];
	}
	
	flTotal /= CTFMoveData::MOMENTUM_MAXSIZE;

	return flTotal;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
bool CTFGameMovement::CheckJumpButton( void )
{
	if (player->pl.deadflag)
	{
		mv->m_nOldButtons |= IN_JUMP ;	// don't jump again until released
		return false;
	}

	// See if we are waterjumping.  If so, decrement count and return.
	if (player->m_flWaterJumpTime)
	{
		player->m_flWaterJumpTime -= gpGlobals->frametime;
		if (player->m_flWaterJumpTime < 0)
			player->m_flWaterJumpTime = 0;
		
		return false;
	}

	// If we are in the water most of the way...
	if ( player->GetWaterLevel() >= 2 )
	{	
		// swimming, not jumping
		SetGroundEntity( NULL );

		if(player->GetWaterType() == CONTENTS_WATER)    // We move up a certain amount
			mv->m_vecVelocity[2] = 100;
		else if (player->GetWaterType() == CONTENTS_SLIME)
			mv->m_vecVelocity[2] = 80;
		
		// play swiming sound
		if ( player->m_flSwimSoundTime <= 0 )
		{
			// Don't play sound again for 1 second
			player->m_flSwimSoundTime = 1000;
			PlaySwimSound();
		}

		return false;
	}

	// No more effect
 	if (player->GetGroundEntity() == NULL)
	{
		mv->m_nOldButtons |= IN_JUMP;
		return false;		// in air, so no effect
	}

	if ( mv->m_nOldButtons & IN_JUMP )
		return false;		// don't pogo stick

	// In the air now.
    SetGroundEntity( NULL );
	
	PlayStepSound( m_pSurfaceData, 1.0, true );
	
	MoveHelper()->PlayerSetAnimation( PLAYER_JUMP );

	float flGroundFactor = 1.0f;
	if (m_pSurfaceData)
	{
		flGroundFactor = m_pSurfaceData->game.jumpFactor; 
	}

	float flMul;
	flMul = sqrt(2 * GetCurrentGravity() * 45.0);

	// Acclerate upward
	// If we are ducking...
	float startz = mv->m_vecVelocity[2];
	if ( (  player->m_Local.m_bDucking ) || (  player->GetFlags() & FL_DUCKING ) )
	{
		// d = 0.5 * g * t^2		- distance traveled with linear accel
		// t = sqrt(2.0 * 45 / g)	- how long to fall 45 units
		// v = g * t				- velocity at the end (just invert it to jump up that high)
		// v = g * sqrt(2.0 * 45 / g )
		// v^2 = g * g * 2.0 * 45 / g
		// v = sqrt( g * 2.0 * 45 )
		mv->m_vecVelocity[2] = flGroundFactor * flMul;  // 2 * gravity * height
	}
	else
	{
		mv->m_vecVelocity[2] += flGroundFactor * flMul;  // 2 * gravity * height
	}

	FinishGravity();

	mv->m_outJumpVel.z += mv->m_vecVelocity[2] - startz;
	mv->m_outStepHeight += 0.1f;

	// Flag that we jumped.
	mv->m_nOldButtons |= IN_JUMP;	// don't jump again until released
	return true;
}