forked from WolfKnight98/wk_wars2x
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcl_radar.lua
1860 lines (1514 loc) · 70.7 KB
/
cl_radar.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--[[---------------------------------------------------------------------------------------
Wraith ARS 2X
Created by WolfKnight
For discussions, information on future updates, and more, join
my Discord: https://discord.gg/fD4e6WD
MIT License
Copyright (c) 2020-2021 WolfKnight
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---------------------------------------------------------------------------------------]]--
-- Cache some of the main Lua functions and libraries
local next = next
local dot = dot
local table = table
local type = type
local tostring = tostring
local math = math
local pairs = pairs
--[[----------------------------------------------------------------------------------
UI loading and key binds registering
----------------------------------------------------------------------------------]]--
local function RegisterKeyBinds()
if ( UTIL:IsResourceNameValid() ) then
UTIL:Log( "Registering radar commands and key binds." )
-- Opens the remote control
RegisterCommand( "radar_remote", function()
if ( not RADAR:GetKeyLockState() ) then
RADAR:OpenRemote()
end
end )
RegisterKeyMapping( "radar_remote", "Open Remote Control", "keyboard", CONFIG.keyDefaults.remote_control )
-- Locks speed from front antenna
RegisterCommand( "radar_fr_ant", function()
if ( not RADAR:GetKeyLockState() and PLY:CanControlRadar() ) then
RADAR:LockAntennaSpeed( "front", nil )
SYNC:LockAntennaSpeed( "front", RADAR:GetAntennaDataPacket( "front" ) )
end
end )
RegisterKeyMapping( "radar_fr_ant", "Front Antenna Lock/Unlock", "keyboard", CONFIG.keyDefaults.front_lock )
-- Locks speed from rear antenna
RegisterCommand( "radar_bk_ant", function()
if ( not RADAR:GetKeyLockState() and PLY:CanControlRadar() ) then
RADAR:LockAntennaSpeed( "rear", nil )
SYNC:LockAntennaSpeed( "rear", RADAR:GetAntennaDataPacket( "rear" ) )
end
end )
RegisterKeyMapping( "radar_bk_ant", "Rear Antenna Lock/Unlock", "keyboard", CONFIG.keyDefaults.rear_lock )
-- Locks front plate reader
RegisterCommand( "radar_fr_cam", function()
if ( not RADAR:GetKeyLockState() and PLY:CanControlRadar() ) then
READER:LockCam( "front", true, false )
SYNC:LockReaderCam( "front", READER:GetCameraDataPacket( "front" ) )
end
end )
RegisterKeyMapping( "radar_fr_cam", "Front Plate Reader Lock/Unlock", "keyboard", CONFIG.keyDefaults.plate_front_lock )
-- Locks rear plate reader
RegisterCommand( "radar_bk_cam", function()
if ( not RADAR:GetKeyLockState() and PLY:CanControlRadar() ) then
READER:LockCam( "rear", true, false )
SYNC:LockReaderCam( "rear", READER:GetCameraDataPacket( "rear" ) )
end
end )
RegisterKeyMapping( "radar_bk_cam", "Rear Plate Reader Lock/Unlock", "keyboard", CONFIG.keyDefaults.plate_rear_lock )
-- Toggles the key lock state
RegisterCommand( "radar_key_lock", function()
RADAR:ToggleKeyLock()
end )
RegisterKeyMapping( "radar_key_lock", "Toggle Keybind Lock", "keyboard", CONFIG.keyDefaults.key_lock )
-- Deletes all of the KVPs
RegisterCommand( "reset_radar_data", function()
DeleteResourceKvp( "wk_wars2x_ui_data" )
DeleteResourceKvp( "wk_wars2x_om_data" )
DeleteResourceKvp( "wk_wars2x_new_user" )
UTIL:Notify( "Radar data deleted, please immediately restart your game without opening the radar's remote." )
end, false )
TriggerEvent( "chat:addSuggestion", "/reset_radar_data", "Resets the KVP data stored for the wk_wars2x resource." )
else
UTIL:Log( "ERROR: Resource name is not wk_wars2x. Key binds will not be registered for compatibility reasons. Contact the server owner and ask them to change the resource name back to wk_wars2x" )
end
end
local function LoadUISettings()
UTIL:Log( "Attempting to load saved UI settings data." )
-- Try and get the saved UI data
local uiData = GetResourceKvpString( "wk_wars2x_ui_data" )
-- If the data exists, then we send it off!
if ( uiData ~= nil ) then
SendNUIMessage( { _type = "loadUiSettings", data = json.decode( uiData ) } )
UTIL:Log( "Saved UI settings data loaded!" )
-- If the data doesn't exist, then we send the defaults
else
SendNUIMessage( { _type = "setUiDefaults", data = CONFIG.uiDefaults } )
UTIL:Log( "Could not find any saved UI settings data." )
end
end
--[[----------------------------------------------------------------------------------
Radar variables
NOTE - This is not a config, do not touch anything unless you know what
you are actually doing.
----------------------------------------------------------------------------------]]--
RADAR = {}
RADAR.vars =
{
-- Whether or not the radar's UI is visible
displayed = false,
-- The radar's power, the system simulates the radar unit powering up when the user clicks the
-- power button on the interface
power = false,
poweringUp = false,
-- Whether or not the radar should be hidden, e.g. the display is active but the player then steps
-- out of their vehicle
hidden = false,
-- These are the settings that are used in the operator menu
settings = {
-- Should the system calculate and display faster targets
["fastDisplay"] = CONFIG.menuDefaults["fastDisplay"],
-- Sensitivity for each radar mode, this changes how far the antennas will detect vehicles
["same"] = CONFIG.menuDefaults["same"],
["opp"] = CONFIG.menuDefaults["opp"],
-- The volume of the audible beep
["beep"] = CONFIG.menuDefaults["beep"],
-- The volume of the verbal lock confirmation
["voice"] = CONFIG.menuDefaults["voice"],
-- The volume of the plate reader audio
["plateAudio"] = CONFIG.menuDefaults["plateAudio"],
-- The speed unit used in conversions
["speedType"] = CONFIG.menuDefaults["speedType"],
-- The state of automatic speed locking
["fastLock"] = CONFIG.menuDefaults["fastLock"],
-- The speed limit for automatic speed locking
["fastLimit"] = CONFIG.menuDefaults["fastLimit"]
},
-- These 3 variables are for the in-radar menu that can be accessed through the remote control, the menuOptions table
-- stores all of the information about each of the settings the user can change
menuActive = false,
currentOptionIndex = 1,
menuOptions = {
{ displayText = { "¦¦¦", "FAS" }, optionsText = { "On¦", "Off" }, options = { true, false }, optionIndex = -1, settingText = "fastDisplay" },
{ displayText = { "¦SL", "SEn" }, optionsText = { "¦1¦", "¦2¦", "¦3¦", "¦4¦", "¦5¦" }, options = { 0.2, 0.4, 0.6, 0.8, 1.0 }, optionIndex = -1, settingText = "same" },
{ displayText = { "¦OP", "SEn" }, optionsText = { "¦1¦", "¦2¦", "¦3¦", "¦4¦", "¦5¦" }, options = { 0.2, 0.4, 0.6, 0.8, 1.0 }, optionIndex = -1, settingText = "opp" },
{ displayText = { "bEE", "P¦¦" }, optionsText = { "Off", "¦1¦", "¦2¦", "¦3¦", "¦4¦", "¦5¦" }, options = { 0.0, 0.2, 0.4, 0.6, 0.8, 1.0 }, optionIndex = -1, settingText = "beep" },
{ displayText = { "VOI", "CE¦" }, optionsText = { "Off", "¦1¦", "¦2¦", "¦3¦", "¦4¦", "¦5¦" }, options = { 0.0, 0.2, 0.4, 0.6, 0.8, 1.0 }, optionIndex = -1, settingText = "voice" },
{ displayText = { "PLt", "AUd" }, optionsText = { "Off", "¦1¦", "¦2¦", "¦3¦", "¦4¦", "¦5¦" }, options = { 0.0, 0.2, 0.4, 0.6, 0.8, 1.0 }, optionIndex = -1, settingText = "plateAudio" },
{ displayText = { "Uni", "tS¦" }, optionsText = { "USA", "INT" }, options = { "mph", "kmh" }, optionIndex = -1, settingText = "speedType" }
},
-- Player's vehicle speed, mainly used in the dynamic thread wait update
patrolSpeed = 0,
-- Antennas, this table contains all of the data needed for operation of the front and rear antennas
antennas = {
-- Variables for the front antenna
[ "front" ] = {
xmit = false, -- Whether the antenna is transmitting or in hold
mode = 0, -- Current antenna mode, 0 = none, 1 = same, 2 = opp, 3 = same and opp
speed = 0, -- Speed of the vehicle caught by the front antenna
dir = nil, -- Direction the caught vehicle is going, 0 = towards, 1 = away
fastSpeed = 0, -- Speed of the fastest vehicle caught by the front antenna
fastDir = nil, -- Direction the fastest vehicle is going
speedLocked = false, -- A speed has been locked for this antenna
lockedSpeed = nil, -- The locked speed
lockedDir = nil, -- The direction of the vehicle that was locked
lockedType = nil -- The locked type, 1 = strongest, 2 = fastest
},
-- Variables for the rear antenna
[ "rear" ] = {
xmit = false, -- Whether the antenna is transmitting or in hold
mode = 0, -- Current antenna mode, 0 = none, 1 = same, 2 = opp, 3 = same and opp
speed = 0, -- Speed of the vehicle caught by the front antenna
dir = nil, -- Direction the caught vehicle is going, 0 = towards, 1 = away
fastSpeed = 0, -- Speed of the fastest vehicle caught by the front antenna
fastDir = nil, -- Direction the fastest vehicle is going
speedLocked = false, -- A speed has been locked for this antenna
lockedSpeed = nil, -- The locked speed
lockedDir = nil, -- The direction of the vehicle that was locked
lockedType = nil -- The locked type, 1 = strongest, 2 = fastest
}
},
-- The maximum distance that the radar system's ray traces can go, changing this will change the max
-- distance in-game, but I wouldn't really put it more than 500.0
maxCheckDist = 350.0,
-- Cached dynamic vehicle sphere sizes, automatically populated when the system is running
sphereSizes = {},
-- Table to store tables for hit entities of captured vehicles
capturedVehicles = {},
-- Table to store the valid vehicle models
validVehicles = {},
-- The current vehicle data for display
activeVehicles = {},
-- Vehicle pool, automatically populated when the system is running, holds all of the current
-- vehicle IDs for the player using entity enumeration (see cl_utils.lua)
vehiclePool = {},
-- Ray trace state, this is used so the radar system doesn't initiate another set of ray traces until
-- the current set has finished
rayTraceState = 0,
-- Number of ray traces, automatically cached when the system first runs
numberOfRays = 0,
-- The wait time for the ray trace system, this changes dynamically based on if the player's vehicle is stationary
-- or not
threadWaitTime = 500,
-- Key lock, when true, prevents any of the radar's key events from working, like the ELS key lock
keyLock = false
}
-- Speed conversion values
RADAR.speedConversions = { ["mph"] = 2.236936, ["kmh"] = 3.6 }
-- These vectors are used in the custom ray tracing system
RADAR.rayTraces = {
{ startVec = { x = 0.0 }, endVec = { x = 0.0, y = 0.0 }, rayType = "same" },
{ startVec = { x = -5.0 }, endVec = { x = -5.0, y = 0.0 }, rayType = "same" },
{ startVec = { x = 5.0 }, endVec = { x = 5.0, y = 0.0 }, rayType = "same" },
{ startVec = { x = -10.0 }, endVec = { x = -10.0, y = 0.0 }, rayType = "opp" },
{ startVec = { x = -17.0 }, endVec = { x = -17.0, y = 0.0 }, rayType = "opp" }
}
-- Each of these are used for sorting the captured vehicle data, the 'strongest' filter is used for the main
-- target window of each antenna, whereas the 'fastest' filter is used for the fast target window of each antenna
RADAR.sorting = {
strongest = function( a, b ) return a.size > b.size end,
fastest = function( a, b ) return a.speed > b.speed end
}
--[[----------------------------------------------------------------------------------
Radar essentials functions
----------------------------------------------------------------------------------]]--
-- Returns if the radar's power is on or off
function RADAR:IsPowerOn()
return self.vars.power
end
-- Returns if the radar system is powering up, the powering up stage only takes 2 seconds
function RADAR:IsPoweringUp()
return self.vars.poweringUp
end
-- Allows the powering up state variable to be set
function RADAR:SetPoweringUpState( state )
self.vars.poweringUp = state
end
-- Toggles the radar power
function RADAR:SetPowerState( state, instantOverride )
local currentState = self:IsPowerOn()
-- Only power up if the system is not already powering up
if ( not self:IsPoweringUp() and currentState ~= state ) then
-- Toggle the power variable
self.vars.power = state
-- Send the NUI message to toggle the power
SendNUIMessage( { _type = "radarPower", state = state, override = instantOverride, fast = self:IsFastDisplayEnabled() } )
-- Power is now turned on
if ( self:IsPowerOn() ) then
-- Also make sure the operator menu is inactive
self:SetMenuState( false )
-- Only do the power up simulation if allowed
if ( not instantOverride ) then
-- Tell the system the radar is 'powering up'
self:SetPoweringUpState( true )
-- Set a 2 second countdown
Citizen.SetTimeout( 2000, function()
-- Tell the system the radar has 'powered up'
self:SetPoweringUpState( false )
-- Let the UI side know the system has loaded
SendNUIMessage( { _type = "poweredUp", fast = self:IsFastDisplayEnabled() } )
end )
end
else
-- If the system is being turned off, then we reset the antennas
self:ResetAntenna( "front" )
self:ResetAntenna( "rear" )
end
end
end
-- Toggles the display state of the radar system
function RADAR:ToggleDisplayState()
-- Toggle the display variable
self.vars.displayed = not self.vars.displayed
-- Send the toggle message to the NUI side
SendNUIMessage( { _type = "setRadarDisplayState", state = self:GetDisplayState() } )
end
-- Gets the display state
function RADAR:GetDisplayState()
return self.vars.displayed
end
-- Return the state of the fastDisplay setting, short hand direct way to check if the fast system is enabled
function RADAR:IsFastDisplayEnabled()
return self:GetSettingValue( "fastDisplay" )
end
-- Returns if either of the antennas are transmitting
function RADAR:IsEitherAntennaOn()
return self:IsAntennaTransmitting( "front" ) or self:IsAntennaTransmitting( "rear" )
end
-- Sends an update to the NUI side with the current state of the antennas and if the fast system is enabled
function RADAR:SendSettingUpdate()
-- Create a table to store the setting information for the antennas
local antennas = {}
-- Iterate through each antenna and grab the relevant information
for ant in UTIL:Values( { "front", "rear" } ) do
antennas[ant] = {}
antennas[ant].xmit = self:IsAntennaTransmitting( ant )
antennas[ant].mode = self:GetAntennaMode( ant )
antennas[ant].speedLocked = self:IsAntennaSpeedLocked( ant )
antennas[ant].fast = self:ShouldFastBeDisplayed( ant )
end
-- Send a message to the NUI side with the current state of the antennas
SendNUIMessage( { _type = "settingUpdate", antennaData = antennas } )
end
-- Returns if a main task can be performed
-- A main task such as the ray trace thread should only run if the radar's power is on, the system is not in the
-- process of powering up, and the operator menu is not open
function RADAR:CanPerformMainTask()
return self:IsPowerOn() and not self:IsPoweringUp() and not self:IsMenuOpen()
end
-- Returns/sets what the dynamic thread wait time is
function RADAR:GetThreadWaitTime() return self.vars.threadWaitTime end
function RADAR:SetThreadWaitTime( time ) self.vars.threadWaitTime = time end
-- Returns/sets the radr's display hidden state
function RADAR:GetDisplayHidden() return self.vars.hidden end
function RADAR:SetDisplayHidden( state ) self.vars.hidden = state end
-- Opens the remote only if the pause menu is not open and the player's vehicle state is valid, as the
-- passenger can also open the remote, we check the config variable as well.
function RADAR:OpenRemote()
if ( not IsPauseMenuActive() and PLY:CanViewRadar() ) then
-- Get the remote open state from the other player
local openByOtherPly = SYNC:IsRemoteAlreadyOpen( PLY:GetOtherPed() )
-- Check that the remote can be opened
if ( not openByOtherPly ) then
-- Tell the NUI side to open the remote
SendNUIMessage( { _type = "openRemote" } )
SYNC:SetRemoteOpenState( true )
if ( CONFIG.allow_quick_start_video ) then
-- Display the new user popup if we can
local show = GetResourceKvpInt( "wk_wars2x_new_user" )
if ( show == 0 ) then
SendNUIMessage( { _type = "showNewUser" } )
end
end
-- Bring focus to the NUI side
SetNuiFocus( true, true )
else
UTIL:Notify( "Another player already has the remote open." )
end
end
end
-- Event to open the remote
RegisterNetEvent( "wk:openRemote" )
AddEventHandler( "wk:openRemote", function()
RADAR:OpenRemote()
end )
-- Returns if the passenger can view the radar too
function RADAR:IsPassengerViewAllowed()
return CONFIG.allow_passenger_view
end
-- Returns if the passenger can control the radar and plate reader, reliant on the passenger being
-- able to view the radar and plate reader too
function RADAR:IsPassengerControlAllowed()
return CONFIG.allow_passenger_view and CONFIG.allow_passenger_control
end
-- Returns if we only auto lock vehicle speeds if said vehicle is a player
function RADAR:OnlyLockFastPlayers()
return CONFIG.only_lock_players
end
-- Returns if the fast limit option should be available for the radar
function RADAR:IsFastLimitAllowed()
return CONFIG.allow_fast_limit
end
-- Only create the functions if the fast limit config option is enabled
if ( RADAR:IsFastLimitAllowed() ) then
-- Adds settings into the radar's variables for when the allow_fast_limit variable is true
function RADAR:CreateFastLimitConfig()
-- Create the options for the menu
local fastOptions =
{
{ displayText = { "FAS", "Loc" }, optionsText = { "On¦", "Off" }, options = { true, false }, optionIndex = 2, settingText = "fastLock" },
{ displayText = { "FAS", "SPd" }, optionsText = {}, options = {}, optionIndex = 12, settingText = "fastLimit" }
}
-- Iterate from 5 to 200 in steps of 5 and insert into the fast limit option
for i = 5, 200, 5 do
local text = UTIL:FormatSpeed( i )
table.insert( fastOptions[2].optionsText, text )
table.insert( fastOptions[2].options, i )
end
-- Add the fast options to the main menu options table
if ( CONFIG.fast_limit_first_in_menu ) then
table.insert( self.vars.menuOptions, 1, fastOptions[2] ) --FasSpd
table.insert( self.vars.menuOptions, 2, fastOptions[1] ) --FasLoc
else
table.insert( self.vars.menuOptions, fastOptions[1] ) --FasLoc
table.insert( self.vars.menuOptions, fastOptions[2] ) --FasSpd
end
end
-- Returns the numerical fast limit
function RADAR:GetFastLimit()
return self:GetSettingValue( "fastLimit" )
end
-- Returns if the fast lock menu option is on or off
function RADAR:IsFastLockEnabled()
return self:GetSettingValue( "fastLock" )
end
end
-- Toggles the internal key lock state, which stops any of the radar's key binds from working
function RADAR:ToggleKeyLock()
-- Check the player state is valid
if ( PLY:CanViewRadar() ) then
-- Toggle the key lock variable
self.vars.keyLock = not self.vars.keyLock
-- Tell the NUI side to display the key lock message
SendNUIMessage( { _type = "displayKeyLock", state = self:GetKeyLockState() } )
end
end
-- Returns the key lock state
function RADAR:GetKeyLockState()
return self.vars.keyLock
end
--[[----------------------------------------------------------------------------------
Radar menu functions
----------------------------------------------------------------------------------]]--
-- Sets the menu state to the given state
function RADAR:SetMenuState( state )
-- Make sure that the radar's power is on
if ( self:IsPowerOn() ) then
-- Set the menuActive variable to the given state
self.vars.menuActive = state
-- If we are opening the menu, make sure the first item is displayed
if ( state ) then
self.vars.currentOptionIndex = 1
end
end
end
-- Closes the operator menu
function RADAR:CloseMenu( playAudio )
-- Set the internal menu state to be closed (false)
RADAR:SetMenuState( false )
-- Send a setting update to the NUI side
RADAR:SendSettingUpdate()
-- Play a menu done beep
if ( playAudio or playAudio == nil ) then
SendNUIMessage( { _type = "audio", name = "done", vol = RADAR:GetSettingValue( "beep" ) } )
end
-- Save the operator menu values
local omData = json.encode( RADAR.vars.settings )
SetResourceKvp( "wk_wars2x_om_data", omData )
-- Send the operator menu to the passenger if allowed
if ( self:IsPassengerViewAllowed() ) then
local updatedOMData = self:GetOMTableData()
SYNC:SendUpdatedOMData( updatedOMData )
end
end
-- Returns if the operator menu is open
function RADAR:IsMenuOpen()
return self.vars.menuActive
end
-- This function changes the menu index variable so the user can iterate through the options in the operator menu
function RADAR:ChangeMenuIndex()
-- Create a temporary variable of the current menu index plus 1
local temp = self.vars.currentOptionIndex + 1
-- If the temporary value is larger than how many options there are, set it to 1, this way the menu
-- loops back round to the start of the menu
if ( temp > #self.vars.menuOptions ) then
temp = 1
end
-- Set the menu index variable to the temporary value we created
self.vars.currentOptionIndex = temp
-- Call the function to send an update to the NUI side
self:SendMenuUpdate()
end
-- Returns the option table of the current menu index
function RADAR:GetMenuOptionTable()
return self.vars.menuOptions[self.vars.currentOptionIndex]
end
-- Changes the index for an individual option
-- E.g. { "On" "Off" }, index = 2 would be "Off"
function RADAR:SetMenuOptionIndex( index )
self.vars.menuOptions[self.vars.currentOptionIndex].optionIndex = index
end
-- Returns the option value for the current option
function RADAR:GetMenuOptionValue()
local opt = self:GetMenuOptionTable()
local index = opt.optionIndex
return opt.options[index]
end
-- This function is similar to RADAR:ChangeMenuIndex() but allows for iterating forward and backward through options
function RADAR:ChangeMenuOption( dir )
-- Get the option table of the currently selected option
local opt = self:GetMenuOptionTable()
-- Get the current option index of the selected option
local index = opt.optionIndex
-- Cache the size of this setting's options table
local size = #opt.options
-- As the XMIT/HOLD buttons are used for changing the option values, we have to check which button is being pressed
if ( dir == "front" ) then
index = index + 1
if ( index > size ) then index = 1 end
elseif ( dir == "rear" ) then
index = index - 1
if ( index < 1 ) then index = size end
end
-- Update the option's index
self:SetMenuOptionIndex( index )
-- Change the value of the setting in the main RADAR.vars.settings table
self:SetSettingValue( opt.settingText, self:GetMenuOptionValue() )
-- Call the function to send an update to the NUI side
self:SendMenuUpdate()
end
-- Returns what text should be displayed in the boxes for the current option
-- E.g. "¦SL" "SEN"
function RADAR:GetMenuOptionDisplayText()
return self:GetMenuOptionTable().displayText
end
-- Returns the option text of the currently selected setting
function RADAR:GetMenuOptionText()
local opt = self:GetMenuOptionTable()
return opt.optionsText[opt.optionIndex]
end
-- Sends a message to the NUI side with updated information on what should be displayed for the menu
function RADAR:SendMenuUpdate()
SendNUIMessage( { _type = "menu", text = self:GetMenuOptionDisplayText(), option = self:GetMenuOptionText() } )
end
-- Used to set individual settings within RADAR.vars.settings, as all of the settings use string keys, using this
-- function makes updating settings easier
function RADAR:SetSettingValue( setting, value )
-- Make sure that we're not trying to set a nil value for the setting
if ( value ~= nil ) then
-- Set the setting's value
self.vars.settings[setting] = value
-- If the setting that's being updated is same or opp, then we update the end coordinates for the ray tracer
if ( setting == "same" or setting == "opp" ) then
self:UpdateRayEndCoords()
end
end
end
-- Returns the value of the given setting
function RADAR:GetSettingValue( setting )
return self.vars.settings[setting]
end
-- Attempts to load the saved operator menu data
function RADAR:LoadOMData()
UTIL:Log( "Attempting to load saved operator menu data." )
-- Try and get the data
local rawData = GetResourceKvpString( "wk_wars2x_om_data" )
-- If the data exists, decode it and replace the operator menu table
if ( rawData ~= nil ) then
local omData = json.decode( rawData )
self.vars.settings = omData
UTIL:Log( "Saved operator menu data loaded!" )
else
UTIL:Log( "Could not find any saved operator menu data." )
end
end
-- Updates the operator menu option indexes, as the default menu values can be changed in the config, we
-- need to update the indexes otherwise the menu will display the wrong values
function RADAR:UpdateOptionIndexes( loadSaved )
if ( loadSaved ) then
self:LoadOMData()
end
-- Iterate through each of the internal settings
for k, v in pairs( self.vars.settings ) do
-- Iterate through all of the menu options
for i, t in pairs( self.vars.menuOptions ) do
-- If the current menu option is the same as the current setting
if ( t.settingText == k ) then
-- Iterate through the option values of the current menu option
for oi, ov in pairs( t.options ) do
-- If the value of the current option set in the config matches the current value of
-- the option value, then we update the option index variable
if ( v == ov ) then
t.optionIndex = oi
end
end
end
end
end
end
--[[----------------------------------------------------------------------------------
Radar basics functions
----------------------------------------------------------------------------------]]--
-- Returns the patrol speed value stored
function RADAR:GetPatrolSpeed() return self.vars.patrolSpeed end
-- Returns the current vehicle pool
function RADAR:GetVehiclePool() return self.vars.vehiclePool end
-- Returns the maximum distance a ray trace can go
function RADAR:GetMaxCheckDist() return self.vars.maxCheckDist end
-- Returns the table sorting function 'strongest'
function RADAR:GetStrongestSortFunc() return self.sorting.strongest end
-- Returns the table sorting function 'fastest'
function RADAR:GetFastestSortFunc() return self.sorting.fastest end
-- Sets the patrol speed to a formatted version of the given number
function RADAR:SetPatrolSpeed( speed )
if ( type( speed ) == "number" ) then
self.vars.patrolSpeed = self:GetVehSpeedConverted( speed )
end
end
-- Sets the vehicle pool to the given value if it's a table
function RADAR:SetVehiclePool( pool )
if ( type( pool ) == "table" ) then
self.vars.vehiclePool = pool
end
end
--[[----------------------------------------------------------------------------------
Radar ray trace functions
----------------------------------------------------------------------------------]]--
-- Returns what the current ray trace state is
function RADAR:GetRayTraceState() return self.vars.rayTraceState end
-- Caches the number of ray traces in RADAR.rayTraces
function RADAR:CacheNumRays() self.vars.numberOfRays = #self.rayTraces end
-- Returns the number of ray traces the system has
function RADAR:GetNumOfRays() return self.vars.numberOfRays end
-- Increases the system's ray trace state ny 1
function RADAR:IncreaseRayTraceState() self.vars.rayTraceState = self.vars.rayTraceState + 1 end
-- Resets the ray trace state to 0
function RADAR:ResetRayTraceState() self.vars.rayTraceState = 0 end
-- This function is used to determine if a sphere intersect is in front or behind the player's vehicle, the
-- sphere intersect calculation has a 'tProj' value that is a line from the centre of the sphere that goes onto
-- the line being traced. This value will either be positive or negative and can be used to work out the
-- relative position of a point.
function RADAR:GetIntersectedVehIsFrontOrRear( t )
if ( t > 8.0 ) then
return 1 -- vehicle is in front
elseif ( t < -8.0 ) then
return -1 -- vehicle is behind
end
return 0 -- vehicle is next to self
end
-- This function is used to check if a line going from point A to B intersects with a given sphere, it's used in
-- the radar system to check if the patrol vehicle can detect any vehicles. As the default ray trace system in GTA
-- cannot detect vehicles beyond 40~ units, my system acts as a replacement that allows the detection of vehicles
-- much further away (400+ units). Also, as my system uses sphere intersections, each sphere can have a different
-- radius, which means that larger vehicles can have larger spheres, and smaller vehicles can have smaller spheres.
function RADAR:GetLineHitsSphereAndDir( c, radius, rs, re )
-- Take the vector3's and turn them into vector2's, this way all of the calculations below are for an
-- infinite cylinder rather than a sphere, which also means that vehicles can be detected even when on
-- an incline!
local rayStart = vector2( rs.x, rs.y )
local rayEnd = vector2( re.x, re.y )
local centre = vector2( c.x, c.y )
-- First we get the normalised ray, this way we then know the direction the ray is going
local rayNorm = norm( rayEnd - rayStart )
-- Then we calculate the ray from the start point to the centre position of the sphere
local rayToCentre = centre - rayStart
-- Now that we have the ray to the centre of the sphere, and the normalised ray direction, we
-- can calculate the shortest point from the centre of the sphere onto the ray itself. This
-- would then give us the opposite side of the right angled triangle. All of the resulting
-- values are also in squared form, as performing square root functions is slower.
local tProj = dot( rayToCentre, rayNorm )
local oppLenSqr = dot( rayToCentre, rayToCentre ) - ( tProj * tProj )
-- Square the radius
local radiusSqr = radius * radius
-- Calculate the distance of the ray trace to make sure we only return valid results if the trace
-- is actually within the distance
local rayDist = #( rayEnd - rayStart )
local distToCentre = #( rayStart - centre ) - ( radius * 2 )
-- Now all we have to do is compare the squared opposite length and the radius squared, this
-- will then tell us if the ray intersects with the sphere.
if ( oppLenSqr < radiusSqr and not ( distToCentre > rayDist ) ) then
return true, self:GetIntersectedVehIsFrontOrRear( tProj )
end
return false, nil
end
-- This function is used to check if the target vehicle is in the same general traffic flow as the player's vehicle
-- is sitting. If the angle is too great, then the radar would have an incorrect return for the speed.
function RADAR:IsVehicleInTraffic( tgtVeh, relPos )
local tgtHdg = GetEntityHeading( tgtVeh )
local plyHdg = GetEntityHeading( PLY.veh )
-- Work out the heading difference, but also take into account extreme opposites (e.g. 5deg and 350deg)
local hdgDiff = math.abs( ( plyHdg - tgtHdg + 180 ) % 360 - 180 )
if ( relPos == 1 and hdgDiff > 45 and hdgDiff < 135 ) then
return false
elseif ( relPos == -1 and hdgDiff > 45 and ( hdgDiff < 135 or hdgDiff > 215 ) ) then
return false
end
return true
end
-- This function is the main custom ray trace function, it performs most of the major tasks for checking a vehicle
-- is valid and should be tested. It also makes use of the LOS native to make sure that we can only trace a vehicle
-- if actually nas a direct line of sight with the player's vehicle, this way we don't pick up vehicles behind walls
-- for example. It then creates a dynamic sphere for the vehicle based on the actual model dimensions of it, adds a
-- small bit of realism, as real radars usually return the strongest target speed.
function RADAR:ShootCustomRay( plyVeh, veh, s, e )
-- Get the world coordinates of the target vehicle
local pos = GetEntityCoords( veh )
-- Calculate the distance between the target vehicle and the start point of the ray trace, note how we don't
-- use GetDistanceBetweenCoords or Vdist, the method below still returns the same result with less cpu time
local dist = #( pos - s )
-- We only perform a trace on the target vehicle if it exists, isn't the player's vehicle, and the distance is
-- less than the max distance defined by the system
if ( DoesEntityExist( veh ) and veh ~= plyVeh and dist < self:GetMaxCheckDist() ) then
-- Get the speed of the target vehicle
local entSpeed = GetEntitySpeed( veh )
-- Check that the target vehicle is within the line of sight of the player's vehicle
local visible = HasEntityClearLosToEntity( plyVeh, veh, 15 ) -- 13 seems okay, 15 too (doesn't grab ents through ents)
-- Get the pitch of the player's vehicle
local pitch = GetEntityPitch( plyVeh )
-- Now we check that the target vehicle is moving and is visible
if ( entSpeed > 0.1 and ( pitch > -35 and pitch < 35 ) and visible ) then
-- Get the dynamic radius as well as the size of the target vehicle
local radius, size = self:GetDynamicRadius( veh )
-- Check that the trace line intersects with the target vehicle's sphere
local hit, relPos = self:GetLineHitsSphereAndDir( pos, radius, s, e )
-- Return all of the information if the vehicle was hit and is in the flow of traffic
if ( hit and self:IsVehicleInTraffic( veh, relPos ) ) then
return true, relPos, dist, entSpeed, size
end
end
end
-- Return a whole lot of nothing
return false, nil, nil, nil, nil
end
-- This function is used to gather all of the data on vehicles that have been hit by the given trace line, when
-- a vehicle is hit, all of the information about that vehicle is put into a keyless table which is then inserted
-- into a main table. When the loop has finished, the function then returns the table with all of the data.
function RADAR:GetVehsHitByRay( ownVeh, vehs, s, e )
-- Create the table that will be used to store all of the results
local caughtVehs = {}
-- Set the variable to say if there has been data collected
local hasData = false
-- Iterate through all of the vehicles
for _, veh in pairs( vehs ) do
-- Shoot a custom ray trace to see if the vehicle gets hit
local hit, relativePos, distance, speed, size = self:ShootCustomRay( ownVeh, veh, s, e )
-- If the vehicle is hit, then we create a table containing all of the information
if ( hit ) then
-- Create the table to store the data
local vehData = {}
vehData.veh = veh
vehData.relPos = relativePos
vehData.dist = distance
vehData.speed = speed
vehData.size = size
-- Insert the table into the caught vehicles table
table.insert( caughtVehs, vehData )
-- Change the has data variable to true, this way the table will be returned
hasData = true
end
end
-- If the caughtVehs table actually has data, then return it
if ( hasData ) then return caughtVehs end
end
-- This function is used to gather all of the vehicles hit by a given line trace, and then insert it into the
-- internal captured vehicles table.
function RADAR:CreateRayThread( vehs, from, startX, endX, endY, rayType )
-- Get the start and end points for the ray trace based on the given start and end coordinates
local startPoint = GetOffsetFromEntityInWorldCoords( from, startX, 0.0, 0.0 )
local endPoint = GetOffsetFromEntityInWorldCoords( from, endX, endY, 0.0 )
-- Get all of the vehicles hit by the ray
local hitVehs = self:GetVehsHitByRay( from, vehs, startPoint, endPoint )
-- Insert the captured vehicle data and pass the ray type too
self:InsertCapturedVehicleData( hitVehs, rayType )
-- Increase the ray trace state
self:IncreaseRayTraceState()
end
-- This function iterates through each of the traces defined in RADAR.rayTraces and creates a 'thread' for
-- them, passing along all of the vehicle pool data and the player's vehicle
function RADAR:CreateRayThreads( ownVeh, vehicles )
for _, v in pairs( self.rayTraces ) do
self:CreateRayThread( vehicles, ownVeh, v.startVec.x, v.endVec.x, v.endVec.y, v.rayType )
end
end
-- When the user changes either the same lane or opp lane sensitivity from within the operator menu, this function
-- is then called to update the end coordinates for all of the traces
function RADAR:UpdateRayEndCoords()
for _, v in pairs( self.rayTraces ) do
-- Calculate what the new end coordinate should be
local endY = self:GetSettingValue( v.rayType ) * self:GetMaxCheckDist()
-- Update the end Y coordinate in the traces table
v.endVec.y = endY
end
end
--[[----------------------------------------------------------------------------------
Radar antenna functions
----------------------------------------------------------------------------------]]--
-- Toggles the state of the given antenna between hold and transmitting, only works if the radar's power is
-- on. Also runs a callback function when present.
function RADAR:ToggleAntenna( ant )
-- Check power is on
if ( self:IsPowerOn() ) then
-- Toggle the given antennas state
self.vars.antennas[ant].xmit = not self.vars.antennas[ant].xmit
-- Update the interface with the new antenna transmit state
SendNUIMessage( { _type = "antennaXmit", ant = ant, on = self:IsAntennaTransmitting( ant ) } )
-- Play some audio specific to the transmit state
SendNUIMessage( { _type = "audio", name = self:IsAntennaTransmitting( ant ) and "xmit_on" or "xmit_off", vol = self:GetSettingValue( "beep" ) } )
end
end
-- Returns if the given antenna is transmitting
function RADAR:IsAntennaTransmitting( ant ) return self.vars.antennas[ant].xmit end
-- Returns if the given relative position value is for the front or rear antenna
function RADAR:GetAntennaTextFromNum( relPos )
if ( relPos == 1 ) then
return "front"
elseif ( relPos == -1 ) then
return "rear"
end
end
-- Returns the mode of the given antenna
function RADAR:GetAntennaMode( ant ) return self.vars.antennas[ant].mode end
-- Sets the mode of the given antenna if the mode is valid and the power is on. Also runs a callback function
-- when present.
function RADAR:SetAntennaMode( ant, mode )
-- Check the mode is actually a number, this is needed as the radar system relies on the mode to be
-- a number to work
if ( type( mode ) == "number" ) then