Overview Package Class Source Class tree Glossary
previous class      next class frames      no frames

Engine.UtilGame


00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045
00046
00047
00048
00049
00050
00051
00052
00053
00054
00055
00056
00057
00058
00059
00060
00061
00062
00063
00064
00065
00066
00067
00068
00069
00070
00071
00072
00073
00074
00075
00076
00077
00078
00079
00080
00081
00082
00083
00084
00085
00086
00087
00088
00089
00090
00091
00092
00093
00094
00095
00096
00097
00098
00099
00100
00101
00102
00103
00104
00105
00106
00107
00108
00109
00110
00111
00112
00113
00114
00115
00116
00117
00118
00119
00120
00121
00122
00123
00124
00125
00126
00127
00128
00129
00130
00131
00132
00133
00134
00135
00136
00137
00138
00139
00140
00141
00142
00143
00144
00145
00146
00147
00148
00149
00150
00151
00152
00153
00154
00155
00156
00157
00158
00159
00160
00161
00162
00163
00164
00165
00166
00167
00168
00169
00170
00171
00172
00173
00174
00175
00176
00177
00178
00179
00180
00181
00182
00183
00184
00185
00186
00187
00188
00189
00190
00191
00192
00193
00194
00195
00196
00197
00198
00199
00200
00201
00202
00203
00204
00205
00206
00207
00208
00209
00210
00211
00212
00213
00214
00215
00216
00217
00218
00219
00220
00221
00222
00223
00224
00225
00226
00227
00228
00229
00230
00231
00232
00233
00234
00235
00236
00237
00238
00239
00240
00241
00242
00243
00244
00245
00246
00247
00248
00249
00250
00251
00252
00253
00254
00255
00256
00257
00258
00259
00260
00261
00262
00263
00264
00265
00266
00267
00268
00269
00270
00271
00272
00273
00274
00275
00276
00277
00278
00279
00280
00281
00282
00283
00284
00285
00286
00287
00288
00289
00290
00291
00292
00293
00294
00295
00296
00297
00298
00299
00300
00301
00302
00303
00304
00305
00306
00307
00308
00309
00310
00311
00312
00313
00314
00315
00316
00317
00318
00319
00320
00321
00322
00323
00324
00325
00326
00327
00328
00329
00330
00331
00332
00333
00334
00335
00336
00337
00338
00339
00340
00341
00342
00343
00344
00345
00346
00347
00348
00349
00350
00351
00352
00353
00354
00355
00356
00357
00358
00359
00360
00361
00362
00363
00364
00365
00366
00367
00368
00369
00370
00371
00372
00373
00374
00375
00376
00377
00378
00379
00380
00381
00382
00383
00384
00385
00386
00387
00388
00389
00390
00391
00392
00393
00394
00395
00396
00397
00398
00399
00400
00401
00402
00403
00404
00405
00406
00407
00408
00409
00410
00411
00412
00413
00414
00415
00416
00417
00418
00419
00420
00421
00422
00423
00424
00425
00426
00427
00428
00429
00430
00431
00432
00433
00434
00435
00436
00437
00438
00439
00440
00441
00442
00443
00444
00445
00446
00447
00448
00449
00450
00451
00452
00453
00454
00455
00456
00457
00458
00459
00460
00461
00462
00463
00464
00465
00466
00467
00468
00469
00470
00471
00472
00473
00474
00475
00476
00477
00478
00479
00480
00481
00482
00483
00484
00485
00486
00487
00488
00489
00490
00491
00492
00493
00494
00495
00496
00497
00498
00499
00500
00501
00502
00503
00504
00505
00506
00507
00508
00509
00510
00511
00512
00513
00514
00515
00516
00517
00518
00519
00520
00521
00522
00523
00524
00525
00526
00527
00528
00529
00530
00531
00532
00533
00534
00535
00536
00537
00538
00539
00540
00541
00542
00543
00544
00545
00546
00547
00548
00549
00550
00551
00552
00553
00554
00555
00556
00557
00558
00559
00560
00561
00562
00563
00564
00565
00566
00567
00568
00569
00570
00571
00572
00573
00574
00575
00576
00577
00578
00579
00580
00581
00582
00583
00584
00585
00586
00587
00588
00589
00590
00591
00592
00593
00594
00595
00596
00597
00598
00599
00600
00601
00602
00603
00604
00605
00606
00607
00608
00609
00610
00611
00612
00613
00614
00615
00616
00617
00618
00619
00620
00621
00622
00623
00624
00625
00626
00627
00628
00629
00630
00631
00632
00633
00634
00635
00636
00637
00638
00639
00640
00641
00642
00643
00644
00645
00646
00647
00648
00649
00650
00651
00652
00653
00654
00655
00656
00657
00658
00659
00660
00661
00662
00663
00664
00665
00666
00667
00668
00669
00670
00671
00672
00673
00674
00675
00676
00677
00678
00679
00680
00681
00682
00683
00684
00685
00686
00687
00688
00689
00690
00691
00692
00693
00694
00695
00696
00697
00698
00699
00700
00701
00702
00703
00704
00705
00706
00707
00708
00709
00710
00711
00712
00713
00714
00715
00716
00717
00718
00719
00720
00721
00722
00723
00724
00725
00726
00727
00728
00729
00730
00731
00732
00733
00734
00735
00736
00737
00738
00739
00740
00741
00742
00743
00744
00745
00746
00747
00748
00749
00750
00751
00752
00753
00754
00755
00756
00757
00758
00759
00760
00761
00762
00763
00764
00765
00766
00767
00768
00769
00770
00771
00772
00773
00774
00775
00776
00777
00778
00779
00780
00781
00782
00783
00784
00785
00786
00787
00788
00789
00790
00791
00792
00793
00794
00795
00796
00797
00798
00799
00800
00801
00802
00803
00804
00805
00806
00807
00808
00809
00810
00811
00812
00813
00814
00815
00816
00817
00818
00819
00820
00821
00822
00823
00824
00825
00826
00827
00828
00829
00830
00831
00832
00833
00834
00835
00836
00837
00838
00839
00840
00841
00842
00843
00844
00845
00846
00847
00848
00849
00850
00851
00852
00853
00854
00855
00856
00857
00858
00859
00860
00861
00862
00863
00864
00865
00866
00867
00868
00869
00870
00871
00872
00873
00874
00875
00876
00877
00878
00879
00880
00881
00882
00883
00884
00885
00886
00887
00888
00889
00890
00891
00892
00893
00894
00895
00896
00897
00898
00899
00900
00901
00902
00903
00904
00905
00906
00907
00908
00909
00910
00911
00912
00913
00914
00915
00916
00917
00918
00919
00920
00921
00922
00923
00924
00925
00926
00927
00928
00929
00930
00931
00932
00933
00934
00935
00936
00937
00938
00939
00940
00941
00942
00943
00944
00945
00946
00947
00948
00949
00950
00951
00952
00953
00954
00955
00956
00957
00958
00959
00960
00961
00962
00963
00964
00965
00966
00967
00968
00969
00970
00971
00972
00973
00974
00975
00976
00977
00978
00979
00980
00981
00982
00983
00984
00985
00986
00987
00988
00989
00990
00991
00992
00993
00994
00995
00996
00997
00998
00999
01000
01001
01002
01003
01004
01005
01006
01007
01008
01009
01010
01011
01012
01013
01014
01015
01016
01017
01018
01019
01020
01021
01022
01023
01024
01025
01026
01027
01028
01029
01030
01031
01032
01033
01034
01035
01036
01037
01038
01039
01040
01041
01042
01043
01044
01045
01046
01047
01048
01049
01050
01051
01052
01053
01054
01055
01056
01057
01058
01059
01060
01061
01062
01063
01064
01065
01066
01067
01068
01069
01070
01071
01072
01073
01074
01075
01076
01077
01078
01079
01080
01081
01082
01083
01084
01085
01086
01087
01088
01089
01090
01091
01092
01093
01094
01095
01096
01097
01098
01099
01100
01101
01102
01103
01104
01105
01106
01107
01108
01109
01110
01111
01112
01113
01114
01115
01116
01117
01118
01119
01120
01121
01122
01123
01124
01125
01126
01127
01128
01129
01130
01131
01132
01133
01134
01135
01136
01137
01138
01139
01140
01141
01142
01143
01144
01145
01146
01147
01148
01149
01150
01151
01152
01153
01154
01155
01156
01157
01158
01159
01160
01161
01162
01163
01164
01165
01166
01167
01168
01169
01170
01171
01172
01173
01174
01175
01176
01177
01178
01179
01180
01181
01182
01183
01184
01185
01186
01187
01188
01189
01190
01191
01192
01193
01194
01195
01196
01197
01198
01199
01200
01201
01202
01203
01204
01205
01206
01207
01208
01209
01210
01211
01212
01213
01214
01215
01216
01217
01218
01219
01220
01221
01222
01223
01224
01225
01226
01227
01228
01229
01230
01231
01232
01233
01234
01235
01236
01237
01238
01239
01240
01241
01242
01243
01244
01245
01246
01247
01248
01249
01250
01251
01252
01253
01254
01255
01256
01257
01258
01259
01260
01261
01262
01263
01264
01265
01266
01267
01268
01269
01270
01271
01272
01273
01274
01275
01276
01277
01278
01279
01280
01281
01282
01283
01284
01285
01286
01287
01288
01289
01290
01291
01292
01293
01294
01295
01296
01297
01298
01299
01300
01301
01302
01303
01304
01305
01306
01307
01308
01309
01310
01311
01312
01313
01314
01315
01316
01317
01318
01319
01320
01321
01322
01323
01324
01325
01326
01327
01328
01329
01330
01331
01332
01333
01334
01335
01336
01337
01338
01339
01340
01341
01342
01343
01344
01345
01346
01347
01348
01349
01350
01351
01352
01353
01354
01355
01356
01357
01358
01359
01360
01361
01362
01363
01364
01365
01366
01367
01368
01369
01370
01371
01372
01373
01374
01375
01376
01377
01378
01379
01380
01381
01382
01383
01384
01385
01386
01387
01388
01389
01390
01391
01392
01393
01394
01395
01396
01397
01398
01399
01400
01401
01402
01403
01404
01405
01406
01407
01408
01409
01410
01411
01412
01413
01414
01415
01416
01417
01418
01419
01420
01421
01422
01423
01424
01425
01426
01427
01428
01429
01430
01431
01432
01433
01434
01435
01436
01437
01438
01439
01440
01441
01442
01443
01444
01445
01446
01447
01448
01449
01450
01451
01452
01453
01454
01455
01456
01457
01458
01459
01460
01461
01462
01463
01464
01465
01466
01467
01468
01469
01470
01471
01472
01473
01474
01475
01476
01477
01478
01479
01480
01481
01482
01483
01484
01485
01486
01487
01488
01489
01490
01491
01492
01493
01494
01495
01496
01497
01498
01499
01500
01501
01502
01503
01504
01505
01506
01507
01508
01509
01510
01511
01512
01513
01514
01515
01516
01517
01518
01519
01520
01521
01522
01523
01524
01525
01526
01527
01528
01529
01530
01531
01532
01533
01534
01535
01536
01537
01538
01539
01540
01541
01542
01543
01544
01545
01546
01547
01548
01549
01550
01551
01552
01553
01554
01555
01556
01557
01558
01559
01560
01561
01562
01563
01564
01565
01566
01567
01568
01569
01570
01571
01572
01573
01574
01575
01576
01577
01578
01579
01580
01581
01582
01583
01584
01585
01586
01587
01588
01589
01590
01591
01592
01593
01594
01595
01596
01597
01598
01599
01600
01601
01602
01603
01604
01605
01606
01607
01608
01609
01610
01611
01612
01613
01614
01615
01616
01617
01618
01619
01620
01621
01622
01623
01624
01625
01626
01627
01628
01629
01630
01631
01632
01633
01634
01635
01636
01637
01638
01639
01640
01641
01642
01643
01644
01645
01646
01647
01648
01649
01650
01651
01652
01653
01654
01655
01656
01657
01658
01659
01660
01661
01662
01663
01664
01665
01666
01667
01668
01669
01670
01671
01672
01673
01674
01675
01676
01677
01678
01679
01680
01681
01682
01683
01684
01685
01686
01687
01688
01689
01690
01691
01692
01693
01694
01695
01696
01697
01698
01699
01700
01701
01702
01703
01704
01705
01706
01707
01708
01709
01710
01711
01712
01713
01714
01715
01716
01717
01718
01719
01720
01721
01722
01723
01724
01725
01726
01727
01728
01729
01730
01731
01732
01733
01734
01735
01736
01737
01738
01739
01740
01741
01742
01743
01744
01745
01746
01747
01748
01749
01750
01751
01752
01753
01754
01755
01756
01757
01758
01759
01760
01761
01762
01763
01764
01765
01766
01767
01768
01769
01770
01771
01772
01773
01774
01775
01776
01777
01778
01779
01780
01781
01782
01783
01784
01785
01786
01787
01788
01789
01790
01791
01792
01793
01794
01795
01796
01797
01798
01799
01800
01801
01802
01803
01804
01805
01806
01807
01808
01809
01810
01811
01812
01813
01814
01815
01816
01817
01818
01819
01820
01821
01822
01823
01824
01825
01826
01827
01828
01829
01830
01831
01832
01833
01834
01835
01836
01837
01838
01839
01840
01841
01842
01843
01844
01845
01846
01847
01848
01849
01850
01851
01852
01853
01854
01855
01856
01857
01858
01859
01860
01861
01862
01863
01864
01865
01866
01867
01868
01869
01870
01871
01872
01873
01874
01875
01876
01877
01878
01879
01880
01881
01882
01883
01884
01885
01886
01887
01888
01889
01890
01891
01892
01893
01894
01895
01896
01897
01898
01899
01900
01901
01902
01903
01904
01905
01906
01907
01908
01909
01910
01911
01912
01913
01914
01915
01916
01917
01918
01919
01920
01921
01922
01923
01924
01925
01926
01927
01928
01929
01930
01931
01932
01933
01934
01935
01936
01937
01938
01939
01940
01941
01942
01943
01944
01945
01946
01947
01948
01949
01950
01951
01952
01953
01954
01955
01956
01957
01958
01959
01960
01961
01962
01963
01964
01965
01966
01967
01968
01969
01970
01971
01972
01973
01974
01975
01976
01977
01978
01979
01980
01981
01982
01983
01984
01985
01986
01987
01988
01989
01990
01991
01992
01993
01994
01995
01996
01997
01998
01999
02000
02001
02002
02003
02004
02005
02006
02007
02008
02009
02010
02011
02012
02013
02014
02015
02016
02017
02018
02019
02020
02021
02022
02023
02024
02025
02026
02027
02028
02029
02030
02031
02032
02033
02034
02035
02036
02037
02038
02039
02040
02041
02042
02043
02044
02045
02046
02047
02048
02049
02050
02051
02052
02053
02054
02055
02056
02057
02058
02059
02060
02061
02062
02063
02064
02065
02066
02067
02068
02069
02070
02071
02072
02073
02074
02075
02076
02077
02078
02079
02080
02081
02082
02083
02084
02085
02086
02087
02088
02089
02090
02091
02092
02093
02094
02095
02096
02097
02098
02099
02100
02101
02102
02103
02104
02105
02106
02107
02108
02109
02110
02111
02112
02113
02114
02115
02116
02117
02118
02119
02120
02121
02122
02123
02124
02125
02126
02127
02128
02129
02130
02131
02132
02133
02134
02135
02136
02137
02138
02139
02140
02141
02142
02143
02144
02145
02146
02147
02148
02149
02150
02151
02152
02153
02154
02155
02156
02157
02158
02159
02160
02161
02162
02163
02164
02165
02166
02167
02168
02169
02170
02171
02172
02173
02174
02175
02176
02177
02178
02179
02180
02181
02182
02183
02184
02185
02186
02187
02188
02189
02190
02191
02192
02193
02194
02195
02196
02197
02198
02199
02200
02201
02202
02203
02204
02205
02206
02207
02208
02209
02210
02211
02212
02213
02214
02215
02216
02217
02218
02219
02220
02221
02222
02223
02224
02225
02226
02227
02228
02229
02230
02231
02232
02233
02234
02235
02236
02237
02238
02239
02240
02241
02242
02243
02244
02245
02246
02247
02248
02249
02250
02251
02252
02253
02254
02255
02256
02257
02258
02259
02260
02261
02262
02263
02264
02265
02266
02267
02268
02269
02270
02271
02272
02273
02274
02275
02276
02277
02278
02279
02280
02281
02282
02283
02284
02285
02286
02287
02288
02289
02290
02291
02292
02293
02294
02295
02296
02297
02298
02299
02300
02301
02302
02303
02304
02305
02306
02307
02308
02309
02310
02311
02312
02313
02314
02315
02316
02317
02318
02319
02320
02321
02322
02323
02324
02325
02326
02327
02328
02329
02330
02331
02332
02333
02334
02335
02336
02337
02338
02339
02340
02341
02342
02343
02344
02345
02346
02347
02348
02349
02350
02351
02352
02353
02354
02355
02356
02357
02358
02359
02360
02361
02362
02363
02364
02365
02366
02367
02368
02369
02370
02371
02372
02373
02374
02375
02376
02377
02378
02379
02380
02381
02382
02383
02384
02385
02386
02387
02388
02389
02390
02391
02392
02393
02394
02395
02396
02397
02398
02399
02400
02401
02402
02403
02404
02405
02406
02407
02408
02409
02410
02411
02412
02413
02414
02415
02416
02417
02418
02419
02420
02421
02422
02423
02424
02425
02426
02427
02428
02429
02430
02431
02432
02433
02434
02435
02436
02437
02438
02439
02440
02441
02442
02443
02444
02445
02446
02447
02448
02449
02450
02451
02452
02453
02454
02455
02456
02457
02458
02459
02460
02461
02462
02463
02464
02465
02466
02467
02468
02469
02470
02471
02472
02473
02474
02475
02476
02477
02478
02479
02480
02481
02482
02483
02484
02485
02486
02487
02488
02489
02490
02491
02492
02493
02494
02495
02496
02497
02498
02499
02500
02501
02502
02503
02504
02505
02506
02507
02508
02509
02510
02511
02512
02513
02514
02515
02516
02517
02518
02519
02520
02521
02522
02523
02524
02525
02526
02527
02528
02529
02530
02531
02532
02533
02534
02535
02536
02537
02538
02539
02540
02541
02542
02543
02544
02545
02546
02547
02548
02549
02550
02551
02552
02553
02554
02555
02556
02557
02558
02559
02560
02561
02562
02563
02564
02565
02566
02567
02568
02569
02570
02571
02572
02573
02574
02575
02576
02577
02578
02579
02580
02581
02582
02583
02584
02585
02586
02587
02588
02589
02590
02591
02592
02593
02594
02595
02596
02597
02598
02599
02600
02601
02602
02603
02604
02605
02606
02607
02608
02609
//=============================================================================
// UtilGame.uc
// $Author: Mfox $
// $Date: 1/05/03 8:45p $
// $Revision: 38 $
//=============================================================================
//NEW: file

class UtilGame extends Actor // never instantiated and extending Actor makes things easier
	abstract;

//=============================================================================
// Game-level utility functions, e.g. inventory, actor searching, AI. 
//=============================================================================

const MaxFilteredActors		= 10;

const NonPawnGravityFactor	= 0.500;	// amount we need to scale gravity by for Newtonian physics calculations to work
const PawnGravityFactor		= 1.000;	// pawns seem to fall under 2x the gravity of other actors...?

// debug
const TimeFieldSize			=  8;
const NameFieldSize			= 15;
const StateFieldSize		= 32;
const PrefixFieldSize		=  5;

const MaxPathCheckRadius	= 1300;		// (PathsMaxDist+100)

const Radians45				= 0.785398; // 45 degrees in radians

//=============================================================================

enum ETrajectoryType
{
	TRAJ_None,
	TRAJ_Low,			// only check/return low trajectory
	TRAJ_High,			// only check/return high trajectory
	TRAJ_PreferLow,		// check/return low first, then check/return high if low fails
	TRAJ_PreferHigh,	// check/return high first, then check/return low if high fails
};

enum ELeapResult
{
	LR_None,			// no solution or blocked
	LR_OutOfRange,		// destination is too far to reach
	LR_OutOfAngle,		// angle between vector to destination and Pawn's rotation is too great
	LR_Success,			// found a valid solution
};

enum EDistanceFilterType
{
	DFT_First,
	DFT_Closest,
	DFT_Furthest,
	DFT_Any,
};

enum EVisibilityFilterType
{
	VFT_None,
	VFT_Visible,
	VFT_FOV,
};

var int VerifyTrajectorySamples;
var float VerifyTrajectoryHorizontalExtentPadding;
var float VerifyTrajectoryVerticalExtentPadding;
var int MaxPredictProjectileAttempts;
var float PredictProjectileThreshold;

var float MinTargetBlockedMissMultiplier;
var float MaxTargetBlockedMissMultiplier;
var float MinTargetBlockedPitchError;
var float MaxTargetBlockedPitchError;
var float MinModifyForSpreadDistance;
var float MinPitchError;
var float MaxPitchError;

var private name LastDebugName;

//=============================================================================
//@ Inventory accessor and mutator functions
//=============================================================================

static final function DumpInventory( Pawn P, optional string ContextString )
{
	local Inventory Inv;
	
	P.DMTNS( "DumpInventory" @ ContextString $ ":" );
	for( Inv = P.Inventory; Inv != None; Inv = Inv.Inventory )
		P.DMTNS( "  " $ Inv );
}

//-----------------------------------------------------------------------------
// Spawn and add to inventory if not already present. If an item of the same
// class is present, return that one.

static final function Inventory GiveInventoryClass( Pawn TargetPawn, class<Inventory> InvClass )
{
	local Inventory Inv, InvNew;

	//TargetPawn.DMTNS( "GiveInventoryClass " $ InvClass );
	//class'UtilGame'.static.DumpInventory( TargetPawn, "GiveInventoryClass BEGIN" );
	if( InvClass != None )
	{
		Inv = TargetPawn.FindInventoryType( InvClass );
		if( Inv == None || Inv.bMergesCopies )
		{
			InvNew = TargetPawn.Spawn( InvClass );
			if( InvNew != None )
				InvNew.GiveTo( TargetPawn );
		}
	}
	//class'UtilGame'.static.DumpInventory( TargetPawn, "GiveInventoryClass END" );
	if( Inv != None )
		return Inv;
	else
		return InvNew;
}

//-----------------------------------------------------------------------------
// Spawn and add to inventory if not already present.

static final function Inventory GiveInventoryString( Pawn TargetPawn, coerce string InventoryString )
{
	return GiveInventoryClass( TargetPawn, class<Inventory>(DynamicLoadObject( InventoryString, class'Class' )) );
}

//-----------------------------------------------------------------------------
// Add to inventory if not already present.

static final function bool GiveInventory( Pawn TargetPawn, Inventory Inv )
{
	local Inventory MatchingInv;

	if( Inv != None )
	{
		MatchingInv = TargetPawn.FindInventoryType( Inv.Class );
		if( MatchingInv == None || Inv.bMergesCopies )
		{
			Inv.GiveTo( TargetPawn );
			return true;
		}
	}

	return false;
}

//-----------------------------------------------------------------------------

static final function bool RemoveInventoryString( Pawn TargetPawn, coerce string InventoryString )
{
	local Inventory Inv;
	local class<Inventory> RemovedClass;

	if( InventoryString != "" )
		RemovedClass = class<Inventory>(DynamicLoadObject( InventoryString, class'Class' ));
	else
		RemovedClass = class'Inventory';

	if( RemovedClass != None )
	{
		for( Inv = TargetPawn.Inventory; Inv != None; Inv = Inv.Inventory )
		{
			if( Inv.IsA( RemovedClass.Name ) )
				Inv.Destroy(); //removes inventory as well
		}
	}

	return (RemovedClass != None);
}

//-----------------------------------------------------------------------------
// Return inventory item from holder's inventory matching class 'InventoryType'

static final function Inventory GetInventoryItem( Pawn InventoryHolder, class<Inventory> InventoryType )
{
	local Inventory CurrentInventoryItem;
	local Inventory FoundInventoryItem;

	if( InventoryHolder == None )
		return None;

	for( CurrentInventoryItem = InventoryHolder.Inventory;
			( ( None != CurrentInventoryItem ) && ( None == FoundInventoryItem ) );
			CurrentInventoryItem = CurrentInventoryItem.Inventory )
	{
		if( ClassIsChildOf( CurrentInventoryItem.Class, InventoryType ) )
		{
			FoundInventoryItem = CurrentInventoryItem;
		}
	}
	
	return FoundInventoryItem;
}

//-----------------------------------------------------------------------------

static final function int GetInventoryCount( Pawn InventoryHolder, class<Inventory> InventoryType )
{
	local Inventory CurrentInventoryItem;
	local int InventoryCount;

	for( CurrentInventoryItem = InventoryHolder.Inventory;
			CurrentInventoryItem != None;
			CurrentInventoryItem = CurrentInventoryItem.Inventory )
	{
		if( CurrentInventoryItem.IsA( InventoryType.Name ) )
		{
			InventoryCount++;
		}
	}
	
	return InventoryCount;
}

//-----------------------------------------------------------------------------
// Checks whether P has the given weapon in its inventory, spawning one and
// giving it to P if necessary.

static final function Weapon ForceWeaponIntoInventory( Pawn P, class<Weapon> WeapClass )
{
	local Inventory Inv;
	local Weapon Weap;

	//class'UtilGame'.static.DumpInventory( P, "ForceWeaponIntoInventory BEGIN" );
	// see if already in inventory
	Inv = P.FindInventoryType( WeapClass );
	if( Inv == None )
	{
		//P.DMTNS( "ForceWeaponIntoInventory spawning " $ WeapClass );
		Weap = P.Spawn( WeapClass );
		Weap.GiveTo( P );
	}
	else
	{
		Weap = Weapon( Inv );
	}

	//class'UtilGame'.static.DumpInventory( P, "ForceWeaponIntoInventory END" );
	
	return Weap;
}

//-----------------------------------------------------------------------------
// Note: Weap can be None to specify that the Pawn should be holding no weapon.

static final function MakeWeaponCurrent( Pawn P, Weapon Weap )
{
	#debug   P.Controller.StopFiring( 0.5, SFI_WeaponSwitch, GetContext() );
	#release P.Controller.StopFiring( 0.5, SFI_WeaponSwitch );

	P.PendingWeapon = Weap;
	if( P.PendingWeapon == P.Weapon )
		P.PendingWeapon = None;
	if( P.PendingWeapon == None )
		return;

	if( P.Weapon == None )
		P.ChangedWeapon();

	if( P.Weapon != P.PendingWeapon )
		P.Weapon.PutDown();
}

//-----------------------------------------------------------------------------
// Note: can use WeapClass=None to specify that the Pawn shouldn't be holding a
// weapon.

static final function Weapon SetCurrentWeaponClass( Pawn P, class<Weapon> WeapClass )
{
	local Weapon Weap;

 	if( WeapClass != None )
 	{
 		Weap = ForceWeaponIntoInventory( P, WeapClass );
 		
 		if( P.Weapon != Weap )
 			MakeWeaponCurrent( P, Weap );
 	}
 	
	return Weap;
}

//-----------------------------------------------------------------------------
// Makes sure Pawn has the given weapon in his inventory and makes it the 
// currently selected weapon. Makes sure that the Pawn has the default amount
// of ammo for the weapon. Can use WeaponClassString="" to specify that the
// Pawn shouldn't be holding a weapon.

static final function Weapon SetCurrentWeaponString( Pawn P, string WeaponClassString )
{
	local Weapon Weap;
	local class<Weapon> WeapClass;

	if( P != None )
	{
		if( WeaponClassString != "" )
			WeapClass = Class<Weapon>( DynamicLoadObject( WeaponClassString, Class'Class' ) );

		// set even if DynamicLoadObject fails to make problem obvious
		Weap = SetCurrentWeaponClass( P, WeapClass );
	}

	// !!mdf-tbr?:
	if( Weap == None && WeaponClassString != "" )
		P.DMTN( "SetCurrentWeaponString -- couldn't set weapon to: " $ WeaponClassString );

	return Weap;
}

//=============================================================================
//@ Misc
//=============================================================================

//-----------------------------------------------------------------------------
// Returns true if the given actor can be moved MoveDistance units along the 
// given MoveDir. Makes sure that the collision cylinder will fit along the
// trace from the actor's current location to the new location and that the
// maximum step height is not exceeded.
//-----------------------------------------------------------------------------

static final function bool CanActorMoveTo( Actor A, vector MoveDir, float MoveDistance )
{				
	local vector HitLocation, HitNormal, Extent;
	local Actor HitActor;
		
	Extent.X = A.CollisionRadius;
	Extent.Y = A.CollisionRadius;
	Extent.Z = A.CollisionHeight;

	//trace from actor's location MoveDistance units along MoveDir using extents	
	HitActor = class'Util'.static.TraceRecursive( A, HitLocation, HitNormal, A.Location, false, , MoveDir, MoveDistance, Extent, TRACE_AllBlocking );

	return ( ( HitActor == None ) || ( VSize( HitLocation - A.Location ) >= MoveDistance ) );
}

//-----------------------------------------------------------------------------
// Put the given actor at the given location, but adjust location's Z value so
// the bottom of the actor's collision cylinder is touching the floor.
//
// Doesn't handled sloped surfaces currently (actor could end up intersecting
// surface). Probably not too great on stairs either.
//
// !!mdf-tbd: add an optional offset used instead of calculated one to avoid doing
// this 2x?
//
// !!mdf-tbd: turn into exec function which calls actor version or at least consolidate
// common functionality?

static final function bool PlaceActorOnFloorUnderLocation( Actor TargetActor, vector TargetLocation )
{
	local vector HitLocation, HitNormal;
	local vector NewLocation;
	local float HeightAboveFloor;
	local bool bRetVal;

	bRetVal = false;

	// trace down from target location to determine height above floor
	// !!mdf-tbd: instance actor probably isn't at either of the endpoints for the trace -- can
	// this cause problems? More generally, can't TraceRecursive fail or return incorrect
	// results if the desired HitLocation is inside the instance actor?

	class'Util'.static.TraceRecursive( TargetActor, HitLocation, HitNormal, TargetLocation, false, 500, , 500 );

	// !!mdf-tbf: this assumes a flat surface. Not sure but I think the engine might "pop" the 
	// TargetActor up if necessary on a sloped surface or on stairs etc. Not trivial to determine
	// (quickly) exactly how much vertical offset should be so that actor under/over given location
	// will *just* sit on the floor.
	HeightAboveFloor = VSize( TargetLocation - HitLocation );

	NewLocation = TargetLocation;
	NewLocation.Z += (TargetActor.CollisionHeight - HeightAboveFloor);
			   
	return TargetActor.SetLocation( NewLocation );
}

//-----------------------------------------------------------------------------
// !!mdf-tbd: really need to turn this into a native function which uses 
// MoveActor to drop the actor to the floor (after turning on collision 
// temporarily as needed). This function will likely fail for sloped surfaces.

static final function PlaceActorOnFloor( Actor A )
{
	local Actor HitActor;
	local vector HitLocation, HitNormal;

	// NOTE: can't use phys_falling etc. -- we might want this to happen right away
	HitActor = class'Util'.static.TraceRecursive( A, HitLocation, HitNormal, A.Location, false, 500, , 500 );
	if( HitActor != None )
	{
		if( !A.SetLocation( HitLocation + A.CollisionHeight*vect(0,0,1) ) )
			A.DMAssert( false, GetContext() );
	}
}

//-----------------------------------------------------------------------------
// If the NPC could be obstructed by geometry at the given location, find point 
// on ground slightly above/below given location that Pawn is likely able to 
// reach. For flying or swimming NPCs, only need to adjust if the point above 
// the ground is higher than the original location (i.e. fix NPCs flying or
// swimming into geometry but don't fix case where destination will cause NPC
// to fly/swim above the ground since that is ok unless the NPC is walking).

//!!mdf-tbd: return false if destination is in geometry and can't be adjusted?

static function AdjustDestinationForPhysics( Actor SourceActor, out vector DestinationLocation )
{
	local float TargetDistance;
	local vector OriginalLocation, AdjustedLocation, HitLocation, HitNormal;
	local Actor HitActor;

	OriginalLocation = DestinationLocation;

	//AddCylinder( OriginalLocation, 2, 2, ColorWhite() );
	
	TargetDistance = 1.25*VSize2D( DestinationLocation - SourceActor.Location );

	//SourceActor.DMTNS( "TargetDistance #1: " $ TargetDistance );
	// first trace up to make sure TargetDistance won't shift us up into
	// geometry above the original location.
	//AddArrow( DestinationLocation, DestinationLocation + FMax( TargetDistance*1.10, 1024.0 )*vect(0,0,1), ColorWhite() );
	HitActor = SourceActor.Trace( HitLocation, HitNormal, DestinationLocation + FMax( TargetDistance*1.10, 1024.0 )*vect(0,0,1), DestinationLocation, false );
	if( HitActor != None && HitLocation != DestinationLocation )
		TargetDistance = VSize( DestinationLocation - HitLocation );
	
	// raise destination location up enough to account for where Pawn could end up if
	// walking toward destination on a max steepness slope
	AdjustedLocation = DestinationLocation;
	AdjustedLocation.Z += TargetDistance;
	
	// trace down until we hit the ground (allow for sloped surface)
	//SourceActor.DMTNS( "TargetDistance #2: " $ TargetDistance );
	//AddArrow( AdjustedLocation, AdjustedLocation - FMax( TargetDistance*1.10, 1024.0 )*vect(0,0,1), ColorOrange() );
	//!!mdf-tbd: use moveactor with extents to do this (drop location back to ground) then eliminate fitactor at stuff?
	HitActor = SourceActor.Trace( HitLocation, HitNormal, AdjustedLocation - FMax( TargetDistance*1.10, 1024.0 )*vect(0,0,1), AdjustedLocation, false );
	if( HitActor != None )
	{
		// adjust destination location?
		AdjustedLocation = HitLocation;
		AdjustedLocation.Z += SourceActor.CollisionHeight + CCFloatHeight;
		//AddCylinder( AdjustedLocation, 4, 4, ColorYellow() );
		if( SourceActor.FitActorAt( AdjustedLocation ) != 0 ) // get engine to pop location out of geometry?
		{	
			if( SourceActor.Physics == PHYS_Walking )
			{
				// trace to ground again (location may have been pushed above the ground
				HitActor = SourceActor.Trace( HitLocation, HitNormal, AdjustedLocation - 128.0*vect(0,0,1), AdjustedLocation, false );
				if( HitActor != None )
				{
					AdjustedLocation = HitLocation;
					AdjustedLocation.Z += SourceActor.CollisionHeight + CCFloatHeight;
					DestinationLocation = AdjustedLocation; // walking creature has to stay on ground
				}
			}
			else if( AdjustedLocation.Z > DestinationLocation.Z )
				DestinationLocation = AdjustedLocation; // flying/swimming creature blocked by geometry?
				
			//AddCylinder( AdjustedLocation, 8, 8, ColorOrange() );
		}
	}
	
	#debugbegin
	//AddCylinder( OriginalLocation, 4, 4, ColorMagenta() );
	//if( DestinationLocation != OriginalLocation )
	//	AddArrow( OriginalLocation, DestinationLocation, ColorMagenta() );
	#debugend
}

//-----------------------------------------------------------------------------

static final function MakeShake( Actor Context, vector ShakeLocation, float ShakeRadius, float ShakeMagnitude, optional float ShakeDuration )
{
	local Controller C;
	local PlayerController Player;
	local float Dist,Pct;

	if( Context==None || ShakeRadius<=0 || ShakeMagnitude<=0 )
		return;

	for( C=Context.Level.ControllerList; C!=None; C=C.nextController )
	{
		Player = PlayerController(C);
		//NEW (mib) - don't shake a flying / ghosted player (leave shake in for matinee cutscenes)
		if( Player!=None &&
			(Player.Pawn==None || Player.Pawn.Physics != PHYS_Flying) )
		/*OLD
		if( Player!=None )
		*/
		{
			Dist = VSize(ShakeLocation-Player.Location);
			if( Dist<ShakeRadius )
			{
				Pct = 1.0 - (Dist / ShakeRadius);
				Player.ShakeView( ShakeMagnitude * Pct, ShakeDuration );
			}
		}
	}
}

//-----------------------------------------------------------------------------
// Copies display-related information from Source Actor to DestinationActor.

static final function CopyDisplaySettings( Actor Source, Actor Destination )
{
	local int i;

	for( i = 0; i < Destination.Skins.length; i++ )
	{
		Destination.Skins[ i ] = Source.Skins[ i ];
	}

	Destination.Mesh					= Source.Mesh;
	Destination.Mesh					= Source.Mesh;
	Destination.Texture					= Source.Texture;
	Destination.SetDrawScale			( Source.DrawScale );
	Destination.AnimSequence			= Source.AnimSequence;
	Destination.AnimFrame				= Source.AnimFrame;
	Destination.AnimRate				= Source.AnimRate;
	Destination.TweenRate				= Source.TweenRate;
	Destination.SimAnim.bAnimLoop		= Source.SimAnim.bAnimLoop;
	Destination.SimAnim.AnimFrame		= Source.AnimFrame * 10000;
	Destination.SimAnim.AnimRate		= Source.AnimRate  * 5000; 
	Destination.SimAnim.TweenRate		= Source.TweenRate * 1000; 
//!!cdh	Destination.SimAnim.W				= Source.AnimLast  * 10000;
	Destination.bAnimFinished			= Source.bAnimFinished;
	Destination.bSpecialLit				= Source.bSpecialLit;
}

static final function string GetAIDebugMessage( Controller C, string Prefix, coerce string Msg, optional coerce string StateStr, optional bool bSpace )
{
	local name ThisDebugName;
	local string ThisDebugNameStr;

	if( C.Pawn != None )
		ThisDebugName = C.Pawn.Name;
	else
		ThisDebugName = 'xxxx';

	if( default.LastDebugName != ThisDebugName )
	{
		if( bSpace )
			log( "", '' );
		default.LastDebugName = ThisDebugName;
	}

	// use real name for players (bots)
	if( C.PlayerReplicationInfo != None )
		ThisDebugNameStr = C.PlayerReplicationInfo.PlayerName;
	else
		ThisDebugNameStr = string(ThisDebugName);

	return ( class'Util'.static.GetPaddedTime( C.Level.TimeSeconds, TimeFieldSize, true ) @
			 class'Util'.static.PadString( Right( ThisDebugNameStr, NameFieldSize ), NameFieldSize ) @
			 class'Util'.static.PadString( StateStr, StateFieldSize ) @
			 class'Util'.static.PadString( Prefix, PrefixFieldSize ) @
			 Msg );
}

//-----------------------------------------------------------------------------

static final function LogAIDebugMessage( Controller C, string Prefix, coerce string Msg, optional coerce string StateStr, optional bool bSkipLine )
{
	local string HealthStr;
	
	if( C.Pawn != None )
		HealthStr = string(C.Pawn.Health);	
	else
		HealthStr = "NA";
		
	C.DM( GetAIDebugMessage( C, Prefix, Msg $ " (Controller: " $ C $ " Enemy: " $ C.ControllerEnemy $ " Health: " $ HealthStr $ ")", StateStr, true ) );
	if( bSkipLine )
		log( "", '' );
}

//-----------------------------------------------------------------------------

static final function DrawFace( Face F, Color Clr )
{
	local int i;
	for( i=0; i<F.Points.Length-1; i++ )
		AddLine( F.Points[ i ], F.Points[ i+1 ], Clr );

	AddLine( F.Points[ F.Points.Length-1 ], F.Points[ 0 ], Clr );
}

//-----------------------------------------------------------------------------

static final function bool VertexWithinDistance( Actor A, array<Face> Faces, float MaxDistance )
{
	local float Distance;
	local int ii, jj;
	
	for( ii=0; ii<Faces.Length; ii++ )
	{
		for( jj=0; jj<Faces[ jj ].Points.Length; jj++ )
		{
			Distance = VSize( A.Location - Faces[ ii ].Points[ jj ] );
			if( Distance < MaxDistance )
				return true;
		}
	}
	
	return false;
}

//-----------------------------------------------------------------------------
// Note: assumes that no edge in Faces is > MaxPathDistance units long (for the
// quick-filter test).

static final function bool UpdatePathsForBlockingFaces( Actor ContextActor, array<Face> Faces, float CostToAdd, int TeamNumber, array<ReachSpec> ModifiedReachSpecs )
{
	local int ii, jj;
	local vector IntersectionPoint;
	local NavigationPoint StartNP, EndNP;
	local ReachSpec RS;
	local Controller C;
	local float AddPathOffset;
	local bool bIntersects;
	local bool bModifiedPaths;
	
	//!!debug help
	//ContextActor.DMTNS( "Faces: " $ Faces.Length );
	//for( ii=0; ii<Faces.Length; ii++ )
	//	DrawFace( Faces[ ii ], ColorRed() );

	ModifiedReachSpecs.Length = 0;
	for( StartNP = ContextActor.Level.NavigationPointList; StartNP != None; StartNP = StartNP.nextNavigationPoint )
	{
		// NOTE: optimization don't bother to check points which are too far away 
		// from any point in the Faces list to possibly have a path through it.
		if( VertexWithinDistance( StartNP, Faces, MaxPathCheckRadius ) )
		{
			// look at all paths (reachspecs) out of this StartNP
			for( ii=0; ii<StartNP.PathList.Length; ii++ )
			{
				RS = StartNP.PathList[ ii ];
				EndNP = StartNP.PathList[ ii ].End;
				//ContextActor.DMTNS( "  checking NP2: " $ EndNP );
				if( VertexWithinDistance( EndNP, Faces, MaxPathCheckRadius ) )
				{
					// see if path out of StartNP passes through wall (all 6 sides -- can't use a bounding box as left/right might not be at same height)
					bIntersects = false;
					for( jj=0; jj<Faces.Length; jj++ )
					{	
						if( class'Util'.static.LineConvexPolygonIntersection( RS.Start.Location, EndNP.Location, Faces[ jj ].Points, IntersectionPoint ) )
						{
							bIntersects = true;
							break;
						}
					}

					if( bIntersects )												
					{
						ModifiedReachSpecs[ ModifiedReachSpecs.Length ] = RS;
						
						// enable/disable modify/restore any paths which pass through or near the wall
						RS.ExtraCost += CostToAdd;
						
						// is the reachspec back to 0 ExtraCost?
						if( RS.ExtraCost != 0 )
						{
							RS.SpecialTeamNumber = TeamNumber;
							RS.bSpecialCollision = true;
						}
						else
						{
							RS.SpecialTeamNumber = class'ReachSpec'.default.SpecialTeamNumber;
							RS.bSpecialCollision = false;
						}
						
						bModifiedPaths = true;
					}
				}
			}
		}
	}

	//mdf-tbr: for testing (so path colors updated instantlly) but pbly not adding much overhead
	if( bModifiedPaths )
	{
		for( C=ContextActor.Level.ControllerList; C!=None; C=C.nextController )
		{
			if( C.IsRealPlayer() )
			{
				C.ConsoleCommand( "paths refresh" );
				break;
			}
		}
	}
	
	return bModifiedPaths;
}

//-----------------------------------------------------------------------------
// 
static function bool CutsceneIsRunning( actor ContextActor )
{
	local SceneManager SM;
	foreach ContextActor.AllActors( class'SceneManager', SM )
	{
		if( SM.bIsRunning )
			return true;
	}
	return false;
}


//=============================================================================
//@ Projectile Motion 
//=============================================================================

static final function float GetGravityConstant( Actor SourceActor, class<Actor> ProjectileClass )
{
	if( ClassIsChildOf( ProjectileClass, class'Pawn' ) )
		return -PawnGravityFactor * SourceActor.PhysicsVolume.default.Gravity.Z;
	else
		return -NonPawnGravityFactor * SourceActor.PhysicsVolume.default.Gravity.Z;
}

/*-----------------------------------------------------------------------------
The range of a projectile (horizontal distance traveled before the projectile
is back at the starting height is given by:

	Range = speed^2 * sin( 2*theta ) / g

where

	speed = initial speed
	theta = initial angle above horizontal
	g     = gravity
	
Unreal's simulated physics are close enough to Newtonian physics for these
equations to work fine as long as the gravity is scaled by a "magic" fudge
factor to get the gravity "right".
*/

static final function float GetRange( Actor SourceActor, class<Actor> ProjectileClass, float ProjectileSpeed, float Theta )
{
	return ProjectileSpeed * ProjectileSpeed * sin( 2*Theta ) / GetGravityConstant( SourceActor, ProjectileClass );
}

/*-----------------------------------------------------------------------------
The maximum range of a projectile (see GetRange equation) occurs when the
sin( 2*Theta) component is maximized, which will occur when 2*Theta = 90 
degrees since sin(90) = 1.0.
	
	RangeMax = speed^2 / g
*/

static final function float GetMaxRange( Actor SourceActor, class<Actor> ProjectileClass, float ProjectileSpeed )
{
	return ProjectileSpeed * ProjectileSpeed / GetGravityConstant( SourceActor, ProjectileClass );
}

/*-----------------------------------------------------------------------------
The best reference for this is probably "Inverse Trajectory Determination" from
Game Programming Gems 2 (Aaron Nicholls).

If we have

V = initial velocity
X = target distance from start
Y = target elevation relative to start elevation
G = gravity

the angle needed to have the fired projectile pass through X,Y is given by

	Theta = invtan[ V^2[ -X +/- sqrt( (X^2 - G^2*X^4/V^4 + 2G*X^2*Y/V^2) / G*X^2 ) ]]

and the time to the target is given by

	T = X / (V * cos(Theta))

Returns the number of solutions found:

	0: target is outside of projectile's range (try 45 degrees?)
	1: target is at projectile's range
	2: target is inside projectile's range (high and low solutions)
	
Note that if the target is inside the projectile'salways be 2 solutions, one
using a lower/flatter trajectory, the other using a higher/more arcing 
trajectory. In general, the lower trajectory is more desirable as it will get
the projectile to the target more quickly, but there are cases where the higher
trajectory may be desired, e.g. to "mix up" shots or to shoot over an 
obstruction.

Use VerifyTrajectory to check whether the trajectory is likely to intersect
with any geometry.
*/

static final function int GetInverseTrajectory( 
	Actor SourceActor, 
	class<Actor> ProjectileClass, 
	float ProjectileSpeed, 
	vector StartLocation, 
	vector TargetLocation, 
	out float ThetaLow, 
	out float ThetaHigh, 
	out float InterceptTimeLow, 
	out float InterceptTimeHigh )
{
	local float V;
	local float G;
	local float X, Y;
	local float Root, SquareRoot;
	local float XSquared, VSquared, GXSquared;
	local float TempFloat;
	local int NumSolutions;

	if( ProjectileSpeed ~= 0.0 )
		return 0;

	V = ProjectileSpeed;
	X = VSize2D( TargetLocation - StartLocation );
	Y = -(TargetLocation.Z - StartLocation.Z);
	
	G = GetGravityConstant( SourceActor, ProjectileClass );

	//SourceActor.DMTNS( "GetInveseTrajectory BEGIN" );
	//SourceActor.DMTNS( "  TargetDistance:  " $ VSize( TargetLocation - StartLocation ) );
	//SourceActor.DMTNS( "  ProjectileSpeed: " $ ProjectileSpeed );
	//SourceActor.DMTNS( "  Gravity:         " $ G );
	//SourceActor.DMTNS( "  MaxRange (flat): " $ GetMaxRange( SourceActor, ProjectileClass, ProjectileSpeed ) );
	
	XSquared = X*X;		
	VSquared = V*V;
	
	Root = XSquared - (G*G*XSquared*XSquared/(VSquared*VSquared)) + (2*G*XSquared*Y/VSquared);
	
	//SourceActor.DMTNS( "  V:    " $ V );
	//SourceActor.DMTNS( "  G:    " $ G );
	//SourceActor.DMTNS( "  X:    " $ X );
	//SourceActor.DMTNS( "  Y:    " $ Y );
	//SourceActor.DMTNS( "  Root: " $ Root );
	
	if( Root < 0 )
	{
		NumSolutions = 0;
	}
	else
	{
		GXSquared = G*XSquared;
			
		if( Root ~= 0 )
		{
			ThetaLow = ATan( -X / G*XSquared );
			ThetaHigh = ThetaLow;

			InterceptTimeLow = X / (V * Cos( ThetaLow ));
			InterceptTimeHigh = InterceptTimeLow;
			
			NumSolutions = 1;
		}
		else
		{
			SquareRoot = Sqrt( Root );
			
			ThetaLow = ATan( VSquared*(-X + SquareRoot) / GXSquared );
			ThetaHigh = ATan( VSquared*(-X - SquareRoot) / GXSquared );
			
			if( Abs( ThetaHigh ) < Abs( ThetaLow ) )
			{
				//SourceActor.DMT( "  swapping ThetaLo and ThetaHi" );
				TempFloat = ThetaHigh;
				ThetaHigh = ThetaLow;
				ThetaLow = TempFloat;
			}
			
			InterceptTimeLow = X / (V * Cos( ThetaLow ));
			InterceptTimeHigh = X / (V * Cos( ThetaHigh ));
			
			NumSolutions = 2;
		}
	}
	
	//SourceActor.DMTNS( "  ThetaLow:  " $ ThetaLow $  " Time: " $ InterceptTimeLow );
	//SourceActor.DMTNS( "  ThetaHigh: " $ ThetaHigh $ " Time: " $ InterceptTimeHigh );
	//SourceActor.DMTNS( "GetInveseTrajectory END  NumSolutions: " $ NumSolutions );
	
	return NumSolutions;
}

/*-----------------------------------------------------------------------------
Return false if any of several lines along trajectory are blocked by anything
apart from the target actor. Also return false if the projectile won't arive 
before it expires (non-zero LifeSpan).

The location of the projectile at time T is given by:

	X = X0 + Vx * t
	Y = Y0 + Vy * t + 1/2 * gt^2

or, if we shift the projectile start to the origin:

	X = Vx * t
	Y = Vy * t + 1/2 * gt^2	
	
where

X0 = starting X position
Y0 = starting Y position
Vx = horizontal component of initial velocity
Vy = vertical component of initial velocity
G  = gravity

and
	
	Vx = V * cos( Theta )
	Vy = V * sin( Theta )
*/

static final function bool VerifyTrajectory( 
	Actor SourceActor, 
	class<Actor> ProjectileClass, 
	float ProjectileSpeed, 
	vector StartLocation, 
	vector TargetLocation, 
	Actor TargetActor, 
	float Theta, 
	optional float InterceptTime, 
	optional vector Extents, 
	optional float MinTimeOutDistance )
{
	local float G;
	local float X, Y;
	local float VX, VY;
	local float SampleTime, TimeIncrement;
	local int ii;
	local vector SampleLocation, PreviousLocation, ProjectileDirection;
	local Actor HitActor;
	local vector HitNormal, HitLocation;
	local bool bValid;
	
	//SourceActor.DMTNS( "VerifyTrajectory BEGIN" );
	//SourceActor.DMTNS( "  Theta: " $ Theta );
	
	//AddCylinder( StartLocation, 4, 4, ColorWhite() );
	//AddCylinder( TargetLocation, 4, 4, ColorWhite() );

	bValid = true;

	if( InterceptTime <= 0.0 )
	{
		if( ProjectileSpeed ~= 0.0 )
		{
			bValid = false;
		}
		else
		{
			// caller wants us to determine the intercept time
			InterceptTime = VSize2D( TargetLocation - StartLocation) / (ProjectileSpeed * cos( Theta ) );
			//SourceActor.DMTNS( "  InterceptTime: " $ InterceptTime );
		}
	}
	
	VX = ProjectileSpeed * cos( Theta );
	VY = ProjectileSpeed * sin( Theta );

	G = GetGravityConstant( SourceActor, ProjectileClass );

	ProjectileDirection = TargetLocation - StartLocation;
	ProjectileDirection.Z = 0;
	ProjectileDirection = Normal( ProjectileDirection );

	// return false if the projectile be within X units of the target before it expires
	if( ProjectileClass != None && ProjectileClass.default.LifeSpan > 0.0 && InterceptTime > ProjectileClass.default.LifeSpan )
	{
		//SourceActor.DMTNS( "  Projectile LifeSpan too short checking timeout distance  InterceptTime: " $ InterceptTime );
		
		SampleTime = ProjectileClass.default.LifeSpan;
		
		X = VX * SampleTime;
		Y = VY * SampleTime + 0.5 * G * SampleTime*SampleTime;

		SampleLocation = StartLocation + X * ProjectileDirection;
		SampleLocation.Z = SampleLocation.Z - Y;
		if( VSize( SampleLocation - TargetLocation ) > MinTimeOutDistance )
			bValid = false;
	}

	if( bValid )
	{
		SampleTime = 0.0;
		TimeIncrement = InterceptTime / default.VerifyTrajectorySamples;

		//AddCylinder( StartLocation, 4, 4, ColorYellow() );
		
		//SourceActor.DMTNS( "  TargetActor: " $ TargetActor $ " Gravity: " $ G $ " target distance: " $ VSize( TargetLocation - StartLocation ) $ " TargetHeight: " $ TargetLocation.Z );
		
		PreviousLocation = StartLocation;
		PreviousLocation.Z += default.VerifyTrajectoryVerticalExtentPadding; // so first trace doesn't hit level below source
		
		// needed since the predicted trajectory isn't exactly what we'll get (should be dead-on in X/Y though)
		Extents.X += default.VerifyTrajectoryHorizontalExtentPadding;
		Extents.Y += default.VerifyTrajectoryHorizontalExtentPadding;
		Extents.Z += default.VerifyTrajectoryVerticalExtentPadding;
		
		for( ii=0; ii<default.VerifyTrajectorySamples; ii++ )
		{
			//!!hack: if "projectile" is a pawn, back up the last sample somewhat
			//if( ii == (default.VerifyTrajectorySamples-1) && ClassIsChildOf( ProjectileClass, class'Pawn' ) )
			//	TimeIncrement *= 0.5;

			SampleTime += TimeIncrement;
			
			X = VX * SampleTime;
			Y = VY * SampleTime + 0.5 * G * SampleTime*SampleTime;

			SampleLocation = StartLocation + X * ProjectileDirection;
			SampleLocation.Z = SampleLocation.Z - Y;

			// for the last sample, shift the location up by vertical padding or else 
			// we'll pbly trace into the world geometry below the target locationa
			if( ii == (default.VerifyTrajectorySamples-1) )
			{
				//SourceActor.DMTNS( "  Shifting SampleLocation up by " $ default.VerifyTrajectoryVerticalExtentPadding );
				SampleLocation.Z += default.VerifyTrajectoryVerticalExtentPadding;
			}
			//SourceActor.DMTNS( "  X: " $ X $ " Y: " $ Y $ " Height: " $ SampleLocation.Z );
			
			//!!mdf-tbd: should we worry about (dynamic) actors when tracing?
			// yes, so we'll hit XMP items?
			HitActor = SourceActor.Trace( HitLocation, HitNormal, SampleLocation, PreviousLocation, false, Extents, , TRACE_AllBlocking );
			//HitActor = SourceActor.Trace( HitLocation, HitNormal, SampleLocation, PreviousLocation, false, Extents, , TRACE_World );
			
			if( HitActor == None )
			{
				//!!mdf-tbd: static meshes don't generally block extent traces so try a no-extent trace
				//this might catch some cases but without proper extent collision it won't be perfect
				//this check can be removed if we assume that levels with the GL used by NPCs or
				//leaping NPCs will have extent collision added as needed.
				//!!mdf-tbd: possible optimization, especially in areas with low ceilings
				// check the entire trajectory with single line traces first
				HitActor = SourceActor.Trace( HitLocation, HitNormal, SampleLocation, PreviousLocation, false, vect(0,0,0), , TRACE_World );
				
				//if( HitActor != None && HitActor != TargetActor )
				//	SourceActor.DMTNS( "  no-extent trace hit " $ HitActor );
			}
			
			if( HitActor != None && HitActor != TargetActor && Theta ~= -Radians45 )
			{
				//SourceActor.DMTNS( "  checking for max range hit" );
				//SourceActor.DMTNS( "    SampleLocation.Z: " $ SampleLocation.Z );
				//SourceActor.DMTNS( "    TargetLocation.Z: " $ TargetLocation.Z );
				// hack for using maximum range -- allow a hit below or past target location
				if( SampleLocation.Z < TargetLocation.Z )
					HitActor = TargetActor;
			}
		
			//!!tbd: call OKToHit on HitActor instead of just checking if we hit TargetActor?
			if( HitActor != None && HitActor != TargetActor )
			{
				//SourceActor.DMTNS( "  failed - hit: " $ HitActor $ " instead of " $ TargetActor );
				//AddArrow( PreviousLocation, SampleLocation, ColorRed() );
				//AddCylinder( SampleLocation, Extents.X, Extents.Z, ColorRed() );
				bValid = false;
				break;
			}
			else
			{
				//AddArrow( PreviousLocation, SampleLocation, ColorYellow() );
			}
			
			if( HitActor == TargetActor )
				break;
						
			PreviousLocation = SampleLocation;
		}
	}
	
	//SourceActor.DMTNS( "VerifyTrajectory END: " $ bValid );
	
	return bValid;
}

/*-----------------------------------------------------------------------------
Wrapper for GetInverseTrajectory / VerifyTrajectory. Calculates solution for
specified trajectory (low and/or high) then verifies that the trajector is 
valid.
*/

static final function bool GetVerifiedInverseTrajectory( 
	Actor SourceActor, 
	class<Actor> ProjectileClass, 
	float ProjectileSpeed, 
	vector StartLocation, 
	vector TargetLocation, 
	Actor TargetActor, 
	ETrajectoryType TrajectoryType, 
	out float Theta, 
	out float InterceptTime, 
	optional vector Extents, 
	optional float MinTimeOutDistance )
{
	local int NumSolutions;
	local float ThetaLow, ThetaHigh, InterceptTimeLow, InterceptTimeHigh;
	local bool bTriedHi;
	local bool bSuccess;
		
	//SourceActor.DMTNS( "GetVerifiedInverseTrajectory BEGIN" );
	NumSolutions = GetInverseTrajectory( SourceActor, ProjectileClass, ProjectileSpeed, StartLocation, TargetLocation, ThetaLow, ThetaHigh, InterceptTimeLow, InterceptTimeHigh );

	//SourceActor.DMTNS( "  NumSolutions: " $ NumSolutions );
	if( NumSolutions == 1 )
	{
		// only one trajectory (45 degrees)
		//SourceActor.DMTNS( "  checking only solution (45 degrees)" );
		if( VerifyTrajectory( SourceActor, ProjectileClass, ProjectileSpeed, StartLocation, TargetLocation, TargetActor, ThetaLow, InterceptTimeLow, Extents, MinTimeOutDistance ) )
		{
			Theta = ThetaLow;
			InterceptTime = InterceptTimeLow;
			bSuccess = true;
		}
	}
	else if( NumSolutions == 2 )
	{
		// 2 possible trajectories
		if( TrajectoryType == TRAJ_High || TrajectoryType == TRAJ_PreferHigh )
		{
			// try high first
			//SourceActor.DMTNS( "  checking high solution" );
			Theta = ThetaHigh;
			InterceptTime = InterceptTimeHigh;
			bTriedHi = true;
		}
		else
		{
			// try low first
			//SourceActor.DMTNS( "  checking low solution" );
			Theta = ThetaLow;
			InterceptTime = InterceptTimeLow;
			bSuccess = true;
		}

		bSuccess = VerifyTrajectory( SourceActor, ProjectileClass, ProjectileSpeed, StartLocation, TargetLocation, TargetActor, Theta, InterceptTime, Extents, MinTimeOutDistance );
		
		if( !bSuccess && TrajectoryType != TRAJ_High && TrajectoryType != TRAJ_Low )
		{
			if( bTriedHi )
			{
				// now check low
				//SourceActor.DMTNS( "  checking low solution" );
				Theta = ThetaLow;
				InterceptTime = InterceptTimeLow;
			}
			else
			{
				// now check high
				//SourceActor.DMTNS( "  checking high solution" );
				Theta = ThetaHigh;
				InterceptTime = InterceptTimeHigh;
			}
			
			bSuccess = VerifyTrajectory( SourceActor, ProjectileClass, ProjectileSpeed, StartLocation, TargetLocation, TargetActor, Theta, InterceptTime, Extents, MinTimeOutDistance );
		}
	}
	
	//SourceActor.DMTNS( "GetVerifiedInverseTrajectory END  bSuccess: " $ bSuccess );
	return bSuccess;		
}
		
//-----------------------------------------------------------------------------

static final function ELeapResult VerifyLeapParameters( 
	Actor SourceActor, 
	class<Actor> ProjectileClass, 
	float ProjectileSpeed, 
	vector TargetLocation, 
	vector StartLocation, 
	Actor TargetActor, 
	ETrajectoryType TrajectoryType, 
	out float Theta, 
	optional vector Extents )
{
	local float InterceptTime;
	local ELeapResult Result;

	// don't bother with trajectory calculation if predicted location isn't within range 
	if( VSize( TargetLocation - SourceActor.Location ) > GetMaxRange( SourceActor, ProjectileClass, ProjectileSpeed ) )
	{
		Result = LR_OutOfRange;
	}
	else if( !GetVerifiedInverseTrajectory( 
		SourceActor, 
		ProjectileClass, 
		ProjectileSpeed, 
		SourceActor.Location, 
		TargetLocation, 
		TargetActor, 
		TrajectoryType, 
		Theta, 
		InterceptTime, 
		Extents ) )
	{
		Result = LR_None;
	}
	else if( Normal( TargetLocation - SourceActor.Location ) dot vector( SourceActor.Rotation ) < 0.707 )
	{
		Result = LR_OutOfAngle;
	}
	else
	{
		Result = LR_Success;
	}
	
	//SourceActor.DMTNS( "  VerifyLeapParameters returning " $ EnumStr( enum'ELeapResult', Result ) );
	return Result;
}
	
//=============================================================================
//@ Aiming
//=============================================================================

static final function vector GetRotatedFireStart( Pawn SourcePawn, vector SourceLocation, rotator TargetRotation, vector FireOffset )
{
	local vector X, Y, Z;
	local vector ReturnedFireStart;
	
	GetAxes( TargetRotation, X, Y, Z );
	
	ReturnedFireStart = SourceLocation + SourcePawn.EyePosition() + FireOffset.X * X + FireOffset.Y * Y + FireOffset.Z * Z;
	
	// prone NPCs are getting a fire start that is in the ground?
	ReturnedFireStart.Z = FMax( SourceLocation.Z - 0.5*SourcePawn.CollisionHeight, ReturnedFireStart.Z );
	
	//SourcePawn.DMTNS( "GetRotatedFireStart returning " $ ReturnedFireStart );
	//SourcePawn.DMTNS( "  TargetRotation: " $ TargetRotation );
	//SourcePawn.DMTNS( "  EyePosition:    " $ TargetPawn.EyePosition() );
	return ReturnedFireStart;
}

//-----------------------------------------------------------------------------

static final function bool TryToHit( 
	Actor AimingActor,
	Actor TargetActor, 
	float TargetDistance,
	float SpreadDegrees,						// weapon firing spread -- increases trytohit odds with increasing distance
	float LastHitTime,
	float MaxAffectedByHitTime,
	float LastAcquisitionTime,
	float MaxAffectedByAcquisitionTime,
	float TryToHitBaseOddsMin, 
	float TryToHitBaseOddsMax, 
	float TryToHitBaseDistance, 
	float TryToHitMinMissDistance, 
	float TryToHitMaxHitDistance,
	optional float TryToHitBaseSpeed,
	optional float TryToHitBaseSpeedOdds )
{
	local float TryToHitOdds;
	local float SizeRelativeVelocity;
	local float TimeSinceLastHit;
	local float TimeSinceLastAcquired;
	
	TryToHitOdds = TryToHitBaseOddsMin + (TryToHitBaseOddsMax - TryToHitBaseOddsMin) * AimingActor.GetSkill();

	#debugbegin
	//AimingActor.DMT( "TryToHit (" $ AimingActor.GetStateName() $ ")" );
	//AimingActor.DMT( "  Initial Odds:         " $ TryToHitOdds );
	//AimingActor.DMT( "  Relative Velocity:    " $ VSize( TargetActor.Velocity - AimingActor.Velocity ) );
	//AimingActor.DMT( "  TimeSinceLastHit:     " $ AimingActor.Level.TimeSeconds - LastHitTime );
	//AimingActor.DMT( "  TimeSinceLastAcquired: " $ AimingActor.Level.TimeSeconds - LastAcquisitionTime );
	#debugend
	
	// modify base odds depending on distance
	if( TargetDistance > TryToHitMaxHitDistance )
		TryToHitOdds = 0.0;
	else if( TargetDistance < TryToHitMinMissDistance )
		TryToHitOdds = 1.0;
	else if( TargetDistance < TryToHitBaseDistance )
		TryToHitOdds += (1.0 - TryToHitOdds) * ((TryToHitBaseDistance - TargetDistance) / (TryToHitBaseDistance - TryToHitMinMissDistance));
	else if( TargetDistance > TryToHitBaseDistance )
		TryToHitOdds += -TryToHitOdds * ((TargetDistance - TryToHitBaseDistance) / (TryToHitMaxHitDistance - TryToHitBaseDistance));

	//#debug AimingActor.DMT( "  TryToHitOdds (distance): " $ TryToHitOdds );
	
	if( SpreadDegrees > 0.0 && TargetDistance > default.MinModifyForSpreadDistance )
	{
		//#debug AimingActor.DMT( "  SpreadDegrees:" $ SpreadDegrees );
		// if weapon has a spread (e.g. the AR primary) increase odds of trying to hit
		// with distance wrt spread at targetdistance vs target radius (i.e. small
		// target at great distance will be missed most of the time even if aiming
		// right at the target).
		TryToHitOdds = TryToHitOdds * TargetDistance * sin( 0.5*DegreesToRadians*SpreadDegrees ) / TargetActor.CollisionRadius;
	}
	
	//#debug AimingActor.DMT( "  TryToHitOdds (spread): " $ TryToHitOdds );
	
	//!!mdf-tbd used to control this with bUsePhysics param but uc doesn't allow > 16 
	// params so just do this if AimingActor is a Pawn for now.
	if( Pawn(AimingActor) != None )
	{
		// aiming actor should have aim affected by target's physics
		if( TryToHitOdds > 0.0 && TryToHitBaseSpeed > 0.0 && TryToHitBaseSpeedOdds > 0.0 )
		{
			// decrease odds of hit with increasing relative velocity
			SizeRelativeVelocity = VSize( TargetActor.Velocity - AimingActor.Velocity );
			
			if( SizeRelativeVelocity <= TryToHitBaseSpeed )
				TryToHitOdds *= 1.0 - (1.0-TryToHitBaseSpeedOdds)*(SizeRelativeVelocity / TryToHitBaseSpeed);
			else
				TryToHitOdds *= TryToHitBaseSpeedOdds*(TryToHitBaseSpeed / SizeRelativeVelocity);
				
			//#debug AimingActor.DMT( "  TryToHitOdds (velocity): " $ TryToHitOdds );
		}

		if( TryToHitOdds > 0.0 )
		{
			TimeSinceLastHit = AimingActor.Level.TimeSeconds - LastHitTime;
			if( TimeSinceLastHit < MaxAffectedByHitTime )
			{
				// decrease odds of hit due to being hit recently
				TryToHitOdds *= TimeSinceLastHit / MaxAffectedByHitTime;
				//#debug AimingActor.DMT( "  TryToHitOdds (hit): " $ TryToHitOdds );
			}
			
			TimeSinceLastAcquired = AimingActor.Level.TimeSeconds - LastAcquisitionTime;
			if( TimeSinceLastAcquired < MaxAffectedByAcquisitionTime )
			{
				// decrease odds of hit due to target being acquired recently
				TryToHitOdds *= TimeSinceLastAcquired / MaxAffectedByAcquisitionTime;
				//#debug AimingActor.DMT( "  TryToHitOdds (acquisition): " $ TryToHitOdds );
			}

			if( AimingActor.Physics == PHYS_Falling )
			{
				// decrease odds of hit due to NPC falling (note: relative velocity considered above instead of here)
				TryToHitOdds *= 0.5;
				//#debug AimingActor.DMT( "  TryToHitOdds (NPC falling): " $ TryToHitOdds );
			}
		
			if( TargetActor.Physics == PHYS_Falling )
			{
				// decrease odds of hit due to target falling (note: relative velocity considered above instead of here)
				TryToHitOdds *= 0.5;
				//#debug AimingActor.DMT( "  TryToHitOdds (target falling): " $ TryToHitOdds );
			}
		}
	}

	//!!mdf-tbd: maybe increase odds of hitting stationary non-Pawn targets?	
	//#debug AimingActor.DMT( "TryToHit  Final Odds: " $ TryToHitOdds );
	
	TryToHitOdds = FClamp( TryToHitOdds, 0.0, 1.0 );

	return ( FRand() <= TryToHitOdds );
}

/*-----------------------------------------------------------------------------
Determine a good vector along which to intentionally miss the given target
actor based on the direction that the actor is facing. If the actor is an NPC
or if the actor (player) is generally facing the NPC, the NPC shouldn't favor 
missing in either direction (ReverseOdds ~0.50), otherwise, the NPC should try 
to miss along the given vector (ReverseOdds < 0.50) so that the player sees the
shots pass in front of him for greater effect.
*/

static final function vector GetMissVector( 
	Actor AimingActor,
	Actor TargetActor, 
	float LastHitTime,
	float MaxAffectedByHitTime,
	float MaxHitMissMultiplier,
	float MinHitPitchError,
	float MaxHitPitchError,	
	float LastAcquisitionTime,
	float MaxAffectedByAcquisitionTime,
	float MaxAcquireMissMultiplier,
	float MinAcquirePitchError,
	float MaxAcquirePitchError,
	bool bTargetObscured,					// true ==> don't have LOS to target (e.g. smoke in way)
	out int PitchError )
{
	local vector TargetVector;
	local vector TargetFacingVector;
	local vector MissVector;
	local float CosFacingAngle;
	local float ReverseOdds;
	local float TimeSinceLastHit;
	local float TimeSinceLastAcquired;
	local float PitchAdjustMultiplier;
	local int AddedPitchError;
	
	TargetVector = Normal( AimingActor.Location - TargetActor.Location );
	TargetFacingVector = vector(TargetActor.Rotation);
	CosFacingAngle = TargetVector dot TargetFacingVector;
	//DMTNS( "angle: " $ RadiansToDegrees * ACos( CosFacingAngle ) $ "(" $ CosFacingAngle $ ")" );
	
	if( TargetActor.IsRealPlayer() && Abs( CosFacingAngle ) < 0.866 )
	{
		//DMTNS( "target not facing NPC" );
//		ReverseOdds = 0.25; // player generally facing across firing direction -- favor shots in front 
		ReverseOdds = 0.0; // player generally facing across firing direction -- favor shots in front 
	}
	else
	{
		//DMTNS( "target facing NPC" );
		ReverseOdds = 0.50; // player generally facing along firing direction -- don't favor shots in front 
	}

	//DMTNS( "ReverseOdds: " $ ReverseOdds );
	
	MissVector = Normal( TargetVector cross vect(0,0,1) ); // vector across firing direction
	
	if( (MissVector dot TargetFacingVector) < 0 )
		MissVector = -MissVector;
			
	if( FDecision( ReverseOdds ) )
		MissVector = -MissVector;

	// when missing, miss by more than usual if recently hit?
	TimeSinceLastHit = AimingActor.Level.TimeSeconds - LastHitTime;
	if( TimeSinceLastHit < MaxAffectedByHitTime )
	{
		MissVector *= MaxHitMissMultiplier*(MaxAffectedByHitTime - TimeSinceLastHit);
		AddedPitchError = (MaxHitPitchError - FRand()*(MaxHitPitchError - MinHitPitchError))*(MaxAffectedByHitTime - TimeSinceLastHit);
		PitchError += AddedPitchError;

		//AimingActor.DMTNS( "increased PitchError by " $ AddedPitchError $ " due to taking hit " $ TimeSinceLastHit $ " secs ago" );
	}
	
	// when missing, miss by more than usual if recently acquired?
	TimeSinceLastAcquired = AimingActor.Level.TimeSeconds - LastAcquisitionTime;
	if( TimeSinceLastAcquired < MaxAffectedByAcquisitionTime )
	{
		MissVector *= MaxAcquireMissMultiplier*(MaxAffectedByAcquisitionTime - TimeSinceLastAcquired);
		AddedPitchError = (MaxAcquirePitchError - FRand()*(MaxAcquirePitchError - MinAcquirePitchError))*(MaxAffectedByAcquisitionTime - TimeSinceLastAcquired);
		PitchError += AddedPitchError;
		
		//AimingActor.DMTNS( "increased PitchError by " $ AddedPitchError $ " due to acquired " $ TimeSinceLastAcquired $ " secs ago" );
	}
	
	if( bTargetObscured )
	{
		MissVector *= default.MinTargetBlockedMissMultiplier + default.MaxTargetBlockedMissMultiplier * FRand();
		AddedPitchError = default.MinTargetBlockedPitchError - FRand()*(default.MaxTargetBlockedPitchError - default.MinTargetBlockedPitchError);
		PitchError += AddedPitchError;
		
		//AimingActor.DMTNS( "increased PitchError by " $ AddedPitchError $ " due to target being obscured" );
	}
	
	// scale pitch error depending on how much target is facing aiming actor
	// so shots generally tend to pass in front of the target (more exciting)
	if( TargetActor.IsRealPlayer() )
	{
		// scale by 1.0 (target facing aiming actor) to 0.1 (target facing completely across firing direction or away from aiming actor)
		PitchAdjustMultiplier = FMax( 0.1, 0.9 * CosFacingAngle + 0.1 );
		PitchError *= PitchAdjustMultiplier;
	}
	
	PitchError = FClamp( PitchError, default.MinPitchError, default.MaxPitchError );
	
	//AddArrow( TargetActor.Location, TargetActor.Location + 64.0*MissVector, ColorCyan() );
	
	return MissVector;
}
			
//-----------------------------------------------------------------------------
// Returns false for cases where there is no solution, otherwise sets 
// AimingDestination to the location to move to/fire at to reach the target.
// NOTE: predicts where AimingActor and TargetActor might meet but doesn't
// check to see whether those locations are actually reachable.

static final function bool GetAimingDestination( 
	Actor AimingActor, 
	float AimingSpeed, 
	float DelayTime,					// optional additional delay before aiming actor will start moving
	Actor TargetActor,
	out vector AimingDestination )
{
	local vector TargetLocation;
	local vector InitialAimingVector;								// vector from target to actor
	local vector TargetVelocity;
	local float TargetSpeed, TargetSpeedSquared;					// speeds convenience vars
	local float InitialAimingDistance, cosY;						// intermediate calcs
	local float a, b, c;											// quadratic vars
	local float InterceptDistance1, InterceptDistance2;				// 2 possible solutions				
	local float BestInterceptDistance;
	local float InterceptTime;										// time 
	#debugbegin	
	// for testing the result
	local vector PredictedTargetActorLocation; 
	local vector PredictedAimingActorLocation;
	local float PredictedDistanceDelta;
	#debugend	
	local bool bResult;

	//AimingActor.DMTNS( "GetAimingDestination Actor: " $ AimingActor $ " Speed: " $ AimingSpeed $ " Target: " $ TargetActor $ " Target Speed: " $ VSize( TargetActor.Velocity ) );	
	if( AimingSpeed <= 0.0 )
		warn( "GetAimingDestination: AimingSpeed is <= 0.0!" );
		
	TargetSpeed = VSize( TargetActor.Velocity );
	if( TargetSpeed ~= 0.0 )
	{
		// special case: target isn't moving
		AimingDestination = TargetActor.Location;
		bResult = true;
	}
	//else if( TargetActor.Physics == PHYS_Falling && TargetActor.Velocity.Z > 0 )
	else if( TargetActor.Physics == PHYS_Falling && TargetActor.Velocity.Z > 0 )
	{
		// special case: target is "falling up"
		
		// hack "solution": predict where NPC will land and assume projectile
		// speed will always be high enough to intercept that location? 
		AimingDestination = TargetActor.FallLanding( TargetActor.Location, TargetActor.Velocity );
		bResult = true;
	}
	else 
	{
		/*!!mdf-tbd: current behavior good enough?
		if( TargetActor.Physics == PHYS_Falling )
		{
			// special case: target is falling (down)
			
			// predict where NPC will land, then use that location + 2D part of
			// current velocity to predict where target will end up? 
		}
		*/
		
		// Label a triangle XYZ with AimingActor's location, TargetActor's initial location, the Intercept location, respectively
		// Let the sides be defined as:
		//		x = TargetActor initial location <---> Intercept location
		//		y = AimingActor initial location <---> Intercept location
		//		z = AimingActor initial location <---> TargetActor initial location (=InitialAimingDistance)
		//
		// Algorithm:
		//	1. InitialAimingVector = AimingActorLocation - AimingTargetLocation   z = | InitialAimingVector |
		// 	2. cosY = Vm dot (z) / ( |Vm| |La-Lm|)
		//	3. The Cosine Law will give us a function of x and y (in terms of z and cosY)
		//		y^2 = x^2 + z^2 - 2*x*z*cos( Y )
		//	4. At the time of intercept:  y / AimingTargetSpeed = x / AimingSpeed
		//	5. Solve 4. for y and substitute back into 3:
		//	6. Simplify the quadratic into the form:  ax^2 + bx + c = 0
		//	7. Apply quadratic rule: x = -b +/- sqrt( b^2 - 4ac ) / 2a
		//	8. Intercept location is x units along the TargetActor's velocity vector
		//	9. Intercept direction = Intercept location - AimingActor location

		// shift target location back/forward in time depending on delay
		TargetLocation = TargetActor.Location + DelayTime * TargetActor.Velocity;

		#debugbegin
		if( DelayTime != 0.0 )
		{
			//AimingActor.DMTNS( "shifting target location to allow for a delay of " $ DelayTime $ " secs");
			//AddArrow( TargetActor.Location, TargetLocation, ColorOrange() );
		}
		#debugend
		
		TargetSpeedSquared = TargetSpeed * TargetSpeed;

		// vector and magnitude of initial location difference
		InitialAimingVector = AimingActor.Location - TargetLocation;
		InitialAimingDistance = VSize( InitialAimingVector );

		cosY = Normal( TargetActor.Velocity ) dot Normal( InitialAimingVector );

		a = AimingSpeed * AimingSpeed - TargetSpeedSquared;
		b = 2 * InitialAimingDistance * TargetSpeedSquared * cosY; 
		c = -TargetSpeedSquared * InitialAimingDistance * InitialAimingDistance;

		if( class'Util'.static.GetQuadraticSolutions( a, b, c, InterceptDistance1, InterceptDistance2 ) > 0 )
		{
			// choose smallest positive solution (so NPC doesn't back up to intercept location)
			if( InterceptDistance1 < 0 )
				BestInterceptDistance = InterceptDistance2;
			else if( InterceptDistance2 < 0 )
				BestInterceptDistance = InterceptDistance1;
			else
				BestInterceptDistance = FMin( InterceptDistance1, InterceptDistance2 );

			InterceptTime = BestInterceptDistance / TargetSpeed;
			
			#debugbegin
			//AimingActor.DMTNS( "  InterceptTime: " $ InterceptTime );
			#debugend
			if( InterceptTime >= 0 )
			{
				AimingDestination = TargetLocation + InterceptTime * TargetActor.Velocity;

				#debugbegin
				// enable this code to verify result
				PredictedTargetActorLocation = TargetLocation + InterceptTime * TargetActor.Velocity;
				PredictedAimingActorLocation = AimingActor.Location + InterceptTime * Normal(AimingDestination - AimingActor.Location) * AimingSpeed;
				PredictedDistanceDelta = VSize( PredictedTargetActorLocation - PredictedAimingActorLocation );
				
				//if( PredictedDistanceDelta > 1.0 )
				//	AimingActor.DMTNS( "WARNING: GetAimingDestination: Predicted intercept is off by:" @ PredictedDistanceDelta @ "units" );
				#debugend
					
				bResult = true;
			}
		}
	}

#debugbegin
	// afaict, as long as the aiming speed is > the speed of the target, there should always be a solution
	AimingActor.DMAssert( bResult || AimingSpeed <= TargetSpeed, GetContext() );
#debugend	
	//AddArrow( AimingActor.Location, AimingDestination );
	//AddCylinder( AimingDestination, 4, 4 );
	
	return bResult;
}

//-----------------------------------------------------------------------------

static final function GetBestPredictedLocation( 
	Actor AimingActor, 
	Actor TargetActor, 
	float ClosingSpeed, 
	float DelayTime,
	out vector PredictedLocation )
{
	local bool bResult;
	local Actor HitActor;
	local vector HitLocation, HitNormal;
	
	// predict where Enemy is headed
	bResult = GetAimingDestination( AimingActor, ClosingSpeed, DelayTime, TargetActor, PredictedLocation );

	// tbd: need to do an extent trace and/or full reachability check?
	// reachability could be optional, e.g. dumb creatures might blindly attack enemy?
	// mdf-tbd: pointreachable should be in Actor?
	//if( !PointReachable( PredictedLocation ) || !TargetActor.PointReachable( PredictedLocation ) )
	//	PredictedLocation = TargetActor.Location;
	if( !bResult )
	{
		//AimingActor.DMTNS( "GetBestPredictedLocation no solution -- looking at where TargetActor will be blocked" );
		//PredictedLocation = TargetActor.Location;
		HitActor = class'Util'.static.TraceRecursive( AimingActor, HitLocation, HitNormal, TargetActor.Location, false, , TargetActor.Velocity, , , TRACE_World );
		if( HitActor != None )
		{
			//AddArrow( TargetActor.Location, HitLocation, ColorMagenta() );
			//AimingActor.DMTNS( "  GetBestPredictedLocation using blocked location" );
			PredictedLocation = HitLocation + AimingActor.CollisionRadius * HitNormal; // pull back enough for aiming actor to fit at target location
		}
		else
		{
			//AimingActor.DMTNS( "  GetBestPredictedLocation no solution using TargetActor location" );
			PredictedLocation = TargetActor.Location;
		}
	}
	else 
	{
		//AimingActor.DMTNS( "  GetBestPredictedLocation -- predicted location found" );
		
		// if target is blocked from PredictedLocation by geometry then back up the PredictedLocation
		HitActor = class'Util'.static.TraceRecursive( AimingActor, HitLocation, HitNormal, TargetActor.Location, false, , PredictedLocation - TargetActor.Location, VSize( PredictedLocation - TargetActor.Location ), , TRACE_World );

		if( HitActor != None )
		{		
			//AddArrow( HitLocation, HitLocation + 128.0 * HitNormal );
			//AimingActor.DMTNS( "GetBestPredictedLocation target will be blocked by geometry - adjusting predicted location" );
			PredictedLocation = HitLocation	+ AimingActor.CollisionRadius * HitNormal; // pull back enough for aiming actor to fit at target location 
			//AddCylinder( PredictedLocation, 4, 4, ColorMagenta() );
		}
		
		// if AimingActor. can't get to PredictedLocation, go right at target instead
		if( !AimingActor.FastTrace( AimingActor.Location, PredictedLocation ) )
		{
			//AimingActor.DMTNS( "GetBestPredictedLocation no trace - using TargetActor" );
			PredictedLocation = TargetActor.Location;
		}
	}
	
	//AddArrow( AimingActor.Location, PredictedLocation, ColorGreen() );
	//AddCylinder( PredictedLocation, 4, 4, ColorGreen() );
}

/*-----------------------------------------------------------------------------
Iterative approach to determining predicted location when using projectile
physics with a moving target. If the location can be predicted it is returned
in PredictedLocation, otherwise the given location is returned unmodified.

!!mdf-tbd: location prediction code should take geometry into account and try
to place the moving actor on the floor if walking (same thing with other
movement prediction code afaik).

!!mdf-tbd: this seems to work really well - is it worth trying to come up with 
a non-iterative equation?
*/

static final function GetBestPredictedProjectileLocation( 
	Actor AimingActor, 
	Actor TargetActor, 
	class<Actor> ProjectileClass, 
	float ProjectileSpeed, 
	float DelayTime,
	vector StartLocation,
	float TargetDistance,
	bool bUseHighTrajectory,
	out vector TargetLocation )
{
	local int NumSolutions;
	local float ThetaLow, ThetaHigh;
	local float InterceptTime, InterceptTimeLow, InterceptTimeHigh;
	local vector CurrentTargetLocation, CurrentPredictedLocation;
	local float DistanceDelta;
	local vector SavedLocation, PredictedMoveVector;
	local int Attempt;	
	
	// note: assumes we are heading towards target actor (e.g. as opposed to a last seen position)
	CurrentTargetLocation = TargetActor.Location;

	for( Attempt=0; Attempt<default.MaxPredictProjectileAttempts; Attempt++ )
	{
		// break when we get an acceptible result or determine that there is no solution?
		NumSolutions = GetInverseTrajectory( AimingActor, ProjectileClass, ProjectileSpeed, StartLocation, CurrentTargetLocation, ThetaLow, ThetaHigh, InterceptTimeLow, InterceptTimeHigh );
		
		//AddCylinder( CurrentTargetLocation, TargetActor.CollisionRadius, TargetActor.CollisionHeight, ColorBlue() );
		if( NumSolutions == 0 )
		{
			if( ProjectileSpeed ~= 0.0 )
			{
				TargetLocation = CurrentTargetLocation;
				return;
			}

			InterceptTime = TargetDistance / (0.5*ProjectileSpeed);
		}
		else if( bUseHighTrajectory )
		{
			InterceptTime = InterceptTimeHigh;
		}
		else
		{
			InterceptTime = InterceptTimeLow;
		}
		
		// use delay + trajectory intercept times to determine where target will be then
		PredictedMoveVector = (InterceptTime + DelayTime) * TargetActor.Velocity;
		
		// see how far target will be able to move in that direction
		SavedLocation = TargetActor.Location;
		TargetActor.Move( PredictedMoveVector, true );
		if( TargetActor.Location != (SavedLocation + PredictedMoveVector ) )
		{
			// target will hit a wall or something so aim for that location
			TargetLocation = TargetActor.Location;
			TargetActor.SetLocation( SavedLocation );
			return;
		}
		CurrentPredictedLocation = TargetActor.Location;
		TargetActor.SetLocation( SavedLocation );
		
		//AddCylinder( CurrentPredictedLocation, TargetActor.CollisionRadius, TargetActor.CollisionHeight, ColorCyan() );

		// how far off are we?
		DistanceDelta = VSize( CurrentTargetLocation - CurrentPredictedLocation );

		//AimingActor.DMTNS( "delta for attempt #" $ Attempt $ " is: " $ DistanceDelta );
		if( DistanceDelta <= default.PredictProjectileThreshold )
		{
			TargetLocation = CurrentTargetLocation;		
			return;
		}
		
		// try half way?
		CurrentTargetLocation += 0.5*(CurrentPredictedLocation - CurrentTargetLocation);
	}
}

//=============================================================================
//@ Searching
//=============================================================================

static final function bool VerifyNamedActor( Actor A, bool bAllowUnSafe )
{
	if( bAllowUnSafe || A.bEditorPlaced )
		return true;

	A.DMTNS( "Warning: GetFilteredActors used to find a named non-editor placed actor (this is unreliable): " $ A $ "!" );
	return false;
}

//-----------------------------------------------------------------------------
// Search for closest actor to InstanceActor which matches given ClassName 
// (bIsA=false) or IsA(ClassName) (bIsA=true). Returns None if no such actor
// found. Matches with InstanceActor are NOT filtered out.

static final function Actor GetClosestOfClass( Actor InstanceActor, name ClassName, bool bIsA )
{
	local Actor A;
	local float MinDist;
	local float Distance;
	local Actor Closest;

	// try to match closest actor with same class (not including super classes) as given name
	Closest = None;
	MinDist = 999999;

	foreach InstanceActor.AllActors( class'Actor', A )
	{
		if( A.Class.Name == ClassName || (bIsA && A.IsA(ClassName)) )
		{
			Distance = VSize( InstanceActor.Location - A.Location );
			if( Distance < MinDist )
			{
				Closest = A;
				MinDist = Distance;
			}
		}
	}

	return Closest;
}

//-----------------------------------------------------------------------------
// NOTE: if this is called with a target name that ends in a digit, we look for
// a matching actor in the level. But, this isn't safe if the actor was spawned
// in-game since there is no guarantee that the same name will be used each 
// time. Will normally return None for these cases, use bAllowUnSafe=true to
// allow such actors to be found, e.g. for testing purposes.

static final function Actor GetNamedActor( Actor InstanceActor, name N, optional bool bTryClassMatch, optional bool bAllowUnSafe )
{
	local Actor A;

	if( InstanceActor != None )
	{
		if( !bTryClassMatch || class'Util'.static.EndsInDigit( string(N) ) )
		{
			// first try to find an actor with the given name (can be at most one)
			//!!!			
			foreach InstanceActor.AllActors( class'Actor', A )
			//foreach InstanceActor.DynamicActors( class'Actor', A )
			{
				if( A.Name == N )
				{
					if( VerifyNamedActor( A, bAllowUnSafe ) )
						return A;
					else
						return None;
				}
			}
		}

		if( bTryClassMatch )
		{
			A = GetClosestOfClass( InstanceActor, N, false );		// try exact match
			if( A == None )
				A = GetClosestOfClass( InstanceActor, N, true );	// try IsA match
	
			return A;
		}
	}

	return None;
}

//-----------------------------------------------------------------------------

static final function Actor GetNamedOrHitActor( Controller C, optional name TargetName, optional bool bTraceVisibleNonColliding, optional bool bTryClassMatch )
{
	if( TargetName != '' )
	{
		return GetNamedActor( C, TargetName, bTryClassMatch, true );
	}
	else
	{
		return class'Util'.static.GetHitActor( C, bTraceVisibleNonColliding );
	}
}

//-----------------------------------------------------------------------------

static final function bool FindActorByName( Actor SearchingActor, Name ActorName, out Actor FoundActor )
{
	local Actor CurrentActor;
	local bool bFoundActor;
	
	foreach SearchingActor.AllActors( class'Actor', CurrentActor )
	{
		if( CurrentActor.Name == ActorName )
		{
			FoundActor = CurrentActor;
			bFoundActor = true;
			break;
		}
	}

	return bFoundActor;
}

/*-----------------------------------------------------------------------------
GetFilteredActors:

For now searches:
	navigation point list if given class is NavigationPoint (or a child class)
	dynamic actors if given class isn't static by default
	allactors (potentially sloow)

If TagetName ends in digits, assumes that goal is a named object, rather than a
class (searches all colliding actors for one with matching name). Otherwise
maps TargetName to a specific class.

When using VFT_Visible/VFT_FOV uses LineOfSightTo/CanSee if OriginActor is a Pawn
otherwise uses Trace.

Returns number of matching actors found (usually 0/1 unless Type=3 in which
case can return 0..MaxFilteredActorss).

!!mdf-tbd: collapse as many of the actor iterator classes as possible once 
generic lists support integrated.
*/

static final function int GetFilteredActors( 
	Actor OriginActor,									// actor to search from
	string TargetNameStr, 								// name of class or object to search for
	out Actor MatchingActors[ MaxFilteredActors ],		// array for returning matching actors
	float MinRadius,									// min considered distance around OriginActor
	float MaxRadius,									// max considered distance around OriginActor
	EDistanceFilterType DistanceFilterType,	 			// first/closest/furthest/all
	EVisibilityFilterType VisibilityFilterType,			// none/visible/fov
	int MaxMatches,										// when using DFT_Any, caps number of matches (to less than MaxFilteredActors )
	optional bool bAllowUnSafe,							// allow finding named non-level placed actors
	optional bool b2DDistanceCheck )					// consider 2D distance checks only
{
	local Actor A;
	local int NumMatchingActors;
	local name TargetName;
	local class<Actor> BaseClass;
	local float DistanceBetweenActors;
	local Pawn P;
	local Controller OriginController;
	local bool bPawnVisibleFilter, bPawnFOVFilter, bActorVisibleFilter;
	local float BestDistance;

	// !!mdf-tbr:
	local NavigationPoint TempN;
	local Controller TempC;
	
	if( DistanceFilterType == DFT_Closest )
		BestDistance =  999999.9;
	else
		BestDistance = -999999.9;

	if( class'Util'.static.EndsInDigit( TargetNameStr ) ) // !!mdf-tbd: this assumes no class names end in digits (bad anyway because of way engine creates object names)
	{
		BaseClass = class'Actor';
		TargetName = StringToName( TargetNameStr, true );
	}
	else
	{
		BaseClass = class<Actor>( DynamicLoadObject( TargetNameStr, class'class' ));
		TargetName = '';
	}

	if( MaxRadius <= 0.0 )
		MaxRadius = 999999.0;
	else if( MaxRadius > 999999.0 )
		MaxRadius = 999999.0;

	// prepare for any necessary visibility checks
	if( VisibilityFilterType != VFT_None )
	{
		P = Pawn(OriginActor);
		if( P != None )
		{
			OriginController = P.Controller;
			if( VisibilityFilterType == VFT_Visible )
				bPawnVisibleFilter = true;
			else
				bPawnFOVFilter = true;
		}
		else
		{
			bActorVisibleFilter = true;
		}
	}

	if( MaxMatches == 0 )
		MaxMatches = MaxFilteredActors;

	NumMatchingActors = -1;
	if( BaseClass != None && MaxRadius >= MinRadius )
	{
		NumMatchingActors = 0;

		// !!mdf-tbr: temp cut and paste job -- once MJL finishes actor lists support
		// we can go back to using a single AllActors loop. Factoring out the filter
		// and add code would be a complete waste of time (and slow) at this point..

		if( ClassIsChildOf( BaseClass, class'NavigationPoint' ) )
		{
			// use navigation point list
			for( TempN=OriginActor.Level.NavigationPointList; TempN!=None; TempN=TempN.NextNavigationPoint )
			{
				A = TempN;

				if( !ClassIsChildOf( A.Class, BaseClass ) )
					continue;
					
				if( b2DDistanceCheck )
					DistanceBetweenActors = VSize2D( A.Location - OriginActor.Location );	
				else
					DistanceBetweenActors = VSize( A.Location - OriginActor.Location );	
		
				if( DistanceBetweenActors < MinRadius )
					continue; // too close
	
				if( DistanceBetweenActors > MaxRadius )
					continue; // too far
	
				// in Min..Max
	
				if( TargetName != '' && A.Name != TargetName )
					continue; // wrong object name (if looking for a specific actor)
	
				// check any visibility constraints
	
				if( bPawnVisibleFilter && !OriginController.LineOfSightTo( A ) )
					continue; // Pawn has no LOS to A
	
				if( bPawnFOVFilter && !OriginController.CanSee( A ) )
					continue; // A not in Pawn's field of view (stronger test than LOS)
	
				if( bActorVisibleFilter && !SLCActorCanSeeActor( OriginActor, A ) )
					continue; // something is between OriginActor and A
	
				// this is a valid actor
	
				if( TargetName != '' )
				{
					// looking for a specific target actor
					if( A.Name == TargetName )
					{
						if( VerifyNamedActor( A, bAllowUnSafe ) )
							MatchingActors[ NumMatchingActors++ ] = A;
						break;
					}
				}
				else if( DistanceFilterType == DFT_First )
				{
					// done -- return first candidate
					MatchingActors[ NumMatchingActors++ ] = A;
					break;
				}
				else if( DistanceFilterType == DFT_Any )
				{
					// return first N candidates
					MatchingActors[ NumMatchingActors++ ] = A;
					if( NumMatchingActors == MaxMatches )
						break;
				}
				else if( DistanceFilterType == DFT_Closest )
				{
					// track closest
					if( DistanceBetweenActors < BestDistance )
					{
						MatchingActors[ 0 ] = A;
						BestDistance = DistanceBetweenActors;
						NumMatchingActors = 1; // ya -- this could be reset to 1 multiple times
					}
				}
				else
				{
					// track furthest
					if( DistanceBetweenActors > BestDistance )
					{
						MatchingActors[ 0 ] = A;
						BestDistance = DistanceBetweenActors;
						NumMatchingActors = 1; // ya -- this could be reset to 1 multiple times
					}
				}
			}
		}
		else if( ClassIsChildOf( BaseClass, class'Pawn' ) )
		{
			// use controller list
			for( TempC=OriginActor.Level.ControllerList; TempC!=None; TempC=TempC.NextController )
			{
				A = TempC.Pawn;

				if( A == None )
					continue;

				if( !ClassIsChildOf( A.Class, BaseClass ) )
					continue;

				DistanceBetweenActors = VSize( A.Location - OriginActor.Location );	
		
				if( DistanceBetweenActors < MinRadius )
					continue; // too close
	
				if( DistanceBetweenActors > MaxRadius )
					continue; // too far
	
				// in Min..Max

				if( TargetName != '' && A.Name != TargetName )
					continue; // wrong object name (if looking for a specific actor)

				// check any visibility constraints
	
				if( bPawnVisibleFilter && !OriginController.LineOfSightTo( A ) )
					continue; // Pawn has no LOS to A
	
				if( bPawnFOVFilter && !OriginController.CanSee( A ) )
					continue; // A not in Pawn's field of view (stronger test than LOS)
	
				if( bActorVisibleFilter && !SLCActorCanSeeActor( OriginActor, A ) )
					continue; // something is between OriginActor and A
	
				// this is a valid actor
	
				if( TargetName != '' )
				{
					// looking for a specific target actor
					if( A.Name == TargetName )
					{
						// found it
						if( VerifyNamedActor( A, bAllowUnSafe ) )
							MatchingActors[ NumMatchingActors++ ] = A;
						break;
					}
				}
				else if( DistanceFilterType == DFT_First )
				{
					// done -- return first candidate
					MatchingActors[ NumMatchingActors++ ] = A;
					break;
				}
				else if( DistanceFilterType == DFT_Any )
				{
					// return first N candidates
					MatchingActors[ NumMatchingActors++ ] = A;
					if( NumMatchingActors == MaxMatches )
						break;
				}
				else if( DistanceFilterType == DFT_Closest )
				{
					// track closest
					if( DistanceBetweenActors < BestDistance )
					{
						MatchingActors[ 0 ] = A;
						BestDistance = DistanceBetweenActors;
						NumMatchingActors = 1; // ya -- this could be reset to 1 multiple times
					}
				}
				else
				{
					// track furthest
					if( DistanceBetweenActors > BestDistance )
					{
						MatchingActors[ 0 ] = A;
						BestDistance = DistanceBetweenActors;
						NumMatchingActors = 1; // ya -- this could be reset to 1 multiple times
					}
				}
			}
		}
		else if( BaseClass.default.bStatic )
		{
			// use RadiusActors (sloow)
		  	foreach OriginActor.RadiusActors( BaseClass, A, MaxRadius )
			{
				DistanceBetweenActors = VSize( A.Location - OriginActor.Location );	
		
				if( DistanceBetweenActors < MinRadius )
					continue; // too close
	
				//!!mdf-tbr: shouldn't be needed with radius check in AllActors? if( DistanceBetweenActors > MaxRadius )
				//!!mdf-tbr:	continue; // too far
	
				// in Min..Max
	
				if( TargetName != '' && A.Name != TargetName )
					continue; // wrong object name (if looking for a specific actor)
	
				// check any visibility constraints
	
				if( bPawnVisibleFilter && !OriginController.LineOfSightTo( A ) )
					continue; // Pawn has no LOS to A
	
				if( bPawnFOVFilter && !OriginController.CanSee( A ) )
					continue; // A not in Pawn's field of view (stronger test than LOS)
	
				if( bActorVisibleFilter && !SLCActorCanSeeActor( OriginActor, A ) )
					continue; // something is between OriginActor and A
	
				// this is a valid actor
	
				if( TargetName != '' )
				{
					// looking for a specific target actor
					if( A.Name == TargetName )
					{
						// found it
						if( VerifyNamedActor( A, bAllowUnSafe ) )
							MatchingActors[ NumMatchingActors++ ] = A;
						break;
					}
				}
				else if( DistanceFilterType == DFT_First )
				{
					// done -- return first candidate
					MatchingActors[ NumMatchingActors++ ] = A;
					break;
				}
				else if( DistanceFilterType == DFT_Any )
				{
					// return first N candidates
					MatchingActors[ NumMatchingActors++ ] = A;
					if( NumMatchingActors == MaxMatches )
						break;
				}
				else if( DistanceFilterType == DFT_Closest )
				{
					// track closest
					if( DistanceBetweenActors < BestDistance )
					{
						MatchingActors[ 0 ] = A;
						BestDistance = DistanceBetweenActors;
						NumMatchingActors = 1; // ya -- this could be reset to 1 multiple times
					}
				}
				else
				{
					// track furthest
					if( DistanceBetweenActors > BestDistance )
					{
						MatchingActors[ 0 ] = A;
						BestDistance = DistanceBetweenActors;
						NumMatchingActors = 1; // ya -- this could be reset to 1 multiple times
					}
				}
			}
		}
		else
		{
			// use DynamicActors
		  	foreach OriginActor.DynamicActors( BaseClass, A, , MaxRadius )
			{
				DistanceBetweenActors = VSize( A.Location - OriginActor.Location );	

				if( DistanceBetweenActors < MinRadius )
					continue; // too close
	
				//!!mdf-tbr: shouldn't be needed with radius check in DynamicActors? if( DistanceBetweenActors > MaxRadius )
				//!!mdf-tbr:	continue; // too far
	
				// in Min..Max
	
				if( TargetName != '' && A.Name != TargetName )
					continue; // wrong object name (if looking for a specific actor)
	
				// check any visibility constraints
	
				if( bPawnVisibleFilter && !OriginController.LineOfSightTo( A ) )
					continue; // Pawn has no LOS to A
	
				if( bPawnFOVFilter && !OriginController.CanSee( A ) )
					continue; // A not in Pawn's field of view (stronger test than LOS)
	
				if( bActorVisibleFilter && !SLCActorCanSeeActor( OriginActor, A ) )
					continue; // something is between OriginActor and A
	
				// this is a valid actor
	
				if( TargetName != '' )
				{
					// looking for a specific target actor
					if( A.Name == TargetName )
					{
						// found it
						if( VerifyNamedActor( A, bAllowUnSafe ) )
							MatchingActors[ NumMatchingActors++ ] = A;
						break;
					}
				}
				else if( DistanceFilterType == DFT_First )
				{
					// done -- return first candidate
					MatchingActors[ NumMatchingActors++ ] = A;
					break;
				}
				else if( DistanceFilterType == DFT_Any )
				{
					// return first N candidates
					MatchingActors[ NumMatchingActors++ ] = A;
					if( NumMatchingActors == MaxMatches )
						break;
				}
				else if( DistanceFilterType == DFT_Closest )
				{
					// track closest
					if( DistanceBetweenActors < BestDistance )
					{
						MatchingActors[ 0 ] = A;
						BestDistance = DistanceBetweenActors;
						NumMatchingActors = 1; // ya -- this could be reset to 1 multiple times
					}
				}
				else
				{
					// track furthest
					if( DistanceBetweenActors > BestDistance )
					{
						MatchingActors[ 0 ] = A;
						BestDistance = DistanceBetweenActors;
						NumMatchingActors = 1; // ya -- this could be reset to 1 multiple times
					}
				}
			}
		}
	}

	return NumMatchingActors;
}

//-----------------------------------------------------------------------------
// GetClosestActor
//
// Returns the Actor of the specified class which is closest to the OriginActor
// and withing the specified MaxSearchRadius (if 0 any distance is valid).
//
// Optimized for NavigationPoints, Controllers and Projectiles (including 
// but this can still be a very slow call).
										 
static final function Actor GetClosestActor( Actor OriginActor, class<Actor> ClassToSearchFor, optional float MaxSearchRadius )
{
	local Controller C;
	local NavigationPoint NP;
	local Actor A;
	local float DistanceBetweenActors;

	local float ClosestDistance;
	local Actor ClosestActor;

	ClosestDistance = 999999.9;

	if( MaxSearchRadius ~= 0.0 )
		MaxSearchRadius = 999999.9;

	// optimize special cases
	if( ClassIsChildOf( ClassToSearchFor, class'Controller' ) )
	{
		// optimization for Controllers
	  	for( C=OriginActor.Level.ControllerList; C!=None; C=C.NextController )
		{
			if( C.IsA( ClassToSearchFor.Name ) )
			{
				DistanceBetweenActors = VSize( C.Pawn.Location - OriginActor.Location );	
	
				if( DistanceBetweenActors <= MaxSearchRadius && DistanceBetweenActors < ClosestDistance )
				{
					ClosestActor = C;
					ClosestDistance = DistanceBetweenActors;
				}
			}
		}
	}
	else if( ClassIsChildOf( ClassToSearchFor, class'NavigationPoint' ) )
	{
		// optimization for NavigationPoints
	  	for( NP=OriginActor.Level.NavigationPointList; NP!=None; NP=NP.NextNavigationPoint )
		{
			if( NP.IsA( ClassToSearchFor.Name )	)
			{
				DistanceBetweenActors = VSize( NP.Location - OriginActor.Location );	
	
				if( DistanceBetweenActors <= MaxSearchRadius && DistanceBetweenActors < ClosestDistance )
				{
					ClosestActor = NP;
					ClosestDistance = DistanceBetweenActors;
				}
			}
		}
	}
	else
	{
		//mjl-tbd: have this search the LevelInfo's ActorLists for a thing of the appropriate class, and use it
		// general case -- slooow
	  	foreach OriginActor.AllActors( ClassToSearchFor, A )
		{
			DistanceBetweenActors = VSize( A.Location - OriginActor.Location );	

			if( DistanceBetweenActors <= MaxSearchRadius && DistanceBetweenActors < ClosestDistance )
			{
				ClosestActor = A;
				ClosestDistance = DistanceBetweenActors;
			}
		}
	}

	return ClosestActor;
}

//=============================================================================
//@ Visibility
//=============================================================================

//-----------------------------------------------------------------------------
// Allows you to check if an object is in your view.
//-----------------------------------------------------------------------------
// ViewVec:	A vector facing "forward"						(relative to your location.)
// DirVec:	A vector pointing to the object in question.	(relative to your location.)
// FOVCos:	Cosine of how many degrees between ViewVec and DirVec to be seen.
//-----------------------------------------------------------------------------
// REQUIRE: FOVCos > 0
// NOTE: While normalization is not required for ViewVec or DirVec, it helps
// if both vectors are about the same size.
//-----------------------------------------------------------------------------

static final function bool IsInViewCos( vector ViewVec, vector DirVec, float FOVCos )
{
	local float CosAngle;		//cosine of angle from object's LOS to WP
    
    CosAngle = Normal( ViewVec ) dot  Normal( DirVec );

	//The first test makes sure the target is within the firer's front 180o view.
	//The second test might look backwards, but it isn't.  Since cos(0) == 1,
	//as the angle gets smaller, CosAngle *increases*, so an angle less than
	//the max will have a larger cosine value.
	
	return (0 <= CosAngle && FOVCos < CosAngle);
}

//-----------------------------------------------------------------------------
// Allows you to check if an object is in your view.
//-----------------------------------------------------------------------------
// ViewVec:	A vector facing "forward"						(relative to your location.)
// DirVec:	A vector pointing to the object in question.	(relative to your location.)
// FOV:		How many degrees the target must be within to be seen.
//-----------------------------------------------------------------------------
// REQUIRE: FOV < 90
// NOTE: While normalization is not required for ViewVec or DirVec, it helps
// if both vectors are about the same size.
//-----------------------------------------------------------------------------

static final function bool IsInView( vector ViewVec, vector DirVec, float FOV )
{
	return IsInViewCos( ViewVec, DirVec, cos( ( 2 * Pi ) / ( 360 / FOV ) ) );
}

//-----------------------------------------------------------------------------
// Returns true if the first Actor has an uninterrupted LOS to the second actor.

static final function bool SLCActorCanSeeActor( Actor SourceActor, Actor TargetActor )
{
	local vector TraceHitLocation, TraceHitNormal;

	// can we trace a line from the source actor to the target actor?
	return( SourceActor.Trace( 
		   		TraceHitLocation, 
		   		TraceHitNormal,		
		   		TargetActor.Location, 
		   		SourceActor.Location, 
		   		true ) == TargetActor );
}

//-----------------------------------------------------------------------------
// Returns true if Target is in within given FOVCos wrt SeeingActor.
//-----------------------------------------------------------------------------

static final function bool ActorLookingAt( Actor SeeingActor, Actor Target, float FOVCos )
{
	//2002.12.19 (mdf) warning fix
	if( Target == None || SeeingActor == None )
		return false;

	return IsInViewCos( vector(SeeingActor.Rotation), Target.Location - SeeingActor.Location, FOVCos );
}

//-----------------------------------------------------------------------------
// MLCActorCanSeeActor:
//-----------------------------------------------------------------------------
// TraceFromActor:	Actor to trace from
// TraceToActor:	Actor to trace to
// FOVCos:			(optional) cos of FOV to use (1/2 of the total FOV), 
//					If	<= -1, FOV not used.
//
//-----------------------------------------------------------------------------
// Returns true if Actor is not entirely occluded by geometry from the given
// TraceFromActor's point of view. If bTraceActors is true, other actors will 
// block the TraceFromActor's view of the TraceToActor.
//
// Determines whether an Actor can see another actor, i.e. whether any line from
// the TraceFroActor's center (+baseeyeheight if TraceFromActor is a Pawn) 
// to the TraceToActor exists which doesn't hit any geometry or another actor 
// (if bTraceActors is true) and is within the FOV relative to the TraceFromActor's
// ViewRotation.
//
//-----------------------------------------------------------------------------
// Notes:
// 
// There's got to be a better way to do this.  Tim has to do this when he 
// draws the actors on the screen.  Is there any way we can piggy-back off
// of that code?
//
// CanSee is fubar: reports true even if facing 180 degrees away, but close,
// could be related to the fact that CanSee also takes noises into account...
// LineOfSightTo is fubar: doesn't take actor's into account?
//
// Will return true if the TraceFromActor can see the bottom, center or top of 
// the given TraceToActor's collision cylinder. Currently only traces to the 
// horizontal center of the actor, doesn't currently check left and right sides.
//
// TBD: do left-left and right-right checks as well to handle case where 
// actors can only see each other's left/right side.
//
// Seems this can fail for small (fast?) actors e.g. tracing from a Pawn to a 
// dart projectile which was maybe 200 units in front consistently fails to
// hit the dart.
//-----------------------------------------------------------------------------

static final function bool ActorCanSeeActor( Actor TraceFromActor, Actor TraceToActor, float FOVCos, optional bool bTraceActors )
{
	local bool bCanSee;
	local vector StartPoint;
	local vector EndPoints[5];
	local int ii;
	local Actor HitActor;
	local vector HitLocation, HitNormal;
	
	// Is the Actor even in the Pawns FOV?
	if( FOVCos > -1.0 && !ActorLookingAt( TraceFromActor, TraceToActor, FOVCos ) )
	  	return false;

	// Can we trace a line from the Pawn's eyes to the actor without hitting geometry?
	StartPoint = TraceFromActor.Location;
	if( Pawn(TraceFromActor) != None )
		StartPoint.Z += Pawn(TraceFromActor).BaseEyeHeight;
		
	EndPoints[0] = TraceToActor.Location;												// eyes/center -> actor center
	EndPoints[1] = TraceToActor.Location + TraceToActor.CollisionHeight*vect(0,0,1);	// eyes/center -> actor top (head)
	EndPoints[2] = TraceToActor.Location - TraceToActor.CollisionHeight*vect(0,0,1);	// eyes/center -> actor bottom (feet)
	EndPoints[3] = TraceToActor.Location + TraceToActor.CollisionRadius*( Normal(vect(0,0,1) cross (TraceToActor.Location - TraceFromActor.Location)) );	// eyes/center -> actor left
	EndPoints[4] = TraceToActor.Location - TraceToActor.CollisionRadius*( Normal(vect(0,0,1) cross (TraceToActor.Location - TraceFromActor.Location)) );	// eyes/center -> actor right

	for( ii=0; ii<ArrayCount(EndPoints); ii++ )
	{
		HitActor = class'Util'.static.TraceRecursive(
				TraceFromActor,
				HitLocation,
				HitNormal,
				StartPoint,
				bTraceActors,,
				Normal(EndPoints[ii] - StartPoint),		// direction.
				VSize(EndPoints[ii] - StartPoint)		// limit.
			);

		// if bTraceActors is true, trace should hit TraceToActor if TraceFromActor can see TraceToActor
		// if bTraceActors is false, trace should hit nothing if TraceFromActor can see TraceToActor
		bCanSee = ( HitActor == None || HitActor == TraceToActor );

    	if( bCanSee )	
			break;		// No need to go on.
	}

	return bCanSee;
}

//-----------------------------------------------------------------------------
// Check for line of sight to target DeltaTime from now. Moved here from 
// Controller hierarchy but not called from anywhere currently (tbr?).

static final function bool CheckFutureSight( Pawn SourcePawn, Actor TargetActor, float DeltaTime )
{
	local vector FutureLoc;

	if( TargetActor == None )
		return false;

	if( VSize( SourcePawn.Velocity ) ~= 0.0 )
		FutureLoc = SourcePawn.Location;
	else
		FutureLoc = SourcePawn.Location + SourcePawn.GroundSpeed * Normal( SourcePawn.Velocity ) * DeltaTime;

	if( SourcePawn.Base != None ) 
		FutureLoc += SourcePawn.Base.Velocity * DeltaTime;

	//make sure won't run into something
	if( !SourcePawn.FastTrace( FutureLoc, SourcePawn.Location ) && ( SourcePawn.Physics != PHYS_Falling ) )
		return false;

	//check if can still see target actor
	if( SourcePawn.FastTrace( TargetActor.Location + TargetActor.Velocity * DeltaTime, FutureLoc ) )
		return true;

	return false;
}

//-----------------------------------------------------------------------------

defaultproperties
{
	VerifyTrajectorySamples=8
	VerifyTrajectoryVerticalExtentPadding=8.000000
	MaxPredictProjectileAttempts=16
	PredictProjectileThreshold=16.000000
	MaxTargetBlockedMissMultiplier=3.000000
	MinTargetBlockedPitchError=-1024.000000
	MaxTargetBlockedPitchError=4096.000000
	MinModifyForSpreadDistance=512.000000
	MinPitchError=-1024.000000
	MaxPitchError=4096.000000
     UseReticleOnEvents(0)="UseReticleText"
     UseReticleOnEvents(1)="UseReticleCorners"
     UseReticleOnEvents(2)="UseReticleTopBars"
     ProximityReticleOnEvents(0)="ProximityReticleCorners"
     ProximityReticleOnEvents(1)="ProximityReticleTopBars"
}

Overview Package Class Source Class tree Glossary
previous class      next class frames      no frames
Class file time: sk 3-1-2016 10:38:40.000 - Creation time: sk 3-1-2016 10:48:43.694 - Created with UnCodeX