--[[---------------------------------------------------------------------------------- Wraith ARS 2X Created by WolfKnight ----------------------------------------------------------------------------------]]-- -- 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 --[[---------------------------------------------------------------------------------- Resource Rename Fix - for those muppets who rename the resource and complain that the NUI aspect doesn't work! ----------------------------------------------------------------------------------]]-- Citizen.SetTimeout( 1000, function() -- Get the name of the resource, for example the default name is 'wk_wrs2' local name = GetCurrentResourceName() -- Print a little message in the client's console print( "WK_WARS2X: Sending resource name (" .. name .. ") to JavaScript side." ) -- Send a message through the NUI system to the JavaScript file to give the name of the resource SendNUIMessage( { _type = "updatePathName", pathName = name } ) end ) --[[---------------------------------------------------------------------------------- Player info variables ----------------------------------------------------------------------------------]]-- local PLY = {} PLY.ped = PlayerPedId() PLY.veh = nil PLY.inDriverSeat = false PLY.vehClassValid = false function PLY:VehicleStateValid() return DoesEntityExist( self.veh ) and self.veh > 0 and self.inDriverSeat and self.vehClassValid end -- The main purpose of this thread is to update the information about the local player, including their -- ped id, the vehicle id (if they're in one), whether they're in a driver seat, and if the vehicle's class -- is valid or not Citizen.CreateThread( function() while ( true ) do PLY.ped = PlayerPedId() PLY.veh = GetVehiclePedIsIn( PLY.ped, false ) PLY.inDriverSeat = GetPedInVehicleSeat( PLY.veh, -1 ) == PLY.ped PLY.vehClassValid = GetVehicleClass( PLY.veh ) == 18 Citizen.Wait( 500 ) end end ) --[[---------------------------------------------------------------------------------- Radar variables NOTE - This is not a config, do not touch anything unless you know what you are actually doing. ----------------------------------------------------------------------------------]]-- 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"] = true, -- Sensitivty for each radar mode, this changes how far the antennas will detect vehicles ["same"] = 3, ["opp"] = 3, -- Future feature! -- ["alert"] = true, -- The volume of the audible beep, follows the JS format (0.0 - 1.0) ["beep"] = 0.6, -- The speed unit used in conversions ["speedType"] = "mph" }, -- 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 = 3, settingText = "same" }, { displayText = { "¦OP", "SEn" }, optionsText = { "¦1¦", "¦2¦", "¦3¦", "¦4¦", "¦5¦" }, options = { 0.2, 0.4, 0.6, 0.8, 1.0 }, optionIndex = 3, 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 = 4, settingText = "beep" }, { 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 = 0, -- The locked speed lockedDir = 0 -- The direction of the vehicle that was locked }, [ "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 = 0, -- The locked speed lockedDir = 0 -- The direction of the vehicle that was locked } }, -- 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 400.0 maxCheckDist = 300.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 for temp id storage to stop unnecessary trace checks tempVehicleIDs = {}, -- 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 } -- 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 ff 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:TogglePower() -- Toggle the power variable self.vars.power = not self.vars.power -- Send the NUI message to toggle the power SendNUIMessage( { _type = "radarPower", state = self:IsPowerOn() } ) -- Power is now turned on if ( self:IsPowerOn() ) 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" } ) end ) else -- If the system is being turned off, then we reset the antennas self:ResetAntenna( "front" ) self:ResetAntenna( "rear" ) 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 = "toggleDisplay", state = self:GetDisplayState() } ) end -- Gets the display state function RADAR:GetDisplayState() return self.vars.displayed 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 do 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 -- Return the state of the fastDisplay setting, short hand direct way to check if the fast system is enabled function RADAR:IsFastDisplayEnabled() return self.vars.settings["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() -- Grab the antennas table and the fast system state local antennas = self.vars.antennas local fast = self:IsFastDisplayEnabled() -- Send a message to the NUI side with the current state of the antennas and the fast mode SendNUIMessage( { _type = "settingUpdate", antennaData = antennas, fast = fast } ) 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 what the dynamic thread wait time is function RADAR:GetThreadWaitTime() return self.vars.threadWaitTime end -- Sets the dynamic thread wait time to the given value function RADAR:SetThreadWaitTime( time ) self.vars.threadWaitTime = time end -- Sets the display's hidden state to the given state function RADAR:SetDisplayHidden( state ) self.vars.hidden = state end -- Returns if the display is hidden function RADAR:GetDisplayHidden() return self.vars.hidden end -- Opens the remote only if the pause menu is not open and the player's vehicle state is valid function RADAR:OpenRemote() if ( not IsPauseMenuActive() and PLY:VehicleStateValid() ) then -- Tell the NUI side to open the remote SendNUIMessage( { _type = "openRemote" } ) -- Bring focus to the NUI side SetNuiFocus( true, true ) end 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 -- 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 --[[---------------------------------------------------------------------------------- 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 currently set active vehicles function RADAR:GetActiveVehicles() return self.vars.activeVehicles 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:GetVehSpeedFormatted( 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 -- Sets the active vehicles to the given value if it's a table function RADAR:SetActiveVehicles( vehs ) if ( type( vehs ) == "table" ) then self.vars.activeVehicles = vehs 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( centre, radius, rayStart, rayEnd ) -- 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 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 ) local key = tostring( veh ) -- 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() --[[ and not self:HasVehicleAlreadyBeenHit( key ) ]] ) 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) -- Now we check that the target vehicle is moving and is visible if ( entSpeed > 0.1 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 if ( hit ) then self:SetVehicleHasBeenHit( key ) 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 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 function RADAR:UpdateRayEndCoords() for k, v in pairs( self.rayTraces ) do local endY = self:GetSettingValue( v.rayType ) * self:GetMaxCheckDist() v.endVec.y = endY end end --[[---------------------------------------------------------------------------------- Radar antenna functions ----------------------------------------------------------------------------------]]-- function RADAR:ToggleAntenna( ant, cb ) if ( self:IsPowerOn() ) then self.vars.antennas[ant].xmit = not self.vars.antennas[ant].xmit if ( cb ) then cb() end end end function RADAR:IsAntennaTransmitting( ant ) return self.vars.antennas[ant].xmit end function RADAR:GetAntennaTextFromNum( relPos ) if ( relPos == 1 ) then return "front" elseif ( relPos == -1 ) then return "rear" end end function RADAR:GetAntennaMode( ant ) return self.vars.antennas[ant].mode end function RADAR:SetAntennaMode( ant, mode, cb ) if ( type( mode ) == "number" ) then if ( mode >= 0 and mode <= 3 and self:IsPowerOn() ) then self.vars.antennas[ant].mode = mode if ( cb ) then cb() end end end end function RADAR:GetAntennaSpeed( ant ) return self.vars.antennas[ant].speed end function RADAR:SetAntennaSpeed( ant, speed ) self.vars.antennas[ant].speed = speed end function RADAR:GetAntennaDir( ant ) return self.vars.antennas[ant].dir end function RADAR:SetAntennaDir( ant, dir ) self.vars.antennas[ant].dir = dir end function RADAR:GetAntennaFastSpeed( ant ) return self.vars.antennas[ant].fastSpeed end function RADAR:SetAntennaFastSpeed( ant, speed ) self.vars.antennas[ant].fastSpeed = speed end function RADAR:GetAntennaFastDir( ant ) return self.vars.antennas[ant].fastDir end function RADAR:SetAntennaFastDir( ant, dir ) self.vars.antennas[ant].fastDir = dir end function RADAR:DoesAntennaHaveValidData( ant ) return self:GetAntennaSpeed( ant ) ~= nil end function RADAR:DoesAntennaHaveValidFastData( ant ) return self:GetAntennaFastSpeed( ant ) ~= nil end function RADAR:IsAntennaSpeedLocked( ant ) return self.vars.antennas[ant].speedLocked end function RADAR:SetAntennaSpeedIsLocked( ant, state ) self.vars.antennas[ant].speedLocked = state end function RADAR:SetAntennaSpeedLock( ant, speed, dir ) if ( speed ~= nil and dir ~= nil ) then self.vars.antennas[ant].lockedSpeed = speed self.vars.antennas[ant].lockedDir = dir self:SetAntennaSpeedIsLocked( ant, true ) SendNUIMessage( { _type = "audio", name = "beep", vol = RADAR:GetSettingValue( "beep" ) } ) end end function RADAR:ResetAntennaSpeedLock( ant ) self.vars.antennas[ant].lockedSpeed = nil self.vars.antennas[ant].lockedDir = nil self:SetAntennaSpeedIsLocked( ant, false ) end function RADAR:LockAntennaSpeed( ant ) if ( self:IsAntennaSpeedLocked( ant ) ) then self:ResetAntennaSpeedLock( ant ) else local data = { nil, nil } if ( self:IsFastDisplayEnabled() and self:DoesAntennaHaveValidFastData( ant ) ) then data[1] = self:GetAntennaFastSpeed( ant ) data[2] = self:GetAntennaFastDir( ant ) else data[1] = self:GetAntennaSpeed( ant ) data[2] = self:GetAntennaDir( ant ) end self:SetAntennaSpeedLock( ant, data[1], data[2] ) end SendNUIMessage( { _type = "antennaLock", ant = ant, state = self:IsAntennaSpeedLocked( ant ) } ) end function RADAR:ResetAntenna( ant ) -- Overwrite default behaviour, this is because when the system is turned off, the temporary memory is -- technically reset, as the setter functions require either the radar power to be on or the antenna to -- be transmitting, this is the only way to reset the values self.vars.antennas[ant].xmit = false self.vars.antennas[ant].mode = 0 self:ResetAntennaSpeedLock( ant ) end --[[---------------------------------------------------------------------------------- Radar captured vehicle functions ----------------------------------------------------------------------------------]]-- function RADAR:GetCapturedVehicles() return self.vars.capturedVehicles end function RADAR:ResetCapturedVehicles() self.vars.capturedVehicles = {} end function RADAR:InsertCapturedVehicleData( t, rt ) if ( type( t ) == "table" and not UTIL:IsTableEmpty( t ) ) then for _, v in pairs( t ) do v.rayType = rt table.insert( self.vars.capturedVehicles, v ) end end end function RADAR:HasVehicleAlreadyBeenHit( key ) return self.vars.tempVehicleIDs[key] end function RADAR:SetVehicleHasBeenHit( key ) self.vars.tempVehicleIDs[key] = true end function RADAR:ResetTempVehicleIDs() self.vars.tempVehicleIDs = {} end --[[---------------------------------------------------------------------------------- Radar dynamic sphere radius functions ----------------------------------------------------------------------------------]]-- function RADAR:GetDynamicDataValue( key ) return self.vars.sphereSizes[key] end function RADAR:DoesDynamicRadiusDataExist( key ) return self:GetDynamicDataValue( key ) ~= nil end function RADAR:SetDynamicRadiusKey( key, t ) self.vars.sphereSizes[key] = t end function RADAR:InsertDynamicRadiusData( key, radius, actualSize ) if ( self:GetDynamicDataValue( key ) == nil ) then local t = {} t.radius = radius t.actualSize = actualSize self:SetDynamicRadiusKey( key, t ) end end function RADAR:GetRadiusData( key ) return self.vars.sphereSizes[key].radius or 5.0, self.vars.sphereSizes[key].actualSize end function RADAR:GetDynamicRadius( veh ) local mdl = GetEntityModel( veh ) local key = tostring( mdl ) local dataExists = self:DoesDynamicRadiusDataExist( key ) if ( not dataExists ) then local min, max = GetModelDimensions( mdl ) local size = max - min local numericSize = size.x + size.y + size.z local dynamicRadius = UTIL:Clamp( ( numericSize * numericSize ) / 12, 6.0, 10.0 ) self:InsertDynamicRadiusData( key, dynamicRadius, numericSize ) return dynamicRadius, numericSize end return self:GetRadiusData( key ) end --[[---------------------------------------------------------------------------------- Radar functions ----------------------------------------------------------------------------------]]-- function RADAR:GetVehSpeedFormatted( speed ) if ( self:GetSettingValue( "speedType" ) == "mph" ) then return UTIL:Round( speed * 2.236936, 0 ) else return UTIL:Round( speed * 3.6, 0 ) end end function RADAR:GetAllVehicles() local t = {} for v in UTIL:EnumerateVehicles() do table.insert( t, v ) end return t end function RADAR:CheckVehicleDataFitsMode( ant, rt ) local mode = self:GetAntennaMode( ant ) if ( ( mode == 3 ) or ( mode == 1 and rt == "same" ) or ( mode == 2 and rt == "opp" ) ) then return true end return false end function RADAR:GetVehiclesForAntenna() local vehs = { ["front"] = {}, ["rear"] = {} } local results = { ["front"] = { nil, nil }, ["rear"] = { nil, nil } } -- Loop through and split up the vehicles based on front and rear, this is simply because the actual system -- that gets all of the vehicles hit by the radar only has a relative position of either 1 or -1, which we -- then convert below into an antenna string! for ant in UTIL:Values( { "front", "rear" } ) do if ( self:IsAntennaTransmitting( ant ) ) then for k, v in pairs( self:GetCapturedVehicles() ) do local antText = self:GetAntennaTextFromNum( v.relPos ) if ( ant == antText ) then table.insert( vehs[ant], v ) end end -- As the radar is based on how the real Stalker DSR 2X works, we now sort the dataset by -- the 'strongest' (largest) target, this way the first result for the front and rear data -- will be the one that gets displayed in the target boxes. table.sort( vehs[ant], self:GetStrongestSortFunc() ) end end for ant in UTIL:Values( { "front", "rear" } ) do if ( not UTIL:IsTableEmpty( vehs[ant] ) ) then -- Get the 'strongest' vehicle for the antenna for k, v in pairs( vehs[ant] ) do if ( self:CheckVehicleDataFitsMode( ant, v.rayType ) ) then results[ant][1] = v break end end if ( self:IsFastDisplayEnabled() ) then -- Get the 'fastest' vehicle for the antenna table.sort( vehs[ant], self:GetFastestSortFunc() ) local temp = results[ant][1] for k, v in pairs( vehs[ant] ) do if ( self:CheckVehicleDataFitsMode( ant, v.rayType ) and v.veh ~= temp.veh and v.size < temp.size and v.speed > temp.speed ) then results[ant][2] = v break end end end end end return { ["front"] = { results["front"][1], results["front"][2] }, ["rear"] = { results["rear"][1], results["rear"][2] } } end --[[---------------------------------------------------------------------------------- NUI callback ----------------------------------------------------------------------------------]]-- RegisterNUICallback( "toggleDisplay", function() RADAR:ToggleDisplayState() end ) RegisterNUICallback( "togglePower", function() RADAR:TogglePower() end ) RegisterNUICallback( "closeRemote", function() SetNuiFocus( false, false ) end ) RegisterNUICallback( "setAntennaMode", function( data ) if ( RADAR:IsPowerOn() and RADAR:IsMenuOpen() ) then RADAR:SetMenuState( false ) RADAR:SendSettingUpdate() SendNUIMessage( { _type = "audio", name = "done", vol = RADAR:GetSettingValue( "beep" ) } ) else RADAR:SetAntennaMode( data.value, tonumber( data.mode ), function() SendNUIMessage( { _type = "antennaMode", ant = data.value, mode = tonumber( data.mode ) } ) SendNUIMessage( { _type = "audio", name = "beep", vol = RADAR:GetSettingValue( "beep" ) } ) end ) end end ) RegisterNUICallback( "toggleAntenna", function( data ) if ( RADAR:IsPowerOn() and RADAR:IsMenuOpen() ) then RADAR:ChangeMenuOption( data.value ) SendNUIMessage( { _type = "audio", name = "beep", vol = RADAR:GetSettingValue( "beep" ) } ) else RADAR:ToggleAntenna( data.value, function() SendNUIMessage( { _type = "antennaXmit", ant = data.value, on = RADAR:IsAntennaTransmitting( data.value ) } ) SendNUIMessage( { _type = "audio", name = RADAR:IsAntennaTransmitting( data.value ) and "xmit_on" or "xmit_off", vol = RADAR:GetSettingValue( "beep" ) } ) end ) end end ) RegisterNUICallback( "menu", function() if ( RADAR:IsMenuOpen() ) then RADAR:ChangeMenuIndex() else -- Set the menu state to open, which will prevent anything else from working RADAR:SetMenuState( true ) RADAR:SendMenuUpdate() end SendNUIMessage( { _type = "audio", name = "beep", vol = RADAR:GetSettingValue( "beep" ) } ) end ) --[[---------------------------------------------------------------------------------- Main threads ----------------------------------------------------------------------------------]]-- function RADAR:RunDynamicThreadWaitCheck() local speed = self:GetPatrolSpeed() if ( speed < 0.1 ) then self:SetThreadWaitTime( 200 ) else self:SetThreadWaitTime( 500 ) end end Citizen.CreateThread( function() while ( true ) do RADAR:RunDynamicThreadWaitCheck() Citizen.Wait( 2000 ) end end ) function RADAR:RunThreads() if ( PLY:VehicleStateValid() and self:CanPerformMainTask() and self:IsEitherAntennaOn() ) then if ( self:GetRayTraceState() == 0 ) then local vehs = self:GetVehiclePool() self:ResetCapturedVehicles() self:ResetRayTraceState() self:CreateRayThreads( PLY.veh, vehs ) Citizen.Wait( self:GetThreadWaitTime() ) elseif ( self:GetRayTraceState() == self:GetNumOfRays() ) then self:ResetRayTraceState() end end end Citizen.CreateThread( function() while ( true ) do RADAR:RunThreads() Citizen.Wait( 0 ) end end ) function RADAR:Main() -- Check to make sure the player is in the driver's seat, and also that the vehicle has a class of VC_EMERGENCY (18) if ( PLY:VehicleStateValid() and self:CanPerformMainTask() ) then local data = {} -- Get the player's vehicle speed local entSpeed = GetEntitySpeed( PLY.veh ) self:SetPatrolSpeed( entSpeed ) if ( entSpeed == 0 ) then data.patrolSpeed = "¦[]" else local speed = self:GetVehSpeedFormatted( entSpeed ) data.patrolSpeed = UTIL:FormatSpeed( speed ) end -- Only grab data to send if there have actually been vehicles captured by the radar if ( not UTIL:IsTableEmpty( self:GetCapturedVehicles() ) ) then local vehsForDisplay = self:GetVehiclesForAntenna() self:SetActiveVehicles( vehsForDisplay ) else self:SetActiveVehicles( { ["front"] = { nil, nil }, ["rear"] = { nil, nil } } ) end -- Work out what has to be sent local av = self:GetActiveVehicles() data.antennas = { ["front"] = nil, ["rear"] = nil } for ant in UTIL:Values( { "front", "rear" } ) do if ( self:IsAntennaTransmitting( ant ) ) then data.antennas[ant] = {} for i = 1, 2 do data.antennas[ant][i] = { speed = "¦¦¦", dir = 0 } if ( i == 2 and self:IsAntennaSpeedLocked( ant ) ) then data.antennas[ant][i].speed = self.vars.antennas[ant].lockedSpeed data.antennas[ant][i].dir = self.vars.antennas[ant].lockedDir else -- The vehicle data exists for this slot if ( av[ant][i] ~= nil ) then -- We already have the vehicle speed as we needed it earlier on for filtering local uSpeed = GetEntitySpeed( av[ant][i].veh ) data.antennas[ant][i].speed = UTIL:FormatSpeed( self:GetVehSpeedFormatted( uSpeed ) ) -- Work out if the vehicle is closing or away local ownH = UTIL:Round( GetEntityHeading( PLY.veh ), 0 ) local tarH = UTIL:Round( GetEntityHeading( av[ant][i].veh ), 0 ) data.antennas[ant][i].dir = UTIL:GetEntityRelativeDirection( ownH, tarH ) -- Set the internal antenna data as this actual dataset is valid if ( i % 2 == 0 ) then self:SetAntennaFastSpeed( ant, data.antennas[ant][i].speed ) self:SetAntennaFastDir( ant, data.antennas[ant][i].dir ) else self:SetAntennaSpeed( ant, data.antennas[ant][i].speed ) self:SetAntennaDir( ant, data.antennas[ant][i].dir ) end else -- If the active vehicle is not valid, we reset the internal data if ( i % 2 == 0 ) then self:SetAntennaFastSpeed( ant, nil ) self:SetAntennaFastDir( ant, nil ) else self:SetAntennaSpeed( ant, nil ) self:SetAntennaDir( ant, nil ) end end end end end end -- Send the update to the NUI side SendNUIMessage( { _type = "update", speed = data.patrolSpeed, antennas = data.antennas } ) self:ResetTempVehicleIDs() self:ResetRayTraceState() end end -- Main thread Citizen.CreateThread( function() SetNuiFocus( false, false ) RADAR:CacheNumRays() RADAR:UpdateRayEndCoords() while ( true ) do RADAR:Main() Citizen.Wait( 50 ) end end ) function RADAR:RunDisplayValidationCheck() if ( ( ( PLY.veh == 0 or ( PLY.veh > 0 and not PLY.vehClassValid ) ) and self:GetDisplayState() and not self:GetDisplayHidden() ) or IsPauseMenuActive() and self:GetDisplayState() ) then self:SetDisplayHidden( true ) SendNUIMessage( { _type = "toggleDisplay", state = false } ) elseif ( PLY.veh > 0 and PLY.vehClassValid and self:GetDisplayState() and self:GetDisplayHidden() ) then self:SetDisplayHidden( false ) SendNUIMessage( { _type = "toggleDisplay", state = true } ) end end Citizen.CreateThread( function() Citizen.Wait( 100 ) while ( true ) do RADAR:RunDisplayValidationCheck() Citizen.Wait( 100 ) end end ) -- Update the vehicle pool every 3 seconds function RADAR:UpdateVehiclePool() if ( PLY:VehicleStateValid() and self:CanPerformMainTask() and self:IsEitherAntennaOn() ) then local vehs = self:GetAllVehicles() self:SetVehiclePool( vehs ) end end Citizen.CreateThread( function() while ( true ) do RADAR:UpdateVehiclePool() Citizen.Wait( 3000 ) end end ) -- Num4 = 108 - INPUT_VEH_FLY_ROLL_LEFT_ONLY -- Num5 = 112 - INPUT_VEH_FLY_PITCH_DOWN_ONLY -- Num6 = 109 - INPUT_VEH_FLY_ROLL_RIGHT_ONLY -- Num7 = 117 - INPUT_VEH_FLY_SELECT_TARGET_LEFT -- Num8 = 111 - INPUT_VEH_FLY_PITCH_UP_ONLY -- Num9 = 118 - INPUT_VEH_FLY_SELECT_TARGET_RIGHT -- F5 = 166 - INPUT_SELECT_CHARACTER_MICHAEL function RADAR:RunControlManager() -- 'Z' key, toggles debug mode if ( IsDisabledControlJustPressed( 1, 20 ) ) then self.config.debug_mode = not self.config.debug_mode end -- Opens the remote control if ( IsDisabledControlJustPressed( 1, self.config.remote_control_key ) ) then self:OpenRemote() end -- Locks speed from front antenna if ( IsDisabledControlJustPressed( 1, self.config.front_lock_key ) ) then self:LockAntennaSpeed( "front" ) end -- Locks speed from rear antenna if ( IsDisabledControlJustPressed( 1, self.config.rear_lock_key ) ) then self:LockAntennaSpeed( "rear" ) end -- Shortcut to restart the resource if ( IsDisabledControlJustPressed( 1, 167 ) ) then ExecuteCommand( "restart wk_wars2x" ) end end -- Control manager Citizen.CreateThread( function() while ( true ) do RADAR:RunControlManager() Citizen.Wait( 0 ) end end ) ------------------------------ DEBUG ------------------------------ Citizen.CreateThread( function() while ( true ) do if ( RADAR.config.debug_mode ) then for k, v in pairs( RADAR.rayTraces ) do for i = -1, 1, 2 do local startP = GetOffsetFromEntityInWorldCoords( PLY.veh, v.startVec.x, 0.0, 0.0 ) local endP = GetOffsetFromEntityInWorldCoords( PLY.veh, v.endVec.x, v.endVec.y * i, 0.0 ) UTIL:DrawDebugLine( startP, endP ) end end local av = RADAR:GetActiveVehicles() for ant in UTIL:Values( { "front", "rear" } ) do for i = 1, 2, 1 do if ( av[ant] ~= nil and av[ant][i] ~= nil ) then local pos = GetEntityCoords( av[ant][i].veh ) local r = RADAR:GetDynamicRadius( av[ant][i].veh ) if ( i == 1 ) then UTIL:DrawDebugSphere( pos.x, pos.y, pos.z, r, { 255, 127, 0, 100 } ) else UTIL:DrawDebugSphere( pos.x, pos.y, pos.z, r, { 255, 0, 0, 100 } ) end end end end Citizen.Wait( 0 ) else Citizen.Wait( 500 ) end end end )